file_path
stringlengths 3
280
| file_language
stringclasses 66
values | content
stringlengths 1
1.04M
| repo_name
stringlengths 5
92
| repo_stars
int64 0
154k
| repo_description
stringlengths 0
402
| repo_primary_language
stringclasses 108
values | developer_username
stringlengths 1
25
| developer_name
stringlengths 0
30
| developer_company
stringlengths 0
82
|
|---|---|---|---|---|---|---|---|---|---|
python/ray/autoscaler/updater.py
|
Python
|
try: # py3
from shlex import quote
except ImportError: # py2
from pipes import quote
import hashlib
import logging
import os
import subprocess
import sys
import time
from threading import Thread
from getpass import getuser
from ray.autoscaler.tags import TAG_RAY_NODE_STATUS, TAG_RAY_RUNTIME_CONFIG, \
STATUS_UP_TO_DATE, STATUS_UPDATE_FAILED, STATUS_WAITING_FOR_SSH, \
STATUS_SETTING_UP, STATUS_SYNCING_FILES
from ray.autoscaler.log_timer import LogTimer
logger = logging.getLogger(__name__)
# How long to wait for a node to start, in seconds
NODE_START_WAIT_S = 300
READY_CHECK_INTERVAL = 5
HASH_MAX_LENGTH = 10
KUBECTL_RSYNC = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "kubernetes/kubectl-rsync.sh")
def with_interactive(cmd):
force_interactive = ("true && source ~/.bashrc && "
"export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && ")
return ["bash", "--login", "-c", "-i", quote(force_interactive + cmd)]
class KubernetesCommandRunner:
def __init__(self, log_prefix, namespace, node_id, auth_config,
process_runner):
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = node_id
self.namespace = namespace
self.kubectl = ["kubectl", "-n", self.namespace]
def run(self,
cmd,
timeout=120,
allocate_tty=False,
exit_on_fail=False,
port_forward=None):
logger.info(self.log_prefix + "Running {}...".format(cmd))
if port_forward:
if not isinstance(port_forward, list):
port_forward = [port_forward]
port_forward_cmd = self.kubectl + [
"port-forward",
self.node_id,
] + [str(fwd) for fwd in port_forward]
port_forward_process = subprocess.Popen(port_forward_cmd)
# Give port-forward a grace period to run and print output before
# running the actual command. This is a little ugly, but it should
# work in most scenarios and nothing should go very wrong if the
# command starts running before the port forward starts.
time.sleep(1)
final_cmd = self.kubectl + [
"exec",
"-it" if allocate_tty else "-i",
self.node_id,
"--",
] + with_interactive(cmd)
try:
self.process_runner.check_call(" ".join(final_cmd), shell=True)
except subprocess.CalledProcessError:
if exit_on_fail:
quoted_cmd = " ".join(final_cmd[:-1] + [quote(final_cmd[-1])])
logger.error(self.log_prefix +
"Command failed: \n\n {}\n".format(quoted_cmd))
sys.exit(1)
else:
raise
finally:
# Clean up the port forward process. First, try to let it exit
# gracefull with SIGTERM. If that doesn't work after 1s, send
# SIGKILL.
if port_forward:
port_forward_process.terminate()
for _ in range(10):
time.sleep(0.1)
port_forward_process.poll()
if port_forward_process.returncode:
break
logger.info(self.log_prefix +
"Waiting for port forward to die...")
else:
logger.warning(self.log_prefix +
"Killing port forward with SIGKILL.")
port_forward_process.kill()
def run_rsync_up(self, source, target):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
source,
"{}@{}:{}".format(self.node_id, self.namespace, target),
])
except Exception as e:
logger.warning(self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'"
.format(e))
self.process_runner.check_call(self.kubectl + [
"cp", source, "{}/{}:{}".format(self.namespace, self.node_id,
target)
])
def run_rsync_down(self, source, target):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
"{}@{}:{}".format(self.node_id, self.namespace, source),
target,
])
except Exception as e:
logger.warning(self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'"
.format(e))
self.process_runner.check_call(self.kubectl + [
"cp", "{}/{}:{}".format(self.namespace, self.node_id, source),
target
])
def remote_shell_command_str(self):
return "{} exec -it {} bash".format(" ".join(self.kubectl),
self.node_id)
class SSHCommandRunner:
def __init__(self, log_prefix, node_id, provider, auth_config,
cluster_name, process_runner, use_internal_ip):
ssh_control_hash = hashlib.md5(cluster_name.encode()).hexdigest()
ssh_user_hash = hashlib.md5(getuser().encode()).hexdigest()
ssh_control_path = "/tmp/ray_ssh_{}/{}".format(
ssh_user_hash[:HASH_MAX_LENGTH],
ssh_control_hash[:HASH_MAX_LENGTH])
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = node_id
self.use_internal_ip = use_internal_ip
self.provider = provider
self.ssh_private_key = auth_config["ssh_private_key"]
self.ssh_user = auth_config["ssh_user"]
self.ssh_control_path = ssh_control_path
self.ssh_ip = None
def get_default_ssh_options(self, connect_timeout):
OPTS = [
("ConnectTimeout", "{}s".format(connect_timeout)),
("StrictHostKeyChecking", "no"),
("ControlMaster", "auto"),
("ControlPath", "{}/%C".format(self.ssh_control_path)),
("ControlPersist", "10s"),
]
return ["-i", self.ssh_private_key] + [
x for y in (["-o", "{}={}".format(k, v)] for k, v in OPTS)
for x in y
]
def get_node_ip(self):
if self.use_internal_ip:
return self.provider.internal_ip(self.node_id)
else:
return self.provider.external_ip(self.node_id)
def wait_for_ip(self, deadline):
while time.time() < deadline and \
not self.provider.is_terminated(self.node_id):
logger.info(self.log_prefix + "Waiting for IP...")
ip = self.get_node_ip()
if ip is not None:
return ip
time.sleep(10)
return None
def set_ssh_ip_if_required(self):
if self.ssh_ip is not None:
return
# We assume that this never changes.
# I think that's reasonable.
deadline = time.time() + NODE_START_WAIT_S
with LogTimer(self.log_prefix + "Got IP"):
ip = self.wait_for_ip(deadline)
assert ip is not None, "Unable to find IP of node"
self.ssh_ip = ip
# This should run before any SSH commands and therefore ensure that
# the ControlPath directory exists, allowing SSH to maintain
# persistent sessions later on.
try:
self.process_runner.check_call(
["mkdir", "-p", self.ssh_control_path])
except subprocess.CalledProcessError as e:
logger.warning(e)
try:
self.process_runner.check_call(
["chmod", "0700", self.ssh_control_path])
except subprocess.CalledProcessError as e:
logger.warning(self.log_prefix + str(e))
def run(self,
cmd,
timeout=120,
allocate_tty=False,
exit_on_fail=False,
port_forward=None):
self.set_ssh_ip_if_required()
logger.info(self.log_prefix +
"Running {} on {}...".format(cmd, self.ssh_ip))
ssh = ["ssh"]
if allocate_tty:
ssh.append("-tt")
if port_forward:
if not isinstance(port_forward, list):
port_forward = [port_forward]
for fwd in port_forward:
ssh += ["-L", "{}:localhost:{}".format(fwd, fwd)]
final_cmd = ssh + self.get_default_ssh_options(timeout) + [
"{}@{}".format(self.ssh_user, self.ssh_ip)
] + with_interactive(cmd)
try:
self.process_runner.check_call(final_cmd)
except subprocess.CalledProcessError:
if exit_on_fail:
quoted_cmd = " ".join(final_cmd[:-1] + [quote(final_cmd[-1])])
logger.error(self.log_prefix +
"Command failed: \n\n {}\n".format(quoted_cmd))
sys.exit(1)
else:
raise
def run_rsync_up(self, source, target):
self.set_ssh_ip_if_required()
self.process_runner.check_call([
"rsync", "--rsh",
" ".join(["ssh"] + self.get_default_ssh_options(120)), "-avz",
source, "{}@{}:{}".format(self.ssh_user, self.ssh_ip, target)
])
def run_rsync_down(self, source, target):
self.set_ssh_ip_if_required()
self.process_runner.check_call([
"rsync", "--rsh",
" ".join(["ssh"] + self.get_default_ssh_options(120)), "-avz",
"{}@{}:{}".format(self.ssh_user, self.ssh_ip, source), target
])
def remote_shell_command_str(self):
return "ssh -i {} {}@{}\n".format(self.ssh_private_key, self.ssh_user,
self.ssh_ip)
class NodeUpdater:
"""A process for syncing files and running init commands on a node."""
def __init__(self,
node_id,
provider_config,
provider,
auth_config,
cluster_name,
file_mounts,
initialization_commands,
setup_commands,
ray_start_commands,
runtime_hash,
process_runner=subprocess,
use_internal_ip=False):
self.log_prefix = "NodeUpdater: {}: ".format(node_id)
if provider_config["type"] == "kubernetes":
self.cmd_runner = KubernetesCommandRunner(
self.log_prefix, provider.namespace, node_id, auth_config,
process_runner)
else:
use_internal_ip = (use_internal_ip or provider_config.get(
"use_internal_ips", False))
self.cmd_runner = SSHCommandRunner(
self.log_prefix, node_id, provider, auth_config, cluster_name,
process_runner, use_internal_ip)
self.daemon = True
self.process_runner = process_runner
self.node_id = node_id
self.provider = provider
self.file_mounts = {
remote: os.path.expanduser(local)
for remote, local in file_mounts.items()
}
self.initialization_commands = initialization_commands
self.setup_commands = setup_commands
self.ray_start_commands = ray_start_commands
self.runtime_hash = runtime_hash
def run(self):
logger.info(self.log_prefix +
"Updating to {}".format(self.runtime_hash))
try:
with LogTimer(self.log_prefix +
"Applied config {}".format(self.runtime_hash)):
self.do_update()
except Exception as e:
error_str = str(e)
if hasattr(e, "cmd"):
error_str = "(Exit Status {}) {}".format(
e.returncode, " ".join(e.cmd))
logger.error(self.log_prefix +
"Error updating {}".format(error_str))
self.provider.set_node_tags(
self.node_id, {TAG_RAY_NODE_STATUS: STATUS_UPDATE_FAILED})
raise e
self.provider.set_node_tags(
self.node_id, {
TAG_RAY_NODE_STATUS: STATUS_UP_TO_DATE,
TAG_RAY_RUNTIME_CONFIG: self.runtime_hash
})
self.exitcode = 0
def sync_file_mounts(self, sync_cmd):
# Rsync file mounts
for remote_path, local_path in self.file_mounts.items():
assert os.path.exists(local_path), local_path
if os.path.isdir(local_path):
if not local_path.endswith("/"):
local_path += "/"
if not remote_path.endswith("/"):
remote_path += "/"
with LogTimer(self.log_prefix +
"Synced {} to {}".format(local_path, remote_path)):
self.cmd_runner.run("mkdir -p {}".format(
os.path.dirname(remote_path)))
sync_cmd(local_path, remote_path)
def wait_ready(self, deadline):
with LogTimer(self.log_prefix + "Got remote shell"):
logger.info(self.log_prefix + "Waiting for remote shell...")
while time.time() < deadline and \
not self.provider.is_terminated(self.node_id):
try:
logger.debug(self.log_prefix +
"Waiting for remote shell...")
self.cmd_runner.run("uptime", timeout=5)
logger.debug("Uptime succeeded.")
return True
except Exception as e:
retry_str = str(e)
if hasattr(e, "cmd"):
retry_str = "(Exit Status {}): {}".format(
e.returncode, " ".join(e.cmd))
logger.debug(self.log_prefix +
"Node not up, retrying: {}".format(retry_str))
time.sleep(READY_CHECK_INTERVAL)
assert False, "Unable to connect to node"
def do_update(self):
self.provider.set_node_tags(
self.node_id, {TAG_RAY_NODE_STATUS: STATUS_WAITING_FOR_SSH})
deadline = time.time() + NODE_START_WAIT_S
self.wait_ready(deadline)
node_tags = self.provider.node_tags(self.node_id)
logger.debug("Node tags: {}".format(str(node_tags)))
if node_tags.get(TAG_RAY_RUNTIME_CONFIG) == self.runtime_hash:
logger.info(self.log_prefix +
"{} already up-to-date, skip to ray start".format(
self.node_id))
else:
self.provider.set_node_tags(
self.node_id, {TAG_RAY_NODE_STATUS: STATUS_SYNCING_FILES})
self.sync_file_mounts(self.rsync_up)
# Run init commands
self.provider.set_node_tags(
self.node_id, {TAG_RAY_NODE_STATUS: STATUS_SETTING_UP})
with LogTimer(self.log_prefix +
"Initialization commands completed"):
for cmd in self.initialization_commands:
self.cmd_runner.run(cmd)
with LogTimer(self.log_prefix + "Setup commands completed"):
for cmd in self.setup_commands:
self.cmd_runner.run(cmd)
with LogTimer(self.log_prefix + "Ray start commands completed"):
for cmd in self.ray_start_commands:
self.cmd_runner.run(cmd)
def rsync_up(self, source, target):
logger.info(self.log_prefix +
"Syncing {} to {}...".format(source, target))
self.cmd_runner.run_rsync_up(source, target)
def rsync_down(self, source, target):
logger.info(self.log_prefix +
"Syncing {} from {}...".format(source, target))
self.cmd_runner.run_rsync_down(source, target)
class NodeUpdaterThread(NodeUpdater, Thread):
def __init__(self, *args, **kwargs):
Thread.__init__(self)
NodeUpdater.__init__(self, *args, **kwargs)
self.exitcode = -1
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/cloudpickle/__init__.py
|
Python
|
from __future__ import absolute_import
import os
import sys
CLOUDPICKLE_PATH = os.path.dirname(os.path.realpath(__file__))
if os.path.exists(os.path.join(CLOUDPICKLE_PATH, "..", "pickle5_files", "pickle5")):
HAS_PICKLE5 = True
else:
HAS_PICKLE5 = False
if sys.version_info[:2] >= (3, 8) or HAS_PICKLE5:
from ray.cloudpickle.cloudpickle_fast import *
FAST_CLOUDPICKLE_USED = True
else:
from ray.cloudpickle.cloudpickle import *
FAST_CLOUDPICKLE_USED = False
__version__ = '1.2.2.dev0'
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/cloudpickle/cloudpickle.py
|
Python
|
"""
This class is defined to override standard pickle functionality
The goals of it follow:
-Serialize lambdas and nested functions to compiled byte code
-Deal with main module correctly
-Deal with other non-serializable objects
It does not include an unpickler, as standard python unpickling suffices.
This module was extracted from the `cloud` package, developed by `PiCloud, Inc.
<https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
Copyright (c) 2012, Regents of the University of California.
Copyright (c) 2009 `PiCloud, Inc. <https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of California, Berkeley nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from __future__ import print_function
import dis
from functools import partial
import io
import itertools
import logging
import opcode
import operator
import pickle
import platform
import struct
import sys
import traceback
import types
import weakref
import uuid
import threading
try:
from enum import Enum
except ImportError:
Enum = None
# cloudpickle is meant for inter process communication: we expect all
# communicating processes to run the same Python version hence we favor
# communication speed over compatibility:
DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL
# Track the provenance of reconstructed dynamic classes to make it possible to
# recontruct instances from the matching singleton class definition when
# appropriate and preserve the usual "isinstance" semantics of Python objects.
_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
PYPY = platform.python_implementation() == "PyPy"
builtin_code_type = None
if PYPY:
# builtin-code objects only exist in pypy
builtin_code_type = type(float.__new__.__code__)
if sys.version_info[0] < 3: # pragma: no branch
from pickle import Pickler
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
string_types = (basestring,) # noqa
PY3 = False
PY2 = True
else:
types.ClassType = type
from pickle import _Pickler as Pickler
from io import BytesIO as StringIO
string_types = (str,)
PY3 = True
PY2 = False
from importlib._bootstrap import _find_spec
_extract_code_globals_cache = weakref.WeakKeyDictionary()
def _ensure_tracking(class_def):
with _DYNAMIC_CLASS_TRACKER_LOCK:
class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def)
if class_tracker_id is None:
class_tracker_id = uuid.uuid4().hex
_DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
_DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def
return class_tracker_id
def _lookup_class_or_track(class_tracker_id, class_def):
if class_tracker_id is not None:
with _DYNAMIC_CLASS_TRACKER_LOCK:
class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
class_tracker_id, class_def)
_DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
return class_def
if sys.version_info[:2] >= (3, 5):
from pickle import _getattribute
elif sys.version_info[:2] >= (3, 4):
from pickle import _getattribute as _py34_getattribute
# pickle._getattribute does not return the parent under Python 3.4
def _getattribute(obj, name):
return _py34_getattribute(obj, name), None
else:
# pickle._getattribute is a python3 addition and enchancement of getattr,
# that can handle dotted attribute names. In cloudpickle for python2,
# handling dotted names is not needed, so we simply define _getattribute as
# a wrapper around getattr.
def _getattribute(obj, name):
return getattr(obj, name, None), None
def _whichmodule(obj, name):
"""Find the module an object belongs to.
This function differs from ``pickle.whichmodule`` in two ways:
- it does not mangle the cases where obj's module is __main__ and obj was
not found in any module.
- Errors arising during module introspection are ignored, as those errors
are considered unwanted side effects.
"""
module_name = getattr(obj, '__module__', None)
if module_name is not None:
return module_name
# Protect the iteration by using a list copy of sys.modules against dynamic
# modules that trigger imports of other modules upon calls to getattr.
for module_name, module in list(sys.modules.items()):
if module_name == '__main__' or module is None:
continue
try:
if _getattribute(module, name)[0] is obj:
return module_name
except Exception:
pass
return None
def _is_global(obj, name=None):
"""Determine if obj can be pickled as attribute of a file-backed module"""
if name is None:
name = getattr(obj, '__qualname__', None)
if name is None:
name = getattr(obj, '__name__', None)
module_name = _whichmodule(obj, name)
if module_name is None:
# In this case, obj.__module__ is None AND obj was not found in any
# imported module. obj is thus treated as dynamic.
return False
if module_name == "__main__":
return False
module = sys.modules.get(module_name, None)
if module is None:
# The main reason why obj's module would not be imported is that this
# module has been dynamically created, using for example
# types.ModuleType. The other possibility is that module was removed
# from sys.modules after obj was created/imported. But this case is not
# supported, as the standard pickle does not support it either.
return False
# module has been added to sys.modules, but it can still be dynamic.
if _is_dynamic(module):
return False
try:
obj2, parent = _getattribute(module, name)
except AttributeError:
# obj was not found inside the module it points to
return False
return obj2 is obj
def _extract_code_globals(co):
"""
Find all globals names read or written to by codeblock co
"""
out_names = _extract_code_globals_cache.get(co)
if out_names is None:
names = co.co_names
out_names = {names[oparg] for _, oparg in _walk_global_ops(co)}
# Declaring a function inside another one using the "def ..."
# syntax generates a constant code object corresonding to the one
# of the nested function's As the nested function may itself need
# global variables, we need to introspect its code, extract its
# globals, (look for code object in it's co_consts attribute..) and
# add the result to code_globals
if co.co_consts:
for const in co.co_consts:
if isinstance(const, types.CodeType):
out_names |= _extract_code_globals(const)
_extract_code_globals_cache[co] = out_names
return out_names
def _find_imported_submodules(code, top_level_dependencies):
"""
Find currently imported submodules used by a function.
Submodules used by a function need to be detected and referenced for the
function to work correctly at depickling time. Because submodules can be
referenced as attribute of their parent package (``package.submodule``), we
need a special introspection technique that does not rely on GLOBAL-related
opcodes to find references of them in a code object.
Example:
```
import concurrent.futures
import cloudpickle
def func():
x = concurrent.futures.ThreadPoolExecutor
if __name__ == '__main__':
cloudpickle.dumps(func)
```
The globals extracted by cloudpickle in the function's state include the
concurrent package, but not its submodule (here, concurrent.futures), which
is the module used by func. Find_imported_submodules will detect the usage
of concurrent.futures. Saving this module alongside with func will ensure
that calling func once depickled does not fail due to concurrent.futures
not being imported
"""
subimports = []
# check if any known dependency is an imported package
for x in top_level_dependencies:
if (isinstance(x, types.ModuleType) and
hasattr(x, '__package__') and x.__package__):
# check if the package has any currently loaded sub-imports
prefix = x.__name__ + '.'
# A concurrent thread could mutate sys.modules,
# make sure we iterate over a copy to avoid exceptions
for name in list(sys.modules):
# Older versions of pytest will add a "None" module to
# sys.modules.
if name is not None and name.startswith(prefix):
# check whether the function can address the sub-module
tokens = set(name[len(prefix):].split('.'))
if not tokens - set(code.co_names):
subimports.append(sys.modules[name])
return subimports
def cell_set(cell, value):
"""Set the value of a closure cell.
The point of this function is to set the cell_contents attribute of a cell
after its creation. This operation is necessary in case the cell contains a
reference to the function the cell belongs to, as when calling the
function's constructor
``f = types.FunctionType(code, globals, name, argdefs, closure)``,
closure will not be able to contain the yet-to-be-created f.
In Python3.7, cell_contents is writeable, so setting the contents of a cell
can be done simply using
>>> cell.cell_contents = value
In earlier Python3 versions, the cell_contents attribute of a cell is read
only, but this limitation can be worked around by leveraging the Python 3
``nonlocal`` keyword.
In Python2 however, this attribute is read only, and there is no
``nonlocal`` keyword. For this reason, we need to come up with more
complicated hacks to set this attribute.
The chosen approach is to create a function with a STORE_DEREF opcode,
which sets the content of a closure variable. Typically:
>>> def inner(value):
... lambda: cell # the lambda makes cell a closure
... cell = value # cell is a closure, so this triggers a STORE_DEREF
(Note that in Python2, A STORE_DEREF can never be triggered from an inner
function. The function g for example here
>>> def f(var):
... def g():
... var += 1
... return g
will not modify the closure variable ``var```inplace, but instead try to
load a local variable var and increment it. As g does not assign the local
variable ``var`` any initial value, calling f(1)() will fail at runtime.)
Our objective is to set the value of a given cell ``cell``. So we need to
somewhat reference our ``cell`` object into the ``inner`` function so that
this object (and not the smoke cell of the lambda function) gets affected
by the STORE_DEREF operation.
In inner, ``cell`` is referenced as a cell variable (an enclosing variable
that is referenced by the inner function). If we create a new function
cell_set with the exact same code as ``inner``, but with ``cell`` marked as
a free variable instead, the STORE_DEREF will be applied on its closure -
``cell``, which we can specify explicitly during construction! The new
cell_set variable thus actually sets the contents of a specified cell!
Note: we do not make use of the ``nonlocal`` keyword to set the contents of
a cell in early python3 versions to limit possible syntax errors in case
test and checker libraries decide to parse the whole file.
"""
if sys.version_info[:2] >= (3, 7): # pragma: no branch
cell.cell_contents = value
else:
_cell_set = types.FunctionType(
_cell_set_template_code, {}, '_cell_set', (), (cell,),)
_cell_set(value)
def _make_cell_set_template_code():
def _cell_set_factory(value):
lambda: cell
cell = value
co = _cell_set_factory.__code__
if PY2: # pragma: no branch
_cell_set_template_code = types.CodeType(
co.co_argcount,
co.co_nlocals,
co.co_stacksize,
co.co_flags,
co.co_code,
co.co_consts,
co.co_names,
co.co_varnames,
co.co_filename,
co.co_name,
co.co_firstlineno,
co.co_lnotab,
co.co_cellvars, # co_freevars is initialized with co_cellvars
(), # co_cellvars is made empty
)
else:
_cell_set_template_code = types.CodeType(
co.co_argcount,
co.co_kwonlyargcount, # Python 3 only argument
co.co_nlocals,
co.co_stacksize,
co.co_flags,
co.co_code,
co.co_consts,
co.co_names,
co.co_varnames,
co.co_filename,
co.co_name,
co.co_firstlineno,
co.co_lnotab,
co.co_cellvars, # co_freevars is initialized with co_cellvars
(), # co_cellvars is made empty
)
return _cell_set_template_code
if sys.version_info[:2] < (3, 7):
_cell_set_template_code = _make_cell_set_template_code()
# relevant opcodes
STORE_GLOBAL = opcode.opmap['STORE_GLOBAL']
DELETE_GLOBAL = opcode.opmap['DELETE_GLOBAL']
LOAD_GLOBAL = opcode.opmap['LOAD_GLOBAL']
GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL)
HAVE_ARGUMENT = dis.HAVE_ARGUMENT
EXTENDED_ARG = dis.EXTENDED_ARG
_BUILTIN_TYPE_NAMES = {}
for k, v in types.__dict__.items():
if type(v) is type:
_BUILTIN_TYPE_NAMES[v] = k
def _builtin_type(name):
return getattr(types, name)
if sys.version_info < (3, 4): # pragma: no branch
def _walk_global_ops(code):
"""
Yield (opcode, argument number) tuples for all
global-referencing instructions in *code*.
"""
code = getattr(code, 'co_code', b'')
if PY2: # pragma: no branch
code = map(ord, code)
n = len(code)
i = 0
extended_arg = 0
while i < n:
op = code[i]
i += 1
if op >= HAVE_ARGUMENT:
oparg = code[i] + code[i + 1] * 256 + extended_arg
extended_arg = 0
i += 2
if op == EXTENDED_ARG:
extended_arg = oparg * 65536
if op in GLOBAL_OPS:
yield op, oparg
else:
def _walk_global_ops(code):
"""
Yield (opcode, argument number) tuples for all
global-referencing instructions in *code*.
"""
for instr in dis.get_instructions(code):
op = instr.opcode
if op in GLOBAL_OPS:
yield op, instr.arg
def _extract_class_dict(cls):
"""Retrieve a copy of the dict of a class without the inherited methods"""
clsdict = dict(cls.__dict__) # copy dict proxy to a dict
if len(cls.__bases__) == 1:
inherited_dict = cls.__bases__[0].__dict__
else:
inherited_dict = {}
for base in reversed(cls.__bases__):
inherited_dict.update(base.__dict__)
to_remove = []
for name, value in clsdict.items():
try:
base_value = inherited_dict[name]
if value is base_value:
to_remove.append(name)
except KeyError:
pass
for name in to_remove:
clsdict.pop(name)
return clsdict
class CloudPickler(Pickler):
dispatch = Pickler.dispatch.copy()
def __init__(self, file, protocol=None):
if protocol is None:
protocol = DEFAULT_PROTOCOL
Pickler.__init__(self, file, protocol=protocol)
# map ids to dictionary. used to ensure that functions can share global env
self.globals_ref = {}
def dump(self, obj):
self.inject_addons()
try:
return Pickler.dump(self, obj)
except RuntimeError as e:
if 'recursion' in e.args[0]:
msg = """Could not pickle object as excessively deep recursion required."""
raise pickle.PicklingError(msg)
else:
raise
def save_memoryview(self, obj):
self.save(obj.tobytes())
dispatch[memoryview] = save_memoryview
if PY2: # pragma: no branch
def save_buffer(self, obj):
self.save(str(obj))
dispatch[buffer] = save_buffer # noqa: F821 'buffer' was removed in Python 3
def save_module(self, obj):
"""
Save a module as an import
"""
if _is_dynamic(obj):
self.save_reduce(dynamic_subimport, (obj.__name__, vars(obj)),
obj=obj)
else:
self.save_reduce(subimport, (obj.__name__,), obj=obj)
dispatch[types.ModuleType] = save_module
def save_codeobject(self, obj):
"""
Save a code object
"""
if PY3: # pragma: no branch
if hasattr(obj, "co_posonlyargcount"): # pragma: no branch
args = (
obj.co_argcount, obj.co_posonlyargcount,
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
obj.co_varnames, obj.co_filename, obj.co_name,
obj.co_firstlineno, obj.co_lnotab, obj.co_freevars,
obj.co_cellvars
)
else:
args = (
obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals,
obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts,
obj.co_names, obj.co_varnames, obj.co_filename,
obj.co_name, obj.co_firstlineno, obj.co_lnotab,
obj.co_freevars, obj.co_cellvars
)
else:
args = (
obj.co_argcount, obj.co_nlocals, obj.co_stacksize, obj.co_flags, obj.co_code,
obj.co_consts, obj.co_names, obj.co_varnames, obj.co_filename, obj.co_name,
obj.co_firstlineno, obj.co_lnotab, obj.co_freevars, obj.co_cellvars
)
self.save_reduce(types.CodeType, args, obj=obj)
dispatch[types.CodeType] = save_codeobject
def save_function(self, obj, name=None):
""" Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately.
"""
if _is_global(obj, name=name):
return Pickler.save_global(self, obj, name=name)
elif PYPY and isinstance(obj.__code__, builtin_code_type):
return self.save_pypy_builtin_func(obj)
else:
return self.save_function_tuple(obj)
dispatch[types.FunctionType] = save_function
def save_pypy_builtin_func(self, obj):
"""Save pypy equivalent of builtin functions.
PyPy does not have the concept of builtin-functions. Instead,
builtin-functions are simple function instances, but with a
builtin-code attribute.
Most of the time, builtin functions should be pickled by attribute. But
PyPy has flaky support for __qualname__, so some builtin functions such
as float.__new__ will be classified as dynamic. For this reason only,
we created this special routine. Because builtin-functions are not
expected to have closure or globals, there is no additional hack
(compared the one already implemented in pickle) to protect ourselves
from reference cycles. A simple (reconstructor, newargs, obj.__dict__)
tuple is save_reduced.
Note also that PyPy improved their support for __qualname__ in v3.6, so
this routing should be removed when cloudpickle supports only PyPy 3.6
and later.
"""
rv = (types.FunctionType, (obj.__code__, {}, obj.__name__,
obj.__defaults__, obj.__closure__),
obj.__dict__)
self.save_reduce(*rv, obj=obj)
def _save_dynamic_enum(self, obj, clsdict):
"""Special handling for dynamic Enum subclasses
Use a dedicated Enum constructor (inspired by EnumMeta.__call__) as the
EnumMeta metaclass has complex initialization that makes the Enum
subclasses hold references to their own instances.
"""
members = dict((e.name, e.value) for e in obj)
# Python 2.7 with enum34 can have no qualname:
qualname = getattr(obj, "__qualname__", None)
self.save_reduce(_make_skeleton_enum,
(obj.__bases__, obj.__name__, qualname, members,
obj.__module__, _ensure_tracking(obj), None),
obj=obj)
# Cleanup the clsdict that will be passed to _rehydrate_skeleton_class:
# Those attributes are already handled by the metaclass.
for attrname in ["_generate_next_value_", "_member_names_",
"_member_map_", "_member_type_",
"_value2member_map_"]:
clsdict.pop(attrname, None)
for member in members:
clsdict.pop(member)
def save_dynamic_class(self, obj):
"""Save a class that can't be stored as module global.
This method is used to serialize classes that are defined inside
functions, or that otherwise can't be serialized as attribute lookups
from global modules.
"""
clsdict = _extract_class_dict(obj)
clsdict.pop('__weakref__', None)
# For ABCMeta in python3.7+, remove _abc_impl as it is not picklable.
# This is a fix which breaks the cache but this only makes the first
# calls to issubclass slower.
if "_abc_impl" in clsdict:
import abc
(registry, _, _, _) = abc._get_dump(obj)
clsdict["_abc_impl"] = [subclass_weakref()
for subclass_weakref in registry]
# On PyPy, __doc__ is a readonly attribute, so we need to include it in
# the initial skeleton class. This is safe because we know that the
# doc can't participate in a cycle with the original class.
type_kwargs = {'__doc__': clsdict.pop('__doc__', None)}
if hasattr(obj, "__slots__"):
type_kwargs['__slots__'] = obj.__slots__
# pickle string length optimization: member descriptors of obj are
# created automatically from obj's __slots__ attribute, no need to
# save them in obj's state
if isinstance(obj.__slots__, string_types):
clsdict.pop(obj.__slots__)
else:
for k in obj.__slots__:
clsdict.pop(k, None)
# If type overrides __dict__ as a property, include it in the type
# kwargs. In Python 2, we can't set this attribute after construction.
__dict__ = clsdict.pop('__dict__', None)
if isinstance(__dict__, property):
type_kwargs['__dict__'] = __dict__
save = self.save
write = self.write
# We write pickle instructions explicitly here to handle the
# possibility that the type object participates in a cycle with its own
# __dict__. We first write an empty "skeleton" version of the class and
# memoize it before writing the class' __dict__ itself. We then write
# instructions to "rehydrate" the skeleton class by restoring the
# attributes from the __dict__.
#
# A type can appear in a cycle with its __dict__ if an instance of the
# type appears in the type's __dict__ (which happens for the stdlib
# Enum class), or if the type defines methods that close over the name
# of the type, (which is common for Python 2-style super() calls).
# Push the rehydration function.
save(_rehydrate_skeleton_class)
# Mark the start of the args tuple for the rehydration function.
write(pickle.MARK)
# Create and memoize an skeleton class with obj's name and bases.
if Enum is not None and issubclass(obj, Enum):
# Special handling of Enum subclasses
self._save_dynamic_enum(obj, clsdict)
else:
# "Regular" class definition:
tp = type(obj)
self.save_reduce(_make_skeleton_class,
(tp, obj.__name__, obj.__bases__, type_kwargs,
_ensure_tracking(obj), None),
obj=obj)
# Now save the rest of obj's __dict__. Any references to obj
# encountered while saving will point to the skeleton class.
save(clsdict)
# Write a tuple of (skeleton_class, clsdict).
write(pickle.TUPLE)
# Call _rehydrate_skeleton_class(skeleton_class, clsdict)
write(pickle.REDUCE)
def save_function_tuple(self, func):
""" Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
can contain a ref to the func itself. Thus, a naive save on these
pieces could trigger an infinite loop of save's. To get around that,
we first create a skeleton func object using just the code (this is
safe, since this won't contain a ref to the func), and memoize it as
soon as it's created. The other stuff can then be filled in later.
"""
if is_tornado_coroutine(func):
self.save_reduce(_rebuild_tornado_coroutine, (func.__wrapped__,),
obj=func)
return
save = self.save
write = self.write
code, f_globals, defaults, closure_values, dct, base_globals = self.extract_func_data(func)
save(_fill_function) # skeleton function updater
write(pickle.MARK) # beginning of tuple that _fill_function expects
# Extract currently-imported submodules used by func. Storing these
# modules in a smoke _cloudpickle_subimports attribute of the object's
# state will trigger the side effect of importing these modules at
# unpickling time (which is necessary for func to work correctly once
# depickled)
submodules = _find_imported_submodules(
code,
itertools.chain(f_globals.values(), closure_values or ()),
)
# create a skeleton function object and memoize it
save(_make_skel_func)
save((
code,
len(closure_values) if closure_values is not None else -1,
base_globals,
))
write(pickle.REDUCE)
self.memoize(func)
# save the rest of the func data needed by _fill_function
state = {
'globals': f_globals,
'defaults': defaults,
'dict': dct,
'closure_values': closure_values,
'module': func.__module__,
'name': func.__name__,
'doc': func.__doc__,
'_cloudpickle_submodules': submodules
}
if hasattr(func, '__annotations__') and sys.version_info >= (3, 4):
state['annotations'] = func.__annotations__
if hasattr(func, '__qualname__'):
state['qualname'] = func.__qualname__
if hasattr(func, '__kwdefaults__'):
state['kwdefaults'] = func.__kwdefaults__
save(state)
write(pickle.TUPLE)
write(pickle.REDUCE) # applies _fill_function on the tuple
def extract_func_data(self, func):
"""
Turn the function into a tuple of data necessary to recreate it:
code, globals, defaults, closure_values, dict
"""
code = func.__code__
# extract all global ref's
func_global_refs = _extract_code_globals(code)
# process all variables referenced by global environment
f_globals = {}
for var in func_global_refs:
if var in func.__globals__:
f_globals[var] = func.__globals__[var]
# defaults requires no processing
defaults = func.__defaults__
# process closure
closure = (
list(map(_get_cell_contents, func.__closure__))
if func.__closure__ is not None
else None
)
# save the dict
dct = func.__dict__
# base_globals represents the future global namespace of func at
# unpickling time. Looking it up and storing it in globals_ref allow
# functions sharing the same globals at pickling time to also
# share them once unpickled, at one condition: since globals_ref is
# an attribute of a Cloudpickler instance, and that a new CloudPickler is
# created each time pickle.dump or pickle.dumps is called, functions
# also need to be saved within the same invokation of
# cloudpickle.dump/cloudpickle.dumps (for example: cloudpickle.dumps([f1, f2])). There
# is no such limitation when using Cloudpickler.dump, as long as the
# multiple invokations are bound to the same Cloudpickler.
base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
if base_globals == {}:
# Add module attributes used to resolve relative imports
# instructions inside func.
for k in ["__package__", "__name__", "__path__", "__file__"]:
# Some built-in functions/methods such as object.__new__ have
# their __globals__ set to None in PyPy
if func.__globals__ is not None and k in func.__globals__:
base_globals[k] = func.__globals__[k]
return (code, f_globals, defaults, closure, dct, base_globals)
if not PY3: # pragma: no branch
# Python3 comes with native reducers that allow builtin functions and
# methods pickling as module/class attributes. The following method
# extends this for python2.
# Please note that currently, neither pickle nor cloudpickle support
# dynamically created builtin functions/method pickling.
def save_builtin_function_or_method(self, obj):
is_bound = getattr(obj, '__self__', None) is not None
if is_bound:
# obj is a bound builtin method.
rv = (getattr, (obj.__self__, obj.__name__))
return self.save_reduce(obj=obj, *rv)
is_unbound = hasattr(obj, '__objclass__')
if is_unbound:
# obj is an unbound builtin method (accessed from its class)
rv = (getattr, (obj.__objclass__, obj.__name__))
return self.save_reduce(obj=obj, *rv)
# Otherwise, obj is not a method, but a function. Fallback to
# default pickling by attribute.
return Pickler.save_global(self, obj)
dispatch[types.BuiltinFunctionType] = save_builtin_function_or_method
# A comprehensive summary of the various kinds of builtin methods can
# be found in PEP 579: https://www.python.org/dev/peps/pep-0579/
classmethod_descriptor_type = type(float.__dict__['fromhex'])
wrapper_descriptor_type = type(float.__repr__)
method_wrapper_type = type(1.5.__repr__)
dispatch[classmethod_descriptor_type] = save_builtin_function_or_method
dispatch[wrapper_descriptor_type] = save_builtin_function_or_method
dispatch[method_wrapper_type] = save_builtin_function_or_method
if sys.version_info[:2] < (3, 4):
method_descriptor = type(str.upper)
dispatch[method_descriptor] = save_builtin_function_or_method
def save_getset_descriptor(self, obj):
return self.save_reduce(getattr, (obj.__objclass__, obj.__name__))
dispatch[types.GetSetDescriptorType] = save_getset_descriptor
def save_global(self, obj, name=None, pack=struct.pack):
"""
Save a "global".
The name of this method is somewhat misleading: all types get
dispatched here.
"""
if obj is type(None):
return self.save_reduce(type, (None,), obj=obj)
elif obj is type(Ellipsis):
return self.save_reduce(type, (Ellipsis,), obj=obj)
elif obj is type(NotImplemented):
return self.save_reduce(type, (NotImplemented,), obj=obj)
elif obj in _BUILTIN_TYPE_NAMES:
return self.save_reduce(
_builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj)
elif name is not None:
Pickler.save_global(self, obj, name=name)
elif not _is_global(obj, name=name):
self.save_dynamic_class(obj)
else:
Pickler.save_global(self, obj, name=name)
dispatch[type] = save_global
dispatch[types.ClassType] = save_global
def save_instancemethod(self, obj):
# Memoization rarely is ever useful due to python bounding
if obj.__self__ is None:
self.save_reduce(getattr, (obj.im_class, obj.__name__))
else:
if PY3: # pragma: no branch
self.save_reduce(types.MethodType, (obj.__func__, obj.__self__), obj=obj)
else:
self.save_reduce(
types.MethodType,
(obj.__func__, obj.__self__, type(obj.__self__)), obj=obj)
dispatch[types.MethodType] = save_instancemethod
def save_inst(self, obj):
"""Inner logic to save instance. Based off pickle.save_inst"""
cls = obj.__class__
# Try the dispatch table (pickle module doesn't do it)
f = self.dispatch.get(cls)
if f:
f(self, obj) # Call unbound method with explicit self
return
memo = self.memo
write = self.write
save = self.save
if hasattr(obj, '__getinitargs__'):
args = obj.__getinitargs__()
len(args) # XXX Assert it's a sequence
pickle._keep_alive(args, memo)
else:
args = ()
write(pickle.MARK)
if self.bin:
save(cls)
for arg in args:
save(arg)
write(pickle.OBJ)
else:
for arg in args:
save(arg)
write(pickle.INST + cls.__module__ + '\n' + cls.__name__ + '\n')
self.memoize(obj)
try:
getstate = obj.__getstate__
except AttributeError:
stuff = obj.__dict__
else:
stuff = getstate()
pickle._keep_alive(stuff, memo)
save(stuff)
write(pickle.BUILD)
if PY2: # pragma: no branch
dispatch[types.InstanceType] = save_inst
def save_property(self, obj):
# properties not correctly saved in python
self.save_reduce(property, (obj.fget, obj.fset, obj.fdel, obj.__doc__), obj=obj)
dispatch[property] = save_property
def save_classmethod(self, obj):
orig_func = obj.__func__
self.save_reduce(type(obj), (orig_func,), obj=obj)
dispatch[classmethod] = save_classmethod
dispatch[staticmethod] = save_classmethod
def save_itemgetter(self, obj):
"""itemgetter serializer (needed for namedtuple support)"""
class Dummy:
def __getitem__(self, item):
return item
items = obj(Dummy())
if not isinstance(items, tuple):
items = (items,)
return self.save_reduce(operator.itemgetter, items)
if type(operator.itemgetter) is type:
dispatch[operator.itemgetter] = save_itemgetter
def save_attrgetter(self, obj):
"""attrgetter serializer"""
class Dummy(object):
def __init__(self, attrs, index=None):
self.attrs = attrs
self.index = index
def __getattribute__(self, item):
attrs = object.__getattribute__(self, "attrs")
index = object.__getattribute__(self, "index")
if index is None:
index = len(attrs)
attrs.append(item)
else:
attrs[index] = ".".join([attrs[index], item])
return type(self)(attrs, index)
attrs = []
obj(Dummy(attrs))
return self.save_reduce(operator.attrgetter, tuple(attrs))
if type(operator.attrgetter) is type:
dispatch[operator.attrgetter] = save_attrgetter
def save_file(self, obj):
"""Save a file"""
try:
import StringIO as pystringIO # we can't use cStringIO as it lacks the name attribute
except ImportError:
import io as pystringIO
if not hasattr(obj, 'name') or not hasattr(obj, 'mode'):
raise pickle.PicklingError("Cannot pickle files that do not map to an actual file")
if obj is sys.stdout:
return self.save_reduce(getattr, (sys, 'stdout'), obj=obj)
if obj is sys.stderr:
return self.save_reduce(getattr, (sys, 'stderr'), obj=obj)
if obj is sys.stdin:
raise pickle.PicklingError("Cannot pickle standard input")
if obj.closed:
raise pickle.PicklingError("Cannot pickle closed files")
if hasattr(obj, 'isatty') and obj.isatty():
raise pickle.PicklingError("Cannot pickle files that map to tty objects")
if 'r' not in obj.mode and '+' not in obj.mode:
raise pickle.PicklingError("Cannot pickle files that are not opened for reading: %s" % obj.mode)
name = obj.name
retval = pystringIO.StringIO()
try:
# Read the whole file
curloc = obj.tell()
obj.seek(0)
contents = obj.read()
obj.seek(curloc)
except IOError:
raise pickle.PicklingError("Cannot pickle file %s as it cannot be read" % name)
retval.write(contents)
retval.seek(curloc)
retval.name = name
self.save(retval)
self.memoize(obj)
def save_ellipsis(self, obj):
self.save_reduce(_gen_ellipsis, ())
def save_not_implemented(self, obj):
self.save_reduce(_gen_not_implemented, ())
try: # Python 2
dispatch[file] = save_file
except NameError: # Python 3 # pragma: no branch
dispatch[io.TextIOWrapper] = save_file
dispatch[type(Ellipsis)] = save_ellipsis
dispatch[type(NotImplemented)] = save_not_implemented
def save_weakset(self, obj):
self.save_reduce(weakref.WeakSet, (list(obj),))
dispatch[weakref.WeakSet] = save_weakset
def save_logger(self, obj):
self.save_reduce(logging.getLogger, (obj.name,), obj=obj)
dispatch[logging.Logger] = save_logger
def save_root_logger(self, obj):
self.save_reduce(logging.getLogger, (), obj=obj)
dispatch[logging.RootLogger] = save_root_logger
if hasattr(types, "MappingProxyType"): # pragma: no branch
def save_mappingproxy(self, obj):
self.save_reduce(types.MappingProxyType, (dict(obj),), obj=obj)
dispatch[types.MappingProxyType] = save_mappingproxy
"""Special functions for Add-on libraries"""
def inject_addons(self):
"""Plug in system. Register additional pickling functions if modules already loaded"""
pass
# Tornado support
def is_tornado_coroutine(func):
"""
Return whether *func* is a Tornado coroutine function.
Running coroutines are not supported.
"""
if 'tornado.gen' not in sys.modules:
return False
gen = sys.modules['tornado.gen']
if not hasattr(gen, "is_coroutine_function"):
# Tornado version is too old
return False
return gen.is_coroutine_function(func)
def _rebuild_tornado_coroutine(func):
from tornado import gen
return gen.coroutine(func)
# Shorthands for legacy support
def dump(obj, file, protocol=None):
"""Serialize obj as bytes streamed into file
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
CloudPickler(file, protocol=protocol).dump(obj)
def dumps(obj, protocol=None):
"""Serialize obj as a string of bytes allocated in memory
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
file = StringIO()
try:
cp = CloudPickler(file, protocol=protocol)
cp.dump(obj)
return file.getvalue()
finally:
file.close()
# including pickles unloading functions in this namespace
load = pickle.load
loads = pickle.loads
# hack for __import__ not working as desired
def subimport(name):
__import__(name)
return sys.modules[name]
def dynamic_subimport(name, vars):
mod = types.ModuleType(name)
mod.__dict__.update(vars)
return mod
def _gen_ellipsis():
return Ellipsis
def _gen_not_implemented():
return NotImplemented
def _get_cell_contents(cell):
try:
return cell.cell_contents
except ValueError:
# sentinel used by ``_fill_function`` which will leave the cell empty
return _empty_cell_value
def instance(cls):
"""Create a new instance of a class.
Parameters
----------
cls : type
The class to create an instance of.
Returns
-------
instance : cls
A new instance of ``cls``.
"""
return cls()
@instance
class _empty_cell_value(object):
"""sentinel for empty closures
"""
@classmethod
def __reduce__(cls):
return cls.__name__
def _fill_function(*args):
"""Fills in the rest of function data into the skeleton function object
The skeleton itself is create by _make_skel_func().
"""
if len(args) == 2:
func = args[0]
state = args[1]
elif len(args) == 5:
# Backwards compat for cloudpickle v0.4.0, after which the `module`
# argument was introduced
func = args[0]
keys = ['globals', 'defaults', 'dict', 'closure_values']
state = dict(zip(keys, args[1:]))
elif len(args) == 6:
# Backwards compat for cloudpickle v0.4.1, after which the function
# state was passed as a dict to the _fill_function it-self.
func = args[0]
keys = ['globals', 'defaults', 'dict', 'module', 'closure_values']
state = dict(zip(keys, args[1:]))
else:
raise ValueError('Unexpected _fill_value arguments: %r' % (args,))
# - At pickling time, any dynamic global variable used by func is
# serialized by value (in state['globals']).
# - At unpickling time, func's __globals__ attribute is initialized by
# first retrieving an empty isolated namespace that will be shared
# with other functions pickled from the same original module
# by the same CloudPickler instance and then updated with the
# content of state['globals'] to populate the shared isolated
# namespace with all the global variables that are specifically
# referenced for this function.
func.__globals__.update(state['globals'])
func.__defaults__ = state['defaults']
func.__dict__ = state['dict']
if 'annotations' in state:
func.__annotations__ = state['annotations']
if 'doc' in state:
func.__doc__ = state['doc']
if 'name' in state:
func.__name__ = state['name']
if 'module' in state:
func.__module__ = state['module']
if 'qualname' in state:
func.__qualname__ = state['qualname']
if 'kwdefaults' in state:
func.__kwdefaults__ = state['kwdefaults']
# _cloudpickle_subimports is a set of submodules that must be loaded for
# the pickled function to work correctly at unpickling time. Now that these
# submodules are depickled (hence imported), they can be removed from the
# object's state (the object state only served as a reference holder to
# these submodules)
if '_cloudpickle_submodules' in state:
state.pop('_cloudpickle_submodules')
cells = func.__closure__
if cells is not None:
for cell, value in zip(cells, state['closure_values']):
if value is not _empty_cell_value:
cell_set(cell, value)
return func
def _make_empty_cell():
if False:
# trick the compiler into creating an empty cell in our lambda
cell = None
raise AssertionError('this route should not be executed')
return (lambda: cell).__closure__[0]
def _make_skel_func(code, cell_count, base_globals=None):
""" Creates a skeleton function object that contains just the provided
code and the correct number of cells in func_closure. All other
func attributes (e.g. func_globals) are empty.
"""
# This is backward-compatibility code: for cloudpickle versions between
# 0.5.4 and 0.7, base_globals could be a string or None. base_globals
# should now always be a dictionary.
if base_globals is None or isinstance(base_globals, str):
base_globals = {}
base_globals['__builtins__'] = __builtins__
closure = (
tuple(_make_empty_cell() for _ in range(cell_count))
if cell_count >= 0 else
None
)
return types.FunctionType(code, base_globals, None, None, closure)
def _make_skeleton_class(type_constructor, name, bases, type_kwargs,
class_tracker_id, extra):
"""Build dynamic class with an empty __dict__ to be filled once memoized
If class_tracker_id is not None, try to lookup an existing class definition
matching that id. If none is found, track a newly reconstructed class
definition under that id so that other instances stemming from the same
class id will also reuse this class definition.
The "extra" variable is meant to be a dict (or None) that can be used for
forward compatibility shall the need arise.
"""
skeleton_class = type_constructor(name, bases, type_kwargs)
return _lookup_class_or_track(class_tracker_id, skeleton_class)
def _rehydrate_skeleton_class(skeleton_class, class_dict):
"""Put attributes from `class_dict` back on `skeleton_class`.
See CloudPickler.save_dynamic_class for more info.
"""
registry = None
for attrname, attr in class_dict.items():
if attrname == "_abc_impl":
registry = attr
else:
setattr(skeleton_class, attrname, attr)
if registry is not None:
for subclass in registry:
skeleton_class.register(subclass)
return skeleton_class
def _make_skeleton_enum(bases, name, qualname, members, module,
class_tracker_id, extra):
"""Build dynamic enum with an empty __dict__ to be filled once memoized
The creation of the enum class is inspired by the code of
EnumMeta._create_.
If class_tracker_id is not None, try to lookup an existing enum definition
matching that id. If none is found, track a newly reconstructed enum
definition under that id so that other instances stemming from the same
class id will also reuse this enum definition.
The "extra" variable is meant to be a dict (or None) that can be used for
forward compatibility shall the need arise.
"""
# enums always inherit from their base Enum class at the last position in
# the list of base classes:
enum_base = bases[-1]
metacls = enum_base.__class__
classdict = metacls.__prepare__(name, bases)
for member_name, member_value in members.items():
classdict[member_name] = member_value
enum_class = metacls.__new__(metacls, name, bases, classdict)
enum_class.__module__ = module
# Python 2.7 compat
if qualname is not None:
enum_class.__qualname__ = qualname
return _lookup_class_or_track(class_tracker_id, enum_class)
def _is_dynamic(module):
"""
Return True if the module is special module that cannot be imported by its
name.
"""
# Quick check: module that have __file__ attribute are not dynamic modules.
if hasattr(module, '__file__'):
return False
if hasattr(module, '__spec__'):
if module.__spec__ is not None:
return False
# In PyPy, Some built-in modules such as _codecs can have their
# __spec__ attribute set to None despite being imported. For such
# modules, the ``_find_spec`` utility of the standard library is used.
parent_name = module.__name__.rpartition('.')[0]
if parent_name: # pragma: no cover
# This code handles the case where an imported package (and not
# module) remains with __spec__ set to None. It is however untested
# as no package in the PyPy stdlib has __spec__ set to None after
# it is imported.
try:
parent = sys.modules[parent_name]
except KeyError:
msg = "parent {!r} not in sys.modules"
raise ImportError(msg.format(parent_name))
else:
pkgpath = parent.__path__
else:
pkgpath = None
return _find_spec(module.__name__, pkgpath, module) is None
else:
# Backward compat for Python 2
import imp
try:
path = None
for part in module.__name__.split('.'):
if path is not None:
path = [path]
f, path, description = imp.find_module(part, path)
if f is not None:
f.close()
except ImportError:
return True
return False
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/cloudpickle/cloudpickle_fast.py
|
Python
|
"""
New, fast version of the CloudPickler.
This new CloudPickler class can now extend the fast C Pickler instead of the
previous Python implementation of the Pickler class. Because this functionality
is only available for Python versions 3.8+, a lot of backward-compatibility
code is also removed.
Note that the C Pickler sublassing API is CPython-specific. Therefore, some
guards present in cloudpickle.py that were written to handle PyPy specificities
are not present in cloudpickle_fast.py
"""
import abc
import copyreg
import io
import itertools
import logging
import sys
import types
import weakref
from .cloudpickle import (
_is_dynamic, _extract_code_globals, _BUILTIN_TYPE_NAMES, DEFAULT_PROTOCOL,
_find_imported_submodules, _get_cell_contents, _is_global, _builtin_type,
Enum, _ensure_tracking, _make_skeleton_class, _make_skeleton_enum,
_extract_class_dict, string_types, dynamic_subimport, subimport, cell_set,
_make_empty_cell
)
if sys.version_info[:2] < (3, 8):
import pickle5 as pickle
from pickle5 import Pickler
load, loads = pickle.load, pickle.loads
else:
import _pickle
import pickle
from _pickle import Pickler
load, loads = _pickle.load, _pickle.loads
# Shorthands similar to pickle.dump/pickle.dumps
def dump(obj, file, protocol=None, buffer_callback=None):
"""Serialize obj as bytes streamed into file
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
CloudPickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj)
def dumps(obj, protocol=None, buffer_callback=None):
"""Serialize obj as a string of bytes allocated in memory
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed
between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
with io.BytesIO() as file:
cp = CloudPickler(file, protocol=protocol, buffer_callback=buffer_callback)
cp.dump(obj)
return file.getvalue()
# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
# -------------------------------------------------
def _class_getnewargs(obj):
type_kwargs = {}
if hasattr(obj, "__slots__"):
type_kwargs["__slots__"] = obj.__slots__
__dict__ = obj.__dict__.get('__dict__', None)
if isinstance(__dict__, property):
type_kwargs['__dict__'] = __dict__
return (type(obj), obj.__name__, obj.__bases__, type_kwargs,
_ensure_tracking(obj), None)
def _enum_getnewargs(obj):
members = dict((e.name, e.value) for e in obj)
return (obj.__bases__, obj.__name__, obj.__qualname__, members,
obj.__module__, _ensure_tracking(obj), None)
# COLLECTION OF OBJECTS RECONSTRUCTORS
# ------------------------------------
def _file_reconstructor(retval):
return retval
# COLLECTION OF OBJECTS STATE GETTERS
# -----------------------------------
def _function_getstate(func):
# - Put func's dynamic attributes (stored in func.__dict__) in state. These
# attributes will be restored at unpickling time using
# f.__dict__.update(state)
# - Put func's members into slotstate. Such attributes will be restored at
# unpickling time by iterating over slotstate and calling setattr(func,
# slotname, slotvalue)
slotstate = {
"__name__": func.__name__,
"__qualname__": func.__qualname__,
"__annotations__": func.__annotations__,
"__kwdefaults__": func.__kwdefaults__,
"__defaults__": func.__defaults__,
"__module__": func.__module__,
"__doc__": func.__doc__,
}
f_globals_ref = _extract_code_globals(func.__code__)
f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in
func.__globals__}
closure_values = (
list(map(_get_cell_contents, func.__closure__))
if func.__closure__ is not None else ()
)
# Extract currently-imported submodules used by func. Storing these modules
# in a smoke _cloudpickle_subimports attribute of the object's state will
# trigger the side effect of importing these modules at unpickling time
# (which is necessary for func to work correctly once depickled)
slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
func.__code__, itertools.chain(f_globals.values(), closure_values))
slotstate["__globals__"] = f_globals
state = func.__dict__
return state, slotstate
def _class_getstate(obj):
clsdict = _extract_class_dict(obj)
clsdict.pop('__weakref__', None)
# For ABCMeta in python3.7+, remove _abc_impl as it is not picklable.
# This is a fix which breaks the cache but this only makes the first
# calls to issubclass slower.
if "_abc_impl" in clsdict:
(registry, _, _, _) = abc._get_dump(obj)
clsdict["_abc_impl"] = [subclass_weakref()
for subclass_weakref in registry]
if hasattr(obj, "__slots__"):
# pickle string length optimization: member descriptors of obj are
# created automatically from obj's __slots__ attribute, no need to
# save them in obj's state
if isinstance(obj.__slots__, string_types):
clsdict.pop(obj.__slots__)
else:
for k in obj.__slots__:
clsdict.pop(k, None)
clsdict.pop('__dict__', None) # unpicklable property object
return (clsdict, {})
def _enum_getstate(obj):
clsdict, slotstate = _class_getstate(obj)
members = dict((e.name, e.value) for e in obj)
# Cleanup the clsdict that will be passed to _rehydrate_skeleton_class:
# Those attributes are already handled by the metaclass.
for attrname in ["_generate_next_value_", "_member_names_",
"_member_map_", "_member_type_",
"_value2member_map_"]:
clsdict.pop(attrname, None)
for member in members:
clsdict.pop(member)
# Special handling of Enum subclasses
return clsdict, slotstate
# COLLECTIONS OF OBJECTS REDUCERS
# -------------------------------
# A reducer is a function taking a single argument (obj), and that returns a
# tuple with all the necessary data to re-construct obj. Apart from a few
# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
# correctly pickle an object.
# While many built-in objects (Exceptions objects, instances of the "object"
# class, etc), are shipped with their own built-in reducer (invoked using
# obj.__reduce__), some do not. The following methods were created to "fill
# these holes".
def _code_reduce(obj):
"""codeobject reducer"""
if hasattr(obj, "co_posonlyargcount"): # pragma: no branch
args = (
obj.co_argcount, obj.co_posonlyargcount,
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
obj.co_varnames, obj.co_filename, obj.co_name,
obj.co_firstlineno, obj.co_lnotab, obj.co_freevars,
obj.co_cellvars
)
else:
args = (
obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals,
obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts,
obj.co_names, obj.co_varnames, obj.co_filename,
obj.co_name, obj.co_firstlineno, obj.co_lnotab,
obj.co_freevars, obj.co_cellvars
)
return types.CodeType, args
def _make_cell(contents):
cell = _make_empty_cell()
cell_set(cell, contents)
return cell
def _cell_reduce(obj):
"""Cell (containing values of a function's free variables) reducer"""
try:
contents = (obj.cell_contents,)
except ValueError: # cell is empty
contents = ()
if sys.version_info[:2] < (3, 8):
if contents:
return _make_cell, contents
else:
return _make_empty_cell, ()
else:
return types.CellType, contents
def _classmethod_reduce(obj):
orig_func = obj.__func__
return type(obj), (orig_func,)
def _file_reduce(obj):
"""Save a file"""
import io
if not hasattr(obj, "name") or not hasattr(obj, "mode"):
raise pickle.PicklingError(
"Cannot pickle files that do not map to an actual file"
)
if obj is sys.stdout:
return getattr, (sys, "stdout")
if obj is sys.stderr:
return getattr, (sys, "stderr")
if obj is sys.stdin:
raise pickle.PicklingError("Cannot pickle standard input")
if obj.closed:
raise pickle.PicklingError("Cannot pickle closed files")
if hasattr(obj, "isatty") and obj.isatty():
raise pickle.PicklingError(
"Cannot pickle files that map to tty objects"
)
if "r" not in obj.mode and "+" not in obj.mode:
raise pickle.PicklingError(
"Cannot pickle files that are not opened for reading: %s"
% obj.mode
)
name = obj.name
retval = io.StringIO()
try:
# Read the whole file
curloc = obj.tell()
obj.seek(0)
contents = obj.read()
obj.seek(curloc)
except IOError:
raise pickle.PicklingError(
"Cannot pickle file %s as it cannot be read" % name
)
retval.write(contents)
retval.seek(curloc)
retval.name = name
return _file_reconstructor, (retval,)
def _getset_descriptor_reduce(obj):
return getattr, (obj.__objclass__, obj.__name__)
def _mappingproxy_reduce(obj):
return types.MappingProxyType, (dict(obj),)
def _memoryview_reduce(obj):
return bytes, (obj.tobytes(),)
def _module_reduce(obj):
if _is_dynamic(obj):
return dynamic_subimport, (obj.__name__, vars(obj))
else:
return subimport, (obj.__name__,)
def _method_reduce(obj):
return (types.MethodType, (obj.__func__, obj.__self__))
def _logger_reduce(obj):
return logging.getLogger, (obj.name,)
def _root_logger_reduce(obj):
return logging.getLogger, ()
def _weakset_reduce(obj):
return weakref.WeakSet, (list(obj),)
def _dynamic_class_reduce(obj):
"""
Save a class that can't be stored as module global.
This method is used to serialize classes that are defined inside
functions, or that otherwise can't be serialized as attribute lookups
from global modules.
"""
if Enum is not None and issubclass(obj, Enum):
return (
_make_skeleton_enum, _enum_getnewargs(obj), _enum_getstate(obj),
None, None, _class_setstate
)
else:
return (
_make_skeleton_class, _class_getnewargs(obj), _class_getstate(obj),
None, None, _class_setstate
)
def _class_reduce(obj):
"""Select the reducer depending on the dynamic nature of the class obj"""
if obj is type(None): # noqa
return type, (None,)
elif obj is type(Ellipsis):
return type, (Ellipsis,)
elif obj is type(NotImplemented):
return type, (NotImplemented,)
elif obj in _BUILTIN_TYPE_NAMES:
return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
elif not _is_global(obj):
return _dynamic_class_reduce(obj)
return NotImplemented
# COLLECTIONS OF OBJECTS STATE SETTERS
# ------------------------------------
# state setters are called at unpickling time, once the object is created and
# it has to be updated to how it was at unpickling time.
def _function_setstate(obj, state):
"""Update the state of a dynaamic function.
As __closure__ and __globals__ are readonly attributes of a function, we
cannot rely on the native setstate routine of pickle.load_build, that calls
setattr on items of the slotstate. Instead, we have to modify them inplace.
"""
state, slotstate = state
obj.__dict__.update(state)
obj_globals = slotstate.pop("__globals__")
# _cloudpickle_subimports is a set of submodules that must be loaded for
# the pickled function to work correctly at unpickling time. Now that these
# submodules are depickled (hence imported), they can be removed from the
# object's state (the object state only served as a reference holder to
# these submodules)
slotstate.pop("_cloudpickle_submodules")
obj.__globals__.update(obj_globals)
obj.__globals__["__builtins__"] = __builtins__
for k, v in slotstate.items():
setattr(obj, k, v)
def _class_setstate(obj, state):
state, slotstate = state
registry = None
for attrname, attr in state.items():
if attrname == "_abc_impl":
registry = attr
else:
setattr(obj, attrname, attr)
if registry is not None:
for subclass in registry:
obj.register(subclass)
return obj
def _property_reduce(obj):
# Python < 3.8 only
return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
class CloudPickler(Pickler):
"""Fast C Pickler extension with additional reducing routines.
CloudPickler's extensions exist into into:
* its dispatch_table containing reducers that are called only if ALL
built-in saving functions were previously discarded.
* a special callback named "reducer_override", invoked before standard
function/class builtin-saving method (save_global), to serialize dynamic
functions
"""
# cloudpickle's own dispatch_table, containing the additional set of
# objects (compared to the standard library pickle) that cloupickle can
# serialize.
dispatch = {}
dispatch[classmethod] = _classmethod_reduce
dispatch[io.TextIOWrapper] = _file_reduce
dispatch[logging.Logger] = _logger_reduce
dispatch[logging.RootLogger] = _root_logger_reduce
dispatch[memoryview] = _memoryview_reduce
dispatch[staticmethod] = _classmethod_reduce
dispatch[types.CodeType] = _code_reduce
dispatch[types.GetSetDescriptorType] = _getset_descriptor_reduce
dispatch[types.ModuleType] = _module_reduce
dispatch[types.MethodType] = _method_reduce
dispatch[types.MappingProxyType] = _mappingproxy_reduce
dispatch[weakref.WeakSet] = _weakset_reduce
if sys.version_info[:2] >= (3, 8):
dispatch[types.CellType] = _cell_reduce
else:
dispatch[type(_make_empty_cell())] = _cell_reduce
if sys.version_info[:2] < (3, 8):
dispatch[property] = _property_reduce
def __init__(self, file, protocol=None, buffer_callback=None):
if protocol is None:
protocol = DEFAULT_PROTOCOL
Pickler.__init__(self, file, protocol=protocol, buffer_callback=buffer_callback)
# map functions __globals__ attribute ids, to ensure that functions
# sharing the same global namespace at pickling time also share their
# global namespace at unpickling time.
self.globals_ref = {}
# Take into account potential custom reducers registered by external
# modules
self.dispatch_table = copyreg.dispatch_table.copy()
self.dispatch_table.update(self.dispatch)
self.proto = int(protocol)
def reducer_override(self, obj):
"""Type-agnostic reducing callback for function and classes.
For performance reasons, subclasses of the C _pickle.Pickler class
cannot register custom reducers for functions and classes in the
dispatch_table. Reducer for such types must instead implemented in the
special reducer_override method.
Note that method will be called for any object except a few
builtin-types (int, lists, dicts etc.), which differs from reducers in
the Pickler's dispatch_table, each of them being invoked for objects of
a specific type only.
This property comes in handy for classes: although most classes are
instances of the ``type`` metaclass, some of them can be instances of
other custom metaclasses (such as enum.EnumMeta for example). In
particular, the metaclass will likely not be known in advance, and thus
cannot be special-cased using an entry in the dispatch_table.
reducer_override, among other things, allows us to register a reducer
that will be called for any class, independently of its type.
Notes:
* reducer_override has the priority over dispatch_table-registered
reducers.
* reducer_override can be used to fix other limitations of cloudpickle
for other types that suffered from type-specific reducers, such as
Exceptions. See https://github.com/cloudpipe/cloudpickle/issues/248
"""
t = type(obj)
try:
is_anyclass = issubclass(t, type)
except TypeError: # t is not a class (old Boost; see SF #502085)
is_anyclass = False
if is_anyclass:
return _class_reduce(obj)
elif isinstance(obj, types.FunctionType):
return self._function_reduce(obj)
else:
# fallback to save_global, including the Pickler's distpatch_table
return NotImplemented
# function reducers are defined as instance methods of CloudPickler
# objects, as they rely on a CloudPickler attribute (globals_ref)
def _dynamic_function_reduce(self, func):
"""Reduce a function that is not pickleable via attribute lookup."""
newargs = self._function_getnewargs(func)
state = _function_getstate(func)
return (types.FunctionType, newargs, state, None, None,
_function_setstate)
def _function_reduce(self, obj):
"""Reducer for function objects.
If obj is a top-level attribute of a file-backed module, this
reducer returns NotImplemented, making the CloudPickler fallback to
traditional _pickle.Pickler routines to save obj. Otherwise, it reduces
obj using a custom cloudpickle reducer designed specifically to handle
dynamic functions.
As opposed to cloudpickle.py, There no special handling for builtin
pypy functions because cloudpickle_fast is CPython-specific.
"""
if _is_global(obj):
return NotImplemented
else:
return self._dynamic_function_reduce(obj)
def _function_getnewargs(self, func):
code = func.__code__
# base_globals represents the future global namespace of func at
# unpickling time. Looking it up and storing it in
# CloudpiPickler.globals_ref allow functions sharing the same globals
# at pickling time to also share them once unpickled, at one condition:
# since globals_ref is an attribute of a CloudPickler instance, and
# that a new CloudPickler is created each time pickle.dump or
# pickle.dumps is called, functions also need to be saved within the
# same invocation of cloudpickle.dump/cloudpickle.dumps (for example:
# cloudpickle.dumps([f1, f2])). There is no such limitation when using
# CloudPickler.dump, as long as the multiple invocations are bound to
# the same CloudPickler.
base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
if base_globals == {}:
# Add module attributes used to resolve relative imports
# instructions inside func.
for k in ["__package__", "__name__", "__path__", "__file__"]:
if k in func.__globals__:
base_globals[k] = func.__globals__[k]
return code, base_globals, None, None, func.__closure__
def dump(self, obj):
try:
return Pickler.dump(self, obj)
except RuntimeError as e:
if "recursion" in e.args[0]:
msg = (
"Could not pickle object as excessively deep recursion "
"required."
)
raise pickle.PicklingError(msg)
else:
raise
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/cluster_utils.py
|
Python
|
import logging
import time
import redis
import ray
from ray import ray_constants
logger = logging.getLogger(__name__)
class Cluster:
def __init__(self,
initialize_head=False,
connect=False,
head_node_args=None,
shutdown_at_exit=True):
"""Initializes the cluster.
Args:
initialize_head (bool): Automatically start a Ray cluster
by initializing the head node. Defaults to False.
connect (bool): If `initialize_head=True` and `connect=True`,
ray.init will be called with the redis address of this cluster
passed in.
head_node_args (dict): Arguments to be passed into
`start_ray_head` via `self.add_node`.
shutdown_at_exit (bool): If True, registers an exit hook
for shutting down all started processes.
"""
self.head_node = None
self.worker_nodes = set()
self.redis_address = None
self.connected = False
self._shutdown_at_exit = shutdown_at_exit
if not initialize_head and connect:
raise RuntimeError("Cannot connect to uninitialized cluster.")
if initialize_head:
head_node_args = head_node_args or {}
self.add_node(**head_node_args)
if connect:
self.connect()
@property
def address(self):
return self.redis_address
def connect(self):
"""Connect the driver to the cluster."""
assert self.redis_address is not None
assert not self.connected
output_info = ray.init(
ignore_reinit_error=True,
address=self.redis_address,
redis_password=self.redis_password)
logger.info(output_info)
self.connected = True
def add_node(self, **node_args):
"""Adds a node to the local Ray Cluster.
All nodes are by default started with the following settings:
cleanup=True,
num_cpus=1,
object_store_memory=150 * 1024 * 1024 # 150 MiB
Args:
node_args: Keyword arguments used in `start_ray_head` and
`start_ray_node`. Overrides defaults.
Returns:
Node object of the added Ray node.
"""
default_kwargs = {
"num_cpus": 1,
"num_gpus": 0,
"object_store_memory": 150 * 1024 * 1024, # 150 MiB
}
ray_params = ray.parameter.RayParams(**node_args)
ray_params.use_pickle = ray.cloudpickle.FAST_CLOUDPICKLE_USED
ray_params.update_if_absent(**default_kwargs)
if self.head_node is None:
node = ray.node.Node(
ray_params,
head=True,
shutdown_at_exit=self._shutdown_at_exit,
spawn_reaper=self._shutdown_at_exit)
self.head_node = node
self.redis_address = self.head_node.redis_address
self.redis_password = node_args.get(
"redis_password", ray_constants.REDIS_DEFAULT_PASSWORD)
self.webui_url = self.head_node.webui_url
else:
ray_params.update_if_absent(redis_address=self.redis_address)
# We only need one log monitor per physical node.
ray_params.update_if_absent(include_log_monitor=False)
# Let grpc pick a port.
ray_params.update(node_manager_port=0)
node = ray.node.Node(
ray_params,
head=False,
shutdown_at_exit=self._shutdown_at_exit,
spawn_reaper=self._shutdown_at_exit)
self.worker_nodes.add(node)
# Wait for the node to appear in the client table. We do this so that
# the nodes appears in the client table in the order that the
# corresponding calls to add_node were made. We do this because in the
# tests we assume that the driver is connected to the first node that
# is added.
self._wait_for_node(node)
return node
def remove_node(self, node, allow_graceful=True):
"""Kills all processes associated with worker node.
Args:
node (Node): Worker node of which all associated processes
will be removed.
"""
if self.head_node == node:
self.head_node.kill_all_processes(
check_alive=False, allow_graceful=allow_graceful)
self.head_node = None
# TODO(rliaw): Do we need to kill all worker processes?
else:
node.kill_all_processes(
check_alive=False, allow_graceful=allow_graceful)
self.worker_nodes.remove(node)
assert not node.any_processes_alive(), (
"There are zombie processes left over after killing.")
def _wait_for_node(self, node, timeout=30):
"""Wait until this node has appeared in the client table.
Args:
node (ray.node.Node): The node to wait for.
timeout: The amount of time in seconds to wait before raising an
exception.
Raises:
Exception: An exception is raised if the timeout expires before the
node appears in the client table.
"""
ip_address, port = self.redis_address.split(":")
redis_client = redis.StrictRedis(
host=ip_address, port=int(port), password=self.redis_password)
start_time = time.time()
while time.time() - start_time < timeout:
clients = ray.state._parse_client_table(redis_client)
object_store_socket_names = [
client["ObjectStoreSocketName"] for client in clients
]
if node.plasma_store_socket_name in object_store_socket_names:
return
else:
time.sleep(0.1)
raise Exception("Timed out while waiting for nodes to join.")
def wait_for_nodes(self, timeout=30):
"""Waits for correct number of nodes to be registered.
This will wait until the number of live nodes in the client table
exactly matches the number of "add_node" calls minus the number of
"remove_node" calls that have been made on this cluster. This means
that if a node dies without "remove_node" having been called, this will
raise an exception.
Args:
timeout (float): The number of seconds to wait for nodes to join
before failing.
Raises:
Exception: An exception is raised if we time out while waiting for
nodes to join.
"""
ip_address, port = self.address.split(":")
redis_client = redis.StrictRedis(
host=ip_address, port=int(port), password=self.redis_password)
start_time = time.time()
while time.time() - start_time < timeout:
clients = ray.state._parse_client_table(redis_client)
live_clients = [client for client in clients if client["Alive"]]
expected = len(self.list_all_nodes())
if len(live_clients) == expected:
logger.debug("All nodes registered as expected.")
return
else:
logger.debug(
"{} nodes are currently registered, but we are expecting "
"{}".format(len(live_clients), expected))
time.sleep(0.1)
raise Exception("Timed out while waiting for nodes to join.")
def list_all_nodes(self):
"""Lists all nodes.
TODO(rliaw): What is the desired behavior if a head node
dies before worker nodes die?
Returns:
List of all nodes, including the head node.
"""
nodes = list(self.worker_nodes)
if self.head_node:
nodes = [self.head_node] + nodes
return nodes
def remaining_processes_alive(self):
"""Returns a bool indicating whether all processes are alive or not.
Note that this ignores processes that have been explicitly killed,
e.g., via a command like node.kill_raylet().
Returns:
True if all processes are alive and false otherwise.
"""
return all(
node.remaining_processes_alive() for node in self.list_all_nodes())
def shutdown(self):
"""Removes all nodes."""
# We create a list here as a copy because `remove_node`
# modifies `self.worker_nodes`.
all_nodes = list(self.worker_nodes)
for node in all_nodes:
self.remove_node(node)
if self.head_node is not None:
self.remove_node(self.head_node)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/public/index.html
|
HTML
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Ray Dashboard</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/public/speedscope-1.5.3/demangle-cpp.8a387750.js
|
JavaScript
|
parcelRequire=function(e,r,n,t){var i="function"==typeof parcelRequire&&parcelRequire,o="function"==typeof require&&require;function u(n,t){if(!r[n]){if(!e[n]){var f="function"==typeof parcelRequire&&parcelRequire;if(!t&&f)return f(n,!0);if(i)return i(n,!0);if(o&&"string"==typeof n)return o(n);var c=new Error("Cannot find module '"+n+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[n][1][r]||r};var l=r[n]=new u.Module(n);e[n][0].call(l.exports,p,l,l.exports,this)}return r[n].exports;function p(e){return u(p.resolve(e))}}u.isParcelRequire=!0,u.Module=function(e){this.id=e,this.bundle=u,this.exports={}},u.modules=e,u.cache=r,u.parent=i,u.register=function(r,n){e[r]=[function(e,r){r.exports=n},{}]};for(var f=0;f<n.length;f++)u(n[f]);if(n.length){var c=u(n[n.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=c:"function"==typeof define&&define.amd?define(function(){return c}):t&&(this[t]=c)}return u}({180:[function(require,module,exports) {
"use strict";let e;Object.defineProperty(exports,"__esModule",{value:!0}),exports.demangleCpp=a;const r=new Map;function a(a){if(a.startsWith("__Z")){let v=r.get(a);void 0!==v?a=v:(e||(e=new Function("exports",i)()),v="(null)"===(v=e(a.slice(1)))?a:v,r.set(a,v),a=v)}return a}const i='\nreturn function(){function r(r){eval.call(null,r)}function a(r){throw print(r+":\\n"+(new Error).stack),ke=!0,"Assertion: "+r}function e(r,e){r||a("Assertion failed: "+e)}function i(r,a,i,v){function t(r,a){if("string"==a){var e=Oe;return le.stackAlloc(r.length+1),A(r,e),e}return r}function f(r,a){return"string"==a?s(r):r}try{func=ce.Module["_"+r]}catch(r){}e(func,"Cannot call unknown function "+r+" (perhaps LLVM optimizations or closure removed it?)");var _=0,n=v?v.map(function(r){return t(r,i[_++])}):[];return f(func.apply(null,n),a)}function v(r,a,e){return function(){return i(r,a,e,Array.prototype.slice.call(arguments))}}function t(r,e,i,v){switch(i=i||"i8","*"===i[i.length-1]&&(i="i32"),i){case"i1":Ae[r]=e;break;case"i8":Ae[r]=e;break;case"i16":ye[r>>1]=e;break;case"i32":Se[r>>2]=e;break;case"i64":Se[r>>2]=e;break;case"float":Ce[r>>2]=e;break;case"double":ze[0]=e,Se[r>>2]=xe[0],Se[r+4>>2]=xe[1];break;default:a("invalid type for setValue: "+i)}}function f(r,e,i){switch(e=e||"i8","*"===e[e.length-1]&&(e="i32"),e){case"i1":return Ae[r];case"i8":return Ae[r];case"i16":return ye[r>>1];case"i32":return Se[r>>2];case"i64":return Se[r>>2];case"float":return Ce[r>>2];case"double":return xe[0]=Se[r>>2],xe[1]=Se[r+4>>2],ze[0];default:a("invalid type for setValue: "+e)}return null}function _(r,a,e){var i,v;"number"==typeof r?(i=!0,v=r):(i=!1,v=r.length);var f="string"==typeof a?a:null,_=[Jr,le.stackAlloc,le.staticAlloc][void 0===e?we:e](Math.max(v,f?1:a.length));if(i)return Fa(_,0,v),_;for(var s,n=0;n<v;){var o=r[n];"function"==typeof o&&(o=le.getFunctionIndex(o)),s=f||a[n],0!==s?("i64"==s&&(s="i32"),t(_+n,o,s),n+=le.getNativeTypeSize(s)):n++}return _}function s(r,a){for(var e,i="undefined"==typeof a,v="",t=0,f=String.fromCharCode(0);;){if(e=String.fromCharCode(ge[r+t]),i&&e==f)break;if(v+=e,t+=1,!i&&t==a)break}return v}function n(r){for(var a="",e=0;e<r.length;e++)a+=String.fromCharCode(r[e]);return a}function o(r){return r+4095>>12<<12}function l(){for(;Le<=Ie;)Le=o(2*Le);var r=Ae,a=new ArrayBuffer(Le);Ae=new Int8Array(a),ye=new Int16Array(a),Se=new Int32Array(a),ge=new Uint8Array(a),me=new Uint16Array(a),Me=new Uint32Array(a),Ce=new Float32Array(a),Re=new Float64Array(a),Ae.set(r)}function b(r){for(;r.length>0;){var a=r.shift(),e=a.func;"number"==typeof e&&(e=pe[e]),e(void 0===a.arg?null:a.arg)}}function k(){b(Ve)}function u(){b(Be),be.print()}function c(r,a){return Array.prototype.slice.call(Ae.subarray(r,r+a))}function h(r,a){for(var e=new Uint8Array(a),i=0;i<a;++i)e[i]=Ae[r+i];return e.buffer}function d(r){for(var a=0;Ae[r+a];)a++;return a}function w(r,a){var e=d(r);a&&e++;var i=c(r,e);return a&&(i[e-1]=0),i}function p(r,a){for(var e=[],i=0;i<r.length;){var v=r.charCodeAt(i);v>255&&(v&=255),e.push(v),i+=1}return a||e.push(0),e}function E(r){for(var a=[],e=0;e<r.length;e++){var i=r[e];i>255&&(i&=255),a.push(String.fromCharCode(i))}return a.join("")}function A(r,a,e){for(var i=0;i<r.length;){var v=r.charCodeAt(i);v>255&&(v&=255),Ae[a+i]=v,i+=1}e||(Ae[a+i]=0)}function g(r,a,e,i){return r>=0?r:a<=32?2*Math.abs(1<<a-1)+r:Math.pow(2,a)+r}function y(r,a,e,i){if(r<=0)return r;var v=a<=32?Math.abs(1<<a-1):Math.pow(2,a-1);return r>=v&&(a<=32||r>v)&&(r=-2*v+r),r}function m(r,a,e){if(0==(0|r)|0==(0|a)|0==(0|e))var i=0;else{Se[r>>2]=0,Se[r+4>>2]=a,Se[r+8>>2]=e;var i=1}var i;return i}function S(r,a,e){if(0==(0|r)|(0|a)<0|0==(0|e))var i=0;else{Se[r>>2]=41,Se[r+4>>2]=a,Se[r+8>>2]=e;var i=1}var i;return i}function M(r,a,e){if(0==(0|r)|0==(0|e))var i=0;else{Se[r>>2]=6,Se[r+4>>2]=a,Se[r+8>>2]=e;var i=1}var i;return i}function C(r,a,e){if(0==(0|r)|0==(0|e))var i=0;else{Se[r>>2]=7,Se[r+4>>2]=a,Se[r+8>>2]=e;var i=1}var i;return i}function R(r,a){var e,i=0==(0|a);do if(i)var v=0;else{var e=(r+32|0)>>2,t=Se[e];if((0|t)>=(0|Se[r+36>>2])){var v=0;break}var f=(t<<2)+Se[r+28>>2]|0;Se[f>>2]=a;var _=Se[e]+1|0;Se[e]=_;var v=1}while(0);var v;return v}function T(r,a){var e,e=(r+12|0)>>2,i=Se[e],v=i+1|0;Se[e]=v;var t=Ae[i]<<24>>24==95;do if(t){var f=i+2|0;if(Se[e]=f,Ae[v]<<24>>24!=90){var _=0;break}var s=O(r,a),_=s}else var _=0;while(0);var _;return _}function O(r,a){var e=r+12|0,i=Ae[Se[e>>2]];r:do if(i<<24>>24==71||i<<24>>24==84)var v=Tr(r),t=v;else{var f=Ar(r),_=0==(0|f)|0==(0|a);do if(!_){if(0!=(1&Se[r+8>>2]|0))break;var s=Me[f>>2],n=(s-25|0)>>>0<3;a:do if(n)for(var o=f;;){var o,l=Me[o+4>>2],b=Me[l>>2];if((b-25|0)>>>0>=3){var k=l,u=b;break a}var o=l}else var k=f,u=s;while(0);var u,k;if(2!=(0|u)){var t=k;break r}var c=k+8|0,h=Me[c>>2],d=(Se[h>>2]-25|0)>>>0<3;a:do if(d)for(var w=h;;){var w,p=Me[w+4>>2];if((Se[p>>2]-25|0)>>>0>=3){var E=p;break a}var w=p}else var E=h;while(0);var E;Se[c>>2]=E;var t=k;break r}while(0);var A=Ae[Se[e>>2]];if(A<<24>>24==0||A<<24>>24==69){var t=f;break}var g=Or(f),y=Sr(r,g),m=D(r,3,f,y),t=m}while(0);var t;return t}function N(r){var a,e,i=Oe;Oe+=4;var v=i,e=v>>2,a=(r+12|0)>>2,t=Me[a],f=Ae[t],_=f<<24>>24;r:do if(f<<24>>24==114||f<<24>>24==86||f<<24>>24==75){var s=I(r,v,0);if(0==(0|s)){var n=0;break}var o=N(r);Se[s>>2]=o;var l=Se[e],b=R(r,l);if(0==(0|b)){var n=0;break}var n=Se[e]}else{do{if(97==(0|_)||98==(0|_)||99==(0|_)||100==(0|_)||101==(0|_)||102==(0|_)||103==(0|_)||104==(0|_)||105==(0|_)||106==(0|_)||108==(0|_)||109==(0|_)||110==(0|_)||111==(0|_)||115==(0|_)||116==(0|_)||118==(0|_)||119==(0|_)||120==(0|_)||121==(0|_)||122==(0|_)){var k=ai+20*(_-97)|0,u=P(r,k);Se[e]=u;var c=r+48|0,h=Se[c>>2]+Se[Se[u+4>>2]+4>>2]|0;Se[c>>2]=h;var d=Se[a]+1|0;Se[a]=d;var n=u;break r}if(117==(0|_)){Se[a]=t+1|0;var w=L(r),p=D(r,34,w,0);Se[e]=p;var E=p}else if(70==(0|_)){var A=F(r);Se[e]=A;var E=A}else if(48==(0|_)||49==(0|_)||50==(0|_)||51==(0|_)||52==(0|_)||53==(0|_)||54==(0|_)||55==(0|_)||56==(0|_)||57==(0|_)||78==(0|_)||90==(0|_)){var g=X(r);Se[e]=g;var E=g}else if(65==(0|_)){var y=j(r);Se[e]=y;var E=y}else if(77==(0|_)){var m=U(r);Se[e]=m;var E=m}else if(84==(0|_)){var S=x(r);if(Se[e]=S,Ae[Se[a]]<<24>>24!=73){var E=S;break}var M=R(r,S);if(0==(0|M)){var n=0;break r}var C=Se[e],T=z(r),O=D(r,4,C,T);Se[e]=O;var E=O}else if(83==(0|_)){var B=ge[t+1|0];if((B-48&255&255)<10|B<<24>>24==95|(B-65&255&255)<26){var H=V(r,0);if(Se[e]=H,Ae[Se[a]]<<24>>24!=73){var n=H;break r}var K=z(r),Y=D(r,4,H,K);Se[e]=Y;var E=Y}else{var G=X(r);if(Se[e]=G,0==(0|G)){var E=0;break}if(21==(0|Se[G>>2])){var n=G;break r}var E=G}}else if(80==(0|_)){Se[a]=t+1|0;var W=N(r),Z=D(r,29,W,0);Se[e]=Z;var E=Z}else if(82==(0|_)){Se[a]=t+1|0;var Q=N(r),q=D(r,30,Q,0);Se[e]=q;var E=q}else if(67==(0|_)){Se[a]=t+1|0;var $=N(r),J=D(r,31,$,0);Se[e]=J;var E=J}else if(71==(0|_)){Se[a]=t+1|0;var rr=N(r),ar=D(r,32,rr,0);Se[e]=ar;var E=ar}else{if(85!=(0|_)){var n=0;break r}Se[a]=t+1|0;var er=L(r);Se[e]=er;var ir=N(r),vr=Se[e],tr=D(r,28,ir,vr);Se[e]=tr;var E=tr}}while(0);var E,fr=R(r,E);if(0==(0|fr)){var n=0;break}var n=Se[e]}while(0);var n;return Oe=i,n}function I(r,a,e){for(var i,v=r+12|0,t=0!=(0|e),f=t?25:22,i=(r+48|0)>>2,_=t?26:23,s=t?27:24,n=a;;){var n,o=Se[v>>2],l=Ae[o];if(l<<24>>24!=114&&l<<24>>24!=86&&l<<24>>24!=75){var b=n;break}var k=o+1|0;if(Se[v>>2]=k,l<<24>>24==114){var u=Se[i]+9|0;Se[i]=u;var c=f}else if(l<<24>>24==86){var h=Se[i]+9|0;Se[i]=h;var c=_}else{var d=Se[i]+6|0;Se[i]=d;var c=s}var c,w=D(r,c,0,0);if(Se[n>>2]=w,0==(0|w)){var b=0;break}var n=w+4|0}var b;return b}function P(r,a){var e=0==(0|a);do if(e)var i=0;else{var v=J(r);if(0==(0|v)){var i=0;break}Se[v>>2]=33,Se[v+4>>2]=a;var i=v}while(0);var i;return i}function D(r,a,e,i){var v,t;do{if(1==(0|a)||2==(0|a)||3==(0|a)||4==(0|a)||10==(0|a)||28==(0|a)||37==(0|a)||43==(0|a)||44==(0|a)||45==(0|a)||46==(0|a)||47==(0|a)||48==(0|a)||49==(0|a)||50==(0|a)){if(0==(0|e)|0==(0|i)){var f=0;t=7;break}t=5;break}if(8==(0|a)||9==(0|a)||11==(0|a)||12==(0|a)||13==(0|a)||14==(0|a)||15==(0|a)||16==(0|a)||17==(0|a)||18==(0|a)||19==(0|a)||20==(0|a)||29==(0|a)||30==(0|a)||31==(0|a)||32==(0|a)||34==(0|a)||38==(0|a)||39==(0|a)||42==(0|a)){if(0==(0|e)){var f=0;t=7;break}t=5;break}if(36==(0|a)){if(0==(0|i)){var f=0;t=7;break}t=5;break}if(35==(0|a)||22==(0|a)||23==(0|a)||24==(0|a)||25==(0|a)||26==(0|a)||27==(0|a))t=5;else{var f=0;t=7}}while(0);do if(5==t){var _=J(r),v=_>>2;if(0==(0|_)){var f=0;break}Se[v]=a,Se[v+1]=e,Se[v+2]=i;var f=_}while(0);var f;return f}function L(r){var a=sr(r);if((0|a)<1)var e=0;else{var i=Rr(r,a);Se[r+44>>2]=i;var e=i}var e;return e}function F(r){var a,a=(r+12|0)>>2,e=Se[a],i=e+1|0;if(Se[a]=i,Ae[e]<<24>>24==70){if(Ae[i]<<24>>24==89){var v=e+2|0;Se[a]=v}var t=Sr(r,1),f=Se[a],_=f+1|0;Se[a]=_;var s=Ae[f]<<24>>24==69?t:0,n=s}else var n=0;var n;return n}function X(r){var a=Ar(r);return a}function j(r){var a,a=(r+12|0)>>2,e=Se[a],i=e+1|0;Se[a]=i;var v=Ae[e]<<24>>24==65;do if(v){var t=Ae[i];if(t<<24>>24==95)var f=0;else if((t-48&255&255)<10){for(var _=i;;){var _,s=_+1|0;if(Se[a]=s,(Ae[s]-48&255&255)>=10)break;var _=s}var n=s-i|0,o=lr(r,i,n);if(0==(0|o)){var l=0;break}var f=o}else{var b=nr(r);if(0==(0|b)){var l=0;break}var f=b}var f,k=Se[a],u=k+1|0;if(Se[a]=u,Ae[k]<<24>>24!=95){var l=0;break}var c=N(r),h=D(r,36,f,c),l=h}else var l=0;while(0);var l;return l}function U(r){var a=Oe;Oe+=4;var e=a,i=r+12|0,v=Se[i>>2],t=v+1|0;Se[i>>2]=t;var f=Ae[v]<<24>>24==77;r:do if(f){var _=N(r),s=I(r,e,1);if(0==(0|s)){var n=0;break}var o=N(r);Se[s>>2]=o;var l=(0|s)==(0|e);do if(!l){if(35==(0|Se[o>>2]))break;var b=Se[e>>2],k=R(r,b);if(0==(0|k)){var n=0;break r}}while(0);var u=Se[e>>2],c=D(r,37,_,u),n=c}else var n=0;while(0);var n;return Oe=a,n}function x(r){var a,a=(r+12|0)>>2,e=Se[a],i=e+1|0;Se[a]=i;var v=Ae[e]<<24>>24==84;do if(v){if(Ae[i]<<24>>24==95)var t=0,f=i;else{var _=sr(r);if((0|_)<0){var s=0;break}var t=_+1|0,f=Se[a]}var f,t;if(Se[a]=f+1|0,Ae[f]<<24>>24!=95){var s=0;break}var n=r+40|0,o=Se[n>>2]+1|0;Se[n>>2]=o;var l=Er(r,t),s=l}else var s=0;while(0);var s;return s}function z(r){var a,e=Oe;Oe+=4;var i=e,v=r+44|0,t=Se[v>>2],a=(r+12|0)>>2,f=Se[a],_=f+1|0;Se[a]=_;var s=Ae[f]<<24>>24==73;r:do if(s){Se[i>>2]=0;for(var n=i;;){var n,o=_r(r);if(0==(0|o)){var l=0;break r}var b=D(r,39,o,0);if(Se[n>>2]=b,0==(0|b)){var l=0;break r}var k=Se[a];if(Ae[k]<<24>>24==69)break;var n=b+8|0}var u=k+1|0;Se[a]=u,Se[v>>2]=t;var l=Se[i>>2]}else var l=0;while(0);var l;return Oe=e,l}function V(r,a){var e,e=(r+12|0)>>2,i=Se[e],v=i+1|0;Se[e]=v;var t=Ae[i]<<24>>24==83;r:do if(t){var f=i+2|0;Se[e]=f;var _=ge[v];if(_<<24>>24==95)var s=0;else{if(!((_-48&255&255)<10|(_-65&255&255)<26)){var n=8&Se[r+8>>2],o=n>>>3,l=0!=(0|n)|0==(0|a);do if(l)var b=o;else{if((Ae[f]-67&255&255)>=2){var b=o;break}var b=1}while(0);for(var b,k=0|ei;;){var k;if(k>>>0>=(ei+196|0)>>>0){var u=0;break r}if(_<<24>>24==Ae[0|k]<<24>>24)break;var k=k+28|0}var c=Se[k+20>>2];if(0!=(0|c)){var h=Se[k+24>>2],d=fr(r,c,h);Se[r+44>>2]=d}if(0==(0|b))var w=k+8|0,p=k+4|0;else var w=k+16|0,p=k+12|0;var p,w,E=Se[w>>2],A=Se[p>>2],g=r+48|0,y=Se[g>>2]+E|0;Se[g>>2]=y;var m=fr(r,A,E),u=m;break}for(var S=_,M=0,C=f;;){var C,M,S;if((S-48&255&255)<10)var R=36*M-48|0;else{if((S-65&255&255)>=26){var u=0;break r}var R=36*M-55|0}var R,T=(S<<24>>24)+R|0;if((0|T)<0){var u=0;break r}var O=C+1|0;Se[e]=O;var N=ge[C];if(N<<24>>24==95)break;var S=N,M=T,C=O}var s=T+1|0}var s;if((0|s)>=(0|Se[r+32>>2])){var u=0;break}var I=r+40|0,P=Se[I>>2]+1|0;Se[I>>2]=P;var u=Se[Se[r+28>>2]+(s<<2)>>2]}else var u=0;while(0);var u;return u}function B(r,a,e,i){var v,t,f,_,s=Oe;Oe+=28;var n,o=s,_=o>>2;Se[_]=r;var l=e+1|0,f=(o+12|0)>>2;Se[f]=l;var b=Jr(l),t=(o+4|0)>>2;if(Se[t]=b,0==(0|b))var k=0,u=1;else{var v=(o+8|0)>>2;Se[v]=0,Se[_+4]=0,Se[_+5]=0;var c=o+24|0;Se[c>>2]=0,H(o,a);var h=Me[t],d=0==(0|h);do{if(!d){var w=Me[v];if(w>>>0>=Me[f]>>>0){n=5;break}Se[v]=w+1|0,Ae[h+w|0]=0,n=6;break}n=5}while(0);5==n&&Y(o,0);var p=Se[t],E=0==(0|p)?Se[c>>2]:Se[f],k=p,u=E}var u,k;return Se[i>>2]=u,Oe=s,k}function H(r,a){var e,i,v,t,f,_,s,n,o,l,b,k,u,c,h,d,w,p,E,A,g,y,m,S,M,C,R,T,O,N,I,P,D,L,F,X,j,U,x,z,V,B,K,G,W,J,vr,tr,fr,_r,sr,nr,or,lr,br,kr,ur,cr,hr,dr,wr,pr=a>>2,Er=r>>2,Ar=Oe;Oe+=184;var gr,yr=Ar,wr=yr>>2,mr=Ar+64,dr=mr>>2,Sr=Ar+72,Mr=Ar+88,Cr=Ar+104,hr=Cr>>2,Rr=Ar+168,Tr=0==(0|a);r:do if(Tr)Z(r);else{var cr=(r+4|0)>>2,Or=Me[cr];if(0==(0|Or))break;var Nr=0|a,Ir=Me[Nr>>2];a:do{if(0==(0|Ir)){if(0!=(4&Se[Er]|0)){var Pr=Se[pr+1],Dr=Se[pr+2];q(r,Pr,Dr);break r}var ur=(r+8|0)>>2,Lr=Me[ur],Fr=a+8|0,Xr=Me[Fr>>2];if((Xr+Lr|0)>>>0>Me[Er+3]>>>0){var jr=Se[pr+1];Q(r,jr,Xr);break r}var Ur=Or+Lr|0,xr=Se[pr+1];Pa(Ur,xr,Xr,1);var zr=Se[ur]+Se[Fr>>2]|0;Se[ur]=zr;break r}if(1==(0|Ir)||2==(0|Ir)){var Vr=Se[pr+1];H(r,Vr);var Br=0==(4&Se[Er]|0),Hr=Me[cr],Kr=0!=(0|Hr);e:do if(Br){do if(Kr){var kr=(r+8|0)>>2,Yr=Me[kr];if((Yr+2|0)>>>0>Me[Er+3]>>>0)break;var Gr=Hr+Yr|0;oe=14906,Ae[Gr]=255&oe,oe>>=8,Ae[Gr+1]=255&oe;var Wr=Se[kr]+2|0;Se[kr]=Wr;break e}while(0);Q(r,0|He.__str120,2)}else{do if(Kr){var Zr=r+8|0,Qr=Me[Zr>>2];if(Qr>>>0>=Me[Er+3]>>>0)break;Se[Zr>>2]=Qr+1|0,Ae[Hr+Qr|0]=46;break e}while(0);Y(r,46)}while(0);var qr=Se[pr+2];H(r,qr);break r}if(3==(0|Ir)){for(var br=(r+20|0)>>2,$r=Me[br],lr=(r+16|0)>>2,Jr=a,ra=0,aa=$r;;){var aa,ra,Jr,ea=Me[Jr+4>>2];if(0==(0|ea)){var ia=ra,va=0;gr=33;break}if(ra>>>0>3){Z(r);break r}var ta=(ra<<4)+yr|0;Se[ta>>2]=aa,Se[br]=ta,Se[((ra<<4)+4>>2)+wr]=ea,Se[((ra<<4)+8>>2)+wr]=0;var fa=Me[lr];Se[((ra<<4)+12>>2)+wr]=fa;var _a=ra+1|0,sa=0|ea,na=Me[sa>>2];if((na-25|0)>>>0>=3){gr=25;break}var Jr=ea,ra=_a,aa=ta}e:do if(25==gr){if(4==(0|na)){Se[dr]=fa,Se[lr]=mr,Se[dr+1]=ea;var oa=Se[sa>>2],la=mr}else var oa=na,la=fa;var la,oa;if(2!=(0|oa)){var ia=_a,va=sa;break}for(var ba=_a,ka=ea+8|0;;){var ka,ba,ua=Me[ka>>2];if((Se[ua>>2]-25|0)>>>0>=3){var ia=ba,va=sa;break e}if(ba>>>0>3)break;var ca=(ba<<4)+yr|0,ha=ba-1|0,da=(ha<<4)+yr|0,or=ca>>2,nr=da>>2;Se[or]=Se[nr],Se[or+1]=Se[nr+1],Se[or+2]=Se[nr+2],Se[or+3]=Se[nr+3],Se[ca>>2]=da,Se[br]=ca,Se[((ha<<4)+4>>2)+wr]=ua,Se[((ha<<4)+8>>2)+wr]=0,Se[((ha<<4)+12>>2)+wr]=la;var ba=ba+1|0,ka=ua+4|0}Z(r);break r}while(0);var va,ia,wa=Se[pr+2];if(H(r,wa),4==(0|Se[va>>2])){var pa=Se[dr];Se[lr]=pa}var Ea=0==(0|ia);e:do if(!Ea)for(var Aa=r+8|0,ga=r+12|0,ya=ia;;){var ya,ma=ya-1|0;if(0==(0|Se[((ma<<4)+8>>2)+wr])){var Sa=Me[cr],Ma=0==(0|Sa);do{if(!Ma){var Ca=Me[Aa>>2];if(Ca>>>0>=Me[ga>>2]>>>0){gr=41;break}Se[Aa>>2]=Ca+1|0,Ae[Sa+Ca|0]=32,gr=42;break}gr=41}while(0);41==gr&&Y(r,32);var Ra=Se[((ma<<4)+4>>2)+wr];$(r,Ra)}if(0==(0|ma))break e;var ya=ma}while(0);Se[br]=$r;break r}if(4==(0|Ir)){var sr=(r+20|0)>>2,Ta=Se[sr];Se[sr]=0;var Oa=Se[pr+1];H(r,Oa);var Na=Me[cr],Ia=0==(0|Na);do{if(!Ia){var _r=(r+8|0)>>2,Da=Me[_r],La=0==(0|Da);do if(!La){if(Ae[Na+(Da-1)|0]<<24>>24!=60)break;Da>>>0<Me[Er+3]>>>0?(Se[_r]=Da+1|0,Ae[Na+Da|0]=32):Y(r,32)}while(0);var Fa=Me[cr];if(0==(0|Fa)){gr=54;break}var Xa=Me[_r];if(Xa>>>0>=Me[Er+3]>>>0){gr=54;break}Se[_r]=Xa+1|0,Ae[Fa+Xa|0]=60,gr=55;break}gr=54}while(0);54==gr&&Y(r,60);var ja=Se[pr+2];H(r,ja);var Ua=Me[cr],xa=0==(0|Ua);do{if(!xa){var fr=(r+8|0)>>2,za=Me[fr],Va=0==(0|za);do if(!Va){if(Ae[Ua+(za-1)|0]<<24>>24!=62)break;za>>>0<Me[Er+3]>>>0?(Se[fr]=za+1|0,Ae[Ua+za|0]=32):Y(r,32)}while(0);var Ba=Me[cr];if(0==(0|Ba)){gr=64;break}var Ha=Me[fr];if(Ha>>>0>=Me[Er+3]>>>0){gr=64;break}Se[fr]=Ha+1|0,Ae[Ba+Ha|0]=62,gr=65;break}gr=64}while(0);64==gr&&Y(r,62),Se[sr]=Ta;break r}if(5==(0|Ir)){var tr=(r+16|0)>>2,Ka=Me[tr];if(0==(0|Ka)){Z(r);break r}for(var Ya=Se[pr+1],Ga=Se[Ka+4>>2];;){var Ga,Ya,Wa=Se[Ga+8>>2];if(0==(0|Wa))break;if(39!=(0|Se[Wa>>2])){Z(r);break r}if((0|Ya)<1){if(0!=(0|Ya))break;var Za=Se[Ka>>2];Se[tr]=Za;var Qa=Se[Wa+4>>2];H(r,Qa),Se[tr]=Ka;break r}var Ya=Ya-1|0,Ga=Wa}Z(r);break r}if(6==(0|Ir)){var qa=Se[pr+2];H(r,qa);break r}if(7==(0|Ir)){var $a=r+8|0,Ja=Me[$a>>2];Ja>>>0<Me[Er+3]>>>0?(Se[$a>>2]=Ja+1|0,Ae[Or+Ja|0]=126):Y(r,126);var re=Se[pr+2];H(r,re);break r}if(8==(0|Ir)){var vr=(r+8|0)>>2,ae=Me[vr];if((ae+11|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str121,11);else{for(var ee=Or+ae|0,ie=0|He.__str121,ve=ee,te=ie+11;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var fe=Se[vr]+11|0;Se[vr]=fe}var _e=Se[pr+1];H(r,_e);break r}if(9==(0|Ir)){var J=(r+8|0)>>2,se=Me[J];if((se+8|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str122,8);else{var ne=Or+se|0,le=0|ne;oe=542397526,Ae[le]=255&oe,oe>>=8,Ae[le+1]=255&oe,oe>>=8,Ae[le+2]=255&oe,oe>>=8,Ae[le+3]=255&oe;var be=ne+4|0;oe=544370534,Ae[be]=255&oe,oe>>=8,Ae[be+1]=255&oe,oe>>=8,Ae[be+2]=255&oe,oe>>=8,Ae[be+3]=255&oe;var ke=Se[J]+8|0;Se[J]=ke}var ue=Se[pr+1];H(r,ue);break r}if(10==(0|Ir)){var W=(r+8|0)>>2,ce=Me[W],he=r+12|0;if((ce+24|0)>>>0>Me[he>>2]>>>0)Q(r,0|He.__str123,24);else{var de=Or+ce|0;Pa(de,0|He.__str123,24,1);var we=Se[W]+24|0;Se[W]=we}var pe=Se[pr+1];H(r,pe);var Ee=Me[cr],ge=0==(0|Ee);do{if(!ge){var ye=Me[W];if((ye+4|0)>>>0>Me[he>>2]>>>0){gr=96;break}var me=Ee+ye|0;oe=762210605,Ae[me]=255&oe,oe>>=8,Ae[me+1]=255&oe,oe>>=8,Ae[me+2]=255&oe,oe>>=8,Ae[me+3]=255&oe;var Ce=Se[W]+4|0;Se[W]=Ce,gr=97;break}gr=96}while(0);96==gr&&Q(r,0|He.__str124,4);var Re=Se[pr+2];H(r,Re);break r}if(11==(0|Ir)){var G=(r+8|0)>>2,Te=Me[G];if((Te+13|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str125,13);else{for(var Ne=Or+Te|0,ie=0|He.__str125,ve=Ne,te=ie+13;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var Ie=Se[G]+13|0;Se[G]=Ie}var Pe=Se[pr+1];H(r,Pe);break r}if(12==(0|Ir)){var K=(r+8|0)>>2,De=Me[K];if((De+18|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str126,18);else{for(var Le=Or+De|0,ie=0|He.__str126,ve=Le,te=ie+18;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var Fe=Se[K]+18|0;Se[K]=Fe}var Xe=Se[pr+1];H(r,Xe);break r}if(13==(0|Ir)){var B=(r+8|0)>>2,je=Me[B];if((je+16|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str127,16);else{for(var Ue=Or+je|0,ie=0|He.__str127,ve=Ue,te=ie+16;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var xe=Se[B]+16|0;Se[B]=xe}var ze=Se[pr+1];H(r,ze);break r}if(14==(0|Ir)){var V=(r+8|0)>>2,Ve=Me[V];if((Ve+21|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str128,21);else{var Be=Or+Ve|0;Pa(Be,0|He.__str128,21,1);var Ke=Se[V]+21|0;Se[V]=Ke}var Ye=Se[pr+1];H(r,Ye);break r}if(15==(0|Ir)){var z=(r+8|0)>>2,Ge=Me[z];if((Ge+17|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str129,17);else{for(var We=Or+Ge|0,ie=0|He.__str129,ve=We,te=ie+17;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var Ze=Se[z]+17|0;Se[z]=Ze}var Qe=Se[pr+1];H(r,Qe);break r}if(16==(0|Ir)){var x=(r+8|0)>>2,qe=Me[x];if((qe+26|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str130,26);else{var $e=Or+qe|0;Pa($e,0|He.__str130,26,1);var Je=Se[x]+26|0;Se[x]=Je}var ri=Se[pr+1];H(r,ri);break r}if(17==(0|Ir)){var U=(r+8|0)>>2,ai=Me[U];if((ai+15|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str131,15);else{for(var ei=Or+ai|0,ie=0|He.__str131,ve=ei,te=ie+15;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var ii=Se[U]+15|0;Se[U]=ii}var vi=Se[pr+1];H(r,vi);break r}if(18==(0|Ir)){var j=(r+8|0)>>2,ti=Me[j];if((ti+19|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str132,19);else{for(var fi=Or+ti|0,ie=0|He.__str132,ve=fi,te=ie+19;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var _i=Se[j]+19|0;Se[j]=_i}var si=Se[pr+1];H(r,si);break r}if(19==(0|Ir)){var X=(r+8|0)>>2,ni=Me[X];if((ni+24|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str133,24);else{var oi=Or+ni|0;Pa(oi,0|He.__str133,24,1);var li=Se[X]+24|0;Se[X]=li}var bi=Se[pr+1];H(r,bi);break r}if(20==(0|Ir)){var F=(r+8|0)>>2,ki=Me[F];if((ki+17|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str134,17);else{for(var ui=Or+ki|0,ie=0|He.__str134,ve=ui,te=ie+17;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var ci=Se[F]+17|0;Se[F]=ci}var hi=Se[pr+1];H(r,hi);break r}if(21==(0|Ir)){var L=(r+8|0)>>2,di=Me[L],wi=a+8|0,pi=Me[wi>>2];if((pi+di|0)>>>0>Me[Er+3]>>>0){var Ei=Se[pr+1];Q(r,Ei,pi);break r}var Ai=Or+di|0,gi=Se[pr+1];Pa(Ai,gi,pi,1);var yi=Se[L]+Se[wi>>2]|0;Se[L]=yi;break r}if(22==(0|Ir)||23==(0|Ir)||24==(0|Ir)){for(var mi=r+20|0;;){var mi,Si=Me[mi>>2];if(0==(0|Si))break a;if(0==(0|Se[Si+8>>2])){var Mi=Me[Se[Si+4>>2]>>2];if((Mi-22|0)>>>0>=3)break a;if((0|Mi)==(0|Ir))break}var mi=0|Si}var Ci=Se[pr+1];H(r,Ci);break r}if(25!=(0|Ir)&&26!=(0|Ir)&&27!=(0|Ir)&&28!=(0|Ir)&&29!=(0|Ir)&&30!=(0|Ir)&&31!=(0|Ir)&&32!=(0|Ir)){if(33==(0|Ir)){var D=(r+8|0)>>2,Ri=Me[D],P=(a+4|0)>>2,I=Me[P]>>2;if(0==(4&Se[Er]|0)){var Ti=Me[I+1];if((Ti+Ri|0)>>>0>Me[Er+3]>>>0){var Oi=Se[I];Q(r,Oi,Ti);break r}var Ni=Or+Ri|0,Ii=Se[I];Pa(Ni,Ii,Ti,1);var Pi=Se[D]+Se[Se[P]+4>>2]|0;Se[D]=Pi;break r}var Di=Me[I+3];if((Di+Ri|0)>>>0>Me[Er+3]>>>0){var Li=Se[I+2];Q(r,Li,Di);break r}var Fi=Or+Ri|0,Xi=Se[I+2];Pa(Fi,Xi,Di,1);var ji=Se[D]+Se[Se[P]+12>>2]|0;Se[D]=ji;break r}if(34==(0|Ir)){var Ui=Se[pr+1];H(r,Ui);break r}if(35==(0|Ir)){var N=(0|r)>>2;if(0!=(32&Se[N]|0)){var xi=Se[Er+5];rr(r,a,xi)}var zi=a+4|0,Vi=0==(0|Se[zi>>2]);e:do if(!Vi){var O=(r+20|0)>>2,Bi=Se[O],Hi=0|Mr;Se[Hi>>2]=Bi,Se[O]=Mr,Se[Mr+4>>2]=a;var Ki=Mr+8|0;Se[Ki>>2]=0;var Yi=Se[Er+4];Se[Mr+12>>2]=Yi;var Gi=Se[zi>>2];H(r,Gi);var Wi=Se[Hi>>2];if(Se[O]=Wi,0!=(0|Se[Ki>>2]))break r;if(0!=(32&Se[N]|0))break;var Zi=Me[cr],Qi=0==(0|Zi);do if(!Qi){var qi=r+8|0,$i=Me[qi>>2];if($i>>>0>=Me[Er+3]>>>0)break;Se[qi>>2]=$i+1|0,Ae[Zi+$i|0]=32;break e}while(0);Y(r,32)}while(0);if(0!=(32&Se[N]|0))break r;var Ji=Se[Er+5];rr(r,a,Ji);break r}if(36==(0|Ir)){var T=(r+20|0)>>2,rv=Me[T],av=0|Cr;Se[hr]=rv,Se[T]=av,Se[hr+1]=a;var ev=Cr+8|0;Se[ev>>2]=0;var iv=Se[Er+4];Se[hr+3]=iv;for(var vv=rv,tv=1;;){var tv,vv;if(0==(0|vv))break;if((Se[Se[vv+4>>2]>>2]-22|0)>>>0>=3)break;var fv=vv+8|0;if(0==(0|Se[fv>>2])){if(tv>>>0>3){Z(r);break r}var _v=(tv<<4)+Cr|0,R=_v>>2,C=vv>>2;Se[R]=Se[C],Se[R+1]=Se[C+1],Se[R+2]=Se[C+2],Se[R+3]=Se[C+3];var sv=Se[T];Se[_v>>2]=sv,Se[T]=_v,Se[fv>>2]=1;var nv=tv+1|0}else var nv=tv;var nv,vv=Se[vv>>2],tv=nv}var ov=Se[pr+2];if(H(r,ov),Se[T]=rv,0!=(0|Se[ev>>2]))break r;if(tv>>>0>1){for(var lv=tv;;){var lv,bv=lv-1|0,kv=Se[((bv<<4)+4>>2)+hr];if($(r,kv),bv>>>0<=1)break;var lv=bv}var uv=Se[T]}else var uv=rv;var uv;ar(r,a,uv);break r}if(37==(0|Ir)){var M=(r+20|0)>>2,cv=Se[M],hv=0|Rr;Se[hv>>2]=cv,Se[M]=Rr,Se[Rr+4>>2]=a;var dv=Rr+8|0;Se[dv>>2]=0;var wv=Se[Er+4];Se[Rr+12>>2]=wv;var pv=a+4|0,Ev=Se[pr+2];H(r,Ev);var Av=0==(0|Se[dv>>2]);e:do if(Av){var gv=Me[cr],yv=0==(0|gv);do{if(!yv){var mv=r+8|0,Sv=Me[mv>>2];if(Sv>>>0>=Me[Er+3]>>>0){gr=187;break}Se[mv>>2]=Sv+1|0,Ae[gv+Sv|0]=32,gr=188;break}gr=187}while(0);187==gr&&Y(r,32);var Mv=Se[pv>>2];H(r,Mv);var Cv=Me[cr],Rv=0==(0|Cv);do if(!Rv){var S=(r+8|0)>>2,Tv=Me[S];if((Tv+3|0)>>>0>Me[Er+3]>>>0)break;var Ov=Cv+Tv|0;Ae[Ov]=Ae[0|He.__str135],Ae[Ov+1]=Ae[(0|He.__str135)+1],Ae[Ov+2]=Ae[(0|He.__str135)+2];var Nv=Se[S]+3|0;Se[S]=Nv;break e}while(0);Q(r,0|He.__str135,3)}while(0);var Iv=Se[hv>>2];Se[M]=Iv;break r}if(38==(0|Ir)||39==(0|Ir)){var Pv=Se[pr+1];H(r,Pv);var Dv=a+8|0;if(0==(0|Se[Dv>>2]))break r;var Lv=Me[cr],Fv=0==(0|Lv);do{if(!Fv){var m=(r+8|0)>>2,Xv=Me[m];if((Xv+2|0)>>>0>Me[Er+3]>>>0){gr=197;break}var jv=Lv+Xv|0;oe=8236,Ae[jv]=255&oe,oe>>=8,Ae[jv+1]=255&oe;var Uv=Se[m]+2|0;Se[m]=Uv,gr=198;break}gr=197}while(0);197==gr&&Q(r,0|He.__str136,2);var xv=Se[Dv>>2];H(r,xv);break r}if(40==(0|Ir)){var y=(r+8|0)>>2,zv=Me[y],g=(r+12|0)>>2;if((zv+8|0)>>>0>Me[g]>>>0)Q(r,0|He.__str137,8);else{var Vv=Or+zv|0,le=0|Vv;oe=1919250543,Ae[le]=255&oe,oe>>=8,Ae[le+1]=255&oe,oe>>=8,Ae[le+2]=255&oe,oe>>=8,Ae[le+3]=255&oe;var be=Vv+4|0;oe=1919906913,Ae[be]=255&oe,oe>>=8,Ae[be+1]=255&oe,oe>>=8,Ae[be+2]=255&oe,oe>>=8,Ae[be+3]=255&oe;var Bv=Se[y]+8|0;Se[y]=Bv}var A=(a+4|0)>>2,Hv=(Ae[Se[Se[A]+4>>2]]-97&255&255)<26;e:do if(Hv){var Kv=Me[cr],Yv=0==(0|Kv);do if(!Yv){var Gv=Me[y];if(Gv>>>0>=Me[g]>>>0)break;Se[y]=Gv+1|0,Ae[Kv+Gv|0]=32;break e}while(0);Y(r,32)}while(0);var Wv=Me[cr],Zv=0==(0|Wv);do{if(!Zv){var Qv=Me[y],qv=Me[A],$v=Me[qv+8>>2];if(($v+Qv|0)>>>0>Me[g]>>>0){var Jv=qv,rt=$v;break}var at=Wv+Qv|0,et=Se[qv+4>>2];Pa(at,et,$v,1);var it=Se[y]+Se[Se[A]+8>>2]|0;Se[y]=it;break r}var vt=Me[A],Jv=vt,rt=Se[vt+8>>2]}while(0);var rt,Jv,tt=Se[Jv+4>>2];Q(r,tt,rt);break r}if(41==(0|Ir)){var E=(r+8|0)>>2,ft=Me[E];if((ft+9|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str10180,9);else{for(var _t=Or+ft|0,ie=0|He.__str10180,ve=_t,te=ie+9;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var st=Se[E]+9|0;Se[E]=st}var nt=Se[pr+2];H(r,nt);break r}if(42==(0|Ir)){var p=(r+8|0)>>2,ot=Me[p];if((ot+9|0)>>>0>Me[Er+3]>>>0)Q(r,0|He.__str10180,9);else{for(var lt=Or+ot|0,ie=0|He.__str10180,ve=lt,te=ie+9;ie<te;ie++,ve++)Ae[ve]=Ae[ie];var bt=Se[p]+9|0;Se[p]=bt}er(r,a);break r}if(43==(0|Ir)){var kt=a+4|0,ut=Se[kt>>2],ct=42==(0|Se[ut>>2]);e:do if(ct){var w=(r+8|0)>>2,ht=Me[w],dt=r+12|0;ht>>>0<Me[dt>>2]>>>0?(Se[w]=ht+1|0,Ae[Or+ht|0]=40):Y(r,40);var wt=Se[kt>>2];er(r,wt);var pt=Me[cr],Et=0==(0|pt);do if(!Et){var At=Me[w];if(At>>>0>=Me[dt>>2]>>>0)break;Se[w]=At+1|0,Ae[pt+At|0]=41;break e}while(0);Y(r,41)}else ir(r,ut);while(0);var gt=Me[cr],yt=0==(0|gt);do{if(!yt){var mt=r+8|0,St=Me[mt>>2];if(St>>>0>=Me[Er+3]>>>0){gr=232;break}Se[mt>>2]=St+1|0,Ae[gt+St|0]=40,gr=233;break}gr=232}while(0);232==gr&&Y(r,40);var Mt=Se[pr+2];H(r,Mt);var Ct=Me[cr],Rt=0==(0|Ct);do if(!Rt){var Tt=r+8|0,Ot=Me[Tt>>2];if(Ot>>>0>=Me[Er+3]>>>0)break;Se[Tt>>2]=Ot+1|0,Ae[Ct+Ot|0]=41;break r}while(0);Y(r,41);break r}if(44==(0|Ir)){var d=(a+8|0)>>2;if(45==(0|Se[Se[d]>>2])){var h=(a+4|0)>>2,Nt=Se[h],It=40==(0|Se[Nt>>2]);do if(It){var Pt=Se[Nt+4>>2];if(1!=(0|Se[Pt+8>>2]))break;if(Ae[Se[Pt+4>>2]]<<24>>24!=62)break;var Dt=r+8|0,Lt=Me[Dt>>2];Lt>>>0<Me[Er+3]>>>0?(Se[Dt>>2]=Lt+1|0,Ae[Or+Lt|0]=40):Y(r,40)}while(0);var Ft=Me[cr],Xt=0==(0|Ft);do{if(!Xt){var jt=r+8|0,Ut=Me[jt>>2];if(Ut>>>0>=Me[Er+3]>>>0){gr=248;break}Se[jt>>2]=Ut+1|0,Ae[Ft+Ut|0]=40,gr=249;break}gr=248}while(0);248==gr&&Y(r,40);var xt=Se[Se[d]+4>>2];H(r,xt);var zt=Me[cr],Vt=0==(0|zt);do{if(!Vt){var c=(r+8|0)>>2,Bt=Me[c];if((Bt+2|0)>>>0>Me[Er+3]>>>0){gr=252;break}var Ht=zt+Bt|0;oe=8233,Ae[Ht]=255&oe,oe>>=8,Ae[Ht+1]=255&oe;var Kt=Se[c]+2|0;Se[c]=Kt,gr=253;break}gr=252}while(0);252==gr&&Q(r,0|He.__str139,2);var Yt=Se[h];ir(r,Yt);var Gt=Me[cr],Wt=0==(0|Gt);do{if(!Wt){var u=(r+8|0)>>2,Zt=Me[u];if((Zt+2|0)>>>0>Me[Er+3]>>>0){gr=256;break}var Qt=Gt+Zt|0;oe=10272,Ae[Qt]=255&oe,oe>>=8,Ae[Qt+1]=255&oe;var qt=Se[u]+2|0;Se[u]=qt,gr=257;break}gr=256}while(0);256==gr&&Q(r,0|He.__str140,2);var $t=Se[Se[d]+8>>2];H(r,$t);var Jt=Me[cr],rf=0==(0|Jt);do{if(!rf){var af=r+8|0,ef=Me[af>>2];if(ef>>>0>=Me[Er+3]>>>0){gr=260;break}Se[af>>2]=ef+1|0,Ae[Jt+ef|0]=41,gr=261;break}gr=260}while(0);260==gr&&Y(r,41);var vf=Se[h];if(40!=(0|Se[vf>>2]))break r;var tf=Se[vf+4>>2];if(1!=(0|Se[tf+8>>2]))break r;if(Ae[Se[tf+4>>2]]<<24>>24!=62)break r;var ff=Me[cr],_f=0==(0|ff);do if(!_f){var sf=r+8|0,nf=Me[sf>>2];if(nf>>>0>=Me[Er+3]>>>0)break;Se[sf>>2]=nf+1|0,Ae[ff+nf|0]=41;break r}while(0);Y(r,41);break r}Z(r);break r}if(45==(0|Ir)){Z(r);break r}if(46==(0|Ir)){var of=a+4|0,k=(a+8|0)>>2,lf=Se[k],bf=47==(0|Se[lf>>2]);do if(bf){if(48!=(0|Se[Se[lf+8>>2]>>2]))break;var b=(r+8|0)>>2,kf=Me[b],l=(r+12|0)>>2;kf>>>0<Me[l]>>>0?(Se[b]=kf+1|0,Ae[Or+kf|0]=40):Y(r,40);var uf=Se[Se[k]+4>>2];H(r,uf);var cf=Me[cr],hf=0==(0|cf);do{if(!hf){var df=Me[b];if((df+2|0)>>>0>Me[l]>>>0){gr=278;break}var wf=cf+df|0;oe=8233,Ae[wf]=255&oe,oe>>=8,Ae[wf+1]=255&oe;var pf=Se[b]+2|0;Se[b]=pf,gr=279;break}gr=278}while(0);278==gr&&Q(r,0|He.__str139,2);var Ef=Se[of>>2];ir(r,Ef);var Af=Me[cr],gf=0==(0|Af);do{if(!gf){var yf=Me[b];if((yf+2|0)>>>0>Me[l]>>>0){gr=282;break}var mf=Af+yf|0;oe=10272,Ae[mf]=255&oe,oe>>=8,Ae[mf+1]=255&oe;var Sf=Se[b]+2|0;Se[b]=Sf,gr=283;break}gr=282}while(0);282==gr&&Q(r,0|He.__str140,2);var Mf=Se[Se[Se[k]+8>>2]+4>>2];H(r,Mf);var Cf=Me[cr],Rf=0==(0|Cf);do{if(!Rf){var Tf=Me[b];if((Tf+5|0)>>>0>Me[l]>>>0){gr=286;break}var Of=Cf+Tf|0;Ae[Of]=Ae[0|He.__str141],Ae[Of+1]=Ae[(0|He.__str141)+1],Ae[Of+2]=Ae[(0|He.__str141)+2],Ae[Of+3]=Ae[(0|He.__str141)+3],Ae[Of+4]=Ae[(0|He.__str141)+4];var Nf=Se[b]+5|0;Se[b]=Nf,gr=287;break}gr=286}while(0);286==gr&&Q(r,0|He.__str141,5);var If=Se[Se[Se[k]+8>>2]+8>>2];H(r,If);var Pf=Me[cr],Df=0==(0|Pf);do if(!Df){var Lf=Me[b];if(Lf>>>0>=Me[l]>>>0)break;Se[b]=Lf+1|0,Ae[Pf+Lf|0]=41;break r}while(0);Y(r,41);break r}while(0);Z(r);break r}if(47==(0|Ir)||48==(0|Ir)){Z(r);break r}if(49==(0|Ir)||50==(0|Ir)){var Ff=a+4|0,Xf=Se[Ff>>2],jf=33==(0|Se[Xf>>2]);do{if(jf){var Uf=Me[Se[Xf+4>>2]+16>>2];if(1==(0|Uf)||2==(0|Uf)||3==(0|Uf)||4==(0|Uf)||5==(0|Uf)||6==(0|Uf)){var xf=a+8|0;if(0!=(0|Se[Se[xf>>2]>>2])){var zf=Uf;break}if(50==(0|Ir)){var Vf=r+8|0,Bf=Me[Vf>>2];Bf>>>0<Me[Er+3]>>>0?(Se[Vf>>2]=Bf+1|0,Ae[Or+Bf|0]=45):Y(r,45)}var Hf=Se[xf>>2];if(H(r,Hf),2==(0|Uf)){var Kf=Me[cr],Yf=0==(0|Kf);do if(!Yf){var Gf=r+8|0,Wf=Me[Gf>>2];if(Wf>>>0>=Me[Er+3]>>>0)break;Se[Gf>>2]=Wf+1|0,Ae[Kf+Wf|0]=117;break r}while(0);Y(r,117);break r}if(3==(0|Uf)){var Zf=Me[cr],Qf=0==(0|Zf);do if(!Qf){var qf=r+8|0,$f=Me[qf>>2];if($f>>>0>=Me[Er+3]>>>0)break;Se[qf>>2]=$f+1|0,Ae[Zf+$f|0]=108;break r}while(0);Y(r,108);break r}if(4==(0|Uf)){var Jf=Me[cr],r_=0==(0|Jf);do if(!r_){var o=(r+8|0)>>2,a_=Me[o];if((a_+2|0)>>>0>Me[Er+3]>>>0)break;var e_=Jf+a_|0;oe=27765,Ae[e_]=255&oe,oe>>=8,Ae[e_+1]=255&oe;var i_=Se[o]+2|0;Se[o]=i_;break r}while(0);Q(r,0|He.__str142,2);break r}if(5==(0|Uf)){var v_=Me[cr],t_=0==(0|v_);do if(!t_){var n=(r+8|0)>>2,f_=Me[n];if((f_+2|0)>>>0>Me[Er+3]>>>0)break;var __=v_+f_|0;oe=27756,Ae[__]=255&oe,oe>>=8,Ae[__+1]=255&oe;var s_=Se[n]+2|0;Se[n]=s_;break r}while(0);Q(r,0|He.__str143,2);break r}if(6==(0|Uf)){var n_=Me[cr],o_=0==(0|n_);do if(!o_){var s=(r+8|0)>>2,l_=Me[s];if((l_+3|0)>>>0>Me[Er+3]>>>0)break;var b_=n_+l_|0;Ae[b_]=Ae[0|He.__str144],Ae[b_+1]=Ae[(0|He.__str144)+1],Ae[b_+2]=Ae[(0|He.__str144)+2];var k_=Se[s]+3|0;Se[s]=k_;break r}while(0);Q(r,0|He.__str144,3);break r}break r}if(7==(0|Uf)){var _=Se[pr+2]>>2;if(0!=(0|Se[_])){var zf=7;break}if(!(1==(0|Se[_+2])&49==(0|Ir))){var zf=Uf;break}var u_=Ae[Se[_+1]]<<24>>24;if(48==(0|u_)){var f=(r+8|0)>>2,c_=Me[f];if((c_+5|0)>>>0>Me[Er+3]>>>0){Q(r,0|He.__str145,5);break r}var h_=Or+c_|0;Ae[h_]=Ae[0|He.__str145],Ae[h_+1]=Ae[(0|He.__str145)+1],Ae[h_+2]=Ae[(0|He.__str145)+2],Ae[h_+3]=Ae[(0|He.__str145)+3],Ae[h_+4]=Ae[(0|He.__str145)+4];var d_=Se[f]+5|0;Se[f]=d_;break r}if(49==(0|u_)){var t=(r+8|0)>>2,w_=Me[t];if((w_+4|0)>>>0>Me[Er+3]>>>0){Q(r,0|He.__str146,4);break r}var p_=Or+w_|0;oe=1702195828,Ae[p_]=255&oe,oe>>=8,Ae[p_+1]=255&oe,oe>>=8,Ae[p_+2]=255&oe,oe>>=8,Ae[p_+3]=255&oe;var E_=Se[t]+4|0;Se[t]=E_;break r}var zf=Uf;break}var zf=Uf;break}var zf=0}while(0);var zf,v=(r+8|0)>>2,A_=Me[v],i=(r+12|0)>>2;A_>>>0<Me[i]>>>0?(Se[v]=A_+1|0,Ae[Or+A_|0]=40):Y(r,40);var g_=Se[Ff>>2];H(r,g_);var y_=Me[cr],m_=0==(0|y_);do{if(!m_){var S_=Me[v];if(S_>>>0>=Me[i]>>>0){gr=335;break}Se[v]=S_+1|0,Ae[y_+S_|0]=41,gr=336;break}gr=335}while(0);335==gr&&Y(r,41);var M_=50==(0|Se[Nr>>2]);e:do if(M_){var C_=Me[cr],R_=0==(0|C_);do if(!R_){var T_=Me[v];if(T_>>>0>=Me[i]>>>0)break;Se[v]=T_+1|0,Ae[C_+T_|0]=45;break e}while(0);Y(r,45)}while(0);if(8==(0|zf)){var O_=Me[cr],N_=0==(0|O_);do{if(!N_){var I_=Me[v];if(I_>>>0>=Me[i]>>>0){gr=345;break}Se[v]=I_+1|0,Ae[O_+I_|0]=91,gr=346;break}gr=345}while(0);345==gr&&Y(r,91);var P_=Se[pr+2];H(r,P_);var D_=Me[cr],L_=0==(0|D_);do if(!L_){var F_=Me[v];if(F_>>>0>=Me[i]>>>0)break;Se[v]=F_+1|0,Ae[D_+F_|0]=93;break r}while(0);Y(r,93);break r}var X_=Se[pr+2];H(r,X_);break r}Z(r);break r}}while(0);var e=(r+20|0)>>2,j_=Se[e],U_=0|Sr;Se[U_>>2]=j_,Se[e]=Sr,Se[Sr+4>>2]=a;var x_=Sr+8|0;Se[x_>>2]=0;var z_=Se[Er+4];Se[Sr+12>>2]=z_;var V_=Se[pr+1];H(r,V_),0==(0|Se[x_>>2])&&$(r,a);var B_=Se[U_>>2];Se[e]=B_}while(0);Oe=Ar}function K(r,a,e,i){var v=i>>2;Se[v]=r,Se[v+1]=r+e|0,Se[v+2]=a,Se[v+3]=r,Se[v+6]=e<<1,Se[v+5]=0,Se[v+9]=e,Se[v+8]=0,Se[v+10]=0,Se[v+11]=0,Se[v+12]=0}function Y(r,a){var e,i=r+4|0,v=Me[i>>2],t=0==(0|v);do if(!t){var e=(r+8|0)>>2,f=Me[e];if(f>>>0<Me[r+12>>2]>>>0)var _=v,s=f;else{tr(r,1);var n=Me[i>>2];if(0==(0|n))break;var _=n,s=Se[e]}var s,_;Ae[_+s|0]=255&a;var o=Se[e]+1|0;Se[e]=o}while(0)}function G(r,a,e,i){var v,t=i>>2,f=Oe;Oe+=4;var _=f,v=_>>2,s=0==(0|r);do if(s){if(0==(0|i)){var n=0;break}Se[t]=-3;var n=0}else{var o=0==(0|e);if(0!=(0|a)&o){if(0==(0|i)){var n=0;break}Se[t]=-3;var n=0}else{var l=W(r,_);if(0==(0|l)){if(0==(0|i)){var n=0;break}if(1==(0|Se[v])){Se[t]=-1;var n=0}else{Se[t]=-2;var n=0}}else{var b=0==(0|a);do if(b){if(o){var k=l;break}var u=Se[v];Se[e>>2]=u;var k=l}else{var c=Ca(l);if(c>>>0<Me[e>>2]>>>0){Ra(a,l);va(l);var k=a}else{va(a);var h=Se[v];Se[e>>2]=h;var k=l}}while(0);var k;if(0==(0|i)){var n=k;break}Se[t]=0;var n=k}}}while(0);var n;return Oe=f,n}function W(r,a){var e,i=Oe;Oe+=52;var v,t=i,e=t>>2;Se[a>>2]=0;var f=Ca(r),_=Ae[r]<<24>>24==95;do{if(_){if(Ae[r+1|0]<<24>>24==90){var s=0;v=13;break}v=3;break}v=3}while(0);do if(3==v){var n=Na(r,0|He.__str117,8);if(0!=(0|n)){var s=1;v=13;break}var o=Ae[r+8|0];if(o<<24>>24!=46&&o<<24>>24!=95&&o<<24>>24!=36){var s=1;v=13;break}var l=r+9|0,b=Ae[l];if(b<<24>>24!=68&&b<<24>>24!=73){\nvar s=1;v=13;break}if(Ae[r+10|0]<<24>>24!=95){var s=1;v=13;break}var k=f+29|0,u=Jr(k);if(0==(0|u)){Se[a>>2]=1;var c=0;v=19;break}Ae[l]<<24>>24==73?Pa(u,0|He.__str118,30,1):Pa(u,0|He.__str119,29,1);var h=r+11|0,c=(Ia(u,h),u);v=19;break}while(0);if(13==v){var s;K(r,17,f,t);var d=Se[e+6],w=Ta(),p=Oe;Oe+=12*d,Oe=Oe+3>>2<<2;var E=Oe;if(Oe+=4*Se[e+9],Oe=Oe+3>>2<<2,Se[e+4]=p,Se[e+7]=E,s)var A=N(t),g=A;else var y=T(t,1),g=y;var g,m=Ae[Se[e+3]]<<24>>24==0?g:0,S=Se[e+12]+f+10*Se[e+10]|0;if(0==(0|m))var M=0;else var C=S/8+S|0,R=B(17,m,C,a),M=R;var M;Oa(w);var c=M}var c;return Oe=i,c}function Z(r){var a=r+4|0,e=Se[a>>2];va(e),Se[a>>2]=0}function Q(r,a,e){var i,v=r+4|0,t=Me[v>>2],f=0==(0|t);do if(!f){var i=(r+8|0)>>2,_=Me[i];if((_+e|0)>>>0>Me[r+12>>2]>>>0){tr(r,e);var s=Me[v>>2];if(0==(0|s))break;var n=s,o=Se[i]}else var n=t,o=_;var o,n;Pa(n+o|0,a,e,1);var l=Se[i]+e|0;Se[i]=l}while(0)}function q(r,a,e){var i,v,t=a+e|0,f=(0|e)>0;r:do if(f)for(var _=t,s=r+4|0,i=(r+8|0)>>2,n=r+12|0,o=a;;){var o,l=(_-o|0)>3;a:do{if(l){if(Ae[o]<<24>>24!=95){v=21;break}if(Ae[o+1|0]<<24>>24!=95){v=21;break}if(Ae[o+2|0]<<24>>24!=85){v=21;break}for(var b=o+3|0,k=0;;){var k,b;if(b>>>0>=t>>>0){v=21;break a}var u=ge[b],c=u<<24>>24;if((u-48&255&255)<10)var h=c-48|0;else if((u-65&255&255)<6)var h=c-55|0;else{if((u-97&255&255)>=6)break;var h=c-87|0}var h,b=b+1|0,k=(k<<4)+h|0}if(!(u<<24>>24==95&k>>>0<256)){v=21;break}var d=Me[s>>2],w=0==(0|d);do if(!w){var p=Me[i];if(p>>>0>=Me[n>>2]>>>0)break;Se[i]=p+1|0,Ae[d+p|0]=255&k;var E=b;v=25;break a}while(0);Y(r,k);var E=b;v=25;break}v=21}while(0);a:do if(21==v){var A=Me[s>>2],g=0==(0|A);do if(!g){var y=Me[i];if(y>>>0>=Me[n>>2]>>>0)break;var m=Ae[o];Se[i]=y+1|0,Ae[A+y|0]=m;var E=o;break a}while(0);var S=Ae[o]<<24>>24;Y(r,S);var E=o}while(0);var E,M=E+1|0;if(M>>>0>=t>>>0)break r;var o=M}while(0)}function $(r,a){var e,i,v,t,f,_,s,n=r>>2,o=Se[a>>2];r:do if(22==(0|o)||25==(0|o)){var l=Me[n+1],b=0==(0|l);do if(!b){var _=(r+8|0)>>2,k=Me[_];if((k+9|0)>>>0>Me[n+3]>>>0)break;for(var u=l+k|0,c=0|He.__str147,h=u,d=c+9;c<d;c++,h++)Ae[h]=Ae[c];var w=Se[_]+9|0;Se[_]=w;break r}while(0);Q(r,0|He.__str147,9)}else if(23==(0|o)||26==(0|o)){var p=Me[n+1],E=0==(0|p);do if(!E){var f=(r+8|0)>>2,A=Me[f];if((A+9|0)>>>0>Me[n+3]>>>0)break;for(var g=p+A|0,c=0|He.__str148,h=g,d=c+9;c<d;c++,h++)Ae[h]=Ae[c];var y=Se[f]+9|0;Se[f]=y;break r}while(0);Q(r,0|He.__str148,9)}else if(24==(0|o)||27==(0|o)){var m=Me[n+1],S=0==(0|m);do if(!S){var t=(r+8|0)>>2,M=Me[t];if((M+6|0)>>>0>Me[n+3]>>>0)break;var C=m+M|0;Ae[C]=Ae[0|He.__str149],Ae[C+1]=Ae[(0|He.__str149)+1],Ae[C+2]=Ae[(0|He.__str149)+2],Ae[C+3]=Ae[(0|He.__str149)+3],Ae[C+4]=Ae[(0|He.__str149)+4],Ae[C+5]=Ae[(0|He.__str149)+5];var R=Se[t]+6|0;Se[t]=R;break r}while(0);Q(r,0|He.__str149,6)}else if(28==(0|o)){var T=Me[n+1],O=0==(0|T);do{if(!O){var N=r+8|0,I=Me[N>>2];if(I>>>0>=Me[n+3]>>>0){s=17;break}Se[N>>2]=I+1|0,Ae[T+I|0]=32,s=18;break}s=17}while(0);17==s&&Y(r,32);var P=Se[a+8>>2];H(r,P)}else if(29==(0|o)){if(0!=(4&Se[n]|0))break;var D=Me[n+1],L=0==(0|D);do if(!L){var F=r+8|0,X=Me[F>>2];if(X>>>0>=Me[n+3]>>>0)break;Se[F>>2]=X+1|0,Ae[D+X|0]=42;break r}while(0);Y(r,42)}else if(30==(0|o)){var j=Me[n+1],U=0==(0|j);do if(!U){var x=r+8|0,z=Me[x>>2];if(z>>>0>=Me[n+3]>>>0)break;Se[x>>2]=z+1|0,Ae[j+z|0]=38;break r}while(0);Y(r,38)}else if(31==(0|o)){var V=Me[n+1],B=0==(0|V);do if(!B){var v=(r+8|0)>>2,K=Me[v];if((K+8|0)>>>0>Me[n+3]>>>0)break;var G=V+K|0,W=0|G;oe=1886220131,Ae[W]=255&oe,oe>>=8,Ae[W+1]=255&oe,oe>>=8,Ae[W+2]=255&oe,oe>>=8,Ae[W+3]=255&oe;var Z=G+4|0;oe=544761196,Ae[Z]=255&oe,oe>>=8,Ae[Z+1]=255&oe,oe>>=8,Ae[Z+2]=255&oe,oe>>=8,Ae[Z+3]=255&oe;var q=Se[v]+8|0;Se[v]=q;break r}while(0);Q(r,0|He.__str150,8)}else if(32==(0|o)){var $=Me[n+1],J=0==(0|$);do if(!J){var i=(r+8|0)>>2,rr=Me[i];if((rr+10|0)>>>0>Me[n+3]>>>0)break;for(var ar=$+rr|0,c=0|He.__str151,h=ar,d=c+10;c<d;c++,h++)Ae[h]=Ae[c];var er=Se[i]+10|0;Se[i]=er;break r}while(0);Q(r,0|He.__str151,10)}else if(37==(0|o)){var ir=r+4|0,vr=Me[ir>>2],tr=0==(0|vr);do{if(!tr){var fr=r+8|0,_r=Me[fr>>2];if(0!=(0|_r)&&Ae[vr+(_r-1)|0]<<24>>24==40){s=42;break}if(_r>>>0>=Me[n+3]>>>0){s=41;break}Se[fr>>2]=_r+1|0,Ae[vr+_r|0]=32,s=42;break}s=41}while(0);41==s&&Y(r,32);var sr=Se[a+4>>2];H(r,sr);var nr=Me[ir>>2],or=0==(0|nr);do if(!or){var e=(r+8|0)>>2,lr=Me[e];if((lr+3|0)>>>0>Me[n+3]>>>0)break;var br=nr+lr|0;Ae[br]=Ae[0|He.__str135],Ae[br+1]=Ae[(0|He.__str135)+1],Ae[br+2]=Ae[(0|He.__str135)+2];var kr=Se[e]+3|0;Se[e]=kr;break r}while(0);Q(r,0|He.__str135,3)}else if(3==(0|o)){var ur=Se[a+4>>2];H(r,ur)}else H(r,a);while(0)}function J(r){var a=r+20|0,e=Se[a>>2];if((0|e)<(0|Se[r+24>>2])){var i=Se[r+16>>2]+12*e|0,v=e+1|0;Se[a>>2]=v;var t=i}else var t=0;var t;return t}function rr(r,a,e){var i,v,t,f,_=r>>2,s=e,t=s>>2,n=0;r:for(;;){var n,s,o=0==(0|s);do if(!o){if(0!=(0|Se[t+2]))break;var l=Se[Se[t+1]>>2];if(29==(0|l)||30==(0|l)){f=9;break r}if(22==(0|l)||23==(0|l)||24==(0|l)||28==(0|l)||31==(0|l)||32==(0|l)||37==(0|l)){var b=Se[_+1];f=12;break r}var s=Se[t],t=s>>2,n=1;continue r}while(0);if(0!=(0|Se[a+4>>2])&0==(0|n)){f=9;break}var k=0,u=r+4|0,v=u>>2;f=22;break}do if(9==f){var c=Se[_+1];if(0==(0|c)){f=17;break}var h=Se[_+2];if(0==(0|h)){var d=c;f=13;break}var w=Ae[c+(h-1)|0];if(w<<24>>24==40||w<<24>>24==42){f=18;break}var b=c;f=12;break}while(0);do if(12==f){var b;if(0==(0|b)){f=17;break}var d=b;f=13;break}while(0);do if(13==f){var d,p=r+8|0,E=Me[p>>2];if(0!=(0|E)&&Ae[d+(E-1)|0]<<24>>24==32){f=18;break}if(E>>>0>=Me[_+3]>>>0){f=17;break}Se[p>>2]=E+1|0,Ae[d+E|0]=32,f=18;break}while(0);do if(17==f){Y(r,32),f=18;break}while(0);r:do if(18==f){var A=r+4|0,g=Me[A>>2],y=0==(0|g);do if(!y){var m=r+8|0,S=Me[m>>2];if(S>>>0>=Me[_+3]>>>0)break;Se[m>>2]=S+1|0,Ae[g+S|0]=40;var k=1,u=A,v=u>>2;break r}while(0);Y(r,40);var k=1,u=A,v=u>>2}while(0);var u,k,i=(r+20|0)>>2,M=Se[i];Se[i]=0,vr(r,e,0);r:do if(k){var C=Me[v],R=0==(0|C);do if(!R){var T=r+8|0,O=Me[T>>2];if(O>>>0>=Me[_+3]>>>0)break;Se[T>>2]=O+1|0,Ae[C+O|0]=41;break r}while(0);Y(r,41)}while(0);var N=Me[v],I=0==(0|N);do{if(!I){var P=r+8|0,D=Me[P>>2];if(D>>>0>=Me[_+3]>>>0){f=30;break}Se[P>>2]=D+1|0,Ae[N+D|0]=40,f=31;break}f=30}while(0);30==f&&Y(r,40);var L=Se[a+8>>2];0!=(0|L)&&H(r,L);var F=Me[v],X=0==(0|F);do{if(!X){var j=r+8|0,U=Me[j>>2];if(U>>>0>=Me[_+3]>>>0){f=36;break}Se[j>>2]=U+1|0,Ae[F+U|0]=41,f=37;break}f=36}while(0);36==f&&Y(r,41),vr(r,e,1),Se[i]=M}function ar(r,a,e){var i,v,t,f=r>>2,_=0==(0|e);do{if(!_){var s=e,v=s>>2;r:for(;;){var s;if(0==(0|s)){var n=1;t=14;break}if(0==(0|Se[v+2])){var o=36==(0|Se[Se[v+1]>>2]),l=1&o^1;if(o){var n=l;t=14;break}var b=r+4|0,k=Me[b>>2],u=0==(0|k);do{if(!u){var i=(r+8|0)>>2,c=Me[i];if((c+2|0)>>>0>Me[f+3]>>>0){t=9;break}var h=k+c|0;oe=10272,Ae[h]=255&oe,oe>>=8,Ae[h+1]=255&oe;var d=Se[i]+2|0;Se[i]=d,vr(r,e,0),t=10;break}t=9}while(0);9==t&&(Q(r,0|He.__str140,2),vr(r,e,0));var w=Me[b>>2],p=0==(0|w);do if(!p){var E=r+8|0,A=Me[E>>2];if(A>>>0>=Me[f+3]>>>0)break;Se[E>>2]=A+1|0,Ae[w+A|0]=41;var g=l;t=15;break r}while(0);Y(r,41);var g=l;t=15;break}var s=Se[v],v=s>>2}if(14==t){var n;vr(r,e,0);var g=n}var g;if(0!=(0|g)){t=17;break}var y=r+4|0;t=21;break}t=17}while(0);r:do if(17==t){var m=r+4|0,S=Me[m>>2],M=0==(0|S);do if(!M){var C=r+8|0,R=Me[C>>2];if(R>>>0>=Me[f+3]>>>0)break;Se[C>>2]=R+1|0,Ae[S+R|0]=32;var y=m;break r}while(0);Y(r,32);var y=m}while(0);var y,T=Me[y>>2],O=0==(0|T);do{if(!O){var N=r+8|0,I=Me[N>>2];if(I>>>0>=Me[f+3]>>>0){t=24;break}Se[N>>2]=I+1|0,Ae[T+I|0]=91,t=25;break}t=24}while(0);24==t&&Y(r,91);var P=Se[a+4>>2];0!=(0|P)&&H(r,P);var D=Me[y>>2],L=0==(0|D);do{if(!L){var F=r+8|0,X=Me[F>>2];if(X>>>0>=Me[f+3]>>>0){t=30;break}Se[F>>2]=X+1|0,Ae[D+X|0]=93,t=31;break}t=30}while(0);30==t&&Y(r,93)}function er(r,a){var e,i,v,t,f,_,s=Oe;Oe+=8;var n,o=s,_=(a+4|0)>>2,l=Se[_];if(4==(0|Se[l>>2])){var f=(r+20|0)>>2,b=Se[f];Se[f]=0;var t=(r+16|0)>>2,k=Se[t],u=0|o;Se[u>>2]=k,Se[t]=o;var c=Se[_];Se[o+4>>2]=c;var h=Se[c+4>>2];H(r,h);var d=Se[u>>2];Se[t]=d;var v=(r+4|0)>>2,w=Me[v],p=0==(0|w);do{if(!p){var i=(r+8|0)>>2,E=Me[i],A=0==(0|E);do if(!A){if(Ae[w+(E-1)|0]<<24>>24!=60)break;E>>>0<Me[r+12>>2]>>>0?(Se[i]=E+1|0,Ae[w+E|0]=32):Y(r,32)}while(0);var g=Me[v];if(0==(0|g)){n=12;break}var y=Me[i];if(y>>>0>=Me[r+12>>2]>>>0){n=12;break}Se[i]=y+1|0,Ae[g+y|0]=60,n=13;break}n=12}while(0);12==n&&Y(r,60);var m=Se[Se[_]+8>>2];H(r,m);var S=Me[v],M=0==(0|S);do{if(!M){var e=(r+8|0)>>2,C=Me[e],R=0==(0|C);do if(!R){if(Ae[S+(C-1)|0]<<24>>24!=62)break;C>>>0<Me[r+12>>2]>>>0?(Se[e]=C+1|0,Ae[S+C|0]=32):Y(r,32)}while(0);var T=Me[v];if(0==(0|T)){n=22;break}var O=Me[e];if(O>>>0>=Me[r+12>>2]>>>0){n=22;break}Se[e]=O+1|0,Ae[T+O|0]=62,n=23;break}n=22}while(0);22==n&&Y(r,62),Se[f]=b}else H(r,l);Oe=s}function ir(r,a){var e,i=40==(0|Se[a>>2]);r:do if(i){var v=Me[r+4>>2],t=0==(0|v);do{if(!t){var e=(r+8|0)>>2,f=Me[e],_=a+4|0,s=Me[_>>2],n=Me[s+8>>2];if((n+f|0)>>>0>Me[r+12>>2]>>>0){var o=s,l=n;break}var b=v+f|0,k=Se[s+4>>2];Pa(b,k,n,1);var u=Se[e]+Se[Se[_>>2]+8>>2]|0;Se[e]=u;break r}var c=Me[a+4>>2],o=c,l=Se[c+8>>2]}while(0);var l,o,h=Se[o+4>>2];Q(r,h,l)}else H(r,a);while(0)}function vr(r,a,e){var i,v,t,f,_,f=(r+4|0)>>2,s=0==(0|e),t=(r+16|0)>>2;r:do if(s)for(var n=a;;){var n;if(0==(0|n)){_=29;break r}if(0==(0|Se[f])){_=29;break r}var o=n+8|0,l=0==(0|Se[o>>2]);do if(l){var b=n+4|0;if((Se[Se[b>>2]>>2]-25|0)>>>0<3)break;Se[o>>2]=1;var k=Me[t],u=Se[n+12>>2];Se[t]=u;var c=Me[b>>2],h=Se[c>>2];if(35==(0|h)){var d=n,w=k,p=c;_=14;break r}if(36==(0|h)){var E=n,A=k,g=c;_=15;break r}if(2==(0|h)){var y=k,m=b;_=16;break r}$(r,c),Se[t]=k}while(0);var n=Se[n>>2]}else for(var S=a;;){var S;if(0==(0|S)){_=29;break r}if(0==(0|Se[f])){_=29;break r}var M=S+8|0;if(0==(0|Se[M>>2])){Se[M>>2]=1;var C=Me[t],R=Se[S+12>>2];Se[t]=R;var T=S+4|0,O=Me[T>>2],N=Se[O>>2];if(35==(0|N)){var d=S,w=C,p=O;_=14;break r}if(36==(0|N)){var E=S,A=C,g=O;_=15;break r}if(2==(0|N)){var y=C,m=T;_=16;break r}$(r,O),Se[t]=C}var S=Se[S>>2]}while(0);if(14==_){var p,w,d,I=Se[d>>2];rr(r,p,I),Se[t]=w}else if(15==_){var g,A,E,P=Se[E>>2];ar(r,g,P),Se[t]=A}else if(16==_){var m,y,v=(r+20|0)>>2,D=Se[v];Se[v]=0;var L=Se[Se[m>>2]+4>>2];H(r,L),Se[v]=D;var F=0==(4&Se[r>>2]|0),X=Me[f],j=0!=(0|X);r:do if(F){do if(j){var i=(r+8|0)>>2,U=Me[i];if((U+2|0)>>>0>Me[r+12>>2]>>>0)break;var x=X+U|0;oe=14906,Ae[x]=255&oe,oe>>=8,Ae[x+1]=255&oe;var z=Se[i]+2|0;Se[i]=z;break r}while(0);Q(r,0|He.__str120,2)}else{do if(j){var V=r+8|0,B=Me[V>>2];if(B>>>0>=Me[r+12>>2]>>>0)break;Se[V>>2]=B+1|0,Ae[X+B|0]=46;break r}while(0);Y(r,46)}while(0);var K=Me[Se[m>>2]+8>>2],G=(Se[K>>2]-25|0)>>>0<3;r:do if(G)for(var W=K;;){var W,Z=Me[W+4>>2];if((Se[Z>>2]-25|0)>>>0>=3){var q=Z;break r}var W=Z}else var q=K;while(0);var q;H(r,q),Se[t]=y}}function tr(r,a){var e,e=(r+4|0)>>2,i=Se[e],v=0==(0|i);r:do if(!v){for(var t=Se[r+8>>2]+a|0,f=r+12|0,_=Se[f>>2],s=i;;){var s,_;if(t>>>0<=_>>>0)break r;var n=_<<1,o=fa(s,n);if(0==(0|o))break;Se[e]=o,Se[f>>2]=n;var _=n,s=o}var l=Se[e];va(l),Se[e]=0,Se[r+24>>2]=1}while(0)}function fr(r,a,e){var i,v=J(r),i=v>>2;return 0!=(0|v)&&(Se[i]=21,Se[i+1]=a,Se[i+2]=e),v}function _r(r){var a,a=(r+12|0)>>2,e=Se[a],i=Ae[e]<<24>>24;if(88==(0|i)){var v=e+1|0;Se[a]=v;var t=nr(r),f=Se[a],_=f+1|0;Se[a]=_;var s=Ae[f]<<24>>24==69?t:0,n=s}else if(76==(0|i))var o=or(r),n=o;else var l=N(r),n=l;var n;return n}function sr(r){var a,a=(r+12|0)>>2,e=Se[a],i=Ae[e];if(i<<24>>24==110){var v=e+1|0;Se[a]=v;var t=1,f=Ae[v],_=v}else var t=0,f=i,_=e;var _,f,t,s=(f-48&255&255)<10;r:do if(s)for(var n=f,o=0,l=_;;){var l,o,n,b=(n<<24>>24)-48+10*o|0,k=l+1|0;Se[a]=k;var u=ge[k];if((u-48&255&255)>=10){var c=b;break r}var n=u,o=b,l=k}else var c=0;while(0);var c,h=0==(0|t)?c:0|-c;return h}function nr(r){var a,e,a=(r+12|0)>>2,i=Se[a],v=Ae[i];do{if(v<<24>>24==76){var t=or(r),f=t;e=21;break}if(v<<24>>24==84){var _=x(r),f=_;e=21;break}if(v<<24>>24==115){if(Ae[i+1|0]<<24>>24!=114){e=8;break}var s=i+2|0;Se[a]=s;var n=N(r),o=br(r);if(Ae[Se[a]]<<24>>24==73){var l=z(r),b=D(r,4,o,l),k=D(r,1,n,b),f=k;e=21;break}var u=D(r,1,n,o),f=u;e=21;break}e=8}while(0);r:do if(8==e){var c=kr(r);if(0==(0|c)){var f=0;break}var h=0|c,d=Se[h>>2],w=40==(0|d);do{if(w){var p=c+4|0,E=r+48|0,A=Se[Se[p>>2]+8>>2]-2+Se[E>>2]|0;Se[E>>2]=A;var g=Se[h>>2];if(40!=(0|g)){var y=g;e=13;break}var m=Se[p>>2],S=Se[m>>2],M=Da(S,0|He.__str90);if(0!=(0|M)){var C=m;e=15;break}var R=N(r),T=D(r,43,c,R),f=T;break r}var y=d;e=13}while(0);do if(13==e){var y;if(40==(0|y)){var C=Se[c+4>>2];e=15;break}if(41==(0|y)){var O=c+4|0;e=17;break}if(42==(0|y)){e=18;break}var f=0;break r}while(0);do if(15==e){var C,O=C+12|0;e=17;break}while(0);do if(17==e){var O,I=Se[O>>2];if(1==(0|I))break;if(2==(0|I)){var P=nr(r),L=nr(r),F=D(r,45,P,L),X=D(r,44,c,F);return X}if(3==(0|I)){var j=nr(r),U=nr(r),V=nr(r),B=D(r,48,U,V),H=D(r,47,j,B),K=D(r,46,c,H);return K}var f=0;break r}while(0);var Y=nr(r),G=D(r,43,c,Y);return G}while(0);var f;return f}function or(r){var a,a=(r+12|0)>>2,e=Se[a],i=e+1|0;Se[a]=i;var v=Ae[e]<<24>>24==76;r:do if(v){if(Ae[i]<<24>>24==95)var t=T(r,0),f=t;else{var _=N(r);if(0==(0|_)){var s=0;break}var n=33==(0|Se[_>>2]);do if(n){var o=Se[_+4>>2];if(0==(0|Se[o+16>>2]))break;var l=r+48|0,b=Se[l>>2]-Se[o+4>>2]|0;Se[l>>2]=b}while(0);var k=Se[a];if(Ae[k]<<24>>24==110){var u=k+1|0;Se[a]=u;var c=50,h=u}else var c=49,h=k;for(var h,c,d=h;;){var d,w=Ae[d];if(w<<24>>24==69)break;if(w<<24>>24==0){var s=0;break r}var p=d+1|0;Se[a]=p;var d=p}var E=lr(r,h,d-h|0),A=D(r,c,_,E),f=A}var f,g=Se[a],y=g+1|0;Se[a]=y;var m=Ae[g]<<24>>24==69?f:0,s=m}else var s=0;while(0);var s;return s}function lr(r,a,e){var i=J(r),v=m(i,a,e),t=0==(0|v)?0:i;return t}function br(r){var a=r+12|0,e=Me[a>>2],i=ge[e],v=(i-48&255&255)<10;do if(v)var t=L(r),f=t;else if((i-97&255&255)<26){var _=kr(r);if(0==(0|_)){var f=0;break}if(40!=(0|Se[_>>2])){var f=_;break}var s=r+48|0,n=Se[Se[_+4>>2]+8>>2]+Se[s>>2]+7|0;Se[s>>2]=n;var f=_}else if(i<<24>>24==67||i<<24>>24==68)var o=hr(r),f=o;else{if(i<<24>>24!=76){var f=0;break}Se[a>>2]=e+1|0;var l=L(r);if(0==(0|l)){var f=0;break}var b=dr(r),k=0==(0|b)?0:l,f=k}while(0);var f;return f}function kr(r){var a,e,a=(r+12|0)>>2,i=Se[a],v=i+1|0;Se[a]=v;var t=ge[i],f=i+2|0;Se[a]=f;var _=ge[v];do{if(t<<24>>24==118){if((_-48&255&255)>=10){var s=49,n=0;e=6;break}var o=(_<<24>>24)-48|0,l=L(r),b=ur(r,o,l),k=b;e=14;break}if(t<<24>>24==99){if(_<<24>>24!=118){var s=49,n=0;e=6;break}var u=N(r),c=D(r,42,u,0),k=c;e=14;break}var s=49,n=0;e=6}while(0);r:do if(6==e){for(;;){var n,s,h=(s-n)/2+n|0,d=(h<<4)+ri|0,w=Se[d>>2],p=Ae[w],E=t<<24>>24==p<<24>>24;if(E&&_<<24>>24==Ae[w+1|0]<<24>>24)break;var A=t<<24>>24<p<<24>>24;do if(A)var g=h,y=n;else{if(E&&_<<24>>24<Ae[w+1|0]<<24>>24){var g=h,y=n;break}var g=s,y=h+1|0}while(0);var y,g;if((0|y)==(0|g)){var k=0;break r}var s=g,n=y}var m=cr(r,d),k=m}while(0);var k;return k}function ur(r,a,e){var i=J(r),v=S(i,a,e),t=0==(0|v)?0:i;return t}function cr(r,a){var e=J(r);return 0!=(0|e)&&(Se[e>>2]=40,Se[e+4>>2]=a),e}function hr(r){var a,e,i=Se[r+44>>2],e=i>>2,v=0==(0|i);do if(!v){var t=Se[e];if(0==(0|t)){var f=r+48|0,_=Se[f>>2]+Se[e+2]|0;Se[f>>2]=_}else{if(21!=(0|t))break;var s=r+48|0,n=Se[s>>2]+Se[e+2]|0;Se[s>>2]=n}}while(0);var a=(r+12|0)>>2,o=Se[a],l=o+1|0;Se[a]=l;var b=Ae[o]<<24>>24;do if(67==(0|b)){var k=o+2|0;Se[a]=k;var u=Ae[l]<<24>>24;if(49==(0|u))var c=1;else if(50==(0|u))var c=2;else{if(51!=(0|u)){var h=0;break}var c=3}var c,d=wr(r,c,i),h=d}else if(68==(0|b)){var w=o+2|0;Se[a]=w;var p=Ae[l]<<24>>24;if(48==(0|p))var E=1;else if(49==(0|p))var E=2;else{if(50!=(0|p)){var h=0;break}var E=3}var E,A=pr(r,E,i),h=A}else var h=0;while(0);var h;return h}function dr(r){var a=r+12|0,e=Se[a>>2];if(Ae[e]<<24>>24==95){var i=e+1|0;Se[a>>2]=i;var v=sr(r),t=v>>>31^1}else var t=1;var t;return t}function wr(r,a,e){var i=J(r),v=M(i,a,e),t=0==(0|v)?0:i;return t}function pr(r,a,e){var i=J(r),v=C(i,a,e),t=0==(0|v)?0:i;return t}function Er(r,a){var e=J(r);return 0!=(0|e)&&(Se[e>>2]=5,Se[e+4>>2]=a),e}function Ar(r){var a,a=(r+12|0)>>2,e=Se[a],i=Ae[e]<<24>>24;do if(78==(0|i))var v=gr(r),t=v;else if(90==(0|i))var f=yr(r),t=f;else if(76==(0|i))var _=br(r),t=_;else if(83==(0|i)){if(Ae[e+1|0]<<24>>24==116){var s=e+2|0;Se[a]=s;var n=lr(r,0|He.__str152,3),o=br(r),l=D(r,1,n,o),b=r+48|0,k=Se[b>>2]+3|0;Se[b>>2]=k;var u=0,c=l}else var h=V(r,0),u=1,c=h;var c,u;if(Ae[Se[a]]<<24>>24!=73){var t=c;break}if(0==(0|u)){var d=R(r,c);if(0==(0|d)){var t=0;break}}var w=z(r),p=D(r,4,c,w),t=p}else{var E=br(r);if(Ae[Se[a]]<<24>>24!=73){var t=E;break}var A=R(r,E);if(0==(0|A)){var t=0;break}var g=z(r),y=D(r,4,E,g),t=y}while(0);var t;return t}function gr(r){var a,e=Oe;Oe+=4;var i=e,a=(r+12|0)>>2,v=Se[a],t=v+1|0;Se[a]=t;var f=Ae[v]<<24>>24==78;do if(f){var _=I(r,i,1);if(0==(0|_)){var s=0;break}var n=mr(r);if(Se[_>>2]=n,0==(0|n)){var s=0;break}var o=Se[a],l=o+1|0;if(Se[a]=l,Ae[o]<<24>>24!=69){var s=0;break}var s=Se[i>>2]}else var s=0;while(0);var s;return Oe=e,s}function yr(r){var a,a=(r+12|0)>>2,e=Se[a],i=e+1|0;Se[a]=i;var v=Ae[e]<<24>>24==90;do if(v){var t=O(r,0),f=Se[a],_=f+1|0;if(Se[a]=_,Ae[f]<<24>>24!=69){var s=0;break}if(Ae[_]<<24>>24==115){var n=f+2|0;Se[a]=n;var o=dr(r);if(0==(0|o)){var s=0;break}var l=lr(r,0|He.__str168,14),b=D(r,2,t,l),s=b}else{var k=Ar(r),u=dr(r);if(0==(0|u)){var s=0;break}var c=D(r,2,t,k),s=c}}else var s=0;while(0);var s;return s}function mr(r){var a,e=r+12|0,i=0;r:for(;;){var i,v=ge[Se[e>>2]];if(v<<24>>24==0){var t=0;break}var f=(v-48&255&255)<10|(v-97&255&255)<26;do{if(!f){if(v<<24>>24==76||v<<24>>24==68||v<<24>>24==67){a=5;break}if(v<<24>>24==83){var _=V(r,1),s=_;a=10;break}if(v<<24>>24==73){if(0==(0|i)){var t=0;break r}var n=z(r),o=4,l=n;a=11;break}if(v<<24>>24==84){var b=x(r),s=b;a=10;break}if(v<<24>>24==69){var t=i;break r}var t=0;break r}a=5}while(0);do if(5==a){var k=br(r),s=k;a=10;break}while(0);do if(10==a){var s;if(0==(0|i)){var u=s;a=12;break}var o=1,l=s;a=11;break}while(0);if(11==a)var l,o,c=D(r,o,i,l),u=c;var u;if(v<<24>>24!=83)if(Ae[Se[e>>2]]<<24>>24!=69){var h=R(r,u);if(0==(0|h)){var t=0;break}var i=u}else var i=u;else var i=u}var t;return t}function Sr(r,a){var e,i,v=Oe;Oe+=4;var t=v,i=t>>2,e=(r+12|0)>>2,f=Se[e];if(Ae[f]<<24>>24==74){var _=f+1|0;Se[e]=_;var s=1}else var s=a;var s;Se[i]=0;var n=s,o=0,l=t;r:for(;;)for(var l,o,n,b=n,k=o;;){var k,b,u=Ae[Se[e]];if(u<<24>>24==0||u<<24>>24==69){var c=Se[i];if(0==(0|c)){var h=0;break r}var d=0==(0|Se[c+8>>2]);do if(d){var w=Se[c+4>>2];if(33!=(0|Se[w>>2])){var p=c;break}var E=Se[w+4>>2];if(9!=(0|Se[E+16>>2])){var p=c;break}var A=r+48|0,g=Se[A>>2]-Se[E+4>>2]|0;Se[A>>2]=g,Se[i]=0;var p=0}else var p=c;while(0);var p,y=D(r,35,k,p),h=y;break r}var m=N(r);if(0==(0|m)){var h=0;break r}if(0==(0|b)){var S=D(r,38,m,0);if(Se[l>>2]=S,0==(0|S)){var h=0;break r}var n=0,o=k,l=S+8|0;continue r}var b=0,k=m}var h;return Oe=v,h}function Mr(r){for(var a=r;;){var a;if(0==(0|a)){var e=0;break}var i=Se[a>>2];if(1!=(0|i)&&2!=(0|i)){if(6==(0|i)||7==(0|i)||42==(0|i)){var e=1;break}var e=0;break}var a=Se[a+8>>2]}var e;return e}function Cr(r){var a=r>>2;Se[a+3]=0,Se[a+2]=0,Se[a+1]=0,Se[a]=0,Se[a+4]=0}function Rr(r,a){var e,e=(r+12|0)>>2,i=Se[e],v=(Se[r+4>>2]-i|0)<(0|a);r:do if(v)var t=0;else{var f=i+a|0;Se[e]=f;var _=0==(4&Se[r+8>>2]|0);do if(!_){if(Ae[f]<<24>>24!=36)break;var s=a+(i+1)|0;Se[e]=s}while(0);var n=(0|a)>9;do if(n){var o=La(i,0|He.__str117,8);if(0!=(0|o))break;var l=Ae[i+8|0];if(l<<24>>24!=46&&l<<24>>24!=95&&l<<24>>24!=36)break;if(Ae[i+9|0]<<24>>24!=78)break;var b=r+48|0,k=22-a+Se[b>>2]|0;Se[b>>2]=k;var u=lr(r,0|He.__str169,21),t=u;break r}while(0);var c=lr(r,i,a),t=c}while(0);var t;return t}function Tr(r){var a,e,e=(r+48|0)>>2,i=Se[e],v=i+20|0;Se[e]=v;var a=(r+12|0)>>2,t=Se[a],f=t+1|0;Se[a]=f;var _=Ae[t];do if(_<<24>>24==84){var s=t+2|0;Se[a]=s;var n=Ae[f]<<24>>24;if(86==(0|n)){var o=i+15|0;Se[e]=o;var l=N(r),b=D(r,8,l,0),k=b}else if(84==(0|n)){var u=i+10|0;Se[e]=u;var c=N(r),h=D(r,9,c,0),k=h}else if(73==(0|n))var d=N(r),w=D(r,11,d,0),k=w;else if(83==(0|n))var p=N(r),E=D(r,12,p,0),k=E;else if(104==(0|n)){var A=Nr(r,104);if(0==(0|A)){var k=0;break}var g=O(r,0),y=D(r,14,g,0),k=y}else if(118==(0|n)){var m=Nr(r,118);if(0==(0|m)){var k=0;break}var S=O(r,0),M=D(r,15,S,0),k=M}else if(99==(0|n)){var C=Nr(r,0);if(0==(0|C)){var k=0;break}var R=Nr(r,0);if(0==(0|R)){var k=0;break}var T=O(r,0),I=D(r,16,T,0),k=I}else if(67==(0|n)){var P=N(r),L=sr(r);if((0|L)<0){var k=0;break}var F=Se[a],X=F+1|0;if(Se[a]=X,Ae[F]<<24>>24!=95){var k=0;break}var j=N(r),U=Se[e]+5|0;Se[e]=U;var x=D(r,10,j,P),k=x}else if(70==(0|n))var z=N(r),V=D(r,13,z,0),k=V;else{if(74!=(0|n)){var k=0;break}var B=N(r),H=D(r,17,B,0),k=H}}else if(_<<24>>24==71){var K=t+2|0;Se[a]=K;var Y=Ae[f]<<24>>24;if(86==(0|Y))var G=Ar(r),W=D(r,18,G,0),k=W;else if(82==(0|Y))var Z=Ar(r),Q=D(r,19,Z,0),k=Q;else{if(65!=(0|Y)){var k=0;break}var q=O(r,0),$=D(r,20,q,0),k=$}}else var k=0;while(0);var k;return k}function Or(r){for(var a,e=r,a=e>>2;;){var e;if(0==(0|e)){var i=0;break}var v=Se[a];if(4==(0|v)){var t=Se[a+1],f=Mr(t),i=0==(0|f)&1;break}if(25!=(0|v)&&26!=(0|v)&&27!=(0|v)){var i=0;break}var e=Se[a+1],a=e>>2}var i;return i}function Nr(r,a){var e;if(0==(0|a)){var i=r+12|0,v=Se[i>>2],t=v+1|0;Se[i>>2]=t;var f=Ae[v]<<24>>24}else var f=a;var f;do{if(104==(0|f)){var _=(sr(r),r+12|0);e=7;break}if(118==(0|f)){var s=(sr(r),r+12|0),n=Se[s>>2],o=n+1|0;if(Se[s>>2]=o,Ae[n]<<24>>24!=95){var l=0;e=8;break}var _=(sr(r),s);e=7;break}var l=0;e=8}while(0);if(7==e){var _,b=Se[_>>2],k=b+1|0;Se[_>>2]=k;var l=Ae[b]<<24>>24==95&1}var l;return l}function Ir(r){var a,e,i=r>>2,v=Oe;Oe+=56;var t,f=v,_=v+8,s=v+16,n=v+36,e=(0|r)>>2,o=Se[e],l=0==(8192&o|0);r:do{if(l){var a=(r+12|0)>>2,b=Se[a];if(Ae[b]<<24>>24!=63){var k=0;t=111;break}var u=b+1|0;Se[a]=u;var c=Ae[u];do if(c<<24>>24==63){if(Ae[b+2|0]<<24>>24==36){var h=b+3|0;if(Ae[h]<<24>>24!=63){var d=5;t=90;break}Se[a]=h;var w=6,p=h}else var w=0,p=u;var p,w,E=p+1|0;Se[a]=E;var A=Ae[E]<<24>>24;do if(48==(0|A)){var g=1;t=81}else{if(49==(0|A)){var g=2;t=81;break}if(50!=(0|A)){if(51==(0|A)){var y=0|He.__str2172,m=E;t=82;break}if(52==(0|A)){var y=0|He.__str3173,m=E;t=82;break}if(53==(0|A)){var y=0|He.__str4174,m=E;t=82;break}if(54==(0|A)){var y=0|He.__str5175,m=E;t=82;break}if(55==(0|A)){var y=0|He.__str6176,m=E;t=82;break}if(56==(0|A)){var y=0|He.__str7177,m=E;t=82;break}if(57==(0|A)){var y=0|He.__str8178,m=E;t=82;break}if(65==(0|A)){var y=0|He.__str9179,m=E;t=82;break}if(66==(0|A)){Se[a]=p+2|0;var S=0|He.__str10180,M=3;t=88;break}if(67==(0|A)){var y=0|He.__str11181,m=E;t=82;break}if(68==(0|A)){var y=0|He.__str12182,m=E;t=82;break}if(69==(0|A)){var y=0|He.__str13183,m=E;t=82;break}if(70==(0|A)){var y=0|He.__str14184,m=E;t=82;break}if(71==(0|A)){var y=0|He.__str15185,m=E;t=82;break}if(72==(0|A)){var y=0|He.__str16186,m=E;t=82;break}if(73==(0|A)){var y=0|He.__str17187,m=E;t=82;break}if(74==(0|A)){var y=0|He.__str18188,m=E;t=82;break}if(75==(0|A)){var y=0|He.__str19189,m=E;t=82;break}if(76==(0|A)){var y=0|He.__str20190,m=E;t=82;break}if(77==(0|A)){var y=0|He.__str21191,m=E;t=82;break}if(78==(0|A)){var y=0|He.__str22192,m=E;t=82;break}if(79==(0|A)){var y=0|He.__str23193,m=E;t=82;break}if(80==(0|A)){var y=0|He.__str24194,m=E;t=82;break}if(81==(0|A)){var y=0|He.__str25195,m=E;t=82;break}if(82==(0|A)){var y=0|He.__str26196,m=E;t=82;break}if(83==(0|A)){var y=0|He.__str27197,m=E;t=82;break}if(84==(0|A)){var y=0|He.__str28198,m=E;t=82;break}if(85==(0|A)){var y=0|He.__str29199,m=E;t=82;break}if(86==(0|A)){var y=0|He.__str30200,m=E;t=82;break}if(87==(0|A)){var y=0|He.__str31201,m=E;t=82;break}if(88==(0|A)){var y=0|He.__str32202,m=E;t=82;break}if(89==(0|A)){var y=0|He.__str33203,m=E;t=82;break}if(90==(0|A)){var y=0|He.__str34204,m=E;t=82;break}if(95==(0|A)){var C=p+2|0;Se[a]=C;var R=Ae[C]<<24>>24;if(48==(0|R)){var y=0|He.__str35205,m=C;t=82;break}if(49==(0|R)){var y=0|He.__str36206,m=C;t=82;break}if(50==(0|R)){var y=0|He.__str37207,m=C;t=82;break}if(51==(0|R)){var y=0|He.__str38208,m=C;t=82;break}if(52==(0|R)){var y=0|He.__str39209,m=C;t=82;break}if(53==(0|R)){var y=0|He.__str40210,m=C;t=82;break}if(54==(0|R)){var y=0|He.__str41211,m=C;t=82;break}if(55==(0|R)){var y=0|He.__str42212,m=C;t=82;break}if(56==(0|R)){var y=0|He.__str43213,m=C;t=82;break}if(57==(0|R)){var y=0|He.__str44214,m=C;t=82;break}if(65==(0|R)){var y=0|He.__str45215,m=C;t=82;break}if(66==(0|R)){var y=0|He.__str46216,m=C;t=82;break}if(67==(0|R)){Se[a]=p+3|0;var T=0|He.__str47217;t=84;break}if(68==(0|R)){var y=0|He.__str48218,m=C;t=82;break}if(69==(0|R)){var y=0|He.__str49219,m=C;t=82;break}if(70==(0|R)){var y=0|He.__str50220,m=C;t=82;break}if(71==(0|R)){var y=0|He.__str51221,m=C;t=82;break}if(72==(0|R)){var y=0|He.__str52222,m=C;t=82;break}if(73==(0|R)){var y=0|He.__str53223,m=C;t=82;break}if(74==(0|R)){var y=0|He.__str54224,m=C;t=82;break}if(75==(0|R)){var y=0|He.__str55225,m=C;t=82;break}if(76==(0|R)){var y=0|He.__str56226,m=C;t=82;break}if(77==(0|R)){var y=0|He.__str57227,m=C;t=82;break}if(78==(0|R)){var y=0|He.__str58228,m=C;t=82;break}if(79==(0|R)){var y=0|He.__str59229,m=C;t=82;break}if(82==(0|R)){var O=4|o;Se[e]=O;var N=p+3|0;Se[a]=N;var I=Ae[N]<<24>>24;if(48==(0|I)){Se[a]=p+4|0,Cr(s);var P=(Pr(r,_,s,0),Se[_>>2]),D=Se[_+4>>2],L=Dr(r,0|He.__str60230,(ne=Oe,Oe+=8,Se[ne>>2]=P,Se[ne+4>>2]=D,ne)),F=Se[a]-1|0;Se[a]=F;var y=L,m=F;t=82;break}if(49==(0|I)){Se[a]=p+4|0;var X=Lr(r),j=Lr(r),U=Lr(r),x=Lr(r),z=Se[a]-1|0;Se[a]=z;var V=Dr(r,0|He.__str61231,(ne=Oe,Oe+=16,Se[ne>>2]=X,Se[ne+4>>2]=j,Se[ne+8>>2]=U,Se[ne+12>>2]=x,ne)),y=V,m=Se[a];t=82;break}if(50==(0|I)){var y=0|He.__str62232,m=N;t=82;break}if(51==(0|I)){var y=0|He.__str63233,m=N;t=82;break}if(52==(0|I)){var y=0|He.__str64234,m=N;t=82;break}var y=0,m=N;t=82;break}if(83==(0|R)){var y=0|He.__str65235,m=C;t=82;break}if(84==(0|R)){var y=0|He.__str66236,m=C;t=82;break}if(85==(0|R)){var y=0|He.__str67237,m=C;t=82;break}if(86==(0|R)){var y=0|He.__str68238,m=C;t=82;break}if(88==(0|R)){var y=0|He.__str69239,m=C;t=82;break}if(89==(0|R)){var y=0|He.__str70240,m=C;t=82;break}var k=0;t=111;break r}var k=0;t=111;break r}var y=0|He.__str1171,m=E;t=82}while(0);do{if(81==t){var g;Se[a]=p+2|0;var B=g;t=83;break}if(82==t){var m,y;if(Se[a]=m+1|0,1==(0|w)||2==(0|w)){var B=w;t=83;break}if(4==(0|w)){var T=y;t=84;break}if(6!=(0|w)){var S=y,M=w;t=88;break}Cr(n);var H=Xr(r,n,0,60,62);if(0==(0|H))var K=y;else var Y=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=y,Se[ne+4>>2]=H,ne)),K=Y;var K;Se[i+6]=0;var S=K,M=w;t=88;break}}while(0);if(83==t){var B,G=r+40|0,W=Fr(r,0|He._symbol_demangle_dashed_null,-1,G);if(0==(0|W)){var k=0;t=111;break r}var d=B;t=90;break}if(84==t){var T;Se[i+4]=T;var Z=1,Q=T;t=109;break r}if(88==t){var M,S,q=r+40|0,$=Fr(r,S,-1,q);if(0==(0|$)){var k=0;t=111;break r}var d=M;t=90;break}}else{if(c<<24>>24==36){var J=b+2|0;Se[a]=J;var rr=jr(r);Se[i+4]=rr;var ar=0!=(0|rr)&1;t=107;break}var d=0;t=90}while(0);if(90==t){var d,er=Me[a],ir=Ae[er]<<24>>24;if(64==(0|ir))Se[a]=er+1|0;else if(36==(0|ir))t=93;else{var vr=zr(r);if(0==(0|vr)){var k=-1;t=111;break}}if(5==(0|d)){var tr=r+20|0,fr=Se[tr>>2]+1|0;Se[tr>>2]=fr}else if(1==(0|d)||2==(0|d)){if(Me[i+11]>>>0<2){var k=-1;t=111;break}var _r=r+56|0,sr=Me[_r>>2],nr=Se[sr+4>>2];if(1==(0|d))Se[sr>>2]=nr;else{var or=Dr(r,0|He.__str71241,(ne=Oe,Oe+=4,Se[ne>>2]=nr,ne)),lr=Se[_r>>2];Se[lr>>2]=or}var br=4|Se[e];Se[e]=br}else if(3==(0|d)){var kr=Se[e]&-5;Se[e]=kr}var ur=ge[Se[a]];if((ur-48&255&255)<10)var cr=Vr(r),ar=cr;else if((ur-65&255&255)<26)var hr=Br(r,3==(0|d)&1),ar=hr;else{if(ur<<24>>24!=36){var k=-1;t=111;break}var dr=Hr(r),ar=dr}}var ar;if(0==(0|ar)){var k=-1;t=111;break}var Z=ar,Q=Se[i+4];t=109;break}var wr=Pr(r,f,0,0);if(0==(0|wr)){var k=-1;t=111;break}var pr=Se[f>>2],Er=Se[f+4>>2],Ar=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=pr,Se[ne+4>>2]=Er,ne));Se[i+4]=Ar;var Z=1,Q=Ar;t=109;break}while(0);do if(109==t){var Q,Z;if(0!=(0|Q)){var k=Z;break}Xa(0|He.__str72242,1499,0|He.___func___symbol_demangle,0|He.__str73243);var k=Z}while(0);var k;return Oe=v,k}function Pr(r,a,e,i){var v,t,f,_=Oe;Oe+=24;var s=_,n=_+4,o=_+8,l=_+16,b=_+20;0==(0|a)&&Xa(0|He.__str72242,829,0|He.___func___demangle_datatype,0|He.__str121291);var f=(a+4|0)>>2;Se[f]=0;var t=(0|a)>>2;Se[t]=0;var v=(r+12|0)>>2,k=Me[v],u=k+1|0;Se[v]=u;var c=Ae[k],h=c<<24>>24;do if(95==(0|h)){Se[v]=k+2|0;var d=Ae[u],w=Zr(d);Se[t]=w}else if(67==(0|h)||68==(0|h)||69==(0|h)||70==(0|h)||71==(0|h)||72==(0|h)||73==(0|h)||74==(0|h)||75==(0|h)||77==(0|h)||78==(0|h)||79==(0|h)||88==(0|h)||90==(0|h)){var p=Qr(c);Se[t]=p}else if(84==(0|h)||85==(0|h)||86==(0|h)||89==(0|h)){var E=qr(r);if(0==(0|E))break;var A=0==(32768&Se[r>>2]|0);do if(A)if(84==(0|h))var g=0|He.__str122292;else if(85==(0|h))var g=0|He.__str123293;else if(86==(0|h))var g=0|He.__str124294;else{if(89!=(0|h)){var g=0;break}var g=0|He.__str125295}else var g=0;while(0);var g,y=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=g,Se[ne+4>>2]=E,ne));Se[t]=y}else if(63==(0|h))if(0==(0|i))$r(a,r,e,63,0);else{var m=Lr(r);if(0==(0|m))break;var S=Dr(r,0|He.__str126296,(ne=Oe,Oe+=4,Se[ne>>2]=m,ne));Se[t]=S}else if(65==(0|h)||66==(0|h))$r(a,r,e,c,i);else if(81==(0|h)||82==(0|h)||83==(0|h)){var M=0==(0|i)?80:c;$r(a,r,e,M,i)}else if(80==(0|h))if(((Ae[u]<<24>>24)-48|0)>>>0<10){var C=k+2|0;if(Se[v]=C,Ae[u]<<24>>24!=54)break;var R=r+44|0,T=Se[R>>2];Se[v]=k+3|0;var O=Ae[C],N=Se[r>>2]&-17,I=Ur(O,s,n,N);if(0==(0|I))break;var P=Pr(r,o,e,0);if(0==(0|P))break;var D=Xr(r,e,1,40,41);if(0==(0|D))break;Se[R>>2]=T;var L=Se[o>>2],F=Se[o+4>>2],X=Se[s>>2],j=Dr(r,0|He.__str127297,(ne=Oe,Oe+=12,Se[ne>>2]=L,Se[ne+4>>2]=F,Se[ne+8>>2]=X,ne));Se[t]=j;var U=Dr(r,0|He.__str128298,(ne=Oe,Oe+=4,Se[ne>>2]=D,ne));Se[f]=U}else $r(a,r,e,80,i);else if(87==(0|h)){if(Ae[u]<<24>>24!=52)break;Se[v]=k+2|0;var x=qr(r);if(0==(0|x))break;if(0==(32768&Se[r>>2]|0)){var z=Dr(r,0|He.__str129299,(ne=Oe,Oe+=4,Se[ne>>2]=x,ne));Se[t]=z}else Se[t]=x}else if(48==(0|h)||49==(0|h)||50==(0|h)||51==(0|h)||52==(0|h)||53==(0|h)||54==(0|h)||55==(0|h)||56==(0|h)||57==(0|h)){var V=h<<1,B=V-96|0,H=Yr(e,B);Se[t]=H;var K=V-95|0,Y=Yr(e,K);Se[f]=Y}else if(36==(0|h)){var G=k+2|0;Se[v]=G;var W=Ae[u]<<24>>24;if(48==(0|W)){var Z=Lr(r);Se[t]=Z}else if(68==(0|W)){var Q=Lr(r);if(0==(0|Q))break;var q=Dr(r,0|He.__str130300,(ne=Oe,Oe+=4,Se[ne>>2]=Q,ne));Se[t]=q}else if(70==(0|W)){var $=Lr(r);if(0==(0|$))break;var J=Lr(r);if(0==(0|J))break;var rr=Dr(r,0|He.__str131301,(ne=Oe,Oe+=8,Se[ne>>2]=$,Se[ne+4>>2]=J,ne));Se[t]=rr}else if(71==(0|W)){var ar=Lr(r);if(0==(0|ar))break;var er=Lr(r);if(0==(0|er))break;var ir=Lr(r);if(0==(0|ir))break;var vr=Dr(r,0|He.__str132302,(ne=Oe,Oe+=12,Se[ne>>2]=ar,Se[ne+4>>2]=er,Se[ne+8>>2]=ir,ne));Se[t]=vr}else if(81==(0|W)){var tr=Lr(r);if(0==(0|tr))break;var fr=Dr(r,0|He.__str133303,(ne=Oe,Oe+=4,Se[ne>>2]=tr,ne));Se[t]=fr}else{if(36!=(0|W))break;if(Ae[G]<<24>>24!=67)break;Se[v]=k+3|0;var _r=xr(r,l,b);if(0==(0|_r))break;var sr=Pr(r,a,e,i);if(0==(0|sr))break;var nr=Se[t],or=Se[l>>2],lr=Dr(r,0|He.__str83253,(ne=Oe,Oe+=8,Se[ne>>2]=nr,Se[ne+4>>2]=or,ne));Se[t]=lr}}while(0);var br=0!=(0|Se[t])&1;return Oe=_,br}function Dr(r,a){var e,i=Oe;Oe+=4;var v=i,e=v>>2,t=v;Se[t>>2]=arguments[Dr.length];var f=1,_=0;r:for(;;){var _,f,s=Ae[a+_|0];do{if(s<<24>>24==0)break r;if(s<<24>>24==37){var n=_+1|0,o=Ae[a+n|0]<<24>>24;if(115==(0|o)){var l=Se[e],b=l,k=l+4|0;Se[e]=k;var u=Se[b>>2];if(0==(0|u)){var c=f,h=n;break}var d=Ca(u),c=d+f|0,h=n;break}if(99==(0|o)){var w=Se[e]+4|0;Se[e]=w;var c=f+1|0,h=n;break}if(37==(0|o))var p=n;else var p=_;var p,c=f+1|0,h=p}else var c=f+1|0,h=_}while(0);var h,c,f=c,_=h+1|0}var E=Wr(r,f);if(0==(0|E))var A=0;else{Se[t>>2]=arguments[Dr.length];var g=E,y=0;r:for(;;){var y,g,m=Ae[a+y|0];do{if(m<<24>>24==0)break r;if(m<<24>>24==37){var S=y+1|0,M=Ae[a+S|0]<<24>>24;if(115==(0|M)){var C=Se[e],R=C,T=C+4|0;Se[e]=T;var O=Se[R>>2];if(0==(0|O)){var N=g,I=S;break}var P=Ca(O);Pa(g,O,P,1);var N=g+P|0,I=S;break}if(99==(0|M)){var D=Se[e],L=D,F=D+4|0;Se[e]=F,Ae[g]=255&Se[L>>2];var N=g+1|0,I=S;break}if(37==(0|M))var X=S;else var X=y;var X;Ae[g]=37;var N=g+1|0,I=X}else{Ae[g]=m;var N=g+1|0,I=y}}while(0);var I,N,g=N,y=I+1|0}Ae[g]=0;var A=E}var A;return Oe=i,A}function Lr(r){var a,a=(r+12|0)>>2,e=Se[a],i=Ae[e];if(i<<24>>24==63){var v=e+1|0;Se[a]=v;var t=1,f=v,_=Ae[v]}else var t=0,f=e,_=i;var _,f,t,s=(_-48&255&255)<9;do if(s){var n=Wr(r,3),o=0!=(0|t);o&&(Ae[n]=45);var l=Ae[Se[a]]+1&255;Ae[n+t|0]=l;var b=o?2:1;\nAe[n+b|0]=0;var k=Se[a]+1|0;Se[a]=k;var u=n}else if(_<<24>>24==57){var c=Wr(r,4),h=0!=(0|t);h&&(Ae[c]=45),Ae[c+t|0]=49;var d=h?2:1;Ae[c+d|0]=48;var w=h?3:2;Ae[c+w|0]=0;var p=Se[a]+1|0;Se[a]=p;var u=c}else{if((_-65&255&255)>=16){var u=0;break}for(var E=0,A=f;;){var A,E,g=A+1|0;Se[a]=g;var y=(Ae[A]<<24>>24)+((E<<4)-65)|0,m=ge[g];if((m-65&255&255)>=16)break;var E=y,A=g}if(m<<24>>24!=64){var u=0;break}var S=Wr(r,17),M=0!=(0|t)?0|He.__str119289:0|ii,C=(za(S,0|He.__str118288,(ne=Oe,Oe+=8,Se[ne>>2]=M,Se[ne+4>>2]=y,ne)),Se[a]+1|0);Se[a]=C;var u=S}while(0);var u;return u}function Fr(r,a,e,i){var v,t,f,_;0==(0|a)&&Xa(0|He.__str72242,212,0|He.___func___str_array_push,0|He.__str115285),0==(0|i)&&Xa(0|He.__str72242,213,0|He.___func___str_array_push,0|He.__str116286);var f=(i+12|0)>>2,s=Me[f],n=0==(0|s);do{if(n){Se[f]=32;var o=Wr(r,128);if(0==(0|o)){var l=0;_=17;break}Se[i+16>>2]=o,_=11;break}if(Me[i+8>>2]>>>0<s>>>0){_=11;break}var b=s<<3,k=Wr(r,b);if(0==(0|k)){var l=0;_=17;break}var u=k,c=i+16|0,h=Se[c>>2],d=Se[f]<<2;Pa(k,h,d,1);var w=Se[f]<<1;Se[f]=w,Se[c>>2]=u,_=11;break}while(0);do if(11==_){if((0|e)==-1)var p=Ca(a),E=p;else var E=e;var E,A=ja(a),g=E+1|0,y=Wr(r,g),t=(i+4|0)>>2,v=(i+16|0)>>2,m=(Se[t]<<2)+Se[v]|0;Se[m>>2]=y;var S=Se[Se[v]+(Se[t]<<2)>>2];if(0==(0|S)){Xa(0|He.__str72242,233,0|He.___func___str_array_push,0|He.__str117287);var M=Se[Se[v]+(Se[t]<<2)>>2]}else var M=S;var M;Pa(M,A,E,1),va(A),Ae[Se[Se[v]+(Se[t]<<2)>>2]+g|0]=0;var C=Se[t]+1|0;Se[t]=C;var R=i+8|0;if(C>>>0<Me[R>>2]>>>0){var l=1;break}Se[R>>2]=C;var l=1}while(0);var l;return l}function Xr(r,a,e,i,v){var t,f,_=Oe;Oe+=28;var s,n=_,o=_+8;Cr(o);var f=(r+12|0)>>2,l=0==(0|e),t=(0|n)>>2,b=n+4|0;r:do if(l)for(;;){var k=Se[f],u=Ae[k];if(u<<24>>24==0){s=12;break r}if(u<<24>>24==64){var c=k;s=7;break r}var h=Pr(r,n,a,1);if(0==(0|h)){var d=0;s=25;break r}var w=Se[t],p=Se[b>>2],E=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=w,Se[ne+4>>2]=p,ne)),A=Fr(r,E,-1,o);if(0==(0|A)){var d=0;s=25;break r}var g=Se[t],y=Da(g,0|He.__str110280);if(0==(0|y)){s=12;break r}}else for(;;){var m=Se[f],S=Ae[m];if(S<<24>>24==0){s=12;break r}if(S<<24>>24==64){var c=m;s=7;break r}var M=Pr(r,n,a,1);if(0==(0|M)){var d=0;s=25;break r}var C=Se[t],R=Da(C,0|He.__str84254);if(0==(0|R)){s=13;break r}var T=Se[b>>2],O=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=C,Se[ne+4>>2]=T,ne)),N=Fr(r,O,-1,o);if(0==(0|N)){var d=0;s=25;break r}var I=Se[t],P=Da(I,0|He.__str110280);if(0==(0|P)){s=12;break r}}while(0);do if(7==s){var c;Se[f]=c+1|0,s=12;break}while(0);do if(12==s){if(l){s=14;break}s=13;break}while(0);do if(13==s){var D=Se[f],L=D+1|0;if(Se[f]=L,Ae[D]<<24>>24==90){s=14;break}var d=0;s=25;break}while(0);r:do if(14==s){var F=o+4|0,X=Me[F>>2];do{if(0!=(0|X)){if(1==(0|X)){var j=o+16|0,U=Se[Se[j>>2]>>2],x=Da(U,0|He.__str84254);if(0==(0|x)){s=17;break}var z=j;s=20;break}var V=o+16|0;if(X>>>0<=1){var z=V;s=20;break}for(var B=0,H=1;;){var H,B,K=Se[Se[V>>2]+(H<<2)>>2],Y=Dr(r,0|He.__str112282,(ne=Oe,Oe+=8,Se[ne>>2]=B,Se[ne+4>>2]=K,ne)),G=H+1|0;if(G>>>0>=Me[F>>2]>>>0)break;var B=Y,H=G}if(0==(0|Y)){var z=V;s=20;break}var W=Y,Z=Y;s=21;break}s=17}while(0);if(17==s){var Q=i<<24>>24,q=v<<24>>24,$=Dr(r,0|He.__str111281,(ne=Oe,Oe+=8,Se[ne>>2]=Q,Se[ne+4>>2]=q,ne)),d=$;break}if(20==s)var z,W=Se[Se[z>>2]>>2],Z=0;var Z,W,J=v<<24>>24,rr=v<<24>>24==62;do if(rr){var ar=Ca(W);if(Ae[W+(ar-1)|0]<<24>>24!=62)break;var er=i<<24>>24,ir=Se[Se[o+16>>2]>>2],vr=Dr(r,0|He.__str113283,(ne=Oe,Oe+=16,Se[ne>>2]=er,Se[ne+4>>2]=ir,Se[ne+8>>2]=Z,Se[ne+12>>2]=J,ne)),d=vr;break r}while(0);var tr=i<<24>>24,fr=Se[Se[o+16>>2]>>2],_r=Dr(r,0|He.__str114284,(ne=Oe,Oe+=16,Se[ne>>2]=tr,Se[ne+4>>2]=fr,Se[ne+8>>2]=Z,Se[ne+12>>2]=J,ne)),d=_r}while(0);var d;return Oe=_,d}function jr(r){var a,e=Oe;Oe+=20;var i=e,v=r+24|0,t=Se[v>>2],a=(r+20|0)>>2,f=Se[a],_=r+44|0,s=Se[_>>2];Se[a]=t;var n=Kr(r);if(0==(0|n))var o=0;else{Cr(i);var l=Xr(r,i,0,60,62);if(0==(0|l))var b=n;else var k=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=n,Se[ne+4>>2]=l,ne)),b=k;var b;Se[v>>2]=t,Se[a]=f,Se[_>>2]=s;var o=b}var o;return Oe=e,o}function Ur(r,a,e,i){var v,t=a>>2;Se[e>>2]=0,Se[t]=0;var f=0==(18&i|0);do{if(f){var _=r<<24>>24,s=1==((_-65)%2|0);if(0==(1&i|0)){if(s?Se[e>>2]=0|He.__str95265:v=14,65==(0|_)||66==(0|_)){Se[t]=0|He.__str96266,v=21;break}if(67==(0|_)||68==(0|_)){Se[t]=0|He.__str97267,v=21;break}if(69==(0|_)||70==(0|_)){Se[t]=0|He.__str98268,v=21;break}if(71==(0|_)||72==(0|_)){Se[t]=0|He.__str99269,v=21;break}if(73==(0|_)||74==(0|_)){Se[t]=0|He.__str100270,v=21;break}if(75==(0|_)||76==(0|_)){v=21;break}if(77==(0|_)){Se[t]=0|He.__str101271,v=21;break}var n=0;v=22;break}if(s?Se[e>>2]=0|He.__str88258:v=5,65==(0|_)||66==(0|_)){Se[t]=0|He.__str89259,v=21;break}if(67==(0|_)||68==(0|_)){Se[t]=0|He.__str90260,v=21;break}if(69==(0|_)||70==(0|_)){Se[t]=0|He.__str91261,v=21;break}if(71==(0|_)||72==(0|_)){Se[t]=0|He.__str92262,v=21;break}if(73==(0|_)||74==(0|_)){Se[t]=0|He.__str93263,v=21;break}if(75==(0|_)||76==(0|_)){v=21;break}if(77==(0|_)){Se[t]=0|He.__str94264,v=21;break}var n=0;v=22;break}v=21}while(0);if(21==v)var n=1;var n;return n}function xr(r,a,e){var i;Se[e>>2]=0;var i=(r+12|0)>>2,v=Se[i];if(Ae[v]<<24>>24==69){Se[e>>2]=0|He.__str102272;var t=Se[i]+1|0;Se[i]=t;var f=t}else var f=v;var f;Se[i]=f+1|0;var _=Ae[f]<<24>>24;if(65==(0|_)){Se[a>>2]=0;var s=1}else if(66==(0|_)){Se[a>>2]=0|He.__str103273;var s=1}else if(67==(0|_)){Se[a>>2]=0|He.__str104274;var s=1}else if(68==(0|_)){Se[a>>2]=0|He.__str105275;var s=1}else var s=0;var s;return s}function zr(r){var a,e,a=(r+12|0)>>2,i=r+40|0,v=r+20|0,t=0|i,f=r+44|0,_=r+48|0,s=r+52|0,n=r+56|0,o=r+20|0,l=r+24|0,b=r+16|0,k=0;r:for(;;){var k,u=Se[a],c=Ae[u];if(c<<24>>24==64){var h=u+1|0;Se[a]=h;var d=1;break}var w=c<<24>>24;do{if(0==(0|w)){var d=0;break r}if(48==(0|w)||49==(0|w)||50==(0|w)||51==(0|w)||52==(0|w)||53==(0|w)||54==(0|w)||55==(0|w)||56==(0|w)||57==(0|w)){var p=u+1|0;Se[a]=p;var E=(Ae[u]<<24>>24)-48|0,A=Yr(v,E),g=A;e=14;break}if(63==(0|w)){var y=u+1|0;Se[a]=y;var m=Ae[y]<<24>>24;if(36==(0|m)){var S=u+2|0;Se[a]=S;var M=jr(r);if(0==(0|M)){var d=0;break r}var C=Fr(r,M,-1,v);if(0==(0|C)){var d=0;break r}var R=M;e=15;break}if(63==(0|m)){var T=Se[t>>2],O=Se[f>>2],N=Se[_>>2],I=Se[s>>2],P=Se[n>>2],D=Se[o>>2],L=Se[l>>2];Cr(i);var F=Ir(r);if(0==(0|F))var X=k;else var j=Se[b>>2],U=Dr(r,0|He.__str109279,(ne=Oe,Oe+=4,Se[ne>>2]=j,ne)),X=U;var X;Se[o>>2]=D,Se[l>>2]=L,Se[t>>2]=T,Se[f>>2]=O,Se[_>>2]=N,Se[s>>2]=I,Se[n>>2]=P;var g=X;e=14;break}var x=Lr(r);if(0==(0|x)){var d=0;break r}var z=Dr(r,0|He.__str109279,(ne=Oe,Oe+=4,Se[ne>>2]=x,ne)),g=z;e=14;break}var V=Kr(r),g=V;e=14;break}while(0);if(14==e){var g;if(0==(0|g)){var d=0;break}var R=g}var R,B=Fr(r,R,-1,i);if(0==(0|B)){var d=0;break}var k=R}var d;return d}function Vr(r){var a,e,i,v=Oe;Oe+=36;var t,f=v,i=f>>2,_=v+4,s=v+8,e=s>>2,n=v+16;Se[i]=0;var o=0|r,l=Se[o>>2],b=0==(128&l|0),k=r+12|0;do if(b){var u=Ae[Se[k>>2]]<<24>>24;if(48==(0|u))var c=0|He.__str76246,h=k,a=h>>2;else if(49==(0|u))var c=0|He.__str77247,h=k,a=h>>2;else{if(50!=(0|u)){var c=0,h=k,a=h>>2;break}var c=0|He.__str78248,h=k,a=h>>2}}else var c=0,h=k,a=h>>2;while(0);var h,c,d=0==(512&l|0);do if(d){if((Ae[Se[a]]-48&255&255)>=3){var w=0;break}var w=0|He.__str79249}else var w=0;while(0);var w,p=Gr(r,0),E=Se[a],A=E+1|0;Se[a]=A;var g=Ae[E]<<24>>24;do{if(48==(0|g)||49==(0|g)||50==(0|g)||51==(0|g)||52==(0|g)||53==(0|g)){var y=r+44|0,m=Se[y>>2];Cr(n);var S=Pr(r,s,n,0);if(0==(0|S)){var M=0;t=28;break}var C=xr(r,f,_);if(0==(0|C)){var M=0;t=28;break}var R=Se[i],T=0==(0|R),O=Se[_>>2];do if(T)Se[i]=O;else{if(0==(0|O))break;var N=Dr(r,0|He.__str83253,(ne=Oe,Oe+=8,Se[ne>>2]=R,Se[ne+4>>2]=O,ne));Se[i]=N}while(0);Se[y>>2]=m,t=22;break}if(54==(0|g)||55==(0|g)){var I=s+4|0;Se[I>>2]=0,Se[e]=0;var P=xr(r,f,_);if(0==(0|P)){var M=0;t=28;break}if(Ae[Se[a]]<<24>>24==64){t=22;break}var D=qr(r);if(0==(0|D)){var M=0;t=28;break}var L=Dr(r,0|He.__str107277,(ne=Oe,Oe+=4,Se[ne>>2]=D,ne));Se[I>>2]=L,t=22;break}if(56==(0|g)||57==(0|g)){Se[e+1]=0,Se[e]=0,Se[i]=0,t=22;break}var M=0;t=28}while(0);if(22==t){var F=0==(4096&Se[o>>2]|0);do{if(F){var X=Se[e],j=Se[i];if(0==(0|j)){var U=X;t=26;break}var x=0!=(0|X)?0|He.__str87257:0,z=0|He.__str87257,V=j,B=x,H=X;t=27;break}Se[i]=0,Se[e+1]=0,Se[e]=0;var U=0;t=26;break}while(0);if(26==t)var U,K=0!=(0|U)?0|He.__str87257:0,z=K,V=0,B=0,H=U;var H,B,V,z,Y=Se[e+1],G=Dr(r,0|He.__str108278,(ne=Oe,Oe+=32,Se[ne>>2]=c,Se[ne+4>>2]=w,Se[ne+8>>2]=H,Se[ne+12>>2]=B,Se[ne+16>>2]=V,Se[ne+20>>2]=z,Se[ne+24>>2]=p,Se[ne+28>>2]=Y,ne));Se[r+16>>2]=G;var M=1}var M;return Oe=v,M}function Br(r,a){var e,i,v,t,f=Oe;Oe+=44;var _,s=f,t=s>>2,n=f+8,o=f+12,v=o>>2,l=f+16,b=f+20,k=f+40;Se[v]=0;var i=(r+12|0)>>2,u=Se[i],c=u+1|0;Se[i]=c;var h=ge[u],d=h<<24>>24,w=(h-65&255&255)>25;r:do if(w)var p=0;else{var e=(0|r)>>2,E=Me[e],A=0==(128&E|0),g=d-65|0;do if(A){var y=g/8|0;if(0==(0|y))var m=0|He.__str76246,S=g;else if(1==(0|y))var m=0|He.__str77247,S=g;else{if(2!=(0|y)){var m=0,S=g;break}var m=0|He.__str78248,S=g}}else var m=0,S=g;while(0);var S,m,M=0==(512&E|0)&h<<24>>24<89,C=(0|S)%8;do if(M)if(2==(0|C)||3==(0|C))var R=m,T=0|He.__str79249;else if(4==(0|C)||5==(0|C))var R=m,T=0|He.__str80250;else{if(6!=(0|C)&&7!=(0|C)){var R=m,T=0;break}var O=Dr(r,0|He.__str81251,(ne=Oe,Oe+=4,Se[ne>>2]=m,ne)),R=O,T=0|He.__str80250}else var R=m,T=0;while(0);var T,R,N=Gr(r,0),I=6==(0|C);do{if(!I){if(7==((d-56)%8|0)){_=14;break}var P=N;_=15;break}_=14}while(0);if(14==_)var D=Lr(r),L=Dr(r,0|He.__str82252,(ne=Oe,Oe+=8,Se[ne>>2]=N,Se[ne+4>>2]=D,ne)),P=L;var P,F=h<<24>>24>88;do if(F)var X=0;else{if((C-2|0)>>>0<2){var X=0;break}var j=xr(r,o,k);if(0==(0|j)){var p=0;break r}var U=Me[v],x=Se[k>>2];if(0==(0|U)&0==(0|x)){var X=0;break}var z=Dr(r,0|He.__str83253,(ne=Oe,Oe+=8,Se[ne>>2]=U,Se[ne+4>>2]=x,ne));Se[v]=z;var X=z}while(0);var X,V=Se[i],B=V+1|0;Se[i]=B;var H=Ae[V],K=Se[e],Y=Ur(H,n,l,K);if(0==(0|Y)){var p=0;break}Cr(b);var G=Se[i];if(Ae[G]<<24>>24==64){Se[t]=0|He.__str84254,Se[t+1]=0;var W=G+1|0;Se[i]=W}else{var Z=Pr(r,s,b,0);if(0==(0|Z)){var p=0;break}}if(0!=(4&Se[e]|0)&&(Se[t+1]=0,Se[t]=0),0==(0|a))var Q=P;else{var q=0|s,$=Se[q>>2],J=s+4|0,rr=Se[J>>2],ar=Dr(r,0|He.__str85255,(ne=Oe,Oe+=12,Se[ne>>2]=P,Se[ne+4>>2]=$,Se[ne+8>>2]=rr,ne));Se[J>>2]=0,Se[q>>2]=0;var Q=ar}var Q,er=r+44|0,ir=Se[er>>2],vr=Xr(r,b,1,40,41);if(0==(0|vr)){var p=0;break}if(0==(4096&Se[e]|0))var tr=vr,fr=X;else{Se[v]=0;var tr=0,fr=0}var fr,tr;Se[er>>2]=ir;var _r=Se[t],sr=Se[t+1];if(0==(0|_r))var nr=0;else var or=0!=(0|sr)?0:0|He.__str87257,nr=or;var nr,lr=Se[n>>2],br=0!=(0|lr)?0|He.__str87257:0,kr=Se[l>>2],ur=Dr(r,0|He.__str86256,(ne=Oe,Oe+=44,Se[ne>>2]=R,Se[ne+4>>2]=T,Se[ne+8>>2]=_r,Se[ne+12>>2]=nr,Se[ne+16>>2]=lr,Se[ne+20>>2]=br,Se[ne+24>>2]=kr,Se[ne+28>>2]=Q,Se[ne+32>>2]=tr,Se[ne+36>>2]=fr,Se[ne+40>>2]=sr,ne));Se[r+16>>2]=ur;var p=1}while(0);var p;return Oe=f,p}function Hr(r){var a,a=(r+12|0)>>2,e=Se[a];if(Ae[e]<<24>>24==36)var i=e;else{Xa(0|He.__str72242,1252,0|He.___func___handle_template,0|He.__str74244);var i=Se[a]}var i;Se[a]=i+1|0;var v=Kr(r),t=0==(0|v);do if(t)var f=0;else{var _=Xr(r,0,0,60,62);if(0==(0|_)){var f=0;break}var s=Dr(r,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=v,Se[ne+4>>2]=_,ne));Se[r+16>>2]=s;var f=1}while(0);var f;return f}function Kr(r){for(var a,a=(r+12|0)>>2,e=Me[a],i=e,v=Ae[e];;){var v,i;if(!((v-65&255&255)<26|(v-97&255&255)<26|(v-48&255&255)<10)&&v<<24>>24!=95&&v<<24>>24!=36){var t=0;break}var f=i+1|0;Se[a]=f;var _=ge[f];if(_<<24>>24==64){Se[a]=i+2|0;var s=f-e|0,n=r+20|0,o=Fr(r,e,s,n);if(0==(0|o)){var t=0;break}var l=Se[r+24>>2]-1-Se[n>>2]|0,b=Yr(n,l),t=b;break}var i=f,v=_}var t;return t}function Yr(r,a){0==(0|r)&&Xa(0|He.__str72242,263,0|He.___func___str_array_get_ref,0|He.__str75245);var e=Se[r>>2]+a|0;if(e>>>0<Me[r+8>>2]>>>0)var i=Se[Se[r+16>>2]+(e<<2)>>2];else var i=0;var i;return i}function Gr(r,a){var e,e=(r+44|0)>>2,i=Me[e];if(i>>>0>a>>>0){for(var v=r+56|0,t=a,f=0,_=Se[v>>2],s=i;;){var s,_,f,t,n=Me[_+(t<<2)>>2];if(0==(0|n)){Xa(0|He.__str72242,680,0|He.___func___get_class_string,0|He.__str106276);var o=Se[v>>2],l=o,b=Se[o+(t<<2)>>2],k=Se[e]}else var l=_,b=n,k=s;var k,b,l,u=Ca(b),c=u+(f+2)|0,h=t+1|0;if(h>>>0>=k>>>0)break;var t=h,f=c,_=l,s=k}var d=c-1|0}else var d=-1;var d,w=Wr(r,d);if(0==(0|w))var p=0;else{var E=Se[e]-1|0,A=(0|E)<(0|a);r:do if(A)var g=0;else for(var y=r+56|0,m=0,S=E;;){var S,m,M=Se[Se[y>>2]+(S<<2)>>2],C=Ca(M),R=w+m|0;Pa(R,M,C,1);var T=C+m|0;if((0|S)>(0|a)){var O=T+1|0;Ae[w+T|0]=58;var N=T+2|0;Ae[w+O|0]=58;var I=N}else var I=T;var I,P=S-1|0;if((0|P)<(0|a)){var g=I;break r}var m=I,S=P}while(0);var g;Ae[w+g|0]=0;var p=w}var p;return p}function Wr(r,a){var e,i=a>>>0>1020;do if(i){var v=Se[r+4>>2],t=a+4|0,f=pe[v](t);if(0==(0|f)){var _=0;break}var s=r+60|0,n=Se[s>>2],o=f;Se[o>>2]=n,Se[s>>2]=f,Se[r+64>>2]=0;var _=f+4|0}else{var e=(r+64|0)>>2,l=Me[e];if(l>>>0<a>>>0){var b=Se[r+4>>2],k=pe[b](1024);if(0==(0|k)){var _=0;break}var u=r+60|0,c=Se[u>>2],h=k;Se[h>>2]=c,Se[u>>2]=k,Se[e]=1020;var d=1020,w=k}else var d=l,w=Se[r+60>>2];var w,d;Se[e]=d-a|0;var _=w+(1024-d)|0}while(0);var _;return _}function Zr(r){var a=r<<24>>24;if(68==(0|a))var e=0|He.__str157327;else if(69==(0|a))var e=0|He.__str158328;else if(70==(0|a))var e=0|He.__str159329;else if(71==(0|a))var e=0|He.__str160330;else if(72==(0|a))var e=0|He.__str161331;else if(73==(0|a))var e=0|He.__str162332;else if(74==(0|a))var e=0|He.__str163333;else if(75==(0|a))var e=0|He.__str164334;else if(76==(0|a))var e=0|He.__str165335;else if(77==(0|a))var e=0|He.__str166336;else if(78==(0|a))var e=0|He.__str167337;else if(87==(0|a))var e=0|He.__str168338;else var e=0;var e;return e}function Qr(r){var a=r<<24>>24;if(67==(0|a))var e=0|He.__str145315;else if(68==(0|a))var e=0|He.__str146316;else if(69==(0|a))var e=0|He.__str147317;else if(70==(0|a))var e=0|He.__str148318;else if(71==(0|a))var e=0|He.__str149319;else if(72==(0|a))var e=0|He.__str150320;else if(73==(0|a))var e=0|He.__str151321;else if(74==(0|a))var e=0|He.__str152322;else if(75==(0|a))var e=0|He.__str153323;else if(77==(0|a))var e=0|He.__str154324;else if(78==(0|a))var e=0|He.__str155325;else if(79==(0|a))var e=0|He.__str156326;else if(88==(0|a))var e=0|He.__str84254;else if(90==(0|a))var e=0|He.__str110280;else var e=0;var e;return e}function qr(r){var a=r+44|0,e=Se[a>>2],i=zr(r);if(0==(0|i))var v=0;else var t=Gr(r,e),v=t;var v;return Se[a>>2]=e,v}function $r(r,a,e,i,v){var t,f,_,s=Oe;Oe+=16;var n,o=s,_=o>>2,l=s+4,b=s+8,f=b>>2;Se[l>>2]=0|ii;var t=(a+12|0)>>2,k=Se[t];if(Ae[k]<<24>>24==69){Se[l>>2]=0|He.__str134304;var u=k+1|0;Se[t]=u;var c=0|He.__str134304}else var c=0|ii;var c,h=i<<24>>24;do{if(65==(0|h)){var d=Dr(a,0|He.__str135305,(ne=Oe,Oe+=4,Se[ne>>2]=c,ne)),w=d;n=10;break}if(66==(0|h)){var p=Dr(a,0|He.__str136306,(ne=Oe,Oe+=4,Se[ne>>2]=c,ne)),w=p;n=10;break}if(80==(0|h)){var E=Dr(a,0|He.__str137307,(ne=Oe,Oe+=4,Se[ne>>2]=c,ne)),w=E;n=10;break}if(81==(0|h)){var A=Dr(a,0|He.__str138308,(ne=Oe,Oe+=4,Se[ne>>2]=c,ne)),w=A;n=10;break}if(82==(0|h)){var g=Dr(a,0|He.__str139309,(ne=Oe,Oe+=4,Se[ne>>2]=c,ne)),w=g;n=10;break}if(83==(0|h)){var y=Dr(a,0|He.__str140310,(ne=Oe,Oe+=4,Se[ne>>2]=c,ne)),w=y;n=10;break}if(63==(0|h)){var w=0|ii;n=10}else n=31}while(0);r:do if(10==n){var w,m=xr(a,o,l);if(0==(0|m))break;var S=a+44|0,M=Se[S>>2],C=Se[t],R=Ae[C]<<24>>24==89;a:do if(R){var T=C+1|0;Se[t]=T;var O=Lr(a);if(0==(0|O))break r;var N=Ha(O),I=Ae[w]<<24>>24==32,P=Se[_],D=0==(0|P);do{if(I){if(!D){n=17;break}var L=w+1|0;n=18;break}if(D){var L=w;n=18;break}n=17;break}while(0);if(17==n){var F=Dr(a,0|He.__str141311,(ne=Oe,Oe+=8,Se[ne>>2]=P,Se[ne+4>>2]=w,ne));Se[_]=0;var X=F}else if(18==n)var L,j=Dr(a,0|He.__str142312,(ne=Oe,Oe+=4,Se[ne>>2]=L,ne)),X=j;var X;if(0==(0|N)){var U=X;break}for(var x=X,z=N;;){var z,x,V=z-1|0,B=Lr(a),H=Dr(a,0|He.__str143313,(ne=Oe,Oe+=8,Se[ne>>2]=x,Se[ne+4>>2]=B,ne));if(0==(0|V)){var U=H;break a}var x=H,z=V}}else var U=w;while(0);var U,K=Pr(a,b,e,0);if(0==(0|K))break;var Y=Se[_];if(0==(0|Y)){var G=0==(0|v);do if(G){if(Ae[U]<<24>>24==0){var W=U;break}var Z=U+1|0;if(Ae[Z]<<24>>24!=42){var W=U;break}var Q=Se[f],q=Ca(Q);if(Ae[Q+(q-1)|0]<<24>>24!=42){var W=U;break}var W=Z}else var W=U;while(0);var W,$=Se[f],J=Dr(a,0|He.__str170,(ne=Oe,Oe+=8,Se[ne>>2]=$,Se[ne+4>>2]=W,ne));Se[r>>2]=J}else{var rr=Se[f],ar=Dr(a,0|He.__str144314,(ne=Oe,Oe+=12,Se[ne>>2]=rr,Se[ne+4>>2]=Y,Se[ne+8>>2]=U,ne));Se[r>>2]=ar}var er=Se[f+1];Se[r+4>>2]=er,Se[S>>2]=M}while(0);Oe=s}function Jr(r){var a,e=r>>>0<245;do{if(e){if(r>>>0<11)var i=16;else var i=r+11&-8;var i,v=i>>>3,t=Me[vi>>2],f=t>>>(v>>>0);if(0!=(3&f|0)){var _=(1&f^1)+v|0,s=_<<1,n=(s<<2)+vi+40|0,o=(s+2<<2)+vi+40|0,l=Me[o>>2],b=l+8|0,k=Me[b>>2];if((0|n)==(0|k))Se[vi>>2]=t&(1<<_^-1);else{if(k>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[o>>2]=k,Se[k+12>>2]=n}var u=_<<3;Se[l+4>>2]=3|u;var c=l+(4|u)|0,h=1|Se[c>>2];Se[c>>2]=h;var d=b;a=38;break}if(i>>>0<=Me[vi+8>>2]>>>0){var w=i;a=30;break}if(0!=(0|f)){var p=2<<v,E=f<<v&(p|-p),A=(E&-E)-1|0,g=A>>>12&16,y=A>>>(g>>>0),m=y>>>5&8,S=y>>>(m>>>0),M=S>>>2&4,C=S>>>(M>>>0),R=C>>>1&2,T=C>>>(R>>>0),O=T>>>1&1,N=(m|g|M|R|O)+(T>>>(O>>>0))|0,I=N<<1,P=(I<<2)+vi+40|0,D=(I+2<<2)+vi+40|0,L=Me[D>>2],F=L+8|0,X=Me[F>>2];if((0|P)==(0|X))Se[vi>>2]=t&(1<<N^-1);else{if(X>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[D>>2]=X,Se[X+12>>2]=P}var j=N<<3,U=j-i|0;Se[L+4>>2]=3|i;var x=L,z=x+i|0;Se[x+(4|i)>>2]=1|U,Se[x+j>>2]=U;var V=Me[vi+8>>2];if(0!=(0|V)){var B=Se[vi+20>>2],H=V>>>2&1073741822,K=(H<<2)+vi+40|0,Y=Me[vi>>2],G=1<<(V>>>3),W=0==(Y&G|0);do{if(!W){var Z=(H+2<<2)+vi+40|0,Q=Me[Z>>2];if(Q>>>0>=Me[vi+16>>2]>>>0){var q=Q,$=Z;break}throw Ka(),"Reached an unreachable!"}Se[vi>>2]=Y|G;var q=K,$=(H+2<<2)+vi+40|0}while(0);var $,q;Se[$>>2]=B,Se[q+12>>2]=B;var J=B+8|0;Se[J>>2]=q;var rr=B+12|0;Se[rr>>2]=K}Se[vi+8>>2]=U,Se[vi+20>>2]=z;var d=F;a=38;break}if(0==(0|Se[vi+4>>2])){var w=i;a=30;break}var ar=ra(i);if(0==(0|ar)){var w=i;a=30;break}var d=ar;a=38;break}if(r>>>0>4294967231){var w=-1;a=30;break}var er=r+11&-8;if(0==(0|Se[vi+4>>2])){var w=er;a=30;break}var ir=ea(er);if(0==(0|ir)){var w=er;a=30;break}var d=ir;a=38;break}while(0);if(30==a){var w,vr=Me[vi+8>>2];if(w>>>0>vr>>>0){var tr=Me[vi+12>>2];if(w>>>0<tr>>>0){var fr=tr-w|0;Se[vi+12>>2]=fr;var _r=Me[vi+24>>2],sr=_r;Se[vi+24>>2]=sr+w|0,Se[w+(sr+4)>>2]=1|fr,Se[_r+4>>2]=3|w;var d=_r+8|0}else var nr=aa(w),d=nr}else{var or=vr-w|0,lr=Me[vi+20>>2];if(or>>>0>15){var br=lr;Se[vi+20>>2]=br+w|0,Se[vi+8>>2]=or,Se[w+(br+4)>>2]=1|or,Se[br+vr>>2]=or,Se[lr+4>>2]=3|w}else{Se[vi+8>>2]=0,Se[vi+20>>2]=0,Se[lr+4>>2]=3|vr;var kr=vr+(lr+4)|0,ur=1|Se[kr>>2];Se[kr>>2]=ur}var d=lr+8|0}}var d;return d}function ra(r){var a,e,i,v=Se[vi+4>>2],t=(v&-v)-1|0,f=t>>>12&16,_=t>>>(f>>>0),s=_>>>5&8,n=_>>>(s>>>0),o=n>>>2&4,l=n>>>(o>>>0),b=l>>>1&2,k=l>>>(b>>>0),u=k>>>1&1,c=Me[vi+((s|f|o|b|u)+(k>>>(u>>>0))<<2)+304>>2],h=c,e=h>>2,d=(Se[c+4>>2]&-8)-r|0;r:for(;;)for(var d,h,w=h;;){var w,p=Se[w+16>>2];if(0==(0|p)){var E=Se[w+20>>2];if(0==(0|E))break r;var A=E}else var A=p;var A,g=(Se[A+4>>2]&-8)-r|0;if(g>>>0<d>>>0){var h=A,e=h>>2,d=g;continue r}var w=A}var y=h,m=Me[vi+16>>2],S=y>>>0<m>>>0;do if(!S){var M=y+r|0,C=M;if(y>>>0>=M>>>0)break;var R=Me[e+6],T=Me[e+3],O=(0|T)==(0|h);do if(O){var N=h+20|0,I=Se[N>>2];if(0==(0|I)){var P=h+16|0,D=Se[P>>2];if(0==(0|D)){var L=0,a=L>>2;break}var F=P,X=D}else{var F=N,X=I;i=14}for(;;){var X,F,j=X+20|0,U=Se[j>>2];if(0==(0|U)){var x=X+16|0,z=Me[x>>2];if(0==(0|z))break;var F=x,X=z}else var F=j,X=U}if(F>>>0<m>>>0)throw Ka(),"Reached an unreachable!";Se[F>>2]=0;var L=X,a=L>>2}else{var V=Me[e+2];if(V>>>0<m>>>0)throw Ka(),"Reached an unreachable!";Se[V+12>>2]=T,Se[T+8>>2]=V;var L=T,a=L>>2}while(0);var L,B=0==(0|R);r:do if(!B){var H=h+28|0,K=(Se[H>>2]<<2)+vi+304|0,Y=(0|h)==(0|Se[K>>2]);do{if(Y){if(Se[K>>2]=L,0!=(0|L))break;var G=Se[vi+4>>2]&(1<<Se[H>>2]^-1);Se[vi+4>>2]=G;break r}if(R>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";var W=R+16|0;if((0|Se[W>>2])==(0|h)?Se[W>>2]=L:Se[R+20>>2]=L,0==(0|L))break r}while(0);if(L>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+6]=R;var Z=Me[e+4];if(0!=(0|Z)){if(Z>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+4]=Z,Se[Z+24>>2]=L}var Q=Me[e+5];if(0==(0|Q))break;if(Q>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+5]=Q,Se[Q+24>>2]=L}while(0);if(d>>>0<16){var q=d+r|0;Se[e+1]=3|q;var $=q+(y+4)|0,J=1|Se[$>>2];Se[$>>2]=J}else{Se[e+1]=3|r,Se[r+(y+4)>>2]=1|d,Se[y+d+r>>2]=d;var rr=Me[vi+8>>2];if(0!=(0|rr)){var ar=Me[vi+20>>2],er=rr>>>2&1073741822,ir=(er<<2)+vi+40|0,vr=Me[vi>>2],tr=1<<(rr>>>3),fr=0==(vr&tr|0);do{if(!fr){var _r=(er+2<<2)+vi+40|0,sr=Me[_r>>2];if(sr>>>0>=Me[vi+16>>2]>>>0){var nr=sr,or=_r;break}throw Ka(),"Reached an unreachable!"}Se[vi>>2]=vr|tr;var nr=ir,or=(er+2<<2)+vi+40|0}while(0);var or,nr;Se[or>>2]=ar,Se[nr+12>>2]=ar,Se[ar+8>>2]=nr,Se[ar+12>>2]=ir}Se[vi+8>>2]=d,Se[vi+20>>2]=C}return h+8|0}while(0);throw Ka(),"Reached an unreachable!"}function aa(r){var a,e;0==(0|Se[ti>>2])&&ba();var i=0==(4&Se[vi+440>>2]|0);do{if(i){var v=Se[vi+24>>2],t=0==(0|v);do{if(!t){var f=v,_=ua(f);if(0==(0|_)){e=6;break}var s=Se[ti+8>>2],n=r+47-Se[vi+12>>2]+s&-s;if(n>>>0>=2147483647){e=14;break}var o=re(n);if((0|o)==(Se[_>>2]+Se[_+4>>2]|0)){var l=o,b=n,k=o;e=13;break}var u=o,c=n;e=15;break}e=6}while(0);do if(6==e){var h=re(0);if((0|h)==-1){e=14;break}var d=Se[ti+8>>2],w=d+(r+47)&-d,p=h,E=Se[ti+4>>2],A=E-1|0;if(0==(A&p|0))var g=w;else var g=w-p+(A+p&-E)|0;var g;if(g>>>0>=2147483647){e=14;break}var y=re(g);if((0|y)==(0|h)){var l=h,b=g,k=y;e=13;break}var u=y,c=g;e=15;break}while(0);if(13==e){var k,b,l;if((0|l)!=-1){var m=b,S=l;e=26;break}var u=k,c=b}else if(14==e){var M=4|Se[vi+440>>2];Se[vi+440>>2]=M,e=23;break}var c,u,C=0|-c,R=(0|u)!=-1&c>>>0<2147483647;do{if(R){if(c>>>0>=(r+48|0)>>>0){var T=c;e=21;break}var O=Se[ti+8>>2],N=r+47-c+O&-O;if(N>>>0>=2147483647){var T=c;e=21;break}var I=re(N);if((0|I)==-1){re(C);e=22;break}var T=N+c|0;e=21;break}var T=c;e=21}while(0);if(21==e){var T;if((0|u)!=-1){var m=T,S=u;e=26;break}}var P=4|Se[vi+440>>2];Se[vi+440>>2]=P,e=23;break}e=23}while(0);do if(23==e){var D=Se[ti+8>>2],L=D+(r+47)&-D;if(L>>>0>=2147483647){e=49;break}var F=re(L),X=re(0);if(!((0|X)!=-1&(0|F)!=-1&F>>>0<X>>>0)){e=49;break}var j=X-F|0;if(j>>>0<=(r+40|0)>>>0|(0|F)==-1){e=49;break}var m=j,S=F;e=26;break}while(0);r:do if(26==e){var S,m,U=Se[vi+432>>2]+m|0;Se[vi+432>>2]=U,U>>>0>Me[vi+436>>2]>>>0&&(Se[vi+436>>2]=U);var x=Me[vi+24>>2],z=0==(0|x);a:do if(z){var V=Me[vi+16>>2];0==(0|V)|S>>>0<V>>>0&&(Se[vi+16>>2]=S),Se[vi+444>>2]=S,Se[vi+448>>2]=m,Se[vi+456>>2]=0;var B=Se[ti>>2];Se[vi+36>>2]=B,Se[vi+32>>2]=-1,ha(),ca(S,m-40|0)}else{for(var H=vi+444|0,a=H>>2;;){var H;if(0==(0|H))break;var K=Me[a],Y=H+4|0,G=Me[Y>>2],W=K+G|0;if((0|S)==(0|W)){if(0!=(8&Se[a+3]|0))break;var Z=x;if(!(Z>>>0>=K>>>0&Z>>>0<W>>>0))break;Se[Y>>2]=G+m|0;var Q=Se[vi+24>>2],q=Se[vi+12>>2]+m|0;ca(Q,q);break a}var H=Se[a+2],a=H>>2}S>>>0<Me[vi+16>>2]>>>0&&(Se[vi+16>>2]=S);for(var $=S+m|0,J=vi+444|0;;){var J;if(0==(0|J))break;var rr=0|J,ar=Me[rr>>2];if((0|ar)==(0|$)){if(0!=(8&Se[J+12>>2]|0))break;Se[rr>>2]=S;var er=J+4|0,ir=Se[er>>2]+m|0;Se[er>>2]=ir;var vr=da(S,ar,r),tr=vr;e=50;break r}var J=Se[J+8>>2]}Ma(S,m)}while(0);var fr=Me[vi+12>>2];if(fr>>>0<=r>>>0){e=49;break}var _r=fr-r|0;Se[vi+12>>2]=_r;var sr=Me[vi+24>>2],nr=sr;Se[vi+24>>2]=nr+r|0,Se[r+(nr+4)>>2]=1|_r,Se[sr+4>>2]=3|r;var tr=sr+8|0;e=50;break}while(0);if(49==e){var or=Je();Se[or>>2]=12;var tr=0}var tr;return tr}function ea(r){var a,e,i,v,t,f,_=r>>2,s=0|-r,n=r>>>8,o=0==(0|n);do if(o)var l=0;else{if(r>>>0>16777215){var l=31;break}var b=(n+1048320|0)>>>16&8,k=n<<b,u=(k+520192|0)>>>16&4,c=k<<u,h=(c+245760|0)>>>16&2,d=14-(u|b|h)+(c<<h>>>15)|0,l=r>>>((d+7|0)>>>0)&1|d<<1}while(0);var l,w=Me[vi+(l<<2)+304>>2],p=0==(0|w);r:do if(p)var E=0,A=s,g=0;else{if(31==(0|l))var y=0;else var y=25-(l>>>1)|0;for(var y,m=0,S=s,M=w,t=M>>2,C=r<<y,R=0;;){var R,C,M,S,m,T=Se[t+1]&-8,O=T-r|0;if(O>>>0<S>>>0){if((0|T)==(0|r)){var E=M,A=O,g=M;break r}var N=M,I=O}else var N=m,I=S;var I,N,P=Me[t+5],D=Me[((C>>>31<<2)+16>>2)+t],L=0==(0|P)|(0|P)==(0|D)?R:P;if(0==(0|D)){var E=N,A=I,g=L;break r}var m=N,S=I,M=D,t=M>>2,C=C<<1,R=L}}while(0);var g,A,E,F=0==(0|g)&0==(0|E);do if(F){var X=2<<l,j=Se[vi+4>>2]&(X|-X);if(0==(0|j)){var U=g;break}var x=(j&-j)-1|0,z=x>>>12&16,V=x>>>(z>>>0),B=V>>>5&8,H=V>>>(B>>>0),K=H>>>2&4,Y=H>>>(K>>>0),G=Y>>>1&2,W=Y>>>(G>>>0),Z=W>>>1&1,U=Se[vi+((B|z|K|G|Z)+(W>>>(Z>>>0))<<2)+304>>2]}else var U=g;while(0);var U,Q=0==(0|U);r:do if(Q)var q=A,$=E,v=$>>2;else for(var J=U,i=J>>2,rr=A,ar=E;;){var ar,rr,J,er=(Se[i+1]&-8)-r|0,ir=er>>>0<rr>>>0,vr=ir?er:rr,tr=ir?J:ar,fr=Me[i+4];if(0==(0|fr)){var _r=Me[i+5];if(0==(0|_r)){var q=vr,$=tr,v=$>>2;break r}var J=_r,i=J>>2,rr=vr,ar=tr}else var J=fr,i=J>>2,rr=vr,ar=tr}while(0);var $,q,sr=0==(0|$);r:do{if(!sr){if(q>>>0>=(Se[vi+8>>2]-r|0)>>>0){var nr=0;break}var or=$,e=or>>2,lr=Me[vi+16>>2],br=or>>>0<lr>>>0;do if(!br){var kr=or+r|0,ur=kr;if(or>>>0>=kr>>>0)break;var cr=Me[v+6],hr=Me[v+3],dr=(0|hr)==(0|$);do if(dr){var wr=$+20|0,pr=Se[wr>>2];if(0==(0|pr)){var Er=$+16|0,Ar=Se[Er>>2];if(0==(0|Ar)){var gr=0,a=gr>>2;break}var yr=Er,mr=Ar}else{var yr=wr,mr=pr;f=28}for(;;){var mr,yr,Sr=mr+20|0,Mr=Se[Sr>>2];if(0==(0|Mr)){var Cr=mr+16|0,Rr=Me[Cr>>2];if(0==(0|Rr))break;var yr=Cr,mr=Rr}else var yr=Sr,mr=Mr}if(yr>>>0<lr>>>0)throw Ka(),"Reached an unreachable!";Se[yr>>2]=0;var gr=mr,a=gr>>2}else{var Tr=Me[v+2];if(Tr>>>0<lr>>>0)throw Ka(),"Reached an unreachable!";Se[Tr+12>>2]=hr,Se[hr+8>>2]=Tr;var gr=hr,a=gr>>2}while(0);var gr,Or=0==(0|cr);a:do if(!Or){var Nr=$+28|0,Ir=(Se[Nr>>2]<<2)+vi+304|0,Pr=(0|$)==(0|Se[Ir>>2]);do{if(Pr){if(Se[Ir>>2]=gr,0!=(0|gr))break;var Dr=Se[vi+4>>2]&(1<<Se[Nr>>2]^-1);Se[vi+4>>2]=Dr;break a}if(cr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";var Lr=cr+16|0;if((0|Se[Lr>>2])==(0|$)?Se[Lr>>2]=gr:Se[cr+20>>2]=gr,0==(0|gr))break a}while(0);if(gr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+6]=cr;var Fr=Me[v+4];if(0!=(0|Fr)){if(Fr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+4]=Fr,Se[Fr+24>>2]=gr}var Xr=Me[v+5];if(0==(0|Xr))break;if(Xr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+5]=Xr,Se[Xr+24>>2]=gr}while(0);var jr=q>>>0<16;a:do if(jr){var Ur=q+r|0;Se[v+1]=3|Ur;var xr=Ur+(or+4)|0,zr=1|Se[xr>>2];Se[xr>>2]=zr}else if(Se[v+1]=3|r,Se[_+(e+1)]=1|q,Se[(q>>2)+e+_]=q,q>>>0<256){var Vr=q>>>2&1073741822,Br=(Vr<<2)+vi+40|0,Hr=Me[vi>>2],Kr=1<<(q>>>3),Yr=0==(Hr&Kr|0);do{if(!Yr){var Gr=(Vr+2<<2)+vi+40|0,Wr=Me[Gr>>2];if(Wr>>>0>=Me[vi+16>>2]>>>0){var Zr=Wr,Qr=Gr;break}throw Ka(),"Reached an unreachable!"}Se[vi>>2]=Hr|Kr;var Zr=Br,Qr=(Vr+2<<2)+vi+40|0}while(0);var Qr,Zr;Se[Qr>>2]=ur,Se[Zr+12>>2]=ur,Se[_+(e+2)]=Zr,Se[_+(e+3)]=Br}else{var qr=kr,$r=q>>>8,Jr=0==(0|$r);do if(Jr)var ra=0;else{if(q>>>0>16777215){var ra=31;break}var aa=($r+1048320|0)>>>16&8,ea=$r<<aa,ia=(ea+520192|0)>>>16&4,va=ea<<ia,ta=(va+245760|0)>>>16&2,fa=14-(ia|aa|ta)+(va<<ta>>>15)|0,ra=q>>>((fa+7|0)>>>0)&1|fa<<1}while(0);var ra,_a=(ra<<2)+vi+304|0;Se[_+(e+7)]=ra;var sa=r+(or+16)|0;Se[_+(e+5)]=0,Se[sa>>2]=0;var na=Se[vi+4>>2],oa=1<<ra;if(0==(na&oa|0)){var la=na|oa;Se[vi+4>>2]=la,Se[_a>>2]=qr,Se[_+(e+6)]=_a,Se[_+(e+3)]=qr,Se[_+(e+2)]=qr}else{if(31==(0|ra))var ba=0;else var ba=25-(ra>>>1)|0;for(var ba,ka=q<<ba,ua=Se[_a>>2];;){var ua,ka;if((Se[ua+4>>2]&-8|0)==(0|q)){var ca=ua+8|0,ha=Me[ca>>2],da=Me[vi+16>>2],wa=ua>>>0<da>>>0;do if(!wa){if(ha>>>0<da>>>0)break;Se[ha+12>>2]=qr,Se[ca>>2]=qr,Se[_+(e+2)]=ha,Se[_+(e+3)]=ua,Se[_+(e+6)]=0;break a}while(0);throw Ka(),"Reached an unreachable!"}var pa=(ka>>>31<<2)+ua+16|0,Ea=Me[pa>>2];if(0==(0|Ea)){if(pa>>>0>=Me[vi+16>>2]>>>0){Se[pa>>2]=qr,Se[_+(e+6)]=ua,Se[_+(e+3)]=qr,Se[_+(e+2)]=qr;break a}throw Ka(),"Reached an unreachable!"}var ka=ka<<1,ua=Ea}}}while(0);var nr=$+8|0;break r}while(0);throw Ka(),"Reached an unreachable!"}var nr=0}while(0);var nr;return nr}function ia(r){var a;0==(0|Se[ti>>2])&&ba();var e=r>>>0<4294967232;r:do if(e){var i=Me[vi+24>>2];if(0==(0|i)){var v=0;break}var t=Me[vi+12>>2],f=t>>>0>(r+40|0)>>>0;do if(f){var _=Me[ti+8>>2],s=-40-r-1+t+_|0,n=Math.floor((s>>>0)/(_>>>0)),o=(n-1)*_|0,l=i,b=ua(l);if(0!=(8&Se[b+12>>2]|0))break;var k=re(0),a=(b+4|0)>>2;if((0|k)!=(Se[b>>2]+Se[a]|0))break;var u=o>>>0>2147483646?-2147483648-_|0:o,c=0|-u,h=re(c),d=re(0);if(!((0|h)!=-1&d>>>0<k>>>0))break;var w=k-d|0;if((0|k)==(0|d))break;var p=Se[a]-w|0;Se[a]=p;var E=Se[vi+432>>2]-w|0;Se[vi+432>>2]=E;var A=Se[vi+24>>2],g=Se[vi+12>>2]-w|0;ca(A,g);var v=(0|k)!=(0|d);break r}while(0);if(Me[vi+12>>2]>>>0<=Me[vi+28>>2]>>>0){var v=0;break}Se[vi+28>>2]=-1;var v=0}else var v=0;while(0);var v;return 1&v}function va(r){var a,e,i,v,t,f,_,s=r>>2,n=0==(0|r);r:do if(!n){var o=r-8|0,l=o,b=Me[vi+16>>2],k=o>>>0<b>>>0;a:do if(!k){var u=Me[r-4>>2],c=3&u;if(1==(0|c))break;var h=u&-8,f=h>>2,d=r+(h-8)|0,w=d,p=0==(1&u|0);e:do if(p){var E=Me[o>>2];if(0==(0|c))break r;var A=-8-E|0,t=A>>2,g=r+A|0,y=g,m=E+h|0;if(g>>>0<b>>>0)break a;if((0|y)==(0|Se[vi+20>>2])){var v=(r+(h-4)|0)>>2;if(3!=(3&Se[v]|0)){var S=y,i=S>>2,M=m;break}Se[vi+8>>2]=m;var C=Se[v]&-2;Se[v]=C,Se[t+(s+1)]=1|m,Se[d>>2]=m;break r}if(E>>>0<256){var R=Me[t+(s+2)],T=Me[t+(s+3)];if((0|R)!=(0|T)){var O=((E>>>2&1073741822)<<2)+vi+40|0,N=(0|R)!=(0|O)&R>>>0<b>>>0;do if(!N){if(!((0|T)==(0|O)|T>>>0>=b>>>0))break;Se[R+12>>2]=T,Se[T+8>>2]=R;var S=y,i=S>>2,M=m;break e}while(0);throw Ka(),"Reached an unreachable!"}var I=Se[vi>>2]&(1<<(E>>>3)^-1);Se[vi>>2]=I;var S=y,i=S>>2,M=m}else{var P=g,D=Me[t+(s+6)],L=Me[t+(s+3)],F=(0|L)==(0|P);do if(F){var X=A+(r+20)|0,j=Se[X>>2];if(0==(0|j)){var U=A+(r+16)|0,x=Se[U>>2];if(0==(0|x)){var z=0,e=z>>2;break}var V=U,B=x}else{var V=X,B=j;_=21}for(;;){var B,V,H=B+20|0,K=Se[H>>2];if(0==(0|K)){var Y=B+16|0,G=Me[Y>>2];if(0==(0|G))break;var V=Y,B=G}else var V=H,B=K}if(V>>>0<b>>>0)throw Ka(),"Reached an unreachable!";Se[V>>2]=0;var z=B,e=z>>2}else{var W=Me[t+(s+2)];if(W>>>0<b>>>0)throw Ka(),"Reached an unreachable!";Se[W+12>>2]=L,Se[L+8>>2]=W;var z=L,e=z>>2}while(0);var z;if(0==(0|D)){var S=y,i=S>>2,M=m;break}var Z=A+(r+28)|0,Q=(Se[Z>>2]<<2)+vi+304|0,q=(0|P)==(0|Se[Q>>2]);do{if(q){if(Se[Q>>2]=z,0!=(0|z))break;var $=Se[vi+4>>2]&(1<<Se[Z>>2]^-1);Se[vi+4>>2]=$;var S=y,i=S>>2,M=m;break e}if(D>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";var J=D+16|0;if((0|Se[J>>2])==(0|P)?Se[J>>2]=z:Se[D+20>>2]=z,0==(0|z)){var S=y,i=S>>2,M=m;break e}}while(0);if(z>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[e+6]=D;var rr=Me[t+(s+4)];if(0!=(0|rr)){if(rr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[e+4]=rr,Se[rr+24>>2]=z}var ar=Me[t+(s+5)];if(0==(0|ar)){var S=y,i=S>>2,M=m;break}if(ar>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[e+5]=ar,Se[ar+24>>2]=z;var S=y,i=S>>2,M=m}}else var S=l,i=S>>2,M=h;while(0);var M,S,er=S;if(er>>>0>=d>>>0)break;var ir=r+(h-4)|0,vr=Me[ir>>2];if(0==(1&vr|0))break;var tr=0==(2&vr|0);do{if(tr){if((0|w)==(0|Se[vi+24>>2])){var fr=Se[vi+12>>2]+M|0;Se[vi+12>>2]=fr,Se[vi+24>>2]=S;var _r=1|fr;if(Se[i+1]=_r,(0|S)==(0|Se[vi+20>>2])&&(Se[vi+20>>2]=0,Se[vi+8>>2]=0),fr>>>0<=Me[vi+28>>2]>>>0)break r;ia(0);break r}if((0|w)==(0|Se[vi+20>>2])){var sr=Se[vi+8>>2]+M|0;Se[vi+8>>2]=sr,Se[vi+20>>2]=S;var nr=1|sr;Se[i+1]=nr;var or=er+sr|0;Se[or>>2]=sr;break r}var lr=(vr&-8)+M|0,br=vr>>>3,kr=vr>>>0<256;e:do if(kr){var ur=Me[s+f],cr=Me[((4|h)>>2)+s];if((0|ur)!=(0|cr)){var hr=((vr>>>2&1073741822)<<2)+vi+40|0,dr=(0|ur)==(0|hr);do{if(!dr){if(ur>>>0<Me[vi+16>>2]>>>0){_=66;break}_=63;break}_=63}while(0);do if(63==_){if((0|cr)!=(0|hr)&&cr>>>0<Me[vi+16>>2]>>>0)break;Se[ur+12>>2]=cr,Se[cr+8>>2]=ur;break e}while(0);throw Ka(),"Reached an unreachable!"}var wr=Se[vi>>2]&(1<<br^-1);Se[vi>>2]=wr}else{var pr=d,Er=Me[f+(s+4)],Ar=Me[((4|h)>>2)+s],gr=(0|Ar)==(0|pr);do if(gr){var yr=h+(r+12)|0,mr=Se[yr>>2];if(0==(0|mr)){var Sr=h+(r+8)|0,Mr=Se[Sr>>2];if(0==(0|Mr)){var Cr=0,a=Cr>>2;break}var Rr=Sr,Tr=Mr}else{var Rr=yr,Tr=mr;_=73}for(;;){var Tr,Rr,Or=Tr+20|0,Nr=Se[Or>>2];if(0==(0|Nr)){var Ir=Tr+16|0,Pr=Me[Ir>>2];if(0==(0|Pr))break;var Rr=Ir,Tr=Pr}else var Rr=Or,Tr=Nr}if(Rr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[Rr>>2]=0;var Cr=Tr,a=Cr>>2}else{var Dr=Me[s+f];if(Dr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[Dr+12>>2]=Ar,\nSe[Ar+8>>2]=Dr;var Cr=Ar,a=Cr>>2}while(0);var Cr;if(0==(0|Er))break;var Lr=h+(r+20)|0,Fr=(Se[Lr>>2]<<2)+vi+304|0,Xr=(0|pr)==(0|Se[Fr>>2]);do{if(Xr){if(Se[Fr>>2]=Cr,0!=(0|Cr))break;var jr=Se[vi+4>>2]&(1<<Se[Lr>>2]^-1);Se[vi+4>>2]=jr;break e}if(Er>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";var Ur=Er+16|0;if((0|Se[Ur>>2])==(0|pr)?Se[Ur>>2]=Cr:Se[Er+20>>2]=Cr,0==(0|Cr))break e}while(0);if(Cr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+6]=Er;var xr=Me[f+(s+2)];if(0!=(0|xr)){if(xr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+4]=xr,Se[xr+24>>2]=Cr}var zr=Me[f+(s+3)];if(0==(0|zr))break;if(zr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[a+5]=zr,Se[zr+24>>2]=Cr}while(0);if(Se[i+1]=1|lr,Se[er+lr>>2]=lr,(0|S)!=(0|Se[vi+20>>2])){var Vr=lr;break}Se[vi+8>>2]=lr;break r}Se[ir>>2]=vr&-2,Se[i+1]=1|M,Se[er+M>>2]=M;var Vr=M}while(0);var Vr;if(Vr>>>0<256){var Br=Vr>>>2&1073741822,Hr=(Br<<2)+vi+40|0,Kr=Me[vi>>2],Yr=1<<(Vr>>>3),Gr=0==(Kr&Yr|0);do{if(!Gr){var Wr=(Br+2<<2)+vi+40|0,Zr=Me[Wr>>2];if(Zr>>>0>=Me[vi+16>>2]>>>0){var Qr=Zr,qr=Wr;break}throw Ka(),"Reached an unreachable!"}Se[vi>>2]=Kr|Yr;var Qr=Hr,qr=(Br+2<<2)+vi+40|0}while(0);var qr,Qr;Se[qr>>2]=S,Se[Qr+12>>2]=S,Se[i+2]=Qr,Se[i+3]=Hr;break r}var $r=S,Jr=Vr>>>8,ra=0==(0|Jr);do if(ra)var aa=0;else{if(Vr>>>0>16777215){var aa=31;break}var ea=(Jr+1048320|0)>>>16&8,va=Jr<<ea,fa=(va+520192|0)>>>16&4,_a=va<<fa,sa=(_a+245760|0)>>>16&2,na=14-(fa|ea|sa)+(_a<<sa>>>15)|0,aa=Vr>>>((na+7|0)>>>0)&1|na<<1}while(0);var aa,oa=(aa<<2)+vi+304|0;Se[i+7]=aa,Se[i+5]=0,Se[i+4]=0;var la=Se[vi+4>>2],ba=1<<aa,ka=0==(la&ba|0);e:do if(ka){var ua=la|ba;Se[vi+4>>2]=ua,Se[oa>>2]=$r,Se[i+6]=oa,Se[i+3]=S,Se[i+2]=S}else{if(31==(0|aa))var ca=0;else var ca=25-(aa>>>1)|0;for(var ca,ha=Vr<<ca,da=Se[oa>>2];;){var da,ha;if((Se[da+4>>2]&-8|0)==(0|Vr)){var wa=da+8|0,pa=Me[wa>>2],Ea=Me[vi+16>>2],Aa=da>>>0<Ea>>>0;do if(!Aa){if(pa>>>0<Ea>>>0)break;Se[pa+12>>2]=$r,Se[wa>>2]=$r,Se[i+2]=pa,Se[i+3]=da,Se[i+6]=0;break e}while(0);throw Ka(),"Reached an unreachable!"}var ga=(ha>>>31<<2)+da+16|0,ya=Me[ga>>2];if(0==(0|ya)){if(ga>>>0>=Me[vi+16>>2]>>>0){Se[ga>>2]=$r,Se[i+6]=da,Se[i+3]=S,Se[i+2]=S;break e}throw Ka(),"Reached an unreachable!"}var ha=ha<<1,da=ya}}while(0);var ma=Se[vi+32>>2]-1|0;if(Se[vi+32>>2]=ma,0!=(0|ma))break r;ta();break r}while(0);throw Ka(),"Reached an unreachable!"}while(0)}function ta(){var r=Se[vi+452>>2],a=0==(0|r);r:do if(!a)for(var e=r;;){var e,i=Se[e+8>>2];if(0==(0|i))break r;var e=i}while(0);Se[vi+32>>2]=-1}function fa(r,a){if(0==(0|r))var e=Jr(a),i=e;else var v=la(r,a),i=v;var i;return i}function _a(r,a){var e,i=r>>>0<9;do if(i)var v=Jr(a),t=v;else{var f=r>>>0<16?16:r,_=0==(f-1&f|0);r:do if(_)var s=f;else{if(f>>>0<=16){var s=16;break}for(var n=16;;){var n,o=n<<1;if(o>>>0>=f>>>0){var s=o;break r}var n=o}}while(0);var s;if((-64-s|0)>>>0>a>>>0){if(a>>>0<11)var l=16;else var l=a+11&-8;var l,b=Jr(l+(s+12)|0);if(0==(0|b)){var t=0;break}var k=b-8|0;if(0==((b>>>0)%(s>>>0)|0))var u=k,c=0;else{var h=b+(s-1)&-s,d=h-8|0,w=k;if((d-w|0)>>>0>15)var p=d;else var p=h+(s-8)|0;var p,E=p-w|0,e=(b-4|0)>>2,A=Se[e],g=(A&-8)-E|0;if(0==(3&A|0)){var y=Se[k>>2]+E|0;Se[p>>2]=y,Se[p+4>>2]=g;var u=p,c=0}else{var m=p+4|0,S=g|1&Se[m>>2]|2;Se[m>>2]=S;var M=g+(p+4)|0,C=1|Se[M>>2];Se[M>>2]=C;var R=E|1&Se[e]|2;Se[e]=R;var T=b+(E-4)|0,O=1|Se[T>>2];Se[T>>2]=O;var u=p,c=b}}var c,u,N=u+4|0,I=Me[N>>2],P=0==(3&I|0);do if(P)var D=0;else{var L=I&-8;if(L>>>0<=(l+16|0)>>>0){var D=0;break}var F=L-l|0;Se[N>>2]=l|1&I|2,Se[u+(4|l)>>2]=3|F;var X=u+(4|L)|0,j=1|Se[X>>2];Se[X>>2]=j;var D=l+(u+8)|0}while(0);var D;0!=(0|c)&&va(c),0!=(0|D)&&va(D);var t=u+8|0}else{var U=Je();Se[U>>2]=12;var t=0}}while(0);var t;return t}function sa(r,a,e,i){var v,t;0==(0|Se[ti>>2])&&ba();var f=0==(0|i),_=0==(0|r);do{if(f){if(_){var s=Jr(0),n=s;t=30;break}var o=r<<2;if(o>>>0<11){var l=0,b=16;t=9;break}var l=0,b=o+11&-8;t=9;break}if(_){var n=i;t=30;break}var l=i,b=0;t=9;break}while(0);do if(9==t){var b,l,k=0==(1&e|0);r:do if(k){if(_){var u=0,c=0;break}for(var h=0,d=0;;){var d,h,w=Me[a+(d<<2)>>2];if(w>>>0<11)var p=16;else var p=w+11&-8;var p,E=p+h|0,A=d+1|0;if((0|A)==(0|r)){var u=0,c=E;break r}var h=E,d=A}}else{var g=Me[a>>2];if(g>>>0<11)var y=16;else var y=g+11&-8;var y,u=y,c=y*r|0}while(0);var c,u,m=Jr(b-4+c|0);if(0==(0|m)){var n=0;break}var S=m-8|0,M=Se[m-4>>2]&-8;if(0!=(2&e|0)){var C=-4-b+M|0;Fa(m,0,C,1)}if(0==(0|l)){var R=m+c|0,T=M-c|3;Se[m+(c-4)>>2]=T;var O=R,v=O>>2,N=c}else var O=l,v=O>>2,N=M;var N,O;Se[v]=m;var I=r-1|0,P=0==(0|I);r:do if(P)var D=S,L=N;else if(0==(0|u))for(var F=S,X=N,j=0;;){var j,X,F,U=Me[a+(j<<2)>>2];if(U>>>0<11)var x=16;else var x=U+11&-8;var x,z=X-x|0;Se[F+4>>2]=3|x;var V=F+x|0,B=j+1|0;if(Se[(B<<2>>2)+v]=x+(F+8)|0,(0|B)==(0|I)){var D=V,L=z;break r}var F=V,X=z,j=B}else for(var H=3|u,K=u+8|0,Y=S,G=N,W=0;;){var W,G,Y,Z=G-u|0;Se[Y+4>>2]=H;var Q=Y+u|0,q=W+1|0;if(Se[(q<<2>>2)+v]=Y+K|0,(0|q)==(0|I)){var D=Q,L=Z;break r}var Y=Q,G=Z,W=q}while(0);var L,D;Se[D+4>>2]=3|L;var n=O}while(0);var n;return n}function na(r){var a=r>>2;0==(0|Se[ti>>2])&&ba();var e=Me[vi+24>>2];if(0==(0|e))var i=0,v=0,t=0,f=0,_=0,s=0,n=0;else{for(var o=Me[vi+12>>2],l=o+40|0,b=vi+444|0,k=l,u=l,c=1;;){var c,u,k,b,h=Me[b>>2],d=h+8|0;if(0==(7&d|0))var w=0;else var w=7&-d;for(var w,p=b+4|0,E=h+w|0,A=c,g=u,y=k;;){var y,g,A,E;if(E>>>0<h>>>0)break;if(E>>>0>=(h+Se[p>>2]|0)>>>0|(0|E)==(0|e))break;var m=Se[E+4>>2];if(7==(0|m))break;var S=m&-8,M=S+y|0;if(1==(3&m|0))var C=A+1|0,R=S+g|0;else var C=A,R=g;var R,C,E=E+S|0,A=C,g=R,y=M}var T=Me[b+8>>2];if(0==(0|T))break;var b=T,k=y,u=g,c=A}var O=Se[vi+432>>2],i=y,v=A,t=o,f=g,_=O-y|0,s=Se[vi+436>>2],n=O-g|0}var n,s,_,f,t,v,i;Se[a]=i,Se[a+1]=v,Se[a+2]=0,Se[a+3]=0,Se[a+4]=_,Se[a+5]=s,Se[a+6]=0,Se[a+7]=n,Se[a+8]=f,Se[a+9]=t}function oa(){0==(0|Se[ti>>2])&&ba();var r=Me[vi+24>>2],a=0==(0|r);r:do if(a)var e=0,i=0,v=0;else for(var t=Se[vi+436>>2],f=Me[vi+432>>2],_=vi+444|0,s=f-40-Se[vi+12>>2]|0;;){var s,_,n=Me[_>>2],o=n+8|0;if(0==(7&o|0))var l=0;else var l=7&-o;for(var l,b=_+4|0,k=n+l|0,u=s;;){var u,k;if(k>>>0<n>>>0)break;if(k>>>0>=(n+Se[b>>2]|0)>>>0|(0|k)==(0|r))break;var c=Se[k+4>>2];if(7==(0|c))break;var h=c&-8,d=1==(3&c|0)?h:0,w=u-d|0,k=k+h|0,u=w}var p=Me[_+8>>2];if(0==(0|p)){var e=t,i=f,v=u;break r}var _=p,s=u}while(0);var v,i,e,E=Se[Se[qe>>2]+12>>2],A=(Qa(E,0|He.__str339,(ne=Oe,Oe+=4,Se[ne>>2]=e,ne)),Se[Se[qe>>2]+12>>2]),g=(Qa(A,0|He.__str1340,(ne=Oe,Oe+=4,Se[ne>>2]=i,ne)),Se[Se[qe>>2]+12>>2]);Qa(g,0|He.__str2341,(ne=Oe,Oe+=4,Se[ne>>2]=v,ne))}function la(r,a){var e,i,v,t=a>>>0>4294967231;r:do{if(!t){var f=r-8|0,_=f,i=(r-4|0)>>2,s=Me[i],n=s&-8,o=n-8|0,l=r+o|0,b=f>>>0<Me[vi+16>>2]>>>0;do if(!b){var k=3&s;if(!(1!=(0|k)&(0|o)>-8))break;var e=(r+(n-4)|0)>>2;if(0==(1&Se[e]|0))break;if(a>>>0<11)var u=16;else var u=a+11&-8;var u,c=0==(0|k);do{if(c){var h=ka(_,u),d=0,w=h;v=17;break}if(n>>>0<u>>>0){if((0|l)!=(0|Se[vi+24>>2])){v=21;break}var p=Se[vi+12>>2]+n|0;if(p>>>0<=u>>>0){v=21;break}var E=p-u|0,A=r+(u-8)|0;Se[i]=u|1&s|2;var g=1|E;Se[r+(u-4)>>2]=g,Se[vi+24>>2]=A,Se[vi+12>>2]=E;var d=0,w=_;v=17;break}var y=n-u|0;if(y>>>0<=15){var d=0,w=_;v=17;break}Se[i]=u|1&s|2,Se[r+(u-4)>>2]=3|y;var m=1|Se[e];Se[e]=m;var d=r+u|0,w=_;v=17;break}while(0);do if(17==v){var w,d;if(0==(0|w))break;0!=(0|d)&&va(d);var S=w+8|0;break r}while(0);var M=Jr(a);if(0==(0|M)){var S=0;break r}var C=0==(3&Se[i]|0)?8:4,R=n-C|0,T=R>>>0<a>>>0?R:a;Pa(M,r,T,1),va(r);var S=M;break r}while(0);throw Ka(),"Reached an unreachable!"}var O=Je();Se[O>>2]=12;var S=0}while(0);var S;return S}function ba(){if(0==(0|Se[ti>>2])){var r=qa(8);if(0!=(r-1&r|0))throw Ka(),"Reached an unreachable!";Se[ti+8>>2]=r,Se[ti+4>>2]=r,Se[ti+12>>2]=-1,Se[ti+16>>2]=2097152,Se[ti+20>>2]=0,Se[vi+440>>2]=0;var a=$a(0);Se[ti>>2]=a&-16^1431655768}}function ka(r,a){var e=Se[r+4>>2]&-8,i=a>>>0<256;do if(i)var v=0;else{if(e>>>0>=(a+4|0)>>>0&&(e-a|0)>>>0<=Se[ti+8>>2]<<1>>>0){var v=r;break}var v=0}while(0);var v;return v}function ua(r){for(var a,e=vi+444|0,a=e>>2;;){var e,i=Me[a];if(i>>>0<=r>>>0&&(i+Se[a+1]|0)>>>0>r>>>0){var v=e;break}var t=Me[a+2];if(0==(0|t)){var v=0;break}var e=t,a=e>>2}var v;return v}function ca(r,a){var e=r,i=r+8|0;if(0==(7&i|0))var v=0;else var v=7&-i;var v,t=a-v|0;Se[vi+24>>2]=e+v|0,Se[vi+12>>2]=t,Se[v+(e+4)>>2]=1|t,Se[a+(e+4)>>2]=40;var f=Se[ti+16>>2];Se[vi+28>>2]=f}function ha(){for(var r=0;;){var r,a=r<<1,e=(a<<2)+vi+40|0;Se[vi+(a+3<<2)+40>>2]=e,Se[vi+(a+2<<2)+40>>2]=e;var i=r+1|0;if(32==(0|i))break;var r=i}}function da(r,a,e){var i,v,t,f,_=a>>2,s=r>>2,n=r+8|0;if(0==(7&n|0))var o=0;else var o=7&-n;var o,l=a+8|0;if(0==(7&l|0))var b=0,t=b>>2;else var b=7&-l,t=b>>2;var b,k=a+b|0,u=k,c=o+e|0,v=c>>2,h=r+c|0,d=h,w=k-(r+o)-e|0;Se[(o+4>>2)+s]=3|e;var p=(0|u)==(0|Se[vi+24>>2]);r:do if(p){var E=Se[vi+12>>2]+w|0;Se[vi+12>>2]=E,Se[vi+24>>2]=d;var A=1|E;Se[v+(s+1)]=A}else if((0|u)==(0|Se[vi+20>>2])){var g=Se[vi+8>>2]+w|0;Se[vi+8>>2]=g,Se[vi+20>>2]=d;var y=1|g;Se[v+(s+1)]=y;var m=r+g+c|0;Se[m>>2]=g}else{var S=Me[t+(_+1)];if(1==(3&S|0)){var M=S&-8,C=S>>>3,R=S>>>0<256;a:do if(R){var T=Me[((8|b)>>2)+_],O=Me[t+(_+3)];if((0|T)!=(0|O)){var N=((S>>>2&1073741822)<<2)+vi+40|0,I=(0|T)==(0|N);do{if(!I){if(T>>>0<Me[vi+16>>2]>>>0){f=18;break}f=15;break}f=15}while(0);do if(15==f){if((0|O)!=(0|N)&&O>>>0<Me[vi+16>>2]>>>0)break;Se[T+12>>2]=O,Se[O+8>>2]=T;break a}while(0);throw Ka(),"Reached an unreachable!"}var P=Se[vi>>2]&(1<<C^-1);Se[vi>>2]=P}else{var D=k,L=Me[((24|b)>>2)+_],F=Me[t+(_+3)],X=(0|F)==(0|D);do if(X){var j=16|b,U=j+(a+4)|0,x=Se[U>>2];if(0==(0|x)){var z=a+j|0,V=Se[z>>2];if(0==(0|V)){var B=0,i=B>>2;break}var H=z,K=V}else{var H=U,K=x;f=25}for(;;){var K,H,Y=K+20|0,G=Se[Y>>2];if(0==(0|G)){var W=K+16|0,Z=Me[W>>2];if(0==(0|Z))break;var H=W,K=Z}else var H=Y,K=G}if(H>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[H>>2]=0;var B=K,i=B>>2}else{var Q=Me[((8|b)>>2)+_];if(Q>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[Q+12>>2]=F,Se[F+8>>2]=Q;var B=F,i=B>>2}while(0);var B;if(0==(0|L))break;var q=b+(a+28)|0,$=(Se[q>>2]<<2)+vi+304|0,J=(0|D)==(0|Se[$>>2]);do{if(J){if(Se[$>>2]=B,0!=(0|B))break;var rr=Se[vi+4>>2]&(1<<Se[q>>2]^-1);Se[vi+4>>2]=rr;break a}if(L>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";var ar=L+16|0;if((0|Se[ar>>2])==(0|D)?Se[ar>>2]=B:Se[L+20>>2]=B,0==(0|B))break a}while(0);if(B>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[i+6]=L;var er=16|b,ir=Me[(er>>2)+_];if(0!=(0|ir)){if(ir>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[i+4]=ir,Se[ir+24>>2]=B}var vr=Me[(er+4>>2)+_];if(0==(0|vr))break;if(vr>>>0<Me[vi+16>>2]>>>0)throw Ka(),"Reached an unreachable!";Se[i+5]=vr,Se[vr+24>>2]=B}while(0);var tr=a+(M|b)|0,fr=M+w|0}else var tr=u,fr=w;var fr,tr,_r=tr+4|0,sr=Se[_r>>2]&-2;if(Se[_r>>2]=sr,Se[v+(s+1)]=1|fr,Se[(fr>>2)+s+v]=fr,fr>>>0<256){var nr=fr>>>2&1073741822,or=(nr<<2)+vi+40|0,lr=Me[vi>>2],br=1<<(fr>>>3),kr=0==(lr&br|0);do{if(!kr){var ur=(nr+2<<2)+vi+40|0,cr=Me[ur>>2];if(cr>>>0>=Me[vi+16>>2]>>>0){var hr=cr,dr=ur;break}throw Ka(),"Reached an unreachable!"}Se[vi>>2]=lr|br;var hr=or,dr=(nr+2<<2)+vi+40|0}while(0);var dr,hr;Se[dr>>2]=d,Se[hr+12>>2]=d,Se[v+(s+2)]=hr,Se[v+(s+3)]=or}else{var wr=h,pr=fr>>>8,Er=0==(0|pr);do if(Er)var Ar=0;else{if(fr>>>0>16777215){var Ar=31;break}var gr=(pr+1048320|0)>>>16&8,yr=pr<<gr,mr=(yr+520192|0)>>>16&4,Sr=yr<<mr,Mr=(Sr+245760|0)>>>16&2,Cr=14-(mr|gr|Mr)+(Sr<<Mr>>>15)|0,Ar=fr>>>((Cr+7|0)>>>0)&1|Cr<<1}while(0);var Ar,Rr=(Ar<<2)+vi+304|0;Se[v+(s+7)]=Ar;var Tr=c+(r+16)|0;Se[v+(s+5)]=0,Se[Tr>>2]=0;var Or=Se[vi+4>>2],Nr=1<<Ar;if(0==(Or&Nr|0)){var Ir=Or|Nr;Se[vi+4>>2]=Ir,Se[Rr>>2]=wr,Se[v+(s+6)]=Rr,Se[v+(s+3)]=wr,Se[v+(s+2)]=wr}else{if(31==(0|Ar))var Pr=0;else var Pr=25-(Ar>>>1)|0;for(var Pr,Dr=fr<<Pr,Lr=Se[Rr>>2];;){var Lr,Dr;if((Se[Lr+4>>2]&-8|0)==(0|fr)){var Fr=Lr+8|0,Xr=Me[Fr>>2],jr=Me[vi+16>>2],Ur=Lr>>>0<jr>>>0;do if(!Ur){if(Xr>>>0<jr>>>0)break;Se[Xr+12>>2]=wr,Se[Fr>>2]=wr,Se[v+(s+2)]=Xr,Se[v+(s+3)]=Lr,Se[v+(s+6)]=0;break r}while(0);throw Ka(),"Reached an unreachable!"}var xr=(Dr>>>31<<2)+Lr+16|0,zr=Me[xr>>2];if(0==(0|zr)){if(xr>>>0>=Me[vi+16>>2]>>>0){Se[xr>>2]=wr,Se[v+(s+6)]=Lr,Se[v+(s+3)]=wr,Se[v+(s+2)]=wr;break r}throw Ka(),"Reached an unreachable!"}var Dr=Dr<<1,Lr=zr}}}}while(0);return r+(8|o)|0}function wa(r){return 0|He.__str3342}function pa(r){return 0|He.__str14343}function Ea(r){Se[r>>2]=si+8|0}function Aa(r){0!=(0|r)&&va(r)}function ga(r){ya(r);var a=r;Aa(a)}function ya(r){var a=0|r;Ye(a)}function ma(r){var a=0|r;Ea(a),Se[r>>2]=ni+8|0}function Sa(r){var a=0|r;ya(a);var e=r;Aa(e)}function Ma(r,a){var e,i,v=Me[vi+24>>2],i=v>>2,t=v,f=ua(t),_=Se[f>>2],s=Se[f+4>>2],n=_+s|0,o=_+(s-39)|0;if(0==(7&o|0))var l=0;else var l=7&-o;var l,b=_+(s-47)+l|0,k=b>>>0<(v+16|0)>>>0?t:b,u=k+8|0,e=u>>2,c=u,h=r,d=a-40|0;ca(h,d);var w=k+4|0;Se[w>>2]=27,Se[e]=Se[vi+444>>2],Se[e+1]=Se[vi+448>>2],Se[e+2]=Se[vi+452>>2],Se[e+3]=Se[vi+456>>2],Se[vi+444>>2]=r,Se[vi+448>>2]=a,Se[vi+456>>2]=0,Se[vi+452>>2]=c;var p=k+28|0;Se[p>>2]=7;var E=(k+32|0)>>>0<n>>>0;r:do if(E)for(var A=p;;){var A,g=A+4|0;if(Se[g>>2]=7,(A+8|0)>>>0>=n>>>0)break r;var A=g}while(0);var y=(0|k)==(0|t);r:do if(!y){var m=k-v|0,S=t+m|0,M=m+(t+4)|0,C=Se[M>>2]&-2;Se[M>>2]=C;var R=1|m;Se[i+1]=R;var T=S;if(Se[T>>2]=m,m>>>0<256){var O=m>>>2&1073741822,N=(O<<2)+vi+40|0,I=Me[vi>>2],P=1<<(m>>>3),D=0==(I&P|0);do{if(!D){var L=(O+2<<2)+vi+40|0,F=Me[L>>2];if(F>>>0>=Me[vi+16>>2]>>>0){var X=F,j=L;break}throw Ka(),"Reached an unreachable!"}var U=I|P;Se[vi>>2]=U;var X=N,j=(O+2<<2)+vi+40|0}while(0);var j,X;Se[j>>2]=v,Se[X+12>>2]=v,Se[i+2]=X,Se[i+3]=N}else{var x=v,z=m>>>8,V=0==(0|z);do if(V)var B=0;else{if(m>>>0>16777215){var B=31;break}var H=(z+1048320|0)>>>16&8,K=z<<H,Y=(K+520192|0)>>>16&4,G=K<<Y,W=(G+245760|0)>>>16&2,Z=14-(Y|H|W)+(G<<W>>>15)|0,B=m>>>((Z+7|0)>>>0)&1|Z<<1}while(0);var B,Q=(B<<2)+vi+304|0;Se[i+7]=B,Se[i+5]=0,Se[i+4]=0;var q=Se[vi+4>>2],$=1<<B;if(0==(q&$|0)){var J=q|$;Se[vi+4>>2]=J,Se[Q>>2]=x,Se[i+6]=Q,Se[i+3]=v,Se[i+2]=v}else{if(31==(0|B))var rr=0;else var rr=25-(B>>>1)|0;for(var rr,ar=m<<rr,er=Se[Q>>2];;){var er,ar;if((Se[er+4>>2]&-8|0)==(0|m)){var ir=er+8|0,vr=Me[ir>>2],tr=Me[vi+16>>2],fr=er>>>0<tr>>>0;do if(!fr){if(vr>>>0<tr>>>0)break;Se[vr+12>>2]=x,Se[ir>>2]=x,Se[i+2]=vr,Se[i+3]=er,Se[i+6]=0;break r}while(0);throw Ka(),"Reached an unreachable!"}var _r=(ar>>>31<<2)+er+16|0,sr=Me[_r>>2];if(0==(0|sr)){if(_r>>>0>=Me[vi+16>>2]>>>0){Se[_r>>2]=x,Se[i+6]=er,Se[i+3]=v,Se[i+2]=v;break r}throw Ka(),"Reached an unreachable!"}var ar=ar<<1,er=sr}}}}while(0)}function Ca(r){return d(r)}function Ra(r,a){var e=0;do Ae[r+e]=Ae[a+e],e++;while(0!=Ae[a+e-1]);return r}function Ta(){var r=Ta;return r.LLVM_SAVEDSTACKS||(r.LLVM_SAVEDSTACKS=[]),r.LLVM_SAVEDSTACKS.push(le.stackSave()),r.LLVM_SAVEDSTACKS.length-1}function Oa(r){var a=Ta,e=a.LLVM_SAVEDSTACKS[r];a.LLVM_SAVEDSTACKS.splice(r,1),le.stackRestore(e)}function Na(r,a,e){for(var i=0;i<e;){var v=Ae[r+i],t=Ae[a+i];if(v==t&&0==v)return 0;if(0==v)return-1;if(0==t)return 1;if(v!=t)return v>t?1:-1;i++}return 0}function Ia(r,a){var e=Ca(r),i=0;do Ae[r+e+i]=Ae[a+i],i++;while(0!=Ae[a+i-1]);return r}function Pa(r,a,e,i){if(e>=20&&a%2==r%2)if(a%4==r%4){for(var v=a+e;a%4;)Ae[r++]=Ae[a++];for(var t=a>>2,f=r>>2,_=v>>2;t<_;)Se[f++]=Se[t++];for(a=t<<2,r=f<<2;a<v;)Ae[r++]=Ae[a++]}else{var v=a+e;a%2&&(Ae[r++]=Ae[a++]);for(var s=a>>1,n=r>>1,o=v>>1;s<o;)ye[n++]=ye[s++];a=s<<1,r=n<<1,a<v&&(Ae[r++]=Ae[a++])}else for(;e--;)Ae[r++]=Ae[a++]}function Da(r,a){return Na(r,a,Le)}function La(r,a,e){for(var i=0;i<e;i++){var v=Ae[r+i],t=Ae[a+i];if(v!=t)return v>t?1:-1}return 0}function Fa(r,a,e,i){if(e>=20){for(var v=r+e;r%4;)Ae[r++]=a;a<0&&(a+=256);for(var t=r>>2,f=v>>2,_=a|a<<8|a<<16|a<<24;t<f;)Se[t++]=_;for(r=t<<2;r<v;)Ae[r++]=a}else for(;e--;)Ae[r++]=a}function Xa(r,a,e,i){throw"Assertion failed: "+s(i)+", at: "+[s(r),a,s(e)]}function ja(r){var a=d(r),e=Jr(a+1);return Pa(e,r,a,1),Ae[e+a]=0,e}function Ua(r,a){function e(r){var e;return"double"===r?(xe[0]=Se[a+_>>2],xe[1]=Se[a+_+4>>2],e=ze[0]):"i64"==r?e=[Se[a+_>>2],Se[a+_+4>>2]]:(r="i32",e=Se[a+_>>2]),_+=le.getNativeFieldSize(r),e}for(var i,v,t,f=r,_=0,s=[];;){var n=f;if(i=Ae[f],0===i)break;if(v=Ae[f+1],i=="%".charCodeAt(0)){var o=!1,l=!1,b=!1,k=!1;r:for(;;){switch(v){case"+".charCodeAt(0):o=!0;break;case"-".charCodeAt(0):l=!0;break;case"#".charCodeAt(0):b=!0;break;case"0".charCodeAt(0):if(k)break r;k=!0;break;default:break r}f++,v=Ae[f+1]}var u=0;if(v=="*".charCodeAt(0))u=e("i32"),f++,v=Ae[f+1];else for(;v>="0".charCodeAt(0)&&v<="9".charCodeAt(0);)u=10*u+(v-"0".charCodeAt(0)),f++,v=Ae[f+1];var c=!1;if(v==".".charCodeAt(0)){var h=0;if(c=!0,f++,v=Ae[f+1],v=="*".charCodeAt(0))h=e("i32"),f++;else for(;;){var d=Ae[f+1];if(d<"0".charCodeAt(0)||d>"9".charCodeAt(0))break;h=10*h+(d-"0".charCodeAt(0)),f++}v=Ae[f+1]}else var h=6;var E;switch(String.fromCharCode(v)){case"h":var A=Ae[f+2];A=="h".charCodeAt(0)?(f++,E=1):E=2;break;case"l":var A=Ae[f+2];A=="l".charCodeAt(0)?(f++,E=8):E=4;break;case"L":case"q":case"j":E=8;break;case"z":case"t":case"I":E=4;break;default:E=null}if(E&&f++,v=Ae[f+1],["d","i","u","o","x","X","p"].indexOf(String.fromCharCode(v))!=-1){var m=v=="d".charCodeAt(0)||v=="i".charCodeAt(0);E=E||4;var t=e("i"+8*E);if(8==E&&(t=le.makeBigInt(t[0],t[1],v=="u".charCodeAt(0))),E<=4){var S=Math.pow(256,E)-1;t=(m?y:g)(t&S,8*E)}var M,C=Math.abs(t),R="";if(v=="d".charCodeAt(0)||v=="i".charCodeAt(0))M=y(t,8*E,1).toString(10);else if(v=="u".charCodeAt(0))M=g(t,8*E,1).toString(10),t=Math.abs(t);else if(v=="o".charCodeAt(0))M=(b?"0":"")+C.toString(8);else if(v=="x".charCodeAt(0)||v=="X".charCodeAt(0)){if(R=b?"0x":"",t<0){t=-t,M=(C-1).toString(16);for(var T=[],O=0;O<M.length;O++)T.push((15-parseInt(M[O],16)).toString(16));for(M=T.join("");M.length<2*E;)M="f"+M}else M=C.toString(16);v=="X".charCodeAt(0)&&(R=R.toUpperCase(),M=M.toUpperCase())}else v=="p".charCodeAt(0)&&(0===C?M="(nil)":(R="0x",M=C.toString(16)));if(c)for(;M.length<h;)M="0"+M;for(o&&(R=t<0?"-"+R:"+"+R);R.length+M.length<u;)l?M+=" ":k?M="0"+M:R=" "+R;M=R+M,M.split("").forEach(function(r){s.push(r.charCodeAt(0))})}else if(["f","F","e","E","g","G"].indexOf(String.fromCharCode(v))!=-1){var M,t=e("double");if(isNaN(t))M="nan",k=!1;else if(isFinite(t)){var N=!1,I=Math.min(h,20);if(v=="g".charCodeAt(0)||v=="G".charCodeAt(0)){N=!0,h=h||1;var P=parseInt(t.toExponential(I).split("e")[1],10);h>P&&P>=-4?(v=(v=="g".charCodeAt(0)?"f":"F").charCodeAt(0),h-=P+1):(v=(v=="g".charCodeAt(0)?"e":"E").charCodeAt(0),h--),I=Math.min(h,20)}v=="e".charCodeAt(0)||v=="E".charCodeAt(0)?(M=t.toExponential(I),/[eE][-+]\\d$/.test(M)&&(M=M.slice(0,-1)+"0"+M.slice(-1))):v!="f".charCodeAt(0)&&v!="F".charCodeAt(0)||(M=t.toFixed(I));var D=M.split("e");if(N&&!b)for(;D[0].length>1&&D[0].indexOf(".")!=-1&&("0"==D[0].slice(-1)||"."==D[0].slice(-1));)D[0]=D[0].slice(0,-1);else for(b&&M.indexOf(".")==-1&&(D[0]+=".");h>I++;)D[0]+="0";M=D[0]+(D.length>1?"e"+D[1]:""),v=="E".charCodeAt(0)&&(M=M.toUpperCase()),o&&t>=0&&(M="+"+M)}else M=(t<0?"-":"")+"inf",k=!1;for(;M.length<u;)l?M+=" ":M=!k||"-"!=M[0]&&"+"!=M[0]?(k?"0":" ")+M:M[0]+"0"+M.slice(1);v<"a".charCodeAt(0)&&(M=M.toUpperCase()),M.split("").forEach(function(r){s.push(r.charCodeAt(0))})}else if(v=="s".charCodeAt(0)){var L,F=e("i8*");if(F?(L=w(F),c&&L.length>h&&(L=L.slice(0,h))):L=p("(null)",!0),!l)for(;L.length<u--;)s.push(" ".charCodeAt(0));if(s=s.concat(L),l)for(;L.length<u--;)s.push(" ".charCodeAt(0))}else if(v=="c".charCodeAt(0)){for(l&&s.push(e("i8"));--u>0;)s.push(" ".charCodeAt(0));l||s.push(e("i8"))}else if(v=="n".charCodeAt(0)){var X=e("i32*");Se[X>>2]=s.length}else if(v=="%".charCodeAt(0))s.push(i);else for(var O=n;O<f+2;O++)s.push(Ae[O]);f+=2}else s.push(i),f+=1}return s}function xa(r,a,e,i){for(var v=Ua(e,i),t=void 0===a?v.length:Math.min(v.length,a-1),f=0;f<t;f++)Ae[r+f]=v[f];return Ae[r+f]=0,v.length}function za(r,a,e){return xa(r,void 0,a,e)}function Va(r){return r in{32:0,9:0,10:0,11:0,12:0,13:0}}function Ba(r){return r>="0".charCodeAt(0)&&r<="9".charCodeAt(0)}function Ha(r){for(var a;(a=Ae[r])&&Va(a);)r++;if(!a||!Ba(a))return 0;for(var e=r;(a=Ae[e])&&Ba(a);)e++;return Math.floor(Number(s(r).substr(0,e-r)))}function Ka(r){throw ke=!0,"ABORT: "+r+", at "+(new Error).stack}function Ya(r){return Ya.ret||(Ya.ret=_([0],"i32",we)),Se[Ya.ret>>2]=r,r}function Ga(r,a,e,i){var v=$e.streams[r];if(!v||v.object.isDevice)return Ya(Ge.EBADF),-1;if(v.isWrite){if(v.object.isFolder)return Ya(Ge.EISDIR),-1;if(e<0||i<0)return Ya(Ge.EINVAL),-1;for(var t=v.object.contents;t.length<i;)t.push(0);for(var f=0;f<e;f++)t[i+f]=ge[a+f];return v.object.timestamp=Date.now(),f}return Ya(Ge.EACCES),-1}function Wa(r,a,e){var i=$e.streams[r];if(i){if(i.isWrite){if(e<0)return Ya(Ge.EINVAL),-1;if(i.object.isDevice){if(i.object.output){for(var v=0;v<e;v++)try{i.object.output(Ae[a+v])}catch(r){return Ya(Ge.EIO),-1}return i.object.timestamp=Date.now(),v}return Ya(Ge.ENXIO),-1}var t=Ga(r,a,e,i.position);return t!=-1&&(i.position+=t),t}return Ya(Ge.EACCES),-1}return Ya(Ge.EBADF),-1}function Za(r,a,e,i){var v=e*a;if(0==v)return 0;var t=Wa(i,r,v);return t==-1?($e.streams[i]&&($e.streams[i].error=!0),-1):Math.floor(t/a)}function Qa(r,a,e){var i=Ua(a,e),v=le.stackSave(),t=Za(_(i,"i8",de),1,i.length,r);return le.stackRestore(v),t}function qa(r){switch(r){case 8:return Pe;case 54:case 56:case 21:case 61:case 63:case 22:case 67:case 23:case 24:case 25:case 26:case 27:case 69:case 28:case 101:case 70:case 71:case 29:case 30:case 199:case 75:case 76:case 32:case 43:case 44:case 80:case 46:case 47:case 45:case 48:case 49:case 42:case 82:case 33:case 7:case 108:case 109:case 107:case 112:case 119:case 121:return 200809;case 13:case 104:case 94:case 95:case 34:case 35:case 77:case 81:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 91:case 94:case 95:case 110:case 111:case 113:case 114:case 115:case 116:case 117:case 118:case 120:case 40:case 16:case 79:case 19:return-1;case 92:case 93:case 5:case 72:case 6:case 74:case 92:case 93:case 96:case 97:case 98:case 99:case 102:case 103:case 105:return 1;case 38:case 66:case 50:case 51:case 4:return 1024;case 15:case 64:case 41:return 32;case 55:case 37:case 17:return 2147483647;case 18:case 1:return 47839;case 59:case 57:return 99;case 68:case 58:return 2048;case 0:return 2097152;case 3:return 65536;case 14:return 32768;case 73:return 32767;case 39:return 16384;case 60:return 1e3;case 106:return 700;case 52:return 256;case 62:return 255;case 2:return 100;case 65:return 64;case 36:return 20;case 100:return 16;case 20:return 6;case 53:return 4}return Ya(Ge.EINVAL),-1}function $a(r){var a=Math.floor(Date.now()/1e3);return r&&(Se[r>>2]=a),a}function Ja(){return Ya.ret}function re(r){var a=re;a.called||(Ie=o(Ie),a.called=!0);var e=Ie;return 0!=r&&le.staticAlloc(r),e}function ae(){return Se[ae.buf>>2]}function ee(r){r=r||Module.arguments,k();var a=null;return Module._main&&(a=Module.callMain(r),Module.noExitRuntime||u()),a}var ie=[],ve=false,te="object"==typeof window,fe="function"==typeof importScripts,_e=!te&&!ve&&!fe;if(ve){print=function(r){process.stdout.write(r+"\\n")},printErr=function(r){process.stderr.write(r+"\\n")};var se=require("fs");read=function(r){var a=se.readFileSync(r).toString();return a||"/"==r[0]||(r=__dirname.split("/").slice(0,-1).join("/")+"/src/"+r,a=se.readFileSync(r).toString()),a},load=function(a){r(read(a))},ie=process.argv.slice(2)}else if(_e)this.read||(this.read=function(r){snarf(r)}),"undefined"!=typeof scriptArgs?ie=scriptArgs:"undefined"!=typeof arguments&&(ie=arguments);else if(te)this.print=printErr=function(r){console.log(r)},this.read=function(r){var a=new XMLHttpRequest;return a.open("GET",r,!1),a.send(null),a.responseText},this.arguments&&(ie=arguments);else{if(!fe)throw"Unknown runtime environment. Where are we?";this.load=importScripts}"undefined"==typeof load&&"undefined"!=typeof read&&(this.load=function(a){r(read(a))}),"undefined"==typeof printErr&&(this.printErr=function(){}),"undefined"==typeof print&&(this.print=printErr);try{this.Module=Module}catch(r){this.Module=Module={}}Module.arguments||(Module.arguments=ie),Module.print&&(print=Module.print);var ne,oe,le={stackSave:function(){return Oe},stackRestore:function(r){Oe=r},forceAlign:function(r,a){if(a=a||4,1==a)return r;if(isNumber(r)&&isNumber(a))return Math.ceil(r/a)*a;if(isNumber(a)&&isPowerOfTwo(a)){var e=log2(a);return"(((("+r+")+"+(a-1)+")>>"+e+")<<"+e+")"}return"Math.ceil(("+r+")/"+a+")*"+a},isNumberType:function(r){return r in le.INT_TYPES||r in le.FLOAT_TYPES},isPointerType:function(r){return"*"==r[r.length-1]},isStructType:function(r){return!isPointerType(r)&&(!!/^\\[\\d+\\ x\\ (.*)\\]/.test(r)||(!!/<?{ [^}]* }>?/.test(r)||"%"==r[0]))},INT_TYPES:{i1:0,i8:0,i16:0,i32:0,i64:0},FLOAT_TYPES:{float:0,double:0},bitshift64:function(r,e,i,v){var t=Math.pow(2,v)-1;if(v<32)switch(i){case"shl":return[r<<v,e<<v|(r&t<<32-v)>>>32-v];case"ashr":return[(r>>>v|(e&t)<<32-v)>>0>>>0,e>>v>>>0];case"lshr":return[(r>>>v|(e&t)<<32-v)>>>0,e>>>v]}else if(32==v)switch(i){case"shl":return[0,r];case"ashr":return[e,(0|e)<0?t:0];case"lshr":return[e,0]}else switch(i){case"shl":return[0,r<<v-32];case"ashr":return[e>>v-32>>>0,(0|e)<0?t:0];case"lshr":return[e>>>v-32,0]}a("unknown bitshift64 op: "+[value,i,v])},or64:function(r,a){var e=0|r|(0|a),i=4294967296*(Math.round(r/4294967296)|Math.round(a/4294967296));return e+i},and64:function(r,a){var e=(0|r)&(0|a),i=4294967296*(Math.round(r/4294967296)&Math.round(a/4294967296));return e+i},xor64:function(r,a){var e=(0|r)^(0|a),i=4294967296*(Math.round(r/4294967296)^Math.round(a/4294967296));return e+i},getNativeTypeSize:function(r,a){if(1==le.QUANTUM_SIZE)return 1;var i={"%i1":1,"%i8":1,"%i16":2,"%i32":4,"%i64":8,"%float":4,"%double":8}["%"+r];if(!i)if("*"==r[r.length-1])i=le.QUANTUM_SIZE;else if("i"==r[0]){var v=parseInt(r.substr(1));e(v%8==0),i=v/8}return i},getNativeFieldSize:function(r){return Math.max(le.getNativeTypeSize(r),le.QUANTUM_SIZE)},dedup:function(r,a){var e={};return a?r.filter(function(r){return!e[r[a]]&&(e[r[a]]=!0,!0)}):r.filter(function(r){return!e[r]&&(e[r]=!0,!0)})},set:function(){for(var r="object"==typeof arguments[0]?arguments[0]:arguments,a={},e=0;e<r.length;e++)a[r[e]]=0;return a},calculateStructAlignment:function(r){r.flatSize=0,r.alignSize=0;var a=[],e=-1;return r.flatIndexes=r.fields.map(function(i){var v,t;if(le.isNumberType(i)||le.isPointerType(i))v=le.getNativeTypeSize(i),t=v;else{if(!le.isStructType(i))throw"Unclear type in struct: "+i+", in "+r.name_+" :: "+dump(Types.types[r.name_]);v=Types.types[i].flatSize,t=Types.types[i].alignSize}t=r.packed?1:Math.min(t,le.QUANTUM_SIZE),r.alignSize=Math.max(r.alignSize,t);var f=le.alignMemory(r.flatSize,t);return r.flatSize=f+v,e>=0&&a.push(f-e),e=f,f}),r.flatSize=le.alignMemory(r.flatSize,r.alignSize),0==a.length?r.flatFactor=r.flatSize:1==le.dedup(a).length&&(r.flatFactor=a[0]),r.needsFlattening=1!=r.flatFactor,r.flatIndexes},generateStructInfo:function(r,a,i){var v,t;if(a){if(i=i||0,v=("undefined"==typeof Types?le.typeInfo:Types.types)[a],!v)return null;e(v.fields.length===r.length,"Number of named fields must match the type for "+a),t=v.flatIndexes}else{var v={fields:r.map(function(r){return r[0]})};t=le.calculateStructAlignment(v)}var f={__size__:v.flatSize};return a?r.forEach(function(r,a){if("string"==typeof r)f[r]=t[a]+i;else{var e;for(var _ in r)e=_;f[e]=le.generateStructInfo(r[e],v.fields[a],t[a])}}):r.forEach(function(r,a){f[r[1]]=t[a]}),f},stackAlloc:function(r){var a=Oe;return Oe+=r,Oe=Oe+3>>2<<2,a},staticAlloc:function(r){var a=Ie;return Ie+=r,Ie=Ie+3>>2<<2,Ie>=Le&&l(),a},alignMemory:function(r,a){var e=r=Math.ceil(r/(a?a:4))*(a?a:4);return e},makeBigInt:function(r,a,e){var i=e?(r>>>0)+4294967296*(a>>>0):(r>>>0)+4294967296*(0|a);return i},QUANTUM_SIZE:4,__dummy__:0},be={MAX_ALLOWED:0,corrections:0,sigs:{},note:function(r,e,i){e||(this.corrections++,this.corrections>=this.MAX_ALLOWED&&a("\\n\\nToo many corrections!"))},print:function(){}},ke=!1,ue=0,ce=this;Module.ccall=i,Module.setValue=t,Module.getValue=f;var he=0,de=1,we=2;Module.ALLOC_NORMAL=he,Module.ALLOC_STACK=de,Module.ALLOC_STATIC=we,Module.allocate=_,Module.Pointer_stringify=s,Module.Array_stringify=n;var pe,Ee,Ae,ge,ye,me,Se,Me,Ce,Re,Te,Oe,Ne,Ie,Pe=4096,De=Module.TOTAL_STACK||5242880,Le=Module.TOTAL_MEMORY||10485760;Module.FAST_MEMORY||2097152;e(!!(Int32Array&&Float64Array&&new Int32Array(1).subarray&&new Int32Array(1).set),"Cannot fallback to non-typed array case: Code is too specialized");var Fe=new ArrayBuffer(Le);Ae=new Int8Array(Fe),ye=new Int16Array(Fe),Se=new Int32Array(Fe),ge=new Uint8Array(Fe),me=new Uint16Array(Fe),Me=new Uint32Array(Fe),Ce=new Float32Array(Fe),Re=new Float64Array(Fe),Se[0]=255,e(255===ge[0]&&0===ge[3],"Typed arrays 2 must be run on a little-endian system");var Xe=p("(null)");Ie=Xe.length;for(var je=0;je<Xe.length;je++)Ae[je]=Xe[je];Module.HEAP=Ee,Module.HEAP8=Ae,Module.HEAP16=ye,Module.HEAP32=Se,Module.HEAPU8=ge,Module.HEAPU16=me,Module.HEAPU32=Me,Module.HEAPF32=Ce,Module.HEAPF64=Re,Te=Oe=le.alignMemory(Ie),Ne=Te+De;var Ue=le.alignMemory(Ne,8),xe=(Ae.subarray(Ue),Se.subarray(Ue>>2)),ze=(Ce.subarray(Ue>>2),Re.subarray(Ue>>3));Ne=Ue+8,Ie=o(Ne);var Ve=[],Be=[];Module.Array_copy=c,Module.TypedArray_copy=h,Module.String_len=d,Module.String_copy=w,Module.intArrayFromString=p,Module.intArrayToString=E,Module.writeStringToMemory=A;var He=[],Ke=0;O.X=1,N.X=1,V.X=1,H.X=1,G.X=1,W.X=1,q.X=1,$.X=1,rr.X=1,ar.X=1,er.X=1,vr.X=1,nr.X=1,or.X=1,kr.X=1,hr.X=1,Ar.X=1,Sr.X=1,Tr.X=1,Ir.X=1,Pr.X=1,Dr.X=1,Lr.X=1,Fr.X=1,Xr.X=1,zr.X=1,Vr.X=1,Br.X=1,Gr.X=1,$r.X=1,Module._malloc=Jr,Jr.X=1,ra.X=1,aa.X=1,ea.X=1,ia.X=1,Module._free=va,va.X=1,_a.X=1,sa.X=1,na.X=1,oa.X=1,la.X=1,da.X=1,Ma.X=1;var Ye,Ge={E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTRECOVERABLE:131,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOVERFLOW:75,EOWNERDEAD:130,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18},We=0,Ze=0,Qe=0,qe=0,$e={currentPath:"/",nextInode:2,streams:[null],ignorePermissions:!0,absolutePath:function(r,a){if("string"!=typeof r)return null;void 0===a&&(a=$e.currentPath),r&&"/"==r[0]&&(a="");for(var e=a+"/"+r,i=e.split("/").reverse(),v=[""];i.length;){var t=i.pop();""==t||"."==t||(".."==t?v.length>1&&v.pop():v.push(t))}return 1==v.length?"/":v.join("/")},analyzePath:function(r,a,e){var i={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};if(r=$e.absolutePath(r),"/"==r)i.isRoot=!0,i.exists=i.parentExists=!0,i.name="/",i.path=i.parentPath="/",i.object=i.parentObject=$e.root;else if(null!==r){e=e||0,r=r.slice(1).split("/");for(var v=$e.root,t=[""];r.length;){1==r.length&&v.isFolder&&(i.parentExists=!0,i.parentPath=1==t.length?"/":t.join("/"),i.parentObject=v,i.name=r[0]);var f=r.shift();if(!v.isFolder){i.error=Ge.ENOTDIR;break}if(!v.read){i.error=Ge.EACCES;break}if(!v.contents.hasOwnProperty(f)){i.error=Ge.ENOENT;break}if(v=v.contents[f],v.link&&(!a||0!=r.length)){if(e>40){i.error=Ge.ELOOP;break}var _=$e.absolutePath(v.link,t.join("/"));return $e.analyzePath([_].concat(r).join("/"),a,e+1)}t.push(f),0==r.length&&(i.exists=!0,i.path=t.join("/"),i.object=v)}return i}return i},findObject:function(r,a){$e.ensureRoot();var e=$e.analyzePath(r,a);return e.exists?e.object:(Ya(e.error),null)},createObject:function(r,a,e,i,v){if(r||(r="/"),"string"==typeof r&&(r=$e.findObject(r)),!r)throw Ya(Ge.EACCES),new Error("Parent path must exist.");if(!r.isFolder)throw Ya(Ge.ENOTDIR),\nnew Error("Parent must be a folder.");if(!r.write&&!$e.ignorePermissions)throw Ya(Ge.EACCES),new Error("Parent folder must be writeable.");if(!a||"."==a||".."==a)throw Ya(Ge.ENOENT),new Error("Name must not be empty.");if(r.contents.hasOwnProperty(a))throw Ya(Ge.EEXIST),new Error("Can\'t overwrite object.");r.contents[a]={read:void 0===i||i,write:void 0!==v&&v,timestamp:Date.now(),inodeNumber:$e.nextInode++};for(var t in e)e.hasOwnProperty(t)&&(r.contents[a][t]=e[t]);return r.contents[a]},createFolder:function(r,a,e,i){var v={isFolder:!0,isDevice:!1,contents:{}};return $e.createObject(r,a,v,e,i)},createPath:function(r,a,e,i){var v=$e.findObject(r);if(null===v)throw new Error("Invalid parent.");for(a=a.split("/").reverse();a.length;){var t=a.pop();t&&(v.contents.hasOwnProperty(t)||$e.createFolder(v,t,e,i),v=v.contents[t])}return v},createFile:function(r,a,e,i,v){return e.isFolder=!1,$e.createObject(r,a,e,i,v)},createDataFile:function(r,a,e,i,v){if("string"==typeof e){for(var t=new Array(e.length),f=0,_=e.length;f<_;++f)t[f]=e.charCodeAt(f);e=t}var s={isDevice:!1,contents:e};return $e.createFile(r,a,s,i,v)},createLazyFile:function(r,a,e,i,v){var t={isDevice:!1,url:e};return $e.createFile(r,a,t,i,v)},createLink:function(r,a,e,i,v){var t={isDevice:!1,link:e};return $e.createFile(r,a,t,i,v)},createDevice:function(r,a,e,i){if(!e&&!i)throw new Error("A device must have at least one callback defined.");var v={isDevice:!0,input:e,output:i};return $e.createFile(r,a,v,Boolean(e),Boolean(i))},forceLoadFile:function(r){if(r.isDevice||r.isFolder||r.link||r.contents)return!0;var a=!0;if("undefined"!=typeof XMLHttpRequest)e("Cannot do synchronous binary XHRs in modern browsers. Use --embed-file or --preload-file in emcc");else{if("undefined"==typeof read)throw new Error("Cannot load without read() or XMLHttpRequest.");try{r.contents=p(read(r.url),!0)}catch(r){a=!1}}return a||Ya(Ge.EIO),a},ensureRoot:function(){$e.root||($e.root={read:!0,write:!0,isFolder:!0,isDevice:!1,timestamp:Date.now(),inodeNumber:1,contents:{}})},init:function(r,a,i){function v(r){null===r||r==="\\n".charCodeAt(0)?(a.printer(a.buffer.join("")),a.buffer=[]):a.buffer.push(String.fromCharCode(r))}e(!$e.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)"),$e.init.initialized=!0,$e.ensureRoot(),r=r||Module.stdin,a=a||Module.stdout,i=i||Module.stderr;var t=!0,f=!0,s=!0;r||(t=!1,r=function(){if(!r.cache||!r.cache.length){var a;"undefined"!=typeof window&&"function"==typeof window.prompt?a=window.prompt("Input: "):"function"==typeof readline&&(a=readline()),a||(a=""),r.cache=p(a+"\\n",!0)}return r.cache.shift()}),a||(f=!1,a=v),a.printer||(a.printer=print),a.buffer||(a.buffer=[]),i||(s=!1,i=v),i.printer||(i.printer=print),i.buffer||(i.buffer=[]),$e.createFolder("/","tmp",!0,!0);var n=$e.createFolder("/","dev",!0,!0),o=$e.createDevice(n,"stdin",r),l=$e.createDevice(n,"stdout",null,a),b=$e.createDevice(n,"stderr",null,i);$e.createDevice(n,"tty",r,a),$e.streams[1]={path:"/dev/stdin",object:o,position:0,isRead:!0,isWrite:!1,isAppend:!1,isTerminal:!t,error:!1,eof:!1,ungotten:[]},$e.streams[2]={path:"/dev/stdout",object:l,position:0,isRead:!1,isWrite:!0,isAppend:!1,isTerminal:!f,error:!1,eof:!1,ungotten:[]},$e.streams[3]={path:"/dev/stderr",object:b,position:0,isRead:!1,isWrite:!0,isAppend:!1,isTerminal:!s,error:!1,eof:!1,ungotten:[]},We=_([1],"void*",we),Ze=_([2],"void*",we),Qe=_([3],"void*",we),$e.createPath("/","dev/shm/tmp",!0,!0),$e.streams[We]=$e.streams[1],$e.streams[Ze]=$e.streams[2],$e.streams[Qe]=$e.streams[3],qe=_([_([0,0,0,0,We,0,0,0,Ze,0,0,0,Qe,0,0,0],"void*",we)],"void*",we)},quit:function(){$e.init.initialized&&($e.streams[2]&&$e.streams[2].object.output.buffer.length>0&&$e.streams[2].object.output("\\n".charCodeAt(0)),$e.streams[3]&&$e.streams[3].object.output.buffer.length>0&&$e.streams[3].object.output("\\n".charCodeAt(0)))}},Je=Ja;Ve.unshift({func:function(){$e.ignorePermissions=!1,$e.init.initialized||$e.init()}}),Be.push({func:function(){$e.quit()}}),Ya(0),ae.buf=_(12,"void*",we),Module.callMain=function(r){function a(){for(var r=0;r<3;r++)i.push(0)}var e=r.length+1,i=[_(p("/bin/this.program"),"i8",we)];a();for(var v=0;v<e-1;v+=1)i.push(_(p(r[v]),"i8",we)),a();return i.push(0),i=_(i,"i32",we),_main(e,i,0)};var ri,ai,ei,ii,vi,ti,qe,fi,_i,si,ni,oi,li,bi,ki,ui,ci,hi,di,wi;if(He.__str=_([97,78,0],"i8",we),He.__str1=_([38,61,0],"i8",we),He.__str2=_([97,83,0],"i8",we),He.__str3=_([61,0],"i8",we),He.__str4=_([97,97,0],"i8",we),He.__str5=_([38,38,0],"i8",we),He.__str6=_([97,100,0],"i8",we),He.__str7=_([38,0],"i8",we),He.__str8=_([97,110,0],"i8",we),He.__str9=_([99,108,0],"i8",we),He.__str10=_([40,41,0],"i8",we),He.__str11=_([99,109,0],"i8",we),He.__str12=_([44,0],"i8",we),He.__str13=_([99,111,0],"i8",we),He.__str14=_([126,0],"i8",we),He.__str15=_([100,86,0],"i8",we),He.__str16=_([47,61,0],"i8",we),He.__str17=_([100,97,0],"i8",we),He.__str18=_([100,101,108,101,116,101,91,93,0],"i8",we),He.__str19=_([100,101,0],"i8",we),He.__str20=_([42,0],"i8",we),He.__str21=_([100,108,0],"i8",we),He.__str22=_([100,101,108,101,116,101,0],"i8",we),He.__str23=_([100,118,0],"i8",we),He.__str24=_([47,0],"i8",we),He.__str25=_([101,79,0],"i8",we),He.__str26=_([94,61,0],"i8",we),He.__str27=_([101,111,0],"i8",we),He.__str28=_([94,0],"i8",we),He.__str29=_([101,113,0],"i8",we),He.__str30=_([61,61,0],"i8",we),He.__str31=_([103,101,0],"i8",we),He.__str32=_([62,61,0],"i8",we),He.__str33=_([103,116,0],"i8",we),He.__str34=_([62,0],"i8",we),He.__str35=_([105,120,0],"i8",we),He.__str36=_([91,93,0],"i8",we),He.__str37=_([108,83,0],"i8",we),He.__str38=_([60,60,61,0],"i8",we),He.__str39=_([108,101,0],"i8",we),He.__str40=_([60,61,0],"i8",we),He.__str41=_([108,115,0],"i8",we),He.__str42=_([60,60,0],"i8",we),He.__str43=_([108,116,0],"i8",we),He.__str44=_([60,0],"i8",we),He.__str45=_([109,73,0],"i8",we),He.__str46=_([45,61,0],"i8",we),He.__str47=_([109,76,0],"i8",we),He.__str48=_([42,61,0],"i8",we),He.__str49=_([109,105,0],"i8",we),He.__str51=_([109,108,0],"i8",we),He.__str52=_([109,109,0],"i8",we),He.__str53=_([45,45,0],"i8",we),He.__str54=_([110,97,0],"i8",we),He.__str55=_([110,101,119,91,93,0],"i8",we),He.__str56=_([110,101,0],"i8",we),He.__str57=_([33,61,0],"i8",we),He.__str58=_([110,103,0],"i8",we),He.__str59=_([110,116,0],"i8",we),He.__str60=_([33,0],"i8",we),He.__str61=_([110,119,0],"i8",we),He.__str62=_([110,101,119,0],"i8",we),He.__str63=_([111,82,0],"i8",we),He.__str64=_([124,61,0],"i8",we),He.__str65=_([111,111,0],"i8",we),He.__str66=_([124,124,0],"i8",we),He.__str67=_([111,114,0],"i8",we),He.__str68=_([124,0],"i8",we),He.__str69=_([112,76,0],"i8",we),He.__str70=_([43,61,0],"i8",we),He.__str71=_([112,108,0],"i8",we),He.__str72=_([43,0],"i8",we),He.__str73=_([112,109,0],"i8",we),He.__str74=_([45,62,42,0],"i8",we),He.__str75=_([112,112,0],"i8",we),He.__str76=_([43,43,0],"i8",we),He.__str77=_([112,115,0],"i8",we),He.__str78=_([112,116,0],"i8",we),He.__str79=_([45,62,0],"i8",we),He.__str80=_([113,117,0],"i8",we),He.__str81=_([63,0],"i8",we),He.__str82=_([114,77,0],"i8",we),He.__str83=_([37,61,0],"i8",we),He.__str84=_([114,83,0],"i8",we),He.__str85=_([62,62,61,0],"i8",we),He.__str86=_([114,109,0],"i8",we),He.__str87=_([37,0],"i8",we),He.__str88=_([114,115,0],"i8",we),He.__str89=_([62,62,0],"i8",we),He.__str90=_([115,116,0],"i8",we),He.__str91=_([115,105,122,101,111,102,32,0],"i8",we),He.__str92=_([115,122,0],"i8",we),ri=_([0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,7,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],["*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0],we),He.__str95=_([98,111,111,108,101,97,110,0],"i8",we),He.__str97=_([98,121,116,101,0],"i8",we),He.__str101=_([95,95,102,108,111,97,116,49,50,56,0],"i8",we),He.__str105=_([117,110,115,105,103,110,101,100,0],"i8",we),He.__str114=_([108,111,110,103,32,108,111,110,103,0],"i8",we),He.__str115=_([117,110,115,105,103,110,101,100,32,108,111,110,103,32,108,111,110,103,0],"i8",we),ai=_([0,0,0,0,11,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,7,0,0,0,7,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,6,0,0,0,8,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,11,0,0,0,8,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,5,0,0,0,8,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,10,0,0,0,8,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,8,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,4,0,0,0,3,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,13,0,0,0,4,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,4,0,0,0,9,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,4,0,0,0,5,0,0,0,0,0,0,0,18,0,0,0,0,0,0,0,18,0,0,0,6,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0],["*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0],we),He.__str117=_([95,71,76,79,66,65,76,95,0],"i8",we),He.__str118=_([103,108,111,98,97,108,32,99,111,110,115,116,114,117,99,116,111,114,115,32,107,101,121,101,100,32,116,111,32,0],"i8",we),He.__str119=_([103,108,111,98,97,108,32,100,101,115,116,114,117,99,116,111,114,115,32,107,101,121,101,100,32,116,111,32,0],"i8",we),He.__str120=_([58,58,0],"i8",we),He.__str121=_([118,116,97,98,108,101,32,102,111,114,32,0],"i8",we),He.__str122=_([86,84,84,32,102,111,114,32,0],"i8",we),He.__str123=_([99,111,110,115,116,114,117,99,116,105,111,110,32,118,116,97,98,108,101,32,102,111,114,32,0],"i8",we),He.__str124=_([45,105,110,45,0],"i8",we),He.__str125=_([116,121,112,101,105,110,102,111,32,102,111,114,32,0],"i8",we),He.__str126=_([116,121,112,101,105,110,102,111,32,110,97,109,101,32,102,111,114,32,0],"i8",we),He.__str127=_([116,121,112,101,105,110,102,111,32,102,110,32,102,111,114,32,0],"i8",we),He.__str128=_([110,111,110,45,118,105,114,116,117,97,108,32,116,104,117,110,107,32,116,111,32,0],"i8",we),He.__str129=_([118,105,114,116,117,97,108,32,116,104,117,110,107,32,116,111,32,0],"i8",we),He.__str130=_([99,111,118,97,114,105,97,110,116,32,114,101,116,117,114,110,32,116,104,117,110,107,32,116,111,32,0],"i8",we),He.__str131=_([106,97,118,97,32,67,108,97,115,115,32,102,111,114,32,0],"i8",we),He.__str132=_([103,117,97,114,100,32,118,97,114,105,97,98,108,101,32,102,111,114,32,0],"i8",we),He.__str133=_([114,101,102,101,114,101,110,99,101,32,116,101,109,112,111,114,97,114,121,32,102,111,114,32,0],"i8",we),He.__str134=_([104,105,100,100,101,110,32,97,108,105,97,115,32,102,111,114,32,0],"i8",we),He.__str135=_([58,58,42,0],"i8",we),He.__str136=_([44,32,0],"i8",we),He.__str137=_([111,112,101,114,97,116,111,114,0],"i8",we),He.__str139=_([41,32,0],"i8",we),He.__str140=_([32,40,0],"i8",we),He.__str141=_([41,32,58,32,40,0],"i8",we),He.__str142=_([117,108,0],"i8",we),He.__str143=_([108,108,0],"i8",we),He.__str144=_([117,108,108,0],"i8",we),He.__str145=_([102,97,108,115,101,0],"i8",we),He.__str146=_([116,114,117,101,0],"i8",we),He.__str147=_([32,114,101,115,116,114,105,99,116,0],"i8",we),He.__str148=_([32,118,111,108,97,116,105,108,101,0],"i8",we),He.__str149=_([32,99,111,110,115,116,0],"i8",we),He.__str150=_([99,111,109,112,108,101,120,32,0],"i8",we),He.__str151=_([105,109,97,103,105,110,97,114,121,32,0],"i8",we),ei=_([116,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,97,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,9,0,0,0,98,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,12,0,0,0,115,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,70,0,0,0,0,0,0,0,12,0,0,0,105,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,49,0,0,0,0,0,0,0,13,0,0,0,111,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,49,0,0,0,0,0,0,0,13,0,0,0,100,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,50,0,0,0,0,0,0,0,14,0,0,0],["i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"i8",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0],we),He.__str152=_([115,116,100,0],"i8",we),He.__str153=_([115,116,100,58,58,97,108,108,111,99,97,116,111,114,0],"i8",we),He.__str154=_([97,108,108,111,99,97,116,111,114,0],"i8",we),He.__str155=_([115,116,100,58,58,98,97,115,105,99,95,115,116,114,105,110,103,0],"i8",we),He.__str156=_([98,97,115,105,99,95,115,116,114,105,110,103,0],"i8",we),He.__str157=_([115,116,100,58,58,115,116,114,105,110,103,0],"i8",we),He.__str158=_([115,116,100,58,58,98,97,115,105,99,95,115,116,114,105,110,103,60,99,104,97,114,44,32,115,116,100,58,58,99,104,97,114,95,116,114,97,105,116,115,60,99,104,97,114,62,44,32,115,116,100,58,58,97,108,108,111,99,97,116,111,114,60,99,104,97,114,62,32,62,0],"i8",we),He.__str159=_([115,116,100,58,58,105,115,116,114,101,97,109,0],"i8",we),He.__str160=_([115,116,100,58,58,98,97,115,105,99,95,105,115,116,114,101,97,109,60,99,104,97,114,44,32,115,116,100,58,58,99,104,97,114,95,116,114,97,105,116,115,60,99,104,97,114,62,32,62,0],"i8",we),He.__str161=_([98,97,115,105,99,95,105,115,116,114,101,97,109,0],"i8",we),He.__str162=_([115,116,100,58,58,111,115,116,114,101,97,109,0],"i8",we),He.__str163=_([115,116,100,58,58,98,97,115,105,99,95,111,115,116,114,101,97,109,60,99,104,97,114,44,32,115,116,100,58,58,99,104,97,114,95,116,114,97,105,116,115,60,99,104,97,114,62,32,62,0],"i8",we),He.__str164=_([98,97,115,105,99,95,111,115,116,114,101,97,109,0],"i8",we),He.__str165=_([115,116,100,58,58,105,111,115,116,114,101,97,109,0],"i8",we),He.__str166=_([115,116,100,58,58,98,97,115,105,99,95,105,111,115,116,114,101,97,109,60,99,104,97,114,44,32,115,116,100,58,58,99,104,97,114,95,116,114,97,105,116,115,60,99,104,97,114,62,32,62,0],"i8",we),He.__str167=_([98,97,115,105,99,95,105,111,115,116,114,101,97,109,0],"i8",we),He.__str168=_([115,116,114,105,110,103,32,108,105,116,101,114,97,108,0],"i8",we),He.__str169=_([40,97,110,111,110,121,109,111,117,115,32,110,97,109,101,115,112,97,99,101,41,0],"i8",we),He._symbol_demangle_dashed_null=_([45,45,110,117,108,108,45,45,0],"i8",we),He.__str170=_([37,115,37,115,0],"i8",we),He.__str1171=_([111,112,101,114,97,116,111,114,32,110,101,119,0],"i8",we),He.__str2172=_([111,112,101,114,97,116,111,114,32,100,101,108,101,116,101,0],"i8",we),He.__str3173=_([111,112,101,114,97,116,111,114,61,0],"i8",we),He.__str4174=_([111,112,101,114,97,116,111,114,62,62,0],"i8",we),He.__str5175=_([111,112,101,114,97,116,111,114,60,60,0],"i8",we),He.__str6176=_([111,112,101,114,97,116,111,114,33,0],"i8",we),He.__str7177=_([111,112,101,114,97,116,111,114,61,61,0],"i8",we),He.__str8178=_([111,112,101,114,97,116,111,114,33,61,0],"i8",we),He.__str9179=_([111,112,101,114,97,116,111,114,91,93,0],"i8",we),He.__str10180=_([111,112,101,114,97,116,111,114,32,0],"i8",we),He.__str11181=_([111,112,101,114,97,116,111,114,45,62,0],"i8",we),He.__str12182=_([111,112,101,114,97,116,111,114,42,0],"i8",we),He.__str13183=_([111,112,101,114,97,116,111,114,43,43,0],"i8",we),He.__str14184=_([111,112,101,114,97,116,111,114,45,45,0],"i8",we),He.__str15185=_([111,112,101,114,97,116,111,114,45,0],"i8",we),He.__str16186=_([111,112,101,114,97,116,111,114,43,0],"i8",we),He.__str17187=_([111,112,101,114,97,116,111,114,38,0],"i8",we),He.__str18188=_([111,112,101,114,97,116,111,114,45,62,42,0],"i8",we),He.__str19189=_([111,112,101,114,97,116,111,114,47,0],"i8",we),He.__str20190=_([111,112,101,114,97,116,111,114,37,0],"i8",we),He.__str21191=_([111,112,101,114,97,116,111,114,60,0],"i8",we),He.__str22192=_([111,112,101,114,97,116,111,114,60,61,0],"i8",we),He.__str23193=_([111,112,101,114,97,116,111,114,62,0],"i8",we),He.__str24194=_([111,112,101,114,97,116,111,114,62,61,0],"i8",we),He.__str25195=_([111,112,101,114,97,116,111,114,44,0],"i8",we),He.__str26196=_([111,112,101,114,97,116,111,114,40,41,0],"i8",we),He.__str27197=_([111,112,101,114,97,116,111,114,126,0],"i8",we),He.__str28198=_([111,112,101,114,97,116,111,114,94,0],"i8",we),He.__str29199=_([111,112,101,114,97,116,111,114,124,0],"i8",we),He.__str30200=_([111,112,101,114,97,116,111,114,38,38,0],"i8",we),He.__str31201=_([111,112,101,114,97,116,111,114,124,124,0],"i8",we),He.__str32202=_([111,112,101,114,97,116,111,114,42,61,0],"i8",we),He.__str33203=_([111,112,101,114,97,116,111,114,43,61,0],"i8",we),He.__str34204=_([111,112,101,114,97,116,111,114,45,61,0],"i8",we),He.__str35205=_([111,112,101,114,97,116,111,114,47,61,0],"i8",we),He.__str36206=_([111,112,101,114,97,116,111,114,37,61,0],"i8",we),He.__str37207=_([111,112,101,114,97,116,111,114,62,62,61,0],"i8",we),He.__str38208=_([111,112,101,114,97,116,111,114,60,60,61,0],"i8",we),He.__str39209=_([111,112,101,114,97,116,111,114,38,61,0],"i8",we),He.__str40210=_([111,112,101,114,97,116,111,114,124,61,0],"i8",we),He.__str41211=_([111,112,101,114,97,116,111,114,94,61,0],"i8",we),He.__str42212=_([96,118,102,116,97,98,108,101,39,0],"i8",we),He.__str43213=_([96,118,98,116,97,98,108,101,39,0],"i8",we),He.__str44214=_([96,118,99,97,108,108,39,0],"i8",we),He.__str45215=_([96,116,121,112,101,111,102,39,0],"i8",we),He.__str46216=_([96,108,111,99,97,108,32,115,116,97,116,105,99,32,103,117,97,114,100,39,0],"i8",we),He.__str47217=_([96,115,116,114,105,110,103,39,0],"i8",we),He.__str48218=_([96,118,98,97,115,101,32,100,101,115,116,114,117,99,116,111,114,39,0],"i8",we),He.__str49219=_([96,118,101,99,116,111,114,32,100,101,108,101,116,105,110,103,32,100,101,115,116,114,117,99,116,111,114,39,0],"i8",we),He.__str50220=_([96,100,101,102,97,117,108,116,32,99,111,110,115,116,114,117,99,116,111,114,32,99,108,111,115,117,114,101,39,0],"i8",we),He.__str51221=_([96,115,99,97,108,97,114,32,100,101,108,101,116,105,110,103,32,100,101,115,116,114,117,99,116,111,114,39,0],"i8",we),He.__str52222=_([96,118,101,99,116,111,114,32,99,111,110,115,116,114,117,99,116,111,114,32,105,116,101,114,97,116,111,114,39,0],"i8",we),He.__str53223=_([96,118,101,99,116,111,114,32,100,101,115,116,114,117,99,116,111,114,32,105,116,101,114,97,116,111,114,39,0],"i8",we),He.__str54224=_([96,118,101,99,116,111,114,32,118,98,97,115,101,32,99,111,110,115,116,114,117,99,116,111,114,32,105,116,101,114,97,116,111,114,39,0],"i8",we),He.__str55225=_([96,118,105,114,116,117,97,108,32,100,105,115,112,108,97,99,101,109,101,110,116,32,109,97,112,39,0],"i8",we),He.__str56226=_([96,101,104,32,118,101,99,116,111,114,32,99,111,110,115,116,114,117,99,116,111,114,32,105,116,101,114,97,116,111,114,39,0],"i8",we),He.__str57227=_([96,101,104,32,118,101,99,116,111,114,32,100,101,115,116,114,117,99,116,111,114,32,105,116,101,114,97,116,111,114,39,0],"i8",we),He.__str58228=_([96,101,104,32,118,101,99,116,111,114,32,118,98,97,115,101,32,99,111,110,115,116,114,117,99,116,111,114,32,105,116,101,114,97,116,111,114,39,0],"i8",we),He.__str59229=_([96,99,111,112,121,32,99,111,110,115,116,114,117,99,116,111,114,32,99,108,111,115,117,114,101,39,0],"i8",we),He.__str60230=_([37,115,37,115,32,96,82,84,84,73,32,84,121,112,101,32,68,101,115,99,114,105,112,116,111,114,39,0],"i8",we),He.__str61231=_([96,82,84,84,73,32,66,97,115,101,32,67,108,97,115,115,32,68,101,115,99,114,105,112,116,111,114,32,97,116,32,40,37,115,44,37,115,44,37,115,44,37,115,41,39,0],"i8",we),He.__str62232=_([96,82,84,84,73,32,66,97,115,101,32,67,108,97,115,115,32,65,114,114,97,121,39,0],"i8",we),He.__str63233=_([96,82,84,84,73,32,67,108,97,115,115,32,72,105,101,114,97,114,99,104,121,32,68,101,115,99,114,105,112,116,111,114,39,0],"i8",we),He.__str64234=_([96,82,84,84,73,32,67,111,109,112,108,101,116,101,32,79,98,106,101,99,116,32,76,111,99,97,116,111,114,39,0],"i8",we),He.__str65235=_([96,108,111,99,97,108,32,118,102,116,97,98,108,101,39,0],"i8",we),He.__str66236=_([96,108,111,99,97,108,32,118,102,116,97,98,108,101,32,99,111,110,115,116,114,117,99,116,111,114,32,99,108,111,115,117,114,101,39,0],"i8",we),He.__str67237=_([111,112,101,114,97,116,111,114,32,110,101,119,91,93,0],"i8",we),He.__str68238=_([111,112,101,114,97,116,111,114,32,100,101,108,101,116,101,91,93,0],"i8",we),He.__str69239=_([96,112,108,97,99,101,109,101,110,116,32,100,101,108,101,116,101,32,99,108,111,115,117,114,101,39,0],"i8",we),He.__str70240=_([96,112,108,97,99,101,109,101,110,116,32,100,101,108,101,116,101,91,93,32,99,108,111,115,117,114,101,39,0],"i8",we),He.__str71241=_([126,37,115,0],"i8",we),He.__str72242=_([117,110,100,110,97,109,101,46,99,0],"i8",we),He.___func___symbol_demangle=_([115,121,109,98,111,108,95,100,101,109,97,110,103,108,101,0],"i8",we),He.__str73243=_([115,121,109,45,62,114,101,115,117,108,116,0],"i8",we),He.___func___handle_template=_([104,97,110,100,108,101,95,116,101,109,112,108,97,116,101,0],"i8",we),He.__str74244=_([42,115,121,109,45,62,99,117,114,114,101,110,116,32,61,61,32,39,36,39,0],"i8",we),He.___func___str_array_get_ref=_([115,116,114,95,97,114,114,97,121,95,103,101,116,95,114,101,102,0],"i8",we),He.__str75245=_([99,114,101,102,0],"i8",we),He.__str76246=_([112,114,105,118,97,116,101,58,32,0],"i8",we),He.__str77247=_([112,114,111,116,101,99,116,101,100,58,32,0],"i8",we),He.__str78248=_([112,117,98,108,105,99,58,32,0],"i8",we),He.__str79249=_([115,116,97,116,105,99,32,0],"i8",we),He.__str80250=_([118,105,114,116,117,97,108,32,0],"i8",we),He.__str81251=_([91,116,104,117,110,107,93,58,37,115,0],"i8",we),He.__str82252=_([37,115,96,97,100,106,117,115,116,111,114,123,37,115,125,39,32,0],"i8",we),He.__str83253=_([37,115,32,37,115,0],"i8",we),He.__str84254=_([118,111,105,100,0],"i8",we),He.__str85255=_([37,115,37,115,37,115,0],"i8",we),He.__str86256=_([37,115,37,115,37,115,37,115,37,115,37,115,37,115,37,115,37,115,37,115,37,115,0],"i8",we),He.__str87257=_([32,0],"i8",we),He.__str88258=_([100,108,108,95,101,120,112,111,114,116,32,0],"i8",we),He.__str89259=_([99,100,101,99,108,0],"i8",we),He.__str90260=_([112,97,115,99,97,108,0],"i8",we),He.__str91261=_([116,104,105,115,99,97,108,108,0],"i8",we),He.__str92262=_([115,116,100,99,97,108,108,0],"i8",we),He.__str93263=_([102,97,115,116,99,97,108,108,0],"i8",we),He.__str94264=_([99,108,114,99,97,108,108,0],"i8",we),He.__str95265=_([95,95,100,108,108,95,101,120,112,111,114,116,32,0],"i8",we),He.__str96266=_([95,95,99,100,101,99,108,0],"i8",we),He.__str97267=_([95,95,112,97,115,99,97,108,0],"i8",we),He.__str98268=_([95,95,116,104,105,115,99,97,108,108,0],"i8",we),He.__str99269=_([95,95,115,116,100,99,97,108,108,0],"i8",we),He.__str100270=_([95,95,102,97,115,116,99,97,108,108,0],"i8",we),He.__str101271=_([95,95,99,108,114,99,97,108,108,0],"i8",we),He.__str102272=_([95,95,112,116,114,54,52,0],"i8",we),He.__str103273=_([99,111,110,115,116,0],"i8",we),He.__str104274=_([118,111,108,97,116,105,108,101,0],"i8",we),He.__str105275=_([99,111,110,115,116,32,118,111,108,97,116,105,108,101,0],"i8",we),He.___func___get_class_string=_([103,101,116,95,99,108,97,115,115,95,115,116,114,105,110,103,0],"i8",we),He.__str106276=_([97,45,62,101,108,116,115,91,105,93,0],"i8",we),He.__str107277=_([123,102,111,114,32,96,37,115,39,125,0],"i8",we),He.__str108278=_([37,115,37,115,37,115,37,115,37,115,37,115,37,115,37,115,0],"i8",we),He.__str109279=_([96,37,115,39,0],"i8",we),He.__str110280=_([46,46,46,0],"i8",we),He.__str111281=_([37,99,118,111,105,100,37,99,0],"i8",we),He.__str112282=_([37,115,44,37,115,0],"i8",we),He.__str113283=_([37,99,37,115,37,115,32,37,99,0],"i8",we),He.__str114284=_([37,99,37,115,37,115,37,99,0],"i8",we),He.___func___str_array_push=_([115,116,114,95,97,114,114,97,121,95,112,117,115,104,0],"i8",we),He.__str115285=_([112,116,114,0],"i8",we),He.__str116286=_([97,0],"i8",we),He.__str117287=_([97,45,62,101,108,116,115,91,97,45,62,110,117,109,93,0],"i8",we),He.__str118288=_([37,115,37,100,0],"i8",we),He.__str119289=_([45,0],"i8",we),ii=_(1,"i8",we),He.___func___demangle_datatype=_([100,101,109,97,110,103,108,101,95,100,97,116,97,116,121,112,101,0],"i8",we),He.__str121291=_([99,116,0],"i8",we),He.__str122292=_([117,110,105,111,110,32,0],"i8",we),He.__str123293=_([115,116,114,117,99,116,32,0],"i8",we),He.__str124294=_([99,108,97,115,115,32,0],"i8",we),He.__str125295=_([99,111,105,110,116,101,114,102,97,99,101,32,0],"i8",we),He.__str126296=_([96,116,101,109,112,108,97,116,101,45,112,97,114,97,109,101,116,101,114,45,37,115,39,0],"i8",we),He.__str127297=_([37,115,37,115,32,40,37,115,42,0],"i8",we),He.__str128298=_([41,37,115,0],"i8",we),He.__str129299=_([101,110,117,109,32,37,115,0],"i8",we),He.__str130300=_([96,116,101,109,112,108,97,116,101,45,112,97,114,97,109,101,116,101,114,37,115,39,0],"i8",we),He.__str131301=_([123,37,115,44,37,115,125,0],"i8",we),He.__str132302=_([123,37,115,44,37,115,44,37,115,125,0],"i8",we),He.__str133303=_([96,110,111,110,45,116,121,112,101,45,116,101,109,112,108,97,116,101,45,112,97,114,97,109,101,116,101,114,37,115,39,0],"i8",we),He.__str134304=_([32,95,95,112,116,114,54,52,0],"i8",we),He.__str135305=_([32,38,37,115,0],"i8",we),He.__str136306=_([32,38,37,115,32,118,111,108,97,116,105,108,101,0],"i8",we),He.__str137307=_([32,42,37,115,0],"i8",we),He.__str138308=_([32,42,37,115,32,99,111,110,115,116,0],"i8",we),He.__str139309=_([32,42,37,115,32,118,111,108,97,116,105,108,101,0],"i8",we),He.__str140310=_([32,42,37,115,32,99,111,110,115,116,32,118,111,108,97,116,105,108,101,0],"i8",we),He.__str141311=_([32,40,37,115,37,115,41,0],"i8",we),He.__str142312=_([32,40,37,115,41,0],"i8",we),He.__str143313=_([37,115,91,37,115,93,0],"i8",we),He.__str144314=_([37,115,32,37,115,37,115,0],"i8",we),He.__str145315=_([115,105,103,110,101,100,32,99,104,97,114,0],"i8",we),He.__str146316=_([99,104,97,114,0],"i8",we),He.__str147317=_([117,110,115,105,103,110,101,100,32,99,104,97,114,0],"i8",we),He.__str148318=_([115,104,111,114,116,0],"i8",we),He.__str149319=_([117,110,115,105,103,110,101,100,32,115,104,111,114,116,0],"i8",we),He.__str150320=_([105,110,116,0],"i8",we),He.__str151321=_([117,110,115,105,103,110,101,100,32,105,110,116,0],"i8",we),He.__str152322=_([108,111,110,103,0],"i8",we),He.__str153323=_([117,110,115,105,103,110,101,100,32,108,111,110,103,0],"i8",we),He.__str154324=_([102,108,111,97,116,0],"i8",we),He.__str155325=_([100,111,117,98,108,101,0],"i8",we),He.__str156326=_([108,111,110,103,32,100,111,117,98,108,101,0],"i8",we),He.__str157327=_([95,95,105,110,116,56,0],"i8",we),He.__str158328=_([117,110,115,105,103,110,101,100,32,95,95,105,110,116,56,0],"i8",we),He.__str159329=_([95,95,105,110,116,49,54,0],"i8",we),He.__str160330=_([117,110,115,105,103,110,101,100,32,95,95,105,110,116,49,54,0],"i8",we),He.__str161331=_([95,95,105,110,116,51,50,0],"i8",we),He.__str162332=_([117,110,115,105,103,110,101,100,32,95,95,105,110,116,51,50,0],"i8",we),He.__str163333=_([95,95,105,110,116,54,52,0],"i8",we),He.__str164334=_([117,110,115,105,103,110,101,100,32,95,95,105,110,116,54,52,0],"i8",we),\nHe.__str165335=_([95,95,105,110,116,49,50,56,0],"i8",we),He.__str166336=_([117,110,115,105,103,110,101,100,32,95,95,105,110,116,49,50,56,0],"i8",we),He.__str167337=_([98,111,111,108,0],"i8",we),He.__str168338=_([119,99,104,97,114,95,116,0],"i8",we),vi=_(468,["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0,"*",0,0,0,"i32",0,0,0],we),ti=_(24,"i32",we),He.__str339=_([109,97,120,32,115,121,115,116,101,109,32,98,121,116,101,115,32,61,32,37,49,48,108,117,10,0],"i8",we),He.__str1340=_([115,121,115,116,101,109,32,98,121,116,101,115,32,32,32,32,32,61,32,37,49,48,108,117,10,0],"i8",we),He.__str2341=_([105,110,32,117,115,101,32,98,121,116,101,115,32,32,32,32,32,61,32,37,49,48,108,117,10,0],"i8",we),fi=_([ue],"i8",we),_i=_(1,"void ()*",we),si=_([0,0,0,0,0,0,0,0,6,0,0,0,8,0,0,0,10,0,0,0],["*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0],we),_(1,"void*",we),He.__str3342=_([115,116,100,58,58,98,97,100,95,97,108,108,111,99,0],"i8",we),ni=_([0,0,0,0,0,0,0,0,6,0,0,0,12,0,0,0,14,0,0,0],["*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0,"*",0,0,0],we),_(1,"void*",we),He.__str14343=_([98,97,100,95,97,114,114,97,121,95,110,101,119,95,108,101,110,103,116,104,0],"i8",we),He.__ZTSSt9bad_alloc=_([83,116,57,98,97,100,95,97,108,108,111,99,0],"i8",we),bi=_(12,"*",we),He.__ZTSSt20bad_array_new_length=_([83,116,50,48,98,97,100,95,97,114,114,97,121,95,110,101,119,95,108,101,110,103,116,104,0],"i8",we),ki=_(12,"*",we),Se[ri>>2]=0|He.__str,Se[ri+4>>2]=0|He.__str1,Se[ri+16>>2]=0|He.__str2,Se[ri+20>>2]=0|He.__str3,Se[ri+32>>2]=0|He.__str4,Se[ri+36>>2]=0|He.__str5,Se[ri+48>>2]=0|He.__str6,Se[ri+52>>2]=0|He.__str7,Se[ri+64>>2]=0|He.__str8,Se[ri+68>>2]=0|He.__str7,Se[ri+80>>2]=0|He.__str9,Se[ri+84>>2]=0|He.__str10,Se[ri+96>>2]=0|He.__str11,Se[ri+100>>2]=0|He.__str12,Se[ri+112>>2]=0|He.__str13,Se[ri+116>>2]=0|He.__str14,Se[ri+128>>2]=0|He.__str15,Se[ri+132>>2]=0|He.__str16,Se[ri+144>>2]=0|He.__str17,Se[ri+148>>2]=0|He.__str18,Se[ri+160>>2]=0|He.__str19,Se[ri+164>>2]=0|He.__str20,Se[ri+176>>2]=0|He.__str21,Se[ri+180>>2]=0|He.__str22,Se[ri+192>>2]=0|He.__str23,Se[ri+196>>2]=0|He.__str24,Se[ri+208>>2]=0|He.__str25,Se[ri+212>>2]=0|He.__str26,Se[ri+224>>2]=0|He.__str27,Se[ri+228>>2]=0|He.__str28,Se[ri+240>>2]=0|He.__str29,Se[ri+244>>2]=0|He.__str30,Se[ri+256>>2]=0|He.__str31,Se[ri+260>>2]=0|He.__str32,Se[ri+272>>2]=0|He.__str33,Se[ri+276>>2]=0|He.__str34,Se[ri+288>>2]=0|He.__str35,Se[ri+292>>2]=0|He.__str36,Se[ri+304>>2]=0|He.__str37,Se[ri+308>>2]=0|He.__str38,Se[ri+320>>2]=0|He.__str39,Se[ri+324>>2]=0|He.__str40,Se[ri+336>>2]=0|He.__str41,Se[ri+340>>2]=0|He.__str42,Se[ri+352>>2]=0|He.__str43,Se[ri+356>>2]=0|He.__str44,Se[ri+368>>2]=0|He.__str45,Se[ri+372>>2]=0|He.__str46,Se[ri+384>>2]=0|He.__str47,Se[ri+388>>2]=0|He.__str48,Se[ri+400>>2]=0|He.__str49,Se[ri+404>>2]=0|He.__str119289,Se[ri+416>>2]=0|He.__str51,Se[ri+420>>2]=0|He.__str20,Se[ri+432>>2]=0|He.__str52,Se[ri+436>>2]=0|He.__str53,Se[ri+448>>2]=0|He.__str54,Se[ri+452>>2]=0|He.__str55,Se[ri+464>>2]=0|He.__str56,Se[ri+468>>2]=0|He.__str57,Se[ri+480>>2]=0|He.__str58,Se[ri+484>>2]=0|He.__str119289,Se[ri+496>>2]=0|He.__str59,Se[ri+500>>2]=0|He.__str60,Se[ri+512>>2]=0|He.__str61,Se[ri+516>>2]=0|He.__str62,Se[ri+528>>2]=0|He.__str63,Se[ri+532>>2]=0|He.__str64,Se[ri+544>>2]=0|He.__str65,Se[ri+548>>2]=0|He.__str66,Se[ri+560>>2]=0|He.__str67,Se[ri+564>>2]=0|He.__str68,Se[ri+576>>2]=0|He.__str69,Se[ri+580>>2]=0|He.__str70,Se[ri+592>>2]=0|He.__str71,Se[ri+596>>2]=0|He.__str72,Se[ri+608>>2]=0|He.__str73,Se[ri+612>>2]=0|He.__str74,Se[ri+624>>2]=0|He.__str75,Se[ri+628>>2]=0|He.__str76,Se[ri+640>>2]=0|He.__str77,Se[ri+644>>2]=0|He.__str72,Se[ri+656>>2]=0|He.__str78,Se[ri+660>>2]=0|He.__str79,Se[ri+672>>2]=0|He.__str80,Se[ri+676>>2]=0|He.__str81,Se[ri+688>>2]=0|He.__str82,Se[ri+692>>2]=0|He.__str83,Se[ri+704>>2]=0|He.__str84,Se[ri+708>>2]=0|He.__str85,Se[ri+720>>2]=0|He.__str86,Se[ri+724>>2]=0|He.__str87,Se[ri+736>>2]=0|He.__str88,Se[ri+740>>2]=0|He.__str89,Se[ri+752>>2]=0|He.__str90,Se[ri+756>>2]=0|He.__str91,Se[ri+768>>2]=0|He.__str92,Se[ri+772>>2]=0|He.__str91,Se[ai>>2]=0|He.__str145315,Se[ai+8>>2]=0|He.__str145315,Se[ai+20>>2]=0|He.__str167337,Se[ai+28>>2]=0|He.__str95,Se[ai+40>>2]=0|He.__str146316,Se[ai+48>>2]=0|He.__str97,Se[ai+60>>2]=0|He.__str155325,Se[ai+68>>2]=0|He.__str155325,Se[ai+80>>2]=0|He.__str156326,Se[ai+88>>2]=0|He.__str156326,Se[ai+100>>2]=0|He.__str154324,Se[ai+108>>2]=0|He.__str154324,Se[ai+120>>2]=0|He.__str101,Se[ai+128>>2]=0|He.__str101,Se[ai+140>>2]=0|He.__str147317,Se[ai+148>>2]=0|He.__str147317,Se[ai+160>>2]=0|He.__str150320,Se[ai+168>>2]=0|He.__str150320,Se[ai+180>>2]=0|He.__str151321,Se[ai+188>>2]=0|He.__str105,Se[ai+220>>2]=0|He.__str152322,Se[ai+228>>2]=0|He.__str152322,Se[ai+240>>2]=0|He.__str153323,Se[ai+248>>2]=0|He.__str153323,Se[ai+260>>2]=0|He.__str165335,Se[ai+268>>2]=0|He.__str165335,Se[ai+280>>2]=0|He.__str166336,Se[ai+288>>2]=0|He.__str166336,Se[ai+360>>2]=0|He.__str148318,Se[ai+368>>2]=0|He.__str148318,Se[ai+380>>2]=0|He.__str149319,Se[ai+388>>2]=0|He.__str149319,Se[ai+420>>2]=0|He.__str84254,Se[ai+428>>2]=0|He.__str84254,Se[ai+440>>2]=0|He.__str168338,Se[ai+448>>2]=0|He.__str146316,Se[ai+460>>2]=0|He.__str114,Se[ai+468>>2]=0|He.__str152322,Se[ai+480>>2]=0|He.__str115,Se[ai+488>>2]=0|He.__str115,Se[ai+500>>2]=0|He.__str110280,Se[ai+508>>2]=0|He.__str110280,Se[ei+4>>2]=0|He.__str152,Se[ei+12>>2]=0|He.__str152,Se[ei+32>>2]=0|He.__str153,Se[ei+40>>2]=0|He.__str153,Se[ei+48>>2]=0|He.__str154,Se[ei+60>>2]=0|He.__str155,Se[ei+68>>2]=0|He.__str155,Se[ei+76>>2]=0|He.__str156,Se[ei+88>>2]=0|He.__str157,Se[ei+96>>2]=0|He.__str158,Se[ei+104>>2]=0|He.__str156,Se[ei+116>>2]=0|He.__str159,Se[ei+124>>2]=0|He.__str160,Se[ei+132>>2]=0|He.__str161,Se[ei+144>>2]=0|He.__str162,Se[ei+152>>2]=0|He.__str163,Se[ei+160>>2]=0|He.__str164,Se[ei+172>>2]=0|He.__str165,Se[ei+180>>2]=0|He.__str166,Se[ei+188>>2]=0|He.__str167,Se[si+4>>2]=bi,Se[ni+4>>2]=ki,oi=_([2,0,0,0,0],["i8*",0,0,0,0],we),Se[bi>>2]=oi+8|0,Se[bi+4>>2]=0|He.__ZTSSt9bad_alloc,Se[bi+8>>2]=li,Se[ki>>2]=oi+8|0,Se[ki+4>>2]=0|He.__ZTSSt20bad_array_new_length,Se[ki+8>>2]=bi,ui=16,ci=6,hi=18,di=6,wi=6,pe=[0,0,Jr,0,va,0,ya,0,ga,0,wa,0,Sa,0,pa,0,Ea,0,ma,0],Module.FUNCTION_TABLE=pe,Module.run=ee,Module.preRun&&Module.preRun(),0==Ke){ee()}Module.postRun&&Module.postRun(),Module.___cxa_demangle=G;var pi=v("__cxa_demangle","string",["string","string","number","number"]);return function(r){return pi(r,"",1,0)}}();\n';
},{}]},{},[180], null)
//# sourceMappingURL=demangle-cpp.8a387750.map
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/public/speedscope-1.5.3/import.a03c2bef.js
|
JavaScript
|
parcelRequire=function(e,r,n,t){var i="function"==typeof parcelRequire&&parcelRequire,o="function"==typeof require&&require;function u(n,t){if(!r[n]){if(!e[n]){var f="function"==typeof parcelRequire&&parcelRequire;if(!t&&f)return f(n,!0);if(i)return i(n,!0);if(o&&"string"==typeof n)return o(n);var c=new Error("Cannot find module '"+n+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[n][1][r]||r};var l=r[n]=new u.Module(n);e[n][0].call(l.exports,p,l,l.exports,this)}return r[n].exports;function p(e){return u(p.resolve(e))}}u.isParcelRequire=!0,u.Module=function(e){this.id=e,this.bundle=u,this.exports={}},u.modules=e,u.cache=r,u.parent=i,u.register=function(r,n){e[r]=[function(e,r){r.exports=n},{}]};for(var f=0;f<n.length;f++)u(n[f]);if(n.length){var c=u(n[n.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=c:"function"==typeof define&&define.amd?define(function(){return c}):t&&(this[t]=c)}return u}({172:[function(require,module,exports) {
"use strict";function e(e){const t=[];return function e(r){t.push({id:r.id,callFrame:{columnNumber:0,functionName:r.functionName,lineNumber:r.lineNumber,scriptId:r.scriptId,url:r.url},hitCount:r.hitCount,children:r.children.map(e=>e.id)}),r.children.forEach(e)}(e),t}function t(e,t){return e.map((r,n)=>{return r-(0===n?1e6*t:e[n-1])})}function r(r){return{samples:r.samples,startTime:1e6*r.startTime,endTime:1e6*r.endTime,nodes:e(r.head),timeDeltas:t(r.timestamps,r.startTime)}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.chromeTreeToNodes=r;
},{}],146:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isChromeTimeline=i,exports.importFromChromeTimeline=o,exports.importFromChromeCPUProfile=f,exports.importFromOldV8CPUProfile=u;var e=require("../lib/profile"),t=require("../lib/utils"),r=require("../lib/value-formatters"),n=require("./v8cpuFormatter");function i(e){if(!Array.isArray(e))return!1;if(e.length<1)return!1;const t=e[0];return"pid"in t&&"tid"in t&&"ph"in t&&"cat"in t&&!!e.find(e=>"CpuProfile"===e.name||"Profile"===e.name||"ProfileChunk"===e.name)}function o(e,r){const n=new Map,i=new Map,o=new Map;(0,t.sortBy)(e,e=>e.ts);for(let t of e){if("CpuProfile"===t.name){const e=`${t.pid}:${t.tid}`,r=t.id||e;n.set(r,t.args.data.cpuProfile),i.set(r,e)}if("Profile"===t.name){const e=`${t.pid}:${t.tid}`;n.set(t.id||e,Object.assign({startTime:0,endTime:0,nodes:[],samples:[],timeDeltas:[]},t.args.data)),t.id&&i.set(t.id,`${t.pid}:${t.tid}`)}if("thread_name"===t.name&&o.set(`${t.pid}:${t.tid}`,t.args.name),"ProfileChunk"===t.name){const e=`${t.pid}:${t.tid}`,r=n.get(t.id||e);if(r){const e=t.args.data;e.cpuProfile&&(e.cpuProfile.nodes&&(r.nodes=r.nodes.concat(e.cpuProfile.nodes)),e.cpuProfile.samples&&(r.samples=r.samples.concat(e.cpuProfile.samples))),e.timeDeltas&&(r.timeDeltas=r.timeDeltas.concat(e.timeDeltas)),null!=e.startTime&&(r.startTime=e.startTime),null!=e.endTime&&(r.endTime=e.endTime)}else console.warn(`Ignoring ProfileChunk for undeclared Profile with id ${t.id||e}`)}}if(n.size>0){const e=[];let l=0;return(0,t.itForEach)(n.keys(),t=>{let a=null,s=i.get(t);s&&(a=o.get(s)||null);const m=f(n.get(t));a&&n.size>1?(m.setName(`${r} - ${a}`),"CrRendererMain"===a&&(l=e.length)):m.setName(`${r}`),e.push(m)}),{name:r,indexToView:l,profiles:e}}throw new Error("Could not find CPU profile in Timeline")}const l=new Map;function a(e){return(0,t.getOrInsert)(l,e,e=>{const t=e.functionName||"(anonymous)",r=e.url,n=e.lineNumber,i=e.columnNumber;return{key:`${t}:${r}:${n}:${i}`,name:t,file:r,line:n,col:i}})}function s(e){const{functionName:t,url:r}=e;return"native dummy.js"===r||("(root)"===t||"(idle)"===t)}function m(e){return"(garbage collector)"===e||"(program)"===e}function f(n){const i=new e.CallTreeProfileBuilder(n.endTime-n.startTime),o=new Map;for(let e of n.nodes)o.set(e.id,e);for(let e of n.nodes)if("number"==typeof e.parent&&(e.parent=o.get(e.parent)),e.children)for(let t of e.children){const r=o.get(t);r&&(r.parent=e)}const l=[],f=[];let u=n.timeDeltas[0],c=NaN;for(let e=0;e<n.samples.length;e++){const t=n.samples[e];if(t!=c&&(l.push(t),f.push(u)),e===n.samples.length-1)isNaN(c)||(l.push(c),f.push(u));else{let r=n.timeDeltas[e+1];r<0&&(r=0),u+=r,c=t}}let p=[];for(let e=0;e<l.length;e++){const r=f[e],n=l[e];let u=o.get(n);if(!u)continue;let c=null;for(c=u;c&&-1===p.indexOf(c);c=m(c.callFrame.functionName)?(0,t.lastOf)(p):c.parent||null);for(;p.length>0&&(0,t.lastOf)(p)!=c;){const e=a(p.pop().callFrame);i.leaveFrame(e,r)}const d=[];for(let e=u;e&&e!=c&&!s(e.callFrame);e=m(e.callFrame.functionName)?(0,t.lastOf)(p):e.parent||null)d.push(e);d.reverse();for(let e of d)i.enterFrame(a(e.callFrame),r);p=p.concat(d)}for(let e=p.length-1;e>=0;e--)i.leaveFrame(a(p[e].callFrame),(0,t.lastOf)(f));return i.setValueFormatter(new r.TimeFormatter("microseconds")),i.build()}function u(e){return f((0,n.chromeTreeToNodes)(e))}
},{"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140,"./v8cpuFormatter":172}],147:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromStackprof=r;var e=require("../lib/profile"),t=require("../lib/value-formatters");function r(r){const o=r.raw_timestamp_deltas.reduce((e,t)=>e+t,0),a=new e.StackListProfileBuilder(o),{frames:l,raw:s,raw_timestamp_deltas:i}=r;let n=0,c=[];for(let e=0;e<s.length;){const t=s[e++];let r=[];for(let o=0;o<t;o++){const t=s[e++];r.push(Object.assign({key:t},l[t]))}1===r.length&&"(garbage collection)"===r[0].name&&(r=c.concat(r));const o=s[e++];let m=0;for(let e=0;e<o;e++)m+=i[n++];a.appendSampleWithWeight(r,m),c=r}return a.setValueFormatter(new t.TimeFormatter("microseconds")),a.build()}
},{"../lib/profile":139,"../lib/value-formatters":140}],178:[function(require,module,exports) {
"use strict";var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function t(r,t){return Object.prototype.hasOwnProperty.call(r,t)}exports.assign=function(r){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var a in n)t(n,a)&&(r[a]=n[a])}}return r},exports.shrinkBuf=function(r,t){return r.length===t?r:r.subarray?r.subarray(0,t):(r.length=t,r)};var e={arraySet:function(r,t,e,n,a){if(t.subarray&&r.subarray)r.set(t.subarray(e,e+n),a);else for(var o=0;o<n;o++)r[a+o]=t[e+o]},flattenChunks:function(r){var t,e,n,a,o,s;for(n=0,t=0,e=r.length;t<e;t++)n+=r[t].length;for(s=new Uint8Array(n),a=0,t=0,e=r.length;t<e;t++)o=r[t],s.set(o,a),a+=o.length;return s}},n={arraySet:function(r,t,e,n,a){for(var o=0;o<n;o++)r[a+o]=t[e+o]},flattenChunks:function(r){return[].concat.apply([],r)}};exports.setTyped=function(r){r?(exports.Buf8=Uint8Array,exports.Buf16=Uint16Array,exports.Buf32=Int32Array,exports.assign(exports,e)):(exports.Buf8=Array,exports.Buf16=Array,exports.Buf32=Array,exports.assign(exports,n))},exports.setTyped(r);
},{}],190:[function(require,module,exports) {
"use strict";var e=require("../utils/common"),t=4,n=0,_=1,r=2;function a(e){for(var t=e.length;--t>=0;)e[t]=0}var i=0,l=1,d=2,f=3,o=258,b=29,s=256,u=s+1+b,c=30,p=19,h=2*u+1,v=15,y=16,x=7,g=256,m=16,w=17,A=18,k=[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],q=[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],z=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],j=512,B=new Array(2*(u+2));a(B);var C=new Array(2*c);a(C);var D=new Array(j);a(D);var E=new Array(o-f+1);a(E);var F=new Array(b);a(F);var G,H,I,J=new Array(c);function K(e,t,n,_,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=_,this.max_length=r,this.has_stree=e&&e.length}function L(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function M(e){return e<256?D[e]:D[256+(e>>>7)]}function N(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function O(e,t,n){e.bi_valid>y-n?(e.bi_buf|=t<<e.bi_valid&65535,N(e,e.bi_buf),e.bi_buf=t>>y-e.bi_valid,e.bi_valid+=n-y):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)}function P(e,t,n){O(e,n[2*t],n[2*t+1])}function Q(e,t){var n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1}function R(e){16===e.bi_valid?(N(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}function T(e,t){var n,_,r,a,i,l,d=t.dyn_tree,f=t.max_code,o=t.stat_desc.static_tree,b=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,u=t.stat_desc.extra_base,c=t.stat_desc.max_length,p=0;for(a=0;a<=v;a++)e.bl_count[a]=0;for(d[2*e.heap[e.heap_max]+1]=0,n=e.heap_max+1;n<h;n++)(a=d[2*d[2*(_=e.heap[n])+1]+1]+1)>c&&(a=c,p++),d[2*_+1]=a,_>f||(e.bl_count[a]++,i=0,_>=u&&(i=s[_-u]),l=d[2*_],e.opt_len+=l*(a+i),b&&(e.static_len+=l*(o[2*_+1]+i)));if(0!==p){do{for(a=c-1;0===e.bl_count[a];)a--;e.bl_count[a]--,e.bl_count[a+1]+=2,e.bl_count[c]--,p-=2}while(p>0);for(a=c;0!==a;a--)for(_=e.bl_count[a];0!==_;)(r=e.heap[--n])>f||(d[2*r+1]!==a&&(e.opt_len+=(a-d[2*r+1])*d[2*r],d[2*r+1]=a),_--)}}function U(e,t,n){var _,r,a=new Array(v+1),i=0;for(_=1;_<=v;_++)a[_]=i=i+n[_-1]<<1;for(r=0;r<=t;r++){var l=e[2*r+1];0!==l&&(e[2*r]=Q(a[l]++,l))}}function V(){var e,t,n,_,r,a=new Array(v+1);for(n=0,_=0;_<b-1;_++)for(F[_]=n,e=0;e<1<<k[_];e++)E[n++]=_;for(E[n-1]=_,r=0,_=0;_<16;_++)for(J[_]=r,e=0;e<1<<q[_];e++)D[r++]=_;for(r>>=7;_<c;_++)for(J[_]=r<<7,e=0;e<1<<q[_]-7;e++)D[256+r++]=_;for(t=0;t<=v;t++)a[t]=0;for(e=0;e<=143;)B[2*e+1]=8,e++,a[8]++;for(;e<=255;)B[2*e+1]=9,e++,a[9]++;for(;e<=279;)B[2*e+1]=7,e++,a[7]++;for(;e<=287;)B[2*e+1]=8,e++,a[8]++;for(U(B,u+1,a),e=0;e<c;e++)C[2*e+1]=5,C[2*e]=Q(e,5);G=new K(B,k,s+1,u,v),H=new K(C,q,0,c,v),I=new K(new Array(0),z,0,p,x)}function W(e){var t;for(t=0;t<u;t++)e.dyn_ltree[2*t]=0;for(t=0;t<c;t++)e.dyn_dtree[2*t]=0;for(t=0;t<p;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*g]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function X(e){e.bi_valid>8?N(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Y(t,n,_,r){X(t),r&&(N(t,_),N(t,~_)),e.arraySet(t.pending_buf,t.window,n,_,t.pending),t.pending+=_}function Z(e,t,n,_){var r=2*t,a=2*n;return e[r]<e[a]||e[r]===e[a]&&_[t]<=_[n]}function $(e,t,n){for(var _=e.heap[n],r=n<<1;r<=e.heap_len&&(r<e.heap_len&&Z(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!Z(t,_,e.heap[r],e.depth));)e.heap[n]=e.heap[r],n=r,r<<=1;e.heap[n]=_}function ee(e,t,n){var _,r,a,i,l=0;if(0!==e.last_lit)do{_=e.pending_buf[e.d_buf+2*l]<<8|e.pending_buf[e.d_buf+2*l+1],r=e.pending_buf[e.l_buf+l],l++,0===_?P(e,r,t):(P(e,(a=E[r])+s+1,t),0!==(i=k[a])&&O(e,r-=F[a],i),P(e,a=M(--_),n),0!==(i=q[a])&&O(e,_-=J[a],i))}while(l<e.last_lit);P(e,g,t)}function te(e,t){var n,_,r,a=t.dyn_tree,i=t.stat_desc.static_tree,l=t.stat_desc.has_stree,d=t.stat_desc.elems,f=-1;for(e.heap_len=0,e.heap_max=h,n=0;n<d;n++)0!==a[2*n]?(e.heap[++e.heap_len]=f=n,e.depth[n]=0):a[2*n+1]=0;for(;e.heap_len<2;)a[2*(r=e.heap[++e.heap_len]=f<2?++f:0)]=1,e.depth[r]=0,e.opt_len--,l&&(e.static_len-=i[2*r+1]);for(t.max_code=f,n=e.heap_len>>1;n>=1;n--)$(e,a,n);r=d;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],$(e,a,1),_=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=_,a[2*r]=a[2*n]+a[2*_],e.depth[r]=(e.depth[n]>=e.depth[_]?e.depth[n]:e.depth[_])+1,a[2*n+1]=a[2*_+1]=r,e.heap[1]=r++,$(e,a,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],T(e,t),U(a,f,e.bl_count)}function ne(e,t,n){var _,r,a=-1,i=t[1],l=0,d=7,f=4;for(0===i&&(d=138,f=3),t[2*(n+1)+1]=65535,_=0;_<=n;_++)r=i,i=t[2*(_+1)+1],++l<d&&r===i||(l<f?e.bl_tree[2*r]+=l:0!==r?(r!==a&&e.bl_tree[2*r]++,e.bl_tree[2*m]++):l<=10?e.bl_tree[2*w]++:e.bl_tree[2*A]++,l=0,a=r,0===i?(d=138,f=3):r===i?(d=6,f=3):(d=7,f=4))}function _e(e,t,n){var _,r,a=-1,i=t[1],l=0,d=7,f=4;for(0===i&&(d=138,f=3),_=0;_<=n;_++)if(r=i,i=t[2*(_+1)+1],!(++l<d&&r===i)){if(l<f)do{P(e,r,e.bl_tree)}while(0!=--l);else 0!==r?(r!==a&&(P(e,r,e.bl_tree),l--),P(e,m,e.bl_tree),O(e,l-3,2)):l<=10?(P(e,w,e.bl_tree),O(e,l-3,3)):(P(e,A,e.bl_tree),O(e,l-11,7));l=0,a=r,0===i?(d=138,f=3):r===i?(d=6,f=3):(d=7,f=4)}}function re(e){var t;for(ne(e,e.dyn_ltree,e.l_desc.max_code),ne(e,e.dyn_dtree,e.d_desc.max_code),te(e,e.bl_desc),t=p-1;t>=3&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}function ae(e,t,n,_){var r;for(O(e,t-257,5),O(e,n-1,5),O(e,_-4,4),r=0;r<_;r++)O(e,e.bl_tree[2*S[r]+1],3);_e(e,e.dyn_ltree,t-1),_e(e,e.dyn_dtree,n-1)}function ie(e){var t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return n;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return _;for(t=32;t<s;t++)if(0!==e.dyn_ltree[2*t])return _;return n}a(J);var le=!1;function de(e){le||(V(),le=!0),e.l_desc=new L(e.dyn_ltree,G),e.d_desc=new L(e.dyn_dtree,H),e.bl_desc=new L(e.bl_tree,I),e.bi_buf=0,e.bi_valid=0,W(e)}function fe(e,t,n,_){O(e,(i<<1)+(_?1:0),3),Y(e,t,n,!0)}function oe(e){O(e,l<<1,3),P(e,g,B),R(e)}function be(e,n,_,a){var i,f,o=0;e.level>0?(e.strm.data_type===r&&(e.strm.data_type=ie(e)),te(e,e.l_desc),te(e,e.d_desc),o=re(e),i=e.opt_len+3+7>>>3,(f=e.static_len+3+7>>>3)<=i&&(i=f)):i=f=_+5,_+4<=i&&-1!==n?fe(e,n,_,a):e.strategy===t||f===i?(O(e,(l<<1)+(a?1:0),3),ee(e,B,C)):(O(e,(d<<1)+(a?1:0),3),ae(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),ee(e,e.dyn_ltree,e.dyn_dtree)),W(e),a&&X(e)}function se(e,t,n){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&n,e.last_lit++,0===t?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(E[n]+s+1)]++,e.dyn_dtree[2*M(t)]++),e.last_lit===e.lit_bufsize-1}exports._tr_init=de,exports._tr_stored_block=fe,exports._tr_flush_block=be,exports._tr_tally=se,exports._tr_align=oe;
},{"../utils/common":178}],191:[function(require,module,exports) {
"use strict";function e(e,r,o,t){for(var u=65535&e|0,i=e>>>16&65535|0,n=0;0!==o;){o-=n=o>2e3?2e3:o;do{i=i+(u=u+r[t++]|0)|0}while(--n);u%=65521,i%=65521}return u|i<<16|0}module.exports=e;
},{}],192:[function(require,module,exports) {
"use strict";function r(){for(var r,o=[],t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=1&r?3988292384^r>>>1:r>>>1;o[t]=r}return o}var o=r();function t(r,t,n,u){var a=o,e=u+n;r^=-1;for(var f=u;f<e;f++)r=r>>>8^a[255&(r^t[f])];return-1^r}module.exports=t;
},{}],185:[function(require,module,exports) {
"use strict";module.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"};
},{}],182:[function(require,module,exports) {
"use strict";var t,a=require("../utils/common"),e=require("./trees"),s=require("./adler32"),i=require("./crc32"),r=require("./messages"),n=0,h=1,l=3,_=4,d=5,o=0,u=1,g=-2,f=-3,c=-5,p=-1,m=1,w=2,v=3,k=4,z=0,b=2,x=8,y=9,B=15,S=8,q=29,I=256,A=I+1+q,C=30,R=19,j=2*A+1,D=15,E=3,H=258,K=H+E+1,N=32,F=42,G=69,J=73,L=91,M=103,O=113,P=666,Q=1,T=2,U=3,V=4,W=3;function X(t,a){return t.msg=r[a],a}function Y(t){return(t<<1)-(t>4?9:0)}function Z(t){for(var a=t.length;--a>=0;)t[a]=0}function $(t){var e=t.state,s=e.pending;s>t.avail_out&&(s=t.avail_out),0!==s&&(a.arraySet(t.output,e.pending_buf,e.pending_out,s,t.next_out),t.next_out+=s,e.pending_out+=s,t.total_out+=s,t.avail_out-=s,e.pending-=s,0===e.pending&&(e.pending_out=0))}function tt(t,a){e._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,a),t.block_start=t.strstart,$(t.strm)}function at(t,a){t.pending_buf[t.pending++]=a}function et(t,a){t.pending_buf[t.pending++]=a>>>8&255,t.pending_buf[t.pending++]=255&a}function st(t,e,r,n){var h=t.avail_in;return h>n&&(h=n),0===h?0:(t.avail_in-=h,a.arraySet(e,t.input,t.next_in,h,r),1===t.state.wrap?t.adler=s(t.adler,e,h,r):2===t.state.wrap&&(t.adler=i(t.adler,e,h,r)),t.next_in+=h,t.total_in+=h,h)}function it(t,a){var e,s,i=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match,l=t.strstart>t.w_size-K?t.strstart-(t.w_size-K):0,_=t.window,d=t.w_mask,o=t.prev,u=t.strstart+H,g=_[r+n-1],f=_[r+n];t.prev_length>=t.good_match&&(i>>=2),h>t.lookahead&&(h=t.lookahead);do{if(_[(e=a)+n]===f&&_[e+n-1]===g&&_[e]===_[r]&&_[++e]===_[r+1]){r+=2,e++;do{}while(_[++r]===_[++e]&&_[++r]===_[++e]&&_[++r]===_[++e]&&_[++r]===_[++e]&&_[++r]===_[++e]&&_[++r]===_[++e]&&_[++r]===_[++e]&&_[++r]===_[++e]&&r<u);if(s=H-(u-r),r=u-H,s>n){if(t.match_start=a,n=s,s>=h)break;g=_[r+n-1],f=_[r+n]}}}while((a=o[a&d])>l&&0!=--i);return n<=t.lookahead?n:t.lookahead}function rt(t){var e,s,i,r,n,h=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=h+(h-K)){a.arraySet(t.window,t.window,h,h,0),t.match_start-=h,t.strstart-=h,t.block_start-=h,e=s=t.hash_size;do{i=t.head[--e],t.head[e]=i>=h?i-h:0}while(--s);e=s=h;do{i=t.prev[--e],t.prev[e]=i>=h?i-h:0}while(--s);r+=h}if(0===t.strm.avail_in)break;if(s=st(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=s,t.lookahead+t.insert>=E)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=(t.ins_h<<t.hash_shift^t.window[n+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[n+E-1])&t.hash_mask,t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<E)););}while(t.lookahead<K&&0!==t.strm.avail_in)}function nt(t,a){var e=65535;for(e>t.pending_buf_size-5&&(e=t.pending_buf_size-5);;){if(t.lookahead<=1){if(rt(t),0===t.lookahead&&a===n)return Q;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var s=t.block_start+e;if((0===t.strstart||t.strstart>=s)&&(t.lookahead=t.strstart-s,t.strstart=s,tt(t,!1),0===t.strm.avail_out))return Q;if(t.strstart-t.block_start>=t.w_size-K&&(tt(t,!1),0===t.strm.avail_out))return Q}return t.insert=0,a===_?(tt(t,!0),0===t.strm.avail_out?U:V):(t.strstart>t.block_start&&(tt(t,!1),t.strm.avail_out),Q)}function ht(t,a){for(var s,i;;){if(t.lookahead<K){if(rt(t),t.lookahead<K&&a===n)return Q;if(0===t.lookahead)break}if(s=0,t.lookahead>=E&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+E-1])&t.hash_mask,s=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==s&&t.strstart-s<=t.w_size-K&&(t.match_length=it(t,s)),t.match_length>=E)if(i=e._tr_tally(t,t.strstart-t.match_start,t.match_length-E),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=E){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+E-1])&t.hash_mask,s=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else i=e._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(tt(t,!1),0===t.strm.avail_out))return Q}return t.insert=t.strstart<E-1?t.strstart:E-1,a===_?(tt(t,!0),0===t.strm.avail_out?U:V):t.last_lit&&(tt(t,!1),0===t.strm.avail_out)?Q:T}function lt(t,a){for(var s,i,r;;){if(t.lookahead<K){if(rt(t),t.lookahead<K&&a===n)return Q;if(0===t.lookahead)break}if(s=0,t.lookahead>=E&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+E-1])&t.hash_mask,s=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=E-1,0!==s&&t.prev_length<t.max_lazy_match&&t.strstart-s<=t.w_size-K&&(t.match_length=it(t,s),t.match_length<=5&&(t.strategy===m||t.match_length===E&&t.strstart-t.match_start>4096)&&(t.match_length=E-1)),t.prev_length>=E&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-E,i=e._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-E),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=r&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+E-1])&t.hash_mask,s=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=E-1,t.strstart++,i&&(tt(t,!1),0===t.strm.avail_out))return Q}else if(t.match_available){if((i=e._tr_tally(t,0,t.window[t.strstart-1]))&&tt(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return Q}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=e._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<E-1?t.strstart:E-1,a===_?(tt(t,!0),0===t.strm.avail_out?U:V):t.last_lit&&(tt(t,!1),0===t.strm.avail_out)?Q:T}function _t(t,a){for(var s,i,r,h,l=t.window;;){if(t.lookahead<=H){if(rt(t),t.lookahead<=H&&a===n)return Q;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=E&&t.strstart>0&&(i=l[r=t.strstart-1])===l[++r]&&i===l[++r]&&i===l[++r]){h=t.strstart+H;do{}while(i===l[++r]&&i===l[++r]&&i===l[++r]&&i===l[++r]&&i===l[++r]&&i===l[++r]&&i===l[++r]&&i===l[++r]&&r<h);t.match_length=H-(h-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=E?(s=e._tr_tally(t,1,t.match_length-E),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(s=e._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),s&&(tt(t,!1),0===t.strm.avail_out))return Q}return t.insert=0,a===_?(tt(t,!0),0===t.strm.avail_out?U:V):t.last_lit&&(tt(t,!1),0===t.strm.avail_out)?Q:T}function dt(t,a){for(var s;;){if(0===t.lookahead&&(rt(t),0===t.lookahead)){if(a===n)return Q;break}if(t.match_length=0,s=e._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,s&&(tt(t,!1),0===t.strm.avail_out))return Q}return t.insert=0,a===_?(tt(t,!0),0===t.strm.avail_out?U:V):t.last_lit&&(tt(t,!1),0===t.strm.avail_out)?Q:T}function ot(t,a,e,s,i){this.good_length=t,this.max_lazy=a,this.nice_length=e,this.max_chain=s,this.func=i}function ut(a){a.window_size=2*a.w_size,Z(a.head),a.max_lazy_match=t[a.level].max_lazy,a.good_match=t[a.level].good_length,a.nice_match=t[a.level].nice_length,a.max_chain_length=t[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=E-1,a.match_available=0,a.ins_h=0}function gt(){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=x,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 a.Buf16(2*j),this.dyn_dtree=new a.Buf16(2*(2*C+1)),this.bl_tree=new a.Buf16(2*(2*R+1)),Z(this.dyn_ltree),Z(this.dyn_dtree),Z(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new a.Buf16(D+1),this.heap=new a.Buf16(2*A+1),Z(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new a.Buf16(2*A+1),Z(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 ft(t){var a;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=b,(a=t.state).pending=0,a.pending_out=0,a.wrap<0&&(a.wrap=-a.wrap),a.status=a.wrap?F:O,t.adler=2===a.wrap?0:1,a.last_flush=n,e._tr_init(a),o):X(t,g)}function ct(t){var a=ft(t);return a===o&&ut(t.state),a}function pt(t,a){return t&&t.state?2!==t.state.wrap?g:(t.state.gzhead=a,o):g}function mt(t,e,s,i,r,n){if(!t)return g;var h=1;if(e===p&&(e=6),i<0?(h=0,i=-i):i>15&&(h=2,i-=16),r<1||r>y||s!==x||i<8||i>15||e<0||e>9||n<0||n>k)return X(t,g);8===i&&(i=9);var l=new gt;return t.state=l,l.strm=t,l.wrap=h,l.gzhead=null,l.w_bits=i,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+E-1)/E),l.window=new a.Buf8(2*l.w_size),l.head=new a.Buf16(l.hash_size),l.prev=new a.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new a.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=n,l.method=s,ct(t)}function wt(t,a){return mt(t,a,x,B,S,z)}function vt(a,s){var r,f,p,m;if(!a||!a.state||s>d||s<0)return a?X(a,g):g;if(f=a.state,!a.output||!a.input&&0!==a.avail_in||f.status===P&&s!==_)return X(a,0===a.avail_out?c:g);if(f.strm=a,r=f.last_flush,f.last_flush=s,f.status===F)if(2===f.wrap)a.adler=0,at(f,31),at(f,139),at(f,8),f.gzhead?(at(f,(f.gzhead.text?1:0)+(f.gzhead.hcrc?2:0)+(f.gzhead.extra?4:0)+(f.gzhead.name?8:0)+(f.gzhead.comment?16:0)),at(f,255&f.gzhead.time),at(f,f.gzhead.time>>8&255),at(f,f.gzhead.time>>16&255),at(f,f.gzhead.time>>24&255),at(f,9===f.level?2:f.strategy>=w||f.level<2?4:0),at(f,255&f.gzhead.os),f.gzhead.extra&&f.gzhead.extra.length&&(at(f,255&f.gzhead.extra.length),at(f,f.gzhead.extra.length>>8&255)),f.gzhead.hcrc&&(a.adler=i(a.adler,f.pending_buf,f.pending,0)),f.gzindex=0,f.status=G):(at(f,0),at(f,0),at(f,0),at(f,0),at(f,0),at(f,9===f.level?2:f.strategy>=w||f.level<2?4:0),at(f,W),f.status=O);else{var k=x+(f.w_bits-8<<4)<<8;k|=(f.strategy>=w||f.level<2?0:f.level<6?1:6===f.level?2:3)<<6,0!==f.strstart&&(k|=N),k+=31-k%31,f.status=O,et(f,k),0!==f.strstart&&(et(f,a.adler>>>16),et(f,65535&a.adler)),a.adler=1}if(f.status===G)if(f.gzhead.extra){for(p=f.pending;f.gzindex<(65535&f.gzhead.extra.length)&&(f.pending!==f.pending_buf_size||(f.gzhead.hcrc&&f.pending>p&&(a.adler=i(a.adler,f.pending_buf,f.pending-p,p)),$(a),p=f.pending,f.pending!==f.pending_buf_size));)at(f,255&f.gzhead.extra[f.gzindex]),f.gzindex++;f.gzhead.hcrc&&f.pending>p&&(a.adler=i(a.adler,f.pending_buf,f.pending-p,p)),f.gzindex===f.gzhead.extra.length&&(f.gzindex=0,f.status=J)}else f.status=J;if(f.status===J)if(f.gzhead.name){p=f.pending;do{if(f.pending===f.pending_buf_size&&(f.gzhead.hcrc&&f.pending>p&&(a.adler=i(a.adler,f.pending_buf,f.pending-p,p)),$(a),p=f.pending,f.pending===f.pending_buf_size)){m=1;break}m=f.gzindex<f.gzhead.name.length?255&f.gzhead.name.charCodeAt(f.gzindex++):0,at(f,m)}while(0!==m);f.gzhead.hcrc&&f.pending>p&&(a.adler=i(a.adler,f.pending_buf,f.pending-p,p)),0===m&&(f.gzindex=0,f.status=L)}else f.status=L;if(f.status===L)if(f.gzhead.comment){p=f.pending;do{if(f.pending===f.pending_buf_size&&(f.gzhead.hcrc&&f.pending>p&&(a.adler=i(a.adler,f.pending_buf,f.pending-p,p)),$(a),p=f.pending,f.pending===f.pending_buf_size)){m=1;break}m=f.gzindex<f.gzhead.comment.length?255&f.gzhead.comment.charCodeAt(f.gzindex++):0,at(f,m)}while(0!==m);f.gzhead.hcrc&&f.pending>p&&(a.adler=i(a.adler,f.pending_buf,f.pending-p,p)),0===m&&(f.status=M)}else f.status=M;if(f.status===M&&(f.gzhead.hcrc?(f.pending+2>f.pending_buf_size&&$(a),f.pending+2<=f.pending_buf_size&&(at(f,255&a.adler),at(f,a.adler>>8&255),a.adler=0,f.status=O)):f.status=O),0!==f.pending){if($(a),0===a.avail_out)return f.last_flush=-1,o}else if(0===a.avail_in&&Y(s)<=Y(r)&&s!==_)return X(a,c);if(f.status===P&&0!==a.avail_in)return X(a,c);if(0!==a.avail_in||0!==f.lookahead||s!==n&&f.status!==P){var z=f.strategy===w?dt(f,s):f.strategy===v?_t(f,s):t[f.level].func(f,s);if(z!==U&&z!==V||(f.status=P),z===Q||z===U)return 0===a.avail_out&&(f.last_flush=-1),o;if(z===T&&(s===h?e._tr_align(f):s!==d&&(e._tr_stored_block(f,0,0,!1),s===l&&(Z(f.head),0===f.lookahead&&(f.strstart=0,f.block_start=0,f.insert=0))),$(a),0===a.avail_out))return f.last_flush=-1,o}return s!==_?o:f.wrap<=0?u:(2===f.wrap?(at(f,255&a.adler),at(f,a.adler>>8&255),at(f,a.adler>>16&255),at(f,a.adler>>24&255),at(f,255&a.total_in),at(f,a.total_in>>8&255),at(f,a.total_in>>16&255),at(f,a.total_in>>24&255)):(et(f,a.adler>>>16),et(f,65535&a.adler)),$(a),f.wrap>0&&(f.wrap=-f.wrap),0!==f.pending?o:u)}function kt(t){var a;return t&&t.state?(a=t.state.status)!==F&&a!==G&&a!==J&&a!==L&&a!==M&&a!==O&&a!==P?X(t,g):(t.state=null,a===O?X(t,f):o):g}function zt(t,e){var i,r,n,h,l,_,d,u,f=e.length;if(!t||!t.state)return g;if(2===(h=(i=t.state).wrap)||1===h&&i.status!==F||i.lookahead)return g;for(1===h&&(t.adler=s(t.adler,e,f,0)),i.wrap=0,f>=i.w_size&&(0===h&&(Z(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new a.Buf8(i.w_size),a.arraySet(u,e,f-i.w_size,i.w_size,0),e=u,f=i.w_size),l=t.avail_in,_=t.next_in,d=t.input,t.avail_in=f,t.next_in=0,t.input=e,rt(i);i.lookahead>=E;){r=i.strstart,n=i.lookahead-(E-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[r+E-1])&i.hash_mask,i.prev[r&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=r,r++}while(--n);i.strstart=r,i.lookahead=E-1,rt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=E-1,i.match_available=0,t.next_in=_,t.input=d,t.avail_in=l,i.wrap=h,o}t=[new ot(0,0,0,0,nt),new ot(4,4,8,4,ht),new ot(4,5,16,8,ht),new ot(4,6,32,32,ht),new ot(4,4,16,16,lt),new ot(8,16,32,32,lt),new ot(8,16,128,128,lt),new ot(8,32,128,256,lt),new ot(32,128,258,1024,lt),new ot(32,258,258,4096,lt)],exports.deflateInit=wt,exports.deflateInit2=mt,exports.deflateReset=ct,exports.deflateResetKeep=ft,exports.deflateSetHeader=pt,exports.deflate=vt,exports.deflateEnd=kt,exports.deflateSetDictionary=zt,exports.deflateInfo="pako deflate (from Nodeca project)";
},{"../utils/common":178,"./trees":190,"./adler32":191,"./crc32":192,"./messages":185}],183:[function(require,module,exports) {
"use strict";var r=require("./common"),n=!0,t=!0;try{String.fromCharCode.apply(null,[0])}catch(r){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(r){t=!1}for(var e=new r.Buf8(256),o=0;o<256;o++)e[o]=o>=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;function f(e,o){if(o<65537&&(e.subarray&&t||!e.subarray&&n))return String.fromCharCode.apply(null,r.shrinkBuf(e,o));for(var f="",u=0;u<o;u++)f+=String.fromCharCode(e[u]);return f}e[254]=e[254]=1,exports.string2buf=function(n){var t,e,o,f,u,a=n.length,i=0;for(f=0;f<a;f++)55296==(64512&(e=n.charCodeAt(f)))&&f+1<a&&56320==(64512&(o=n.charCodeAt(f+1)))&&(e=65536+(e-55296<<10)+(o-56320),f++),i+=e<128?1:e<2048?2:e<65536?3:4;for(t=new r.Buf8(i),u=0,f=0;u<i;f++)55296==(64512&(e=n.charCodeAt(f)))&&f+1<a&&56320==(64512&(o=n.charCodeAt(f+1)))&&(e=65536+(e-55296<<10)+(o-56320),f++),e<128?t[u++]=e:e<2048?(t[u++]=192|e>>>6,t[u++]=128|63&e):e<65536?(t[u++]=224|e>>>12,t[u++]=128|e>>>6&63,t[u++]=128|63&e):(t[u++]=240|e>>>18,t[u++]=128|e>>>12&63,t[u++]=128|e>>>6&63,t[u++]=128|63&e);return t},exports.buf2binstring=function(r){return f(r,r.length)},exports.binstring2buf=function(n){for(var t=new r.Buf8(n.length),e=0,o=t.length;e<o;e++)t[e]=n.charCodeAt(e);return t},exports.buf2string=function(r,n){var t,o,u,a,i=n||r.length,h=new Array(2*i);for(o=0,t=0;t<i;)if((u=r[t++])<128)h[o++]=u;else if((a=e[u])>4)h[o++]=65533,t+=a-1;else{for(u&=2===a?31:3===a?15:7;a>1&&t<i;)u=u<<6|63&r[t++],a--;a>1?h[o++]=65533:u<65536?h[o++]=u:(u-=65536,h[o++]=55296|u>>10&1023,h[o++]=56320|1023&u)}return f(h,o)},exports.utf8border=function(r,n){var t;for((n=n||r.length)>r.length&&(n=r.length),t=n-1;t>=0&&128==(192&r[t]);)t--;return t<0?n:0===t?n:t+e[r[t]]>n?t:n};
},{"./common":178}],184:[function(require,module,exports) {
"use strict";function t(){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}module.exports=t;
},{}],176:[function(require,module,exports) {
"use strict";var t=require("./zlib/deflate"),i=require("./utils/common"),e=require("./utils/strings"),n=require("./zlib/messages"),r=require("./zlib/zstream"),s=Object.prototype.toString,o=0,a=4,u=0,h=1,d=2,l=-1,f=0,p=8;function w(o){if(!(this instanceof w))return new w(o);this.options=i.assign({level:l,method:p,chunkSize:16384,windowBits:15,memLevel:8,strategy:f,to:""},o||{});var a=this.options;a.raw&&a.windowBits>0?a.windowBits=-a.windowBits:a.gzip&&a.windowBits>0&&a.windowBits<16&&(a.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new r,this.strm.avail_out=0;var h=t.deflateInit2(this.strm,a.level,a.method,a.windowBits,a.memLevel,a.strategy);if(h!==u)throw new Error(n[h]);if(a.header&&t.deflateSetHeader(this.strm,a.header),a.dictionary){var d;if(d="string"==typeof a.dictionary?e.string2buf(a.dictionary):"[object ArrayBuffer]"===s.call(a.dictionary)?new Uint8Array(a.dictionary):a.dictionary,(h=t.deflateSetDictionary(this.strm,d))!==u)throw new Error(n[h]);this._dict_set=!0}}function c(t,i){var e=new w(i);if(e.push(t,!0),e.err)throw e.msg||n[e.err];return e.result}function m(t,i){return(i=i||{}).raw=!0,c(t,i)}function g(t,i){return(i=i||{}).gzip=!0,c(t,i)}w.prototype.push=function(n,r){var l,f,p=this.strm,w=this.options.chunkSize;if(this.ended)return!1;f=r===~~r?r:!0===r?a:o,"string"==typeof n?p.input=e.string2buf(n):"[object ArrayBuffer]"===s.call(n)?p.input=new Uint8Array(n):p.input=n,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new i.Buf8(w),p.next_out=0,p.avail_out=w),(l=t.deflate(p,f))!==h&&l!==u)return this.onEnd(l),this.ended=!0,!1;0!==p.avail_out&&(0!==p.avail_in||f!==a&&f!==d)||("string"===this.options.to?this.onData(e.buf2binstring(i.shrinkBuf(p.output,p.next_out))):this.onData(i.shrinkBuf(p.output,p.next_out)))}while((p.avail_in>0||0===p.avail_out)&&l!==h);return f===a?(l=t.deflateEnd(this.strm),this.onEnd(l),this.ended=!0,l===u):f!==d||(this.onEnd(u),p.avail_out=0,!0)},w.prototype.onData=function(t){this.chunks.push(t)},w.prototype.onEnd=function(t){t===u&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},exports.Deflate=w,exports.deflate=c,exports.deflateRaw=m,exports.gzip=g;
},{"./zlib/deflate":182,"./utils/common":178,"./utils/strings":183,"./zlib/messages":185,"./zlib/zstream":184}],199:[function(require,module,exports) {
"use strict";var i=30,e=12;module.exports=function(o,a){var t,d,n,l,s,f,r,b,c,u,v,m,w,h,k,_,x,g,p,z,j,q,y,A,B;t=o.state,d=o.next_in,A=o.input,n=d+(o.avail_in-5),l=o.next_out,B=o.output,s=l-(a-o.avail_out),f=l+(o.avail_out-257),r=t.dmax,b=t.wsize,c=t.whave,u=t.wnext,v=t.window,m=t.hold,w=t.bits,h=t.lencode,k=t.distcode,_=(1<<t.lenbits)-1,x=(1<<t.distbits)-1;i:do{w<15&&(m+=A[d++]<<w,w+=8,m+=A[d++]<<w,w+=8),g=h[m&_];e:for(;;){if(m>>>=p=g>>>24,w-=p,0===(p=g>>>16&255))B[l++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=h[(65535&g)+(m&(1<<p)-1)];continue e}if(32&p){t.mode=e;break i}o.msg="invalid literal/length code",t.mode=i;break i}z=65535&g,(p&=15)&&(w<p&&(m+=A[d++]<<w,w+=8),z+=m&(1<<p)-1,m>>>=p,w-=p),w<15&&(m+=A[d++]<<w,w+=8,m+=A[d++]<<w,w+=8),g=k[m&x];o:for(;;){if(m>>>=p=g>>>24,w-=p,!(16&(p=g>>>16&255))){if(0==(64&p)){g=k[(65535&g)+(m&(1<<p)-1)];continue o}o.msg="invalid distance code",t.mode=i;break i}if(j=65535&g,w<(p&=15)&&(m+=A[d++]<<w,(w+=8)<p&&(m+=A[d++]<<w,w+=8)),(j+=m&(1<<p)-1)>r){o.msg="invalid distance too far back",t.mode=i;break i}if(m>>>=p,w-=p,j>(p=l-s)){if((p=j-p)>c&&t.sane){o.msg="invalid distance too far back",t.mode=i;break i}if(q=0,y=v,0===u){if(q+=b-p,p<z){z-=p;do{B[l++]=v[q++]}while(--p);q=l-j,y=B}}else if(u<p){if(q+=b+u-p,(p-=u)<z){z-=p;do{B[l++]=v[q++]}while(--p);if(q=0,u<z){z-=p=u;do{B[l++]=v[q++]}while(--p);q=l-j,y=B}}}else if(q+=u-p,p<z){z-=p;do{B[l++]=v[q++]}while(--p);q=l-j,y=B}for(;z>2;)B[l++]=y[q++],B[l++]=y[q++],B[l++]=y[q++],z-=3;z&&(B[l++]=y[q++],z>1&&(B[l++]=y[q++]))}else{q=l-j;do{B[l++]=B[q++],B[l++]=B[q++],B[l++]=B[q++],z-=3}while(z>2);z&&(B[l++]=B[q++],z>1&&(B[l++]=B[q++]))}break}}break}}while(d<n&&l<f);d-=z=w>>3,m&=(1<<(w-=z<<3))-1,o.next_in=d,o.next_out=l,o.avail_in=d<n?n-d+5:5-(d-n),o.avail_out=l<f?f-l+257:257-(l-f),t.hold=m,t.bits=w};
},{}],200:[function(require,module,exports) {
"use strict";var r=require("../utils/common"),f=15,i=852,o=592,e=0,u=1,t=2,n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],s=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],b=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];module.exports=function(a,c,m,w,d,v,B,h){var k,p,q,x,g,j,y,z,A,C=h.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new r.Buf16(f+1),Q=new r.Buf16(f+1),R=null,S=0;for(D=0;D<=f;D++)P[D]=0;for(E=0;E<w;E++)P[c[m+E]]++;for(H=C,G=f;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return d[v++]=20971520,d[v++]=20971520,h.bits=1,0;for(F=1;F<G&&0===P[F];F++);for(H<F&&(H=F),K=1,D=1;D<=f;D++)if(K<<=1,(K-=P[D])<0)return-1;if(K>0&&(a===e||1!==G))return-1;for(Q[1]=0,D=1;D<f;D++)Q[D+1]=Q[D]+P[D];for(E=0;E<w;E++)0!==c[m+E]&&(B[Q[c[m+E]]++]=E);if(a===e?(N=R=B,j=19):a===u?(N=n,O-=257,R=l,S-=257,j=256):(N=s,R=b,j=-1),M=0,E=0,D=F,g=v,I=H,J=0,q=-1,x=(L=1<<H)-1,a===u&&L>i||a===t&&L>o)return 1;for(;;){y=D-J,B[E]<j?(z=0,A=B[E]):B[E]>j?(z=R[S+B[E]],A=N[O+B[E]]):(z=96,A=0),k=1<<D-J,F=p=1<<I;do{d[g+(M>>J)+(p-=k)]=y<<24|z<<16|A|0}while(0!==p);for(k=1<<D-1;M&k;)k>>=1;if(0!==k?(M&=k-1,M+=k):M=0,E++,0==--P[D]){if(D===G)break;D=c[m+B[E]]}if(D>H&&(M&x)!==q){for(0===J&&(J=H),g+=F,K=1<<(I=D-J);I+J<G&&!((K-=P[I+J])<=0);)I++,K<<=1;if(L+=1<<I,a===u&&L>i||a===t&&L>o)return 1;d[q=M&x]=H<<24|I<<16|g-v|0}}return 0!==M&&(d[g+M]=D-J<<24|64<<16|0),h.bits=H,0};
},{"../utils/common":178}],187:[function(require,module,exports) {
"use strict";var e=require("../utils/common"),a=require("./adler32"),t=require("./crc32"),i=require("./inffast"),s=require("./inftrees"),n=0,r=1,o=2,d=4,l=5,f=6,c=0,h=1,k=2,b=-2,m=-3,w=-4,u=-5,g=8,v=1,x=2,p=3,_=4,y=5,z=6,B=7,S=8,q=9,C=10,I=11,R=12,j=13,A=14,D=15,E=16,G=17,H=18,K=19,N=20,F=21,J=22,L=23,M=24,O=25,P=26,Q=27,T=28,U=29,V=30,W=31,X=32,Y=852,Z=592,$=15,ee=$;function ae(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function te(){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 e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function ie(a){var t;return a&&a.state?(t=a.state,a.total_in=a.total_out=t.total=0,a.msg="",t.wrap&&(a.adler=1&t.wrap),t.mode=v,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new e.Buf32(Y),t.distcode=t.distdyn=new e.Buf32(Z),t.sane=1,t.back=-1,c):b}function se(e){var a;return e&&e.state?((a=e.state).wsize=0,a.whave=0,a.wnext=0,ie(e)):b}function ne(e,a){var t,i;return e&&e.state?(i=e.state,a<0?(t=0,a=-a):(t=1+(a>>4),a<48&&(a&=15)),a&&(a<8||a>15)?b:(null!==i.window&&i.wbits!==a&&(i.window=null),i.wrap=t,i.wbits=a,se(e))):b}function re(e,a){var t,i;return e?(i=new te,e.state=i,i.window=null,(t=ne(e,a))!==c&&(e.state=null),t):b}function oe(e){return re(e,ee)}var de,le,fe=!0;function ce(a){if(fe){var t;for(de=new e.Buf32(512),le=new e.Buf32(32),t=0;t<144;)a.lens[t++]=8;for(;t<256;)a.lens[t++]=9;for(;t<280;)a.lens[t++]=7;for(;t<288;)a.lens[t++]=8;for(s(r,a.lens,0,288,de,0,a.work,{bits:9}),t=0;t<32;)a.lens[t++]=5;s(o,a.lens,0,32,le,0,a.work,{bits:5}),fe=!1}a.lencode=de,a.lenbits=9,a.distcode=le,a.distbits=5}function he(a,t,i,s){var n,r=a.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new e.Buf8(r.wsize)),s>=r.wsize?(e.arraySet(r.window,t,i-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):((n=r.wsize-r.wnext)>s&&(n=s),e.arraySet(r.window,t,i-s,n,r.wnext),(s-=n)?(e.arraySet(r.window,t,i-s,s,0),r.wnext=s,r.whave=r.wsize):(r.wnext+=n,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=n))),0}function ke(Y,Z){var $,ee,te,ie,se,ne,re,oe,de,le,fe,ke,be,me,we,ue,ge,ve,xe,pe,_e,ye,ze,Be,Se=0,qe=new e.Buf8(4),Ce=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!Y||!Y.state||!Y.output||!Y.input&&0!==Y.avail_in)return b;($=Y.state).mode===R&&($.mode=j),se=Y.next_out,te=Y.output,re=Y.avail_out,ie=Y.next_in,ee=Y.input,ne=Y.avail_in,oe=$.hold,de=$.bits,le=ne,fe=re,ye=c;e:for(;;)switch($.mode){case v:if(0===$.wrap){$.mode=j;break}for(;de<16;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(2&$.wrap&&35615===oe){$.check=0,qe[0]=255&oe,qe[1]=oe>>>8&255,$.check=t($.check,qe,2,0),oe=0,de=0,$.mode=x;break}if($.flags=0,$.head&&($.head.done=!1),!(1&$.wrap)||(((255&oe)<<8)+(oe>>8))%31){Y.msg="incorrect header check",$.mode=V;break}if((15&oe)!==g){Y.msg="unknown compression method",$.mode=V;break}if(de-=4,_e=8+(15&(oe>>>=4)),0===$.wbits)$.wbits=_e;else if(_e>$.wbits){Y.msg="invalid window size",$.mode=V;break}$.dmax=1<<_e,Y.adler=$.check=1,$.mode=512&oe?C:R,oe=0,de=0;break;case x:for(;de<16;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if($.flags=oe,(255&$.flags)!==g){Y.msg="unknown compression method",$.mode=V;break}if(57344&$.flags){Y.msg="unknown header flags set",$.mode=V;break}$.head&&($.head.text=oe>>8&1),512&$.flags&&(qe[0]=255&oe,qe[1]=oe>>>8&255,$.check=t($.check,qe,2,0)),oe=0,de=0,$.mode=p;case p:for(;de<32;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}$.head&&($.head.time=oe),512&$.flags&&(qe[0]=255&oe,qe[1]=oe>>>8&255,qe[2]=oe>>>16&255,qe[3]=oe>>>24&255,$.check=t($.check,qe,4,0)),oe=0,de=0,$.mode=_;case _:for(;de<16;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}$.head&&($.head.xflags=255&oe,$.head.os=oe>>8),512&$.flags&&(qe[0]=255&oe,qe[1]=oe>>>8&255,$.check=t($.check,qe,2,0)),oe=0,de=0,$.mode=y;case y:if(1024&$.flags){for(;de<16;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}$.length=oe,$.head&&($.head.extra_len=oe),512&$.flags&&(qe[0]=255&oe,qe[1]=oe>>>8&255,$.check=t($.check,qe,2,0)),oe=0,de=0}else $.head&&($.head.extra=null);$.mode=z;case z:if(1024&$.flags&&((ke=$.length)>ne&&(ke=ne),ke&&($.head&&(_e=$.head.extra_len-$.length,$.head.extra||($.head.extra=new Array($.head.extra_len)),e.arraySet($.head.extra,ee,ie,ke,_e)),512&$.flags&&($.check=t($.check,ee,ke,ie)),ne-=ke,ie+=ke,$.length-=ke),$.length))break e;$.length=0,$.mode=B;case B:if(2048&$.flags){if(0===ne)break e;ke=0;do{_e=ee[ie+ke++],$.head&&_e&&$.length<65536&&($.head.name+=String.fromCharCode(_e))}while(_e&&ke<ne);if(512&$.flags&&($.check=t($.check,ee,ke,ie)),ne-=ke,ie+=ke,_e)break e}else $.head&&($.head.name=null);$.length=0,$.mode=S;case S:if(4096&$.flags){if(0===ne)break e;ke=0;do{_e=ee[ie+ke++],$.head&&_e&&$.length<65536&&($.head.comment+=String.fromCharCode(_e))}while(_e&&ke<ne);if(512&$.flags&&($.check=t($.check,ee,ke,ie)),ne-=ke,ie+=ke,_e)break e}else $.head&&($.head.comment=null);$.mode=q;case q:if(512&$.flags){for(;de<16;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(oe!==(65535&$.check)){Y.msg="header crc mismatch",$.mode=V;break}oe=0,de=0}$.head&&($.head.hcrc=$.flags>>9&1,$.head.done=!0),Y.adler=$.check=0,$.mode=R;break;case C:for(;de<32;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}Y.adler=$.check=ae(oe),oe=0,de=0,$.mode=I;case I:if(0===$.havedict)return Y.next_out=se,Y.avail_out=re,Y.next_in=ie,Y.avail_in=ne,$.hold=oe,$.bits=de,k;Y.adler=$.check=1,$.mode=R;case R:if(Z===l||Z===f)break e;case j:if($.last){oe>>>=7&de,de-=7&de,$.mode=Q;break}for(;de<3;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}switch($.last=1&oe,de-=1,3&(oe>>>=1)){case 0:$.mode=A;break;case 1:if(ce($),$.mode=N,Z===f){oe>>>=2,de-=2;break e}break;case 2:$.mode=G;break;case 3:Y.msg="invalid block type",$.mode=V}oe>>>=2,de-=2;break;case A:for(oe>>>=7&de,de-=7&de;de<32;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if((65535&oe)!=(oe>>>16^65535)){Y.msg="invalid stored block lengths",$.mode=V;break}if($.length=65535&oe,oe=0,de=0,$.mode=D,Z===f)break e;case D:$.mode=E;case E:if(ke=$.length){if(ke>ne&&(ke=ne),ke>re&&(ke=re),0===ke)break e;e.arraySet(te,ee,ie,ke,se),ne-=ke,ie+=ke,re-=ke,se+=ke,$.length-=ke;break}$.mode=R;break;case G:for(;de<14;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if($.nlen=257+(31&oe),oe>>>=5,de-=5,$.ndist=1+(31&oe),oe>>>=5,de-=5,$.ncode=4+(15&oe),oe>>>=4,de-=4,$.nlen>286||$.ndist>30){Y.msg="too many length or distance symbols",$.mode=V;break}$.have=0,$.mode=H;case H:for(;$.have<$.ncode;){for(;de<3;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}$.lens[Ce[$.have++]]=7&oe,oe>>>=3,de-=3}for(;$.have<19;)$.lens[Ce[$.have++]]=0;if($.lencode=$.lendyn,$.lenbits=7,ze={bits:$.lenbits},ye=s(n,$.lens,0,19,$.lencode,0,$.work,ze),$.lenbits=ze.bits,ye){Y.msg="invalid code lengths set",$.mode=V;break}$.have=0,$.mode=K;case K:for(;$.have<$.nlen+$.ndist;){for(;ue=(Se=$.lencode[oe&(1<<$.lenbits)-1])>>>16&255,ge=65535&Se,!((we=Se>>>24)<=de);){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(ge<16)oe>>>=we,de-=we,$.lens[$.have++]=ge;else{if(16===ge){for(Be=we+2;de<Be;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(oe>>>=we,de-=we,0===$.have){Y.msg="invalid bit length repeat",$.mode=V;break}_e=$.lens[$.have-1],ke=3+(3&oe),oe>>>=2,de-=2}else if(17===ge){for(Be=we+3;de<Be;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}de-=we,_e=0,ke=3+(7&(oe>>>=we)),oe>>>=3,de-=3}else{for(Be=we+7;de<Be;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}de-=we,_e=0,ke=11+(127&(oe>>>=we)),oe>>>=7,de-=7}if($.have+ke>$.nlen+$.ndist){Y.msg="invalid bit length repeat",$.mode=V;break}for(;ke--;)$.lens[$.have++]=_e}}if($.mode===V)break;if(0===$.lens[256]){Y.msg="invalid code -- missing end-of-block",$.mode=V;break}if($.lenbits=9,ze={bits:$.lenbits},ye=s(r,$.lens,0,$.nlen,$.lencode,0,$.work,ze),$.lenbits=ze.bits,ye){Y.msg="invalid literal/lengths set",$.mode=V;break}if($.distbits=6,$.distcode=$.distdyn,ze={bits:$.distbits},ye=s(o,$.lens,$.nlen,$.ndist,$.distcode,0,$.work,ze),$.distbits=ze.bits,ye){Y.msg="invalid distances set",$.mode=V;break}if($.mode=N,Z===f)break e;case N:$.mode=F;case F:if(ne>=6&&re>=258){Y.next_out=se,Y.avail_out=re,Y.next_in=ie,Y.avail_in=ne,$.hold=oe,$.bits=de,i(Y,fe),se=Y.next_out,te=Y.output,re=Y.avail_out,ie=Y.next_in,ee=Y.input,ne=Y.avail_in,oe=$.hold,de=$.bits,$.mode===R&&($.back=-1);break}for($.back=0;ue=(Se=$.lencode[oe&(1<<$.lenbits)-1])>>>16&255,ge=65535&Se,!((we=Se>>>24)<=de);){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(ue&&0==(240&ue)){for(ve=we,xe=ue,pe=ge;ue=(Se=$.lencode[pe+((oe&(1<<ve+xe)-1)>>ve)])>>>16&255,ge=65535&Se,!(ve+(we=Se>>>24)<=de);){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}oe>>>=ve,de-=ve,$.back+=ve}if(oe>>>=we,de-=we,$.back+=we,$.length=ge,0===ue){$.mode=P;break}if(32&ue){$.back=-1,$.mode=R;break}if(64&ue){Y.msg="invalid literal/length code",$.mode=V;break}$.extra=15&ue,$.mode=J;case J:if($.extra){for(Be=$.extra;de<Be;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}$.length+=oe&(1<<$.extra)-1,oe>>>=$.extra,de-=$.extra,$.back+=$.extra}$.was=$.length,$.mode=L;case L:for(;ue=(Se=$.distcode[oe&(1<<$.distbits)-1])>>>16&255,ge=65535&Se,!((we=Se>>>24)<=de);){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(0==(240&ue)){for(ve=we,xe=ue,pe=ge;ue=(Se=$.distcode[pe+((oe&(1<<ve+xe)-1)>>ve)])>>>16&255,ge=65535&Se,!(ve+(we=Se>>>24)<=de);){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}oe>>>=ve,de-=ve,$.back+=ve}if(oe>>>=we,de-=we,$.back+=we,64&ue){Y.msg="invalid distance code",$.mode=V;break}$.offset=ge,$.extra=15&ue,$.mode=M;case M:if($.extra){for(Be=$.extra;de<Be;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}$.offset+=oe&(1<<$.extra)-1,oe>>>=$.extra,de-=$.extra,$.back+=$.extra}if($.offset>$.dmax){Y.msg="invalid distance too far back",$.mode=V;break}$.mode=O;case O:if(0===re)break e;if(ke=fe-re,$.offset>ke){if((ke=$.offset-ke)>$.whave&&$.sane){Y.msg="invalid distance too far back",$.mode=V;break}ke>$.wnext?(ke-=$.wnext,be=$.wsize-ke):be=$.wnext-ke,ke>$.length&&(ke=$.length),me=$.window}else me=te,be=se-$.offset,ke=$.length;ke>re&&(ke=re),re-=ke,$.length-=ke;do{te[se++]=me[be++]}while(--ke);0===$.length&&($.mode=F);break;case P:if(0===re)break e;te[se++]=$.length,re--,$.mode=F;break;case Q:if($.wrap){for(;de<32;){if(0===ne)break e;ne--,oe|=ee[ie++]<<de,de+=8}if(fe-=re,Y.total_out+=fe,$.total+=fe,fe&&(Y.adler=$.check=$.flags?t($.check,te,fe,se-fe):a($.check,te,fe,se-fe)),fe=re,($.flags?oe:ae(oe))!==$.check){Y.msg="incorrect data check",$.mode=V;break}oe=0,de=0}$.mode=T;case T:if($.wrap&&$.flags){for(;de<32;){if(0===ne)break e;ne--,oe+=ee[ie++]<<de,de+=8}if(oe!==(4294967295&$.total)){Y.msg="incorrect length check",$.mode=V;break}oe=0,de=0}$.mode=U;case U:ye=h;break e;case V:ye=m;break e;case W:return w;case X:default:return b}return Y.next_out=se,Y.avail_out=re,Y.next_in=ie,Y.avail_in=ne,$.hold=oe,$.bits=de,($.wsize||fe!==Y.avail_out&&$.mode<V&&($.mode<Q||Z!==d))&&he(Y,Y.output,Y.next_out,fe-Y.avail_out)?($.mode=W,w):(le-=Y.avail_in,fe-=Y.avail_out,Y.total_in+=le,Y.total_out+=fe,$.total+=fe,$.wrap&&fe&&(Y.adler=$.check=$.flags?t($.check,te,fe,Y.next_out-fe):a($.check,te,fe,Y.next_out-fe)),Y.data_type=$.bits+($.last?64:0)+($.mode===R?128:0)+($.mode===N||$.mode===D?256:0),(0===le&&0===fe||Z===d)&&ye===c&&(ye=u),ye)}function be(e){if(!e||!e.state)return b;var a=e.state;return a.window&&(a.window=null),e.state=null,c}function me(e,a){var t;return e&&e.state?0==(2&(t=e.state).wrap)?b:(t.head=a,a.done=!1,c):b}function we(e,t){var i,s=t.length;return e&&e.state?0!==(i=e.state).wrap&&i.mode!==I?b:i.mode===I&&a(1,t,s,0)!==i.check?m:he(e,t,s,s)?(i.mode=W,w):(i.havedict=1,c):b}exports.inflateReset=se,exports.inflateReset2=ne,exports.inflateResetKeep=ie,exports.inflateInit=oe,exports.inflateInit2=re,exports.inflate=ke,exports.inflateEnd=be,exports.inflateGetHeader=me,exports.inflateSetDictionary=we,exports.inflateInfo="pako inflate (from Nodeca project)";
},{"../utils/common":178,"./adler32":191,"./crc32":192,"./inffast":199,"./inftrees":200}],179:[function(require,module,exports) {
"use strict";module.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};
},{}],188:[function(require,module,exports) {
"use strict";function t(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}module.exports=t;
},{}],177:[function(require,module,exports) {
"use strict";var t=require("./zlib/inflate"),i=require("./utils/common"),n=require("./utils/strings"),s=require("./zlib/constants"),r=require("./zlib/messages"),e=require("./zlib/zstream"),o=require("./zlib/gzheader"),u=Object.prototype.toString;function a(n){if(!(this instanceof a))return new a(n);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},n||{});var u=this.options;u.raw&&u.windowBits>=0&&u.windowBits<16&&(u.windowBits=-u.windowBits,0===u.windowBits&&(u.windowBits=-15)),!(u.windowBits>=0&&u.windowBits<16)||n&&n.windowBits||(u.windowBits+=32),u.windowBits>15&&u.windowBits<48&&0==(15&u.windowBits)&&(u.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new e,this.strm.avail_out=0;var h=t.inflateInit2(this.strm,u.windowBits);if(h!==s.Z_OK)throw new Error(r[h]);this.header=new o,t.inflateGetHeader(this.strm,this.header)}function h(t,i){var n=new a(i);if(n.push(t,!0),n.err)throw n.msg||r[n.err];return n.result}function _(t,i){return(i=i||{}).raw=!0,h(t,i)}a.prototype.push=function(r,e){var o,a,h,_,w,l,d=this.strm,f=this.options.chunkSize,p=this.options.dictionary,c=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?s.Z_FINISH:s.Z_NO_FLUSH,"string"==typeof r?d.input=n.binstring2buf(r):"[object ArrayBuffer]"===u.call(r)?d.input=new Uint8Array(r):d.input=r,d.next_in=0,d.avail_in=d.input.length;do{if(0===d.avail_out&&(d.output=new i.Buf8(f),d.next_out=0,d.avail_out=f),(o=t.inflate(d,s.Z_NO_FLUSH))===s.Z_NEED_DICT&&p&&(l="string"==typeof p?n.string2buf(p):"[object ArrayBuffer]"===u.call(p)?new Uint8Array(p):p,o=t.inflateSetDictionary(this.strm,l)),o===s.Z_BUF_ERROR&&!0===c&&(o=s.Z_OK,c=!1),o!==s.Z_STREAM_END&&o!==s.Z_OK)return this.onEnd(o),this.ended=!0,!1;d.next_out&&(0!==d.avail_out&&o!==s.Z_STREAM_END&&(0!==d.avail_in||a!==s.Z_FINISH&&a!==s.Z_SYNC_FLUSH)||("string"===this.options.to?(h=n.utf8border(d.output,d.next_out),_=d.next_out-h,w=n.buf2string(d.output,h),d.next_out=_,d.avail_out=f-_,_&&i.arraySet(d.output,d.output,h,_,0),this.onData(w)):this.onData(i.shrinkBuf(d.output,d.next_out)))),0===d.avail_in&&0===d.avail_out&&(c=!0)}while((d.avail_in>0||0===d.avail_out)&&o!==s.Z_STREAM_END);return o===s.Z_STREAM_END&&(a=s.Z_FINISH),a===s.Z_FINISH?(o=t.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===s.Z_OK):a!==s.Z_SYNC_FLUSH||(this.onEnd(s.Z_OK),d.avail_out=0,!0)},a.prototype.onData=function(t){this.chunks.push(t)},a.prototype.onEnd=function(t){t===s.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},exports.Inflate=a,exports.inflate=h,exports.inflateRaw=_,exports.ungzip=h;
},{"./zlib/inflate":187,"./utils/common":178,"./utils/strings":183,"./zlib/constants":179,"./zlib/messages":185,"./zlib/zstream":184,"./zlib/gzheader":188}],175:[function(require,module,exports) {
"use strict";var e=require("./lib/utils/common").assign,i=require("./lib/deflate"),r=require("./lib/inflate"),l=require("./lib/zlib/constants"),s={};e(s,i,r,l),module.exports=s;
},{"./lib/utils/common":178,"./lib/deflate":176,"./lib/inflate":177,"./lib/zlib/constants":179}],154:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MaybeCompressedDataReader=exports.TextProfileDataSource=void 0;var e=require("pako"),r=t(e);function t(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]=e[t]);return r.default=e,r}var n=function(e,r,t,n){return new(t||(t=Promise))(function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){e.done?o(e.value):new t(function(r){r(e.value)}).then(s,a)}u((n=n.apply(e,r||[])).next())})};class o{constructor(e,r){this.fileName=e,this.contents=r}name(){return n(this,void 0,void 0,function*(){return this.fileName})}readAsArrayBuffer(){return n(this,void 0,void 0,function*(){return new ArrayBuffer(0)})}readAsText(){return n(this,void 0,void 0,function*(){return this.contents})}}exports.TextProfileDataSource=o;class i{constructor(e,t){this.namePromise=e,this.uncompressedData=t.then(e=>n(this,void 0,void 0,function*(){try{return r.inflate(new Uint8Array(e)).buffer}catch(r){return e}}))}name(){return n(this,void 0,void 0,function*(){return yield this.namePromise})}readAsArrayBuffer(){return n(this,void 0,void 0,function*(){return yield this.uncompressedData})}readAsText(){return n(this,void 0,void 0,function*(){const e=yield this.readAsArrayBuffer();let r="";if("undefined"!=typeof TextDecoder){return(new TextDecoder).decode(e)}{const t=new Uint8Array(e);for(let e=0;e<t.length;e++)r+=String.fromCharCode(t[e]);return r}})}static fromFile(e){const r=new Promise(r=>{const t=new FileReader;t.addEventListener("loadend",()=>{if(!(t.result instanceof ArrayBuffer))throw new Error("Expected reader.result to be an instance of ArrayBuffer");r(t.result)}),t.readAsArrayBuffer(e)});return new i(Promise.resolve(e.name),r)}static fromArrayBuffer(e,r){return new i(Promise.resolve(e),Promise.resolve(r))}}exports.MaybeCompressedDataReader=i;
},{"pako":175}],148:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UID=void 0,exports.importFromInstrumentsDeepCopy=a,exports.importFromInstrumentsTrace=w,exports.importRunFromInstrumentsTrace=g,exports.importThreadFromInstrumentsTrace=b,exports.readInstrumentsKeyedArchive=y,exports.decodeUTF8=v;var e=require("../lib/profile"),t=require("../lib/utils"),r=require("../lib/value-formatters"),n=require("./utils"),s=function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{l(n.next(e))}catch(e){i(e)}}function a(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){e.done?s(e.value):new r(function(t){t(e.value)}).then(o,a)}l((n=n.apply(e,t||[])).next())})};function i(e){const t=e.split("\n").map(e=>e.split("\t")),r=t.shift();if(!r)return[];const n=new Map;for(let e=0;e<r.length;e++)n.set(e,r[e]);const s=[];for(let e of t){const t={};for(let r=0;r<e.length;r++)t[n.get(r)]=e[r];s.push(t)}return s}function o(e){if("Bytes Used"in e){const t=e["Bytes Used"],r=/\s*(\d+(?:[.]\d+)?) (\w+)\s+(?:\d+(?:[.]\d+))%/.exec(t);if(!r)return 0;const n=parseInt(r[1],10),s=r[2];switch(s){case"Bytes":return n;case"KB":return 1024*n;case"MB":return 1048576*n;case"GB":return 1073741824*n}throw new Error(`Unrecognized units ${s}`)}if("Weight"in e||"Running Time"in e){const t=e.Weight||e["Running Time"],r=/\s*(\d+(?:[.]\d+)?) ?(\w+)\s+(?:\d+(?:[.]\d+))%/.exec(t);if(!r)return 0;const n=parseInt(r[1],10),s=r[2];switch(s){case"ms":return n;case"s":case"min":return 1e3*n}throw new Error(`Unrecognized units ${s}`)}return-1}function a(t){const n=new e.CallTreeProfileBuilder,s=i(t),a=[];let l=0;for(let e of s){const t=e["Symbol Name"];if(!t)continue;const r=t.trim();let s=t.length-r.length;if(a.length-s<0)throw new Error("Invalid format");let i=[];for(;s<a.length;){const e=a.pop();i.push(e)}for(let e of i)l=Math.max(l,e.endValue),n.leaveFrame(e,l);const c={key:`${e["Source Path"]||""}:${r}`,name:r,file:e["Source Path"],endValue:l+o(e)};n.enterFrame(c,l),a.push(c)}for(;a.length>0;){const e=a.pop();l=Math.max(l,e.endValue),n.leaveFrame(e,l)}return"Bytes Used"in s[0]?n.setValueFormatter(new r.ByteFormatter):("Weight"in s[0]||"Running Time"in s[0])&&n.setValueFormatter(new r.TimeFormatter("milliseconds")),n.build()}function l(e){return s(this,void 0,void 0,function*(){const t={name:e.name,files:new Map,subdirectories:new Map},r=yield new Promise((t,r)=>{e.createReader().readEntries(e=>{t(e)},r)});for(let e of r)if(e.isDirectory){const r=yield l(e);t.subdirectories.set(r.name,r)}else{const r=yield new Promise((t,r)=>{e.file(t,r)});t.files.set(r.name,r)}return t})}function c(e){return n.MaybeCompressedDataReader.fromFile(e).readAsArrayBuffer()}function u(e){return n.MaybeCompressedDataReader.fromFile(e).readAsText()}function f(e,r){const n=(0,t.getOrThrow)(e.subdirectories,"corespace"),s=(0,t.getOrThrow)(n.subdirectories,`run${r}`);return(0,t.getOrThrow)(s.subdirectories,"core")}class h{constructor(e){this.bytePos=0,this.view=new DataView(e)}seek(e){this.bytePos=e}skip(e){this.bytePos+=e}hasMore(){return this.bytePos<this.view.byteLength}bytesLeft(){return this.view.byteLength-this.bytePos}readUint8(){return this.bytePos++,this.bytePos>this.view.byteLength?0:this.view.getUint8(this.bytePos-1)}readUint32(){return this.bytePos+=4,this.bytePos>this.view.byteLength?0:this.view.getUint32(this.bytePos-4,!0)}readUint48(){return this.bytePos+=6,this.bytePos>this.view.byteLength?0:this.view.getUint32(this.bytePos-6,!0)+this.view.getUint16(this.bytePos-2,!0)*Math.pow(2,32)}readUint64(){return this.bytePos+=8,this.bytePos>this.view.byteLength?0:this.view.getUint32(this.bytePos-8,!0)+this.view.getUint32(this.bytePos-4,!0)*Math.pow(2,32)}}function p(e){return s(this,void 0,void 0,function*(){const r=(0,t.getOrThrow)(e.subdirectories,"stores");for(let e of r.subdirectories.values()){const r=e.files.get("schema.xml");if(!r)continue;const n=yield u(r);if(!/name="time-profile"/.exec(n))continue;const s=new h(yield c((0,t.getOrThrow)(e.files,"bulkstore")));s.readUint32(),s.readUint32(),s.readUint32();const i=s.readUint32(),o=s.readUint32();s.seek(i);const a=[];for(;;){const e=s.readUint48();if(0===e)break;const t=s.readUint32();s.skip(o-6-4-4);const r=s.readUint32();a.push({timestamp:e,threadID:t,backtraceID:r})}return a}throw new Error("Could not find sample list")})}function d(e,r){return s(this,void 0,void 0,function*(){const e=(0,t.getOrThrow)(r.subdirectories,"uniquing"),n=(0,t.getOrThrow)(e.subdirectories,"arrayUniquer"),s=(0,t.getOrThrow)(n.files,"integeruniquer.index"),i=(0,t.getOrThrow)(n.files,"integeruniquer.data"),o=new h(yield c(s)),a=new h(yield c(i));o.seek(32);let l=[];for(;o.hasMore();){const e=o.readUint32()+1048576*o.readUint32();if(0===e)continue;a.seek(e);let t=a.readUint32(),r=[];for(;t--;)r.push(a.readUint64());l.push(r)}return l})}function m(e){return s(this,void 0,void 0,function*(){const r=y(yield c((0,t.getOrThrow)(e.files,"form.template"))),n=r["com.apple.xray.owner.template.version"];let s=1;"com.apple.xray.owner.template"in r&&(s=r["com.apple.xray.owner.template"].get("_selectedRunNumber"));let i=r.$1;"stubInfoByUUID"in r&&(i=Array.from(r.stubInfoByUUID.keys())[0]);const o=r["com.apple.xray.run.data"],a=[];for(let e of o.runNumbers){const r=(0,t.getOrThrow)(o.runData,e),n=(0,t.getOrThrow)(r,"symbolsByPid"),s=new Map;for(let r of n.values()){for(let e of r.symbols){if(!e)continue;const{sourcePath:r,symbolName:n,addressToLine:i}=e;for(let e of i.keys())(0,t.getOrInsert)(s,e,()=>{const s=n||`0x${(0,t.zeroPad)(e.toString(16),16)}`,i={key:`${r}:${s}`,name:s};return r&&(i.file=r),i})}a.push({number:e,addressToFrameMap:s})}}return{version:n,instrument:i,selectedRunNumber:s,runs:a}})}function w(e){return s(this,void 0,void 0,function*(){const t=yield l(e),{version:r,runs:n,instrument:s,selectedRunNumber:i}=yield m(t);if("com.apple.xray.instrument-type.coresampler2"!==s)throw new Error(`The only supported instrument from .trace import is "com.apple.xray.instrument-type.coresampler2". Got ${s}`);console.log("version: ",r),console.log("Importing time profile");const o=[];let a=0;for(let r of n){const{addressToFrameMap:n,number:s}=r,l=yield g({fileName:e.name,tree:t,addressToFrameMap:n,runNumber:s});r.number===i&&(a=o.length+l.indexToView),o.push(...l.profiles)}return{name:e.name,indexToView:a,profiles:o}})}function g(e){return s(this,void 0,void 0,function*(){const{fileName:r,tree:n,addressToFrameMap:s,runNumber:i}=e,o=f(n,i);let a=yield p(o);const l=yield d(a,o),c=new Map;for(let e of a)c.set(e.threadID,(0,t.getOrElse)(c,e.threadID,()=>0)+1);const u=Array.from(c.entries());(0,t.sortBy)(u,e=>-e[1]);const h=u.map(e=>e[0]);return{name:r,indexToView:0,profiles:h.map(e=>b({threadID:e,fileName:r,arrays:l,addressToFrameMap:s,samples:a}))}})}function b(n){let{fileName:s,addressToFrameMap:i,arrays:o,threadID:a,samples:l}=n;const c=new Map;l=l.filter(e=>e.threadID===a);const u=new e.StackListProfileBuilder((0,t.lastOf)(l).timestamp);function f(e,r){const n=i.get(e);if(n)r.push(n);else if(e in o)for(let t of o[e])f(t,r);else{const n={key:e,name:`0x${(0,t.zeroPad)(e.toString(16),16)}`};i.set(e,n),r.push(n)}}u.setName(`${s} - thread ${a}`);let h=null;for(let e of l){const r=(0,t.getOrInsert)(c,e.backtraceID,e=>{const t=[];return f(e,t),t.reverse(),t});if(null===h&&(u.appendSampleWithWeight([],e.timestamp),h=e.timestamp),e.timestamp<h)throw new Error("Timestamps out of order!");u.appendSampleWithWeight(r,e.timestamp-h),h=e.timestamp}return u.setValueFormatter(new r.TimeFormatter("nanoseconds")),u.build()}function y(e){return T(I(new Uint8Array(e)),(e,t)=>{switch(e){case"NSTextStorage":case"NSParagraphStyle":case"NSFont":return null;case"PFTSymbolData":{const e=Object.create(null);e.symbolName=t.$0,e.sourcePath=t.$1,e.addressToLine=new Map;for(let r=3;;r+=2){const n=t["$"+r],s=t["$"+(r+1)];if(null==n||null==s)break;e.addressToLine.set(n,s)}return e}case"PFTOwnerData":{const e=Object.create(null);return e.ownerName=t.$0,e.ownerPath=t.$1,e}case"PFTPersistentSymbols":{const e=Object.create(null),r=t.$4;e.threadNames=t.$3,e.symbols=[];for(let n=1;n<r;n++)e.symbols.push(t["$"+(4+n)]);return e}case"XRRunListData":{const e=Object.create(null);return e.runNumbers=t.$0,e.runData=t.$1,e}case"XRIntKeyedDictionary":{const e=new Map,r=t.$0;for(let n=0;n<r;n++){const r=t["$"+(1+2*n)],s=t["$"+(2*n+1+1)];e.set(r,s)}return e}case"XRCore":{const e=Object.create(null);return e.number=t.$0,e.name=t.$1,e}}return t})}function v(e){let t=String.fromCharCode.apply(String,Array.from(e));return"\0"===t.slice(-1)&&(t=t.slice(0,-1)),decodeURIComponent(escape(t))}function U(e){return e instanceof Array}function S(e){return null!==e&&"object"==typeof e&&null===Object.getPrototypeOf(e)}function N(e,t){return t instanceof x?e[t.index]:t}function T(e,t=(e=>e)){if(1e5!==e.$version||"NSKeyedArchiver"!==e.$archiver||!S(e.$top)||!U(e.$objects))throw new Error("Invalid keyed archive");"$null"===e.$objects[0]&&(e.$objects[0]=null);for(let r=0;r<e.$objects.length;r++)e.$objects[r]=$(e.$objects,e.$objects[r],t);let r=t=>{if(t instanceof x)return e.$objects[t.index];if(U(t))for(let e=0;e<t.length;e++)t[e]=r(t[e]);else if(S(t))for(let e in t)t[e]=r(t[e]);else if(t instanceof Map){const e=new Map(t);t.clear();for(let[n,s]of e.entries())t.set(r(n),r(s))}return t};for(let t=0;t<e.$objects.length;t++)r(e.$objects[t]);return r(e.$top)}function $(e,t,r=(e=>e)){if(S(t)&&t.$class){let n=N(e,t.$class).$classname;switch(n){case"NSDecimalNumberPlaceholder":{let e=t["NS.length"],r=t["NS.exponent"],n=t["NS.mantissa.bo"],s=t["NS.negative"],i=new Uint16Array(new Uint8Array(t["NS.mantissa"]).buffer),o=0;for(let t=0;t<e;t++){let e=i[t];1!==n&&(e=(65280&e)>>8|(255&e)<<8),o+=e*Math.pow(65536,t)}return o*=Math.pow(10,r),s?-o:o}case"NSData":case"NSMutableData":return t["NS.bytes"]||t["NS.data"];case"NSString":case"NSMutableString":return t["NS.string"]?t["NS.string"]:t["NS.bytes"]?v(t["NS.bytes"]):(console.warn(`Unexpected ${n} format: `,t),null);case"NSArray":case"NSMutableArray":if("NS.objects"in t)return t["NS.objects"];let e=[];for(;;){let r="NS.object."+e.length;if(!(r in t))break;e.push(t[r])}return e;case"_NSKeyedCoderOldStyleArray":{const e=t["NS.count"];let r=[];for(let n=0;n<e;n++){const e=t["$"+n];r.push(e)}return r}case"NSDictionary":case"NSMutableDictionary":let s=new Map;if("NS.keys"in t&&"NS.objects"in t)for(let e=0;e<t["NS.keys"].length;e++)s.set(t["NS.keys"][e],t["NS.objects"][e]);else for(;;){let e="NS.key."+s.size,r="NS.object."+s.size;if(!(e in t&&r in t))break;s.set(t[e],t[r])}return s;default:const i=r(n,t);if(i!==t)return i}}return t}class x{constructor(e){this.index=e}}function I(e){for(let t=0;t<8;t++)if(e[t]!=="bplist00".charCodeAt(t))throw new Error("File is not a binary plist");return new P(new DataView(e.buffer,e.byteOffset,e.byteLength)).parseRoot()}exports.UID=x;class P{constructor(e){this.view=e,this.referenceSize=0,this.objects=[],this.offsetTable=[]}parseRoot(){let e=this.view.byteLength-32,t=this.view.getUint8(e+6);this.referenceSize=this.view.getUint8(e+7);let r=this.view.getUint32(e+12,!1),n=this.view.getUint32(e+20,!1),s=this.view.getUint32(e+28,!1);for(let e=0;e<r;e++)this.offsetTable.push(this.parseInteger(s,t)),s+=t;return this.parseObject(this.offsetTable[n])}parseLengthAndOffset(e,t){if(15!==t)return{length:t,offset:0};let r=this.view.getUint8(e++);if(16!=(240&r))throw new Error("Unexpected non-integer length at offset "+e);let n=1<<(15&r);return{length:this.parseInteger(e,n),offset:n+1}}parseSingleton(e,t){if(0===t)return null;if(8===t)return!1;if(9===t)return!0;throw new Error("Unexpected extra value "+t+" at offset "+e)}parseInteger(e,t){if(1===t)return this.view.getUint8(e);if(2===t)return this.view.getUint16(e,!1);if(4===t)return this.view.getUint32(e,!1);if(8===t)return Math.pow(2,32)*this.view.getUint32(e+0,!1)+Math.pow(2,0)*this.view.getUint32(e+4,!1);if(16===t)return Math.pow(2,96)*this.view.getUint32(e+0,!1)+Math.pow(2,64)*this.view.getUint32(e+4,!1)+Math.pow(2,32)*this.view.getUint32(e+8,!1)+Math.pow(2,0)*this.view.getUint32(e+12,!1);throw new Error("Unexpected integer of size "+t+" at offset "+e)}parseFloat(e,t){if(4===t)return this.view.getFloat32(e,!1);if(8===t)return this.view.getFloat64(e,!1);throw new Error("Unexpected float of size "+t+" at offset "+e)}parseDate(e,t){if(8!==t)throw new Error("Unexpected date of size "+t+" at offset "+e);let r=this.view.getFloat64(e,!1);return new Date(9783072e5+1e3*r)}parseData(e,t){let r=this.parseLengthAndOffset(e,t);return new Uint8Array(this.view.buffer,e+r.offset,r.length)}parseStringASCII(e,t){let r=this.parseLengthAndOffset(e,t),n="";e+=r.offset;for(let t=0;t<r.length;t++)n+=String.fromCharCode(this.view.getUint8(e++));return n}parseStringUTF16(e,t){let r=this.parseLengthAndOffset(e,t),n="";e+=r.offset;for(let t=0;t<r.length;t++)n+=String.fromCharCode(this.view.getUint16(e,!1)),e+=2;return n}parseUID(e,t){return new x(this.parseInteger(e,t))}parseArray(e,t){let r=this.parseLengthAndOffset(e,t),n=[],s=this.referenceSize;e+=r.offset;for(let t=0;t<r.length;t++)n.push(this.parseObject(this.offsetTable[this.parseInteger(e,s)])),e+=s;return n}parseDictionary(e,t){let r=this.parseLengthAndOffset(e,t),n=Object.create(null),s=this.referenceSize,i=e+r.offset,o=i+r.length*s;for(let e=0;e<r.length;e++){let e=this.parseObject(this.offsetTable[this.parseInteger(i,s)]),t=this.parseObject(this.offsetTable[this.parseInteger(o,s)]);if("string"!=typeof e)throw new Error("Unexpected non-string key at offset "+i);n[e]=t,i+=s,o+=s}return n}parseObject(e){let t=this.view.getUint8(e++),r=15&t;switch(t>>4){case 0:return this.parseSingleton(e,r);case 1:return this.parseInteger(e,1<<r);case 2:return this.parseFloat(e,1<<r);case 3:return this.parseDate(e,1<<r);case 4:return this.parseData(e,r);case 5:return this.parseStringASCII(e,r);case 6:return this.parseStringUTF16(e,r);case 8:return this.parseUID(e,r+1);case 10:return this.parseArray(e,r);case 13:return this.parseDictionary(e,r)}throw new Error("Unexpected marker "+t+" at offset "+--e)}}
},{"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140,"./utils":154}],149:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromBGFlameGraph=t;var e=require("../lib/profile");function r(e){const r=[];return e.replace(/^(.*) (\d+)$/gm,(e,t,i)=>(r.push({stack:t.split(";").map(e=>({key:e,name:e})),duration:parseInt(i,10)}),e)),r}function t(t){const i=r(t),n=i.reduce((e,r)=>e+r.duration,0),o=new e.StackListProfileBuilder(n);if(0===i.length)return null;for(let e of i)o.appendSampleWithWeight(e.stack,e.duration);return o.build()}
},{"../lib/profile":139}],150:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromFirefox=l;var e=require("../lib/profile"),t=require("../lib/utils"),r=require("../lib/value-formatters");function l(l){const n=l.profile,s=1===n.threads.length?n.threads[0]:n.threads.filter(e=>"GeckoMain"===e.name)[0],a=new Map;function o(e){let r=e[0];const l=[];for(;null!=r;){const e=s.stackTable.data[r],[t,n]=e;l.push(n),r=t}return l.reverse(),l.map(e=>{const r=s.frameTable.data[e],l=s.stringTable[r[0]],n=/(.*)\s+\((.*?):?(\d+)?\)$/.exec(l);return n?n[2].startsWith("resource:")||"self-hosted"===n[2]||n[2].startsWith("self-hosted:")?null:(0,t.getOrInsert)(a,l,()=>({key:l,name:n[1],file:n[2],line:n[3]?parseInt(n[3]):void 0})):null}).filter(e=>null!=e)}const i=new e.CallTreeProfileBuilder(l.duration);let u=[];for(let e of s.samples.data){const t=o(e),r=e[1];let l=-1;for(let e=0;e<Math.min(t.length,u.length)&&u[e]===t[e];e++)l=e;for(let e=u.length-1;e>l;e--)i.leaveFrame(u[e],r);for(let e=l+1;e<t.length;e++)i.enterFrame(t[e],r);u=t}return i.setValueFormatter(new r.TimeFormatter("milliseconds")),i.build()}
},{"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140}],151:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromV8ProfLog=n;var e=require("../lib/profile"),t=require("../lib/utils"),r=require("../lib/value-formatters");function a(e,t){if(!e||!e.type)return{key:"(unknown type)",name:"(unknown type)"};let r=e.name;switch(e.type){case"CPP":{const e=r.match(/[tT] ([^(<]*)/);e&&(r=`(c++) ${e[1]}`);break}case"SHARED_LIB":r="(LIB) "+r;break;case"JS":{const e=r.match(/([a-zA-Z0-9\._\-$]*) ([a-zA-Z0-9\.\-_\/$]*):(\d+):(\d+)/);if(e)return{key:r,name:e[1].length>0?e[1]:"(anonymous)",file:e[2].length>0?e[2]:"(unknown file)",line:parseInt(e[3],10),col:parseInt(e[4],10)};break}case"CODE":switch(e.kind){case"LoadIC":case"StoreIC":case"KeyedStoreIC":case"KeyedLoadIC":case"LoadGlobalIC":case"Handler":r="(IC) "+r;break;case"BytecodeHandler":r="(bytecode) ~"+r;break;case"Stub":r="(stub) "+r;break;case"Builtin":r="(builtin) "+r;break;case"RegExp":r="(regexp) "+r}break;default:r=`(${e.type}) ${r}`}return{key:r,name:r}}function n(n){const s=new e.StackListProfileBuilder,o=new Map;let c=0;(0,t.sortBy)(n.ticks,e=>e.tm);for(let e of n.ticks){const r=[];for(let s=e.s.length-2;s>=0;s-=2){const c=e.s[s];-1!==c&&(c>n.code.length?r.push({key:c,name:`0x${c.toString(16)}`}):r.push((i=c,(0,t.getOrInsert)(o,i,e=>a(n.code[e],n)))))}s.appendSampleWithWeight(r,e.tm-c),c=e.tm}var i;return s.setValueFormatter(new r.TimeFormatter("microseconds")),s.build()}
},{"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140}],152:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromLinuxPerf=r;var e=require("../lib/profile"),t=require("../lib/utils"),n=require("../lib/value-formatters");function s(e){const t=e.split("\n").filter(e=>!/^\s*#/.exec(e)),n={command:null,processID:null,threadID:null,time:null,eventType:"",stack:[]},s=t.shift();if(!s)return null;const r=/^(\S.+?)\s+(\d+)(?:\/?(\d+))?\s+/.exec(s);if(!r)return null;n.command=r[1],r[3]?(n.processID=parseInt(r[2],10),n.threadID=parseInt(r[3],10)):n.threadID=parseInt(r[2],10);const l=/\s+(\d+\.\d+):\s+/.exec(s);l&&(n.time=parseFloat(l[1]));const i=/(\S+):\s*$/.exec(s);i&&(n.eventType=i[1]);for(let e of t){const t=/^\s*(\w+)\s*(.+) \((\S*)\)/.exec(e);if(!t)continue;let[,s,r,l]=t;r=r.replace(/\+0x[\da-f]+$/,""),n.stack.push({address:`0x${s}`,symbolName:r,file:l})}return n.stack.reverse(),n}function r(r){const l=new Map;let i=null;const o=r.split("\n\n").map(s);for(let s of o){if(null==s)continue;if(null!=i&&i!=s.eventType)continue;if(null==s.time)continue;i=s.eventType;let r=[];s.command&&r.push(s.command),s.processID&&r.push(`pid: ${s.processID}`),s.threadID&&r.push(`tid: ${s.threadID}`);const o=r.join(" ");(0,t.getOrInsert)(l,o,()=>{const t=new e.StackListProfileBuilder;return t.setName(o),t.setValueFormatter(new n.TimeFormatter("seconds")),t}).appendSampleWithTimestamp(s.stack.map(({symbolName:e,file:t})=>({key:`${e} (${t})`,name:"[unknown]"===e?`??? (${t})`:e,file:t})),s.time)}return 0===l.size?null:{name:1===l.size?Array.from(l.keys())[0]:"",indexToView:0,profiles:Array.from((0,t.itMap)(l.values(),e=>e.build()))}}
},{"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140}],153:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromHaskell=l;var e=require("../lib/profile"),r=require("../lib/value-formatters");function t(e,r,l,o,i){if(0===e.ticks&&0===e.entries&&0===e.alloc&&0===e.children.length)return r;let a=r,s=o.get(e.id);l.enterFrame(s,a);for(let r of e.children)a=t(r,a,l,o,i);return a+=i(e),l.leaveFrame(s,a),a}function l(l){const o=new Map;for(let e of l.cost_centres){const r={key:e.id,name:`${e.module}.${e.label}`};e.src_loc.startsWith("<")||(r.file=e.src_loc),o.set(e.id,r)}const i=new e.CallTreeProfileBuilder(l.total_ticks);t(l.profile,0,i,o,e=>e.ticks),i.setValueFormatter(new r.TimeFormatter("milliseconds")),i.setName(`${l.program} time`);const a=new e.CallTreeProfileBuilder(l.total_ticks);return t(l.profile,0,a,o,e=>e.alloc),a.setValueFormatter(new r.ByteFormatter),a.setName(`${l.program} allocation`),{name:l.program,indexToView:0,profiles:[i.build(),a.build()]}}
},{"../lib/profile":139,"../lib/value-formatters":140}],206:[function(require,module,exports) {
"use strict";function n(n,e){for(var r=new Array(arguments.length-1),t=0,l=2,o=!0;l<arguments.length;)r[t++]=arguments[l++];return new Promise(function(l,u){r[t]=function(n){if(o)if(o=!1,n)u(n);else{for(var e=new Array(arguments.length-1),r=0;r<e.length;)e[r++]=arguments[r];l.apply(null,e)}};try{n.apply(e||null,r)}catch(n){o&&(o=!1,u(n))}})}module.exports=n;
},{}],205:[function(require,module,exports) {
"use strict";var r=exports;r.length=function(r){var e=r.length;if(!e)return 0;for(var a=0;--e%4>1&&"="===r.charAt(e);)++a;return Math.ceil(3*r.length)/4-a};for(var e=new Array(64),a=new Array(123),t=0;t<64;)a[e[t]=t<26?t+65:t<52?t+71:t<62?t-4:t-59|43]=t++;r.encode=function(r,a,t){for(var n,i=null,o=[],c=0,s=0;a<t;){var h=r[a++];switch(s){case 0:o[c++]=e[h>>2],n=(3&h)<<4,s=1;break;case 1:o[c++]=e[n|h>>4],n=(15&h)<<2,s=2;break;case 2:o[c++]=e[n|h>>6],o[c++]=e[63&h],s=0}c>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),c=0)}return s&&(o[c++]=e[n],o[c++]=61,1===s&&(o[c++]=61)),i?(c&&i.push(String.fromCharCode.apply(String,o.slice(0,c))),i.join("")):String.fromCharCode.apply(String,o.slice(0,c))};var n="invalid encoding";r.decode=function(r,e,t){for(var i,o=t,c=0,s=0;s<r.length;){var h=r.charCodeAt(s++);if(61===h&&c>1)break;if(void 0===(h=a[h]))throw Error(n);switch(c){case 0:i=h,c=1;break;case 1:e[t++]=i<<2|(48&h)>>4,i=h,c=2;break;case 2:e[t++]=(15&i)<<4|(60&h)>>2,i=h,c=3;break;case 3:e[t++]=(3&i)<<6|h,c=0}}if(1===c)throw Error(n);return t-o},r.test=function(r){return/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(r)};
},{}],207:[function(require,module,exports) {
"use strict";function t(){this._listeners={}}module.exports=t,t.prototype.on=function(t,s,e){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:s,ctx:e||this}),this},t.prototype.off=function(t,s){if(void 0===t)this._listeners={};else if(void 0===s)this._listeners[t]=[];else for(var e=this._listeners[t],i=0;i<e.length;)e[i].fn===s?e.splice(i,1):++i;return this},t.prototype.emit=function(t){var s=this._listeners[t];if(s){for(var e=[],i=1;i<arguments.length;)e.push(arguments[i++]);for(i=0;i<s.length;)s[i].fn.apply(s[i++].ctx,e)}return this};
},{}],208:[function(require,module,exports) {
"use strict";function n(n){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),r=128===t[3];function o(n,r,o){e[0]=n,r[o]=t[0],r[o+1]=t[1],r[o+2]=t[2],r[o+3]=t[3]}function u(n,r,o){e[0]=n,r[o]=t[3],r[o+1]=t[2],r[o+2]=t[1],r[o+3]=t[0]}function i(n,r){return t[0]=n[r],t[1]=n[r+1],t[2]=n[r+2],t[3]=n[r+3],e[0]}function a(n,r){return t[3]=n[r],t[2]=n[r+1],t[1]=n[r+2],t[0]=n[r+3],e[0]}n.writeFloatLE=r?o:u,n.writeFloatBE=r?u:o,n.readFloatLE=r?i:a,n.readFloatBE=r?a:i}():function(){function u(n,e,t,r){var o=e<0?1:0;if(o&&(e=-e),0===e)n(1/e>0?0:2147483648,t,r);else if(isNaN(e))n(2143289344,t,r);else if(e>3.4028234663852886e38)n((o<<31|2139095040)>>>0,t,r);else if(e<1.1754943508222875e-38)n((o<<31|Math.round(e/1.401298464324817e-45))>>>0,t,r);else{var u=Math.floor(Math.log(e)/Math.LN2);n((o<<31|u+127<<23|8388607&Math.round(e*Math.pow(2,-u)*8388608))>>>0,t,r)}}function i(n,e,t){var r=n(e,t),o=2*(r>>31)+1,u=r>>>23&255,i=8388607&r;return 255===u?i?NaN:o*(1/0):0===u?1.401298464324817e-45*o*i:o*Math.pow(2,u-150)*(i+8388608)}n.writeFloatLE=u.bind(null,e),n.writeFloatBE=u.bind(null,t),n.readFloatLE=i.bind(null,r),n.readFloatBE=i.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),r=128===t[7];function o(n,r,o){e[0]=n,r[o]=t[0],r[o+1]=t[1],r[o+2]=t[2],r[o+3]=t[3],r[o+4]=t[4],r[o+5]=t[5],r[o+6]=t[6],r[o+7]=t[7]}function u(n,r,o){e[0]=n,r[o]=t[7],r[o+1]=t[6],r[o+2]=t[5],r[o+3]=t[4],r[o+4]=t[3],r[o+5]=t[2],r[o+6]=t[1],r[o+7]=t[0]}function i(n,r){return t[0]=n[r],t[1]=n[r+1],t[2]=n[r+2],t[3]=n[r+3],t[4]=n[r+4],t[5]=n[r+5],t[6]=n[r+6],t[7]=n[r+7],e[0]}function a(n,r){return t[7]=n[r],t[6]=n[r+1],t[5]=n[r+2],t[4]=n[r+3],t[3]=n[r+4],t[2]=n[r+5],t[1]=n[r+6],t[0]=n[r+7],e[0]}n.writeDoubleLE=r?o:u,n.writeDoubleBE=r?u:o,n.readDoubleLE=r?i:a,n.readDoubleBE=r?a:i}():function(){function u(n,e,t,r,o,u){var i=r<0?1:0;if(i&&(r=-r),0===r)n(0,o,u+e),n(1/r>0?0:2147483648,o,u+t);else if(isNaN(r))n(0,o,u+e),n(2146959360,o,u+t);else if(r>1.7976931348623157e308)n(0,o,u+e),n((i<<31|2146435072)>>>0,o,u+t);else{var a;if(r<2.2250738585072014e-308)n((a=r/5e-324)>>>0,o,u+e),n((i<<31|a/4294967296)>>>0,o,u+t);else{var l=Math.floor(Math.log(r)/Math.LN2);1024===l&&(l=1023),n(4503599627370496*(a=r*Math.pow(2,-l))>>>0,o,u+e),n((i<<31|l+1023<<20|1048576*a&1048575)>>>0,o,u+t)}}}function i(n,e,t,r,o){var u=n(r,o+e),i=n(r,o+t),a=2*(i>>31)+1,l=i>>>20&2047,f=4294967296*(1048575&i)+u;return 2047===l?f?NaN:a*(1/0):0===l?5e-324*a*f:a*Math.pow(2,l-1075)*(f+4503599627370496)}n.writeDoubleLE=u.bind(null,e,0,4),n.writeDoubleBE=u.bind(null,t,4,0),n.readDoubleLE=i.bind(null,r,0,4),n.readDoubleBE=i.bind(null,o,4,0)}(),n}function e(n,e,t){e[t]=255&n,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24}function t(n,e,t){e[t]=n>>>24,e[t+1]=n>>>16&255,e[t+2]=n>>>8&255,e[t+3]=255&n}function r(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0}function o(n,e){return(n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3])>>>0}module.exports=n(n);
},{}],209:[function(require,module,exports) {
"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire;
},{}],210:[function(require,module,exports) {
"use strict";var r=exports;r.length=function(r){for(var t=0,n=0,e=0;e<r.length;++e)(n=r.charCodeAt(e))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&r.charCodeAt(e+1))?(++e,t+=4):t+=3;return t},r.read=function(r,t,n){if(n-t<1)return"";for(var e,o=null,a=[],i=0;t<n;)(e=r[t++])<128?a[i++]=e:e>191&&e<224?a[i++]=(31&e)<<6|63&r[t++]:e>239&&e<365?(e=((7&e)<<18|(63&r[t++])<<12|(63&r[t++])<<6|63&r[t++])-65536,a[i++]=55296+(e>>10),a[i++]=56320+(1023&e)):a[i++]=(15&e)<<12|(63&r[t++])<<6|63&r[t++],i>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,a)),i=0);return o?(i&&o.push(String.fromCharCode.apply(String,a.slice(0,i))),o.join("")):String.fromCharCode.apply(String,a.slice(0,i))},r.write=function(r,t,n){for(var e,o,a=n,i=0;i<r.length;++i)(e=r.charCodeAt(i))<128?t[n++]=e:e<2048?(t[n++]=e>>6|192,t[n++]=63&e|128):55296==(64512&e)&&56320==(64512&(o=r.charCodeAt(i+1)))?(e=65536+((1023&e)<<10)+(1023&o),++i,t[n++]=e>>18|240,t[n++]=e>>12&63|128,t[n++]=e>>6&63|128,t[n++]=63&e|128):(t[n++]=e>>12|224,t[n++]=e>>6&63|128,t[n++]=63&e|128);return n-a};
},{}],211:[function(require,module,exports) {
"use strict";function r(r,n,t){var u=t||8192,e=u>>>1,l=null,c=u;return function(t){if(t<1||t>e)return r(t);c+t>u&&(l=r(u),c=0);var i=n.call(l,c,c+=t);return 7&c&&(c=1+(7|c)),i}}module.exports=r;
},{}],203:[function(require,module,exports) {
"use strict";module.exports=i;var t=require("../util/minimal");function i(t,i){this.lo=t>>>0,this.hi=i>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var r=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return o;var r=t<0;r&&(t=-t);var h=t>>>0,n=(t-h)/4294967296>>>0;return r&&(n=~n>>>0,h=~h>>>0,++h>4294967295&&(h=0,++n>4294967295&&(n=0))),new i(h,n)},i.from=function(r){if("number"==typeof r)return i.fromNumber(r);if(t.isString(r)){if(!t.Long)return i.fromNumber(parseInt(r,10));r=t.Long.fromString(r)}return r.low||r.high?new i(r.low>>>0,r.high>>>0):o},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var i=1+~this.lo>>>0,o=~this.hi>>>0;return i||(o=o+1>>>0),-(i+4294967296*o)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(i){return t.Long?new t.Long(0|this.lo,0|this.hi,Boolean(i)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(i)}};var h=String.prototype.charCodeAt;i.fromHash=function(t){return t===r?o:new i((h.call(t,0)|h.call(t,1)<<8|h.call(t,2)<<16|h.call(t,3)<<24)>>>0,(h.call(t,4)|h.call(t,5)<<8|h.call(t,6)<<16|h.call(t,7)<<24)>>>0)},i.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)},i.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},i.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},i.prototype.length=function(){var t=this.lo,i=(this.lo>>>28|this.hi<<4)>>>0,o=this.hi>>>24;return 0===o?0===i?t<16384?t<128?1:2:t<2097152?3:4:i<16384?i<128?5:6:i<2097152?7:8:o<128?9:10};
},{"../util/minimal":201}],212:[function(require,module,exports) {
"use strict";exports.byteLength=u,exports.toByteArray=i,exports.fromByteArray=d;for(var r=[],t=[],e="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=n.length;o<a;++o)r[o]=n[o],t[n.charCodeAt(o)]=o;function h(r){var t=r.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=r.indexOf("=");return-1===e&&(e=t),[e,e===t?0:4-e%4]}function u(r){var t=h(r),e=t[0],n=t[1];return 3*(e+n)/4-n}function c(r,t,e){return 3*(t+e)/4-e}function i(r){for(var n,o=h(r),a=o[0],u=o[1],i=new e(c(r,a,u)),f=0,A=u>0?a-4:a,d=0;d<A;d+=4)n=t[r.charCodeAt(d)]<<18|t[r.charCodeAt(d+1)]<<12|t[r.charCodeAt(d+2)]<<6|t[r.charCodeAt(d+3)],i[f++]=n>>16&255,i[f++]=n>>8&255,i[f++]=255&n;return 2===u&&(n=t[r.charCodeAt(d)]<<2|t[r.charCodeAt(d+1)]>>4,i[f++]=255&n),1===u&&(n=t[r.charCodeAt(d)]<<10|t[r.charCodeAt(d+1)]<<4|t[r.charCodeAt(d+2)]>>2,i[f++]=n>>8&255,i[f++]=255&n),i}function f(t){return r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}function A(r,t,e){for(var n,o=[],a=t;a<e;a+=3)n=(r[a]<<16&16711680)+(r[a+1]<<8&65280)+(255&r[a+2]),o.push(f(n));return o.join("")}function d(t){for(var e,n=t.length,o=n%3,a=[],h=0,u=n-o;h<u;h+=16383)a.push(A(t,h,h+16383>u?u:h+16383));return 1===o?(e=t[n-1],a.push(r[e>>2]+r[e<<4&63]+"==")):2===o&&(e=(t[n-2]<<8)+t[n-1],a.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),a.join("")}t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63;
},{}],213:[function(require,module,exports) {
exports.read=function(a,o,t,r,h){var M,p,w=8*h-r-1,f=(1<<w)-1,e=f>>1,i=-7,N=t?h-1:0,n=t?-1:1,s=a[o+N];for(N+=n,M=s&(1<<-i)-1,s>>=-i,i+=w;i>0;M=256*M+a[o+N],N+=n,i-=8);for(p=M&(1<<-i)-1,M>>=-i,i+=r;i>0;p=256*p+a[o+N],N+=n,i-=8);if(0===M)M=1-e;else{if(M===f)return p?NaN:1/0*(s?-1:1);p+=Math.pow(2,r),M-=e}return(s?-1:1)*p*Math.pow(2,M-r)},exports.write=function(a,o,t,r,h,M){var p,w,f,e=8*M-h-1,i=(1<<e)-1,N=i>>1,n=23===h?Math.pow(2,-24)-Math.pow(2,-77):0,s=r?0:M-1,u=r?1:-1,l=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(w=isNaN(o)?1:0,p=i):(p=Math.floor(Math.log(o)/Math.LN2),o*(f=Math.pow(2,-p))<1&&(p--,f*=2),(o+=p+N>=1?n/f:n*Math.pow(2,1-N))*f>=2&&(p++,f/=2),p+N>=i?(w=0,p=i):p+N>=1?(w=(o*f-1)*Math.pow(2,h),p+=N):(w=o*Math.pow(2,N-1)*Math.pow(2,h),p=0));h>=8;a[t+s]=255&w,s+=u,w/=256,h-=8);for(p=p<<h|w,e+=h;e>0;a[t+s]=255&p,s+=u,p/=256,e-=8);a[t+s-u]|=128*l};
},{}],214:[function(require,module,exports) {
var r={}.toString;module.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)};
},{}],204:[function(require,module,exports) {
var global = arguments[3];
var t=arguments[3],r=require("base64-js"),e=require("ieee754"),n=require("isarray");function i(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}function o(){return f.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function u(t,r){if(o()<r)throw new RangeError("Invalid typed array length");return f.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(r)).__proto__=f.prototype:(null===t&&(t=new f(r)),t.length=r),t}function f(t,r,e){if(!(f.TYPED_ARRAY_SUPPORT||this instanceof f))return new f(t,r,e);if("number"==typeof t){if("string"==typeof r)throw new Error("If encoding is specified then the first argument must be a string");return c(this,t)}return s(this,t,r,e)}function s(t,r,e,n){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&r instanceof ArrayBuffer?g(t,r,e,n):"string"==typeof r?l(t,r,e):y(t,r)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function a(t,r,e,n){return h(r),r<=0?u(t,r):void 0!==e?"string"==typeof n?u(t,r).fill(e,n):u(t,r).fill(e):u(t,r)}function c(t,r){if(h(r),t=u(t,r<0?0:0|w(r)),!f.TYPED_ARRAY_SUPPORT)for(var e=0;e<r;++e)t[e]=0;return t}function l(t,r,e){if("string"==typeof e&&""!==e||(e="utf8"),!f.isEncoding(e))throw new TypeError('"encoding" must be a valid string encoding');var n=0|v(r,e),i=(t=u(t,n)).write(r,e);return i!==n&&(t=t.slice(0,i)),t}function p(t,r){var e=r.length<0?0:0|w(r.length);t=u(t,e);for(var n=0;n<e;n+=1)t[n]=255&r[n];return t}function g(t,r,e,n){if(r.byteLength,e<0||r.byteLength<e)throw new RangeError("'offset' is out of bounds");if(r.byteLength<e+(n||0))throw new RangeError("'length' is out of bounds");return r=void 0===e&&void 0===n?new Uint8Array(r):void 0===n?new Uint8Array(r,e):new Uint8Array(r,e,n),f.TYPED_ARRAY_SUPPORT?(t=r).__proto__=f.prototype:t=p(t,r),t}function y(t,r){if(f.isBuffer(r)){var e=0|w(r.length);return 0===(t=u(t,e)).length?t:(r.copy(t,0,0,e),t)}if(r){if("undefined"!=typeof ArrayBuffer&&r.buffer instanceof ArrayBuffer||"length"in r)return"number"!=typeof r.length||W(r.length)?u(t,0):p(t,r);if("Buffer"===r.type&&n(r.data))return p(t,r.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function w(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function d(t){return+t!=t&&(t=0),f.alloc(+t)}function v(t,r){if(f.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return $(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return K(t).length;default:if(n)return $(t).length;r=(""+r).toLowerCase(),n=!0}}function E(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return x(this,r,e);case"utf8":case"utf-8":return Y(this,r,e);case"ascii":return L(this,r,e);case"latin1":case"binary":return D(this,r,e);case"base64":return S(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function b(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function R(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=f.from(r,n)),f.isBuffer(r))return 0===r.length?-1:_(t,r,e,n,i);if("number"==typeof r)return r&=255,f.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):_(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function _(t,r,e,n,i){var o,u=1,f=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,f/=2,s/=2,e/=2}function h(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}if(i){var a=-1;for(o=e;o<f;o++)if(h(t,o)===h(r,-1===a?0:o-a)){if(-1===a&&(a=o),o-a+1===s)return a*u}else-1!==a&&(o-=o-a),a=-1}else for(e+s>f&&(e=f-s),o=e;o>=0;o--){for(var c=!0,l=0;l<s;l++)if(h(t,o+l)!==h(r,l)){c=!1;break}if(c)return o}return-1}function A(t,r,e,n){e=Number(e)||0;var i=t.length-e;n?(n=Number(n))>i&&(n=i):n=i;var o=r.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var u=0;u<n;++u){var f=parseInt(r.substr(2*u,2),16);if(isNaN(f))return u;t[e+u]=f}return u}function m(t,r,e,n){return Q($(r,t.length-e),t,e,n)}function P(t,r,e,n){return Q(G(r),t,e,n)}function T(t,r,e,n){return P(t,r,e,n)}function B(t,r,e,n){return Q(K(r),t,e,n)}function U(t,r,e,n){return Q(H(r,t.length-e),t,e,n)}function S(t,e,n){return 0===e&&n===t.length?r.fromByteArray(t):r.fromByteArray(t.slice(e,n))}function Y(t,r,e){e=Math.min(t.length,e);for(var n=[],i=r;i<e;){var o,u,f,s,h=t[i],a=null,c=h>239?4:h>223?3:h>191?2:1;if(i+c<=e)switch(c){case 1:h<128&&(a=h);break;case 2:128==(192&(o=t[i+1]))&&(s=(31&h)<<6|63&o)>127&&(a=s);break;case 3:o=t[i+1],u=t[i+2],128==(192&o)&&128==(192&u)&&(s=(15&h)<<12|(63&o)<<6|63&u)>2047&&(s<55296||s>57343)&&(a=s);break;case 4:o=t[i+1],u=t[i+2],f=t[i+3],128==(192&o)&&128==(192&u)&&128==(192&f)&&(s=(15&h)<<18|(63&o)<<12|(63&u)<<6|63&f)>65535&&s<1114112&&(a=s)}null===a?(a=65533,c=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=c}return O(n)}exports.Buffer=f,exports.SlowBuffer=d,exports.INSPECT_MAX_BYTES=50,f.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),exports.kMaxLength=o(),f.poolSize=8192,f._augment=function(t){return t.__proto__=f.prototype,t},f.from=function(t,r,e){return s(null,t,r,e)},f.TYPED_ARRAY_SUPPORT&&(f.prototype.__proto__=Uint8Array.prototype,f.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&f[Symbol.species]===f&&Object.defineProperty(f,Symbol.species,{value:null,configurable:!0})),f.alloc=function(t,r,e){return a(null,t,r,e)},f.allocUnsafe=function(t){return c(null,t)},f.allocUnsafeSlow=function(t){return c(null,t)},f.isBuffer=function(t){return!(null==t||!t._isBuffer)},f.compare=function(t,r){if(!f.isBuffer(t)||!f.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(t===r)return 0;for(var e=t.length,n=r.length,i=0,o=Math.min(e,n);i<o;++i)if(t[i]!==r[i]){e=t[i],n=r[i];break}return e<n?-1:n<e?1:0},f.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},f.concat=function(t,r){if(!n(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return f.alloc(0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var i=f.allocUnsafe(r),o=0;for(e=0;e<t.length;++e){var u=t[e];if(!f.isBuffer(u))throw new TypeError('"list" argument must be an Array of Buffers');u.copy(i,o),o+=u.length}return i},f.byteLength=v,f.prototype._isBuffer=!0,f.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)b(this,r,r+1);return this},f.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)b(this,r,r+3),b(this,r+1,r+2);return this},f.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)b(this,r,r+7),b(this,r+1,r+6),b(this,r+2,r+5),b(this,r+3,r+4);return this},f.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?Y(this,0,t):E.apply(this,arguments)},f.prototype.equals=function(t){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===f.compare(this,t)},f.prototype.inspect=function(){var t="",r=exports.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),"<Buffer "+t+">"},f.prototype.compare=function(t,r,e,n,i){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),u=(e>>>=0)-(r>>>=0),s=Math.min(o,u),h=this.slice(n,i),a=t.slice(r,e),c=0;c<s;++c)if(h[c]!==a[c]){o=h[c],u=a[c];break}return o<u?-1:u<o?1:0},f.prototype.includes=function(t,r,e){return-1!==this.indexOf(t,r,e)},f.prototype.indexOf=function(t,r,e){return R(this,t,r,e,!0)},f.prototype.lastIndexOf=function(t,r,e){return R(this,t,r,e,!1)},f.prototype.write=function(t,r,e,n){if(void 0===r)n="utf8",e=this.length,r=0;else if(void 0===e&&"string"==typeof r)n=r,e=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(e)?(e|=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var i=this.length-r;if((void 0===e||e>i)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return A(this,t,r,e);case"utf8":case"utf-8":return m(this,t,r,e);case"ascii":return P(this,t,r,e);case"latin1":case"binary":return T(this,t,r,e);case"base64":return B(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;function O(t){var r=t.length;if(r<=I)return String.fromCharCode.apply(String,t);for(var e="",n=0;n<r;)e+=String.fromCharCode.apply(String,t.slice(n,n+=I));return e}function L(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;i<e;++i)n+=String.fromCharCode(127&t[i]);return n}function D(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;i<e;++i)n+=String.fromCharCode(t[i]);return n}function x(t,r,e){var n=t.length;(!r||r<0)&&(r=0),(!e||e<0||e>n)&&(e=n);for(var i="",o=r;o<e;++o)i+=Z(t[o]);return i}function C(t,r,e){for(var n=t.slice(r,e),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function M(t,r,e){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+r>e)throw new RangeError("Trying to access beyond buffer length")}function k(t,r,e,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||r<o)throw new RangeError('"value" argument is out of bounds');if(e+n>t.length)throw new RangeError("Index out of range")}function N(t,r,e,n){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-e,2);i<o;++i)t[e+i]=(r&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function z(t,r,e,n){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-e,4);i<o;++i)t[e+i]=r>>>8*(n?i:3-i)&255}function F(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function j(t,r,n,i,o){return o||F(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),e.write(t,r,n,i,23,4),n+4}function q(t,r,n,i,o){return o||F(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),e.write(t,r,n,i,52,8),n+8}f.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r<t&&(r=t),f.TYPED_ARRAY_SUPPORT)(e=this.subarray(t,r)).__proto__=f.prototype;else{var i=r-t;e=new f(i,void 0);for(var o=0;o<i;++o)e[o]=this[o+t]}return e},f.prototype.readUIntLE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n},f.prototype.readUIntBE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},f.prototype.readUInt8=function(t,r){return r||M(t,1,this.length),this[t]},f.prototype.readUInt16LE=function(t,r){return r||M(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUInt16BE=function(t,r){return r||M(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUInt32LE=function(t,r){return r||M(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUInt32BE=function(t,r){return r||M(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*r)),n},f.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},f.prototype.readInt8=function(t,r){return r||M(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,r){r||M(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt16BE=function(t,r){r||M(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt32LE=function(t,r){return r||M(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,r){return r||M(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readFloatLE=function(t,r){return r||M(t,4,this.length),e.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,r){return r||M(t,4,this.length),e.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,r){return r||M(t,8,this.length),e.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,r){return r||M(t,8,this.length),e.read(this,t,!1,52,8)},f.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||k(this,t,r,e,Math.pow(2,8*e)-1,0);var i=1,o=0;for(this[r]=255&t;++o<e&&(i*=256);)this[r+o]=t/i&255;return r+e},f.prototype.writeUIntBE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||k(this,t,r,e,Math.pow(2,8*e)-1,0);var i=e-1,o=1;for(this[r+i]=255&t;--i>=0&&(o*=256);)this[r+i]=t/o&255;return r+e},f.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,1,255,0),f.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},f.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):N(this,t,r,!0),r+2},f.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):N(this,t,r,!1),r+2},f.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):z(this,t,r,!0),r+4},f.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):z(this,t,r,!1),r+4},f.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);k(this,t,r,e,i-1,-i)}var o=0,u=1,f=0;for(this[r]=255&t;++o<e&&(u*=256);)t<0&&0===f&&0!==this[r+o-1]&&(f=1),this[r+o]=(t/u>>0)-f&255;return r+e},f.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);k(this,t,r,e,i-1,-i)}var o=e-1,u=1,f=0;for(this[r+o]=255&t;--o>=0&&(u*=256);)t<0&&0===f&&0!==this[r+o+1]&&(f=1),this[r+o]=(t/u>>0)-f&255;return r+e},f.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,1,127,-128),f.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},f.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):N(this,t,r,!0),r+2},f.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):N(this,t,r,!1),r+2},f.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,2147483647,-2147483648),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):z(this,t,r,!0),r+4},f.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):z(this,t,r,!1),r+4},f.prototype.writeFloatLE=function(t,r,e){return j(this,t,r,!0,e)},f.prototype.writeFloatBE=function(t,r,e){return j(this,t,r,!1,e)},f.prototype.writeDoubleLE=function(t,r,e){return q(this,t,r,!0,e)},f.prototype.writeDoubleBE=function(t,r,e){return q(this,t,r,!1,e)},f.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-e&&(n=t.length-r+e);var i,o=n-e;if(this===t&&e<r&&r<n)for(i=o-1;i>=0;--i)t[i+r]=this[i+e];else if(o<1e3||!f.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)t[i+r]=this[i+e];else Uint8Array.prototype.set.call(t,this.subarray(e,e+o),r);return o},f.prototype.fill=function(t,r,e,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,e=this.length):"string"==typeof e&&(n=e,e=this.length),1===t.length){var i=t.charCodeAt(0);i<256&&(t=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!f.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var o;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(o=r;o<e;++o)this[o]=t;else{var u=f.isBuffer(t)?t:$(new f(t,n).toString()),s=u.length;for(o=0;o<e-r;++o)this[o+r]=u[o%s]}return this};var V=/[^+\/0-9A-Za-z-_]/g;function X(t){if((t=J(t).replace(V,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}function J(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function Z(t){return t<16?"0"+t.toString(16):t.toString(16)}function $(t,r){var e;r=r||1/0;for(var n=t.length,i=null,o=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function G(t){for(var r=[],e=0;e<t.length;++e)r.push(255&t.charCodeAt(e));return r}function H(t,r){for(var e,n,i,o=[],u=0;u<t.length&&!((r-=2)<0);++u)n=(e=t.charCodeAt(u))>>8,i=e%256,o.push(i),o.push(n);return o}function K(t){return r.toByteArray(X(t))}function Q(t,r,e,n){for(var i=0;i<n&&!(i+e>=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function W(t){return t!=t}
},{"base64-js":212,"ieee754":213,"isarray":214,"buffer":204}],201:[function(require,module,exports) {
var global = arguments[3];
var Buffer = require("buffer").Buffer;
var e=arguments[3],r=require("buffer").Buffer,t=exports;function n(e,r,t){for(var n=Object.keys(r),o=0;o<n.length;++o)void 0!==e[n[o]]&&t||(e[n[o]]=r[n[o]]);return e}function o(e){function r(e,t){if(!(this instanceof r))return new r(e,t);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,r):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),t&&n(this,t)}return(r.prototype=Object.create(Error.prototype)).constructor=r,Object.defineProperty(r.prototype,"name",{get:function(){return e}}),r.prototype.toString=function(){return this.name+": "+this.message},r}t.asPromise=require("@protobufjs/aspromise"),t.base64=require("@protobufjs/base64"),t.EventEmitter=require("@protobufjs/eventemitter"),t.float=require("@protobufjs/float"),t.inquire=require("@protobufjs/inquire"),t.utf8=require("@protobufjs/utf8"),t.pool=require("@protobufjs/pool"),t.LongBits=require("./longbits"),t.global="undefined"!=typeof window&&window||void 0!==e&&e||"undefined"!=typeof self&&self||this,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isNode=Boolean(t.global.process&&t.global.process.versions&&t.global.process.versions.node),t.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return"string"==typeof e||e instanceof String},t.isObject=function(e){return e&&"object"==typeof e},t.isset=t.isSet=function(e,r){var t=e[r];return!(null==t||!e.hasOwnProperty(r))&&("object"!=typeof t||(Array.isArray(t)?t.length:Object.keys(t).length)>0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return"number"==typeof e?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},t.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,r){var n=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(n.lo,n.hi,r):n.toNumber(Boolean(r))},t.merge=n,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=o,t.ProtocolError=o("ProtocolError"),t.oneOfGetter=function(e){for(var r={},t=0;t<e.length;++t)r[e[t]]=1;return function(){for(var e=Object.keys(this),t=e.length-1;t>-1;--t)if(1===r[e[t]]&&void 0!==this[e[t]]&&null!==this[e[t]])return e[t]}},t.oneOfSetter=function(e){return function(r){for(var t=0;t<e.length;++t)e[t]!==r&&delete this[e[t]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;e?(t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(r,t){return new e(r,t)},t._Buffer_allocUnsafe=e.allocUnsafe||function(r){return new e(r)}):t._Buffer_from=t._Buffer_allocUnsafe=null};
},{"@protobufjs/aspromise":206,"@protobufjs/base64":205,"@protobufjs/eventemitter":207,"@protobufjs/float":208,"@protobufjs/inquire":209,"@protobufjs/utf8":210,"@protobufjs/pool":211,"./longbits":203,"buffer":204}],193:[function(require,module,exports) {
"use strict";module.exports=u;var t,i=require("./util/minimal"),n=i.LongBits,e=i.base64,o=i.utf8;function r(t,i,n){this.fn=t,this.len=i,this.next=void 0,this.val=n}function s(){}function h(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function u(){this.len=0,this.head=new r(s,0,0),this.tail=this.head,this.states=null}function l(t,i,n){i[n]=255&t}function p(t,i,n){for(;t>127;)i[n++]=127&t|128,t>>>=7;i[n]=t}function a(t,i){this.len=t,this.next=void 0,this.val=i}function f(t,i,n){for(;t.hi;)i[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)i[n++]=127&t.lo|128,t.lo=t.lo>>>7;i[n++]=t.lo}function c(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}u.create=i.Buffer?function(){return(u.create=function(){return new t})()}:function(){return new u},u.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(u.alloc=i.pool(u.alloc,i.Array.prototype.subarray)),u.prototype._push=function(t,i,n){return this.tail=this.tail.next=new r(t,i,n),this.len+=i,this},a.prototype=Object.create(r.prototype),a.prototype.fn=p,u.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new a((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},u.prototype.int32=function(t){return t<0?this._push(f,10,n.fromNumber(t)):this.uint32(t)},u.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},u.prototype.uint64=function(t){var i=n.from(t);return this._push(f,i.length(),i)},u.prototype.int64=u.prototype.uint64,u.prototype.sint64=function(t){var i=n.from(t).zzEncode();return this._push(f,i.length(),i)},u.prototype.bool=function(t){return this._push(l,1,t?1:0)},u.prototype.fixed32=function(t){return this._push(c,4,t>>>0)},u.prototype.sfixed32=u.prototype.fixed32,u.prototype.fixed64=function(t){var i=n.from(t);return this._push(c,4,i.lo)._push(c,4,i.hi)},u.prototype.sfixed64=u.prototype.fixed64,u.prototype.float=function(t){return this._push(i.float.writeFloatLE,4,t)},u.prototype.double=function(t){return this._push(i.float.writeDoubleLE,8,t)};var y=i.Array.prototype.set?function(t,i,n){i.set(t,n)}:function(t,i,n){for(var e=0;e<t.length;++e)i[n+e]=t[e]};u.prototype.bytes=function(t){var n=t.length>>>0;if(!n)return this._push(l,1,0);if(i.isString(t)){var o=u.alloc(n=e.length(t));e.decode(t,o,0),t=o}return this.uint32(n)._push(y,n,t)},u.prototype.string=function(t){var i=o.length(t);return i?this.uint32(i)._push(o.write,i,t):this._push(l,1,0)},u.prototype.fork=function(){return this.states=new h(this),this.head=this.tail=new r(s,0,0),this.len=0,this},u.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 r(s,0,0),this.len=0),this},u.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},u.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},u._configure=function(i){t=i};
},{"./util/minimal":201}],194:[function(require,module,exports) {
"use strict";module.exports=n;var t=require("./writer");(n.prototype=Object.create(t.prototype)).constructor=n;var e=require("./util/minimal"),r=e.Buffer;function n(){t.call(this)}n.alloc=function(t){return(n.alloc=e._Buffer_allocUnsafe)(t)};var i=r&&r.prototype instanceof Uint8Array&&"set"===r.prototype.set.name?function(t,e,r){e.set(t,r)}:function(t,e,r){if(t.copy)t.copy(e,r,0,t.length);else for(var n=0;n<t.length;)e[r++]=t[n++]};function o(t,r,n){t.length<40?e.utf8.write(t,r,n):r.utf8Write(t,n)}n.prototype.bytes=function(t){e.isString(t)&&(t=e._Buffer_from(t,"base64"));var r=t.length>>>0;return this.uint32(r),r&&this._push(i,r,t),this},n.prototype.string=function(t){var e=r.byteLength(t);return this.uint32(e),e&&this._push(o,e,t),this};
},{"./writer":193,"./util/minimal":201}],195:[function(require,module,exports) {
"use strict";module.exports=h;var t,i=require("./util/minimal"),s=i.LongBits,r=i.utf8;function o(t,i){return RangeError("index out of range: "+t.pos+" + "+(i||1)+" > "+t.len)}function h(t){this.buf=t,this.pos=0,this.len=t.length}var n="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new h(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new h(t);throw Error("illegal buffer")};function e(){var t=new s(0,0),i=0;if(!(this.len-this.pos>4)){for(;i<3;++i){if(this.pos>=this.len)throw o(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,this.len-this.pos>4){for(;i<5;++i)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*i+3)>>>0,this.buf[this.pos++]<128)return t}else for(;i<5;++i){if(this.pos>=this.len)throw o(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 u(t,i){return(t[i-4]|t[i-3]<<8|t[i-2]<<16|t[i-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw o(this,8);return new s(u(this.buf,this.pos+=4),u(this.buf,this.pos+=4))}h.create=i.Buffer?function(s){return(h.create=function(s){return i.Buffer.isBuffer(s)?new t(s):n(s)})(s)}:n,h.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,h.prototype.uint32=function(){var t=4294967295;return function(){if(t=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return t;if((this.pos+=5)>this.len)throw this.pos=this.len,o(this,10);return t}}(),h.prototype.int32=function(){return 0|this.uint32()},h.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},h.prototype.bool=function(){return 0!==this.uint32()},h.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return u(this.buf,this.pos+=4)},h.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|u(this.buf,this.pos+=4)},h.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},h.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},h.prototype.bytes=function(){var t=this.uint32(),i=this.pos,s=this.pos+t;if(s>this.len)throw o(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(i,s):i===s?new this.buf.constructor(0):this._slice.call(this.buf,i,s)},h.prototype.string=function(){var t=this.bytes();return r.read(t,0,t.length)},h.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw o(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},h.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},h._configure=function(s){t=s;var r=i.Long?"toLong":"toNumber";i.merge(h.prototype,{int64:function(){return e.call(this)[r](!1)},uint64:function(){return e.call(this)[r](!0)},sint64:function(){return e.call(this).zzDecode()[r](!1)},fixed64:function(){return f.call(this)[r](!0)},sfixed64:function(){return f.call(this)[r](!1)}})};
},{"./util/minimal":201}],196:[function(require,module,exports) {
"use strict";module.exports=r;var t=require("./reader");(r.prototype=Object.create(t.prototype)).constructor=r;var e=require("./util/minimal");function r(e){t.call(this,e)}e.Buffer&&(r.prototype._slice=e.Buffer.prototype.slice),r.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len))};
},{"./reader":195,"./util/minimal":201}],202:[function(require,module,exports) {
"use strict";module.exports=t;var e=require("../util/minimal");function t(t,r,i){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");e.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(r),this.responseDelimited=Boolean(i)}(t.prototype=Object.create(e.EventEmitter.prototype)).constructor=t,t.prototype.rpcCall=function t(r,i,n,o,l){if(!o)throw TypeError("request must be specified");var u=this;if(!l)return e.asPromise(t,u,r,i,n,o);if(u.rpcImpl)try{return u.rpcImpl(r,i[u.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(e,t){if(e)return u.emit("error",e,r),l(e);if(null!==t){if(!(t instanceof n))try{t=n[u.responseDelimited?"decodeDelimited":"decode"](t)}catch(e){return u.emit("error",e,r),l(e)}return u.emit("data",t,r),l(null,t)}u.end(!0)})}catch(e){return u.emit("error",e,r),void setTimeout(function(){l(e)},0)}else setTimeout(function(){l(Error("already ended"))},0)},t.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};
},{"../util/minimal":201}],197:[function(require,module,exports) {
"use strict";var e=exports;e.Service=require("./rpc/service");
},{"./rpc/service":202}],198:[function(require,module,exports) {
"use strict";module.exports={};
},{}],189:[function(require,module,exports) {
"use strict";var r=exports;function e(){r.Reader._configure(r.BufferReader),r.util._configure()}r.build="minimal",r.Writer=require("./writer"),r.BufferWriter=require("./writer_buffer"),r.Reader=require("./reader"),r.BufferReader=require("./reader_buffer"),r.util=require("./util/minimal"),r.rpc=require("./rpc"),r.roots=require("./roots"),r.configure=e,r.Writer._configure(r.BufferWriter),e();
},{"./writer":193,"./writer_buffer":194,"./reader":195,"./reader_buffer":196,"./util/minimal":201,"./rpc":197,"./roots":198}],186:[function(require,module,exports) {
"use strict";module.exports=require("./src/index-minimal");
},{"./src/index-minimal":189}],174:[function(require,module,exports) {
"use strict";var e=require("protobufjs/minimal"),n=e.Reader,t=e.Writer,o=e.util,r=e.roots.default||(e.roots.default={});r.perftools=function(){var i,l={};return l.profiles=((i={}).Profile=function(){function i(e){if(this.sampleType=[],this.sample=[],this.mapping=[],this.location=[],this.function=[],this.stringTable=[],this.comment=[],e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.sampleType=o.emptyArray,i.prototype.sample=o.emptyArray,i.prototype.mapping=o.emptyArray,i.prototype.location=o.emptyArray,i.prototype.function=o.emptyArray,i.prototype.stringTable=o.emptyArray,i.prototype.dropFrames=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.keepFrames=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.timeNanos=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.durationNanos=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.periodType=null,i.prototype.period=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.comment=o.emptyArray,i.prototype.defaultSampleType=o.Long?o.Long.fromBits(0,0,!1):0,i.create=function(e){return new i(e)},i.encode=function(e,n){if(n||(n=t.create()),null!=e.sampleType&&e.sampleType.length)for(var o=0;o<e.sampleType.length;++o)r.perftools.profiles.ValueType.encode(e.sampleType[o],n.uint32(10).fork()).ldelim();if(null!=e.sample&&e.sample.length)for(o=0;o<e.sample.length;++o)r.perftools.profiles.Sample.encode(e.sample[o],n.uint32(18).fork()).ldelim();if(null!=e.mapping&&e.mapping.length)for(o=0;o<e.mapping.length;++o)r.perftools.profiles.Mapping.encode(e.mapping[o],n.uint32(26).fork()).ldelim();if(null!=e.location&&e.location.length)for(o=0;o<e.location.length;++o)r.perftools.profiles.Location.encode(e.location[o],n.uint32(34).fork()).ldelim();if(null!=e.function&&e.function.length)for(o=0;o<e.function.length;++o)r.perftools.profiles.Function.encode(e.function[o],n.uint32(42).fork()).ldelim();if(null!=e.stringTable&&e.stringTable.length)for(o=0;o<e.stringTable.length;++o)n.uint32(50).string(e.stringTable[o]);if(null!=e.dropFrames&&e.hasOwnProperty("dropFrames")&&n.uint32(56).int64(e.dropFrames),null!=e.keepFrames&&e.hasOwnProperty("keepFrames")&&n.uint32(64).int64(e.keepFrames),null!=e.timeNanos&&e.hasOwnProperty("timeNanos")&&n.uint32(72).int64(e.timeNanos),null!=e.durationNanos&&e.hasOwnProperty("durationNanos")&&n.uint32(80).int64(e.durationNanos),null!=e.periodType&&e.hasOwnProperty("periodType")&&r.perftools.profiles.ValueType.encode(e.periodType,n.uint32(90).fork()).ldelim(),null!=e.period&&e.hasOwnProperty("period")&&n.uint32(96).int64(e.period),null!=e.comment&&e.comment.length){for(n.uint32(106).fork(),o=0;o<e.comment.length;++o)n.int64(e.comment[o]);n.ldelim()}return null!=e.defaultSampleType&&e.hasOwnProperty("defaultSampleType")&&n.uint32(112).int64(e.defaultSampleType),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Profile;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.sampleType&&i.sampleType.length||(i.sampleType=[]),i.sampleType.push(r.perftools.profiles.ValueType.decode(e,e.uint32()));break;case 2:i.sample&&i.sample.length||(i.sample=[]),i.sample.push(r.perftools.profiles.Sample.decode(e,e.uint32()));break;case 3:i.mapping&&i.mapping.length||(i.mapping=[]),i.mapping.push(r.perftools.profiles.Mapping.decode(e,e.uint32()));break;case 4:i.location&&i.location.length||(i.location=[]),i.location.push(r.perftools.profiles.Location.decode(e,e.uint32()));break;case 5:i.function&&i.function.length||(i.function=[]),i.function.push(r.perftools.profiles.Function.decode(e,e.uint32()));break;case 6:i.stringTable&&i.stringTable.length||(i.stringTable=[]),i.stringTable.push(e.string());break;case 7:i.dropFrames=e.int64();break;case 8:i.keepFrames=e.int64();break;case 9:i.timeNanos=e.int64();break;case 10:i.durationNanos=e.int64();break;case 11:i.periodType=r.perftools.profiles.ValueType.decode(e,e.uint32());break;case 12:i.period=e.int64();break;case 13:if(i.comment&&i.comment.length||(i.comment=[]),2==(7&l))for(var s=e.uint32()+e.pos;e.pos<s;)i.comment.push(e.int64());else i.comment.push(e.int64());break;case 14:i.defaultSampleType=e.int64();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.sampleType&&e.hasOwnProperty("sampleType")){if(!Array.isArray(e.sampleType))return"sampleType: array expected";for(var n=0;n<e.sampleType.length;++n)if(t=r.perftools.profiles.ValueType.verify(e.sampleType[n]))return"sampleType."+t}if(null!=e.sample&&e.hasOwnProperty("sample")){if(!Array.isArray(e.sample))return"sample: array expected";for(n=0;n<e.sample.length;++n)if(t=r.perftools.profiles.Sample.verify(e.sample[n]))return"sample."+t}if(null!=e.mapping&&e.hasOwnProperty("mapping")){if(!Array.isArray(e.mapping))return"mapping: array expected";for(n=0;n<e.mapping.length;++n)if(t=r.perftools.profiles.Mapping.verify(e.mapping[n]))return"mapping."+t}if(null!=e.location&&e.hasOwnProperty("location")){if(!Array.isArray(e.location))return"location: array expected";for(n=0;n<e.location.length;++n)if(t=r.perftools.profiles.Location.verify(e.location[n]))return"location."+t}if(null!=e.function&&e.hasOwnProperty("function")){if(!Array.isArray(e.function))return"function: array expected";for(n=0;n<e.function.length;++n)if(t=r.perftools.profiles.Function.verify(e.function[n]))return"function."+t}if(null!=e.stringTable&&e.hasOwnProperty("stringTable")){if(!Array.isArray(e.stringTable))return"stringTable: array expected";for(n=0;n<e.stringTable.length;++n)if(!o.isString(e.stringTable[n]))return"stringTable: string[] expected"}if(null!=e.dropFrames&&e.hasOwnProperty("dropFrames")&&!(o.isInteger(e.dropFrames)||e.dropFrames&&o.isInteger(e.dropFrames.low)&&o.isInteger(e.dropFrames.high)))return"dropFrames: integer|Long expected";if(null!=e.keepFrames&&e.hasOwnProperty("keepFrames")&&!(o.isInteger(e.keepFrames)||e.keepFrames&&o.isInteger(e.keepFrames.low)&&o.isInteger(e.keepFrames.high)))return"keepFrames: integer|Long expected";if(null!=e.timeNanos&&e.hasOwnProperty("timeNanos")&&!(o.isInteger(e.timeNanos)||e.timeNanos&&o.isInteger(e.timeNanos.low)&&o.isInteger(e.timeNanos.high)))return"timeNanos: integer|Long expected";if(null!=e.durationNanos&&e.hasOwnProperty("durationNanos")&&!(o.isInteger(e.durationNanos)||e.durationNanos&&o.isInteger(e.durationNanos.low)&&o.isInteger(e.durationNanos.high)))return"durationNanos: integer|Long expected";var t;if(null!=e.periodType&&e.hasOwnProperty("periodType")&&(t=r.perftools.profiles.ValueType.verify(e.periodType)))return"periodType."+t;if(null!=e.period&&e.hasOwnProperty("period")&&!(o.isInteger(e.period)||e.period&&o.isInteger(e.period.low)&&o.isInteger(e.period.high)))return"period: integer|Long expected";if(null!=e.comment&&e.hasOwnProperty("comment")){if(!Array.isArray(e.comment))return"comment: array expected";for(n=0;n<e.comment.length;++n)if(!(o.isInteger(e.comment[n])||e.comment[n]&&o.isInteger(e.comment[n].low)&&o.isInteger(e.comment[n].high)))return"comment: integer|Long[] expected"}return null!=e.defaultSampleType&&e.hasOwnProperty("defaultSampleType")&&!(o.isInteger(e.defaultSampleType)||e.defaultSampleType&&o.isInteger(e.defaultSampleType.low)&&o.isInteger(e.defaultSampleType.high))?"defaultSampleType: integer|Long expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Profile)return e;var n=new r.perftools.profiles.Profile;if(e.sampleType){if(!Array.isArray(e.sampleType))throw TypeError(".perftools.profiles.Profile.sampleType: array expected");n.sampleType=[];for(var t=0;t<e.sampleType.length;++t){if("object"!=typeof e.sampleType[t])throw TypeError(".perftools.profiles.Profile.sampleType: object expected");n.sampleType[t]=r.perftools.profiles.ValueType.fromObject(e.sampleType[t])}}if(e.sample){if(!Array.isArray(e.sample))throw TypeError(".perftools.profiles.Profile.sample: array expected");for(n.sample=[],t=0;t<e.sample.length;++t){if("object"!=typeof e.sample[t])throw TypeError(".perftools.profiles.Profile.sample: object expected");n.sample[t]=r.perftools.profiles.Sample.fromObject(e.sample[t])}}if(e.mapping){if(!Array.isArray(e.mapping))throw TypeError(".perftools.profiles.Profile.mapping: array expected");for(n.mapping=[],t=0;t<e.mapping.length;++t){if("object"!=typeof e.mapping[t])throw TypeError(".perftools.profiles.Profile.mapping: object expected");n.mapping[t]=r.perftools.profiles.Mapping.fromObject(e.mapping[t])}}if(e.location){if(!Array.isArray(e.location))throw TypeError(".perftools.profiles.Profile.location: array expected");for(n.location=[],t=0;t<e.location.length;++t){if("object"!=typeof e.location[t])throw TypeError(".perftools.profiles.Profile.location: object expected");n.location[t]=r.perftools.profiles.Location.fromObject(e.location[t])}}if(e.function){if(!Array.isArray(e.function))throw TypeError(".perftools.profiles.Profile.function: array expected");for(n.function=[],t=0;t<e.function.length;++t){if("object"!=typeof e.function[t])throw TypeError(".perftools.profiles.Profile.function: object expected");n.function[t]=r.perftools.profiles.Function.fromObject(e.function[t])}}if(e.stringTable){if(!Array.isArray(e.stringTable))throw TypeError(".perftools.profiles.Profile.stringTable: array expected");for(n.stringTable=[],t=0;t<e.stringTable.length;++t)n.stringTable[t]=String(e.stringTable[t])}if(null!=e.dropFrames&&(o.Long?(n.dropFrames=o.Long.fromValue(e.dropFrames)).unsigned=!1:"string"==typeof e.dropFrames?n.dropFrames=parseInt(e.dropFrames,10):"number"==typeof e.dropFrames?n.dropFrames=e.dropFrames:"object"==typeof e.dropFrames&&(n.dropFrames=new o.LongBits(e.dropFrames.low>>>0,e.dropFrames.high>>>0).toNumber())),null!=e.keepFrames&&(o.Long?(n.keepFrames=o.Long.fromValue(e.keepFrames)).unsigned=!1:"string"==typeof e.keepFrames?n.keepFrames=parseInt(e.keepFrames,10):"number"==typeof e.keepFrames?n.keepFrames=e.keepFrames:"object"==typeof e.keepFrames&&(n.keepFrames=new o.LongBits(e.keepFrames.low>>>0,e.keepFrames.high>>>0).toNumber())),null!=e.timeNanos&&(o.Long?(n.timeNanos=o.Long.fromValue(e.timeNanos)).unsigned=!1:"string"==typeof e.timeNanos?n.timeNanos=parseInt(e.timeNanos,10):"number"==typeof e.timeNanos?n.timeNanos=e.timeNanos:"object"==typeof e.timeNanos&&(n.timeNanos=new o.LongBits(e.timeNanos.low>>>0,e.timeNanos.high>>>0).toNumber())),null!=e.durationNanos&&(o.Long?(n.durationNanos=o.Long.fromValue(e.durationNanos)).unsigned=!1:"string"==typeof e.durationNanos?n.durationNanos=parseInt(e.durationNanos,10):"number"==typeof e.durationNanos?n.durationNanos=e.durationNanos:"object"==typeof e.durationNanos&&(n.durationNanos=new o.LongBits(e.durationNanos.low>>>0,e.durationNanos.high>>>0).toNumber())),null!=e.periodType){if("object"!=typeof e.periodType)throw TypeError(".perftools.profiles.Profile.periodType: object expected");n.periodType=r.perftools.profiles.ValueType.fromObject(e.periodType)}if(null!=e.period&&(o.Long?(n.period=o.Long.fromValue(e.period)).unsigned=!1:"string"==typeof e.period?n.period=parseInt(e.period,10):"number"==typeof e.period?n.period=e.period:"object"==typeof e.period&&(n.period=new o.LongBits(e.period.low>>>0,e.period.high>>>0).toNumber())),e.comment){if(!Array.isArray(e.comment))throw TypeError(".perftools.profiles.Profile.comment: array expected");for(n.comment=[],t=0;t<e.comment.length;++t)o.Long?(n.comment[t]=o.Long.fromValue(e.comment[t])).unsigned=!1:"string"==typeof e.comment[t]?n.comment[t]=parseInt(e.comment[t],10):"number"==typeof e.comment[t]?n.comment[t]=e.comment[t]:"object"==typeof e.comment[t]&&(n.comment[t]=new o.LongBits(e.comment[t].low>>>0,e.comment[t].high>>>0).toNumber())}return null!=e.defaultSampleType&&(o.Long?(n.defaultSampleType=o.Long.fromValue(e.defaultSampleType)).unsigned=!1:"string"==typeof e.defaultSampleType?n.defaultSampleType=parseInt(e.defaultSampleType,10):"number"==typeof e.defaultSampleType?n.defaultSampleType=e.defaultSampleType:"object"==typeof e.defaultSampleType&&(n.defaultSampleType=new o.LongBits(e.defaultSampleType.low>>>0,e.defaultSampleType.high>>>0).toNumber())),n},i.toObject=function(e,n){n||(n={});var t={};if((n.arrays||n.defaults)&&(t.sampleType=[],t.sample=[],t.mapping=[],t.location=[],t.function=[],t.stringTable=[],t.comment=[]),n.defaults){if(o.Long){var i=new o.Long(0,0,!1);t.dropFrames=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else t.dropFrames=n.longs===String?"0":0;o.Long?(i=new o.Long(0,0,!1),t.keepFrames=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.keepFrames=n.longs===String?"0":0,o.Long?(i=new o.Long(0,0,!1),t.timeNanos=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.timeNanos=n.longs===String?"0":0,o.Long?(i=new o.Long(0,0,!1),t.durationNanos=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.durationNanos=n.longs===String?"0":0,t.periodType=null,o.Long?(i=new o.Long(0,0,!1),t.period=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.period=n.longs===String?"0":0,o.Long?(i=new o.Long(0,0,!1),t.defaultSampleType=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.defaultSampleType=n.longs===String?"0":0}if(e.sampleType&&e.sampleType.length){t.sampleType=[];for(var l=0;l<e.sampleType.length;++l)t.sampleType[l]=r.perftools.profiles.ValueType.toObject(e.sampleType[l],n)}if(e.sample&&e.sample.length)for(t.sample=[],l=0;l<e.sample.length;++l)t.sample[l]=r.perftools.profiles.Sample.toObject(e.sample[l],n);if(e.mapping&&e.mapping.length)for(t.mapping=[],l=0;l<e.mapping.length;++l)t.mapping[l]=r.perftools.profiles.Mapping.toObject(e.mapping[l],n);if(e.location&&e.location.length)for(t.location=[],l=0;l<e.location.length;++l)t.location[l]=r.perftools.profiles.Location.toObject(e.location[l],n);if(e.function&&e.function.length)for(t.function=[],l=0;l<e.function.length;++l)t.function[l]=r.perftools.profiles.Function.toObject(e.function[l],n);if(e.stringTable&&e.stringTable.length)for(t.stringTable=[],l=0;l<e.stringTable.length;++l)t.stringTable[l]=e.stringTable[l];if(null!=e.dropFrames&&e.hasOwnProperty("dropFrames")&&("number"==typeof e.dropFrames?t.dropFrames=n.longs===String?String(e.dropFrames):e.dropFrames:t.dropFrames=n.longs===String?o.Long.prototype.toString.call(e.dropFrames):n.longs===Number?new o.LongBits(e.dropFrames.low>>>0,e.dropFrames.high>>>0).toNumber():e.dropFrames),null!=e.keepFrames&&e.hasOwnProperty("keepFrames")&&("number"==typeof e.keepFrames?t.keepFrames=n.longs===String?String(e.keepFrames):e.keepFrames:t.keepFrames=n.longs===String?o.Long.prototype.toString.call(e.keepFrames):n.longs===Number?new o.LongBits(e.keepFrames.low>>>0,e.keepFrames.high>>>0).toNumber():e.keepFrames),null!=e.timeNanos&&e.hasOwnProperty("timeNanos")&&("number"==typeof e.timeNanos?t.timeNanos=n.longs===String?String(e.timeNanos):e.timeNanos:t.timeNanos=n.longs===String?o.Long.prototype.toString.call(e.timeNanos):n.longs===Number?new o.LongBits(e.timeNanos.low>>>0,e.timeNanos.high>>>0).toNumber():e.timeNanos),null!=e.durationNanos&&e.hasOwnProperty("durationNanos")&&("number"==typeof e.durationNanos?t.durationNanos=n.longs===String?String(e.durationNanos):e.durationNanos:t.durationNanos=n.longs===String?o.Long.prototype.toString.call(e.durationNanos):n.longs===Number?new o.LongBits(e.durationNanos.low>>>0,e.durationNanos.high>>>0).toNumber():e.durationNanos),null!=e.periodType&&e.hasOwnProperty("periodType")&&(t.periodType=r.perftools.profiles.ValueType.toObject(e.periodType,n)),null!=e.period&&e.hasOwnProperty("period")&&("number"==typeof e.period?t.period=n.longs===String?String(e.period):e.period:t.period=n.longs===String?o.Long.prototype.toString.call(e.period):n.longs===Number?new o.LongBits(e.period.low>>>0,e.period.high>>>0).toNumber():e.period),e.comment&&e.comment.length)for(t.comment=[],l=0;l<e.comment.length;++l)"number"==typeof e.comment[l]?t.comment[l]=n.longs===String?String(e.comment[l]):e.comment[l]:t.comment[l]=n.longs===String?o.Long.prototype.toString.call(e.comment[l]):n.longs===Number?new o.LongBits(e.comment[l].low>>>0,e.comment[l].high>>>0).toNumber():e.comment[l];return null!=e.defaultSampleType&&e.hasOwnProperty("defaultSampleType")&&("number"==typeof e.defaultSampleType?t.defaultSampleType=n.longs===String?String(e.defaultSampleType):e.defaultSampleType:t.defaultSampleType=n.longs===String?o.Long.prototype.toString.call(e.defaultSampleType):n.longs===Number?new o.LongBits(e.defaultSampleType.low>>>0,e.defaultSampleType.high>>>0).toNumber():e.defaultSampleType),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.ValueType=function(){function i(e){if(e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.type=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.unit=o.Long?o.Long.fromBits(0,0,!1):0,i.create=function(e){return new i(e)},i.encode=function(e,n){return n||(n=t.create()),null!=e.type&&e.hasOwnProperty("type")&&n.uint32(8).int64(e.type),null!=e.unit&&e.hasOwnProperty("unit")&&n.uint32(16).int64(e.unit),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.ValueType;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.type=e.int64();break;case 2:i.unit=e.int64();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.type&&e.hasOwnProperty("type")&&!(o.isInteger(e.type)||e.type&&o.isInteger(e.type.low)&&o.isInteger(e.type.high))?"type: integer|Long expected":null!=e.unit&&e.hasOwnProperty("unit")&&!(o.isInteger(e.unit)||e.unit&&o.isInteger(e.unit.low)&&o.isInteger(e.unit.high))?"unit: integer|Long expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.ValueType)return e;var n=new r.perftools.profiles.ValueType;return null!=e.type&&(o.Long?(n.type=o.Long.fromValue(e.type)).unsigned=!1:"string"==typeof e.type?n.type=parseInt(e.type,10):"number"==typeof e.type?n.type=e.type:"object"==typeof e.type&&(n.type=new o.LongBits(e.type.low>>>0,e.type.high>>>0).toNumber())),null!=e.unit&&(o.Long?(n.unit=o.Long.fromValue(e.unit)).unsigned=!1:"string"==typeof e.unit?n.unit=parseInt(e.unit,10):"number"==typeof e.unit?n.unit=e.unit:"object"==typeof e.unit&&(n.unit=new o.LongBits(e.unit.low>>>0,e.unit.high>>>0).toNumber())),n},i.toObject=function(e,n){n||(n={});var t={};if(n.defaults){if(o.Long){var r=new o.Long(0,0,!1);t.type=n.longs===String?r.toString():n.longs===Number?r.toNumber():r}else t.type=n.longs===String?"0":0;o.Long?(r=new o.Long(0,0,!1),t.unit=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.unit=n.longs===String?"0":0}return null!=e.type&&e.hasOwnProperty("type")&&("number"==typeof e.type?t.type=n.longs===String?String(e.type):e.type:t.type=n.longs===String?o.Long.prototype.toString.call(e.type):n.longs===Number?new o.LongBits(e.type.low>>>0,e.type.high>>>0).toNumber():e.type),null!=e.unit&&e.hasOwnProperty("unit")&&("number"==typeof e.unit?t.unit=n.longs===String?String(e.unit):e.unit:t.unit=n.longs===String?o.Long.prototype.toString.call(e.unit):n.longs===Number?new o.LongBits(e.unit.low>>>0,e.unit.high>>>0).toNumber():e.unit),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.Sample=function(){function i(e){if(this.locationId=[],this.value=[],this.label=[],e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.locationId=o.emptyArray,i.prototype.value=o.emptyArray,i.prototype.label=o.emptyArray,i.create=function(e){return new i(e)},i.encode=function(e,n){if(n||(n=t.create()),null!=e.locationId&&e.locationId.length){n.uint32(10).fork();for(var o=0;o<e.locationId.length;++o)n.uint64(e.locationId[o]);n.ldelim()}if(null!=e.value&&e.value.length){for(n.uint32(18).fork(),o=0;o<e.value.length;++o)n.int64(e.value[o]);n.ldelim()}if(null!=e.label&&e.label.length)for(o=0;o<e.label.length;++o)r.perftools.profiles.Label.encode(e.label[o],n.uint32(26).fork()).ldelim();return n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Sample;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:if(i.locationId&&i.locationId.length||(i.locationId=[]),2==(7&l))for(var s=e.uint32()+e.pos;e.pos<s;)i.locationId.push(e.uint64());else i.locationId.push(e.uint64());break;case 2:if(i.value&&i.value.length||(i.value=[]),2==(7&l))for(s=e.uint32()+e.pos;e.pos<s;)i.value.push(e.int64());else i.value.push(e.int64());break;case 3:i.label&&i.label.length||(i.label=[]),i.label.push(r.perftools.profiles.Label.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.locationId&&e.hasOwnProperty("locationId")){if(!Array.isArray(e.locationId))return"locationId: array expected";for(var n=0;n<e.locationId.length;++n)if(!(o.isInteger(e.locationId[n])||e.locationId[n]&&o.isInteger(e.locationId[n].low)&&o.isInteger(e.locationId[n].high)))return"locationId: integer|Long[] expected"}if(null!=e.value&&e.hasOwnProperty("value")){if(!Array.isArray(e.value))return"value: array expected";for(n=0;n<e.value.length;++n)if(!(o.isInteger(e.value[n])||e.value[n]&&o.isInteger(e.value[n].low)&&o.isInteger(e.value[n].high)))return"value: integer|Long[] expected"}if(null!=e.label&&e.hasOwnProperty("label")){if(!Array.isArray(e.label))return"label: array expected";for(n=0;n<e.label.length;++n){var t=r.perftools.profiles.Label.verify(e.label[n]);if(t)return"label."+t}}return null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Sample)return e;var n=new r.perftools.profiles.Sample;if(e.locationId){if(!Array.isArray(e.locationId))throw TypeError(".perftools.profiles.Sample.locationId: array expected");n.locationId=[];for(var t=0;t<e.locationId.length;++t)o.Long?(n.locationId[t]=o.Long.fromValue(e.locationId[t])).unsigned=!0:"string"==typeof e.locationId[t]?n.locationId[t]=parseInt(e.locationId[t],10):"number"==typeof e.locationId[t]?n.locationId[t]=e.locationId[t]:"object"==typeof e.locationId[t]&&(n.locationId[t]=new o.LongBits(e.locationId[t].low>>>0,e.locationId[t].high>>>0).toNumber(!0))}if(e.value){if(!Array.isArray(e.value))throw TypeError(".perftools.profiles.Sample.value: array expected");for(n.value=[],t=0;t<e.value.length;++t)o.Long?(n.value[t]=o.Long.fromValue(e.value[t])).unsigned=!1:"string"==typeof e.value[t]?n.value[t]=parseInt(e.value[t],10):"number"==typeof e.value[t]?n.value[t]=e.value[t]:"object"==typeof e.value[t]&&(n.value[t]=new o.LongBits(e.value[t].low>>>0,e.value[t].high>>>0).toNumber())}if(e.label){if(!Array.isArray(e.label))throw TypeError(".perftools.profiles.Sample.label: array expected");for(n.label=[],t=0;t<e.label.length;++t){if("object"!=typeof e.label[t])throw TypeError(".perftools.profiles.Sample.label: object expected");n.label[t]=r.perftools.profiles.Label.fromObject(e.label[t])}}return n},i.toObject=function(e,n){n||(n={});var t={};if((n.arrays||n.defaults)&&(t.locationId=[],t.value=[],t.label=[]),e.locationId&&e.locationId.length){t.locationId=[];for(var i=0;i<e.locationId.length;++i)"number"==typeof e.locationId[i]?t.locationId[i]=n.longs===String?String(e.locationId[i]):e.locationId[i]:t.locationId[i]=n.longs===String?o.Long.prototype.toString.call(e.locationId[i]):n.longs===Number?new o.LongBits(e.locationId[i].low>>>0,e.locationId[i].high>>>0).toNumber(!0):e.locationId[i]}if(e.value&&e.value.length)for(t.value=[],i=0;i<e.value.length;++i)"number"==typeof e.value[i]?t.value[i]=n.longs===String?String(e.value[i]):e.value[i]:t.value[i]=n.longs===String?o.Long.prototype.toString.call(e.value[i]):n.longs===Number?new o.LongBits(e.value[i].low>>>0,e.value[i].high>>>0).toNumber():e.value[i];if(e.label&&e.label.length)for(t.label=[],i=0;i<e.label.length;++i)t.label[i]=r.perftools.profiles.Label.toObject(e.label[i],n);return t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.Label=function(){function i(e){if(e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.key=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.str=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.num=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.numUnit=o.Long?o.Long.fromBits(0,0,!1):0,i.create=function(e){return new i(e)},i.encode=function(e,n){return n||(n=t.create()),null!=e.key&&e.hasOwnProperty("key")&&n.uint32(8).int64(e.key),null!=e.str&&e.hasOwnProperty("str")&&n.uint32(16).int64(e.str),null!=e.num&&e.hasOwnProperty("num")&&n.uint32(24).int64(e.num),null!=e.numUnit&&e.hasOwnProperty("numUnit")&&n.uint32(32).int64(e.numUnit),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Label;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.key=e.int64();break;case 2:i.str=e.int64();break;case 3:i.num=e.int64();break;case 4:i.numUnit=e.int64();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.key&&e.hasOwnProperty("key")&&!(o.isInteger(e.key)||e.key&&o.isInteger(e.key.low)&&o.isInteger(e.key.high))?"key: integer|Long expected":null!=e.str&&e.hasOwnProperty("str")&&!(o.isInteger(e.str)||e.str&&o.isInteger(e.str.low)&&o.isInteger(e.str.high))?"str: integer|Long expected":null!=e.num&&e.hasOwnProperty("num")&&!(o.isInteger(e.num)||e.num&&o.isInteger(e.num.low)&&o.isInteger(e.num.high))?"num: integer|Long expected":null!=e.numUnit&&e.hasOwnProperty("numUnit")&&!(o.isInteger(e.numUnit)||e.numUnit&&o.isInteger(e.numUnit.low)&&o.isInteger(e.numUnit.high))?"numUnit: integer|Long expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Label)return e;var n=new r.perftools.profiles.Label;return null!=e.key&&(o.Long?(n.key=o.Long.fromValue(e.key)).unsigned=!1:"string"==typeof e.key?n.key=parseInt(e.key,10):"number"==typeof e.key?n.key=e.key:"object"==typeof e.key&&(n.key=new o.LongBits(e.key.low>>>0,e.key.high>>>0).toNumber())),null!=e.str&&(o.Long?(n.str=o.Long.fromValue(e.str)).unsigned=!1:"string"==typeof e.str?n.str=parseInt(e.str,10):"number"==typeof e.str?n.str=e.str:"object"==typeof e.str&&(n.str=new o.LongBits(e.str.low>>>0,e.str.high>>>0).toNumber())),null!=e.num&&(o.Long?(n.num=o.Long.fromValue(e.num)).unsigned=!1:"string"==typeof e.num?n.num=parseInt(e.num,10):"number"==typeof e.num?n.num=e.num:"object"==typeof e.num&&(n.num=new o.LongBits(e.num.low>>>0,e.num.high>>>0).toNumber())),null!=e.numUnit&&(o.Long?(n.numUnit=o.Long.fromValue(e.numUnit)).unsigned=!1:"string"==typeof e.numUnit?n.numUnit=parseInt(e.numUnit,10):"number"==typeof e.numUnit?n.numUnit=e.numUnit:"object"==typeof e.numUnit&&(n.numUnit=new o.LongBits(e.numUnit.low>>>0,e.numUnit.high>>>0).toNumber())),n},i.toObject=function(e,n){n||(n={});var t={};if(n.defaults){if(o.Long){var r=new o.Long(0,0,!1);t.key=n.longs===String?r.toString():n.longs===Number?r.toNumber():r}else t.key=n.longs===String?"0":0;o.Long?(r=new o.Long(0,0,!1),t.str=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.str=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.num=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.num=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.numUnit=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.numUnit=n.longs===String?"0":0}return null!=e.key&&e.hasOwnProperty("key")&&("number"==typeof e.key?t.key=n.longs===String?String(e.key):e.key:t.key=n.longs===String?o.Long.prototype.toString.call(e.key):n.longs===Number?new o.LongBits(e.key.low>>>0,e.key.high>>>0).toNumber():e.key),null!=e.str&&e.hasOwnProperty("str")&&("number"==typeof e.str?t.str=n.longs===String?String(e.str):e.str:t.str=n.longs===String?o.Long.prototype.toString.call(e.str):n.longs===Number?new o.LongBits(e.str.low>>>0,e.str.high>>>0).toNumber():e.str),null!=e.num&&e.hasOwnProperty("num")&&("number"==typeof e.num?t.num=n.longs===String?String(e.num):e.num:t.num=n.longs===String?o.Long.prototype.toString.call(e.num):n.longs===Number?new o.LongBits(e.num.low>>>0,e.num.high>>>0).toNumber():e.num),null!=e.numUnit&&e.hasOwnProperty("numUnit")&&("number"==typeof e.numUnit?t.numUnit=n.longs===String?String(e.numUnit):e.numUnit:t.numUnit=n.longs===String?o.Long.prototype.toString.call(e.numUnit):n.longs===Number?new o.LongBits(e.numUnit.low>>>0,e.numUnit.high>>>0).toNumber():e.numUnit),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.Mapping=function(){function i(e){if(e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.id=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.memoryStart=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.memoryLimit=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.fileOffset=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.filename=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.buildId=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.hasFunctions=!1,i.prototype.hasFilenames=!1,i.prototype.hasLineNumbers=!1,i.prototype.hasInlineFrames=!1,i.create=function(e){return new i(e)},i.encode=function(e,n){return n||(n=t.create()),null!=e.id&&e.hasOwnProperty("id")&&n.uint32(8).uint64(e.id),null!=e.memoryStart&&e.hasOwnProperty("memoryStart")&&n.uint32(16).uint64(e.memoryStart),null!=e.memoryLimit&&e.hasOwnProperty("memoryLimit")&&n.uint32(24).uint64(e.memoryLimit),null!=e.fileOffset&&e.hasOwnProperty("fileOffset")&&n.uint32(32).uint64(e.fileOffset),null!=e.filename&&e.hasOwnProperty("filename")&&n.uint32(40).int64(e.filename),null!=e.buildId&&e.hasOwnProperty("buildId")&&n.uint32(48).int64(e.buildId),null!=e.hasFunctions&&e.hasOwnProperty("hasFunctions")&&n.uint32(56).bool(e.hasFunctions),null!=e.hasFilenames&&e.hasOwnProperty("hasFilenames")&&n.uint32(64).bool(e.hasFilenames),null!=e.hasLineNumbers&&e.hasOwnProperty("hasLineNumbers")&&n.uint32(72).bool(e.hasLineNumbers),null!=e.hasInlineFrames&&e.hasOwnProperty("hasInlineFrames")&&n.uint32(80).bool(e.hasInlineFrames),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Mapping;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.id=e.uint64();break;case 2:i.memoryStart=e.uint64();break;case 3:i.memoryLimit=e.uint64();break;case 4:i.fileOffset=e.uint64();break;case 5:i.filename=e.int64();break;case 6:i.buildId=e.int64();break;case 7:i.hasFunctions=e.bool();break;case 8:i.hasFilenames=e.bool();break;case 9:i.hasLineNumbers=e.bool();break;case 10:i.hasInlineFrames=e.bool();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.id&&e.hasOwnProperty("id")&&!(o.isInteger(e.id)||e.id&&o.isInteger(e.id.low)&&o.isInteger(e.id.high))?"id: integer|Long expected":null!=e.memoryStart&&e.hasOwnProperty("memoryStart")&&!(o.isInteger(e.memoryStart)||e.memoryStart&&o.isInteger(e.memoryStart.low)&&o.isInteger(e.memoryStart.high))?"memoryStart: integer|Long expected":null!=e.memoryLimit&&e.hasOwnProperty("memoryLimit")&&!(o.isInteger(e.memoryLimit)||e.memoryLimit&&o.isInteger(e.memoryLimit.low)&&o.isInteger(e.memoryLimit.high))?"memoryLimit: integer|Long expected":null!=e.fileOffset&&e.hasOwnProperty("fileOffset")&&!(o.isInteger(e.fileOffset)||e.fileOffset&&o.isInteger(e.fileOffset.low)&&o.isInteger(e.fileOffset.high))?"fileOffset: integer|Long expected":null!=e.filename&&e.hasOwnProperty("filename")&&!(o.isInteger(e.filename)||e.filename&&o.isInteger(e.filename.low)&&o.isInteger(e.filename.high))?"filename: integer|Long expected":null!=e.buildId&&e.hasOwnProperty("buildId")&&!(o.isInteger(e.buildId)||e.buildId&&o.isInteger(e.buildId.low)&&o.isInteger(e.buildId.high))?"buildId: integer|Long expected":null!=e.hasFunctions&&e.hasOwnProperty("hasFunctions")&&"boolean"!=typeof e.hasFunctions?"hasFunctions: boolean expected":null!=e.hasFilenames&&e.hasOwnProperty("hasFilenames")&&"boolean"!=typeof e.hasFilenames?"hasFilenames: boolean expected":null!=e.hasLineNumbers&&e.hasOwnProperty("hasLineNumbers")&&"boolean"!=typeof e.hasLineNumbers?"hasLineNumbers: boolean expected":null!=e.hasInlineFrames&&e.hasOwnProperty("hasInlineFrames")&&"boolean"!=typeof e.hasInlineFrames?"hasInlineFrames: boolean expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Mapping)return e;var n=new r.perftools.profiles.Mapping;return null!=e.id&&(o.Long?(n.id=o.Long.fromValue(e.id)).unsigned=!0:"string"==typeof e.id?n.id=parseInt(e.id,10):"number"==typeof e.id?n.id=e.id:"object"==typeof e.id&&(n.id=new o.LongBits(e.id.low>>>0,e.id.high>>>0).toNumber(!0))),null!=e.memoryStart&&(o.Long?(n.memoryStart=o.Long.fromValue(e.memoryStart)).unsigned=!0:"string"==typeof e.memoryStart?n.memoryStart=parseInt(e.memoryStart,10):"number"==typeof e.memoryStart?n.memoryStart=e.memoryStart:"object"==typeof e.memoryStart&&(n.memoryStart=new o.LongBits(e.memoryStart.low>>>0,e.memoryStart.high>>>0).toNumber(!0))),null!=e.memoryLimit&&(o.Long?(n.memoryLimit=o.Long.fromValue(e.memoryLimit)).unsigned=!0:"string"==typeof e.memoryLimit?n.memoryLimit=parseInt(e.memoryLimit,10):"number"==typeof e.memoryLimit?n.memoryLimit=e.memoryLimit:"object"==typeof e.memoryLimit&&(n.memoryLimit=new o.LongBits(e.memoryLimit.low>>>0,e.memoryLimit.high>>>0).toNumber(!0))),null!=e.fileOffset&&(o.Long?(n.fileOffset=o.Long.fromValue(e.fileOffset)).unsigned=!0:"string"==typeof e.fileOffset?n.fileOffset=parseInt(e.fileOffset,10):"number"==typeof e.fileOffset?n.fileOffset=e.fileOffset:"object"==typeof e.fileOffset&&(n.fileOffset=new o.LongBits(e.fileOffset.low>>>0,e.fileOffset.high>>>0).toNumber(!0))),null!=e.filename&&(o.Long?(n.filename=o.Long.fromValue(e.filename)).unsigned=!1:"string"==typeof e.filename?n.filename=parseInt(e.filename,10):"number"==typeof e.filename?n.filename=e.filename:"object"==typeof e.filename&&(n.filename=new o.LongBits(e.filename.low>>>0,e.filename.high>>>0).toNumber())),null!=e.buildId&&(o.Long?(n.buildId=o.Long.fromValue(e.buildId)).unsigned=!1:"string"==typeof e.buildId?n.buildId=parseInt(e.buildId,10):"number"==typeof e.buildId?n.buildId=e.buildId:"object"==typeof e.buildId&&(n.buildId=new o.LongBits(e.buildId.low>>>0,e.buildId.high>>>0).toNumber())),null!=e.hasFunctions&&(n.hasFunctions=Boolean(e.hasFunctions)),null!=e.hasFilenames&&(n.hasFilenames=Boolean(e.hasFilenames)),null!=e.hasLineNumbers&&(n.hasLineNumbers=Boolean(e.hasLineNumbers)),null!=e.hasInlineFrames&&(n.hasInlineFrames=Boolean(e.hasInlineFrames)),n},i.toObject=function(e,n){n||(n={});var t={};if(n.defaults){if(o.Long){var r=new o.Long(0,0,!0);t.id=n.longs===String?r.toString():n.longs===Number?r.toNumber():r}else t.id=n.longs===String?"0":0;o.Long?(r=new o.Long(0,0,!0),t.memoryStart=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.memoryStart=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!0),t.memoryLimit=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.memoryLimit=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!0),t.fileOffset=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.fileOffset=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.filename=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.filename=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.buildId=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.buildId=n.longs===String?"0":0,t.hasFunctions=!1,t.hasFilenames=!1,t.hasLineNumbers=!1,t.hasInlineFrames=!1}return null!=e.id&&e.hasOwnProperty("id")&&("number"==typeof e.id?t.id=n.longs===String?String(e.id):e.id:t.id=n.longs===String?o.Long.prototype.toString.call(e.id):n.longs===Number?new o.LongBits(e.id.low>>>0,e.id.high>>>0).toNumber(!0):e.id),null!=e.memoryStart&&e.hasOwnProperty("memoryStart")&&("number"==typeof e.memoryStart?t.memoryStart=n.longs===String?String(e.memoryStart):e.memoryStart:t.memoryStart=n.longs===String?o.Long.prototype.toString.call(e.memoryStart):n.longs===Number?new o.LongBits(e.memoryStart.low>>>0,e.memoryStart.high>>>0).toNumber(!0):e.memoryStart),null!=e.memoryLimit&&e.hasOwnProperty("memoryLimit")&&("number"==typeof e.memoryLimit?t.memoryLimit=n.longs===String?String(e.memoryLimit):e.memoryLimit:t.memoryLimit=n.longs===String?o.Long.prototype.toString.call(e.memoryLimit):n.longs===Number?new o.LongBits(e.memoryLimit.low>>>0,e.memoryLimit.high>>>0).toNumber(!0):e.memoryLimit),null!=e.fileOffset&&e.hasOwnProperty("fileOffset")&&("number"==typeof e.fileOffset?t.fileOffset=n.longs===String?String(e.fileOffset):e.fileOffset:t.fileOffset=n.longs===String?o.Long.prototype.toString.call(e.fileOffset):n.longs===Number?new o.LongBits(e.fileOffset.low>>>0,e.fileOffset.high>>>0).toNumber(!0):e.fileOffset),null!=e.filename&&e.hasOwnProperty("filename")&&("number"==typeof e.filename?t.filename=n.longs===String?String(e.filename):e.filename:t.filename=n.longs===String?o.Long.prototype.toString.call(e.filename):n.longs===Number?new o.LongBits(e.filename.low>>>0,e.filename.high>>>0).toNumber():e.filename),null!=e.buildId&&e.hasOwnProperty("buildId")&&("number"==typeof e.buildId?t.buildId=n.longs===String?String(e.buildId):e.buildId:t.buildId=n.longs===String?o.Long.prototype.toString.call(e.buildId):n.longs===Number?new o.LongBits(e.buildId.low>>>0,e.buildId.high>>>0).toNumber():e.buildId),null!=e.hasFunctions&&e.hasOwnProperty("hasFunctions")&&(t.hasFunctions=e.hasFunctions),null!=e.hasFilenames&&e.hasOwnProperty("hasFilenames")&&(t.hasFilenames=e.hasFilenames),null!=e.hasLineNumbers&&e.hasOwnProperty("hasLineNumbers")&&(t.hasLineNumbers=e.hasLineNumbers),null!=e.hasInlineFrames&&e.hasOwnProperty("hasInlineFrames")&&(t.hasInlineFrames=e.hasInlineFrames),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.Location=function(){function i(e){if(this.line=[],e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.id=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.mappingId=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.address=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.line=o.emptyArray,i.prototype.isFolded=!1,i.create=function(e){return new i(e)},i.encode=function(e,n){if(n||(n=t.create()),null!=e.id&&e.hasOwnProperty("id")&&n.uint32(8).uint64(e.id),null!=e.mappingId&&e.hasOwnProperty("mappingId")&&n.uint32(16).uint64(e.mappingId),null!=e.address&&e.hasOwnProperty("address")&&n.uint32(24).uint64(e.address),null!=e.line&&e.line.length)for(var o=0;o<e.line.length;++o)r.perftools.profiles.Line.encode(e.line[o],n.uint32(34).fork()).ldelim();return null!=e.isFolded&&e.hasOwnProperty("isFolded")&&n.uint32(40).bool(e.isFolded),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Location;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.id=e.uint64();break;case 2:i.mappingId=e.uint64();break;case 3:i.address=e.uint64();break;case 4:i.line&&i.line.length||(i.line=[]),i.line.push(r.perftools.profiles.Line.decode(e,e.uint32()));break;case 5:i.isFolded=e.bool();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.id&&e.hasOwnProperty("id")&&!(o.isInteger(e.id)||e.id&&o.isInteger(e.id.low)&&o.isInteger(e.id.high)))return"id: integer|Long expected";if(null!=e.mappingId&&e.hasOwnProperty("mappingId")&&!(o.isInteger(e.mappingId)||e.mappingId&&o.isInteger(e.mappingId.low)&&o.isInteger(e.mappingId.high)))return"mappingId: integer|Long expected";if(null!=e.address&&e.hasOwnProperty("address")&&!(o.isInteger(e.address)||e.address&&o.isInteger(e.address.low)&&o.isInteger(e.address.high)))return"address: integer|Long expected";if(null!=e.line&&e.hasOwnProperty("line")){if(!Array.isArray(e.line))return"line: array expected";for(var n=0;n<e.line.length;++n){var t=r.perftools.profiles.Line.verify(e.line[n]);if(t)return"line."+t}}return null!=e.isFolded&&e.hasOwnProperty("isFolded")&&"boolean"!=typeof e.isFolded?"isFolded: boolean expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Location)return e;var n=new r.perftools.profiles.Location;if(null!=e.id&&(o.Long?(n.id=o.Long.fromValue(e.id)).unsigned=!0:"string"==typeof e.id?n.id=parseInt(e.id,10):"number"==typeof e.id?n.id=e.id:"object"==typeof e.id&&(n.id=new o.LongBits(e.id.low>>>0,e.id.high>>>0).toNumber(!0))),null!=e.mappingId&&(o.Long?(n.mappingId=o.Long.fromValue(e.mappingId)).unsigned=!0:"string"==typeof e.mappingId?n.mappingId=parseInt(e.mappingId,10):"number"==typeof e.mappingId?n.mappingId=e.mappingId:"object"==typeof e.mappingId&&(n.mappingId=new o.LongBits(e.mappingId.low>>>0,e.mappingId.high>>>0).toNumber(!0))),null!=e.address&&(o.Long?(n.address=o.Long.fromValue(e.address)).unsigned=!0:"string"==typeof e.address?n.address=parseInt(e.address,10):"number"==typeof e.address?n.address=e.address:"object"==typeof e.address&&(n.address=new o.LongBits(e.address.low>>>0,e.address.high>>>0).toNumber(!0))),e.line){if(!Array.isArray(e.line))throw TypeError(".perftools.profiles.Location.line: array expected");n.line=[];for(var t=0;t<e.line.length;++t){if("object"!=typeof e.line[t])throw TypeError(".perftools.profiles.Location.line: object expected");n.line[t]=r.perftools.profiles.Line.fromObject(e.line[t])}}return null!=e.isFolded&&(n.isFolded=Boolean(e.isFolded)),n},i.toObject=function(e,n){n||(n={});var t={};if((n.arrays||n.defaults)&&(t.line=[]),n.defaults){if(o.Long){var i=new o.Long(0,0,!0);t.id=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else t.id=n.longs===String?"0":0;o.Long?(i=new o.Long(0,0,!0),t.mappingId=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.mappingId=n.longs===String?"0":0,o.Long?(i=new o.Long(0,0,!0),t.address=n.longs===String?i.toString():n.longs===Number?i.toNumber():i):t.address=n.longs===String?"0":0,t.isFolded=!1}if(null!=e.id&&e.hasOwnProperty("id")&&("number"==typeof e.id?t.id=n.longs===String?String(e.id):e.id:t.id=n.longs===String?o.Long.prototype.toString.call(e.id):n.longs===Number?new o.LongBits(e.id.low>>>0,e.id.high>>>0).toNumber(!0):e.id),null!=e.mappingId&&e.hasOwnProperty("mappingId")&&("number"==typeof e.mappingId?t.mappingId=n.longs===String?String(e.mappingId):e.mappingId:t.mappingId=n.longs===String?o.Long.prototype.toString.call(e.mappingId):n.longs===Number?new o.LongBits(e.mappingId.low>>>0,e.mappingId.high>>>0).toNumber(!0):e.mappingId),null!=e.address&&e.hasOwnProperty("address")&&("number"==typeof e.address?t.address=n.longs===String?String(e.address):e.address:t.address=n.longs===String?o.Long.prototype.toString.call(e.address):n.longs===Number?new o.LongBits(e.address.low>>>0,e.address.high>>>0).toNumber(!0):e.address),e.line&&e.line.length){t.line=[];for(var l=0;l<e.line.length;++l)t.line[l]=r.perftools.profiles.Line.toObject(e.line[l],n)}return null!=e.isFolded&&e.hasOwnProperty("isFolded")&&(t.isFolded=e.isFolded),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.Line=function(){function i(e){if(e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.functionId=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.line=o.Long?o.Long.fromBits(0,0,!1):0,i.create=function(e){return new i(e)},i.encode=function(e,n){return n||(n=t.create()),null!=e.functionId&&e.hasOwnProperty("functionId")&&n.uint32(8).uint64(e.functionId),null!=e.line&&e.hasOwnProperty("line")&&n.uint32(16).int64(e.line),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Line;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.functionId=e.uint64();break;case 2:i.line=e.int64();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.functionId&&e.hasOwnProperty("functionId")&&!(o.isInteger(e.functionId)||e.functionId&&o.isInteger(e.functionId.low)&&o.isInteger(e.functionId.high))?"functionId: integer|Long expected":null!=e.line&&e.hasOwnProperty("line")&&!(o.isInteger(e.line)||e.line&&o.isInteger(e.line.low)&&o.isInteger(e.line.high))?"line: integer|Long expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Line)return e;var n=new r.perftools.profiles.Line;return null!=e.functionId&&(o.Long?(n.functionId=o.Long.fromValue(e.functionId)).unsigned=!0:"string"==typeof e.functionId?n.functionId=parseInt(e.functionId,10):"number"==typeof e.functionId?n.functionId=e.functionId:"object"==typeof e.functionId&&(n.functionId=new o.LongBits(e.functionId.low>>>0,e.functionId.high>>>0).toNumber(!0))),null!=e.line&&(o.Long?(n.line=o.Long.fromValue(e.line)).unsigned=!1:"string"==typeof e.line?n.line=parseInt(e.line,10):"number"==typeof e.line?n.line=e.line:"object"==typeof e.line&&(n.line=new o.LongBits(e.line.low>>>0,e.line.high>>>0).toNumber())),n},i.toObject=function(e,n){n||(n={});var t={};if(n.defaults){if(o.Long){var r=new o.Long(0,0,!0);t.functionId=n.longs===String?r.toString():n.longs===Number?r.toNumber():r}else t.functionId=n.longs===String?"0":0;o.Long?(r=new o.Long(0,0,!1),t.line=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.line=n.longs===String?"0":0}return null!=e.functionId&&e.hasOwnProperty("functionId")&&("number"==typeof e.functionId?t.functionId=n.longs===String?String(e.functionId):e.functionId:t.functionId=n.longs===String?o.Long.prototype.toString.call(e.functionId):n.longs===Number?new o.LongBits(e.functionId.low>>>0,e.functionId.high>>>0).toNumber(!0):e.functionId),null!=e.line&&e.hasOwnProperty("line")&&("number"==typeof e.line?t.line=n.longs===String?String(e.line):e.line:t.line=n.longs===String?o.Long.prototype.toString.call(e.line):n.longs===Number?new o.LongBits(e.line.low>>>0,e.line.high>>>0).toNumber():e.line),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i.Function=function(){function i(e){if(e)for(var n=Object.keys(e),t=0;t<n.length;++t)null!=e[n[t]]&&(this[n[t]]=e[n[t]])}return i.prototype.id=o.Long?o.Long.fromBits(0,0,!0):0,i.prototype.name=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.systemName=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.filename=o.Long?o.Long.fromBits(0,0,!1):0,i.prototype.startLine=o.Long?o.Long.fromBits(0,0,!1):0,i.create=function(e){return new i(e)},i.encode=function(e,n){return n||(n=t.create()),null!=e.id&&e.hasOwnProperty("id")&&n.uint32(8).uint64(e.id),null!=e.name&&e.hasOwnProperty("name")&&n.uint32(16).int64(e.name),null!=e.systemName&&e.hasOwnProperty("systemName")&&n.uint32(24).int64(e.systemName),null!=e.filename&&e.hasOwnProperty("filename")&&n.uint32(32).int64(e.filename),null!=e.startLine&&e.hasOwnProperty("startLine")&&n.uint32(40).int64(e.startLine),n},i.encodeDelimited=function(e,n){return this.encode(e,n).ldelim()},i.decode=function(e,t){e instanceof n||(e=n.create(e));for(var o=void 0===t?e.len:e.pos+t,i=new r.perftools.profiles.Function;e.pos<o;){var l=e.uint32();switch(l>>>3){case 1:i.id=e.uint64();break;case 2:i.name=e.int64();break;case 3:i.systemName=e.int64();break;case 4:i.filename=e.int64();break;case 5:i.startLine=e.int64();break;default:e.skipType(7&l)}}return i},i.decodeDelimited=function(e){return e instanceof n||(e=new n(e)),this.decode(e,e.uint32())},i.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.id&&e.hasOwnProperty("id")&&!(o.isInteger(e.id)||e.id&&o.isInteger(e.id.low)&&o.isInteger(e.id.high))?"id: integer|Long expected":null!=e.name&&e.hasOwnProperty("name")&&!(o.isInteger(e.name)||e.name&&o.isInteger(e.name.low)&&o.isInteger(e.name.high))?"name: integer|Long expected":null!=e.systemName&&e.hasOwnProperty("systemName")&&!(o.isInteger(e.systemName)||e.systemName&&o.isInteger(e.systemName.low)&&o.isInteger(e.systemName.high))?"systemName: integer|Long expected":null!=e.filename&&e.hasOwnProperty("filename")&&!(o.isInteger(e.filename)||e.filename&&o.isInteger(e.filename.low)&&o.isInteger(e.filename.high))?"filename: integer|Long expected":null!=e.startLine&&e.hasOwnProperty("startLine")&&!(o.isInteger(e.startLine)||e.startLine&&o.isInteger(e.startLine.low)&&o.isInteger(e.startLine.high))?"startLine: integer|Long expected":null},i.fromObject=function(e){if(e instanceof r.perftools.profiles.Function)return e;var n=new r.perftools.profiles.Function;return null!=e.id&&(o.Long?(n.id=o.Long.fromValue(e.id)).unsigned=!0:"string"==typeof e.id?n.id=parseInt(e.id,10):"number"==typeof e.id?n.id=e.id:"object"==typeof e.id&&(n.id=new o.LongBits(e.id.low>>>0,e.id.high>>>0).toNumber(!0))),null!=e.name&&(o.Long?(n.name=o.Long.fromValue(e.name)).unsigned=!1:"string"==typeof e.name?n.name=parseInt(e.name,10):"number"==typeof e.name?n.name=e.name:"object"==typeof e.name&&(n.name=new o.LongBits(e.name.low>>>0,e.name.high>>>0).toNumber())),null!=e.systemName&&(o.Long?(n.systemName=o.Long.fromValue(e.systemName)).unsigned=!1:"string"==typeof e.systemName?n.systemName=parseInt(e.systemName,10):"number"==typeof e.systemName?n.systemName=e.systemName:"object"==typeof e.systemName&&(n.systemName=new o.LongBits(e.systemName.low>>>0,e.systemName.high>>>0).toNumber())),null!=e.filename&&(o.Long?(n.filename=o.Long.fromValue(e.filename)).unsigned=!1:"string"==typeof e.filename?n.filename=parseInt(e.filename,10):"number"==typeof e.filename?n.filename=e.filename:"object"==typeof e.filename&&(n.filename=new o.LongBits(e.filename.low>>>0,e.filename.high>>>0).toNumber())),null!=e.startLine&&(o.Long?(n.startLine=o.Long.fromValue(e.startLine)).unsigned=!1:"string"==typeof e.startLine?n.startLine=parseInt(e.startLine,10):"number"==typeof e.startLine?n.startLine=e.startLine:"object"==typeof e.startLine&&(n.startLine=new o.LongBits(e.startLine.low>>>0,e.startLine.high>>>0).toNumber())),n},i.toObject=function(e,n){n||(n={});var t={};if(n.defaults){if(o.Long){var r=new o.Long(0,0,!0);t.id=n.longs===String?r.toString():n.longs===Number?r.toNumber():r}else t.id=n.longs===String?"0":0;o.Long?(r=new o.Long(0,0,!1),t.name=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.name=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.systemName=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.systemName=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.filename=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.filename=n.longs===String?"0":0,o.Long?(r=new o.Long(0,0,!1),t.startLine=n.longs===String?r.toString():n.longs===Number?r.toNumber():r):t.startLine=n.longs===String?"0":0}return null!=e.id&&e.hasOwnProperty("id")&&("number"==typeof e.id?t.id=n.longs===String?String(e.id):e.id:t.id=n.longs===String?o.Long.prototype.toString.call(e.id):n.longs===Number?new o.LongBits(e.id.low>>>0,e.id.high>>>0).toNumber(!0):e.id),null!=e.name&&e.hasOwnProperty("name")&&("number"==typeof e.name?t.name=n.longs===String?String(e.name):e.name:t.name=n.longs===String?o.Long.prototype.toString.call(e.name):n.longs===Number?new o.LongBits(e.name.low>>>0,e.name.high>>>0).toNumber():e.name),null!=e.systemName&&e.hasOwnProperty("systemName")&&("number"==typeof e.systemName?t.systemName=n.longs===String?String(e.systemName):e.systemName:t.systemName=n.longs===String?o.Long.prototype.toString.call(e.systemName):n.longs===Number?new o.LongBits(e.systemName.low>>>0,e.systemName.high>>>0).toNumber():e.systemName),null!=e.filename&&e.hasOwnProperty("filename")&&("number"==typeof e.filename?t.filename=n.longs===String?String(e.filename):e.filename:t.filename=n.longs===String?o.Long.prototype.toString.call(e.filename):n.longs===Number?new o.LongBits(e.filename.low>>>0,e.filename.high>>>0).toNumber():e.filename),null!=e.startLine&&e.hasOwnProperty("startLine")&&("number"==typeof e.startLine?t.startLine=n.longs===String?String(e.startLine):e.startLine:t.startLine=n.longs===String?o.Long.prototype.toString.call(e.startLine):n.longs===Number?new o.LongBits(e.startLine.low>>>0,e.startLine.high>>>0).toNumber():e.startLine),t},i.prototype.toJSON=function(){return this.constructor.toObject(this,e.util.toJSONOptions)},i}(),i),l}(),module.exports=r;
},{"protobufjs/minimal":186}],155:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importAsPprofProfile=r;var e=require("./profile.proto.js"),n=require("../lib/profile"),t=require("../lib/utils"),l=require("../lib/value-formatters");function r(r){if(0===r.byteLength)return null;let o;try{o=e.perftools.profiles.Profile.decode(new Uint8Array(r))}catch(e){return null}function i(e){return"number"==typeof e?e:e.low}function u(e){return o.stringTable[i(e)]||null}const s=new Map;function a(e){const{name:n,filename:t,startLine:l}=e,r=null!=n&&u(n)||"(unknown)",o=null!=t?u(t):null,i=null!=l?+l:null,s={key:`${r}:${o}:${i}`,name:r};return null!=o&&(s.file=o),null!=i&&(s.line=i),s}for(let e of o.function)if(e.id){const n=a(e);null!=n&&s.set(i(e.id),n)}function c(e){const{line:n}=e;if(null==n)return null;const l=(0,t.lastOf)(n);return null==l?null:l.functionId&&s.get(i(l.functionId))||null}const f=new Map;for(let e of o.location)if(null!=e.id){const n=c(e);n&&f.set(i(e.id),n)}const p=o.sampleType.map(e=>({type:e.type&&u(e.type)||"samples",unit:e.unit&&u(e.unit)||"count"})),d=o.defaultSampleType?+o.defaultSampleType:p.length-1,m=p[d],y=new n.StackListProfileBuilder;switch(m.unit){case"nanoseconds":case"microseconds":case"milliseconds":case"seconds":y.setValueFormatter(new l.TimeFormatter(m.unit));break;case"bytes":y.setValueFormatter(new l.ByteFormatter)}for(let e of o.sample){const n=e.locationId?e.locationId.map(e=>f.get(i(e))):[];n.reverse();const t=e.value[d];y.appendSampleWithWeight(n.filter(e=>null!=e),+t)}return y.build()}
},{"./profile.proto.js":174,"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140}],156:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importFromChromeHeapProfile=o;var e=require("../lib/profile"),r=require("../lib/utils"),t=require("../lib/value-formatters");const n=new Map;function i(e){return(0,r.getOrInsert)(n,e,e=>{const r=e.functionName||"(anonymous)",t=e.url,n=e.lineNumber,i=e.columnNumber;return{key:`${r}:${t}:${n}:${i}`,name:r,file:t,line:n,col:i}})}function o(r){const n=new Map;let o=0;const l=(e,r)=>{e.id=o++,n.set(e.id,e),r&&(e.parent=r.id),e.children.forEach(r=>l(r,e))};l(r.head);const u=e=>{if(0===e.children.length)return e.selfSize||0;const r=e.children.reduce((e,r)=>e+=u(r),e.selfSize);return e.totalSize=r,r},a=u(r.head),s=[];for(let e of n.values()){let r=[];for(r.push(e);void 0!==e.parent;){const t=n.get(e.parent);if(void 0===t)break;r.unshift(t),e=t}s.push(r)}const c=new e.StackListProfileBuilder(a);for(let e of s){const r=e[e.length-1];c.appendSampleWithWeight(e.map(e=>i(e.callFrame)),r.selfSize)}return c.setValueFormatter(new t.ByteFormatter),c.build()}
},{"../lib/profile":139,"../lib/utils":70,"../lib/value-formatters":140}],157:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isTraceEventFormatted=l,exports.importTraceEvents=p;var e=require("../lib/utils"),t=require("../lib/profile"),r=require("../lib/value-formatters");function n(e){const t=[];for(let r of e)switch(r.ph){case"B":case"E":case"X":t.push(r)}return t}function i(e){const t=[];for(let r of e)switch(r.ph){case"B":case"E":t.push(r);break;case"X":let e=null;if(null!=r.dur?e=r.dur:null!=r.tdur&&(e=r.tdur),null==e){console.warn("Found a complete event (X) with no duration. Skipping: ",r);continue}t.push(Object.assign({},r,{ph:"B"})),t.push(Object.assign({},r,{ph:"E",ts:r.ts+e}));break;default:return r}return t}function s(e){const t=new Map;for(let r of e)"M"===r.ph&&"process_name"===r.name&&r.args&&r.args.name&&t.set(r.pid,r.args.name);return t}function a(e){const t=new Map;for(let r of e)if("M"===r.ph&&"thread_name"===r.name&&r.args&&r.args.name){const e=`${r.pid}:${r.tid}`;t.set(e,r.args.name)}return t}function u(e){let t=`${e.name||"(unnamed)"}`;return e.args&&(t+=` ${JSON.stringify(e.args)}`),t}function o(o){const c=new Map,f=i(n(o)),l=s(o),p=a(o);if(f.sort((e,t)=>{if(e.ts<t.ts)return-1;if(e.ts>t.ts)return 1;if(e.pid<t.pid)return-1;if(e.pid>t.pid)return 1;if(e.tid<t.tid)return-1;if(e.tid>t.tid)return 1;if(u(e)===u(t)){if("B"===e.ph&&"E"===t.ph)return-1;if("E"===e.ph&&"B"===t.ph)return 1}else{if("B"===e.ph&&"E"===t.ph)return 1;if("E"===e.ph&&"B"===t.ph)return-1}return 0}),f.length>0){const e=f[0].ts;for(let t of f)t.ts-=e}function d(n,i){const s=`${(0,e.zeroPad)(""+n,10)}:${(0,e.zeroPad)(""+i,10)}`;let a=c.get(s);if(null!=a)return a;let u=new t.CallTreeProfileBuilder;a={profile:u,eventStack:[]},u.setValueFormatter(new r.TimeFormatter("microseconds")),c.set(s,a);const o=l.get(n),f=p.get(`${n}:${i}`);return null!=o&&null!=f?u.setName(`${o} (pid ${n}), ${f} (tid ${i})`):null!=o?u.setName(`${o} (pid ${n}, tid ${i})`):null!=f?u.setName(`${f} (pid ${n}, tid ${i})`):u.setName(`pid ${n}, tid ${i}`),a}for(let t of f){const{profile:r,eventStack:n}=d(t.pid,t.tid),i=u(t),s={key:i,name:i};switch(t.ph){case"B":n.push(t),r.enterFrame(s,t.ts);break;case"E":const i=(0,e.lastOf)(n);null!=i&&i.name===t.name?(r.leaveFrame(s,t.ts),n.pop()):console.warn("Event discarded because it did not match top-of-stack. Discarded event:",t,"Top of stack:",i);break;default:return t}}const h=Array.from(c.entries());return(0,e.sortBy)(h,e=>e[0]),{name:"",indexToView:0,profiles:h.map(e=>e[1].profile)}}function c(e){if(!Array.isArray(e))return!1;if(0===e.length)return!1;for(let t of e){if(!("ph"in t))return!1;switch(t.ph){case"B":case"E":case"X":if(!("ts"in t))return!1}}return!0}function f(e){return"traceEvents"in e&&c(e.traceEvents)}function l(e){return f(e)||c(e)}function p(e){if(f(e))return o(e.traceEvents);if(c(e))return o(e);return e}
},{"../lib/utils":70,"../lib/profile":139,"../lib/value-formatters":140}],104:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.importProfileGroupFromText=g,exports.importProfileGroupFromBase64=h,exports.importProfilesFromFile=F,exports.importProfilesFromArrayBuffer=y,exports.importFromFileSystemDirectoryEntry=C;var e=require("./chrome"),r=require("./stackprof"),o=require("./instruments"),t=require("./bg-flamegraph"),i=require("./firefox"),n=require("../lib/file-format"),s=require("./v8proflog"),p=require("./linux-tools-perf"),l=require("./haskell"),m=require("./utils"),a=require("./pprof"),f=require("../lib/utils"),u=require("./v8heapalloc"),c=require("./trace-event"),d=function(e,r,o,t){return new(o||(o=Promise))(function(i,n){function s(e){try{l(t.next(e))}catch(e){n(e)}}function p(e){try{l(t.throw(e))}catch(e){n(e)}}function l(e){e.done?i(e.value):new o(function(r){r(e.value)}).then(s,p)}l((t=t.apply(e,r||[])).next())})};function g(e,r){return d(this,void 0,void 0,function*(){return yield P(new m.TextProfileDataSource(e,r))})}function h(e,r){return d(this,void 0,void 0,function*(){return yield P(m.MaybeCompressedDataReader.fromArrayBuffer(e,(0,f.decodeBase64)(r).buffer))})}function F(e){return d(this,void 0,void 0,function*(){return P(m.MaybeCompressedDataReader.fromFile(e))})}function y(e,r){return d(this,void 0,void 0,function*(){return P(m.MaybeCompressedDataReader.fromArrayBuffer(e,r))})}function P(e){return d(this,void 0,void 0,function*(){const r=yield e.name(),o=yield I(e);if(o){o.name||(o.name=r);for(let e of o.profiles)e&&!e.getName()&&e.setName(r);return o}return null})}function v(e){return e?{name:e.getName(),indexToView:0,profiles:[e]}:null}function x(e){return"["===(e=e.trim())[0]&&"]"!==(e=e.replace(/,\s*$/,""))[e.length-1]&&(e+="]"),e}function I(m){return d(this,void 0,void 0,function*(){const f=yield m.name(),d=yield m.readAsArrayBuffer();{const e=(0,a.importAsPprofProfile)(d);if(e)return console.log("Importing as protobuf encoded pprof file"),v(e)}const g=yield m.readAsText();if(f.endsWith(".speedscope.json"))return console.log("Importing as speedscope json file"),(0,n.importSpeedscopeProfiles)(JSON.parse(g));if(f.endsWith(".chrome.json")||/Profile-\d{8}T\d{6}/.exec(f))return console.log("Importing as Chrome Timeline"),(0,e.importFromChromeTimeline)(JSON.parse(g),f);if(f.endsWith(".stackprof.json"))return console.log("Importing as stackprof profile"),v((0,r.importFromStackprof)(JSON.parse(g)));if(f.endsWith(".instruments.txt"))return console.log("Importing as Instruments.app deep copy"),v((0,o.importFromInstrumentsDeepCopy)(g));if(f.endsWith(".linux-perf.txt"))return console.log("Importing as output of linux perf script"),(0,p.importFromLinuxPerf)(g);if(f.endsWith(".collapsedstack.txt"))return console.log("Importing as collapsed stack format"),v((0,t.importFromBGFlameGraph)(g));if(f.endsWith(".v8log.json"))return console.log("Importing as --prof-process v8 log"),v((0,s.importFromV8ProfLog)(JSON.parse(g)));if(f.endsWith(".heapprofile"))return console.log("Importing as Chrome Heap Profile"),v((0,u.importFromChromeHeapProfile)(JSON.parse(g)));let h;try{h=JSON.parse(x(g))}catch(e){}if(h){if("https://www.speedscope.app/file-format-schema.json"===h.$schema)return console.log("Importing as speedscope json file"),(0,n.importSpeedscopeProfiles)(JSON.parse(g));if(h.systemHost&&"Firefox"==h.systemHost.name)return console.log("Importing as Firefox profile"),v((0,i.importFromFirefox)(h));if((0,e.isChromeTimeline)(h))return console.log("Importing as Chrome Timeline"),(0,e.importFromChromeTimeline)(h,f);if("nodes"in h&&"samples"in h&&"timeDeltas"in h)return console.log("Importing as Chrome CPU Profile"),v((0,e.importFromChromeCPUProfile)(h));if((0,c.isTraceEventFormatted)(h))return console.log("Importing as Trace Event Format profile"),(0,c.importTraceEvents)(h);if("head"in h&&"samples"in h&&"timestamps"in h)return console.log("Importing as Chrome CPU Profile (old format)"),v((0,e.importFromOldV8CPUProfile)(h));if("mode"in h&&"frames"in h&&"raw_timestamp_deltas"in h)return console.log("Importing as stackprof profile"),v((0,r.importFromStackprof)(h));if("code"in h&&"functions"in h&&"ticks"in h)return console.log("Importing as --prof-process v8 log"),v((0,s.importFromV8ProfLog)(h));if("head"in h&&"selfSize"in h.head)return console.log("Importing as Chrome Heap Profile"),v((0,u.importFromChromeHeapProfile)(JSON.parse(g)));if("rts_arguments"in h&&"initial_capabilities"in h)return console.log("Importing as Haskell GHC JSON Profile"),(0,l.importFromHaskell)(h)}else{if(/^[\w \t\(\)]*\tSymbol Name/.exec(g))return console.log("Importing as Instruments.app deep copy"),v((0,o.importFromInstrumentsDeepCopy)(g));const e=g.split(/\n/).length;if(e>=1&&e===g.split(/ \d+\r?\n/).length)return console.log("Importing as collapsed stack format"),v((0,t.importFromBGFlameGraph)(g));const r=(0,p.importFromLinuxPerf)(g);if(r)return console.log("Importing from linux perf script output"),r}return null})}function C(e){return d(this,void 0,void 0,function*(){return(0,o.importFromInstrumentsTrace)(e)})}
},{"./chrome":146,"./stackprof":147,"./instruments":148,"./bg-flamegraph":149,"./firefox":150,"../lib/file-format":83,"./v8proflog":151,"./linux-tools-perf":152,"./haskell":153,"./utils":154,"./pprof":155,"../lib/utils":70,"./v8heapalloc":156,"./trace-event":157}]},{},[104], null)
//# sourceMappingURL=import.a03c2bef.map
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/public/speedscope-1.5.3/index.html
|
HTML
|
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>speedscope</title> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet"> <script></script> <link rel="stylesheet" href="reset.7ae984ff.css"> <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.1165a94e.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.361d2b26.png"> </head> <body> <script src="speedscope.75eb7d8e.js"></script> </body> </html>
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/public/speedscope-1.5.3/reset.7ae984ff.css
|
CSS
|
a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,nav,object,ol,output,p,pre,q,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:after,blockquote:before,q:after,q:before{content:"";content:none}table{border-collapse:collapse;border-spacing:0}html{overflow:hidden}body,html{height:100%}body{overflow:auto}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/public/speedscope-1.5.3/speedscope.75eb7d8e.js
|
JavaScript
|
parcelRequire=function(e,r,n,t){var i="function"==typeof parcelRequire&&parcelRequire,o="function"==typeof require&&require;function u(n,t){if(!r[n]){if(!e[n]){var f="function"==typeof parcelRequire&&parcelRequire;if(!t&&f)return f(n,!0);if(i)return i(n,!0);if(o&&"string"==typeof n)return o(n);var c=new Error("Cannot find module '"+n+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[n][1][r]||r};var l=r[n]=new u.Module(n);e[n][0].call(l.exports,p,l,l.exports,this)}return r[n].exports;function p(e){return u(p.resolve(e))}}u.isParcelRequire=!0,u.Module=function(e){this.id=e,this.bundle=u,this.exports={}},u.modules=e,u.cache=r,u.parent=i,u.register=function(r,n){e[r]=[function(e,r){r.exports=n},{}]};for(var f=0;f<n.length;f++)u(n[f]);if(n.length){var c=u(n[n.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=c:"function"==typeof define&&define.amd?define(function(){return c}):t&&(this[t]=c)}return u}({24:[function(require,module,exports) {
"use strict";function e(){}Object.defineProperty(exports,"__esModule",{value:!0});var t={},n=[],o=[];function r(r,i){var l,a,p,s,c=o;for(s=arguments.length;s-- >2;)n.push(arguments[s]);for(i&&null!=i.children&&(n.length||n.push(i.children),delete i.children);n.length;)if((a=n.pop())&&void 0!==a.pop)for(s=a.length;s--;)n.push(a[s]);else"boolean"==typeof a&&(a=null),(p="function"!=typeof r)&&(null==a?a="":"number"==typeof a?a=String(a):"string"!=typeof a&&(p=!1)),p&&l?c[c.length-1]+=a:c===o?c=[a]:c.push(a),l=p;var u=new e;return u.nodeName=r,u.children=c,u.attributes=null==i?void 0:i,u.key=null==i?void 0:i.key,void 0!==t.vnode&&t.vnode(u),u}function i(e,t){for(var n in t)e[n]=t[n];return e}var l="function"==typeof Promise?Promise.resolve().then.bind(Promise.resolve()):setTimeout;function a(e,t){return r(e.nodeName,i(i({},e.attributes),t),arguments.length>2?[].slice.call(arguments,2):e.children)}var p=/acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i,s=[];function c(e){!e._dirty&&(e._dirty=!0)&&1==s.push(e)&&(t.debounceRendering||l)(u)}function u(){var e,t=s;for(s=[];e=t.pop();)e._dirty&&A(e)}function f(e,t,n){return"string"==typeof t||"number"==typeof t?void 0!==e.splitText:"string"==typeof t.nodeName?!e._componentConstructor&&d(e,t.nodeName):n||e._componentConstructor===t.nodeName}function d(e,t){return e.normalizedNodeName===t||e.nodeName.toLowerCase()===t.toLowerCase()}function _(e){var t=i({},e.attributes);t.children=e.children;var n=e.nodeName.defaultProps;if(void 0!==n)for(var o in n)void 0===t[o]&&(t[o]=n[o]);return t}function v(e,t){var n=t?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e);return n.normalizedNodeName=e,n}function m(e){var t=e.parentNode;t&&t.removeChild(e)}function h(e,t,n,o,r){if("className"===t&&(t="class"),"key"===t);else if("ref"===t)n&&n(null),o&&o(e);else if("class"!==t||r)if("style"===t){if(o&&"string"!=typeof o&&"string"!=typeof n||(e.style.cssText=o||""),o&&"object"==typeof o){if("string"!=typeof n)for(var i in n)i in o||(e.style[i]="");for(var i in o)e.style[i]="number"==typeof o[i]&&!1===p.test(i)?o[i]+"px":o[i]}}else if("dangerouslySetInnerHTML"===t)o&&(e.innerHTML=o.__html||"");else if("o"==t[0]&&"n"==t[1]){var l=t!==(t=t.replace(/Capture$/,""));t=t.toLowerCase().substring(2),o?n||e.addEventListener(t,y,l):e.removeEventListener(t,y,l),(e._listeners||(e._listeners={}))[t]=o}else if("list"!==t&&"type"!==t&&!r&&t in e)b(e,t,null==o?"":o),null!=o&&!1!==o||e.removeAttribute(t);else{var a=r&&t!==(t=t.replace(/^xlink\:?/,""));null==o||!1===o?a?e.removeAttributeNS("http://www.w3.org/1999/xlink",t.toLowerCase()):e.removeAttribute(t):"function"!=typeof o&&(a?e.setAttributeNS("http://www.w3.org/1999/xlink",t.toLowerCase(),o):e.setAttribute(t,o))}else e.className=o||""}function b(e,t,n){try{e[t]=n}catch(e){}}function y(e){return this._listeners[e.type](t.event&&t.event(e)||e)}var x=[],C=0,g=!1,N=!1;function k(){for(var e;e=x.pop();)t.afterMount&&t.afterMount(e),e.componentDidMount&&e.componentDidMount()}function w(e,t,n,o,r,i){C++||(g=null!=r&&void 0!==r.ownerSVGElement,N=null!=e&&!("__preactattr_"in e));var l=S(e,t,n,o,i);return r&&l.parentNode!==r&&r.appendChild(l),--C||(N=!1,i||k()),l}function S(e,t,n,o,r){var i=e,l=g;if(null!=t&&"boolean"!=typeof t||(t=""),"string"==typeof t||"number"==typeof t)return e&&void 0!==e.splitText&&e.parentNode&&(!e._component||r)?e.nodeValue!=t&&(e.nodeValue=t):(i=document.createTextNode(t),e&&(e.parentNode&&e.parentNode.replaceChild(i,e),L(e,!0))),i.__preactattr_=!0,i;var a=t.nodeName;if("function"==typeof a)return D(e,t,n,o);if(g="svg"===a||"foreignObject"!==a&&g,a=String(a),(!e||!d(e,a))&&(i=v(a,g),e)){for(;e.firstChild;)i.appendChild(e.firstChild);e.parentNode&&e.parentNode.replaceChild(i,e),L(e,!0)}var p=i.firstChild,s=i.__preactattr_,c=t.children;if(null==s){s=i.__preactattr_={};for(var u=i.attributes,f=u.length;f--;)s[u[f].name]=u[f].value}return!N&&c&&1===c.length&&"string"==typeof c[0]&&null!=p&&void 0!==p.splitText&&null==p.nextSibling?p.nodeValue!=c[0]&&(p.nodeValue=c[0]):(c&&c.length||null!=p)&&U(i,c,n,o,N||null!=s.dangerouslySetInnerHTML),P(i,t.attributes,s),g=l,i}function U(e,t,n,o,r){var i,l,a,p,s,c=e.childNodes,u=[],d={},_=0,v=0,h=c.length,b=0,y=t?t.length:0;if(0!==h)for(var x=0;x<h;x++){var C=c[x],g=C.__preactattr_;null!=(N=y&&g?C._component?C._component.__key:g.key:null)?(_++,d[N]=C):(g||(void 0!==C.splitText?!r||C.nodeValue.trim():r))&&(u[b++]=C)}if(0!==y)for(x=0;x<y;x++){var N;if(s=null,null!=(N=(p=t[x]).key))_&&void 0!==d[N]&&(s=d[N],d[N]=void 0,_--);else if(!s&&v<b)for(i=v;i<b;i++)if(void 0!==u[i]&&f(l=u[i],p,r)){s=l,u[i]=void 0,i===b-1&&b--,i===v&&v++;break}s=S(s,p,n,o),a=c[x],s&&s!==e&&s!==a&&(null==a?e.appendChild(s):s===a.nextSibling?m(a):e.insertBefore(s,a))}if(_)for(var x in d)void 0!==d[x]&&L(d[x],!1);for(;v<=b;)void 0!==(s=u[b--])&&L(s,!1)}function L(e,t){var n=e._component;n?H(n):(null!=e.__preactattr_&&e.__preactattr_.ref&&e.__preactattr_.ref(null),!1!==t&&null!=e.__preactattr_||m(e),M(e))}function M(e){for(e=e.lastChild;e;){var t=e.previousSibling;L(e,!0),e=t}}function P(e,t,n){var o;for(o in n)t&&null!=t[o]||null==n[o]||h(e,o,n[o],n[o]=void 0,g);for(o in t)"children"===o||"innerHTML"===o||o in n&&t[o]===("value"===o||"checked"===o?e[o]:n[o])||h(e,o,n[o],n[o]=t[o],g)}var T={};function B(e){var t=e.constructor.name;(T[t]||(T[t]=[])).push(e)}function E(e,t,n){var o,r=T[e.name];if(e.prototype&&e.prototype.render?(o=new e(t,n),j.call(o,t,n)):((o=new j(t,n)).constructor=e,o.render=W),r)for(var i=r.length;i--;)if(r[i].constructor===e){o.nextBase=r[i].nextBase,r.splice(i,1);break}return o}function W(e,t,n){return this.constructor(e,n)}function V(e,n,o,r,i){e._disable||(e._disable=!0,(e.__ref=n.ref)&&delete n.ref,(e.__key=n.key)&&delete n.key,!e.base||i?e.componentWillMount&&e.componentWillMount():e.componentWillReceiveProps&&e.componentWillReceiveProps(n,r),r&&r!==e.context&&(e.prevContext||(e.prevContext=e.context),e.context=r),e.prevProps||(e.prevProps=e.props),e.props=n,e._disable=!1,0!==o&&(1!==o&&!1===t.syncComponentUpdates&&e.base?c(e):A(e,1,i)),e.__ref&&e.__ref(e))}function A(e,n,o,r){if(!e._disable){var l,a,p,s=e.props,c=e.state,u=e.context,f=e.prevProps||s,d=e.prevState||c,v=e.prevContext||u,m=e.base,h=e.nextBase,b=m||h,y=e._component,g=!1;if(m&&(e.props=f,e.state=d,e.context=v,2!==n&&e.shouldComponentUpdate&&!1===e.shouldComponentUpdate(s,c,u)?g=!0:e.componentWillUpdate&&e.componentWillUpdate(s,c,u),e.props=s,e.state=c,e.context=u),e.prevProps=e.prevState=e.prevContext=e.nextBase=null,e._dirty=!1,!g){l=e.render(s,c,u),e.getChildContext&&(u=i(i({},u),e.getChildContext()));var N,S,U=l&&l.nodeName;if("function"==typeof U){var M=_(l);(a=y)&&a.constructor===U&&M.key==a.__key?V(a,M,1,u,!1):(N=a,e._component=a=E(U,M,u),a.nextBase=a.nextBase||h,a._parentComponent=e,V(a,M,0,u,!1),A(a,1,o,!0)),S=a.base}else p=b,(N=y)&&(p=e._component=null),(b||1===n)&&(p&&(p._component=null),S=w(p,l,u,o||!m,b&&b.parentNode,!0));if(b&&S!==b&&a!==y){var P=b.parentNode;P&&S!==P&&(P.replaceChild(S,b),N||(b._component=null,L(b,!1)))}if(N&&H(N),e.base=S,S&&!r){for(var T=e,B=e;B=B._parentComponent;)(T=B).base=S;S._component=T,S._componentConstructor=T.constructor}}if(!m||o?x.unshift(e):g||(e.componentDidUpdate&&e.componentDidUpdate(f,d,v),t.afterUpdate&&t.afterUpdate(e)),null!=e._renderCallbacks)for(;e._renderCallbacks.length;)e._renderCallbacks.pop().call(e);C||r||k()}}function D(e,t,n,o){for(var r=e&&e._component,i=r,l=e,a=r&&e._componentConstructor===t.nodeName,p=a,s=_(t);r&&!p&&(r=r._parentComponent);)p=r.constructor===t.nodeName;return r&&p&&(!o||r._component)?(V(r,s,3,n,o),e=r.base):(i&&!a&&(H(i),e=l=null),r=E(t.nodeName,s,n),e&&!r.nextBase&&(r.nextBase=e,l=null),V(r,s,1,n,o),e=r.base,l&&e!==l&&(l._component=null,L(l,!1))),e}function H(e){t.beforeUnmount&&t.beforeUnmount(e);var n=e.base;e._disable=!0,e.componentWillUnmount&&e.componentWillUnmount(),e.base=null;var o=e._component;o?H(o):n&&(n.__preactattr_&&n.__preactattr_.ref&&n.__preactattr_.ref(null),e.nextBase=n,m(n),B(e),M(n)),e.__ref&&e.__ref(null)}function j(e,t){this._dirty=!0,this.context=t,this.props=e,this.state=this.state||{}}function z(e,t,n){return w(n,e,{},!1,t,!1)}i(j.prototype,{setState:function(e,t){var n=this.state;this.prevState||(this.prevState=i({},n)),i(n,"function"==typeof e?e(n,this.props):e),t&&(this._renderCallbacks=this._renderCallbacks||[]).push(t),c(this)},forceUpdate:function(e){e&&(this._renderCallbacks=this._renderCallbacks||[]).push(e),A(this,2)},render:function(){}});var R={h:r,createElement:r,cloneElement:a,Component:j,render:z,rerender:u,options:t};exports.h=r,exports.createElement=r,exports.cloneElement=a,exports.Component=j,exports.render=z,exports.rerender=u,exports.options=t,exports.default=R;
},{}],94:[function(require,module,exports) {
"use strict";function e(e){var o,r=e.Symbol;return"function"==typeof r?r.observable?o=r.observable:(o=r("observable"),r.observable=o):o="@@observable",o}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=e;
},{}],48:[function(require,module,exports) {
var global = arguments[3];
var e=arguments[3];Object.defineProperty(exports,"__esModule",{value:!0});var d,n=require("./ponyfill.js"),u=o(n);function o(e){return e&&e.__esModule?e:{default:e}}d="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof module?module:Function("return this")();var t=(0,u.default)(d);exports.default=t;
},{"./ponyfill.js":94}],31:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.__DO_NOT_USE__ActionTypes=exports.compose=exports.applyMiddleware=exports.bindActionCreators=exports.combineReducers=exports.createStore=void 0;var e=require("symbol-observable"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}var n={INIT:"@@redux/INIT"+Math.random().toString(36).substring(7).split("").join("."),REPLACE:"@@redux/REPLACE"+Math.random().toString(36).substring(7).split("").join(".")},o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};function u(e){if("object"!==(void 0===e?"undefined":o(e))||null===e)return!1;for(var t=e;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function a(e,r,i){var c;if("function"==typeof r&&void 0===i&&(i=r,r=void 0),void 0!==i){if("function"!=typeof i)throw new Error("Expected the enhancer to be a function.");return i(a)(e,r)}if("function"!=typeof e)throw new Error("Expected the reducer to be a function.");var s=e,d=r,f=[],l=f,p=!1;function h(){l===f&&(l=f.slice())}function y(){if(p)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return d}function b(e){if("function"!=typeof e)throw new Error("Expected the listener to be a function.");if(p)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api-reference/store#subscribe(listener) for more details.");var t=!0;return h(),l.push(e),function(){if(t){if(p)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api-reference/store#subscribe(listener) for more details.");t=!1,h();var r=l.indexOf(e);l.splice(r,1)}}}function v(e){if(!u(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(p)throw new Error("Reducers may not dispatch actions.");try{p=!0,d=s(d,e)}finally{p=!1}for(var t=f=l,r=0;r<t.length;r++){(0,t[r])()}return e}return v({type:n.INIT}),(c={dispatch:v,subscribe:b,getState:y,replaceReducer:function(e){if("function"!=typeof e)throw new Error("Expected the nextReducer to be a function.");s=e,v({type:n.REPLACE})}})[t.default]=function(){var e,r=b;return(e={subscribe:function(e){if("object"!==(void 0===e?"undefined":o(e))||null===e)throw new TypeError("Expected the observer to be an object.");function t(){e.next&&e.next(y())}return t(),{unsubscribe:r(t)}}})[t.default]=function(){return this},e},c}function c(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function s(e,t){var r=t&&t.type;return"Given "+(r&&'action "'+String(r)+'"'||"an action")+', reducer "'+e+'" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.'}function d(e,t,r,o){var i=Object.keys(t),a=r&&r.type===n.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===i.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!u(e))return"The "+a+' has unexpected type of "'+{}.toString.call(e).match(/\s([a-z|A-Z]+)/)[1]+'". Expected argument to be an object with the following keys: "'+i.join('", "')+'"';var c=Object.keys(e).filter(function(e){return!t.hasOwnProperty(e)&&!o[e]});return c.forEach(function(e){o[e]=!0}),r&&r.type===n.REPLACE?void 0:c.length>0?"Unexpected "+(c.length>1?"keys":"key")+' "'+c.join('", "')+'" found in '+a+'. Expected to find one of the known reducer keys instead: "'+i.join('", "')+'". Unexpected keys will be ignored.':void 0}function f(e){Object.keys(e).forEach(function(t){var r=e[t];if(void 0===r(void 0,{type:n.INIT}))throw new Error('Reducer "'+t+"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.");if(void 0===r(void 0,{type:"@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".")}))throw new Error('Reducer "'+t+"\" returned undefined when probed with a random type. Don't try to handle "+n.INIT+' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.')})}function l(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++){var o=t[n];0,"function"==typeof e[o]&&(r[o]=e[o])}var i=Object.keys(r);var u=void 0;try{f(r)}catch(e){u=e}return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];if(u)throw u;for(var n=!1,o={},a=0;a<i.length;a++){var c=i[a],d=r[c],f=e[c],l=d(f,t);if(void 0===l){var p=s(c,t);throw new Error(p)}o[c]=l,n=n||l!==f}return n?o:e}}function p(e,t){return function(){return t(e.apply(this,arguments))}}function h(e,t){if("function"==typeof e)return p(e,t);if("object"!==(void 0===e?"undefined":o(e))||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":void 0===e?"undefined":o(e))+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var r=Object.keys(e),n={},i=0;i<r.length;i++){var u=r[i],a=e[u];"function"==typeof a&&(n[u]=p(a,t))}return n}function y(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce(function(e,t){return function(){return e(t.apply(void 0,arguments))}})}function b(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e){return function(){for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];var u=e.apply(void 0,n),a=function(){throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},c={getState:u.getState,dispatch:function(){return a.apply(void 0,arguments)}},s=t.map(function(e){return e(c)});return a=y.apply(void 0,s)(u.dispatch),i({},u,{dispatch:a})}}}function v(){}exports.createStore=a,exports.combineReducers=l,exports.bindActionCreators=h,exports.applyMiddleware=b,exports.compose=y,exports.__DO_NOT_USE__ActionTypes=n;
},{"symbol-observable":48}],26:[function(require,module,exports) {
var global = arguments[3];
var t=arguments[3];Object.defineProperty(exports,"__esModule",{value:!0}),exports.connectAdvanced=exports.connect=exports.Provider=void 0;var e=require("preact"),n=require("redux"),r={only:function(t){return t&&t[0]||null}};function o(){}o.isRequired=o;var i={element:o,func:o,shape:function(){return o},instanceOf:function(){return o}},s=i.shape({trySubscribe:i.func.isRequired,tryUnsubscribe:i.func.isRequired,notifyNestedSubs:i.func.isRequired,isSubscribed:i.func.isRequired}),u=i.shape({subscribe:i.func.isRequired,dispatch:i.func.isRequired,getState:i.func.isRequired});function p(t){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(t);try{throw new Error(t)}catch(t){}}var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},d=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},f=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)},l=function(t,e){var n={};for(var r in t)e.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n},h=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e},b=!1;function y(){b||(b=!0,p("<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions."))}function v(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"store",o=arguments[1]||n+"Subscription",i=function(t){function e(r,o){a(this,e);var i=h(this,t.call(this,r,o));return i[n]=r.store,i}return f(e,t),e.prototype.getChildContext=function(){var t;return(t={})[n]=this[n],t[o]=null,t},e.prototype.render=function(){return r.only(this.props.children)},e}(e.Component);return i.prototype.componentWillReceiveProps=function(t){this[n]!==t.store&&y()},i.childContextTypes=((t={})[n]=u.isRequired,t[o]=s,t),i}var m=v(),P={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},O={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},S=Object.defineProperty,g=Object.getOwnPropertyNames,w=Object.getOwnPropertySymbols,C=Object.getOwnPropertyDescriptor,j=Object.getPrototypeOf,T=j&&j(Object);function x(t,e,n){if("string"!=typeof e){if(T){var r=j(e);r&&r!==T&&x(t,r,n)}var o=g(e);w&&(o=o.concat(w(e)));for(var i=0;i<o.length;++i){var s=o[i];if(!(P[s]||O[s]||n&&n[s])){var u=C(e,s);try{S(t,s,u)}catch(t){}}}return t}return t}var N=x,q=function(){},E=null,U={notify:function(){}};function D(){var t=[],e=[];return{clear:function(){e=E,t=E},notify:function(){for(var n=t=e,r=0;r<n.length;r++)n[r]()},get:function(){return e},subscribe:function(n){var r=!0;return e===t&&(e=t.slice()),e.push(n),function(){r&&t!==E&&(r=!1,e===t&&(e=t.slice()),e.splice(e.indexOf(n),1))}}}}var M=function(){function t(e,n,r){a(this,t),this.store=e,this.parentSub=n,this.onStateChange=r,this.unsubscribe=null,this.listeners=U}return t.prototype.addNestedSub=function(t){return this.trySubscribe(),this.listeners.subscribe(t)},t.prototype.notifyNestedSubs=function(){this.listeners.notify()},t.prototype.isSubscribed=function(){return Boolean(this.unsubscribe)},t.prototype.trySubscribe=function(){this.unsubscribe||(this.unsubscribe=this.parentSub?this.parentSub.addNestedSub(this.onStateChange):this.store.subscribe(this.onStateChange),this.listeners=D())},t.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.listeners.clear(),this.listeners=U)},t}(),R=0,I={};function W(){}function F(t,e){var n={run:function(r){try{var o=t(e.getState(),r);(o!==n.props||n.error)&&(n.shouldComponentUpdate=!0,n.props=o,n.error=null)}catch(t){n.shouldComponentUpdate=!0,n.error=t}}};return n}function A(t){var n,r,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=o.getDisplayName,p=void 0===i?function(t){return"ConnectAdvanced("+t+")"}:i,c=o.methodName,b=void 0===c?"connectAdvanced":c,y=o.renderCountProp,v=void 0===y?void 0:y,m=o.shouldHandleStateChanges,P=void 0===m||m,O=o.storeKey,S=void 0===O?"store":O,g=o.withRef,w=void 0!==g&&g,C=l(o,["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef"]),j=S+"Subscription",T=R++,x=((n={})[S]=u,n[j]=s,n),E=((r={})[j]=s,r);return function(n){q("function"==typeof n,"You must pass a component to the function returned by "+b+". Instead received "+JSON.stringify(n));var r=n.displayName||n.name||"Component",o=p(r),i=d({},C,{getDisplayName:p,methodName:b,renderCountProp:v,shouldHandleStateChanges:P,storeKey:S,withRef:w,displayName:o,wrappedComponentName:r,WrappedComponent:n}),s=function(r){function s(t,e){a(this,s);var n=h(this,r.call(this,t,e));return n.version=T,n.state={},n.renderCount=0,n.store=t[S]||e[S],n.propsMode=Boolean(t[S]),n.setWrappedInstance=n.setWrappedInstance.bind(n),q(n.store,'Could not find "'+S+'" in either the context or props of "'+o+'". Either wrap the root component in a <Provider>, or explicitly pass "'+S+'" as a prop to "'+o+'".'),n.initSelector(),n.initSubscription(),n}return f(s,r),s.prototype.getChildContext=function(){var t,e=this.propsMode?null:this.subscription;return(t={})[j]=e||this.context[j],t},s.prototype.componentDidMount=function(){P&&(this.subscription.trySubscribe(),this.selector.run(this.props),this.selector.shouldComponentUpdate&&this.forceUpdate())},s.prototype.componentWillReceiveProps=function(t){this.selector.run(t)},s.prototype.shouldComponentUpdate=function(){return this.selector.shouldComponentUpdate},s.prototype.componentWillUnmount=function(){this.subscription&&this.subscription.tryUnsubscribe(),this.subscription=null,this.notifyNestedSubs=W,this.store=null,this.selector.run=W,this.selector.shouldComponentUpdate=!1},s.prototype.getWrappedInstance=function(){return q(w,"To access the wrapped instance, you need to specify { withRef: true } in the options argument of the "+b+"() call."),this.wrappedInstance},s.prototype.setWrappedInstance=function(t){this.wrappedInstance=t},s.prototype.initSelector=function(){var e=t(this.store.dispatch,i);this.selector=F(e,this.store),this.selector.run(this.props)},s.prototype.initSubscription=function(){if(P){var t=(this.propsMode?this.props:this.context)[j];this.subscription=new M(this.store,t,this.onStateChange.bind(this)),this.notifyNestedSubs=this.subscription.notifyNestedSubs.bind(this.subscription)}},s.prototype.onStateChange=function(){this.selector.run(this.props),this.selector.shouldComponentUpdate?(this.componentDidUpdate=this.notifyNestedSubsOnComponentDidUpdate,this.setState(I)):this.notifyNestedSubs()},s.prototype.notifyNestedSubsOnComponentDidUpdate=function(){this.componentDidUpdate=void 0,this.notifyNestedSubs()},s.prototype.isSubscribed=function(){return Boolean(this.subscription)&&this.subscription.isSubscribed()},s.prototype.addExtraProps=function(t){if(!(w||v||this.propsMode&&this.subscription))return t;var e=d({},t);return w&&(e.ref=this.setWrappedInstance),v&&(e[v]=this.renderCount++),this.propsMode&&this.subscription&&(e[j]=this.subscription),e},s.prototype.render=function(){var t=this.selector;if(t.shouldComponentUpdate=!1,t.error)throw t.error;return(0,e.h)(n,this.addExtraProps(t.props))},s}(e.Component);return s.WrappedComponent=n,s.displayName=o,s.childContextTypes=E,s.contextTypes=x,s.prototype.componentWillUpdate=function(){var t=this;if(this.version!==T){this.version=T,this.initSelector();var e=[];this.subscription&&(e=this.subscription.listeners.get(),this.subscription.tryUnsubscribe()),this.initSubscription(),P&&(this.subscription.trySubscribe(),e.forEach(function(e){return t.subscription.listeners.subscribe(e)}))}},N(s,n)}}var _=Object.prototype.hasOwnProperty;function B(t,e){return t===e?0!==t||0!==e||1/t==1/e:t!=t&&e!=e}function H(t,e){if(B(t,e))return!0;if("object"!==(void 0===t?"undefined":c(t))||null===t||"object"!==(void 0===e?"undefined":c(e))||null===e)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var o=0;o<n.length;o++)if(!_.call(e,n[o])||!B(t[n[o]],e[n[o]]))return!1;return!0}var k="object"==(void 0===t?"undefined":c(t))&&t&&t.Object===Object&&t,K="object"==("undefined"==typeof self?"undefined":c(self))&&self&&self.Object===Object&&self,J=k||K||Function("return this")(),Y=J.Symbol,z=Object.prototype,G=z.hasOwnProperty,L=z.toString,Q=Y?Y.toStringTag:void 0;function V(t){var e=G.call(t,Q),n=t[Q];try{t[Q]=void 0;var r=!0}catch(t){}var o=L.call(t);return r&&(e?t[Q]=n:delete t[Q]),o}var X=Object.prototype,Z=X.toString;function $(t){return Z.call(t)}var tt="[object Null]",et="[object Undefined]",nt=Y?Y.toStringTag:void 0;function rt(t){return null==t?void 0===t?et:tt:nt&&nt in Object(t)?V(t):$(t)}function ot(t,e){return function(n){return t(e(n))}}var it=ot(Object.getPrototypeOf,Object);function st(t){return null!=t&&"object"==(void 0===t?"undefined":c(t))}var ut="[object Object]",pt=Function.prototype,ct=Object.prototype,at=pt.toString,dt=ct.hasOwnProperty,ft=at.call(Object);function lt(t){if(!st(t)||rt(t)!=ut)return!1;var e=it(t);if(null===e)return!0;var n=dt.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&at.call(n)==ft}function ht(t,e,n){lt(t)||p(n+"() in "+e+" must return a plain object. Instead received "+t+".")}function bt(t){return function(e,n){var r=t(e,n);function o(){return r}return o.dependsOnOwnProps=!1,o}}function yt(t){return null!==t.dependsOnOwnProps&&void 0!==t.dependsOnOwnProps?Boolean(t.dependsOnOwnProps):1!==t.length}function vt(t,e){return function(n,r){var o=r.displayName,i=function(t,e){return i.dependsOnOwnProps?i.mapToProps(t,e):i.mapToProps(t)};return i.dependsOnOwnProps=!0,i.mapToProps=function(n,r){i.mapToProps=t,i.dependsOnOwnProps=yt(t);var s=i(n,r);return"function"==typeof s&&(i.mapToProps=s,i.dependsOnOwnProps=yt(s),s=i(n,r)),ht(s,o,e),s},i}}function mt(t){return"function"==typeof t?vt(t,"mapDispatchToProps"):void 0}function Pt(t){return t?void 0:bt(function(t){return{dispatch:t}})}function Ot(t){return t&&"object"===(void 0===t?"undefined":c(t))?bt(function(e){return(0,n.bindActionCreators)(t,e)}):void 0}var St=[mt,Pt,Ot];function gt(t){return"function"==typeof t?vt(t,"mapStateToProps"):void 0}function wt(t){return t?void 0:bt(function(){return{}})}var Ct=[gt,wt];function jt(t,e,n){return d({},n,t,e)}function Tt(t){return function(e,n){var r=n.displayName,o=n.pure,i=n.areMergedPropsEqual,s=!1,u=void 0;return function(e,n,p){var c=t(e,n,p);return s?o&&i(c,u)||(u=c):(s=!0,ht(u=c,r,"mergeProps")),u}}}function xt(t){return"function"==typeof t?Tt(t):void 0}function Nt(t){return t?void 0:function(){return jt}}var qt=[xt,Nt];function Et(t,e,n){if(!t)throw new Error("Unexpected value for "+e+" in "+n+".");"mapStateToProps"!==e&&"mapDispatchToProps"!==e||t.hasOwnProperty("dependsOnOwnProps")||p("The selector for "+e+" of "+n+" did not specify a value for dependsOnOwnProps.")}function Ut(t,e,n,r){Et(t,"mapStateToProps",r),Et(e,"mapDispatchToProps",r),Et(n,"mergeProps",r)}function Dt(t,e,n,r){return function(o,i){return n(t(o,i),e(r,i),i)}}function Mt(t,e,n,r,o){var i=o.areStatesEqual,s=o.areOwnPropsEqual,u=o.areStatePropsEqual,p=!1,c=void 0,a=void 0,d=void 0,f=void 0,l=void 0;function h(o,p){var h,b,y=!s(p,a),v=!i(o,c);return c=o,a=p,y&&v?(d=t(c,a),e.dependsOnOwnProps&&(f=e(r,a)),l=n(d,f,a)):y?(t.dependsOnOwnProps&&(d=t(c,a)),e.dependsOnOwnProps&&(f=e(r,a)),l=n(d,f,a)):v?(h=t(c,a),b=!u(h,d),d=h,b&&(l=n(d,f,a)),l):l}return function(o,i){return p?h(o,i):(d=t(c=o,a=i),f=e(r,a),l=n(d,f,a),p=!0,l)}}function Rt(t,e){var n=e.initMapStateToProps,r=e.initMapDispatchToProps,o=e.initMergeProps,i=l(e,["initMapStateToProps","initMapDispatchToProps","initMergeProps"]),s=n(t,i),u=r(t,i),p=o(t,i);return Ut(s,u,p,i.displayName),(i.pure?Mt:Dt)(s,u,p,t,i)}function It(t,e,n){for(var r=e.length-1;r>=0;r--){var o=e[r](t);if(o)return o}return function(e,r){throw new Error("Invalid value of type "+(void 0===t?"undefined":c(t))+" for "+n+" argument when connecting component "+r.wrappedComponentName+".")}}function Wt(t,e){return t===e}function Ft(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.connectHOC,n=void 0===e?A:e,r=t.mapStateToPropsFactories,o=void 0===r?Ct:r,i=t.mapDispatchToPropsFactories,s=void 0===i?St:i,u=t.mergePropsFactories,p=void 0===u?qt:u,c=t.selectorFactory,a=void 0===c?Rt:c;return function(t,e,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},u=i.pure,c=void 0===u||u,f=i.areStatesEqual,h=void 0===f?Wt:f,b=i.areOwnPropsEqual,y=void 0===b?H:b,v=i.areStatePropsEqual,m=void 0===v?H:v,P=i.areMergedPropsEqual,O=void 0===P?H:P,S=l(i,["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"]),g=It(t,o,"mapStateToProps"),w=It(e,s,"mapDispatchToProps"),C=It(r,p,"mergeProps");return n(a,d({methodName:"connect",getDisplayName:function(t){return"Connect("+t+")"},shouldHandleStateChanges:Boolean(t),initMapStateToProps:g,initMapDispatchToProps:w,initMergeProps:C,pure:c,areStatesEqual:h,areOwnPropsEqual:y,areStatePropsEqual:m,areMergedPropsEqual:O},S))}}var At=Ft(),_t={Provider:m,connect:At,connectAdvanced:A};exports.Provider=m,exports.connect=At,exports.connectAdvanced=A,exports.default=_t;
},{"preact":24,"redux":31}],36:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StatelessComponent=void 0,exports.actionCreator=n,exports.setter=o,exports.createContainer=s,exports.bindActionCreator=c;var e=require("preact-redux"),t=require("preact");const r=new Set;function n(e){if(r.has(e))throw new Error(`Cannot re-use action type name: ${e}`);const t=(t={})=>({type:e,payload:t});return t.matches=(t=>t.type===e),t}function o(e,t){return(r=t,n)=>e.matches(n)?n.payload:r}function s(t,r){return(0,e.connect)(e=>e,e=>({dispatch:e}),(e,t,n)=>r(e,t.dispatch,n))(t)}class a extends t.Component{}function c(e,t){return r=>{e(t(r))}}exports.StatelessComponent=a;
},{"preact-redux":26,"preact":24}],102:[function(require,module,exports) {
"use strict";function t(t,i,s){return t<i?i:t>s?s:t}Object.defineProperty(exports,"__esModule",{value:!0}),exports.clamp=t;class i{constructor(t,i){this.x=t,this.y=i}withX(t){return new i(t,this.y)}withY(t){return new i(this.x,t)}plus(t){return new i(this.x+t.x,this.y+t.y)}minus(t){return new i(this.x-t.x,this.y-t.y)}times(t){return new i(this.x*t,this.y*t)}timesPointwise(t){return new i(this.x*t.x,this.y*t.y)}dividedByPointwise(t){return new i(this.x/t.x,this.y/t.y)}dot(t){return this.x*t.x+this.y*t.y}equals(t){return this.x===t.x&&this.y===t.y}approxEquals(t,i=1e-9){return Math.abs(this.x-t.x)<i&&Math.abs(this.y-t.y)<i}length2(){return this.dot(this)}length(){return Math.sqrt(this.length2())}abs(){return new i(Math.abs(this.x),Math.abs(this.y))}static min(t,s){return new i(Math.min(t.x,s.x),Math.min(t.y,s.y))}static max(t,s){return new i(Math.max(t.x,s.x),Math.max(t.y,s.y))}static clamp(s,e,r){return new i(t(s.x,e.x,r.x),t(s.y,e.y,r.y))}flatten(){return[this.x,this.y]}}exports.Vec2=i,i.zero=new i(0,0),i.unit=new i(1,1);class s{constructor(t=1,i=0,s=0,e=0,r=1,n=0){this.m00=t,this.m01=i,this.m02=s,this.m10=e,this.m11=r,this.m12=n}withScale(t){let{m00:i,m01:e,m02:r,m10:n,m11:h,m12:m}=this;return i=t.x,h=t.y,new s(i,e,r,n,h,m)}static withScale(t){return(new s).withScale(t)}scaledBy(t){return s.withScale(t).times(this)}getScale(){return new i(this.m00,this.m11)}withTranslation(t){let{m00:i,m01:e,m02:r,m10:n,m11:h,m12:m}=this;return r=t.x,m=t.y,new s(i,e,r,n,h,m)}static withTranslation(t){return(new s).withTranslation(t)}getTranslation(){return new i(this.m02,this.m12)}translatedBy(t){return s.withTranslation(t).times(this)}static betweenRects(t,e){return s.withTranslation(t.origin.times(-1)).scaledBy(new i(e.size.x/t.size.x,e.size.y/t.size.y)).translatedBy(e.origin)}times(t){const i=this.m00*t.m00+this.m01*t.m10,e=this.m00*t.m01+this.m01*t.m11,r=this.m00*t.m02+this.m01*t.m12+this.m02,n=this.m10*t.m00+this.m11*t.m10,h=this.m10*t.m01+this.m11*t.m11,m=this.m10*t.m02+this.m11*t.m12+this.m12;return new s(i,e,r,n,h,m)}equals(t){return this.m00==t.m00&&this.m01==t.m01&&this.m02==t.m02&&this.m10==t.m10&&this.m11==t.m11&&this.m12==t.m12}approxEquals(t,i=1e-9){return Math.abs(this.m00-t.m00)<i&&Math.abs(this.m01-t.m01)<i&&Math.abs(this.m02-t.m02)<i&&Math.abs(this.m10-t.m10)<i&&Math.abs(this.m11-t.m11)<i&&Math.abs(this.m12-t.m12)<i}timesScalar(t){const{m00:i,m01:e,m02:r,m10:n,m11:h,m12:m}=this;return new s(t*i,t*e,t*r,t*n,t*h,t*m)}det(){const{m00:t,m01:i,m02:s,m10:e,m11:r,m12:n}=this;return t*(1*r-0*n)-i*(1*e-0*n)+s*(0*e-0*r)}adj(){const{m00:t,m01:i,m02:e,m10:r,m11:n,m12:h}=this;return new s(+(1*n-0*h),-(1*i-0*e),+(i*h-e*n),-(1*r-0*h),+(1*t-0*e),-(t*h-e*r))}inverted(){const t=this.det();return 0===t?null:this.adj().timesScalar(1/t)}transformVector(t){return new i(t.x*this.m00+t.y*this.m01,t.x*this.m10+t.y*this.m11)}inverseTransformVector(t){const i=this.inverted();return i?i.transformVector(t):null}transformPosition(t){return new i(t.x*this.m00+t.y*this.m01+this.m02,t.x*this.m10+t.y*this.m11+this.m12)}inverseTransformPosition(t){const i=this.inverted();return i?i.transformPosition(t):null}transformRect(t){const i=this.transformVector(t.size),s=this.transformPosition(t.origin);return i.x<0&&i.y<0?new e(s.plus(i),i.abs()):i.x<0?new e(s.withX(s.x+i.x),i.abs()):i.y<0?new e(s.withY(s.y+i.y),i.abs()):new e(s,i)}inverseTransformRect(t){const i=this.inverted();return i?i.transformRect(t):null}flatten(){return[this.m00,this.m10,0,this.m01,this.m11,0,this.m02,this.m12,1]}}exports.AffineTransform=s;class e{constructor(t,i){this.origin=t,this.size=i}isEmpty(){return 0==this.width()||0==this.height()}width(){return this.size.x}height(){return this.size.y}left(){return this.origin.x}right(){return this.left()+this.width()}top(){return this.origin.y}bottom(){return this.top()+this.height()}topLeft(){return this.origin}topRight(){return this.origin.plus(new i(this.width(),0))}bottomRight(){return this.origin.plus(this.size)}bottomLeft(){return this.origin.plus(new i(0,this.height()))}withOrigin(t){return new e(t,this.size)}withSize(t){return new e(this.origin,t)}closestPointTo(s){return new i(t(s.x,this.left(),this.right()),t(s.y,this.top(),this.bottom()))}distanceFrom(t){return t.minus(this.closestPointTo(t)).length()}contains(t){return 0===this.distanceFrom(t)}hasIntersectionWith(t){const i=Math.max(this.top(),t.top());if(Math.max(i,Math.min(this.bottom(),t.bottom()))-i==0)return!1;const s=Math.max(this.left(),t.left());return Math.max(s,Math.min(this.right(),t.right()))-s!=0}intersectWith(t){const s=i.max(this.topLeft(),t.topLeft()),r=i.max(s,i.min(this.bottomRight(),t.bottomRight()));return new e(s,r.minus(s))}equals(t){return this.origin.equals(t.origin)&&this.size.equals(t.size)}approxEquals(t){return this.origin.approxEquals(t.origin)&&this.size.approxEquals(t.size)}area(){return this.size.x*this.size.y}}exports.Rect=e,e.empty=new e(i.zero,i.zero),e.unit=new e(i.zero,i.unit),e.NDC=new e(new i(-1,-1),new i(2,2));
},{}],98:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartID=void 0,exports.createFlamechartViewStateReducer=c;var e=require("../lib/math"),t=require("./actions"),a=exports.FlamechartID=void 0;function c(a,c){let o={hover:null,selectedNode:null,configSpaceViewportRect:e.Rect.empty,logicalSpaceViewportSize:e.Vec2.zero};function r(e){const{payload:t}=e;return t.args.id===a&&t.profileIndex===c}return(e=o,a)=>{if(t.actions.flamechart.setHoveredNode.matches(a)&&r(a)){const{hover:t}=a.payload.args;return Object.assign({},e,{hover:t})}if(t.actions.flamechart.setSelectedNode.matches(a)&&r(a)){const{selectedNode:t}=a.payload.args;return Object.assign({},e,{selectedNode:t})}if(t.actions.flamechart.setConfigSpaceViewportRect.matches(a)&&r(a)){const{configSpaceViewportRect:t}=a.payload.args;return Object.assign({},e,{configSpaceViewportRect:t})}if(t.actions.flamechart.setLogicalSpaceViewportSize.matches(a)&&r(a)){const{logicalSpaceViewportSize:t}=a.payload.args;return Object.assign({},e,{logicalSpaceViewportSize:t})}return t.actions.setViewMode.matches(a)?Object.assign({},e,{hover:null}):e}}!function(e){e.LEFT_HEAVY="LEFT_HEAVY",e.CHRONO="CHRONO",e.SANDWICH_INVERTED_CALLERS="SANDWICH_INVERTED_CALLERS",e.SANDWICH_CALLEES="SANDWICH_CALLEES"}(a||(exports.FlamechartID=a={}));
},{"../lib/math":102,"./actions":40}],100:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createSandwichView=l;var e=require("./flamechart-view-state"),a=require("./actions");function l(l){const r=(0,e.createFlamechartViewStateReducer)(e.FlamechartID.SANDWICH_CALLEES,l),t=(0,e.createFlamechartViewStateReducer)(e.FlamechartID.SANDWICH_INVERTED_CALLERS,l);return(e={callerCallee:null},c)=>{if(a.actions.sandwichView.setSelectedFrame.matches(c)&&function(e){const{payload:a}=e;return a.profileIndex===l}(c))return null==c.payload.args?Object.assign({},e,{callerCallee:null}):Object.assign({},e,{callerCallee:{selectedFrame:c.payload.args,calleeFlamegraph:r(void 0,c),invertedCallerFlamegraph:t(void 0,c)}});const{callerCallee:n}=e;if(n){const{calleeFlamegraph:a,invertedCallerFlamegraph:l}=n,i=r(a,c),s=t(l,c);return i===a&&s===l?e:Object.assign({},e,{callerCallee:Object.assign({},n,{calleeFlamegraph:i,invertedCallerFlamegraph:s})})}return e}}
},{"./flamechart-view-state":98,"./actions":40}],70:[function(require,module,exports) {
"use strict";function t(t){return t[t.length-1]||null}function e(t,e){t.sort(function(t,r){return e(t)<e(r)?-1:1})}function r(t,e,r){return t.has(e)||t.set(e,r(e)),t.get(e)}function n(t,e,r){return t.has(e)?t.get(e):r(e)}function o(t,e){if(!t.has(e))throw new Error(`Expected key ${e}`);return t.get(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.lastOf=t,exports.sortBy=e,exports.getOrInsert=r,exports.getOrElse=n,exports.getOrThrow=o,exports.itMap=l,exports.itForEach=u,exports.itReduce=a,exports.zeroPad=i,exports.formatPercent=c,exports.fract=f,exports.triangle=h,exports.binarySearch=g,exports.noop=p,exports.objectsHaveShallowEquality=x,exports.memoizeByShallowEquality=d,exports.memoizeByReference=y,exports.lazyStatic=w,exports.decodeBase64=m;class s{constructor(){this.map=new Map}getOrInsert(t){const e=t.key,r=this.map.get(e);return r||(this.map.set(e,t),t)}forEach(t){this.map.forEach(t)}[Symbol.iterator](){return this.map.values()}}function*l(t,e){for(let r of t)yield e(r)}function u(t,e){for(let r of t)e(r)}function a(t,e,r){let n=r;for(let r of t)n=e(n,r);return n}function i(t,e){return new Array(Math.max(e-t.length,0)+1).join("0")+t}function c(t){let e=`${t.toFixed(0)}%`;return 100===t?e="100%":t>99?e=">99%":t<.01?e="<0.01%":t<1?e=`${t.toFixed(2)}%`:t<10&&(e=`${t.toFixed(1)}%`),e}function f(t){return t-Math.floor(t)}function h(t){return 2*Math.abs(f(t)-.5)-1}function g(t,e,r,n,o=1){for(console.assert(!isNaN(o)&&!isNaN(n));;){if(e-t<=o)return[t,e];const s=(e+t)/2;r(s)<n?t=s:e=s}}function p(...t){}function x(t,e){for(let r in t)if(t[r]!==e[r])return!1;for(let r in e)if(t[r]!==e[r])return!1;return!0}function d(t){let e=null;return r=>{let n;return null==e?(n=t(r),e={args:r,result:n},n):x(e.args,r)?e.result:(e.args=r,e.result=t(r),e.result)}}function y(t){let e=null;return r=>{let n;return null==e?(n=t(r),e={args:r,result:n},n):e.args===r?e.result:(e.args=r,e.result=t(r),e.result)}}function w(t){let e=null;return()=>(null==e&&(e={result:t()}),e.result)}exports.KeyedSet=s;const E=w(()=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=new Map;for(let r=0;r<t.length;r++)e.set(t.charAt(r),r);return e.set("=",-1),e});function m(t){const e=E();if(t.length%4!=0)throw new Error(`Invalid length for base64 encoded string. Expected length % 4 = 0, got length = ${t.length}`);const r=t.length/4;let n;n=t.length>=4&&"="===t.charAt(t.length-1)?"="===t.charAt(t.length-2)?3*r-2:3*r-1:3*r;const o=new Uint8Array(n);let s=0;for(let n=0;n<r;n++){const r=t.charAt(4*n+0),l=t.charAt(4*n+1),u=t.charAt(4*n+2),a=t.charAt(4*n+3),i=e.get(r),c=e.get(l),f=e.get(u),h=e.get(a);if(null==i||null==c||null==f||null==h)throw new Error(`Invalid quartet at indices ${4*n} .. ${4*n+3}: ${t.substring(4*n,4*n+3)}`);o[s++]=i<<2|c>>4,"="!==u&&(o[s++]=(15&c)<<4|f>>2),"="!==a&&(o[s++]=(7&f)<<6|h)}if(s!==n)throw new Error(`Expected to decode ${n} bytes, but only decoded ${s})`);return o}
},{}],52:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.profileGroup=void 0,exports.actionCreatorWithIndex=n;var e=require("./flamechart-view-state"),t=require("./sandwich-view-state"),i=require("../lib/typed-redux"),r=require("./actions"),a=require("../lib/math"),o=require("../lib/utils");function n(e){return(0,i.actionCreator)(e)}function l(i,r){const a=(0,e.createFlamechartViewStateReducer)(e.FlamechartID.CHRONO,r),n=(0,e.createFlamechartViewStateReducer)(e.FlamechartID.LEFT_HEAVY,r),l=(0,t.createSandwichView)(r);return(e,t)=>{if(void 0===e)return{profile:i,chronoViewState:a(void 0,t),leftHeavyViewState:n(void 0,t),sandwichViewState:l(void 0,t)};const r={profile:i,chronoViewState:a(e.chronoViewState,t),leftHeavyViewState:n(e.leftHeavyViewState,t),sandwichViewState:l(e.sandwichViewState,t)};return(0,o.objectsHaveShallowEquality)(e,r)?e:r}}const c=exports.profileGroup=((e=null,t)=>{if(r.actions.setProfileGroup.matches(t)){const{indexToView:e,profiles:i,name:r}=t.payload;return{indexToView:e,name:r,profiles:i.map((e,i)=>l(e,i)(void 0,t))}}if(null!=e){const{indexToView:n,profiles:c}=e,s=(0,a.clamp)((0,i.setter)(r.actions.setProfileIndexToView,0)(n,t),0,c.length-1),u=c.map((e,i)=>l(e.profile,i)(e,t));return n===s&&(0,o.objectsHaveShallowEquality)(c,u)?e:Object.assign({},e,{indexToView:s,profiles:u})}return e});
},{"./flamechart-view-state":98,"./sandwich-view-state":100,"../lib/typed-redux":36,"./actions":40,"../lib/math":102,"../lib/utils":70}],40:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.actions=void 0;var e=require("../lib/typed-redux"),t=require("./profiles-state"),a=exports.actions=void 0;!function(a){let o,r;a.setProfileGroup=(0,e.actionCreator)("setProfileGroup"),a.setProfileIndexToView=(0,e.actionCreator)("setProfileIndexToView"),a.setGLCanvas=(0,e.actionCreator)("setGLCanvas"),a.setViewMode=(0,e.actionCreator)("setViewMode"),a.setFlattenRecursion=(0,e.actionCreator)("setFlattenRecursion"),a.setDragActive=(0,e.actionCreator)("setDragActive"),a.setLoading=(0,e.actionCreator)("setLoading"),a.setError=(0,e.actionCreator)("setError"),a.setHashParams=(0,e.actionCreator)("setHashParams"),function(a){a.setTableSortMethod=(0,e.actionCreator)("sandwichView.setTableSortMethod"),a.setSelectedFrame=(0,t.actionCreatorWithIndex)("sandwichView.setSelectedFarmr")}(o=a.sandwichView||(a.sandwichView={})),function(e){e.setHoveredNode=(0,t.actionCreatorWithIndex)("flamechart.setHoveredNode"),e.setSelectedNode=(0,t.actionCreatorWithIndex)("flamechart.setSelectedNode"),e.setConfigSpaceViewportRect=(0,t.actionCreatorWithIndex)("flamechart.setConfigSpaceViewportRect"),e.setLogicalSpaceViewportSize=(0,t.actionCreatorWithIndex)("flamechart.setLogicalSpaceViewportSpace")}(r=a.flamechart||(a.flamechart={}))}(a||(exports.actions=a={}));
},{"../lib/typed-redux":36,"./profiles-state":52}],50:[function(require,module,exports) {
"use strict";function t(t=window.location.hash){try{if(!t.startsWith("#"))return{};const e=t.substr(1).split("&"),r={};for(const t of e){let[e,o]=t.split("=");o=decodeURIComponent(o),"profileURL"===e?r.profileURL=o:"title"===e?r.title=o:"localProfilePath"===e&&(r.localProfilePath=o)}return r}catch(t){return console.error("Error when loading hash fragment."),console.error(t),{}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getHashParams=t;
},{}],158:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=t;var e=/-webkit-|-moz-|-ms-/;function t(t){return"string"==typeof t&&e.test(t)}module.exports=exports.default;
},{}],123:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=i;var e=require("css-in-js-utils/lib/isPrefixedValue"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}var u=["-webkit-","-moz-",""];function i(e,r){if("string"==typeof r&&!(0,t.default)(r)&&r.indexOf("calc(")>-1)return u.map(function(e){return r.replace(/calc\(/g,e+"calc(")})}module.exports=exports.default;
},{"css-in-js-utils/lib/isPrefixedValue":158}],124:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=u;var e=require("css-in-js-utils/lib/isPrefixedValue"),r=t(e);function t(e){return e&&e.__esModule?e:{default:e}}var s=["-webkit-",""];function u(e,t){if("string"==typeof t&&!(0,r.default)(t)&&t.indexOf("cross-fade(")>-1)return s.map(function(e){return t.replace(/cross-fade\(/g,e+"cross-fade(")})}module.exports=exports.default;
},{"css-in-js-utils/lib/isPrefixedValue":158}],125:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=o;var e=["-webkit-","-moz-",""],r={"zoom-in":!0,"zoom-out":!0,grab:!0,grabbing:!0};function o(o,t){if("cursor"===o&&r.hasOwnProperty(t))return e.map(function(e){return e+t})}module.exports=exports.default;
},{}],126:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=u;var e=require("css-in-js-utils/lib/isPrefixedValue"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}var i=["-webkit-",""];function u(e,r){if("string"==typeof r&&!(0,t.default)(r)&&r.indexOf("filter(")>-1)return i.map(function(e){return r.replace(/filter\(/g,e+"filter(")})}module.exports=exports.default;
},{"css-in-js-utils/lib/isPrefixedValue":158}],127:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=i;var e={flex:["-webkit-box","-moz-box","-ms-flexbox","-webkit-flex","flex"],"inline-flex":["-webkit-inline-box","-moz-inline-box","-ms-inline-flexbox","-webkit-inline-flex","inline-flex"]};function i(i,l){if("display"===i&&e.hasOwnProperty(l))return e[l]}module.exports=exports.default;
},{}],128:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=s;var e={"space-around":"distribute","space-between":"justify","flex-start":"start","flex-end":"end"},t={alignContent:"msFlexLinePack",alignSelf:"msFlexItemAlign",alignItems:"msFlexAlign",justifyContent:"msFlexPack",order:"msFlexOrder",flexGrow:"msFlexPositive",flexShrink:"msFlexNegative",flexBasis:"msFlexPreferredSize"};function s(s,l,r){t.hasOwnProperty(s)&&(r[t[s]]=e[l]||l)}module.exports=exports.default;
},{}],129:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=i;var e={"space-around":"justify","space-between":"justify","flex-start":"start","flex-end":"end","wrap-reverse":"multiple",wrap:"multiple"},t={alignItems:"WebkitBoxAlign",justifyContent:"WebkitBoxPack",flexWrap:"WebkitBoxLines"};function i(i,r,o){"flexDirection"===i&&"string"==typeof r&&(r.indexOf("column")>-1?o.WebkitBoxOrient="vertical":o.WebkitBoxOrient="horizontal",r.indexOf("reverse")>-1?o.WebkitBoxDirection="reverse":o.WebkitBoxDirection="normal"),t.hasOwnProperty(i)&&(o[t[i]]=e[r]||r)}module.exports=exports.default;
},{}],130:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=n;var e=require("css-in-js-utils/lib/isPrefixedValue"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}var i=["-webkit-","-moz-",""],a=/linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/;function n(e,r){if("string"==typeof r&&!(0,t.default)(r)&&a.test(r))return i.map(function(e){return e+r})}module.exports=exports.default;
},{"css-in-js-utils/lib/isPrefixedValue":158}],131:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=u;var e=require("css-in-js-utils/lib/isPrefixedValue"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}var i=["-webkit-",""];function u(e,r){if("string"==typeof r&&!(0,t.default)(r)&&r.indexOf("image-set(")>-1)return i.map(function(e){return r.replace(/image-set\(/g,e+"image-set(")})}module.exports=exports.default;
},{"css-in-js-utils/lib/isPrefixedValue":158}],132:[function(require,module,exports) {
"use strict";function e(e,t){if("position"===e&&"sticky"===t)return["-webkit-sticky","sticky"]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=e,module.exports=exports.default;
},{}],133:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=i;var t=["-webkit-","-moz-",""],e={maxHeight:!0,maxWidth:!0,width:!0,height:!0,columnWidth:!0,minWidth:!0,minHeight:!0},n={"min-content":!0,"max-content":!0,"fill-available":!0,"fit-content":!0,"contain-floats":!0};function i(i,o){if(e.hasOwnProperty(i)&&n.hasOwnProperty(o))return t.map(function(t){return t+o})}module.exports=exports.default;
},{}],181:[function(require,module,exports) {
"use strict";var e=/[A-Z]/g,r=/^ms-/,s={};function t(t){return t in s?s[t]:s[t]=t.replace(e,"-$&").toLowerCase().replace(r,"-ms-")}module.exports=t;
},{}],165:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=u;var e=require("hyphenate-style-name"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}function u(e){return(0,t.default)(e)}module.exports=exports.default;
},{"hyphenate-style-name":181}],164:[function(require,module,exports) {
"use strict";function e(e){return e.charAt(0).toUpperCase()+e.slice(1)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=e,module.exports=exports.default;
},{}],134:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=l;var t=require("css-in-js-utils/lib/hyphenateProperty"),e=s(t),r=require("css-in-js-utils/lib/isPrefixedValue"),i=s(r),n=require("../../utils/capitalizeString"),o=s(n);function s(t){return t&&t.__esModule?t:{default:t}}var u={transition:!0,transitionProperty:!0,WebkitTransition:!0,WebkitTransitionProperty:!0,MozTransition:!0,MozTransitionProperty:!0},a={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-"};function f(t,r){if((0,i.default)(t))return t;for(var n=t.split(/,(?![^()]*(?:\([^()]*\))?\))/g),o=0,s=n.length;o<s;++o){var u=n[o],f=[u];for(var l in r){var p=(0,e.default)(l);if(u.indexOf(p)>-1&&"order"!==p)for(var d=r[l],c=0,b=d.length;c<b;++c)f.unshift(u.replace(p,a[d[c]]+p))}n[o]=f.join(",")}return n.join(",")}function l(t,e,r,i){if("string"==typeof e&&u.hasOwnProperty(t)){var n=f(e,i),s=n.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function(t){return!/-moz-|-ms-/.test(t)}).join(",");if(t.indexOf("Webkit")>-1)return s;var a=n.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function(t){return!/-webkit-|-ms-/.test(t)}).join(",");return t.indexOf("Moz")>-1?a:(r["Webkit"+(0,o.default)(t)]=s,r["Moz"+(0,o.default)(t)]=a,n)}}module.exports=exports.default;
},{"css-in-js-utils/lib/hyphenateProperty":165,"css-in-js-utils/lib/isPrefixedValue":158,"../../utils/capitalizeString":164}],144:[function(require,module,exports) {
"use strict";function r(r){for(var t=5381,e=r.length;e;)t=33*t^r.charCodeAt(--e);return t>>>0}module.exports=r;
},{}],168:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=u;var e=require("./capitalizeString"),r=t(e);function t(e){return e&&e.__esModule?e:{default:e}}function u(e,t,u){if(e.hasOwnProperty(t)){for(var o={},a=e[t],n=(0,r.default)(t),f=Object.keys(u),l=0;l<f.length;l++){var i=f[l];if(i===t)for(var s=0;s<a.length;s++)o[a[s]+n]=u[t];o[i]=u[i]}return o}return u}module.exports=exports.default;
},{"./capitalizeString":164}],169:[function(require,module,exports) {
"use strict";function e(e,t,r,o,u){for(var s=0,f=e.length;s<f;++s){var l=e[s](t,r,o,u);if(l)return l}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=e,module.exports=exports.default;
},{}],170:[function(require,module,exports) {
"use strict";function e(e,r){-1===e.indexOf(r)&&e.push(r)}function r(r,t){if(Array.isArray(t))for(var o=0,s=t.length;o<s;++o)e(r,t[o]);else e(r,t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=r,module.exports=exports.default;
},{}],171:[function(require,module,exports) {
"use strict";function e(e){return e instanceof Object&&!Array.isArray(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=e,module.exports=exports.default;
},{}],135:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=n;var e=require("../utils/prefixProperty"),r=s(e),t=require("../utils/prefixValue"),u=s(t),l=require("../utils/addNewValuesOnly"),a=s(l),i=require("../utils/isObject"),f=s(i);function s(e){return e&&e.__esModule?e:{default:e}}function n(e){var t=e.prefixMap,l=e.plugins;return function e(i){for(var s in i){var n=i[s];if((0,f.default)(n))i[s]=e(n);else if(Array.isArray(n)){for(var d=[],o=0,p=n.length;o<p;++o){var v=(0,u.default)(l,s,n[o],i,t);(0,a.default)(d,v||n[o])}d.length>0&&(i[s]=d)}else{var x=(0,u.default)(l,s,n,i,t);x&&(i[s]=x),i=(0,r.default)(t,s,i)}}return i}}module.exports=exports.default;
},{"../utils/prefixProperty":168,"../utils/prefixValue":169,"../utils/addNewValuesOnly":170,"../utils/isObject":171}],166:[function(require,module,exports) {
var global = arguments[3];
var e=arguments[3];function t(e){r.length||(n(),a=!0),r[r.length]=e}module.exports=t;var n,r=[],a=!1,o=0,u=1024;function l(){for(;o<r.length;){var e=o;if(o+=1,r[e].call(),o>u){for(var t=0,n=r.length-o;t<n;t++)r[t]=r[t+o];r.length-=o,o=0}}r.length=0,o=0,a=!1}var i=void 0!==e?e:self,c=i.MutationObserver||i.WebKitMutationObserver;function f(e){var t=1,n=new c(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function v(e){return function(){var t=setTimeout(r,0),n=setInterval(r,50);function r(){clearTimeout(t),clearInterval(n),e()}}}n="function"==typeof c?f(l):v(l),t.requestFlush=n,t.makeRequestCallFromTimer=v;
},{}],136:[function(require,module,exports) {
"use strict";var t=require("./raw"),r=[],n=[],e=t.makeRequestCallFromTimer(l);function l(){if(n.length)throw n.shift()}function o(n){var e;(e=r.length?r.pop():new i).task=n,t(e)}function i(){this.task=null}module.exports=o,i.prototype.call=function(){try{this.task.call()}catch(t){o.onerror?o.onerror(t):(n.push(t),e())}finally{this.task=null,r[r.length]=this}};
},{"./raw":166}],68:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushToStyleTag=exports.minify=exports.css=exports.StyleSheetTestUtils=exports.StyleSheetServer=exports.StyleSheet=void 0;var e=require("inline-style-prefixer/static/plugins/calc"),t=I(e),r=require("inline-style-prefixer/static/plugins/crossFade"),n=I(r),i=require("inline-style-prefixer/static/plugins/cursor"),o=I(i),a=require("inline-style-prefixer/static/plugins/filter"),s=I(a),u=require("inline-style-prefixer/static/plugins/flex"),l=I(u),f=require("inline-style-prefixer/static/plugins/flexboxIE"),c=I(f),y=require("inline-style-prefixer/static/plugins/flexboxOld"),p=I(y),d=require("inline-style-prefixer/static/plugins/gradient"),m=I(d),h=require("inline-style-prefixer/static/plugins/imageSet"),g=I(h),S=require("inline-style-prefixer/static/plugins/position"),v=I(S),x=require("inline-style-prefixer/static/plugins/sizing"),b=I(x),k=require("inline-style-prefixer/static/plugins/transition"),O=I(k),w=require("string-hash"),A=I(w),C=require("inline-style-prefixer/static/createPrefixer"),j=I(C),T=require("asap"),E=I(T);function I(e){return e&&e.__esModule?e:{default:e}}var R=["Webkit"],M=["Moz"],q=["ms"],F=["Webkit","Moz"],P=["Webkit","ms"],W=["Webkit","Moz","ms"],D={plugins:[t.default,n.default,o.default,s.default,l.default,c.default,p.default,m.default,g.default,v.default,b.default,O.default],prefixMap:{transform:P,transformOrigin:P,transformOriginX:P,transformOriginY:P,backfaceVisibility:R,perspective:R,perspectiveOrigin:R,transformStyle:R,transformOriginZ:R,animation:R,animationDelay:R,animationDirection:R,animationFillMode:R,animationDuration:R,animationIterationCount:R,animationName:R,animationPlayState:R,animationTimingFunction:R,appearance:F,userSelect:W,fontKerning:R,textEmphasisPosition:R,textEmphasis:R,textEmphasisStyle:R,textEmphasisColor:R,boxDecorationBreak:R,clipPath:R,maskImage:R,maskMode:R,maskRepeat:R,maskPosition:R,maskClip:R,maskOrigin:R,maskSize:R,maskComposite:R,mask:R,maskBorderSource:R,maskBorderMode:R,maskBorderSlice:R,maskBorderWidth:R,maskBorderOutset:R,maskBorderRepeat:R,maskBorder:R,maskType:R,textDecorationStyle:F,textDecorationSkip:F,textDecorationLine:F,textDecorationColor:F,filter:R,fontFeatureSettings:F,breakAfter:W,breakBefore:W,breakInside:W,columnCount:F,columnFill:F,columnGap:F,columnRule:F,columnRuleColor:F,columnRuleStyle:F,columnRuleWidth:F,columns:F,columnSpan:F,columnWidth:F,writingMode:P,flex:P,flexBasis:R,flexDirection:P,flexGrow:R,flexFlow:P,flexShrink:R,flexWrap:P,alignContent:R,alignItems:R,alignSelf:R,justifyContent:R,order:R,transitionDelay:R,transitionDuration:R,transitionProperty:R,transitionTimingFunction:R,backdropFilter:R,scrollSnapType:P,scrollSnapPointsX:P,scrollSnapPointsY:P,scrollSnapDestination:P,scrollSnapCoordinate:P,shapeImageThreshold:R,shapeImageMargin:R,shapeImageOutside:R,hyphens:W,flowInto:P,flowFrom:P,regionFragment:P,boxSizing:M,textAlignLast:M,tabSize:M,wrapFlow:q,wrapThrough:q,wrapMargin:q,touchAction:q,gridTemplateColumns:q,gridTemplateRows:q,gridTemplateAreas:q,gridTemplate:q,gridAutoColumns:q,gridAutoRows:q,gridAutoFlow:q,grid:q,gridRowStart:q,gridColumnStart:q,gridRowEnd:q,gridRow:q,gridColumn:q,gridColumnEnd:q,gridColumnGap:q,gridRowGap:q,gridArea:q,gridGap:q,textSizeAdjust:P,borderImage:R,borderImageOutset:R,borderImageRepeat:R,borderImageSlice:R,borderImageSource:R,borderImageWidth:R}},_="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},z=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();function B(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var G="undefined"!=typeof Map,N=function(){function e(){B(this,e),this.elements={},this.keyOrder=[]}return z(e,[{key:"forEach",value:function(){return function(e){for(var t=0;t<this.keyOrder.length;t++)e(this.elements[this.keyOrder[t]],this.keyOrder[t])}}()},{key:"set",value:function(){return function(t,r,n){if(this.elements.hasOwnProperty(t)){if(n){var i=this.keyOrder.indexOf(t);this.keyOrder.splice(i,1),this.keyOrder.push(t)}}else this.keyOrder.push(t);if(null!=r){if(G&&r instanceof Map||r instanceof e){var o=this.elements.hasOwnProperty(t)?this.elements[t]:new e;return r.forEach(function(e,t){o.set(t,e,n)}),void(this.elements[t]=o)}if(Array.isArray(r)||"object"!==(void 0===r?"undefined":_(r)))this.elements[t]=r;else{for(var a=this.elements.hasOwnProperty(t)?this.elements[t]:new e,s=Object.keys(r),u=0;u<s.length;u+=1)a.set(s[u],r[s[u]],n);this.elements[t]=a}}else this.elements[t]=r}}()},{key:"get",value:function(){return function(e){return this.elements[e]}}()},{key:"has",value:function(){return function(e){return this.elements.hasOwnProperty(e)}}()},{key:"addStyleType",value:function(){return function(t){var r=this;if(G&&t instanceof Map||t instanceof e)t.forEach(function(e,t){r.set(t,e,!0)});else for(var n=Object.keys(t),i=0;i<n.length;i++)this.set(n[i],t[n[i]],!0)}}()}]),e}(),L=/([A-Z])/g,U=function(e){return"-"+String(e.toLowerCase())},H=function(e){var t=e.replace(L,U);return"m"===t[0]&&"s"===t[1]&&"-"===t[2]?"-"+String(t):t},J={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0};function X(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var Y=["Webkit","ms","Moz","O"];Object.keys(J).forEach(function(e){Y.forEach(function(t){J[X(t,e)]=J[e]})});var Z=function(e,t){return"number"==typeof t?J[e]?""+t:t+"px":""+t},K=function(e,t){return $(Z(e,t))},V=function(e,t){return(0,A.default)(e).toString(36)},Q=function(e){return V(JSON.stringify(e))},$=function(e){return"!"===e[e.length-10]&&" !important"===e.slice(-11)?e:String(e)+" !important"};function ee(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}var te=(0,j.default)(D),re=[function(){return function(e,t,r){return":"!==e[0]?null:r(t+e)}}(),function(){return function(e,t,r){if("@"!==e[0])return null;var n=r(t);return[String(e)+"{"+String(n.join(""))+"}"]}}()],ne=function e(t,r,n,i,o){for(var a=new N,s=0;s<r.length;s++)a.addStyleType(r[s]);var u=new N,l=[];a.forEach(function(r,a){n.some(function(s){var u=s(a,t,function(t){return e(t,[r],n,i,o)});if(null!=u)return Array.isArray(u)?l.push.apply(l,ee(u)):(console.warn("WARNING: Selector handlers should return an array of rules.Returning a string containing multiple rules is deprecated.",s),l.push("@media all {"+String(u)+"}")),!0})||u.set(a,r,!0)});var f=se(t,u,i,o,n);return f&&l.unshift(f),l},ie=function(e,t,r){if(t)for(var n=Object.keys(t),i=0;i<n.length;i++){var o=n[i];e.has(o)&&e.set(o,t[o](e.get(o),r),!1)}},oe=function(e,t,r){return String(H(e))+":"+String(r(e,t))+";"},ae=function(e,t){return e[t]=!0,e},se=function(e,t,r,n,i){ie(t,r,i);var o=Object.keys(t.elements).reduce(ae,Object.create(null)),a=te(t.elements),s=Object.keys(a);if(s.length!==t.keyOrder.length)for(var u=0;u<s.length;u++)if(!o[s[u]]){var l=void 0;if((l="W"===s[u][0]?s[u][6].toLowerCase()+s[u].slice(7):"o"===s[u][1]?s[u][3].toLowerCase()+s[u].slice(4):s[u][2].toLowerCase()+s[u].slice(3))&&o[l]){var f=t.keyOrder.indexOf(l);t.keyOrder.splice(f,0,s[u])}else t.keyOrder.unshift(s[u])}for(var c=!1===n?Z:K,y=[],p=0;p<t.keyOrder.length;p++){var d=t.keyOrder[p],m=a[d];if(Array.isArray(m))for(var h=0;h<m.length;h++)y.push(oe(d,m[h],c));else y.push(oe(d,m,c))}return y.length?String(e)+"{"+String(y.join(""))+"}":""},ue="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function le(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}var fe=null,ce=function(e){if(null==fe&&null==(fe=document.querySelector("style[data-aphrodite]"))){var t=document.head||document.getElementsByTagName("head")[0];(fe=document.createElement("style")).type="text/css",fe.setAttribute("data-aphrodite",""),t.appendChild(fe)}var r=fe.styleSheet||fe.sheet;if(r.insertRule){var n=r.cssRules.length;e.forEach(function(e){try{r.insertRule(e,n),n+=1}catch(e){}})}else fe.innerText=(fe.innerText||"")+e.join("")},ye={fontFamily:function(){return function e(t){return Array.isArray(t)?t.map(e).join(","):"object"===(void 0===t?"undefined":ue(t))?(ge(t.src,"@font-face",[t],!1),'"'+String(t.fontFamily)+'"'):t}}(),animationName:function(){return function e(t,r){if(Array.isArray(t))return t.map(function(t){return e(t,r)}).join(",");if("object"===(void 0===t?"undefined":ue(t))){var n="keyframe_"+String(Q(t)),i="@keyframes "+n+"{";return t instanceof N?t.forEach(function(e,t){i+=ne(t,[e],r,ye,!1).join("")}):Object.keys(t).forEach(function(e){i+=ne(e,[t[e]],r,ye,!1).join("")}),he(n,[i+="}"]),n}return t}}()},pe={},de=[],me=!1,he=function(e,t){var r;if(!pe[e]){if(!me){if("undefined"==typeof document)throw new Error("Cannot automatically buffer without a document");me=!0,(0,E.default)(Oe)}(r=de).push.apply(r,le(t)),pe[e]=!0}},ge=function(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[];if(!pe[e]){var o=ne(t,r,i,ye,n);he(e,o)}},Se=function(){de=[],pe={},me=!1,fe=null},ve=function(){return de},xe=function(){if(me)throw new Error("Cannot buffer while already buffering");me=!0},be=function(){me=!1;var e=de;return de=[],e},ke=function(){return be().join("")},Oe=function(){var e=be();e.length>0&&ce(e)},we=function(){return Object.keys(pe)},Ae=function(e){e.forEach(function(e){pe[e]=!0})},Ce=function e(t,r,n,i){for(var o=0;o<t.length;o+=1)t[o]&&(Array.isArray(t[o])?i+=e(t[o],r,n,i):(r.push(t[o]._name),n.push(t[o]._definition),i+=t[o]._len));return i},je=function(e,t,r){var n=[],i=[],o=Ce(t,n,i,0);if(0===n.length)return"";var a=void 0;return a=1===n.length?"_"+String(n[0]):"_"+String(V(n.join()))+String((o%36).toString(36)),ge(a,"."+String(a),i,e,r),a},Te=function(e,t){return String(t)+"_"+String(V(e))},Ee=function(){return V},Ie=Ee(),Re={create:function(){return function(e){for(var t={},r=Object.keys(e),n=0;n<r.length;n+=1){var i=r[n],o=e[i],a=JSON.stringify(o);t[i]={_len:a.length,_name:Ie(a,i),_definition:o}}return t}}(),rehydrate:function(){return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];Ae(e)}}()},Me="undefined"!=typeof window?null:{renderStatic:function(){return function(e){return Se(),xe(),{html:e(),css:{content:ke(),renderedClassNames:we()}}}}()},qe=null;function Fe(e,t){return{StyleSheet:Object.assign({},Re,{extend:function(){return function(r){var n=r.map(function(e){return e.selectorHandler}).filter(function(e){return e});return Fe(e,t.concat(n))}}()}),StyleSheetServer:Me,StyleSheetTestUtils:qe,minify:function(){return function(e){Ie=e?V:Te}}(),css:function(){return function(){for(var r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];return je(e,n,t)}}()}}var Pe=!0,We=Fe(Pe,re),De=We.StyleSheet,_e=We.StyleSheetServer,ze=We.StyleSheetTestUtils,Be=We.css,Ge=We.minify;exports.StyleSheet=De,exports.StyleSheetServer=_e,exports.StyleSheetTestUtils=ze,exports.css=Be,exports.minify=Ge,exports.flushToStyleTag=Oe;
},{"inline-style-prefixer/static/plugins/calc":123,"inline-style-prefixer/static/plugins/crossFade":124,"inline-style-prefixer/static/plugins/cursor":125,"inline-style-prefixer/static/plugins/filter":126,"inline-style-prefixer/static/plugins/flex":127,"inline-style-prefixer/static/plugins/flexboxIE":128,"inline-style-prefixer/static/plugins/flexboxOld":129,"inline-style-prefixer/static/plugins/gradient":130,"inline-style-prefixer/static/plugins/imageSet":131,"inline-style-prefixer/static/plugins/position":132,"inline-style-prefixer/static/plugins/sizing":133,"inline-style-prefixer/static/plugins/transition":134,"string-hash":144,"inline-style-prefixer/static/createPrefixer":135,"asap":136}],79:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.commonStyle=exports.ZIndex=exports.Duration=exports.Sizes=exports.Colors=exports.FontSize=exports.FontFamily=void 0;var o=require("aphrodite"),e=exports.FontFamily=void 0;!function(o){o.MONOSPACE='"Source Code Pro", Courier, monospace'}(e||(exports.FontFamily=e={}));var t=exports.FontSize=void 0;!function(o){o[o.LABEL=10]="LABEL",o[o.TITLE=12]="TITLE",o[o.BIG_BUTTON=36]="BIG_BUTTON"}(t||(exports.FontSize=t={}));var r=exports.Colors=void 0;!function(o){o.WHITE="#FFFFFF",o.OFF_WHITE="#F6F6F6",o.LIGHT_GRAY="#BDBDBD",o.GRAY="#666666",o.DARK_GRAY="#222222",o.BLACK="#000000",o.BRIGHT_BLUE="#56CCF2",o.DARK_BLUE="#2F80ED",o.PALE_DARK_BLUE="#8EB7ED",o.GREEN="#6FCF97",o.TRANSPARENT_GREEN="rgba(111, 207, 151, 0.2)"}(r||(exports.Colors=r={}));var T=exports.Sizes=void 0;!function(o){o[o.MINIMAP_HEIGHT=100]="MINIMAP_HEIGHT",o[o.DETAIL_VIEW_HEIGHT=150]="DETAIL_VIEW_HEIGHT",o[o.TOOLTIP_WIDTH_MAX=900]="TOOLTIP_WIDTH_MAX",o[o.TOOLTIP_HEIGHT_MAX=80]="TOOLTIP_HEIGHT_MAX",o[o.SEPARATOR_HEIGHT=2]="SEPARATOR_HEIGHT",o[o.FRAME_HEIGHT=20]="FRAME_HEIGHT",o[o.TOOLBAR_HEIGHT=20]="TOOLBAR_HEIGHT",o[o.TOOLBAR_TAB_HEIGHT=18]="TOOLBAR_TAB_HEIGHT"}(T||(exports.Sizes=T={}));var i=exports.Duration=void 0;!function(o){o.HOVER_CHANGE="0.07s"}(i||(exports.Duration=i={}));var E=exports.ZIndex=void 0;!function(o){o[o.HOVERTIP=1]="HOVERTIP"}(E||(exports.ZIndex=E={}));const I=exports.commonStyle=o.StyleSheet.create({fillY:{height:"100%"},fillX:{width:"100%"},hbox:{display:"flex",flexDirection:"row",position:"relative",overflow:"hidden"},vbox:{display:"flex",flexDirection:"column",position:"relative",overflow:"hidden"}});
},{"aphrodite":68}],106:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ColorChit=void 0;var e=require("preact"),t=require("aphrodite"),r=require("./style");class o extends e.Component{render(){return(0,e.h)("span",{className:(0,t.css)(i.stackChit),style:{backgroundColor:this.props.color}})}}exports.ColorChit=o;const i=t.StyleSheet.create({stackChit:{position:"relative",top:-1,display:"inline-block",verticalAlign:"middle",marginRight:"0.5em",border:`1px solid ${r.Colors.LIGHT_GRAY}`,width:r.FontSize.LABEL-2,height:r.FontSize.LABEL-2}});
},{"preact":24,"aphrodite":68,"./style":79}],108:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ScrollableListView=void 0;var e=require("preact");class i extends e.Component{constructor(e){super(e),this.viewport=null,this.viewportRef=(e=>{this.viewport=e||null}),this.pendingScroll=0,this.onWindowResize=(()=>{this.recomputeVisibleIndices(this.props)}),this.onViewportScroll=(e=>{this.recomputeVisibleIndices(this.props)}),this.state={firstVisibleIndex:null,lastVisibleIndex:null,invisiblePrefixSize:null,viewportSize:null,cachedTotalSize:e.items.reduce((e,i)=>e+i.size,0)}}recomputeVisibleIndices(e){if(!this.viewport)return;const{items:i}=e,t=this.viewport.getBoundingClientRect().height,s=this.viewport.scrollTop-t/4,o=this.viewport.scrollTop+t+t/4;let l=0,r=0,n=0;for(;n<i.length;n++){if(r=l,(l+=i[n].size)>=s)break}const p=n;for(;n<i.length;n++){if((l+=i[n].size)>=o)break}const c=Math.min(n,i.length-1);this.setState({invisiblePrefixSize:r,firstVisibleIndex:p,lastVisibleIndex:c})}scrollIndexIntoView(e){this.pendingScroll=this.props.items.reduce((i,t,s)=>s>=e?i:i+t.size,0)}applyPendingScroll(){if(!this.viewport)return;const e="y"===this.props.axis?"top":"left";this.viewport.scrollTo({[e]:this.pendingScroll})}componentWillReceiveProps(e){this.props.items!==e.items&&this.recomputeVisibleIndices(e)}componentDidMount(){this.applyPendingScroll(),this.recomputeVisibleIndices(this.props),window.addEventListener("resize",this.onWindowResize)}componentWillUnmount(){window.removeEventListener("resize",this.onWindowResize)}render(){const{cachedTotalSize:i,firstVisibleIndex:t,lastVisibleIndex:s,invisiblePrefixSize:o}=this.state;return(0,e.h)("div",{className:this.props.className,ref:this.viewportRef,onScroll:this.onViewportScroll},(0,e.h)("div",{style:{height:i}},(0,e.h)("div",{style:{transform:`translateY(${o}px)`}},null!=t&&null!=s&&this.props.renderItems(t,s))))}}exports.ScrollableListView=i;
},{"preact":24}],117:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class t{constructor(t){this.data=t,this.prev=null,this.next=null}}class e{constructor(){this.head=null,this.tail=null,this.size=0}getHead(){return this.head}getTail(){return this.tail}getSize(){return this.size}append(t){this.tail?(this.tail.next=t,t.prev=this.tail,this.tail=t):this.head=this.tail=t,this.size++}prepend(t){return this.head?(this.head.prev=t,t.next=this.head,this.head=t):this.head=this.tail=t,this.size++,t}pop(){if(this.tail){const t=this.tail;return t.prev?(this.tail=t.prev,this.tail.next=null):this.head=this.tail=null,this.size--,t.prev=null,t}return null}dequeue(){if(this.head){const t=this.head;return t.next?(this.head=t.next,this.head.prev=null):this.head=this.tail=null,this.size--,t.next=null,t}return null}remove(t){null==t.prev?this.dequeue():null==t.next?this.pop():(t.next.prev=t.prev,t.prev.next=t.next,t.next=null,t.prev=null,this.size--)}}exports.List=e;class i{constructor(t){this.capacity=t,this.list=new e,this.map=new Map}has(t){return this.map.has(t)}get(t){const e=this.map.get(t);return e?(this.list.remove(e.listNode),this.list.prepend(e.listNode),e?e.value:null):null}getSize(){return this.list.getSize()}getCapacity(){return this.capacity}insert(e,i){const s=this.map.get(e);for(s&&this.list.remove(s.listNode);this.list.getSize()>=this.capacity;)this.map.delete(this.list.pop().data);const h=this.list.prepend(new t(e));this.map.set(e,{value:i,listNode:h})}getOrInsert(t,e){let i=this.get(t);return null==i&&(i=e(t),this.insert(t,i)),i}removeLRU(){const t=this.list.pop();if(!t)return null;const e=t.data,i=this.map.get(e).value;return this.map.delete(e),[e,i]}clear(){this.list=new e,this.map=new Map}}exports.LRUCache=i;
},{}],96:[function(require,module,exports) {
var t,e,n=module.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(t===setTimeout)return setTimeout(e,0);if((t===r||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}function u(t){if(e===clearTimeout)return clearTimeout(t);if((e===o||!e)&&clearTimeout)return e=clearTimeout,clearTimeout(t);try{return e(t)}catch(n){try{return e.call(null,t)}catch(n){return e.call(this,t)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:r}catch(e){t=r}try{e="function"==typeof clearTimeout?clearTimeout:o}catch(t){e=o}}();var c,s=[],l=!1,a=-1;function f(){l&&c&&(l=!1,c.length?s=c.concat(s):a=-1,s.length&&h())}function h(){if(!l){var t=i(f);l=!0;for(var e=s.length;e;){for(c=s,s=[];++a<e;)c&&c[a].run();a=-1,e=s.length}c=null,l=!1,u(t)}}function m(t,e){this.fun=t,this.array=e}function p(){}n.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];s.push(new m(t,e)),1!==s.length||l||i(h)},m.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=p,n.addListener=p,n.once=p,n.off=p,n.removeListener=p,n.removeAllListeners=p,n.emit=p,n.prependListener=p,n.prependOnceListener=p,n.listeners=function(t){return[]},n.binding=function(t){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(t){throw new Error("process.chdir is not supported")},n.umask=function(){return 0};
},{}],42:[function(require,module,exports) {
var process = require("process");
var t=require("process");Object.defineProperty(exports,"__esModule",{value:!0});const e=void 0!==t&&t.env&&!0;function i(t){if(!e&&!t)throw new Error("Assertion failed.")}function r(t,e){-1===t.indexOf(e)&&t.push(e)}function s(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}function n(t,e){return i(e>=0&&e<=31),t.TEXTURE0+e}var h=exports.Graphics=void 0;!function(t){t.Rect=class{constructor(t=0,e=0,i=0,r=0){this.x=t,this.y=e,this.width=i,this.height=r}set(t,e,i,r){this.x=t,this.y=e,this.width=i,this.height=r}equals(t){return this.x===t.x&&this.y===t.y&&this.width===t.width&&this.height===t.height}};class e{constructor(t,e,i,r){this.redF=t,this.greenF=e,this.blueF=i,this.alphaF=r}}let i,r,s,n,h;e.TRANSPARENT=new e(0,0,0,0),t.Color=e,function(t){t[t.ZERO=0]="ZERO",t[t.ONE=1]="ONE",t[t.SOURCE_COLOR=2]="SOURCE_COLOR",t[t.TARGET_COLOR=3]="TARGET_COLOR",t[t.INVERSE_SOURCE_COLOR=4]="INVERSE_SOURCE_COLOR",t[t.INVERSE_TARGET_COLOR=5]="INVERSE_TARGET_COLOR",t[t.SOURCE_ALPHA=6]="SOURCE_ALPHA",t[t.TARGET_ALPHA=7]="TARGET_ALPHA",t[t.INVERSE_SOURCE_ALPHA=8]="INVERSE_SOURCE_ALPHA",t[t.INVERSE_TARGET_ALPHA=9]="INVERSE_TARGET_ALPHA",t[t.CONSTANT=10]="CONSTANT",t[t.INVERSE_CONSTANT=11]="INVERSE_CONSTANT"}(i=t.BlendOperation||(t.BlendOperation={})),function(t){t[t.TRIANGLES=0]="TRIANGLES",t[t.TRIANGLE_STRIP=1]="TRIANGLE_STRIP"}(r=t.Primitive||(t.Primitive={}));function a(t){return t==s.FLOAT?4:1}t.Context=class{setCopyBlendState(){this.setBlendState(i.ONE,i.ZERO)}setAddBlendState(){this.setBlendState(i.ONE,i.ONE)}setPremultipliedBlendState(){this.setBlendState(i.ONE,i.INVERSE_SOURCE_ALPHA)}setUnpremultipliedBlendState(){this.setBlendState(i.SOURCE_ALPHA,i.INVERSE_SOURCE_ALPHA)}},function(t){t[t.FLOAT=0]="FLOAT",t[t.BYTE=1]="BYTE"}(s=t.AttributeType||(t.AttributeType={})),t.attributeByteLength=a;class _{constructor(t,e,i,r){this.name=t,this.type=e,this.count=i,this.byteOffset=r}}t.Attribute=_;t.VertexFormat=class{constructor(){this._attributes=[],this._stride=0}get attributes(){return this._attributes}get stride(){return this._stride}add(t,e,i){return this.attributes.push(new _(t,e,i,this.stride)),this._stride+=i*a(e),this}};t.VertexBuffer=class{uploadFloat32Array(t){this.upload(new Uint8Array(t.buffer),0)}uploadFloats(t){this.uploadFloat32Array(new Float32Array(t))}},function(t){t[t.NEAREST=0]="NEAREST",t[t.LINEAR=1]="LINEAR"}(n=t.PixelFilter||(t.PixelFilter={})),function(t){t[t.REPEAT=0]="REPEAT",t[t.CLAMP=1]="CLAMP"}(h=t.PixelWrap||(t.PixelWrap={}));class o{constructor(t,e,i){this.minFilter=t,this.magFilter=e,this.wrap=i}}o.LINEAR_CLAMP=new o(n.LINEAR,n.LINEAR,h.CLAMP),o.LINEAR_MIN_NEAREST_MAG_CLAMP=new o(n.LINEAR,n.NEAREST,h.CLAMP),o.NEAREST_CLAMP=new o(n.NEAREST,n.NEAREST,h.CLAMP),t.TextureFormat=o}(h||(exports.Graphics=h={}));var a=exports.WebGL=void 0;!function(t){class a extends h.Context{constructor(t=document.createElement("canvas")){super(),this._attributeCount=0,this._blendOperations=0,this._contextResetHandlers=[],this._currentClearColor=h.Color.TRANSPARENT,this._currentRenderTarget=null,this._defaultViewport=new h.Rect,this._forceStateUpdate=!0,this._generation=1,this._height=0,this._oldBlendOperations=0,this._oldRenderTarget=null,this._oldViewport=new h.Rect,this._width=0,this.handleWebglContextRestored=(()=>{this._attributeCount=0,this._currentClearColor=h.Color.TRANSPARENT,this._forceStateUpdate=!0,this._generation++;for(let t of this._contextResetHandlers)t()}),this.ANGLE_instanced_arrays=null,this.ANGLE_instanced_arrays_generation=-1;let e=t.getContext("webgl",{alpha:!1,antialias:!1,depth:!1,preserveDrawingBuffer:!1,stencil:!1});if(null==e)throw new Error("Setup failure");this._gl=e;let i=t.style;t.width=0,t.height=0,i.width=i.height="0",t.addEventListener("webglcontextlost",t=>{t.preventDefault()}),t.addEventListener("webglcontextrestored",this.handleWebglContextRestored),this._blendOperationMap={[h.BlendOperation.ZERO]:this._gl.ZERO,[h.BlendOperation.ONE]:this._gl.ONE,[h.BlendOperation.SOURCE_COLOR]:this._gl.SRC_COLOR,[h.BlendOperation.TARGET_COLOR]:this._gl.DST_COLOR,[h.BlendOperation.INVERSE_SOURCE_COLOR]:this._gl.ONE_MINUS_SRC_COLOR,[h.BlendOperation.INVERSE_TARGET_COLOR]:this._gl.ONE_MINUS_DST_COLOR,[h.BlendOperation.SOURCE_ALPHA]:this._gl.SRC_ALPHA,[h.BlendOperation.TARGET_ALPHA]:this._gl.DST_ALPHA,[h.BlendOperation.INVERSE_SOURCE_ALPHA]:this._gl.ONE_MINUS_SRC_ALPHA,[h.BlendOperation.INVERSE_TARGET_ALPHA]:this._gl.ONE_MINUS_DST_ALPHA,[h.BlendOperation.CONSTANT]:this._gl.CONSTANT_COLOR,[h.BlendOperation.INVERSE_CONSTANT]:this._gl.ONE_MINUS_CONSTANT_COLOR}}get widthInPixels(){return this._width}get heightInPixels(){return this._height}testContextLoss(){this.handleWebglContextRestored()}get gl(){return this._gl}get generation(){return this._generation}addContextResetHandler(t){r(this._contextResetHandlers,t)}removeContextResetHandler(t){s(this._contextResetHandlers,t)}get currentRenderTarget(){return this._currentRenderTarget}beginFrame(){this.setRenderTarget(null)}endFrame(){}setBlendState(t,e){this._blendOperations=a._packBlendModes(t,e)}setViewport(t,e,i,r){(null!=this._currentRenderTarget?this._currentRenderTarget.viewport:this._defaultViewport).set(t,e,i,r)}get viewport(){return null!=this._currentRenderTarget?this._currentRenderTarget.viewport:this._defaultViewport}get renderTargetWidthInPixels(){return null!=this._currentRenderTarget?this._currentRenderTarget.viewport.width:this._width}get renderTargetHeightInPixels(){return null!=this._currentRenderTarget?this._currentRenderTarget.viewport.height:this._height}draw(t,e,i){this._updateRenderTargetAndViewport(),f.from(e).prepare(),R.from(i).prepare(),this._updateFormat(e.format),this._updateBlendState(),this._gl.drawArrays(t==h.Primitive.TRIANGLES?this._gl.TRIANGLES:this._gl.TRIANGLE_STRIP,0,Math.floor(i.byteCount/e.format.stride)),this._forceStateUpdate=!1}resize(t,e,i,r){let s=this._gl.canvas;const n=s.getBoundingClientRect();if(this._width===i&&this._height===e&&n.width===i&&n.height===r)return;let h=s.style;s.width=t,s.height=e,h.width=`${i}px`,h.height=`${r}px`,this.setViewport(0,0,t,e),this._width=t,this._height=e}clear(t){this._updateRenderTargetAndViewport(),this._updateBlendState(),t!=this._currentClearColor&&(this._gl.clearColor(t.redF,t.greenF,t.blueF,t.alphaF),this._currentClearColor=t),this._gl.clear(this._gl.COLOR_BUFFER_BIT)}setRenderTarget(t){this._currentRenderTarget=A.from(t)}createMaterial(t,e,i){let r=new f(this,t,e,i);return r.program,r}createVertexBuffer(t){return i(t>0&&t%4==0),new R(this,t)}createTexture(t,e,i,r){return new p(this,t,e,i,r)}createRenderTarget(t){return new A(this,p.from(t))}getANGLE_instanced_arrays(){if(this.ANGLE_instanced_arrays_generation!==this._generation&&(this.ANGLE_instanced_arrays=null),!this.ANGLE_instanced_arrays&&(this.ANGLE_instanced_arrays=this.gl.getExtension("ANGLE_instanced_arrays"),!this.ANGLE_instanced_arrays))throw new Error("Failed to get extension ANGLE_instanced_arrays");return this.ANGLE_instanced_arrays}_updateRenderTargetAndViewport(){let t=this._currentRenderTarget,e=null!=t?t.viewport:this._defaultViewport,i=this._gl;(this._forceStateUpdate||this._oldRenderTarget!=t)&&(i.bindFramebuffer(i.FRAMEBUFFER,t?t.framebuffer:null),this._oldRenderTarget=t),!this._forceStateUpdate&&this._oldViewport.equals(e)||(i.viewport(e.x,this.renderTargetHeightInPixels-e.y-e.height,e.width,e.height),this._oldViewport.set(e.x,e.y,e.width,e.height))}_updateBlendState(){if(this._forceStateUpdate||this._oldBlendOperations!=this._blendOperations){let t=this._gl,e=this._blendOperations,r=this._oldBlendOperations,s=15&e,n=e>>4;i(s in this._blendOperationMap),i(n in this._blendOperationMap),e==a.COPY_BLEND_OPERATIONS?t.disable(t.BLEND):((this._forceStateUpdate||r==a.COPY_BLEND_OPERATIONS)&&t.enable(t.BLEND),t.blendFunc(this._blendOperationMap[s],this._blendOperationMap[n])),this._oldBlendOperations=e}}_updateFormat(t){let e=this._gl,i=t.attributes,r=i.length;for(let s=0;s<r;s++){let r=i[s],n=r.type==h.AttributeType.BYTE;e.vertexAttribPointer(s,r.count,n?e.UNSIGNED_BYTE:e.FLOAT,n,t.stride,r.byteOffset)}for(;this._attributeCount<r;)e.enableVertexAttribArray(this._attributeCount),this._attributeCount++;for(;this._attributeCount>r;)this._attributeCount--,e.disableVertexAttribArray(this._attributeCount);this._attributeCount=r}getWebGLInfo(){const t=this.gl.getExtension("WEBGL_debug_renderer_info");return{renderer:t?this.gl.getParameter(t.UNMASKED_RENDERER_WEBGL):null,vendor:t?this.gl.getParameter(t.UNMASKED_VENDOR_WEBGL):null,version:this.gl.getParameter(this.gl.VERSION)}}static from(t){return i(null==t||t instanceof a),t}static _packBlendModes(t,e){return t|e<<4}}a.COPY_BLEND_OPERATIONS=a._packBlendModes(h.BlendOperation.ONE,h.BlendOperation.ZERO),t.Context=a;class _{constructor(t,e,i=0,r=null,s=!0){this._material=t,this._name=e,this._generation=i,this._location=r,this._isDirty=s}get location(){let t=a.from(this._material.context);if(this._generation!=t.generation&&(this._location=t.gl.getUniformLocation(this._material.program,this._name),this._generation=t.generation,!e)){let e=this._material.program,r=t.gl;for(let t=0,s=r.getProgramParameter(e,r.ACTIVE_UNIFORMS);t<s;t++){let s=r.getActiveUniform(e,t);if(s&&s.name==this._name)switch(i(1==s.size),s.type){case r.FLOAT:i(this instanceof o);break;case r.FLOAT_MAT3:i(this instanceof g);break;case r.FLOAT_VEC2:i(this instanceof u);break;case r.FLOAT_VEC3:i(this instanceof c);break;case r.FLOAT_VEC4:i(this instanceof d);break;case r.INT:i(this instanceof l);break;case r.SAMPLER_2D:i(this instanceof E);break;default:i(!1)}}}if(!this._location)throw new Error("Failed to get uniform location");return this._location}}class o extends _{constructor(){super(...arguments),this._x=0}set(t){t!=this._x&&(this._x=t,this._isDirty=!0)}prepare(){let t=a.from(this._material.context);(this._generation!=t.generation||this._isDirty)&&(t.gl.uniform1f(this.location,this._x),this._isDirty=!1)}}class l extends _{constructor(){super(...arguments),this._x=0}set(t){t!=this._x&&(this._x=t,this._isDirty=!0)}prepare(){let t=a.from(this._material.context);(this._generation!=t.generation||this._isDirty)&&(t.gl.uniform1i(this.location,this._x),this._isDirty=!1)}}class u extends _{constructor(){super(...arguments),this._x=0,this._y=0}set(t,e){t==this._x&&e==this._y||(this._x=t,this._y=e,this._isDirty=!0)}prepare(){let t=a.from(this._material.context);(this._generation!=t.generation||this._isDirty)&&(t.gl.uniform2f(this.location,this._x,this._y),this._isDirty=!1)}}class c extends _{constructor(){super(...arguments),this._x=0,this._y=0,this._z=0}set(t,e,i){t==this._x&&e==this._y&&i==this._z||(this._x=t,this._y=e,this._z=i,this._isDirty=!0)}prepare(){let t=a.from(this._material.context);(this._generation!=t.generation||this._isDirty)&&(t.gl.uniform3f(this.location,this._x,this._y,this._z),this._isDirty=!1)}}class d extends _{constructor(){super(...arguments),this._x=0,this._y=0,this._z=0,this._w=0}set(t,e,i,r){t==this._x&&e==this._y&&i==this._z&&r==this._w||(this._x=t,this._y=e,this._z=i,this._w=r,this._isDirty=!0)}prepare(){let t=a.from(this._material.context);(this._generation!=t.generation||this._isDirty)&&(t.gl.uniform4f(this.location,this._x,this._y,this._z,this._w),this._isDirty=!1)}}class g extends _{constructor(){super(...arguments),this._values=[1,0,0,0,1,0,0,0,1]}set(t,e,i,r,s,n,h,a,_){g._cachedValues[0]=t,g._cachedValues[1]=r,g._cachedValues[2]=h,g._cachedValues[3]=e,g._cachedValues[4]=s,g._cachedValues[5]=a,g._cachedValues[6]=i,g._cachedValues[7]=n,g._cachedValues[8]=_;for(let t=0;t<9;t++)if(g._cachedValues[t]!=this._values[t]){let t=this._values;this._values=g._cachedValues,g._cachedValues=t,this._isDirty=!0;break}}prepare(){let t=a.from(this._material.context);(this._generation!=t.generation||this._isDirty)&&(t.gl.uniformMatrix3fv(this.location,!1,this._values),this._isDirty=!1)}}g._cachedValues=[1,0,0,0,1,0,0,0,1];class E extends _{constructor(){super(...arguments),this._texture=null,this._index=-1}set(t,e){this._texture==t&&this._index==e||(this._texture=p.from(t),this._index=e,this._isDirty=!0)}prepare(){let t=a.from(this._material.context),e=t.gl;i(null==this._texture||null==t.currentRenderTarget||this._texture!=t.currentRenderTarget.texture),(this._generation!=t.generation||this._isDirty)&&(e.uniform1i(this.location,this._index),this._isDirty=!1),e.activeTexture(n(e,this._index)),e.bindTexture(e.TEXTURE_2D,null!=this._texture&&this._texture.width>0&&this._texture.height>0?this._texture.texture:null)}}class f{constructor(t,e,i,r,s={},n=[],h=0,a=null){this._context=t,this._format=e,this._vertexSource=i,this._fragmentSource=r,this._uniformsMap=s,this._uniformsList=n,this._generation=h,this._program=a}get context(){return this._context}get format(){return this._format}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}setUniformFloat(t,e){let r=this._uniformsMap[t]||null;null==r&&(r=new o(this,t),this._uniformsMap[t]=r,this._uniformsList.push(r)),i(r instanceof o),r.set(e)}setUniformInt(t,e){let r=this._uniformsMap[t]||null;null==r&&(r=new l(this,t),this._uniformsMap[t]=r,this._uniformsList.push(r)),i(r instanceof l),r.set(e)}setUniformVec2(t,e,r){let s=this._uniformsMap[t]||null;null==s&&(s=new u(this,t),this._uniformsMap[t]=s,this._uniformsList.push(s)),i(s instanceof u),s.set(e,r)}setUniformVec3(t,e,r,s){let n=this._uniformsMap[t]||null;null==n&&(n=new c(this,t),this._uniformsMap[t]=n,this._uniformsList.push(n)),i(n instanceof c),n.set(e,r,s)}setUniformVec4(t,e,r,s,n){let h=this._uniformsMap[t]||null;null==h&&(h=new d(this,t),this._uniformsMap[t]=h,this._uniformsList.push(h)),i(h instanceof d),h.set(e,r,s,n)}setUniformMat3(t,e,r,s,n,h,a,_,o,l){let u=this._uniformsMap[t]||null;null==u&&(u=new g(this,t),this._uniformsMap[t]=u,this._uniformsList.push(u)),i(u instanceof g),u.set(e,r,s,n,h,a,_,o,l)}setUniformSampler(t,e,r){let s=this._uniformsMap[t]||null;null==s&&(s=new E(this,t),this._uniformsMap[t]=s,this._uniformsList.push(s)),i(s instanceof E),s.set(e,r)}get program(){let t=this._context.gl;if(this._generation!=this._context.generation){this._program=t.createProgram(),this._compileShader(t,t.VERTEX_SHADER,this.vertexSource),this._compileShader(t,t.FRAGMENT_SHADER,this.fragmentSource);let r=this.format.attributes;for(let e=0;e<r.length;e++)t.bindAttribLocation(this._program,e,r[e].name);if(t.linkProgram(this._program),!t.getProgramParameter(this._program,t.LINK_STATUS))throw new Error(`${t.getProgramInfoLog(this._program)}`);if(this._generation=this._context.generation,!e)for(let e of r)for(let r=0,s=t.getProgramParameter(this.program,t.ACTIVE_ATTRIBUTES);r<s;r++){let s=t.getActiveAttrib(this.program,r);if(s&&s.name==e.name)switch(i(1==s.size),e.count){case 1:i(s.type==t.FLOAT);break;case 2:i(s.type==t.FLOAT_VEC2);break;case 3:i(s.type==t.FLOAT_VEC3);break;case 4:i(s.type==t.FLOAT_VEC4);break;default:i(!1)}}}return this._program}prepare(){this._context.gl.useProgram(this.program);for(let t of this._uniformsList)t.prepare()}_compileShader(t,e,i){let r=t.createShader(e);if(!r)throw new Error("Failed to create shader");if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error(`${t.getShaderInfoLog(r)}`);if(!this._program)throw new Error("Tried to attach shader before program was created");t.attachShader(this._program,r)}static from(t){return i(null==t||t instanceof f),t}}class R extends h.VertexBuffer{constructor(t,e){super(),this._generation=0,this._buffer=null,this._bytes=null,this._isDirty=!0,this._dirtyMin=R.INT_MAX,this._dirtyMax=0,this._totalMin=R.INT_MAX,this._totalMax=0,this._byteCount=0,this._context=t,this._byteCount=e,this._bytes=new Uint8Array(e)}get context(){return this._context}get byteCount(){return this._byteCount}move(t,e,r){i(r>=0),i(0<=t&&t+r<=this._byteCount),i(0<=e&&e+r<=this._byteCount),this._bytes&&t!=e&&0!=r&&(this._bytes.set(this._bytes.subarray(t,this._byteCount),e),this._growDirtyRegion(Math.min(t,e),Math.max(t,e)+r))}upload(t,e=0){i(0<=e&&e+t.length<=this._byteCount),i(null!=this._bytes),this._bytes.set(t,e),this._growDirtyRegion(e,e+t.length)}free(){this._buffer&&this._context.gl.deleteBuffer(this._buffer),this._generation=0}prepare(){let t=this._context.gl;this._generation!==this._context.generation&&(this._buffer=t.createBuffer(),this._generation=this._context.generation,this._isDirty=!0),t.bindBuffer(t.ARRAY_BUFFER,this._buffer),this._isDirty&&(t.bufferData(t.ARRAY_BUFFER,this._byteCount,t.DYNAMIC_DRAW),this._dirtyMin=this._totalMin,this._dirtyMax=this._totalMax,this._isDirty=!1),this._dirtyMin<this._dirtyMax&&(t.bufferSubData(t.ARRAY_BUFFER,this._dirtyMin,this._bytes.subarray(this._dirtyMin,this._dirtyMax)),this._dirtyMin=R.INT_MAX,this._dirtyMax=0)}_growDirtyRegion(t,e){this._dirtyMin=Math.min(this._dirtyMin,t),this._dirtyMax=Math.max(this._dirtyMax,e),this._totalMin=Math.min(this._totalMin,t),this._totalMax=Math.max(this._totalMax,e)}static from(t){return i(null==t||t instanceof R),t}}R.INT_MAX=2147483647;class p{constructor(t,e,i,r,s=null,n=null,h=0,a=!0,_=!0){this._context=t,this._format=e,this._width=i,this._height=r,this._pixels=s,this._texture=n,this._generation=h,this._isFormatDirty=a,this._isContentDirty=_}get context(){return this._context}get format(){return this._format}get width(){return this._width}get height(){return this._height}resize(t,e,i=null){this._width=t,this._height=e,this._pixels=i,this._isContentDirty=!0}setFormat(t){this._format!=t&&(this._format=t,this._isFormatDirty=!0)}get texture(){let t=this._context.gl;return this._generation!=this._context.generation&&(this._texture=t.createTexture(),this._generation=this._context.generation,this._isFormatDirty=!0,this._isContentDirty=!0),this._isFormatDirty&&(t.bindTexture(t.TEXTURE_2D,this._texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,this.format.magFilter==h.PixelFilter.NEAREST?t.NEAREST:t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,this.format.minFilter==h.PixelFilter.NEAREST?t.NEAREST:t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,this.format.wrap==h.PixelWrap.REPEAT?t.REPEAT:t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,this.format.wrap==h.PixelWrap.REPEAT?t.REPEAT:t.CLAMP_TO_EDGE),this._isFormatDirty=!1),this._isContentDirty&&(t.bindTexture(t.TEXTURE_2D,this._texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this._width,this._height,0,t.RGBA,t.UNSIGNED_BYTE,this._pixels),this._isContentDirty=!1),this._texture}free(){this.texture&&(this._context.gl.deleteTexture(this.texture),this._generation=0)}static from(t){return i(null==t||t instanceof p),t}}class A{constructor(t,e,i=null,r=0,s=!0,n=new h.Rect){this._context=t,this._texture=e,this._framebuffer=i,this._generation=r,this._isDirty=s,this._viewport=n}get context(){return this._context}get texture(){return this._texture}get viewport(){return this._viewport}setColor(t){this._texture!=t&&(this._texture=p.from(t),this._isDirty=!0)}get framebuffer(){let t=this._context.gl,e=this._texture.texture;return this._generation!=this._context.generation&&(this._framebuffer=t.createFramebuffer(),this._generation=this._context.generation,this._isDirty=!0),this._isDirty&&(t.bindFramebuffer(t.FRAMEBUFFER,this._framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i(t.checkFramebufferStatus(t.FRAMEBUFFER)==t.FRAMEBUFFER_COMPLETE),this._isDirty=!1),this._framebuffer}free(){this._framebuffer&&(this._context.gl.deleteFramebuffer(this._framebuffer),this._generation=0)}static from(t){return i(null==t||t instanceof A),t}}}(a||(exports.WebGL=a={}));
},{"process":96}],119:[function(require,module,exports) {
"use strict";function e(e,t,r){let{m00:n,m01:o,m02:s,m10:i,m11:f,m12:m}=r;e.setUniformMat3(t,n,o,s,i,f,m,0,0,1)}function t(e,t,r){e.setUniformVec2(t,r.x,r.y)}function r(e,t,r){e.setRenderTarget(t),e.setViewport(0,0,t.texture.width,t.texture.height),r(),e.setRenderTarget(null)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.setUniformAffineTransform=e,exports.setUniformVec2=t,exports.renderInto=r;
},{}],118:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RectangleBatchRenderer=exports.RectangleBatch=void 0;var e=require("../lib/math"),t=require("./graphics"),r=require("./utils");const i=new t.Graphics.VertexFormat;i.add("configSpacePos",t.Graphics.AttributeType.FLOAT,2),i.add("color",t.Graphics.AttributeType.FLOAT,3);const s="\n uniform mat3 configSpaceToNDC;\n\n attribute vec2 configSpacePos;\n attribute vec3 color;\n varying vec3 vColor;\n\n void main() {\n vColor = color;\n vec2 position = (configSpaceToNDC * vec3(configSpacePos, 1)).xy;\n gl_Position = vec4(position, 1, 1);\n }\n",n="\n precision mediump float;\n varying vec3 vColor;\n\n void main() {\n gl_FragColor = vec4(vColor.rgb, 1);\n }\n";class o{constructor(e){this.gl=e,this.rects=[],this.colors=[],this.buffer=null}getRectCount(){return this.rects.length}getBuffer(){if(this.buffer)return this.buffer;const e=[[0,0],[1,0],[0,1],[1,0],[0,1],[1,1]],t=new Uint8Array(i.stride*e.length*this.rects.length),r=new Float32Array(t.buffer);let s=0;for(let t=0;t<this.rects.length;t++){const i=this.rects[t],n=this.colors[t];for(let t of e)r[s++]=i.origin.x+t[0]*i.size.x,r[s++]=i.origin.y+t[1]*i.size.y,r[s++]=n.r,r[s++]=n.g,r[s++]=n.b}if(s!==r.length)throw new Error("Buffer expected to be full but wasn't");return this.buffer=this.gl.createVertexBuffer(t.length),this.buffer.upload(t),this.buffer}addRect(e,t){this.rects.push(e),this.colors.push(t),this.buffer&&(this.buffer.free(),this.buffer=null)}free(){this.buffer&&(this.buffer.free(),this.buffer=null)}}exports.RectangleBatch=o;class c{constructor(e){this.gl=e,this.material=e.createMaterial(i,s,n)}render(i){(0,r.setUniformAffineTransform)(this.material,"configSpaceToNDC",(()=>{const t=e.AffineTransform.betweenRects(i.configSpaceSrcRect,i.physicalSpaceDstRect),r=new e.Vec2(this.gl.viewport.width,this.gl.viewport.height);return e.AffineTransform.withTranslation(new e.Vec2(-1,1)).times(e.AffineTransform.withScale(new e.Vec2(2,-2).dividedByPointwise(r))).times(t)})()),this.gl.setUnpremultipliedBlendState(),this.gl.draw(t.Graphics.Primitive.TRIANGLES,this.material,i.batch.getBuffer())}}exports.RectangleBatchRenderer=c;
},{"../lib/math":102,"./graphics":42,"./utils":119}],76:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Color=void 0;var t=require("./math");class r{constructor(t=0,r=0,e=0,o=1){this.r=t,this.g=r,this.b=e,this.a=o}static fromLumaChromaHue(e,o,s){const i=s/60,a=o*(1-Math.abs(i%2-1)),[h,c,u]=i<1?[o,a,0]:i<2?[a,o,0]:i<3?[0,o,a]:i<4?[0,a,o]:i<5?[a,0,o]:[o,0,a],l=e-(.3*h+.59*c+.11*u);return new r((0,t.clamp)(h+l,0,1),(0,t.clamp)(c+l,0,1),(0,t.clamp)(u+l,0,1),1)}toCSS(){return`rgba(${(255*this.r).toFixed()}, ${(255*this.g).toFixed()}, ${(255*this.b).toFixed()}, ${this.a.toFixed(2)})`}}exports.Color=r;
},{"./math":102}],72:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RowAtlas=void 0;var e=require("../lib/lru-cache"),t=require("./rectangle-batch-renderer"),r=require("../lib/math"),i=require("../lib/color"),c=require("./graphics"),h=require("./utils");class a{constructor(h,a,s){this.gl=h,this.rectangleBatchRenderer=a,this.textureRenderer=s,this.texture=h.createTexture(c.Graphics.TextureFormat.NEAREST_CLAMP,4096,4096),this.renderTarget=h.createRenderTarget(this.texture),this.rowCache=new e.LRUCache(this.texture.height),this.clearLineBatch=new t.RectangleBatch(h),this.clearLineBatch.addRect(r.Rect.unit,new i.Color(0,0,0,0)),h.addContextResetHandler(()=>{this.rowCache.clear()})}has(e){return this.rowCache.has(e)}getResolution(){return this.texture.width}getCapacity(){return this.texture.height}allocateLine(e){if(this.rowCache.getSize()<this.rowCache.getCapacity()){const t=this.rowCache.getSize();return this.rowCache.insert(e,t),t}{const[,t]=this.rowCache.removeLRU();return this.rowCache.insert(e,t),t}}writeToAtlasIfNeeded(e,t){(0,h.renderInto)(this.gl,this.renderTarget,()=>{for(let i of e){let e=this.rowCache.get(i);if(null!=e)continue;e=this.allocateLine(i);const c=new r.Rect(new r.Vec2(0,e),new r.Vec2(this.texture.width,1));this.rectangleBatchRenderer.render({batch:this.clearLineBatch,configSpaceSrcRect:r.Rect.unit,physicalSpaceDstRect:c}),t(c,i)}})}renderViaAtlas(e,t){let i=this.rowCache.get(e);if(null==i)return!1;const c=new r.Rect(new r.Vec2(0,i),new r.Vec2(this.texture.width,1));return this.textureRenderer.render({texture:this.texture,srcRect:c,dstRect:t}),!0}}exports.RowAtlas=a;
},{"../lib/lru-cache":117,"./rectangle-batch-renderer":118,"../lib/math":102,"../lib/color":76,"./graphics":42,"./utils":119}],120:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TextureRenderer=void 0;var e=require("../lib/math"),t=require("./graphics"),r=require("./utils");const n="\n uniform mat3 uvTransform;\n uniform mat3 positionTransform;\n\n attribute vec2 position;\n attribute vec2 uv;\n varying vec2 vUv;\n\n void main() {\n vUv = (uvTransform * vec3(uv, 1)).xy;\n gl_Position = vec4((positionTransform * vec3(position, 1)).xy, 0, 1);\n }\n",i="\n precision mediump float;\n\n varying vec2 vUv;\n uniform sampler2D texture;\n\n void main() {\n gl_FragColor = texture2D(texture, vUv);\n }\n";class s{constructor(e){this.gl=e;const r=new t.Graphics.VertexFormat;r.add("position",t.Graphics.AttributeType.FLOAT,2),r.add("uv",t.Graphics.AttributeType.FLOAT,2);const s=[{pos:[-1,1],uv:[0,1]},{pos:[1,1],uv:[1,1]},{pos:[-1,-1],uv:[0,0]},{pos:[1,-1],uv:[1,0]}],o=[];for(let e of s)o.push(e.pos[0]),o.push(e.pos[1]),o.push(e.uv[0]),o.push(e.uv[1]);this.buffer=e.createVertexBuffer(r.stride*s.length),this.buffer.upload(new Uint8Array(new Float32Array(o).buffer)),this.material=e.createMaterial(r,n,i)}render(n){this.material.setUniformSampler("texture",n.texture,0),(0,r.setUniformAffineTransform)(this.material,"uvTransform",(()=>{const{srcRect:t,texture:r}=n,i=e.AffineTransform.withTranslation(new e.Vec2(0,1)).times(e.AffineTransform.withScale(new e.Vec2(1,-1))).times(e.AffineTransform.betweenRects(new e.Rect(e.Vec2.zero,new e.Vec2(r.width,r.height)),e.Rect.unit)).transformRect(t);return e.AffineTransform.betweenRects(e.Rect.unit,i)})()),(0,r.setUniformAffineTransform)(this.material,"positionTransform",(()=>{const{dstRect:t}=n,{viewport:r}=this.gl,i=new e.Vec2(r.width,r.height),s=e.AffineTransform.withScale(new e.Vec2(1,-1)).times(e.AffineTransform.betweenRects(new e.Rect(e.Vec2.zero,i),e.Rect.NDC)).transformRect(t);return e.AffineTransform.betweenRects(e.Rect.NDC,s)})()),this.gl.setUnpremultipliedBlendState(),this.gl.draw(t.Graphics.Primitive.TRIANGLE_STRIP,this.material,this.buffer)}}exports.TextureRenderer=s;
},{"../lib/math":102,"./graphics":42,"./utils":119}],121:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ViewportRectangleRenderer=void 0;var e=require("./graphics"),i=require("./utils");const r=new e.Graphics.VertexFormat;r.add("position",e.Graphics.AttributeType.FLOAT,2);const o="\n attribute vec2 position;\n\n void main() {\n gl_Position = vec4(position, 0, 1);\n }\n",n="\n precision mediump float;\n\n uniform mat3 configSpaceToPhysicalViewSpace;\n uniform vec2 physicalSize;\n uniform vec2 physicalOrigin;\n uniform vec2 configSpaceViewportOrigin;\n uniform vec2 configSpaceViewportSize;\n uniform float framebufferHeight;\n\n void main() {\n vec2 origin = (configSpaceToPhysicalViewSpace * vec3(configSpaceViewportOrigin, 1.0)).xy;\n vec2 size = (configSpaceToPhysicalViewSpace * vec3(configSpaceViewportSize, 0.0)).xy;\n\n vec2 halfSize = physicalSize / 2.0;\n\n float borderWidth = 2.0;\n\n origin = floor(origin * halfSize) / halfSize + borderWidth * vec2(1.0, 1.0);\n size = floor(size * halfSize) / halfSize - 2.0 * borderWidth * vec2(1.0, 1.0);\n\n vec2 coord = gl_FragCoord.xy;\n coord.x = coord.x - physicalOrigin.x;\n coord.y = framebufferHeight - coord.y - physicalOrigin.y;\n vec2 clamped = clamp(coord, origin, origin + size);\n vec2 gap = clamped - coord;\n float maxdist = max(abs(gap.x), abs(gap.y));\n\n // TOOD(jlfwong): Could probably optimize this to use mix somehow.\n if (maxdist == 0.0) {\n // Inside viewport rectangle\n gl_FragColor = vec4(0, 0, 0, 0);\n } else if (maxdist < borderWidth) {\n // Inside viewport rectangle at border\n gl_FragColor = vec4(0.7, 0.7, 0.7, 0.8);\n } else {\n // Outside viewport rectangle\n gl_FragColor = vec4(0.7, 0.7, 0.7, 0.5);\n }\n }\n";class t{constructor(e){this.gl=e;const i=[[-1,1],[1,1],[-1,-1],[1,-1]],t=[];for(let e of i)t.push(e[0]),t.push(e[1]);this.buffer=e.createVertexBuffer(r.stride*i.length),this.buffer.upload(new Uint8Array(new Float32Array(t).buffer)),this.material=e.createMaterial(r,o,n)}render(r){(0,i.setUniformAffineTransform)(this.material,"configSpaceToPhysicalViewSpace",r.configSpaceToPhysicalViewSpace),(0,i.setUniformVec2)(this.material,"configSpaceViewportOrigin",r.configSpaceViewportRect.origin),(0,i.setUniformVec2)(this.material,"configSpaceViewportSize",r.configSpaceViewportRect.size);const o=this.gl.viewport;this.material.setUniformVec2("physicalOrigin",o.x,o.y),this.material.setUniformVec2("physicalSize",o.width,o.height),this.material.setUniformFloat("framebufferHeight",this.gl.renderTargetHeightInPixels),this.gl.setBlendState(e.Graphics.BlendOperation.SOURCE_ALPHA,e.Graphics.BlendOperation.INVERSE_SOURCE_ALPHA),this.gl.draw(e.Graphics.Primitive.TRIANGLE_STRIP,this.material,this.buffer)}}exports.ViewportRectangleRenderer=t;
},{"./graphics":42,"./utils":119}],122:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartColorPassRenderer=void 0;var e=require("../lib/math"),t=require("./graphics"),n=require("./utils");const r=new t.Graphics.VertexFormat;r.add("position",t.Graphics.AttributeType.FLOAT,2),r.add("uv",t.Graphics.AttributeType.FLOAT,2);const i="\n uniform mat3 uvTransform;\n uniform mat3 positionTransform;\n\n attribute vec2 position;\n attribute vec2 uv;\n varying vec2 vUv;\n\n void main() {\n vUv = (uvTransform * vec3(uv, 1)).xy;\n gl_Position = vec4((positionTransform * vec3(position, 1)).xy, 0, 1);\n }\n",o="\n precision mediump float;\n\n uniform vec2 uvSpacePixelSize;\n uniform float renderOutlines;\n\n varying vec2 vUv;\n uniform sampler2D colorTexture;\n\n // https://en.wikipedia.org/wiki/HSL_and_HSV#From_luma/chroma/hue\n vec3 hcl2rgb(float H, float C, float L) {\n float hPrime = H / 60.0;\n float X = C * (1.0 - abs(mod(hPrime, 2.0) - 1.0));\n vec3 RGB =\n hPrime < 1.0 ? vec3(C, X, 0) :\n hPrime < 2.0 ? vec3(X, C, 0) :\n hPrime < 3.0 ? vec3(0, C, X) :\n hPrime < 4.0 ? vec3(0, X, C) :\n hPrime < 5.0 ? vec3(X, 0, C) :\n vec3(C, 0, X);\n\n float m = L - dot(RGB, vec3(0.30, 0.59, 0.11));\n return RGB + vec3(m, m, m);\n }\n\n float triangle(float x) {\n return 2.0 * abs(fract(x) - 0.5) - 1.0;\n }\n\n vec3 colorForBucket(float t) {\n float x = triangle(30.0 * t);\n float H = 360.0 * (0.9 * t);\n float C = 0.25 + 0.2 * x;\n float L = 0.80 - 0.15 * x;\n return hcl2rgb(H, C, L);\n }\n\n void main() {\n vec4 here = texture2D(colorTexture, vUv);\n\n if (here.z == 0.0) {\n // Background color\n gl_FragColor = vec4(0, 0, 0, 0);\n return;\n }\n\n // Sample the 4 surrounding pixels in the depth texture to determine\n // if we should draw a boundary here or not.\n vec4 N = texture2D(colorTexture, vUv + vec2(0, uvSpacePixelSize.y));\n vec4 E = texture2D(colorTexture, vUv + vec2(uvSpacePixelSize.x, 0));\n vec4 S = texture2D(colorTexture, vUv + vec2(0, -uvSpacePixelSize.y));\n vec4 W = texture2D(colorTexture, vUv + vec2(-uvSpacePixelSize.x, 0));\n\n // NOTE: For outline checks, we intentionally check both the right\n // and the left to determine if we're an edge. If a rectangle is a single\n // pixel wide, we don't want to render it as an outline, so this method\n // of checking ensures that we don't outline single physical-space\n // pixel width rectangles.\n if (\n renderOutlines > 0.0 &&\n (\n here.y == N.y && here.y != S.y || // Top edge\n here.y == S.y && here.y != N.y || // Bottom edge\n here.x == E.x && here.x != W.x || // Left edge\n here.x == W.x && here.x != E.x\n )\n ) {\n // We're on an edge! Draw transparent.\n gl_FragColor = vec4(0, 0, 0, 0);\n } else {\n // Not on an edge. Draw the appropriate color.\n gl_FragColor = vec4(colorForBucket(here.z), here.a);\n }\n }\n";class a{constructor(e){this.gl=e;const t=[{pos:[-1,1],uv:[0,1]},{pos:[1,1],uv:[1,1]},{pos:[-1,-1],uv:[0,0]},{pos:[1,-1],uv:[1,0]}],n=[];for(let e of t)n.push(e.pos[0]),n.push(e.pos[1]),n.push(e.uv[0]),n.push(e.uv[1]);this.buffer=e.createVertexBuffer(r.stride*t.length),this.buffer.uploadFloats(n),this.material=e.createMaterial(r,i,o)}render(r){const{srcRect:i,rectInfoTexture:o}=r,a=e.AffineTransform.withTranslation(new e.Vec2(0,1)).times(e.AffineTransform.withScale(new e.Vec2(1,-1))).times(e.AffineTransform.betweenRects(new e.Rect(e.Vec2.zero,new e.Vec2(o.width,o.height)),e.Rect.unit)).transformRect(i),s=e.AffineTransform.betweenRects(e.Rect.unit,a),{dstRect:c}=r,l=new e.Vec2(this.gl.viewport.width,this.gl.viewport.height),u=e.AffineTransform.withScale(new e.Vec2(1,-1)).times(e.AffineTransform.betweenRects(new e.Rect(e.Vec2.zero,l),e.Rect.NDC)).transformRect(c),f=e.AffineTransform.betweenRects(e.Rect.NDC,u),h=e.Vec2.unit.dividedByPointwise(new e.Vec2(r.rectInfoTexture.width,r.rectInfoTexture.height));this.material.setUniformSampler("colorTexture",r.rectInfoTexture,0),(0,n.setUniformAffineTransform)(this.material,"uvTransform",s),this.material.setUniformFloat("renderOutlines",r.renderOutlines?1:0),this.material.setUniformVec2("uvSpacePixelSize",h.x,h.y),(0,n.setUniformAffineTransform)(this.material,"positionTransform",f),this.gl.setUnpremultipliedBlendState(),this.gl.draw(t.Graphics.Primitive.TRIANGLE_STRIP,this.material,this.buffer)}}exports.FlamechartColorPassRenderer=a;
},{"../lib/math":102,"./graphics":42,"./utils":119}],74:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CanvasContext=void 0;var e=require("./graphics"),r=require("./rectangle-batch-renderer"),t=require("./texture-renderer"),i=require("../lib/math"),n=require("./overlay-rectangle-renderer"),s=require("./flamechart-color-pass-renderer");class o{constructor(i){this.animationFrameRequest=null,this.beforeFrameHandlers=new Set,this.onBeforeFrame=(()=>{this.animationFrameRequest=null,this.gl.setViewport(0,0,this.gl.renderTargetWidthInPixels,this.gl.renderTargetHeightInPixels),this.gl.clear(new e.Graphics.Color(1,1,1,1));for(const e of this.beforeFrameHandlers)e()}),this.gl=new e.WebGL.Context(i),this.rectangleBatchRenderer=new r.RectangleBatchRenderer(this.gl),this.textureRenderer=new t.TextureRenderer(this.gl),this.viewportRectangleRenderer=new n.ViewportRectangleRenderer(this.gl),this.flamechartColorPassRenderer=new s.FlamechartColorPassRenderer(this.gl);const o=this.gl.getWebGLInfo();o&&console.log(`WebGL initialized. renderer: ${o.renderer}, vendor: ${o.vendor}, version: ${o.version}`),window.testContextLoss=(()=>{this.gl.testContextLoss()})}addBeforeFrameHandler(e){this.beforeFrameHandlers.add(e)}removeBeforeFrameHandler(e){this.beforeFrameHandlers.delete(e)}requestFrame(){this.animationFrameRequest||(this.animationFrameRequest=requestAnimationFrame(this.onBeforeFrame))}setViewport(e,r){const{origin:t,size:i}=e;let n=this.gl.viewport;this.gl.setViewport(t.x,t.y,i.x,i.y),r();let{x:s,y:o,width:a,height:l}=n;this.gl.setViewport(s,o,a,l)}renderBehind(e,r){const t=e.getBoundingClientRect(),n=new i.Rect(new i.Vec2(t.left*window.devicePixelRatio,t.top*window.devicePixelRatio),new i.Vec2(t.width*window.devicePixelRatio,t.height*window.devicePixelRatio));this.setViewport(n,r)}}exports.CanvasContext=o;
},{"./graphics":42,"./rectangle-batch-renderer":118,"./texture-renderer":120,"../lib/math":102,"./overlay-rectangle-renderer":121,"./flamechart-color-pass-renderer":122}],38:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getFrameToColorBucket=exports.getProfileToView=exports.getProfileWithRecursionFlattened=exports.getRowAtlas=exports.getCanvasContext=exports.createGetCSSColorForFrame=exports.createGetColorBucketForFrame=void 0;var e=require("../lib/utils"),t=require("../gl/row-atlas"),r=require("../gl/canvas-context"),o=require("../lib/color");const n=exports.createGetColorBucketForFrame=(0,e.memoizeByReference)(e=>t=>e.get(t.key)||0),a=exports.createGetCSSColorForFrame=(0,e.memoizeByReference)(t=>{const r=n(t);return t=>{const n=r(t)/255,a=(0,e.triangle)(30*n),l=.9*n*360,i=.25+.2*a,s=.8-.15*a;return o.Color.fromLumaChromaHue(s,i,l).toCSS()}}),l=exports.getCanvasContext=(0,e.memoizeByReference)(e=>new r.CanvasContext(e)),i=exports.getRowAtlas=(0,e.memoizeByReference)(e=>new t.RowAtlas(e.gl,e.rectangleBatchRenderer,e.textureRenderer)),s=exports.getProfileWithRecursionFlattened=(0,e.memoizeByReference)(e=>e.getProfileWithRecursionFlattened()),c=exports.getProfileToView=(0,e.memoizeByShallowEquality)(({profile:e,flattenRecursion:t})=>t?e.getProfileWithRecursionFlattened():e),u=exports.getFrameToColorBucket=(0,e.memoizeByReference)(e=>{const t=[];function r(e){return(e.file||"")+e.name}e.forEachFrame(e=>t.push(e)),t.sort(function(e,t){return r(e)>r(t)?1:-1});const o=new Map;for(let e=0;e<t.length;e++)o.set(t[e].key,Math.floor(255*e/t.length));return o});
},{"../lib/utils":70,"../gl/row-atlas":72,"../gl/canvas-context":74,"../lib/color":76}],55:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProfileTableViewContainer=exports.ProfileTableView=exports.SortDirection=exports.SortField=void 0;var e=require("preact"),t=require("aphrodite"),o=require("../lib/utils"),r=require("./style"),i=require("./color-chit"),s=require("./scrollable-list-view"),l=require("../store/actions"),a=require("../lib/typed-redux"),c=require("../store/getters"),n=exports.SortField=void 0;!function(e){e[e.SYMBOL_NAME=0]="SYMBOL_NAME",e[e.SELF=1]="SELF",e[e.TOTAL=2]="TOTAL"}(n||(exports.SortField=n={}));var h=exports.SortDirection=void 0;!function(e){e[e.ASCENDING=0]="ASCENDING",e[e.DESCENDING=1]="DESCENDING"}(h||(exports.SortDirection=h={}));class d extends e.Component{render(){return(0,e.h)("div",{className:(0,t.css)(E.hBarDisplay)},(0,e.h)("div",{className:(0,t.css)(E.hBarDisplayFilled),style:{width:`${this.props.perc}%`}}))}}class p extends e.Component{render(){const{activeDirection:o}=this.props,i=o===h.ASCENDING?r.Colors.GRAY:r.Colors.LIGHT_GRAY,s=o===h.DESCENDING?r.Colors.GRAY:r.Colors.LIGHT_GRAY;return(0,e.h)("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:(0,t.css)(E.sortIcon)},(0,e.h)("path",{d:"M0 4L4 0L8 4H0Z",fill:i}),(0,e.h)("path",{d:"M0 4L4 0L8 4H0Z",transform:"translate(0 10) scale(1 -1)",fill:s}))}}class S extends e.Component{constructor(){super(...arguments),this.onSortClick=((e,t)=>{t.preventDefault();const{sortMethod:o}=this.props;if(o.field==e)this.props.setSortMethod({field:e,direction:o.direction===h.ASCENDING?h.DESCENDING:h.ASCENDING});else switch(e){case n.SYMBOL_NAME:this.props.setSortMethod({field:e,direction:h.ASCENDING});break;case n.SELF:case n.TOTAL:this.props.setSortMethod({field:e,direction:h.DESCENDING})}}),this.getFrameList=(()=>{const{profile:e,sortMethod:t}=this.props,r=[];switch(e.forEachFrame(e=>r.push(e)),t.field){case n.SYMBOL_NAME:(0,o.sortBy)(r,e=>e.name.toLowerCase());break;case n.SELF:(0,o.sortBy)(r,e=>e.getSelfWeight());break;case n.TOTAL:(0,o.sortBy)(r,e=>e.getTotalWeight())}return t.direction===h.DESCENDING&&r.reverse(),r}),this.listView=null,this.listViewRef=(e=>{if(e===this.listView)return;this.listView=e;const{selectedFrame:t}=this.props;if(!t||!e)return;const o=this.getFrameList().indexOf(t);-1!==o&&e.scrollIndexIntoView(o)})}renderRow(r,s){const{profile:l,selectedFrame:a}=this.props,c=r.getTotalWeight(),n=r.getSelfWeight(),h=100*c/l.getTotalNonIdleWeight(),p=100*n/l.getTotalNonIdleWeight(),S=r===a;return(0,e.h)("tr",{key:`${s}`,onClick:this.props.setSelectedFrame.bind(null,r),className:(0,t.css)(E.tableRow,s%2==0&&E.tableRowEven,S&&E.tableRowSelected)},(0,e.h)("td",{className:(0,t.css)(E.numericCell)},l.formatValue(c)," (",(0,o.formatPercent)(h),")",(0,e.h)(d,{perc:h})),(0,e.h)("td",{className:(0,t.css)(E.numericCell)},l.formatValue(n)," (",(0,o.formatPercent)(p),")",(0,e.h)(d,{perc:p})),(0,e.h)("td",{title:r.file,className:(0,t.css)(E.textCell)},(0,e.h)(i.ColorChit,{color:this.props.getCSSColorForFrame(r)}),r.name))}render(){const{sortMethod:o}=this.props,i=this.getFrameList(),l=i.map(e=>({size:r.Sizes.FRAME_HEIGHT}));return(0,e.h)("div",{className:(0,t.css)(r.commonStyle.vbox,E.profileTableView)},(0,e.h)("table",{className:(0,t.css)(E.tableView)},(0,e.h)("thead",{className:(0,t.css)(E.tableHeader)},(0,e.h)("tr",null,(0,e.h)("th",{className:(0,t.css)(E.numericCell),onClick:e=>this.onSortClick(n.TOTAL,e)},(0,e.h)(p,{activeDirection:o.field===n.TOTAL?o.direction:null}),"Total"),(0,e.h)("th",{className:(0,t.css)(E.numericCell),onClick:e=>this.onSortClick(n.SELF,e)},(0,e.h)(p,{activeDirection:o.field===n.SELF?o.direction:null}),"Self"),(0,e.h)("th",{className:(0,t.css)(E.textCell),onClick:e=>this.onSortClick(n.SYMBOL_NAME,e)},(0,e.h)(p,{activeDirection:o.field===n.SYMBOL_NAME?o.direction:null}),"Symbol Name")))),(0,e.h)(s.ScrollableListView,{ref:this.listViewRef,axis:"y",items:l,className:(0,t.css)(E.scrollView),renderItems:(o,r)=>{const s=[];for(let e=o;e<=r;e++)s.push(this.renderRow(i[e],e));return(0,e.h)("table",{className:(0,t.css)(E.tableView)},s)}}))}}exports.ProfileTableView=S;const E=t.StyleSheet.create({profileTableView:{background:r.Colors.WHITE,height:"100%"},scrollView:{overflowY:"auto",overflowX:"hidden"},tableView:{width:"100%",fontSize:r.FontSize.LABEL,background:r.Colors.WHITE},tableHeader:{borderBottom:`2px solid ${r.Colors.LIGHT_GRAY}`,textAlign:"left",color:r.Colors.GRAY,userSelect:"none"},sortIcon:{position:"relative",top:1,marginRight:r.Sizes.FRAME_HEIGHT/4},tableRow:{height:r.Sizes.FRAME_HEIGHT},tableRowEven:{background:r.Colors.OFF_WHITE},tableRowSelected:{background:r.Colors.DARK_BLUE,color:r.Colors.WHITE},numericCell:{textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",position:"relative",textAlign:"right",paddingRight:r.Sizes.FRAME_HEIGHT,width:6*r.Sizes.FRAME_HEIGHT,minWidth:6*r.Sizes.FRAME_HEIGHT},textCell:{textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",width:"100%",maxWidth:0},hBarDisplay:{position:"absolute",background:r.Colors.TRANSPARENT_GREEN,bottom:2,height:2,width:`calc(100% - ${2*r.Sizes.FRAME_HEIGHT}px)`,right:r.Sizes.FRAME_HEIGHT},hBarDisplayFilled:{height:"100%",position:"absolute",background:r.Colors.GREEN,right:0}}),m=exports.ProfileTableViewContainer=(0,a.createContainer)(S,(e,t,o)=>{const{activeProfileState:r}=o,{profile:i,sandwichViewState:s,index:a}=r;if(!i)throw new Error("profile missing");const{tableSortMethod:n}=e,{callerCallee:h}=s,d=h?h.selectedFrame:null,p=(0,c.getFrameToColorBucket)(i),S=(0,c.createGetCSSColorForFrame)(p);return{profile:i,profileIndex:r.index,selectedFrame:d,getCSSColorForFrame:S,sortMethod:n,setSelectedFrame:e=>{t(l.actions.sandwichView.setSelectedFrame({profileIndex:a,args:e}))},setSortMethod:e=>{t(l.actions.sandwichView.setTableSortMethod(e))}}});
},{"preact":24,"aphrodite":68,"../lib/utils":70,"./style":79,"./color-chit":106,"./scrollable-list-view":108,"../store/actions":40,"../lib/typed-redux":36,"../store/getters":38}],29:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.canUseXHR=exports.ViewMode=void 0,exports.createApplicationStore=d;var e=require("./actions"),t=require("redux"),r=n(t),o=require("../lib/typed-redux"),s=require("../lib/hash-params"),i=require("./profiles-state"),a=require("../views/profile-table-view");function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}var c=exports.ViewMode=void 0;!function(e){e[e.CHRONO_FLAME_CHART=0]="CHRONO_FLAME_CHART",e[e.LEFT_HEAVY_FLAME_GRAPH=1]="LEFT_HEAVY_FLAME_GRAPH",e[e.SANDWICH_VIEW=2]="SANDWICH_VIEW"}(c||(exports.ViewMode=c={}));const l=window.location.protocol,u=exports.canUseXHR="http:"===l||"https:"===l;function d(t){const n=(0,s.getHashParams)(),l=u&&null!=n.profileURL,d=r.combineReducers({profileGroup:i.profileGroup,hashParams:(0,o.setter)(e.actions.setHashParams,n),flattenRecursion:(0,o.setter)(e.actions.setFlattenRecursion,!1),viewMode:(0,o.setter)(e.actions.setViewMode,c.CHRONO_FLAME_CHART),glCanvas:(0,o.setter)(e.actions.setGLCanvas,null),dragActive:(0,o.setter)(e.actions.setDragActive,!1),loading:(0,o.setter)(e.actions.setLoading,l),error:(0,o.setter)(e.actions.setError,!1),tableSortMethod:(0,o.setter)(e.actions.sandwichView.setTableSortMethod,{field:a.SortField.SELF,direction:a.SortDirection.DESCENDING})});return r.createStore(d,t)}
},{"./actions":40,"redux":31,"../lib/typed-redux":36,"../lib/hash-params":50,"./profiles-state":52,"../views/profile-table-view":55}],81:[function(require,module,exports) {
"use strict";function e(e){return e.replace(/\\([a-fA-F0-9]{2})/g,(e,n)=>{const t=parseInt(n,16);return String.fromCharCode(t)})}function n(n){const t=n.split("\n");if(!t.length)return null;if(""===t[t.length-1]&&t.pop(),!t.length)return null;const r=new Map,o=/^(\d+):(.+)$/,s=/^([\$\w]+):([\$\w-]+)$/;for(const n of t){const t=o.exec(n);if(t){r.set(`wasm-function[${t[1]}]`,e(t[2]));continue}const c=s.exec(n);if(!c)return null;r.set(c[1],e(c[2]))}return r}Object.defineProperty(exports,"__esModule",{value:!0}),exports.importEmscriptenSymbolMap=n;
},{}],142:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Flamechart=void 0;var t=require("./utils"),e=require("./math");class r{constructor(e){this.source=e,this.layers=[],this.totalWeight=0,this.minFrameWidth=1;const r=[];this.minFrameWidth=1/0;this.totalWeight=e.getTotalWeight(),e.forEachCall((e,i)=>{const s=(0,t.lastOf)(r),h={node:e,parent:s,children:[],start:i,end:i};s&&s.children.push(h),r.push(h)},(t,e)=>{console.assert(r.length>0);const i=r.pop();if(i.end=e,i.end-i.start==0)return;const s=r.length;for(;this.layers.length<=s;)this.layers.push([]);this.layers[s].push(i),this.minFrameWidth=Math.min(this.minFrameWidth,i.end-i.start)}),isFinite(this.minFrameWidth)||(this.minFrameWidth=1)}getTotalWeight(){return this.totalWeight}getLayers(){return this.layers}getColorBucketForFrame(t){return this.source.getColorBucketForFrame(t)}getMinFrameWidth(){return this.minFrameWidth}formatValue(t){return this.source.formatValue(t)}getClampedViewportWidth(t){const r=this.getTotalWeight(),i=Math.pow(2,40),s=(0,e.clamp)(3*this.getMinFrameWidth(),r/i,r);return(0,e.clamp)(t,s,r)}}exports.Flamechart=r;
},{"./utils":70,"./math":102}],143:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartRenderer=exports.FlamechartRowAtlasKey=void 0;var e=require("./rectangle-batch-renderer"),t=require("../lib/math"),r=require("../lib/color"),n=require("../lib/utils"),s=require("./graphics"),o=require("./utils");const c=1e4;class i{constructor(e,t,r){this.batch=e,this.bounds=t,this.numPrecedingRectanglesInRow=r,this.children=[]}getBatch(){return this.batch}getBounds(){return this.bounds}getRectCount(){return this.batch.getRectCount()}getChildren(){return this.children}getParity(){return this.numPrecedingRectanglesInRow%2}forEachLeafNodeWithinBounds(e,t){this.bounds.hasIntersectionWith(e)&&t(this)}}class h{constructor(e){if(this.children=e,this.rectCount=0,0===e.length)throw new Error("Empty interior node");let r=1/0,n=-1/0,s=1/0,o=-1/0;for(let t of e){this.rectCount+=t.getRectCount();const e=t.getBounds();r=Math.min(r,e.left()),n=Math.max(n,e.right()),s=Math.min(s,e.top()),o=Math.max(o,e.bottom())}this.bounds=new t.Rect(new t.Vec2(r,s),new t.Vec2(n-r,o-s))}getBounds(){return this.bounds}getRectCount(){return this.rectCount}getChildren(){return this.children}forEachLeafNodeWithinBounds(e,t){if(this.bounds.hasIntersectionWith(e))for(let r of this.children)r.forEachLeafNodeWithinBounds(e,t)}}class a{get key(){return`${this.stackDepth}_${this.index}_${this.zoomLevel}`}constructor(e){this.stackDepth=e.stackDepth,this.zoomLevel=e.zoomLevel,this.index=e.index}static getOrInsert(e,t){return e.getOrInsert(new a(t))}}exports.FlamechartRowAtlasKey=a;class l{constructor(s,o,a,l,g,d={inverted:!1}){this.gl=s,this.rowAtlas=o,this.flamechart=a,this.rectangleBatchRenderer=l,this.colorPassRenderer=g,this.options=d,this.layers=[],this.rectInfoTexture=null,this.rectInfoRenderTarget=null,this.atlasKeys=new n.KeyedSet;const f=a.getLayers().length;for(let n=0;n<f;n++){const s=[],o=d.inverted?f-1-n:n;let l=1/0,g=-1/0,u=new e.RectangleBatch(this.gl),R=0;const w=a.getLayers()[n];for(let h=0;h<w.length;h++){const a=w[h];u.getRectCount()>=c&&(s.push(new i(u,new t.Rect(new t.Vec2(l,o),new t.Vec2(g-l,1)),R)),l=1/0,g=-1/0,u=new e.RectangleBatch(this.gl));const d=new t.Rect(new t.Vec2(a.start,o),new t.Vec2(a.end-a.start,1));l=Math.min(l,d.left()),g=Math.max(g,d.right());const f=new r.Color((1+h%255)/256,(1+n%255)/256,(1+this.flamechart.getColorBucketForFrame(a.node.frame))/256);u.addRect(d,f),R++}u.getRectCount()>0&&s.push(new i(u,new t.Rect(new t.Vec2(l,o),new t.Vec2(g-l,1)),R)),this.layers.push(new h(s))}}getRectInfoTexture(e,t){if(this.rectInfoTexture){const r=this.rectInfoTexture;r.width==e&&r.height==t||r.resize(e,t)}else this.rectInfoTexture=this.gl.createTexture(s.Graphics.TextureFormat.NEAREST_CLAMP,e,t);return this.rectInfoTexture}getRectInfoRenderTarget(e,t){const r=this.getRectInfoTexture(e,t);return this.rectInfoRenderTarget&&this.rectInfoRenderTarget.texture!=r&&(this.rectInfoRenderTarget.texture.free(),this.rectInfoRenderTarget.setColor(r)),this.rectInfoRenderTarget||(this.rectInfoRenderTarget=this.gl.createRenderTarget(r)),this.rectInfoRenderTarget}free(){this.rectInfoRenderTarget&&this.rectInfoRenderTarget.free(),this.rectInfoTexture&&this.rectInfoTexture.free()}configSpaceBoundsForKey(e){const{stackDepth:r,zoomLevel:n,index:s}=e,o=this.flamechart.getTotalWeight()/Math.pow(2,n),c=this.flamechart.getLayers().length,i=this.options.inverted?c-1-r:r;return new t.Rect(new t.Vec2(o*s,i),new t.Vec2(o,1))}render(e){const{configSpaceSrcRect:r,physicalSpaceDstRect:n}=e,c=[],i=t.AffineTransform.betweenRects(r,n);if(r.isEmpty())return;let h=0;for(;;){const e=a.getOrInsert(this.atlasKeys,{stackDepth:0,zoomLevel:h,index:0}),t=this.configSpaceBoundsForKey(e);if(i.transformRect(t).width()<this.rowAtlas.getResolution())break;h++}const l=Math.max(0,Math.floor(r.top())),g=Math.min(this.layers.length,Math.ceil(r.bottom())),d=this.flamechart.getTotalWeight(),f=Math.pow(2,h),u=Math.floor(f*r.left()/d),R=Math.ceil(f*r.right()/d),w=this.flamechart.getLayers().length;for(let e=l;e<g;e++)for(let t=u;t<=R;t++){const n=this.options.inverted?w-1-e:e,s=a.getOrInsert(this.atlasKeys,{stackDepth:n,zoomLevel:h,index:t});this.configSpaceBoundsForKey(s).hasIntersectionWith(r)&&c.push(s)}const p=this.rowAtlas.getCapacity(),m=c.slice(0,p),I=c.slice(p);this.rowAtlas.writeToAtlasIfNeeded(m,(e,t)=>{const r=this.configSpaceBoundsForKey(t);this.layers[t.stackDepth].forEachLeafNodeWithinBounds(r,t=>{this.rectangleBatchRenderer.render({batch:t.getBatch(),configSpaceSrcRect:r,physicalSpaceDstRect:e})})});const T=this.getRectInfoRenderTarget(n.width(),n.height());(0,o.renderInto)(this.gl,T,()=>{this.gl.clear(new s.Graphics.Color(0,0,0,0));const e=new t.Rect(t.Vec2.zero,new t.Vec2(this.gl.viewport.width,this.gl.viewport.height)),n=t.AffineTransform.betweenRects(r,e);for(let e of m){const t=this.configSpaceBoundsForKey(e);this.rowAtlas.renderViaAtlas(e,n.transformRect(t))}for(let e of I){const t=this.configSpaceBoundsForKey(e),r=n.transformRect(t);this.layers[e.stackDepth].forEachLeafNodeWithinBounds(t,e=>{this.rectangleBatchRenderer.render({batch:e.getBatch(),configSpaceSrcRect:t,physicalSpaceDstRect:r})})}});const x=this.getRectInfoTexture(n.width(),n.height());this.colorPassRenderer.render({rectInfoTexture:x,srcRect:new t.Rect(t.Vec2.zero,new t.Vec2(x.width,x.height)),dstRect:n,renderOutlines:e.renderOutlines})}}exports.FlamechartRenderer=l;
},{"./rectangle-batch-renderer":118,"../lib/math":102,"../lib/color":76,"../lib/utils":70,"./graphics":42,"./utils":119}],163:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.style=void 0;var e=require("aphrodite"),o=require("./style");const t=exports.style=e.StyleSheet.create({hoverCount:{color:o.Colors.GREEN},fill:{width:"100%",height:"100%",position:"absolute",left:0,top:0},minimap:{height:o.Sizes.MINIMAP_HEIGHT,borderBottom:`${o.Sizes.SEPARATOR_HEIGHT}px solid ${o.Colors.LIGHT_GRAY}`},panZoomView:{flex:1},detailView:{display:"grid",height:o.Sizes.DETAIL_VIEW_HEIGHT,overflow:"hidden",gridTemplateColumns:"120px 120px 1fr",gridTemplateRows:"repeat(4, 1fr)",borderTop:`${o.Sizes.SEPARATOR_HEIGHT}px solid ${o.Colors.LIGHT_GRAY}`,fontSize:o.FontSize.LABEL,position:"absolute",background:o.Colors.WHITE,width:"100vw",bottom:0},stackTraceViewPadding:{padding:5},stackTraceView:{height:o.Sizes.DETAIL_VIEW_HEIGHT,lineHeight:`${o.FontSize.LABEL+2}px`,overflow:"auto"},stackLine:{whiteSpace:"nowrap"},stackFileLine:{color:o.Colors.LIGHT_GRAY},statsTable:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:`repeat(3, ${o.FontSize.LABEL+10}px)`,gridGap:"1px 1px",textAlign:"center",paddingRight:1},statsTableHeader:{gridColumn:"1 / 3"},statsTableCell:{position:"relative",display:"flex",justifyContent:"center",alignItems:"center"},thisInstanceCell:{background:o.Colors.DARK_BLUE,color:o.Colors.WHITE},allInstancesCell:{background:o.Colors.PALE_DARK_BLUE,color:o.Colors.WHITE},barDisplay:{position:"absolute",top:0,left:0,background:"rgba(0, 0, 0, 0.2)",width:"100%"}});
},{"aphrodite":68,"./style":79}],173:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ELLIPSIS=void 0,exports.cachedMeasureTextWidth=n,exports.trimTextMid=s;var e=require("./utils");const t=exports.ELLIPSIS="…",r=new Map;let i=-1;function n(e,t){return window.devicePixelRatio!==i&&(r.clear(),i=window.devicePixelRatio),r.has(t)||r.set(t,e.measureText(t).width),r.get(t)}function o(e,r){const i=Math.floor(r/2),n=e.substr(0,i),o=e.substr(e.length-i,i);return n+t+o}function s(t,r,i){if(n(t,r)<=i)return r;const[s]=(0,e.binarySearch)(0,r.length,e=>n(t,o(r,e)),i);return o(r,s)}
},{"./utils":70}],159:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartMinimapView=void 0;var e,i=require("preact"),t=require("aphrodite"),o=require("../lib/math"),s=require("./flamechart-style"),n=require("./style"),a=require("../lib/text-utils");!function(e){e[e.DRAW_NEW_VIEWPORT=0]="DRAW_NEW_VIEWPORT",e[e.TRANSLATE_VIEWPORT=1]="TRANSLATE_VIEWPORT"}(e||(e={}));class r extends i.Component{constructor(){super(...arguments),this.container=null,this.containerRef=(e=>{this.container=e||null}),this.overlayCanvas=null,this.overlayCtx=null,this.onWindowResize=(()=>{this.onBeforeFrame()}),this.onBeforeFrame=(()=>{this.maybeClearInteractionLock(),this.resizeOverlayCanvasIfNeeded(),this.renderRects(),this.renderOverlays()}),this.renderCanvas=(()=>{this.props.canvasContext.requestFrame()}),this.frameHadWheelEvent=!1,this.framesWithoutWheelEvents=0,this.interactionLock=null,this.maybeClearInteractionLock=(()=>{this.interactionLock&&(this.frameHadWheelEvent||(this.framesWithoutWheelEvents++,this.framesWithoutWheelEvents>=2&&(this.interactionLock=null,this.framesWithoutWheelEvents=0)),this.props.canvasContext.requestFrame()),this.frameHadWheelEvent=!1}),this.onWheel=(e=>{if(e.preventDefault(),this.frameHadWheelEvent=!0,(e.metaKey||e.ctrlKey)&&"pan"!==this.interactionLock){let i=1+e.deltaY/100;e.ctrlKey&&(i=1+e.deltaY/40),i=(0,o.clamp)(i,.1,10),this.zoom(i)}else"zoom"!==this.interactionLock&&this.pan(new o.Vec2(e.deltaX,e.deltaY));this.renderCanvas()}),this.dragStartConfigSpaceMouse=null,this.dragConfigSpaceViewportOffset=null,this.draggingMode=null,this.onMouseDown=(i=>{const t=this.configSpaceMouse(i);t&&(this.props.configSpaceViewportRect.contains(t)?(this.draggingMode=e.TRANSLATE_VIEWPORT,this.dragConfigSpaceViewportOffset=t.minus(this.props.configSpaceViewportRect.origin)):this.draggingMode=e.DRAW_NEW_VIEWPORT,this.dragStartConfigSpaceMouse=t,window.addEventListener("mousemove",this.onWindowMouseMove),window.addEventListener("mouseup",this.onWindowMouseUp),this.updateCursor(t))}),this.onWindowMouseMove=(i=>{if(!this.dragStartConfigSpaceMouse)return;let t=this.configSpaceMouse(i);if(t)if(this.updateCursor(t),t=new o.Rect(new o.Vec2(0,0),this.configSpaceSize()).closestPointTo(t),this.draggingMode===e.DRAW_NEW_VIEWPORT){const e=this.dragStartConfigSpaceMouse;let i=t;if(!e||!i)return;const s=Math.min(e.x,i.x),n=Math.max(e.x,i.x)-s,a=this.props.configSpaceViewportRect.height();this.props.setConfigSpaceViewportRect(new o.Rect(new o.Vec2(s,i.y-a/2),new o.Vec2(n,a)))}else if(this.draggingMode===e.TRANSLATE_VIEWPORT){if(!this.dragConfigSpaceViewportOffset)return;const e=t.minus(this.dragConfigSpaceViewportOffset);this.props.setConfigSpaceViewportRect(this.props.configSpaceViewportRect.withOrigin(e))}}),this.updateCursor=(i=>{this.draggingMode===e.TRANSLATE_VIEWPORT?(document.body.style.cursor="grabbing",document.body.style.cursor="-webkit-grabbing"):this.draggingMode===e.DRAW_NEW_VIEWPORT?document.body.style.cursor="col-resize":this.props.configSpaceViewportRect.contains(i)?(document.body.style.cursor="grab",document.body.style.cursor="-webkit-grab"):document.body.style.cursor="col-resize"}),this.onMouseLeave=(()=>{null==this.draggingMode&&(document.body.style.cursor="default")}),this.onMouseMove=(e=>{const i=this.configSpaceMouse(e);i&&this.updateCursor(i)}),this.onWindowMouseUp=(e=>{this.draggingMode=null,window.removeEventListener("mousemove",this.onWindowMouseMove),window.removeEventListener("mouseup",this.onWindowMouseUp);const i=this.configSpaceMouse(e);i&&this.updateCursor(i)}),this.overlayCanvasRef=(e=>{e?(this.overlayCanvas=e,this.overlayCtx=this.overlayCanvas.getContext("2d"),this.renderCanvas()):(this.overlayCanvas=null,this.overlayCtx=null)})}physicalViewSize(){return new o.Vec2(this.overlayCanvas?this.overlayCanvas.width:0,this.overlayCanvas?this.overlayCanvas.height:0)}minimapOrigin(){return new o.Vec2(0,n.Sizes.FRAME_HEIGHT*window.devicePixelRatio)}configSpaceSize(){return new o.Vec2(this.props.flamechart.getTotalWeight(),this.props.flamechart.getLayers().length)}configSpaceToPhysicalViewSpace(){const e=this.minimapOrigin();return o.AffineTransform.betweenRects(new o.Rect(new o.Vec2(0,0),this.configSpaceSize()),new o.Rect(e,this.physicalViewSize().minus(e)))}logicalToPhysicalViewSpace(){return o.AffineTransform.withScale(new o.Vec2(window.devicePixelRatio,window.devicePixelRatio))}windowToLogicalViewSpace(){if(!this.container)return new o.AffineTransform;const e=this.container.getBoundingClientRect();return o.AffineTransform.withTranslation(new o.Vec2(-e.left,-e.top))}renderRects(){this.container&&(this.physicalViewSize().x<2||this.props.canvasContext.renderBehind(this.container,()=>{this.props.flamechartRenderer.render({configSpaceSrcRect:new o.Rect(new o.Vec2(0,0),this.configSpaceSize()),physicalSpaceDstRect:new o.Rect(this.minimapOrigin(),this.physicalViewSize().minus(this.minimapOrigin())),renderOutlines:!1}),this.props.canvasContext.viewportRectangleRenderer.render({configSpaceViewportRect:this.props.configSpaceViewportRect,configSpaceToPhysicalViewSpace:this.configSpaceToPhysicalViewSpace()})}))}renderOverlays(){const e=this.overlayCtx;if(!e)return;const i=this.physicalViewSize();e.clearRect(0,0,i.x,i.y);const t=this.configSpaceToPhysicalViewSpace(),s=this.configSpaceSize().x,r=(this.configSpaceToPhysicalViewSpace().inverted()||new o.AffineTransform).times(this.logicalToPhysicalViewSpace()).transformVector(new o.Vec2(200,1)).x,c=n.Sizes.FRAME_HEIGHT*window.devicePixelRatio,h=n.FontSize.LABEL*window.devicePixelRatio,l=(c-h)/2;e.font=`${h}px/${c}px ${n.FontFamily.MONOSPACE}`,e.textBaseline="top";let p=Math.pow(10,Math.floor(Math.log10(r)));r/p>5?p*=5:r/p>2&&(p*=2),e.fillStyle="rgba(255, 255, 255, 0.8)",e.fillRect(0,0,i.x,c),e.textBaseline="top",e.fillStyle=n.Colors.DARK_GRAY;for(let n=Math.ceil(0/p)*p;n<s;n+=p){const s=Math.round(t.transformPosition(new o.Vec2(n,0)).x),r=this.props.flamechart.formatValue(n),c=Math.ceil((0,a.cachedMeasureTextWidth)(e,r));e.fillText(r,s-c-l,l),e.fillRect(s,0,1,i.y)}}componentWillReceiveProps(e){this.props.flamechart!==e.flamechart?this.renderCanvas():this.props.configSpaceViewportRect!=e.configSpaceViewportRect&&this.renderCanvas()}componentDidMount(){window.addEventListener("resize",this.onWindowResize),this.props.canvasContext.addBeforeFrameHandler(this.onBeforeFrame)}componentWillUnmount(){window.removeEventListener("resize",this.onWindowResize),this.props.canvasContext.removeBeforeFrameHandler(this.onBeforeFrame)}resizeOverlayCanvasIfNeeded(){if(!this.overlayCanvas)return;let{width:e,height:i}=this.overlayCanvas.getBoundingClientRect();if(e=Math.floor(e),i=Math.floor(i),0===e||0===i)return;const t=e*window.devicePixelRatio,o=i*window.devicePixelRatio;t===this.overlayCanvas.width&&o===this.overlayCanvas.height||(this.overlayCanvas.width=t,this.overlayCanvas.height=o)}pan(e){this.interactionLock="pan";const i=this.logicalToPhysicalViewSpace().transformVector(e),t=this.configSpaceToPhysicalViewSpace().inverseTransformVector(i);t&&this.props.transformViewport(o.AffineTransform.withTranslation(t))}zoom(e){this.interactionLock="zoom";const i=this.props.configSpaceViewportRect,t=i.origin.plus(i.size.times(.5));if(!t)return;const s=o.AffineTransform.withTranslation(t.times(-1)).scaledBy(new o.Vec2(e,1)).translatedBy(t);this.props.transformViewport(s)}configSpaceMouse(e){const i=this.windowToLogicalViewSpace().transformPosition(new o.Vec2(e.clientX,e.clientY)),t=this.logicalToPhysicalViewSpace().transformPosition(i);return this.configSpaceToPhysicalViewSpace().inverseTransformPosition(t)}render(){return(0,i.h)("div",{ref:this.containerRef,onWheel:this.onWheel,onMouseDown:this.onMouseDown,onMouseMove:this.onMouseMove,onMouseLeave:this.onMouseLeave,className:(0,t.css)(s.style.minimap,n.commonStyle.vbox)},(0,i.h)("canvas",{width:1,height:1,ref:this.overlayCanvasRef,className:(0,t.css)(s.style.fill)}))}}exports.FlamechartMinimapView=r;
},{"preact":24,"aphrodite":68,"../lib/math":102,"./flamechart-style":163,"./style":79,"../lib/text-utils":173}],160:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartDetailView=void 0;var e=require("aphrodite"),s=require("preact"),t=require("./flamechart-style"),l=require("../lib/utils"),a=require("./color-chit");class r extends s.Component{render(){const a=this.props.formatter(this.props.selectedTotal),r=this.props.formatter(this.props.selectedSelf),i=100*this.props.selectedTotal/this.props.grandTotal,c=100*this.props.selectedSelf/this.props.grandTotal;return(0,s.h)("div",{className:(0,e.css)(t.style.statsTable)},(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell,t.style.statsTableHeader)},this.props.title),(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell)},"Total"),(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell)},"Self"),(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell)},a),(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell)},r),(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell)},(0,l.formatPercent)(i),(0,s.h)("div",{className:(0,e.css)(t.style.barDisplay),style:{height:`${i}%`}})),(0,s.h)("div",{className:(0,e.css)(this.props.cellStyle,t.style.statsTableCell)},(0,l.formatPercent)(c),(0,s.h)("div",{className:(0,e.css)(t.style.barDisplay),style:{height:`${c}%`}})))}}class i extends s.Component{render(){const l=[];let r=this.props.node;for(;r&&!r.isRoot();r=r.parent){const i=[],{frame:c}=r;if(i.push((0,s.h)(a.ColorChit,{color:this.props.getFrameColor(c)})),l.length&&i.push((0,s.h)("span",{className:(0,e.css)(t.style.stackFileLine)},"> ")),i.push(c.name),c.file){let l=c.file;c.line&&(l+=`:${c.line}`,c.col&&(l+=`:${c.col}`)),i.push((0,s.h)("span",{className:(0,e.css)(t.style.stackFileLine)}," (",l,")"))}l.push((0,s.h)("div",{className:(0,e.css)(t.style.stackLine)},i))}return(0,s.h)("div",{className:(0,e.css)(t.style.stackTraceView)},(0,s.h)("div",{className:(0,e.css)(t.style.stackTraceViewPadding)},l))}}class c extends s.Component{render(){const{flamechart:l,selectedNode:a}=this.props,{frame:c}=a;return(0,s.h)("div",{className:(0,e.css)(t.style.detailView)},(0,s.h)(r,{title:"This Instance",cellStyle:t.style.thisInstanceCell,grandTotal:l.getTotalWeight(),selectedTotal:a.getTotalWeight(),selectedSelf:a.getSelfWeight(),formatter:l.formatValue.bind(l)}),(0,s.h)(r,{title:"All Instances",cellStyle:t.style.allInstancesCell,grandTotal:l.getTotalWeight(),selectedTotal:c.getTotalWeight(),selectedSelf:c.getSelfWeight(),formatter:l.formatValue.bind(l)}),(0,s.h)(i,{node:a,getFrameColor:this.props.getCSSColorForFrame}))}}exports.FlamechartDetailView=c;
},{"aphrodite":68,"preact":24,"./flamechart-style":163,"../lib/utils":70,"./color-chit":106}],161:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartPanZoomView=void 0;var e=require("../lib/math"),t=require("./style"),i=require("../lib/text-utils"),o=require("./flamechart-style"),s=require("preact"),n=require("aphrodite");class r extends s.Component{constructor(){super(...arguments),this.container=null,this.containerRef=(e=>{this.container=e||null}),this.overlayCanvas=null,this.overlayCtx=null,this.hoveredLabel=null,this.overlayCanvasRef=(e=>{e?(this.overlayCanvas=e,this.overlayCtx=this.overlayCanvas.getContext("2d"),this.renderCanvas()):(this.overlayCanvas=null,this.overlayCtx=null)}),this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT=t.Sizes.FRAME_HEIGHT,this.onWindowResize=(()=>{this.updateConfigSpaceViewport(),this.onBeforeFrame()}),this.frameHadWheelEvent=!1,this.framesWithoutWheelEvents=0,this.interactionLock=null,this.maybeClearInteractionLock=(()=>{this.interactionLock&&(this.frameHadWheelEvent||(this.framesWithoutWheelEvents++,this.framesWithoutWheelEvents>=2&&(this.interactionLock=null,this.framesWithoutWheelEvents=0)),this.props.canvasContext.requestFrame()),this.frameHadWheelEvent=!1}),this.onBeforeFrame=(()=>{this.resizeOverlayCanvasIfNeeded(),this.renderRects(),this.renderOverlays(),this.maybeClearInteractionLock()}),this.renderCanvas=(()=>{this.props.canvasContext.requestFrame()}),this.lastDragPos=null,this.mouseDownPos=null,this.onMouseDown=(t=>{this.mouseDownPos=this.lastDragPos=new e.Vec2(t.offsetX,t.offsetY),this.updateCursor(),window.addEventListener("mouseup",this.onWindowMouseUp)}),this.onMouseDrag=(t=>{if(!this.lastDragPos)return;const i=new e.Vec2(t.offsetX,t.offsetY);this.pan(this.lastDragPos.minus(i)),this.lastDragPos=i,this.hoveredLabel&&this.props.onNodeHover(null)}),this.onDblClick=(t=>{if(this.hoveredLabel){const t=this.hoveredLabel.configSpaceBounds,i=new e.Rect(t.origin.minus(new e.Vec2(0,1)),t.size.withY(this.props.configSpaceViewportRect.height()));this.props.setConfigSpaceViewportRect(i)}}),this.onClick=(t=>{const i=new e.Vec2(t.offsetX,t.offsetY),o=this.mouseDownPos;this.mouseDownPos=null,o&&i.minus(o).length()>5||(this.hoveredLabel?(this.props.onNodeSelect(this.hoveredLabel.node),this.renderCanvas()):this.props.onNodeSelect(null))}),this.onWindowMouseUp=(e=>{this.lastDragPos=null,this.updateCursor(),window.removeEventListener("mouseup",this.onWindowMouseUp)}),this.onMouseMove=(t=>{if(this.updateCursor(),this.lastDragPos)return t.preventDefault(),void this.onMouseDrag(t);this.hoveredLabel=null;const i=new e.Vec2(t.offsetX,t.offsetY),o=this.logicalToPhysicalViewSpace().transformPosition(i),s=this.configSpaceToPhysicalViewSpace().inverseTransformPosition(o);if(!s)return;const n=(t,i=0)=>{const o=t.end-t.start,r=this.props.renderInverted?this.configSpaceSize().y-1-i:i,a=new e.Rect(new e.Vec2(t.start,r),new e.Vec2(o,1));if(s.x<a.left())return null;if(s.x>a.right())return null;a.contains(s)&&(this.hoveredLabel={configSpaceBounds:a,node:t.node});for(let e of t.children)n(e,i+1)};for(let e of this.props.flamechart.getLayers()[0]||[])n(e);this.hoveredLabel?this.props.onNodeHover({node:this.hoveredLabel.node,event:t}):this.props.onNodeHover(null),this.renderCanvas()}),this.onMouseLeave=(e=>{this.hoveredLabel=null,this.props.onNodeHover(null),this.renderCanvas()}),this.onWheel=(t=>{t.preventDefault(),this.frameHadWheelEvent=!0;const i=t.metaKey||t.ctrlKey;let o=t.deltaY,s=t.deltaX;if(t.deltaMode===t.DOM_DELTA_LINE&&(o*=this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT,s*=this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT),i&&"pan"!==this.interactionLock){let i=1+o/100;t.ctrlKey&&(i=1+o/40),i=(0,e.clamp)(i,.1,10),this.zoom(new e.Vec2(t.offsetX,t.offsetY),i)}else"zoom"!==this.interactionLock&&this.pan(new e.Vec2(s,o));this.renderCanvas()}),this.onWindowKeyPress=(t=>{if(!this.container)return;const{width:i,height:o}=this.container.getBoundingClientRect();"="===t.key||"+"===t.key?(this.zoom(new e.Vec2(i/2,o/2),.5),t.preventDefault()):"-"!==t.key&&"_"!==t.key||(this.zoom(new e.Vec2(i/2,o/2),2),t.preventDefault()),t.ctrlKey||t.shiftKey||t.metaKey||("0"===t.key?this.zoom(new e.Vec2(i/2,o/2),1e9):"ArrowRight"===t.key||"KeyD"===t.code?this.pan(new e.Vec2(100,0)):"ArrowLeft"===t.key||"KeyA"===t.code?this.pan(new e.Vec2(-100,0)):"ArrowUp"===t.key||"KeyW"===t.code?this.pan(new e.Vec2(0,-100)):"ArrowDown"===t.key||"KeyS"===t.code?this.pan(new e.Vec2(0,100)):"Escape"===t.key&&(this.props.onNodeSelect(null),this.renderCanvas()))})}setConfigSpaceViewportRect(e){this.props.setConfigSpaceViewportRect(e)}configSpaceSize(){return new e.Vec2(this.props.flamechart.getTotalWeight(),this.props.flamechart.getLayers().length)}physicalViewSize(){return new e.Vec2(this.overlayCanvas?this.overlayCanvas.width:0,this.overlayCanvas?this.overlayCanvas.height:0)}physicalBounds(){if(this.props.renderInverted){const t=this.physicalViewSize().y,i=(this.configSpaceSize().y+1)*this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT*window.devicePixelRatio;if(i<t)return new e.Rect(new e.Vec2(0,t-i),this.physicalViewSize())}return new e.Rect(new e.Vec2(0,0),this.physicalViewSize())}configSpaceToPhysicalViewSpace(){return e.AffineTransform.betweenRects(this.props.configSpaceViewportRect,this.physicalBounds())}logicalToPhysicalViewSpace(){return e.AffineTransform.withScale(new e.Vec2(window.devicePixelRatio,window.devicePixelRatio))}resizeOverlayCanvasIfNeeded(){if(!this.overlayCanvas)return;let{width:e,height:t}=this.overlayCanvas.getBoundingClientRect();if(e=Math.floor(e),t=Math.floor(t),0===e||0===t)return;const i=e*window.devicePixelRatio,o=t*window.devicePixelRatio;i===this.overlayCanvas.width&&o===this.overlayCanvas.height||(this.overlayCanvas.width=i,this.overlayCanvas.height=o)}renderOverlays(){const o=this.overlayCtx;if(!o)return;if(this.props.configSpaceViewportRect.isEmpty())return;const s=this.configSpaceToPhysicalViewSpace(),n=t.FontSize.LABEL*window.devicePixelRatio,r=this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT*window.devicePixelRatio,a=this.physicalViewSize();if(o.clearRect(0,0,a.x,a.y),this.hoveredLabel){let e=t.Colors.DARK_GRAY;this.props.selectedNode===this.hoveredLabel.node&&(e=t.Colors.DARK_BLUE),o.lineWidth=2*devicePixelRatio,o.strokeStyle=e;const i=s.transformRect(this.hoveredLabel.configSpaceBounds);o.strokeRect(Math.round(i.left()),Math.round(i.top()),Math.round(Math.max(0,i.width())),Math.round(Math.max(0,i.height())))}o.font=`${n}px/${r}px ${t.FontFamily.MONOSPACE}`,o.textBaseline="alphabetic",o.fillStyle=t.Colors.DARK_GRAY;const h=(0,i.cachedMeasureTextWidth)(o,"M"+i.ELLIPSIS+"M"),c=(s.inverseTransformVector(new e.Vec2(h,0))||new e.Vec2(0,0)).x,l=5*window.devicePixelRatio,p=(t,d=0)=>{const f=t.end-t.start,w=this.props.renderInverted?this.configSpaceSize().y-1-d:d,u=new e.Rect(new e.Vec2(t.start,w),new e.Vec2(f,1));if(!(f<c||u.left()>this.props.configSpaceViewportRect.right()||u.right()<this.props.configSpaceViewportRect.left())){if(this.props.renderInverted){if(u.bottom()<this.props.configSpaceViewportRect.top())return}else if(u.top()>this.props.configSpaceViewportRect.bottom())return;if(u.hasIntersectionWith(this.props.configSpaceViewportRect)){let e=s.transformRect(u);if(e.left()<0&&(e=e.withOrigin(e.origin.withX(0)).withSize(e.size.withX(e.size.x+e.left()))),e.right()>a.x&&(e=e.withSize(e.size.withX(a.x-e.left()))),e.width()>h){const s=(0,i.trimTextMid)(o,t.node.frame.name,e.width()-2*l);o.fillText(s,e.left()+l,Math.round(e.bottom()-(r-n)/2))}}for(let e of t.children)p(e,d+1)}};for(let e of this.props.flamechart.getLayers()[0]||[])p(e);const d=2*window.devicePixelRatio;o.strokeStyle=t.Colors.PALE_DARK_BLUE,o.lineWidth=d;const f=(s.inverseTransformVector(new e.Vec2(1,0))||new e.Vec2(0,0)).x,w=(i,n=0)=>{if(!this.props.selectedNode)return;const r=i.end-i.start,a=this.props.renderInverted?this.configSpaceSize().y-1-n:n,h=new e.Rect(new e.Vec2(i.start,a),new e.Vec2(r,1));if(!(r<f||h.left()>this.props.configSpaceViewportRect.right()||h.right()<this.props.configSpaceViewportRect.left()||h.top()>this.props.configSpaceViewportRect.bottom())){if(h.hasIntersectionWith(this.props.configSpaceViewportRect)){const e=s.transformRect(h);i.node.frame===this.props.selectedNode.frame&&(i.node===this.props.selectedNode?o.strokeStyle!==t.Colors.DARK_BLUE&&(o.stroke(),o.beginPath(),o.strokeStyle=t.Colors.DARK_BLUE):o.strokeStyle!==t.Colors.PALE_DARK_BLUE&&(o.stroke(),o.beginPath(),o.strokeStyle=t.Colors.PALE_DARK_BLUE),o.rect(Math.round(e.left()+1+d/2),Math.round(e.top()+1+d/2),Math.round(Math.max(0,e.width()-2-d)),Math.round(Math.max(0,e.height()-2-d))))}for(let e of i.children)w(e,n+1)}};o.beginPath();for(let e of this.props.flamechart.getLayers()[0]||[])w(e);o.stroke(),this.renderTimeIndicators()}renderTimeIndicators(){const o=this.overlayCtx;if(!o)return;const s=this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT*window.devicePixelRatio,n=this.physicalViewSize(),r=this.configSpaceToPhysicalViewSpace(),a=(s-t.FontSize.LABEL*window.devicePixelRatio)/2,h=this.props.configSpaceViewportRect.left(),c=this.props.configSpaceViewportRect.right(),l=(this.configSpaceToPhysicalViewSpace().inverted()||new e.AffineTransform).times(this.logicalToPhysicalViewSpace()).transformVector(new e.Vec2(200,1)).x;let p=Math.pow(10,Math.floor(Math.log10(l)));l/p>5?p*=5:l/p>2&&(p*=2);{const l=this.props.renderInverted?n.y-s:0;o.fillStyle="rgba(255, 255, 255, 0.8)",o.fillRect(0,l,n.x,s),o.fillStyle=t.Colors.DARK_GRAY,o.textBaseline="top";for(let t=Math.ceil(h/p)*p;t<c;t+=p){const s=Math.round(r.transformPosition(new e.Vec2(t,0)).x),h=this.props.flamechart.formatValue(t),c=(0,i.cachedMeasureTextWidth)(o,h);o.fillText(h,s-c-a,l+a),o.fillRect(s,0,1,n.y)}}}updateConfigSpaceViewport(){if(!this.container)return;const{logicalSpaceViewportSize:t}=this.props,i=this.container.getBoundingClientRect(),{width:o,height:s}=i;if(!(o<2||s<2)){if(this.props.configSpaceViewportRect.isEmpty()){const t=s/this.LOGICAL_VIEW_SPACE_FRAME_HEIGHT;this.props.renderInverted?this.setConfigSpaceViewportRect(new e.Rect(new e.Vec2(0,this.configSpaceSize().y-t+1),new e.Vec2(this.configSpaceSize().x,t))):this.setConfigSpaceViewportRect(new e.Rect(new e.Vec2(0,-1),new e.Vec2(this.configSpaceSize().x,t)))}else t.equals(e.Vec2.zero)||t.x===o&&t.y===s||this.setConfigSpaceViewportRect(this.props.configSpaceViewportRect.withSize(this.props.configSpaceViewportRect.size.timesPointwise(new e.Vec2(o/t.x,s/t.y))));this.props.setLogicalSpaceViewportBounds(new e.Vec2(o,s))}}renderRects(){this.container&&(this.updateConfigSpaceViewport(),this.props.configSpaceViewportRect.isEmpty()||this.props.canvasContext.renderBehind(this.container,()=>{this.props.flamechartRenderer.render({physicalSpaceDstRect:this.physicalBounds(),configSpaceSrcRect:this.props.configSpaceViewportRect,renderOutlines:!0})}))}pan(t){this.interactionLock="pan";const i=this.logicalToPhysicalViewSpace().transformVector(t),o=this.configSpaceToPhysicalViewSpace().inverseTransformVector(i);this.hoveredLabel&&this.props.onNodeHover(null),o&&this.props.transformViewport(e.AffineTransform.withTranslation(o))}zoom(t,i){this.interactionLock="zoom";const o=this.logicalToPhysicalViewSpace().transformPosition(t),s=this.configSpaceToPhysicalViewSpace().inverseTransformPosition(o);if(!s)return;const n=e.AffineTransform.withTranslation(s.times(-1)).scaledBy(new e.Vec2(i,1)).translatedBy(s);this.props.transformViewport(n)}updateCursor(){this.lastDragPos?(document.body.style.cursor="grabbing",document.body.style.cursor="-webkit-grabbing"):document.body.style.cursor="default"}shouldComponentUpdate(){return!1}componentWillReceiveProps(e){this.props.flamechart!==e.flamechart?(this.hoveredLabel=null,this.renderCanvas()):this.props.selectedNode!==e.selectedNode?this.renderCanvas():this.props.configSpaceViewportRect!==e.configSpaceViewportRect&&this.renderCanvas()}componentDidMount(){this.props.canvasContext.addBeforeFrameHandler(this.onBeforeFrame),window.addEventListener("resize",this.onWindowResize),window.addEventListener("keydown",this.onWindowKeyPress)}componentWillUnmount(){this.props.canvasContext.removeBeforeFrameHandler(this.onBeforeFrame),window.removeEventListener("resize",this.onWindowResize),window.removeEventListener("keydown",this.onWindowKeyPress)}render(){return(0,s.h)("div",{className:(0,n.css)(o.style.panZoomView,t.commonStyle.vbox),onMouseDown:this.onMouseDown,onMouseMove:this.onMouseMove,onMouseLeave:this.onMouseLeave,onClick:this.onClick,onDblClick:this.onDblClick,onWheel:this.onWheel,ref:this.containerRef},(0,s.h)("canvas",{width:1,height:1,ref:this.overlayCanvasRef,className:(0,n.css)(o.style.fill)}))}}exports.FlamechartPanZoomView=r;
},{"../lib/math":102,"./style":79,"../lib/text-utils":173,"./flamechart-style":163,"preact":24,"aphrodite":68}],162:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Hovertip=void 0;var e=require("./style"),o=require("aphrodite"),t=require("preact");class i extends t.Component{render(){const{containerSize:i,offset:r}=this.props,n=i.x,p=i.y,d={};return r.x+7+e.Sizes.TOOLTIP_WIDTH_MAX<n?d.left=r.x+7:d.right=n-r.x+1,r.y+7+e.Sizes.TOOLTIP_HEIGHT_MAX<p?d.top=r.y+7:d.bottom=p-r.y+1,(0,t.h)("div",{className:(0,o.css)(s.hoverTip),style:d},(0,t.h)("div",{className:(0,o.css)(s.hoverTipRow)},this.props.children))}}exports.Hovertip=i;const r=2,s=o.StyleSheet.create({hoverTip:{position:"absolute",background:e.Colors.WHITE,border:"1px solid black",maxWidth:e.Sizes.TOOLTIP_WIDTH_MAX,paddingTop:2,paddingBottom:2,pointerEvents:"none",userSelect:"none",fontSize:e.FontSize.LABEL,fontFamily:e.FontFamily.MONOSPACE,zIndex:e.ZIndex.HOVERTIP},hoverTipRow:{textOverflow:"ellipsis",whiteSpace:"nowrap",overflowX:"hidden",paddingLeft:2,paddingRight:2,maxWidth:e.Sizes.TOOLTIP_WIDTH_MAX}});
},{"./style":79,"aphrodite":68,"preact":24}],115:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FlamechartView=void 0;var e=require("preact"),t=require("aphrodite"),r=require("../lib/math"),i=require("../lib/utils"),o=require("./flamechart-minimap-view"),s=require("./flamechart-style"),a=require("./style"),c=require("./flamechart-detail-view"),p=require("./flamechart-pan-zoom-view"),n=require("./hovertip"),h=require("../lib/typed-redux");class l extends h.StatelessComponent{constructor(){super(...arguments),this.setConfigSpaceViewportRect=(e=>{const t=a.Sizes.DETAIL_VIEW_HEIGHT/a.Sizes.FRAME_HEIGHT,i=this.configSpaceSize(),o=this.props.flamechart.getClampedViewportWidth(e.size.x),s=e.size.withX(o),c=r.Vec2.clamp(e.origin,new r.Vec2(0,-1),r.Vec2.max(r.Vec2.zero,i.minus(s).plus(new r.Vec2(0,t+1))));this.props.setConfigSpaceViewportRect(new r.Rect(c,e.size.withX(o)))}),this.setLogicalSpaceViewportSize=(e=>{this.props.setLogicalSpaceViewportSize(e)}),this.transformViewport=(e=>{const t=e.transformRect(this.props.configSpaceViewportRect);this.setConfigSpaceViewportRect(t)}),this.onNodeHover=(e=>{this.props.setNodeHover(e)}),this.onNodeClick=(e=>{this.props.setSelectedNode(e)}),this.container=null,this.containerRef=(e=>{this.container=e||null})}configSpaceSize(){return new r.Vec2(this.props.flamechart.getTotalWeight(),this.props.flamechart.getLayers().length)}formatValue(e){const t=100*e/this.props.flamechart.getTotalWeight(),r=(0,i.formatPercent)(t);return`${this.props.flamechart.formatValue(e)} (${r})`}renderTooltip(){if(!this.container)return null;const{hover:i}=this.props;if(!i)return null;const{width:o,height:a,left:c,top:p}=this.container.getBoundingClientRect(),h=new r.Vec2(i.event.clientX-c,i.event.clientY-p);return(0,e.h)(n.Hovertip,{containerSize:new r.Vec2(o,a),offset:h},(0,e.h)("span",{className:(0,t.css)(s.style.hoverCount)},this.formatValue(i.node.getTotalWeight()))," ",i.node.frame.name)}render(){return(0,e.h)("div",{className:(0,t.css)(s.style.fill,a.commonStyle.vbox),ref:this.containerRef},(0,e.h)(o.FlamechartMinimapView,{configSpaceViewportRect:this.props.configSpaceViewportRect,transformViewport:this.transformViewport,flamechart:this.props.flamechart,flamechartRenderer:this.props.flamechartRenderer,canvasContext:this.props.canvasContext,setConfigSpaceViewportRect:this.setConfigSpaceViewportRect}),(0,e.h)(p.FlamechartPanZoomView,{canvasContext:this.props.canvasContext,flamechart:this.props.flamechart,flamechartRenderer:this.props.flamechartRenderer,renderInverted:!1,onNodeHover:this.onNodeHover,onNodeSelect:this.onNodeClick,selectedNode:this.props.selectedNode,transformViewport:this.transformViewport,configSpaceViewportRect:this.props.configSpaceViewportRect,setConfigSpaceViewportRect:this.setConfigSpaceViewportRect,logicalSpaceViewportSize:this.props.logicalSpaceViewportSize,setLogicalSpaceViewportBounds:this.setLogicalSpaceViewportSize}),this.renderTooltip(),this.props.selectedNode&&(0,e.h)(c.FlamechartDetailView,{flamechart:this.props.flamechart,getCSSColorForFrame:this.props.getCSSColorForFrame,selectedNode:this.props.selectedNode}))}}exports.FlamechartView=l;
},{"preact":24,"aphrodite":68,"../lib/math":102,"../lib/utils":70,"./flamechart-minimap-view":159,"./flamechart-style":163,"./style":79,"./flamechart-detail-view":160,"./flamechart-pan-zoom-view":161,"./hovertip":162,"../lib/typed-redux":36}],62:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LeftHeavyFlamechartView=exports.getLeftHeavyFlamechart=exports.ChronoFlamechartView=exports.createMemoizedFlamechartRenderer=exports.getChronoViewFlamechart=void 0,exports.createFlamechartSetters=n;var e=require("../store/flamechart-view-state"),t=require("../lib/flamechart"),r=require("../gl/flamechart-renderer"),a=require("../lib/typed-redux"),o=require("../lib/utils"),l=require("./flamechart-view"),c=require("../store/getters"),i=require("../store/actions");function n(e,t,r){function a(a,o){return l=>{const c=Object.assign({},o(l),{id:t});e(a({profileIndex:r,args:c}))}}const{setHoveredNode:o,setLogicalSpaceViewportSize:l,setConfigSpaceViewportRect:c,setSelectedNode:n}=i.actions.flamechart;return{setNodeHover:a(o,e=>({hover:e})),setLogicalSpaceViewportSize:a(l,e=>({logicalSpaceViewportSize:e})),setConfigSpaceViewportRect:a(c,e=>({configSpaceViewportRect:e})),setSelectedNode:a(n,e=>({selectedNode:e}))}}const m=exports.getChronoViewFlamechart=(0,o.memoizeByShallowEquality)(({profile:e,getColorBucketForFrame:r})=>new t.Flamechart({getTotalWeight:e.getTotalWeight.bind(e),forEachCall:e.forEachCall.bind(e),formatValue:e.formatValue.bind(e),getColorBucketForFrame:r})),s=exports.createMemoizedFlamechartRenderer=(e=>(0,o.memoizeByShallowEquality)(({canvasContext:t,flamechart:a})=>new r.FlamechartRenderer(t.gl,(0,c.getRowAtlas)(t),a,t.rectangleBatchRenderer,t.flamechartColorPassRenderer,e))),h=s(),F=exports.ChronoFlamechartView=(0,a.createContainer)(l.FlamechartView,(t,r,a)=>{const{activeProfileState:o,glCanvas:l}=a,{index:i,profile:s,chronoViewState:F}=o,C=(0,c.getCanvasContext)(l),f=(0,c.getFrameToColorBucket)(s),g=(0,c.createGetColorBucketForFrame)(f),d=(0,c.createGetCSSColorForFrame)(f),u=m({profile:s,getColorBucketForFrame:g}),p=h({canvasContext:C,flamechart:u});return Object.assign({renderInverted:!1,flamechart:u,flamechartRenderer:p,canvasContext:C,getCSSColorForFrame:d},n(r,e.FlamechartID.CHRONO,i),F)}),C=exports.getLeftHeavyFlamechart=(0,o.memoizeByShallowEquality)(({profile:e,getColorBucketForFrame:r})=>new t.Flamechart({getTotalWeight:e.getTotalNonIdleWeight.bind(e),forEachCall:e.forEachCallGrouped.bind(e),formatValue:e.formatValue.bind(e),getColorBucketForFrame:r})),f=s(),g=exports.LeftHeavyFlamechartView=(0,a.createContainer)(l.FlamechartView,(t,r,a)=>{const{activeProfileState:o,glCanvas:l}=a,{index:i,profile:m,leftHeavyViewState:s}=o,h=(0,c.getCanvasContext)(l),F=(0,c.getFrameToColorBucket)(m),g=(0,c.createGetColorBucketForFrame)(F),d=(0,c.createGetCSSColorForFrame)(F),u=C({profile:m,getColorBucketForFrame:g}),p=f({canvasContext:h,flamechart:u});return Object.assign({renderInverted:!1,flamechart:u,flamechartRenderer:p,canvasContext:h,getCSSColorForFrame:d},n(r,e.FlamechartID.LEFT_HEAVY,i),s)});
},{"../store/flamechart-view-state":98,"../lib/flamechart":142,"../gl/flamechart-renderer":143,"../lib/typed-redux":36,"../lib/utils":70,"./flamechart-view":115,"../store/getters":38,"../store/actions":40}],167:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.style=exports.FlamechartWrapper=void 0;var e=require("aphrodite"),t=require("preact"),r=require("./style"),o=require("../lib/math"),i=require("./flamechart-pan-zoom-view"),s=require("../lib/utils"),a=require("./hovertip"),n=require("../lib/typed-redux");class p extends n.StatelessComponent{constructor(){super(...arguments),this.setConfigSpaceViewportRect=(e=>{this.props.setConfigSpaceViewportRect(this.clampViewportToFlamegraph(e))}),this.setLogicalSpaceViewportSize=(e=>{this.props.setLogicalSpaceViewportSize(e)}),this.transformViewport=(e=>{this.setConfigSpaceViewportRect(e.transformRect(this.props.configSpaceViewportRect))}),this.container=null,this.containerRef=(e=>{this.container=e||null}),this.setNodeHover=(e=>{this.props.setNodeHover(e)})}clampViewportToFlamegraph(e){const{flamechart:t,renderInverted:r}=this.props,i=new o.Vec2(t.getTotalWeight(),t.getLayers().length),s=this.props.flamechart.getClampedViewportWidth(e.size.x),a=e.size.withX(s),n=o.Vec2.clamp(e.origin,new o.Vec2(0,r?0:-1),o.Vec2.max(o.Vec2.zero,i.minus(a).plus(new o.Vec2(0,1))));return new o.Rect(n,e.size.withX(s))}formatValue(e){const t=100*e/this.props.flamechart.getTotalWeight(),r=(0,s.formatPercent)(t);return`${this.props.flamechart.formatValue(e)} (${r})`}renderTooltip(){if(!this.container)return null;const{hover:r}=this.props;if(!r)return null;const{width:i,height:s,left:n,top:p}=this.container.getBoundingClientRect(),l=new o.Vec2(r.event.clientX-n,r.event.clientY-p);return(0,t.h)(a.Hovertip,{containerSize:new o.Vec2(i,s),offset:l},(0,t.h)("span",{className:(0,e.css)(c.hoverCount)},this.formatValue(r.node.getTotalWeight()))," ",r.node.frame.name)}render(){return(0,t.h)("div",{className:(0,e.css)(r.commonStyle.fillY,r.commonStyle.fillX,r.commonStyle.vbox),ref:this.containerRef},(0,t.h)(i.FlamechartPanZoomView,{selectedNode:null,onNodeHover:this.setNodeHover,onNodeSelect:s.noop,configSpaceViewportRect:this.props.configSpaceViewportRect,setConfigSpaceViewportRect:this.setConfigSpaceViewportRect,transformViewport:this.transformViewport,flamechart:this.props.flamechart,flamechartRenderer:this.props.flamechartRenderer,canvasContext:this.props.canvasContext,renderInverted:this.props.renderInverted,logicalSpaceViewportSize:this.props.logicalSpaceViewportSize,setLogicalSpaceViewportBounds:this.setLogicalSpaceViewportSize}),this.renderTooltip())}}exports.FlamechartWrapper=p;const c=exports.style=e.StyleSheet.create({hoverCount:{color:r.Colors.GREEN}});
},{"aphrodite":68,"preact":24,"./style":79,"../lib/math":102,"./flamechart-pan-zoom-view":161,"../lib/utils":70,"./hovertip":162,"../lib/typed-redux":36}],137:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InvertedCallerFlamegraphView=void 0;var e=require("../lib/utils"),r=require("../lib/flamechart"),t=require("./flamechart-view-container"),a=require("../lib/typed-redux"),l=require("../store/getters"),o=require("../store/flamechart-view-state"),i=require("./flamechart-wrapper");const n=(0,e.memoizeByShallowEquality)(({profile:e,frame:r,flattenRecursion:t})=>{let a=e.getInvertedProfileForCallersOf(r);return t?a.getProfileWithRecursionFlattened():a}),c=(0,e.memoizeByShallowEquality)(({invertedCallerProfile:e,getColorBucketForFrame:t})=>new r.Flamechart({getTotalWeight:e.getTotalNonIdleWeight.bind(e),forEachCall:e.forEachCallGrouped.bind(e),formatValue:e.formatValue.bind(e),getColorBucketForFrame:t})),s=(0,t.createMemoizedFlamechartRenderer)({inverted:!0}),m=exports.InvertedCallerFlamegraphView=(0,a.createContainer)(i.FlamechartWrapper,(e,r,a)=>{const{activeProfileState:i}=a;let{profile:m,sandwichViewState:f,index:d}=i,{flattenRecursion:u,glCanvas:C}=e;if(!m)throw new Error("profile missing");if(!C)throw new Error("glCanvas missing");const{callerCallee:h}=f;if(!h)throw new Error("callerCallee missing");const{selectedFrame:F}=h;m=u?(0,l.getProfileWithRecursionFlattened)(m):m;const g=(0,l.getFrameToColorBucket)(m),v=(0,l.createGetColorBucketForFrame)(g),p=(0,l.createGetCSSColorForFrame)(g),w=(0,l.getCanvasContext)(C),S=c({invertedCallerProfile:n({profile:m,frame:F,flattenRecursion:u}),getColorBucketForFrame:v}),E=s({canvasContext:w,flamechart:S});return Object.assign({renderInverted:!0,flamechart:S,flamechartRenderer:E,canvasContext:w,getCSSColorForFrame:p},(0,t.createFlamechartSetters)(r,o.FlamechartID.SANDWICH_INVERTED_CALLERS,d),{setSelectedNode:()=>{}},h.invertedCallerFlamegraph)});
},{"../lib/utils":70,"../lib/flamechart":142,"./flamechart-view-container":62,"../lib/typed-redux":36,"../store/getters":38,"../store/flamechart-view-state":98,"./flamechart-wrapper":167}],138:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CalleeFlamegraphView=void 0;var e=require("../lib/utils"),r=require("../lib/flamechart"),t=require("./flamechart-view-container"),a=require("../lib/typed-redux"),l=require("../store/getters"),o=require("../store/flamechart-view-state"),i=require("./flamechart-wrapper");const c=(0,e.memoizeByShallowEquality)(({profile:e,frame:r,flattenRecursion:t})=>{let a=e.getProfileForCalleesOf(r);return t?a.getProfileWithRecursionFlattened():a}),n=(0,e.memoizeByShallowEquality)(({calleeProfile:e,getColorBucketForFrame:t})=>new r.Flamechart({getTotalWeight:e.getTotalNonIdleWeight.bind(e),forEachCall:e.forEachCallGrouped.bind(e),formatValue:e.formatValue.bind(e),getColorBucketForFrame:t})),s=(0,t.createMemoizedFlamechartRenderer)(),m=exports.CalleeFlamegraphView=(0,a.createContainer)(i.FlamechartWrapper,(e,r,a)=>{const{activeProfileState:i}=a,{index:m,profile:f,sandwichViewState:u}=i,{flattenRecursion:h,glCanvas:C}=e;if(!f)throw new Error("profile missing");if(!C)throw new Error("glCanvas missing");const{callerCallee:F}=u;if(!F)throw new Error("callerCallee missing");const{selectedFrame:g}=F,d=(0,l.getFrameToColorBucket)(f),p=(0,l.createGetColorBucketForFrame)(d),w=(0,l.createGetCSSColorForFrame)(d),v=(0,l.getCanvasContext)(C),S=n({calleeProfile:c({profile:f,frame:g,flattenRecursion:h}),getColorBucketForFrame:p}),q=s({canvasContext:v,flamechart:S});return Object.assign({renderInverted:!1,flamechart:S,flamechartRenderer:q,canvasContext:v,getCSSColorForFrame:w},(0,t.createFlamechartSetters)(r,o.FlamechartID.SANDWICH_CALLEES,m),{setSelectedNode:()=>{}},F.calleeFlamegraph)});
},{"../lib/utils":70,"../lib/flamechart":142,"./flamechart-view-container":62,"../lib/typed-redux":36,"../store/getters":38,"../store/flamechart-view-state":98,"./flamechart-wrapper":167}],60:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SandwichViewContainer=void 0;var e=require("aphrodite"),t=require("./profile-table-view"),a=require("preact"),l=require("./style"),r=require("../store/actions"),s=require("../lib/typed-redux"),i=require("./inverted-caller-flamegraph-view"),o=require("./callee-flamegraph-view");class n extends s.StatelessComponent{constructor(){super(...arguments),this.setSelectedFrame=(e=>{this.props.setSelectedFrame(e)}),this.onWindowKeyPress=(e=>{"Escape"===e.key&&this.setSelectedFrame(null)})}componentDidMount(){window.addEventListener("keydown",this.onWindowKeyPress)}componentWillUnmount(){window.removeEventListener("keydown",this.onWindowKeyPress)}render(){const{selectedFrame:r}=this.props;let s=null;return r&&(s=(0,a.h)("div",{className:(0,e.css)(l.commonStyle.fillY,c.callersAndCallees,l.commonStyle.vbox)},(0,a.h)("div",{className:(0,e.css)(l.commonStyle.hbox,c.panZoomViewWraper)},(0,a.h)("div",{className:(0,e.css)(c.flamechartLabelParent)},(0,a.h)("div",{className:(0,e.css)(c.flamechartLabel)},"Callers")),(0,a.h)(i.InvertedCallerFlamegraphView,{glCanvas:this.props.glCanvas,activeProfileState:this.props.activeProfileState})),(0,a.h)("div",{className:(0,e.css)(c.divider)}),(0,a.h)("div",{className:(0,e.css)(l.commonStyle.hbox,c.panZoomViewWraper)},(0,a.h)("div",{className:(0,e.css)(c.flamechartLabelParent,c.flamechartLabelParentBottom)},(0,a.h)("div",{className:(0,e.css)(c.flamechartLabel,c.flamechartLabelBottom)},"Callees")),(0,a.h)(o.CalleeFlamegraphView,{glCanvas:this.props.glCanvas,activeProfileState:this.props.activeProfileState})))),(0,a.h)("div",{className:(0,e.css)(l.commonStyle.hbox,l.commonStyle.fillY)},(0,a.h)("div",{className:(0,e.css)(c.tableView)},(0,a.h)(t.ProfileTableViewContainer,{activeProfileState:this.props.activeProfileState})),s)}}const c=e.StyleSheet.create({tableView:{flex:1},panZoomViewWraper:{flex:1},flamechartLabelParent:{display:"flex",flexDirection:"column",justifyContent:"flex-end",alignItems:"flex-start",fontSize:l.FontSize.TITLE,width:1.2*l.FontSize.TITLE,borderRight:`1px solid ${l.Colors.LIGHT_GRAY}`},flamechartLabelParentBottom:{justifyContent:"flex-start"},flamechartLabel:{transform:"rotate(-90deg)",transformOrigin:"50% 50% 0",width:1.2*l.FontSize.TITLE,flexShrink:1},flamechartLabelBottom:{transform:"rotate(-90deg)",display:"flex",justifyContent:"flex-end"},callersAndCallees:{flex:1,borderLeft:`${l.Sizes.SEPARATOR_HEIGHT}px solid ${l.Colors.LIGHT_GRAY}`},divider:{height:2,background:l.Colors.LIGHT_GRAY}}),d=exports.SandwichViewContainer=(0,s.createContainer)(n,(e,t,a)=>{const{activeProfileState:l,glCanvas:s}=a,{sandwichViewState:i,index:o}=l,{callerCallee:n}=i;return{activeProfileState:l,glCanvas:s,setSelectedFrame:e=>{t(r.actions.sandwichView.setSelectedFrame({profileIndex:o,args:e}))},selectedFrame:n?n.selectedFrame:null,profileIndex:o}});
},{"aphrodite":68,"./profile-table-view":55,"preact":24,"./style":79,"../store/actions":40,"../lib/typed-redux":36,"./inverted-caller-flamegraph-view":137,"./callee-flamegraph-view":138}],140:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ByteFormatter=exports.TimeFormatter=exports.RawValueFormatter=void 0;var t=require("./utils");class e{constructor(){this.unit="none"}format(t){return t.toLocaleString()}}exports.RawValueFormatter=e;class r{constructor(t){this.unit=t,this.multiplier="nanoseconds"===t?1e-9:"microseconds"===t?1e-6:"milliseconds"===t?.001:1}formatUnsigned(e){const r=e*this.multiplier;if(r/60>=1){const e=Math.floor(r/60),o=Math.floor(r-60*e).toString();return`${e}:${(0,t.zeroPad)(o,2)}`}return r/1>=1?`${r.toFixed(2)}s`:r/.001>=1?`${(r/.001).toFixed(2)}ms`:r/1e-6>=1?`${(r/1e-6).toFixed(2)}µs`:`${(r/1e-9).toFixed(2)}ns`}format(t){return`${t<0?"-":""}${this.formatUnsigned(Math.abs(t))}`}}exports.TimeFormatter=r;class o{constructor(){this.unit="bytes"}format(t){return t<1024?`${t.toFixed(0)} B`:(t/=1024)<1024?`${t.toFixed(2)} KB`:(t/=1024)<1024?`${t.toFixed(2)} MB`:`${(t/=1024).toFixed(2)} GB`}}exports.ByteFormatter=o;
},{"./utils":70}],145:[function(require,module,exports) {
var t=null;function r(){return t||(t=e()),t}function e(){try{throw new Error}catch(r){var t=(""+r.stack).match(/(https?|file|ftp):\/\/[^)\n]+/g);if(t)return n(t[0])}return"/"}function n(t){return(""+t).replace(/^((?:https?|file|ftp):\/\/.+)\/[^\/]+$/,"$1")+"/"}exports.getBundleURL=r,exports.getBaseURL=n;
},{}],66:[function(require,module,exports) {
var r=require("./bundle-url").getBundleURL;function e(r){Array.isArray(r)||(r=[r]);var e=r[r.length-1];try{return Promise.resolve(require(e))}catch(n){if("MODULE_NOT_FOUND"===n.code)return new u(function(n,i){t(r.slice(0,-1)).then(function(){return require(e)}).then(n,i)});throw n}}function t(r){return Promise.all(r.map(s))}var n={};function i(r,e){n[r]=e}module.exports=exports=e,exports.load=t,exports.register=i;var o={};function s(e){var t;if(Array.isArray(e)&&(t=e[1],e=e[0]),o[e])return o[e];var i=(e.substring(e.lastIndexOf(".")+1,e.length)||e).toLowerCase(),s=n[i];return s?o[e]=s(r()+e).then(function(r){return r&&module.bundle.register(t,r),r}):void 0}function u(r){this.executor=r,this.promise=null}u.prototype.then=function(r,e){return null===this.promise&&(this.promise=new Promise(this.executor)),this.promise.then(r,e)},u.prototype.catch=function(r){return null===this.promise&&(this.promise=new Promise(this.executor)),this.promise.catch(r)};
},{"./bundle-url":145}],139:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CallTreeProfileBuilder=exports.StackListProfileBuilder=exports.Profile=exports.CallTreeNode=exports.Frame=exports.HasWeights=void 0;var e=require("./utils"),t=require("./value-formatters"),s=function(e,t,s,r){return new(s||(s=Promise))(function(a,i){function l(e){try{h(r.next(e))}catch(e){i(e)}}function o(e){try{h(r.throw(e))}catch(e){i(e)}}function h(e){e.done?a(e.value):new s(function(t){t(e.value)}).then(l,o)}h((r=r.apply(e,t||[])).next())})};const r=require("_bundle_loader")(require.resolve("./demangle-cpp"));r.then(()=>{});class a{constructor(){this.selfWeight=0,this.totalWeight=0}getSelfWeight(){return this.selfWeight}getTotalWeight(){return this.totalWeight}addToTotalWeight(e){this.totalWeight+=e}addToSelfWeight(e){this.selfWeight+=e}overwriteWeightWith(e){this.selfWeight=e.selfWeight,this.totalWeight=e.totalWeight}}exports.HasWeights=a;class i extends a{constructor(e){super(),this.key=e.key,this.name=e.name,this.file=e.file,this.line=e.line,this.col=e.col}static getOrInsert(e,t){return e.getOrInsert(new i(t))}}exports.Frame=i,i.root=new i({key:"(speedscope root)",name:"(speedscope root)"});class l extends a{constructor(e,t){super(),this.frame=e,this.parent=t,this.children=[],this.frozen=!1}isRoot(){return this.frame===i.root}isFrozen(){return this.frozen}freeze(){this.frozen=!0}}exports.CallTreeNode=l;class o{constructor(s=0){this.name="",this.frames=new e.KeyedSet,this.appendOrderCalltreeRoot=new l(i.root,null),this.groupedCalltreeRoot=new l(i.root,null),this.samples=[],this.weights=[],this.valueFormatter=new t.RawValueFormatter,this.totalNonIdleWeight=null,this.totalWeight=s}getAppendOrderCalltreeRoot(){return this.appendOrderCalltreeRoot}getGroupedCalltreeRoot(){return this.groupedCalltreeRoot}formatValue(e){return this.valueFormatter.format(e)}setValueFormatter(e){this.valueFormatter=e}getWeightUnit(){return this.valueFormatter.unit}getName(){return this.name}setName(e){this.name=e}getTotalWeight(){return this.totalWeight}getTotalNonIdleWeight(){return null===this.totalNonIdleWeight&&(this.totalNonIdleWeight=this.groupedCalltreeRoot.children.reduce((e,t)=>e+t.getTotalWeight(),0)),this.totalNonIdleWeight}forEachCallGrouped(e,t){!function s(r,a){r.frame!==i.root&&e(r,a);let l=0;const o=[...r.children];o.sort((e,t)=>e.getTotalWeight()>t.getTotalWeight()?-1:1),o.forEach(function(e){s(e,a+l),l+=e.getTotalWeight()}),r.frame!==i.root&&t(r,a+r.getTotalWeight())}(this.groupedCalltreeRoot,0)}forEachCall(t,s){let r=[],a=0,l=0;for(let o of this.samples){let h=null;for(h=o;h&&h.frame!=i.root&&-1===r.indexOf(h);h=h.parent);for(;r.length>0&&(0,e.lastOf)(r)!=h;){s(r.pop(),a)}const n=[];for(let e=o;e&&e.frame!=i.root&&e!=h;e=e.parent)n.push(e);n.reverse();for(let e of n)t(e,a);r=r.concat(n),a+=this.weights[l++]}for(let e=r.length-1;e>=0;e--)s(r[e],a)}forEachFrame(e){this.frames.forEach(e)}forEachSample(e){for(let t=0;t<this.samples.length;t++)e(this.samples[t],this.weights[t])}getProfileWithRecursionFlattened(){const e=new n,t=[],s=new Set;this.forEachCall(function(r,a){s.has(r.frame)?t.push(null):(s.add(r.frame),t.push(r),e.enterFrame(r.frame,a))},function(r,a){const i=t.pop();i&&(s.delete(i.frame),e.leaveFrame(i.frame,a))});const r=e.build();return r.name=this.name,r.valueFormatter=this.valueFormatter,this.forEachFrame(e=>{r.frames.getOrInsert(e).overwriteWeightWith(e)}),r}getInvertedProfileForCallersOf(e){const t=i.getOrInsert(this.frames,e),s=new h,r=[];!function e(s){if(s.frame===t)r.push(s);else for(let t of s.children)e(t)}(this.appendOrderCalltreeRoot);for(let e of r){const t=[];for(let s=e;null!=s&&s.frame!==i.root;s=s.parent)t.push(s.frame);s.appendSampleWithWeight(t,e.getTotalWeight())}const a=s.build();return a.name=this.name,a.valueFormatter=this.valueFormatter,a}getProfileForCalleesOf(e){const t=i.getOrInsert(this.frames,e),s=new h;!function e(r){if(r.frame===t)!function(e){const t=[];!function e(r){t.push(r.frame),s.appendSampleWithWeight(t,r.getSelfWeight());for(let t of r.children)e(t);t.pop()}(e)}(r);else for(let t of r.children)e(t)}(this.appendOrderCalltreeRoot);const r=s.build();return r.name=this.name,r.valueFormatter=this.valueFormatter,r}demangle(){return s(this,void 0,void 0,function*(){let e=null;for(let t of this.frames)t.name.startsWith("__Z")&&(e||(e=(yield r).demangleCpp),t.name=e(t.name))})}remapNames(e){for(let t of this.frames)t.name=e(t.name)}}exports.Profile=o;class h extends o{constructor(){super(...arguments),this.pendingSample=null}_appendSample(t,s,r){if(isNaN(s))throw new Error("invalid weight");let a=r?this.appendOrderCalltreeRoot:this.groupedCalltreeRoot,o=new Set;for(let h of t){const t=i.getOrInsert(this.frames,h),n=r?(0,e.lastOf)(a.children):a.children.find(e=>e.frame===t);if(n&&!n.isFrozen()&&n.frame==t)a=n;else{const e=a;a=new l(t,a),e.children.push(a)}a.addToTotalWeight(s),o.add(a.frame)}if(a.addToSelfWeight(s),r)for(let e of a.children)e.freeze();if(r){a.frame.addToSelfWeight(s);for(let e of o)e.addToTotalWeight(s);a===(0,e.lastOf)(this.samples)?this.weights[this.weights.length-1]+=s:(this.samples.push(a),this.weights.push(s))}}appendSampleWithWeight(e,t){if(0!==t){if(t<0)throw new Error("Samples must have positive weights");this._appendSample(e,t,!0),this._appendSample(e,t,!1)}}appendSampleWithTimestamp(e,t){if(this.pendingSample){if(t<this.pendingSample.centralTimestamp)throw new Error("Timestamps received out of order");const s=(t+this.pendingSample.centralTimestamp)/2;this.appendSampleWithWeight(this.pendingSample.stack,s-this.pendingSample.startTimestamp),this.pendingSample={stack:e,startTimestamp:s,centralTimestamp:t}}else this.pendingSample={stack:e,startTimestamp:t,centralTimestamp:t}}build(){return this.pendingSample&&(this.samples.length>0?this.appendSampleWithWeight(this.pendingSample.stack,this.pendingSample.centralTimestamp-this.pendingSample.startTimestamp):(this.appendSampleWithWeight(this.pendingSample.stack,1),this.setValueFormatter(new t.RawValueFormatter))),this.totalWeight=Math.max(this.totalWeight,this.weights.reduce((e,t)=>e+t,0)),this}}exports.StackListProfileBuilder=h;class n extends o{constructor(){super(...arguments),this.appendOrderStack=[this.appendOrderCalltreeRoot],this.groupedOrderStack=[this.groupedCalltreeRoot],this.framesInStack=new Map,this.stack=[],this.lastValue=0}addWeightsToFrames(t){const s=t-this.lastValue;for(let e of this.framesInStack.keys())e.addToTotalWeight(s);const r=(0,e.lastOf)(this.stack);r&&r.addToSelfWeight(s)}addWeightsToNodes(t,s){const r=t-this.lastValue;for(let e of s)e.addToTotalWeight(r);const a=(0,e.lastOf)(s);a&&a.addToSelfWeight(r)}_enterFrame(t,s,r){let a=r?this.appendOrderStack:this.groupedOrderStack;this.addWeightsToNodes(s,a);let i=(0,e.lastOf)(a);if(i){if(r){const e=s-this.lastValue;if(e>0)this.samples.push(i),this.weights.push(s-this.lastValue);else if(e<0)throw new Error(`Samples must be provided in increasing order of cumulative value. Last sample was ${this.lastValue}, this sample was ${s}`)}const o=r?(0,e.lastOf)(i.children):i.children.find(e=>e.frame===t);let h;o&&!o.isFrozen()&&o.frame==t?h=o:(h=new l(t,i),i.children.push(h)),a.push(h)}}enterFrame(e,t){const s=i.getOrInsert(this.frames,e);this.addWeightsToFrames(t),this._enterFrame(s,t,!0),this._enterFrame(s,t,!1),this.stack.push(s);const r=this.framesInStack.get(s)||0;this.framesInStack.set(s,r+1),this.lastValue=t}_leaveFrame(e,t,s){let r=s?this.appendOrderStack:this.groupedOrderStack;if(this.addWeightsToNodes(t,r),s){const s=this.appendOrderStack.pop();if(null==s)throw new Error(`Trying to leave ${e.key} when stack is empty`);if(null==this.lastValue)throw new Error(`Trying to leave a ${e.key} before any have been entered`);s.freeze();const r=t-this.lastValue;if(r>0)this.samples.push(s),this.weights.push(t-this.lastValue);else if(r<0)throw new Error(`Samples must be provided in increasing order of cumulative value. Last sample was ${this.lastValue}, this sample was ${t}`)}else this.groupedOrderStack.pop()}leaveFrame(e,t){const s=i.getOrInsert(this.frames,e);this.addWeightsToFrames(t),this._leaveFrame(s,t,!0),this._leaveFrame(s,t,!1),this.stack.pop();const r=this.framesInStack.get(s);null!=r&&(1===r?this.framesInStack.delete(s):this.framesInStack.set(s,r-1),this.lastValue=t,this.totalWeight=Math.max(this.totalWeight,this.lastValue))}build(){if(this.appendOrderStack.length>1||this.groupedOrderStack.length>1)throw new Error("Tried to complete profile construction with a non-empty stack");return this}}exports.CallTreeProfileBuilder=n;
},{"./utils":70,"./value-formatters":140,"_bundle_loader":66,"./demangle-cpp":[["demangle-cpp.8a387750.js",180],"demangle-cpp.8a387750.map",180]}],141:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=exports.FileFormat=void 0;!function(e){let t,o;!function(e){e.EVENTED="evented",e.SAMPLED="sampled"}(t=e.ProfileType||(e.ProfileType={})),function(e){e.OPEN_FRAME="O",e.CLOSE_FRAME="C"}(o=e.EventType||(e.EventType={}))}(e||(exports.FileFormat=e={}));
},{}],19:[function(require,module,exports) {
module.exports={name:"speedscope",version:"1.5.3",description:"",repository:"jlfwong/speedscope",main:"index.js",bin:{speedscope:"./bin/cli.js"},scripts:{deploy:"./scripts/deploy.sh",prepack:"./scripts/build-release.sh",prettier:"prettier --write 'src/**/*.ts' 'src/**/*.tsx'",lint:"eslint 'src/**/*.ts' 'src/**/*.tsx'",jest:"./scripts/test-setup.sh && jest --runInBand",coverage:"npm run jest -- --coverage && coveralls < coverage/lcov.info",test:"tsc --noEmit && npm run lint && npm run coverage",serve:"parcel assets/index.html --open --no-autoinstall"},files:["bin/cli.js","dist/release/**","!*.map"],browserslist:["last 2 Chrome versions","last 2 Firefox versions"],author:"",license:"MIT",devDependencies:{"@types/jest":"22.2.3","@types/jszip":"3.1.4","@types/node":"10.1.4","@types/pako":"1.0.0",aphrodite:"2.1.0",coveralls:"3.0.1",eslint:"4.19.1","eslint-plugin-prettier":"2.6.0",jest:"24.3.0",jsverify:"0.8.3",jszip:"3.1.5",pako:"1.0.6","parcel-bundler":"1.9.2",preact:"8.2.7","preact-redux":"jlfwong/preact-redux#a56dcc4",prettier:"1.12.0",protobufjs:"6.8.8",quicktype:"15.0.209",redux:"^4.0.0","ts-jest":"24.3.0",typescript:"3.2.4","typescript-eslint-parser":"17.0.1","uglify-es":"3.2.2"},jest:{transform:{"^.+\\.tsx?$":"ts-jest"},testRegex:"\\.test\\.tsx?$",collectCoverageFrom:["**/*.{ts,tsx}","!**/*.d.{ts,tsx}"],moduleFileExtensions:["ts","tsx","js","jsx","json"]},dependencies:{opn:"5.3.0"}};
},{}],83:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.exportProfileGroup=r,exports.importSpeedscopeProfiles=s,exports.saveToFile=l;var e=require("./profile"),t=require("./value-formatters"),n=require("./file-format-spec");function r(e){const t=[],n=new Map;function r(e){let r=n.get(e);if(null==r){const o={name:e.name};null!=e.file&&(o.file=e.file),null!=e.line&&(o.line=e.line),null!=e.col&&(o.col=e.col),r=t.length,n.set(e,r),t.push(o)}return r}const a={exporter:`speedscope@${require("../../package.json").version}`,name:e.name,activeProfileIndex:e.indexToView,$schema:"https://www.speedscope.app/file-format-schema.json",shared:{frames:t},profiles:[]};for(let t of e.profiles)a.profiles.push(o(t,r));return a}function o(e,t){const r={type:n.FileFormat.ProfileType.EVENTED,name:e.getName(),unit:e.getWeightUnit(),startValue:0,endValue:e.getTotalWeight(),events:[]};return e.forEachCall((e,o)=>{r.events.push({type:n.FileFormat.EventType.OPEN_FRAME,frame:t(e.frame),at:o})},(e,o)=>{r.events.push({type:n.FileFormat.EventType.CLOSE_FRAME,frame:t(e.frame),at:o})}),r}function a(r,o){function a(e){const{name:n,unit:o}=r;switch(o){case"nanoseconds":case"microseconds":case"milliseconds":case"seconds":e.setValueFormatter(new t.TimeFormatter(o));break;case"bytes":e.setValueFormatter(new t.ByteFormatter);break;case"none":e.setValueFormatter(new t.RawValueFormatter)}e.setName(n)}switch(r.type){case n.FileFormat.ProfileType.EVENTED:return function(t){const{startValue:r,endValue:s,events:l}=t,i=new e.CallTreeProfileBuilder(s-r);a(i);const c=o.map((e,t)=>Object.assign({key:t},e));for(let e of l)switch(e.type){case n.FileFormat.EventType.OPEN_FRAME:i.enterFrame(c[e.frame],e.at-r);break;case n.FileFormat.EventType.CLOSE_FRAME:i.leaveFrame(c[e.frame],e.at-r)}return i.build()}(r);case n.FileFormat.ProfileType.SAMPLED:return function(t){const{startValue:n,endValue:r,samples:s,weights:l}=t,i=new e.StackListProfileBuilder(r-n);a(i);const c=o.map((e,t)=>Object.assign({key:t},e));if(s.length!==l.length)throw new Error(`Expected samples.length (${s.length}) to equal weights.length (${l.length})`);for(let e=0;e<s.length;e++){const t=s[e],n=l[e];i.appendSampleWithWeight(t.map(e=>c[e]),n)}return i.build()}(r)}}function s(e){return{name:e.name||e.profiles[0].name||"profile",indexToView:e.activeProfileIndex||0,profiles:e.profiles.map(t=>a(t,e.shared.frames))}}function l(e){const t=r(e),n=new Blob([JSON.stringify(t)],{type:"text/json"}),o=`${(t.name?t.name.split(".")[0]:"profile").replace(/\W+/g,"_")}.speedscope.json`;console.log("Saving",o);const a=document.createElement("a");a.download=o,a.href=window.URL.createObjectURL(n),a.dataset.downloadurl=["text/json",a.download,a.href].join(":"),document.body.appendChild(a),a.click(),document.body.removeChild(a)}
},{"./profile":139,"./value-formatters":140,"./file-format-spec":141,"../../package.json":19}],64:[function(require,module,exports) {
module.exports="perf-vertx-stacks-01-collapsed-all.3e0a632c.txt";
},{}],34:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Application=exports.GLCanvas=exports.Toolbar=void 0;var e=require("preact"),t=require("aphrodite"),o=require("./style"),i=require("../lib/emscripten"),s=require("./sandwich-view"),r=require("../lib/file-format"),n=require("../store"),a=require("../lib/typed-redux"),l=require("./flamechart-view-container"),c=require("../gl/graphics"),d=function(e,t,o,i){return new(o||(o=Promise))(function(s,r){function n(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){e.done?s(e.value):new o(function(t){t(e.value)}).then(n,a)}l((i=i.apply(e,t||[])).next())})};const p=require("_bundle_loader")(require.resolve("../import"));function h(e,t){return d(this,void 0,void 0,function*(){return(yield p).importProfileGroupFromText(e,t)})}function f(e,t){return d(this,void 0,void 0,function*(){return(yield p).importProfileGroupFromBase64(e,t)})}function m(e,t){return d(this,void 0,void 0,function*(){return(yield p).importProfilesFromArrayBuffer(e,t)})}function u(e){return d(this,void 0,void 0,function*(){return(yield p).importProfilesFromFile(e)})}function v(e){return d(this,void 0,void 0,function*(){return(yield p).importFromFileSystemDirectoryEntry(e)})}p.then(()=>{});const g=require("../../sample/profiles/stackcollapse/perf-vertx-stacks-01-collapsed-all.txt");class w extends a.StatelessComponent{constructor(){super(...arguments),this.setTimeOrder=(()=>{this.props.setViewMode(n.ViewMode.CHRONO_FLAME_CHART)}),this.setLeftHeavyOrder=(()=>{this.props.setViewMode(n.ViewMode.LEFT_HEAVY_FLAME_GRAPH)}),this.setSandwichView=(()=>{this.props.setViewMode(n.ViewMode.SANDWICH_VIEW)})}renderLeftContent(){return this.props.activeProfileState?(0,e.h)("div",{className:(0,t.css)(y.toolbarLeft)},(0,e.h)("div",{className:(0,t.css)(y.toolbarTab,this.props.viewMode===n.ViewMode.CHRONO_FLAME_CHART&&y.toolbarTabActive),onClick:this.setTimeOrder},(0,e.h)("span",{className:(0,t.css)(y.emoji)},"🕰"),"Time Order"),(0,e.h)("div",{className:(0,t.css)(y.toolbarTab,this.props.viewMode===n.ViewMode.LEFT_HEAVY_FLAME_GRAPH&&y.toolbarTabActive),onClick:this.setLeftHeavyOrder},(0,e.h)("span",{className:(0,t.css)(y.emoji)},"⬅️"),"Left Heavy"),(0,e.h)("div",{className:(0,t.css)(y.toolbarTab,this.props.viewMode===n.ViewMode.SANDWICH_VIEW&&y.toolbarTabActive),onClick:this.setSandwichView},(0,e.h)("span",{className:(0,t.css)(y.emoji)},"🥪"),"Sandwich")):null}renderCenterContent(){const{activeProfileState:o,profileGroup:i}=this.props;if(o&&i){const{index:r}=o;if(1===i.profiles.length)return o.profile.getName();{function s(o,i,s){return(0,e.h)("button",{disabled:i,onClick:s,className:(0,t.css)(y.emoji,y.toolbarProfileNavButton,i&&y.toolbarProfileNavButtonDisabled)},o)}const n=s("⬅️",0===r,()=>this.props.setProfileIndexToView(r-1)),a=s("➡️",r>=i.profiles.length-1,()=>this.props.setProfileIndexToView(r+1));return(0,e.h)("div",{className:(0,t.css)(y.toolbarCenter)},n,o.profile.getName()," ",(0,e.h)("span",{className:(0,t.css)(y.toolbarProfileIndex)},"(",o.index+1,"/",i.profiles.length,")"),a)}}return"🔬speedscope"}renderRightContent(){const o=(0,e.h)("div",{className:(0,t.css)(y.toolbarTab),onClick:this.props.browseForFile},(0,e.h)("span",{className:(0,t.css)(y.emoji)},"⤵️"),"Import"),i=(0,e.h)("div",{className:(0,t.css)(y.toolbarTab)},(0,e.h)("a",{href:"https://github.com/jlfwong/speedscope#usage",className:(0,t.css)(y.noLinkStyle),target:"_blank"},(0,e.h)("span",{className:(0,t.css)(y.emoji)},"❓"),"Help"));return(0,e.h)("div",{className:(0,t.css)(y.toolbarRight)},this.props.activeProfileState&&(0,e.h)("div",{className:(0,t.css)(y.toolbarTab),onClick:this.props.saveFile},(0,e.h)("span",{className:(0,t.css)(y.emoji)},"⤴️"),"Export"),o,i)}render(){return(0,e.h)("div",{className:(0,t.css)(y.toolbar)},this.renderLeftContent(),this.renderCenterContent(),this.renderRightContent())}}exports.Toolbar=w;class b extends e.Component{constructor(){super(...arguments),this.canvas=null,this.ref=(e=>{e instanceof HTMLCanvasElement?this.canvas=e:this.canvas=null,this.props.setGLCanvas(this.canvas)}),this.container=null,this.containerRef=(e=>{e instanceof HTMLElement?this.container=e:this.container=null}),this.maybeResize=(()=>{if(!this.container)return;if(!this.props.canvasContext)return;let{width:e,height:t}=this.container.getBoundingClientRect();const o=e,i=t,s=e*window.devicePixelRatio,r=t*window.devicePixelRatio;this.props.canvasContext.gl.resize(s,r,o,i),this.props.canvasContext.gl.clear(new c.Graphics.Color(1,1,1,1))}),this.onWindowResize=(()=>{this.props.canvasContext&&this.props.canvasContext.requestFrame()})}componentWillReceiveProps(e){this.props.canvasContext!==e.canvasContext&&(this.props.canvasContext&&this.props.canvasContext.removeBeforeFrameHandler(this.maybeResize),e.canvasContext&&(e.canvasContext.addBeforeFrameHandler(this.maybeResize),e.canvasContext.requestFrame()))}componentDidMount(){window.addEventListener("resize",this.onWindowResize)}componentWillUnmount(){this.props.canvasContext&&this.props.canvasContext.removeBeforeFrameHandler(this.maybeResize),window.removeEventListener("resize",this.onWindowResize)}render(){return(0,e.h)("div",{ref:this.containerRef,className:(0,t.css)(y.glCanvasView)},(0,e.h)("canvas",{ref:this.ref,width:1,height:1}))}}exports.GLCanvas=b;class C extends a.StatelessComponent{constructor(){super(...arguments),this.loadExample=(()=>{this.loadProfile(()=>d(this,void 0,void 0,function*(){return yield h("perf-vertx-stacks-01-collapsed-all.txt",yield fetch(g).then(e=>e.text()))}))}),this.onDrop=(e=>{if(this.props.setDragActive(!1),e.preventDefault(),!e.dataTransfer)return;const t=e.dataTransfer.items[0];if("webkitGetAsEntry"in t){const e=t.webkitGetAsEntry();if(e.isDirectory&&e.name.endsWith(".trace"))return console.log("Importing as Instruments.app .trace file"),void this.loadProfile(()=>d(this,void 0,void 0,function*(){return yield v(e)}))}let o=e.dataTransfer.files.item(0);o&&this.loadFromFile(o)}),this.onDragOver=(e=>{this.props.setDragActive(!0),e.preventDefault()}),this.onDragLeave=(e=>{this.props.setDragActive(!1),e.preventDefault()}),this.onWindowKeyPress=(e=>d(this,void 0,void 0,function*(){if("1"===e.key)this.props.setViewMode(n.ViewMode.CHRONO_FLAME_CHART);else if("2"===e.key)this.props.setViewMode(n.ViewMode.LEFT_HEAVY_FLAME_GRAPH);else if("3"===e.key)this.props.setViewMode(n.ViewMode.SANDWICH_VIEW);else if("r"===e.key){const{flattenRecursion:e}=this.props;this.props.setFlattenRecursion(!e)}else if("n"===e.key){const{activeProfileState:e}=this.props;e&&this.props.setProfileIndexToView(e.index+1)}else if("p"===e.key){const{activeProfileState:e}=this.props;e&&this.props.setProfileIndexToView(e.index-1)}})),this.saveFile=(()=>{if(this.props.profileGroup){const{name:e,indexToView:t,profiles:o}=this.props.profileGroup,i={name:e,indexToView:t,profiles:o.map(e=>e.profile)};(0,r.saveToFile)(i)}}),this.browseForFile=(()=>{const e=document.createElement("input");e.type="file",e.addEventListener("change",this.onFileSelect),e.click()}),this.onWindowKeyDown=(e=>d(this,void 0,void 0,function*(){"s"===e.key&&(e.ctrlKey||e.metaKey)?(e.preventDefault(),this.saveFile()):"o"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.browseForFile())})),this.onDocumentPaste=(e=>{e.preventDefault(),e.stopPropagation();const t=e.clipboardData;if(!t)return;const o=t.getData("text");this.loadProfile(()=>d(this,void 0,void 0,function*(){return yield h("From Clipboard",o)}))}),this.onFileSelect=(e=>{const t=e.target.files.item(0);t&&this.loadFromFile(t)})}loadProfile(e){return d(this,void 0,void 0,function*(){if(this.props.setLoading(!0),yield new Promise(e=>setTimeout(e,0)),!this.props.glCanvas)return;console.time("import");let t=null;try{t=yield e()}catch(e){return console.log("Failed to load format",e),void this.props.setError(!0)}if(null==t)return alert("Unrecognized format! See documentation about supported formats."),void this.props.setLoading(!1);if(0===t.profiles.length)return alert("Successfully imported profile, but it's empty!"),void this.props.setLoading(!1);this.props.hashParams.title&&(t=Object.assign({name:this.props.hashParams.title},t)),document.title=`${t.name} - speedscope`;for(let e of t.profiles)yield e.demangle();for(let e of t.profiles){const t=this.props.hashParams.title||e.getName();e.setName(t)}console.timeEnd("import"),this.props.setProfileGroup(t),this.props.setLoading(!1)})}loadFromFile(e){this.loadProfile(()=>d(this,void 0,void 0,function*(){const t=yield u(e);if(t){for(let o of t.profiles)o.getName()||o.setName(e.name);return t}if(this.props.profileGroup&&this.props.activeProfileState){const t=new FileReader,o=new Promise(e=>{t.addEventListener("loadend",()=>{if("string"!=typeof t.result)throw new Error("Expected reader.result to be a string");e(t.result)})});t.readAsText(e);const s=yield o,r=(0,i.importEmscriptenSymbolMap)(s);if(r){const{profile:e,index:t}=this.props.activeProfileState;return console.log("Importing as emscripten symbol map"),e.remapNames(e=>r.get(e)||e),{name:this.props.profileGroup.name||"profile",indexToView:t,profiles:[e]}}}return null}))}componentDidMount(){window.addEventListener("keydown",this.onWindowKeyDown),window.addEventListener("keypress",this.onWindowKeyPress),document.addEventListener("paste",this.onDocumentPaste),this.maybeLoadHashParamProfile()}componentWillUnmount(){window.removeEventListener("keydown",this.onWindowKeyDown),window.removeEventListener("keypress",this.onWindowKeyPress),document.removeEventListener("paste",this.onDocumentPaste)}maybeLoadHashParamProfile(){return d(this,void 0,void 0,function*(){if(this.props.hashParams.profileURL){if(!n.canUseXHR)return void alert(`Cannot load a profile URL when loading from "${window.location.protocol}" URL protocol`);this.loadProfile(()=>d(this,void 0,void 0,function*(){const e=yield fetch(this.props.hashParams.profileURL);let t=new URL(this.props.hashParams.profileURL).pathname;return t.includes("/")&&(t=t.slice(t.lastIndexOf("/")+1)),yield m(t,yield e.arrayBuffer())}))}else if(this.props.hashParams.localProfilePath){window.speedscope={loadFileFromBase64:(e,t)=>{this.loadProfile(()=>f(e,t))}};const e=document.createElement("script");e.src=`file:///${this.props.hashParams.localProfilePath}`,document.head.appendChild(e)}})}renderLanding(){return(0,e.h)("div",{className:(0,t.css)(y.landingContainer)},(0,e.h)("div",{className:(0,t.css)(y.landingMessage)},(0,e.h)("p",{className:(0,t.css)(y.landingP)},"👋 Hi there! Welcome to 🔬speedscope, an interactive"," ",(0,e.h)("a",{className:(0,t.css)(y.link),href:"http://www.brendangregg.com/FlameGraphs/cpuflamegraphs.html"},"flamegraph")," ","visualizer. Use it to help you make your software faster."),n.canUseXHR?(0,e.h)("p",{className:(0,t.css)(y.landingP)},"Drag and drop a profile file onto this window to get started, click the big blue button below to browse for a profile to explore, or"," ",(0,e.h)("a",{tabIndex:0,className:(0,t.css)(y.link),onClick:this.loadExample},"click here")," ","to load an example profile."):(0,e.h)("p",{className:(0,t.css)(y.landingP)},"Drag and drop a profile file onto this window to get started, or click the big blue button below to browse for a profile to explore."),(0,e.h)("div",{className:(0,t.css)(y.browseButtonContainer)},(0,e.h)("input",{type:"file",name:"file",id:"file",onChange:this.onFileSelect,className:(0,t.css)(y.hide)}),(0,e.h)("label",{for:"file",className:(0,t.css)(y.browseButton),tabIndex:0},"Browse")),(0,e.h)("p",{className:(0,t.css)(y.landingP)},"See the"," ",(0,e.h)("a",{className:(0,t.css)(y.link),href:"https://github.com/jlfwong/speedscope#usage",target:"_blank"},"documentation")," ","for information about supported file formats, keyboard shortcuts, and how to navigate around the profile."),(0,e.h)("p",{className:(0,t.css)(y.landingP)},"speedscope is open source. Please"," ",(0,e.h)("a",{className:(0,t.css)(y.link),target:"_blank",href:"https://github.com/jlfwong/speedscope/issues"},"report any issues on GitHub"),".")))}renderError(){return(0,e.h)("div",{className:(0,t.css)(y.error)},(0,e.h)("div",null,"😿 Something went wrong."),(0,e.h)("div",null,"Check the JS console for more details."))}renderLoadingBar(){return(0,e.h)("div",{className:(0,t.css)(y.loading)})}renderContent(){const{viewMode:t,activeProfileState:o,error:i,loading:r,glCanvas:a}=this.props;if(i)return this.renderError();if(r)return this.renderLoadingBar();if(!o||!a)return this.renderLanding();switch(t){case n.ViewMode.CHRONO_FLAME_CHART:return(0,e.h)(l.ChronoFlamechartView,{activeProfileState:o,glCanvas:a});case n.ViewMode.LEFT_HEAVY_FLAME_GRAPH:return(0,e.h)(l.LeftHeavyFlamechartView,{activeProfileState:o,glCanvas:a});case n.ViewMode.SANDWICH_VIEW:return(0,e.h)(s.SandwichViewContainer,{activeProfileState:o,glCanvas:a})}}render(){return(0,e.h)("div",{onDrop:this.onDrop,onDragOver:this.onDragOver,onDragLeave:this.onDragLeave,className:(0,t.css)(y.root,this.props.dragActive&&y.dragTargetRoot)},(0,e.h)(b,{setGLCanvas:this.props.setGLCanvas,canvasContext:this.props.canvasContext}),(0,e.h)(w,Object.assign({saveFile:this.saveFile,browseForFile:this.browseForFile},this.props)),(0,e.h)("div",{className:(0,t.css)(y.contentContainer)},this.renderContent()),this.props.dragActive&&(0,e.h)("div",{className:(0,t.css)(y.dragTarget)}))}}exports.Application=C;const y=t.StyleSheet.create({glCanvasView:{position:"absolute",width:"100vw",height:"100vh",zIndex:-1,pointerEvents:"none"},error:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%"},loading:{height:3,marginBottom:-3,background:o.Colors.DARK_BLUE,transformOrigin:"0% 50%",animationName:[{from:{transform:"scaleX(0)"},to:{transform:"scaleX(1)"}}],animationTimingFunction:"cubic-bezier(0, 1, 0, 1)",animationDuration:"30s"},root:{width:"100vw",height:"100vh",overflow:"hidden",display:"flex",flexDirection:"column",position:"relative",fontFamily:o.FontFamily.MONOSPACE,lineHeight:"20px"},dragTargetRoot:{cursor:"copy"},dragTarget:{boxSizing:"border-box",position:"absolute",top:0,left:0,width:"100%",height:"100%",border:`5px dashed ${o.Colors.DARK_BLUE}`,pointerEvents:"none"},contentContainer:{position:"relative",display:"flex",overflow:"hidden",flexDirection:"column",flex:1},landingContainer:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},landingMessage:{maxWidth:600},landingP:{marginBottom:16},hide:{display:"none"},browseButtonContainer:{display:"flex",alignItems:"center",justifyContent:"center"},browseButton:{marginBottom:16,height:72,flex:1,maxWidth:256,textAlign:"center",fontSize:o.FontSize.BIG_BUTTON,lineHeight:"72px",background:o.Colors.DARK_BLUE,color:o.Colors.WHITE,transition:`all ${o.Duration.HOVER_CHANGE} ease-in`,":hover":{background:o.Colors.BRIGHT_BLUE}},link:{color:o.Colors.BRIGHT_BLUE,cursor:"pointer",textDecoration:"none"},toolbar:{height:o.Sizes.TOOLBAR_HEIGHT,flexShrink:0,background:o.Colors.BLACK,color:o.Colors.WHITE,textAlign:"center",fontFamily:o.FontFamily.MONOSPACE,fontSize:o.FontSize.TITLE,lineHeight:`${o.Sizes.TOOLBAR_TAB_HEIGHT}px`,userSelect:"none"},toolbarLeft:{position:"absolute",height:o.Sizes.TOOLBAR_HEIGHT,overflow:"hidden",top:0,left:0,marginRight:2,textAlign:"left"},toolbarCenter:{paddingTop:1,height:o.Sizes.TOOLBAR_HEIGHT},toolbarRight:{height:o.Sizes.TOOLBAR_HEIGHT,overflow:"hidden",position:"absolute",top:0,right:0,marginRight:2,textAlign:"right"},toolbarProfileIndex:{color:o.Colors.LIGHT_GRAY},toolbarProfileNavButton:{opacity:.8,fontSize:o.FontSize.TITLE,lineHeight:`${o.Sizes.TOOLBAR_TAB_HEIGHT}px`,":hover":{opacity:1},background:"none",border:"none",padding:0,marginLeft:"0.3em",marginRight:"0.3em",transition:`all ${o.Duration.HOVER_CHANGE} ease-in`},toolbarProfileNavButtonDisabled:{opacity:.5,":hover":{opacity:.5}},toolbarTab:{background:o.Colors.DARK_GRAY,marginTop:o.Sizes.SEPARATOR_HEIGHT,height:o.Sizes.TOOLBAR_TAB_HEIGHT,lineHeight:`${o.Sizes.TOOLBAR_TAB_HEIGHT}px`,paddingLeft:2,paddingRight:8,display:"inline-block",marginLeft:2,transition:`all ${o.Duration.HOVER_CHANGE} ease-in`,":hover":{background:o.Colors.GRAY}},toolbarTabActive:{background:o.Colors.BRIGHT_BLUE,":hover":{background:o.Colors.BRIGHT_BLUE}},noLinkStyle:{textDecoration:"none",color:"inherit"},emoji:{display:"inline-block",verticalAlign:"middle",paddingTop:"0px",marginRight:"0.3em"}});
},{"preact":24,"aphrodite":68,"./style":79,"../lib/emscripten":81,"./sandwich-view":60,"../lib/file-format":83,"../store":29,"../lib/typed-redux":36,"./flamechart-view-container":62,"../gl/graphics":42,"_bundle_loader":66,"../import":[["import.a03c2bef.js",104],"import.a03c2bef.map",104],"../../sample/profiles/stackcollapse/perf-vertx-stacks-01-collapsed-all.txt":64}],21:[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ApplicationContainer=void 0;var e=require("../lib/typed-redux"),t=require("./application"),i=require("../store/getters"),o=require("../store/actions"),n=require("../gl/graphics");const r=exports.ApplicationContainer=(0,e.createContainer)(t.Application,(t,r)=>{const{flattenRecursion:s,profileGroup:a}=t;let l=null;if(a&&a.profiles.length>a.indexToView){const e=a.indexToView,t=a.profiles[e];l=Object.assign({},a.profiles[a.indexToView],{profile:(0,i.getProfileToView)({profile:t.profile,flattenRecursion:s}),index:a.indexToView})}function c(t){return(0,e.bindActionCreator)(r,t)}const p={setGLCanvas:c(o.actions.setGLCanvas),setLoading:c(o.actions.setLoading),setError:c(o.actions.setError),setProfileGroup:c(o.actions.setProfileGroup),setDragActive:c(o.actions.setDragActive),setViewMode:c(o.actions.setViewMode),setFlattenRecursion:c(o.actions.setFlattenRecursion),setProfileIndexToView:c(o.actions.setProfileIndexToView)};return Object.assign({activeProfileState:l,dispatch:r,canvasContext:t.glCanvas?(0,i.getCanvasContext)(t.glCanvas):null,resizeCanvas:(e,o,r,s)=>{if(t.glCanvas){const a=(0,i.getCanvasContext)(t.glCanvas).gl;a.resize(e,o,r,s),a.clear(new n.Graphics.Color(1,1,1,1))}}},p,t)});
},{"../lib/typed-redux":36,"./application":34,"../store/getters":38,"../store/actions":40,"../gl/graphics":42}],13:[function(require,module,exports) {
"use strict";var e=require("preact"),o=require("./store"),t=require("preact-redux"),r=require("./views/application-container");console.log(`speedscope v${require("../package.json").version}`),module.hot&&(module.hot.dispose(()=>{(0,e.render)((0,e.h)("div",null),document.body,document.body.lastElementChild||void 0)}),module.hot.accept());const i=window.store,d=(0,o.createApplicationStore)(i?i.getState():{});window.store=d,(0,e.render)((0,e.h)(t.Provider,{store:d},(0,e.h)(r.ApplicationContainer,null)),document.body,document.body.lastElementChild||void 0);
},{"preact":24,"./store":29,"preact-redux":26,"./views/application-container":21,"../package.json":19}],215:[function(require,module,exports) {
module.exports=function(n){return new Promise(function(e,o){var r=document.createElement("script");r.async=!0,r.type="text/javascript",r.charset="utf-8",r.src=n,r.onerror=function(n){r.onerror=r.onload=null,o(n)},r.onload=function(){r.onerror=r.onload=null,e()},document.getElementsByTagName("head")[0].appendChild(r)})};
},{}],0:[function(require,module,exports) {
var b=require(66);b.register("js",require(215));
},{}]},{},[0,13], null)
//# sourceMappingURL=speedscope.9ee942dd.map
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/App.tsx
|
TypeScript (TSX)
|
import CssBaseline from "@material-ui/core/CssBaseline";
import React from "react";
import { Provider } from "react-redux";
import { BrowserRouter, Route } from "react-router-dom";
import Dashboard from "./pages/dashboard/Dashboard";
import Errors from "./pages/dashboard/dialogs/errors/Errors";
import Logs from "./pages/dashboard/dialogs/logs/Logs";
import { store } from "./store";
class App extends React.Component {
render() {
return (
<Provider store={store}>
<BrowserRouter>
<CssBaseline />
<Dashboard />
<Route component={Logs} path="/logs/:hostname/:pid?" />
<Route component={Errors} path="/errors/:hostname/:pid?" />
</BrowserRouter>
</Provider>
);
}
}
export default App;
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/api.ts
|
TypeScript
|
const base =
process.env.NODE_ENV === "development"
? "http://localhost:8265"
: window.location.origin;
// TODO(mitchellstern): Add JSON schema validation for the responses.
const get = async <T>(path: string, params: { [key: string]: any }) => {
const url = new URL(path, base);
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
const response = await fetch(url.toString());
const json = await response.json();
const { result, error } = json;
if (error !== null) {
throw Error(error);
}
return result as T;
};
export interface RayConfigResponse {
min_workers: number;
max_workers: number;
initial_workers: number;
autoscaling_mode: string;
idle_timeout_minutes: number;
head_type: string;
worker_type: string;
}
export const getRayConfig = () => get<RayConfigResponse>("/api/ray_config", {});
export interface NodeInfoResponse {
clients: Array<{
now: number;
hostname: string;
ip: string;
boot_time: number; // System boot time expressed in seconds since epoch
cpu: number; // System-wide CPU utilization expressed as a percentage
cpus: [number, number]; // Number of logical CPUs and physical CPUs
mem: [number, number, number]; // Total, available, and used percentage of memory
disk: {
[path: string]: {
total: number;
free: number;
used: number;
percent: number;
};
};
load_avg: [[number, number, number], [number, number, number]];
net: [number, number]; // Sent and received network traffic in bytes / second
workers: Array<{
pid: number;
create_time: number;
cmdline: string[];
cpu_percent: number;
cpu_times: {
system: number;
children_system: number;
user: number;
children_user: number;
};
memory_info: {
pageins: number;
pfaults: number;
vms: number;
rss: number;
};
}>;
}>;
log_counts: {
[ip: string]: {
[pid: string]: number;
};
};
error_counts: {
[ip: string]: {
[pid: string]: number;
};
};
}
export const getNodeInfo = () => get<NodeInfoResponse>("/api/node_info", {});
export interface RayletInfoResponse {
nodes: {
[ip: string]: {
extraInfo?: string;
workersStats: {
pid: number;
isDriver?: boolean;
}[];
};
};
actors: {
[actorId: string]:
| {
actorId: string;
children: RayletInfoResponse["actors"];
ipAddress: string;
isDirectCall: boolean;
jobId: string;
numLocalObjects: number;
numObjectIdsInScope: number;
port: number;
state: 0 | 1 | 2;
taskQueueLength: number;
usedObjectStoreMemory: number;
usedResources: { [key: string]: number };
currentTaskDesc?: string;
currentTaskFuncDesc?: string[];
numPendingTasks?: number;
webuiDisplay?: string;
}
| {
actorId: string;
requiredResources: { [key: string]: number };
state: -1;
};
};
}
export const getRayletInfo = () =>
get<RayletInfoResponse>("/api/raylet_info", {});
export interface ErrorsResponse {
[pid: string]: Array<{
message: string;
timestamp: number;
type: string;
}>;
}
export const getErrors = (hostname: string, pid: string | undefined) =>
get<ErrorsResponse>("/api/errors", { hostname, pid: pid || "" });
export interface LogsResponse {
[pid: string]: string[];
}
export const getLogs = (hostname: string, pid: string | undefined) =>
get<LogsResponse>("/api/logs", { hostname, pid: pid || "" });
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/common/DialogWithTitle.tsx
|
TypeScript (TSX)
|
import Dialog from "@material-ui/core/Dialog";
import IconButton from "@material-ui/core/IconButton";
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography";
import CloseIcon from "@material-ui/icons/Close";
import React from "react";
const styles = (theme: Theme) =>
createStyles({
paper: {
padding: theme.spacing(3)
},
closeButton: {
position: "absolute",
right: theme.spacing(1.5),
top: theme.spacing(1.5),
zIndex: 1
},
title: {
borderBottomColor: theme.palette.divider,
borderBottomStyle: "solid",
borderBottomWidth: 1,
fontSize: "1.5rem",
lineHeight: 1,
marginBottom: theme.spacing(3),
paddingBottom: theme.spacing(3)
}
});
interface Props {
handleClose: () => void;
title: string;
}
class DialogWithTitle extends React.Component<
Props & WithStyles<typeof styles>
> {
render() {
const { classes, handleClose, title } = this.props;
return (
<Dialog
classes={{ paper: classes.paper }}
fullWidth
maxWidth="md"
onClose={handleClose}
open
scroll="body"
>
<IconButton className={classes.closeButton} onClick={handleClose}>
<CloseIcon />
</IconButton>
<Typography className={classes.title}>{title}</Typography>
{this.props.children}
</Dialog>
);
}
}
export default withStyles(styles)(DialogWithTitle);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/common/NumberedLines.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import classNames from "classnames";
import React from "react";
const styles = (theme: Theme) =>
createStyles({
root: {
overflowX: "auto"
},
cell: {
borderWidth: 0,
fontFamily: "SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace",
padding: 0,
"&:last-child": {
paddingRight: 0
}
},
lineNumber: {
color: theme.palette.text.secondary,
paddingRight: theme.spacing(2),
textAlign: "right",
verticalAlign: "top",
width: "1%",
// Use a ::before pseudo-element for the line number so that it won't
// interact with user selections or searching.
"&::before": {
content: "attr(data-line-number)"
}
},
line: {
textAlign: "left",
whiteSpace: "pre-wrap"
}
});
interface Props {
lines: string[];
}
class NumberedLines extends React.Component<Props & WithStyles<typeof styles>> {
render() {
const { classes, lines } = this.props;
return (
<Table>
<TableBody>
{lines.map((line, index) => (
<TableRow key={index}>
<TableCell
className={classNames(classes.cell, classes.lineNumber)}
data-line-number={index + 1}
/>
<TableCell className={classNames(classes.cell, classes.line)}>
{line}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
}
export default withStyles(styles)(NumberedLines);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/common/UsageBar.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import React from "react";
const blend = (
[r1, g1, b1]: number[],
[r2, g2, b2]: number[],
ratio: number
) => [
r1 * (1 - ratio) + r2 * ratio,
g1 * (1 - ratio) + g2 * ratio,
b1 * (1 - ratio) + b2 * ratio
];
const styles = (theme: Theme) =>
createStyles({
root: {
borderColor: theme.palette.divider,
borderStyle: "solid",
borderWidth: 1
},
inner: {
paddingLeft: theme.spacing(1),
paddingRight: theme.spacing(1)
}
});
interface Props {
percent: number;
text: string;
}
class UsageBar extends React.Component<Props & WithStyles<typeof styles>> {
render() {
const { classes, text } = this.props;
let { percent } = this.props;
percent = Math.max(percent, 0);
percent = Math.min(percent, 100);
const minColor = [0, 255, 0];
const maxColor = [255, 0, 0];
const leftColor = minColor;
const rightColor = blend(minColor, maxColor, percent / 100);
const alpha = 0.2;
const gradient = `
linear-gradient(
to right,
rgba(${leftColor.join(",")}, ${alpha}) 0%,
rgba(${rightColor.join(",")}, ${alpha}) ${percent}%,
transparent ${percent}%
)
`;
// Use a nested `div` here because the right border is affected by the
// gradient background otherwise.
return (
<div className={classes.root}>
<div className={classes.inner} style={{ background: gradient }}>
{text}
</div>
</div>
);
}
}
export default withStyles(styles)(UsageBar);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/common/formatUtils.ts
|
TypeScript
|
export const formatByteAmount = (
amount: number,
unit: "mebibyte" | "gibibyte"
) =>
`${(
amount / (unit === "mebibyte" ? Math.pow(1024, 2) : Math.pow(1024, 3))
).toFixed(1)} ${unit === "mebibyte" ? "MiB" : "GiB"}`;
export const formatUsage = (
used: number,
total: number,
unit: "mebibyte" | "gibibyte"
) => {
const usedFormatted = formatByteAmount(used, unit);
const totalFormatted = formatByteAmount(total, unit);
const percent = (100 * used) / total;
return `${usedFormatted} / ${totalFormatted} (${percent.toFixed(0)}%)`;
};
export const formatDuration = (durationInSeconds: number) => {
const durationSeconds = Math.floor(durationInSeconds) % 60;
const durationMinutes = Math.floor(durationInSeconds / 60) % 60;
const durationHours = Math.floor(durationInSeconds / 60 / 60) % 24;
const durationDays = Math.floor(durationInSeconds / 60 / 60 / 24);
const pad = (value: number) => value.toString().padStart(2, "0");
return [
durationDays ? `${durationDays}d` : "",
`${pad(durationHours)}h`,
`${pad(durationMinutes)}m`,
`${pad(durationSeconds)}s`
].join(" ");
};
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/index.tsx
|
TypeScript (TSX)
|
import React from "react";
import ReactDOM from "react-dom";
import "typeface-roboto";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/Dashboard.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Tab from "@material-ui/core/Tab";
import Tabs from "@material-ui/core/Tabs";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { connect } from "react-redux";
import { getNodeInfo, getRayletInfo } from "../../api";
import { StoreState } from "../../store";
import LastUpdated from "./LastUpdated";
import LogicalView from "./logical-view/LogicalView";
import NodeInfo from "./node-info/NodeInfo";
import RayConfig from "./ray-config/RayConfig";
import { dashboardActions } from "./state";
const styles = (theme: Theme) =>
createStyles({
root: {
backgroundColor: theme.palette.background.paper,
padding: theme.spacing(2),
"& > :not(:first-child)": {
marginTop: theme.spacing(4)
}
},
tabs: {
borderBottomColor: theme.palette.divider,
borderBottomStyle: "solid",
borderBottomWidth: 1
}
});
const mapStateToProps = (state: StoreState) => ({
tab: state.dashboard.tab
});
const mapDispatchToProps = dashboardActions;
class Dashboard extends React.Component<
WithStyles<typeof styles> &
ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps
> {
refreshNodeAndRayletInfo = async () => {
try {
const [nodeInfo, rayletInfo] = await Promise.all([
getNodeInfo(),
getRayletInfo()
]);
this.props.setNodeAndRayletInfo({ nodeInfo, rayletInfo });
this.props.setError(null);
} catch (error) {
this.props.setError(error.toString());
} finally {
setTimeout(this.refreshNodeAndRayletInfo, 1000);
}
};
async componentDidMount() {
await this.refreshNodeAndRayletInfo();
}
handleTabChange = (event: React.ChangeEvent<{}>, value: number) => {
this.props.setTab(value);
};
render() {
const { classes, tab } = this.props;
const tabs = [
{ label: "Machine view", component: NodeInfo },
{ label: "Logical view", component: LogicalView },
{ label: "Ray config", component: RayConfig }
];
const SelectedComponent = tabs[tab].component;
return (
<div className={classes.root}>
<Typography variant="h5">Ray Dashboard</Typography>
<Tabs
className={classes.tabs}
indicatorColor="primary"
onChange={this.handleTabChange}
textColor="primary"
value={tab}
>
{tabs.map(({ label }) => (
<Tab key={label} label={label} />
))}
</Tabs>
<SelectedComponent />
<LastUpdated />
</div>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(Dashboard));
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/LastUpdated.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { connect } from "react-redux";
import { StoreState } from "../../store";
const styles = (theme: Theme) =>
createStyles({
root: {
marginTop: theme.spacing(2)
},
lastUpdated: {
color: theme.palette.text.secondary,
fontSize: "0.8125rem",
textAlign: "center"
},
error: {
color: theme.palette.error.main,
fontSize: "0.8125rem",
textAlign: "center"
}
});
const mapStateToProps = (state: StoreState) => ({
lastUpdatedAt: state.dashboard.lastUpdatedAt,
error: state.dashboard.error
});
class LastUpdated extends React.Component<
WithStyles<typeof styles> & ReturnType<typeof mapStateToProps>
> {
render() {
const { classes, lastUpdatedAt, error } = this.props;
return (
<div className={classes.root}>
{lastUpdatedAt !== null && (
<Typography className={classes.lastUpdated}>
Last updated: {new Date(lastUpdatedAt).toLocaleString()}
</Typography>
)}
{error !== null && (
<Typography className={classes.error}>{error}</Typography>
)}
</div>
);
}
}
export default connect(mapStateToProps)(withStyles(styles)(LastUpdated));
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/dialogs/errors/Errors.tsx
|
TypeScript (TSX)
|
import { fade } from "@material-ui/core/styles/colorManipulator";
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { RouteComponentProps } from "react-router";
import { ErrorsResponse, getErrors } from "../../../../api";
import DialogWithTitle from "../../../../common/DialogWithTitle";
import NumberedLines from "../../../../common/NumberedLines";
const styles = (theme: Theme) =>
createStyles({
header: {
lineHeight: 1,
marginBottom: theme.spacing(3),
marginTop: theme.spacing(3)
},
error: {
backgroundColor: fade(theme.palette.error.main, 0.04),
borderLeftColor: theme.palette.error.main,
borderLeftStyle: "solid",
borderLeftWidth: 2,
marginTop: theme.spacing(3),
padding: theme.spacing(2)
},
timestamp: {
color: theme.palette.text.secondary,
marginBottom: theme.spacing(1)
}
});
interface State {
result: ErrorsResponse | null;
error: string | null;
}
class Errors extends React.Component<
WithStyles<typeof styles> &
RouteComponentProps<{ hostname: string; pid: string | undefined }>,
State
> {
state: State = {
result: null,
error: null
};
handleClose = () => {
this.props.history.push("/");
};
async componentDidMount() {
try {
const { match } = this.props;
const { hostname, pid } = match.params;
const result = await getErrors(hostname, pid);
this.setState({ result, error: null });
} catch (error) {
this.setState({ result: null, error: error.toString() });
}
}
render() {
const { classes, match } = this.props;
const { result, error } = this.state;
const { hostname } = match.params;
return (
<DialogWithTitle handleClose={this.handleClose} title="Errors">
{error !== null ? (
<Typography color="error">{error}</Typography>
) : result === null ? (
<Typography color="textSecondary">Loading...</Typography>
) : (
Object.entries(result).map(([pid, errors]) => (
<React.Fragment key={pid}>
<Typography className={classes.header}>
{hostname} (PID: {pid})
</Typography>
{errors.length > 0 ? (
errors.map(({ message, timestamp }, index) => (
<div className={classes.error} key={index}>
<Typography className={classes.timestamp}>
Error at {new Date(timestamp * 1000).toLocaleString()}
</Typography>
<NumberedLines lines={message.trim().split("\n")} />
</div>
))
) : (
<Typography color="textSecondary">No errors found.</Typography>
)}
</React.Fragment>
))
)}
</DialogWithTitle>
);
}
}
export default withStyles(styles)(Errors);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/dialogs/logs/Logs.tsx
|
TypeScript (TSX)
|
import { fade } from "@material-ui/core/styles/colorManipulator";
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { RouteComponentProps } from "react-router";
import { getLogs, LogsResponse } from "../../../../api";
import DialogWithTitle from "../../../../common/DialogWithTitle";
import NumberedLines from "../../../../common/NumberedLines";
const styles = (theme: Theme) =>
createStyles({
header: {
lineHeight: 1,
marginBottom: theme.spacing(3),
marginTop: theme.spacing(3)
},
log: {
backgroundColor: fade(theme.palette.primary.main, 0.04),
borderLeftColor: theme.palette.primary.main,
borderLeftStyle: "solid",
borderLeftWidth: 2,
padding: theme.spacing(2)
}
});
interface State {
result: LogsResponse | null;
error: string | null;
}
class Logs extends React.Component<
WithStyles<typeof styles> &
RouteComponentProps<{ hostname: string; pid: string | undefined }>,
State
> {
state: State = {
result: null,
error: null
};
handleClose = () => {
this.props.history.push("/");
};
async componentDidMount() {
try {
const { match } = this.props;
const { hostname, pid } = match.params;
const result = await getLogs(hostname, pid);
this.setState({ result, error: null });
} catch (error) {
this.setState({ result: null, error: error.toString() });
}
}
render() {
const { classes, match } = this.props;
const { result, error } = this.state;
const { hostname } = match.params;
return (
<DialogWithTitle handleClose={this.handleClose} title="Logs">
{error !== null ? (
<Typography color="error">{error}</Typography>
) : result === null ? (
<Typography color="textSecondary">Loading...</Typography>
) : (
Object.entries(result).map(([pid, lines]) => (
<React.Fragment key={pid}>
<Typography className={classes.header}>
{hostname} (PID: {pid})
</Typography>
{lines.length > 0 ? (
<div className={classes.log}>
<NumberedLines lines={lines} />
</div>
) : (
<Typography color="textSecondary">No logs found.</Typography>
)}
</React.Fragment>
))
)}
</DialogWithTitle>
);
}
}
export default withStyles(styles)(Logs);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/logical-view/Actor.tsx
|
TypeScript (TSX)
|
import Typography from "@material-ui/core/Typography";
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import React from "react";
import { RayletInfoResponse } from "../../../api";
import Actors from "./Actors";
import Collapse from "@material-ui/core/Collapse";
const styles = (theme: Theme) =>
createStyles({
root: {
borderColor: theme.palette.divider,
borderStyle: "solid",
borderWidth: 1,
marginTop: theme.spacing(2),
padding: theme.spacing(2)
},
title: {
color: theme.palette.text.secondary,
fontSize: "0.75rem"
},
infeasible: {
color: theme.palette.error.main
},
information: {
fontSize: "0.875rem"
},
datum: {
"&:not(:first-child)": {
marginLeft: theme.spacing(2)
}
},
webuiDisplay: {
fontSize: "0.875rem"
},
expandCollapseButton: {
color: theme.palette.primary.main,
"&:hover": {
cursor: "pointer"
}
}
});
interface Props {
actor: RayletInfoResponse["actors"][keyof RayletInfoResponse["actors"]];
}
interface State {
expanded: boolean;
}
class Actor extends React.Component<Props & WithStyles<typeof styles>, State> {
state: State = {
expanded: true
};
setExpanded = (expanded: boolean) => () => {
this.setState({ expanded });
};
render() {
const { classes, actor } = this.props;
const { expanded } = this.state;
const information =
actor.state !== -1
? [
{
label: "ID",
value: actor.actorId
},
{
label: "Resources",
value:
Object.entries(actor.usedResources).length > 0 &&
Object.entries(actor.usedResources)
.map(([key, value]) => `${value.toLocaleString()} ${key}`)
.join(", ")
},
{
label: "Pending",
value:
actor.taskQueueLength !== undefined &&
actor.taskQueueLength > 0 &&
actor.taskQueueLength.toLocaleString()
},
{
label: "Task",
value:
actor.currentTaskFuncDesc && actor.currentTaskFuncDesc.join(".")
}
]
: [
{
label: "ID",
value: actor.actorId
},
{
label: "Required resources",
value:
Object.entries(actor.requiredResources).length > 0 &&
Object.entries(actor.requiredResources)
.map(([key, value]) => `${value.toLocaleString()} ${key}`)
.join(", ")
}
];
return (
<div className={classes.root}>
<Typography className={classes.title}>
{actor.state !== -1 ? (
<React.Fragment>
Actor {actor.actorId}{" "}
{Object.entries(actor.children).length > 0 && (
<React.Fragment>
(
<span
className={classes.expandCollapseButton}
onClick={this.setExpanded(!expanded)}
>
{expanded ? "Collapse" : "Expand"}
</span>
)
</React.Fragment>
)}
</React.Fragment>
) : (
<span className={classes.infeasible}>Infeasible actor</span>
)}
</Typography>
<Typography className={classes.information}>
{information.map(
({ label, value }) =>
value &&
value.length > 0 && (
<React.Fragment key={label}>
<span className={classes.datum}>
{label}: {value}
</span>{" "}
</React.Fragment>
)
)}
</Typography>
{actor.state !== -1 && (
<React.Fragment>
{actor.webuiDisplay && (
<Typography className={classes.webuiDisplay}>
{actor.webuiDisplay}
</Typography>
)}
<Collapse in={expanded}>
<Actors actors={actor.children} />
</Collapse>
</React.Fragment>
)}
</div>
);
}
}
export default withStyles(styles)(Actor);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/logical-view/Actors.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import React from "react";
import { RayletInfoResponse } from "../../../api";
import Actor from "./Actor";
const styles = (theme: Theme) => createStyles({});
interface Props {
actors: RayletInfoResponse["actors"];
}
class Actors extends React.Component<Props & WithStyles<typeof styles>> {
render() {
const { actors } = this.props;
return Object.entries(actors).map(([actorId, actor]) => (
<Actor actor={actor} key={actorId} />
));
}
}
export default withStyles(styles)(Actors);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/logical-view/LogicalView.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { connect } from "react-redux";
import { StoreState } from "../../../store";
import Actors from "./Actors";
const styles = (theme: Theme) => createStyles({});
const mapStateToProps = (state: StoreState) => ({
rayletInfo: state.dashboard.rayletInfo
});
class LogicalView extends React.Component<
WithStyles<typeof styles> & ReturnType<typeof mapStateToProps>
> {
render() {
const { rayletInfo } = this.props;
if (rayletInfo === null) {
return <Typography color="textSecondary">Loading...</Typography>;
}
if (Object.entries(rayletInfo.actors).length === 0) {
return <Typography color="textSecondary">No actors found.</Typography>;
}
return (
<div>
<Actors actors={rayletInfo.actors} />
</div>
);
}
}
export default connect(mapStateToProps)(withStyles(styles)(LogicalView));
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/NodeInfo.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { connect } from "react-redux";
import { StoreState } from "../../../store";
import NodeRowGroup from "./NodeRowGroup";
import TotalRow from "./TotalRow";
const styles = (theme: Theme) =>
createStyles({
table: {
marginTop: theme.spacing(1)
},
cell: {
padding: theme.spacing(1),
textAlign: "center",
"&:last-child": {
paddingRight: theme.spacing(1)
}
}
});
const mapStateToProps = (state: StoreState) => ({
nodeInfo: state.dashboard.nodeInfo,
rayletInfo: state.dashboard.rayletInfo
});
class NodeInfo extends React.Component<
WithStyles<typeof styles> & ReturnType<typeof mapStateToProps>
> {
render() {
const { classes, nodeInfo, rayletInfo } = this.props;
if (nodeInfo === null || rayletInfo === null) {
return <Typography color="textSecondary">Loading...</Typography>;
}
const logCounts: {
[ip: string]: {
perWorker: {
[pid: string]: number;
};
total: number;
};
} = {};
const errorCounts: {
[ip: string]: {
perWorker: {
[pid: string]: number;
};
total: number;
};
} = {};
for (const client of nodeInfo.clients) {
logCounts[client.ip] = { perWorker: {}, total: 0 };
errorCounts[client.ip] = { perWorker: {}, total: 0 };
for (const worker of client.workers) {
logCounts[client.ip].perWorker[worker.pid] = 0;
errorCounts[client.ip].perWorker[worker.pid] = 0;
}
}
for (const ip of Object.keys(nodeInfo.log_counts)) {
if (ip in logCounts) {
for (const [pid, count] of Object.entries(nodeInfo.log_counts[ip])) {
logCounts[ip].perWorker[pid] = count;
logCounts[ip].total += count;
}
}
}
for (const ip of Object.keys(nodeInfo.error_counts)) {
if (ip in errorCounts) {
for (const [pid, count] of Object.entries(nodeInfo.error_counts[ip])) {
errorCounts[ip].perWorker[pid] = count;
errorCounts[ip].total += count;
}
}
}
return (
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell className={classes.cell} />
<TableCell className={classes.cell}>Host</TableCell>
<TableCell className={classes.cell}>Workers</TableCell>
<TableCell className={classes.cell}>Uptime</TableCell>
<TableCell className={classes.cell}>CPU</TableCell>
<TableCell className={classes.cell}>RAM</TableCell>
<TableCell className={classes.cell}>Disk</TableCell>
<TableCell className={classes.cell}>Sent</TableCell>
<TableCell className={classes.cell}>Received</TableCell>
<TableCell className={classes.cell}>Logs</TableCell>
<TableCell className={classes.cell}>Errors</TableCell>
</TableRow>
</TableHead>
<TableBody>
{nodeInfo.clients.map(client => (
<NodeRowGroup
key={client.ip}
node={client}
raylet={
client.ip in rayletInfo.nodes
? rayletInfo.nodes[client.ip]
: null
}
logCounts={logCounts[client.ip]}
errorCounts={errorCounts[client.ip]}
initialExpanded={nodeInfo.clients.length <= 4}
/>
))}
<TotalRow
nodes={nodeInfo.clients}
logCounts={logCounts}
errorCounts={errorCounts}
/>
</TableBody>
</Table>
);
}
}
export default connect(mapStateToProps)(withStyles(styles)(NodeInfo));
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/NodeRowGroup.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import AddIcon from "@material-ui/icons/Add";
import RemoveIcon from "@material-ui/icons/Remove";
import classNames from "classnames";
import React from "react";
import { NodeInfoResponse, RayletInfoResponse } from "../../../api";
import { NodeCPU, WorkerCPU } from "./features/CPU";
import { NodeDisk, WorkerDisk } from "./features/Disk";
import { makeNodeErrors, makeWorkerErrors } from "./features/Errors";
import { NodeHost, WorkerHost } from "./features/Host";
import { makeNodeLogs, makeWorkerLogs } from "./features/Logs";
import { NodeRAM, WorkerRAM } from "./features/RAM";
import { NodeReceived, WorkerReceived } from "./features/Received";
import { NodeSent, WorkerSent } from "./features/Sent";
import { NodeUptime, WorkerUptime } from "./features/Uptime";
import { NodeWorkers, WorkerWorkers } from "./features/Workers";
const styles = (theme: Theme) =>
createStyles({
cell: {
padding: theme.spacing(1),
textAlign: "center",
"&:last-child": {
paddingRight: theme.spacing(1)
}
},
expandCollapseCell: {
cursor: "pointer"
},
expandCollapseIcon: {
color: theme.palette.text.secondary,
fontSize: "1.5em",
verticalAlign: "middle"
},
extraInfo: {
fontFamily: "SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace",
whiteSpace: "pre"
}
});
type ArrayType<T> = T extends Array<infer U> ? U : never;
type Node = ArrayType<NodeInfoResponse["clients"]>;
interface Props {
node: Node;
raylet: RayletInfoResponse["nodes"][keyof RayletInfoResponse["nodes"]] | null;
logCounts: {
perWorker: { [pid: string]: number };
total: number;
};
errorCounts: {
perWorker: { [pid: string]: number };
total: number;
};
initialExpanded: boolean;
}
interface State {
expanded: boolean;
}
class NodeRowGroup extends React.Component<
Props & WithStyles<typeof styles>,
State
> {
state: State = {
expanded: this.props.initialExpanded
};
toggleExpand = () => {
this.setState(state => ({
expanded: !state.expanded
}));
};
render() {
const { classes, node, raylet, logCounts, errorCounts } = this.props;
const { expanded } = this.state;
const features = [
{ NodeFeature: NodeHost, WorkerFeature: WorkerHost },
{ NodeFeature: NodeWorkers, WorkerFeature: WorkerWorkers },
{ NodeFeature: NodeUptime, WorkerFeature: WorkerUptime },
{ NodeFeature: NodeCPU, WorkerFeature: WorkerCPU },
{ NodeFeature: NodeRAM, WorkerFeature: WorkerRAM },
{ NodeFeature: NodeDisk, WorkerFeature: WorkerDisk },
{ NodeFeature: NodeSent, WorkerFeature: WorkerSent },
{ NodeFeature: NodeReceived, WorkerFeature: WorkerReceived },
{
NodeFeature: makeNodeLogs(logCounts),
WorkerFeature: makeWorkerLogs(logCounts)
},
{
NodeFeature: makeNodeErrors(errorCounts),
WorkerFeature: makeWorkerErrors(errorCounts)
}
];
return (
<React.Fragment>
<TableRow hover>
<TableCell
className={classNames(classes.cell, classes.expandCollapseCell)}
onClick={this.toggleExpand}
>
{!expanded ? (
<AddIcon className={classes.expandCollapseIcon} />
) : (
<RemoveIcon className={classes.expandCollapseIcon} />
)}
</TableCell>
{features.map(({ NodeFeature }, index) => (
<TableCell className={classes.cell} key={index}>
<NodeFeature node={node} />
</TableCell>
))}
</TableRow>
{expanded && (
<React.Fragment>
{raylet !== null && raylet.extraInfo !== undefined && (
<TableRow hover>
<TableCell className={classes.cell} />
<TableCell
className={classNames(classes.cell, classes.extraInfo)}
colSpan={features.length}
>
{raylet.extraInfo}
</TableCell>
</TableRow>
)}
{node.workers.map((worker, index: number) => (
<TableRow hover key={index}>
<TableCell className={classes.cell} />
{features.map(({ WorkerFeature }, index) => (
<TableCell className={classes.cell} key={index}>
<WorkerFeature node={node} worker={worker} />
</TableCell>
))}
</TableRow>
))}
</React.Fragment>
)}
</React.Fragment>
);
}
}
export default withStyles(styles)(NodeRowGroup);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/TotalRow.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import LayersIcon from "@material-ui/icons/Layers";
import React from "react";
import { NodeInfoResponse } from "../../../api";
import { ClusterCPU } from "./features/CPU";
import { ClusterDisk } from "./features/Disk";
import { makeClusterErrors } from "./features/Errors";
import { ClusterHost } from "./features/Host";
import { makeClusterLogs } from "./features/Logs";
import { ClusterRAM } from "./features/RAM";
import { ClusterReceived } from "./features/Received";
import { ClusterSent } from "./features/Sent";
import { ClusterUptime } from "./features/Uptime";
import { ClusterWorkers } from "./features/Workers";
const styles = (theme: Theme) =>
createStyles({
cell: {
borderTopColor: theme.palette.divider,
borderTopStyle: "solid",
borderTopWidth: 2,
padding: theme.spacing(1),
textAlign: "center",
"&:last-child": {
paddingRight: theme.spacing(1)
}
},
totalIcon: {
color: theme.palette.text.secondary,
fontSize: "1.5em",
verticalAlign: "middle"
}
});
interface Props {
nodes: NodeInfoResponse["clients"];
logCounts: {
[ip: string]: {
perWorker: { [pid: string]: number };
total: number;
};
};
errorCounts: {
[ip: string]: {
perWorker: { [pid: string]: number };
total: number;
};
};
}
class TotalRow extends React.Component<Props & WithStyles<typeof styles>> {
render() {
const { classes, nodes, logCounts, errorCounts } = this.props;
const features = [
{ ClusterFeature: ClusterHost },
{ ClusterFeature: ClusterWorkers },
{ ClusterFeature: ClusterUptime },
{ ClusterFeature: ClusterCPU },
{ ClusterFeature: ClusterRAM },
{ ClusterFeature: ClusterDisk },
{ ClusterFeature: ClusterSent },
{ ClusterFeature: ClusterReceived },
{ ClusterFeature: makeClusterLogs(logCounts) },
{ ClusterFeature: makeClusterErrors(errorCounts) }
];
return (
<TableRow hover>
<TableCell className={classes.cell}>
<LayersIcon className={classes.totalIcon} />
</TableCell>
{features.map(({ ClusterFeature }, index) => (
<TableCell className={classes.cell} key={index}>
<ClusterFeature nodes={nodes} />
</TableCell>
))}
</TableRow>
);
}
}
export default withStyles(styles)(TotalRow);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/CPU.tsx
|
TypeScript (TSX)
|
import React from "react";
import UsageBar from "../../../../common/UsageBar";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
const getWeightedAverage = (
input: {
weight: number;
value: number;
}[]
) => {
if (input.length === 0) {
return 0;
}
let totalWeightTimesValue = 0;
let totalWeight = 0;
for (const { weight, value } of input) {
totalWeightTimesValue += weight * value;
totalWeight += weight;
}
return totalWeightTimesValue / totalWeight;
};
export const ClusterCPU: ClusterFeatureComponent = ({ nodes }) => {
const cpuWeightedAverage = getWeightedAverage(
nodes.map(node => ({ weight: node.cpus[0], value: node.cpu }))
);
return (
<div style={{ minWidth: 60 }}>
<UsageBar
percent={cpuWeightedAverage}
text={`${cpuWeightedAverage.toFixed(1)}%`}
/>
</div>
);
};
export const NodeCPU: NodeFeatureComponent = ({ node }) => (
<div style={{ minWidth: 60 }}>
<UsageBar percent={node.cpu} text={`${node.cpu.toFixed(1)}%`} />
</div>
);
export const WorkerCPU: WorkerFeatureComponent = ({ worker }) => (
<div style={{ minWidth: 60 }}>
<UsageBar
percent={worker.cpu_percent}
text={`${worker.cpu_percent.toFixed(1)}%`}
/>
</div>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Disk.tsx
|
TypeScript (TSX)
|
import Typography from "@material-ui/core/Typography";
import React from "react";
import { formatUsage } from "../../../../common/formatUtils";
import UsageBar from "../../../../common/UsageBar";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const ClusterDisk: ClusterFeatureComponent = ({ nodes }) => {
let used = 0;
let total = 0;
for (const node of nodes) {
used += node.disk["/"].used;
total += node.disk["/"].total;
}
return (
<UsageBar
percent={(100 * used) / total}
text={formatUsage(used, total, "gibibyte")}
/>
);
};
export const NodeDisk: NodeFeatureComponent = ({ node }) => (
<UsageBar
percent={(100 * node.disk["/"].used) / node.disk["/"].total}
text={formatUsage(node.disk["/"].used, node.disk["/"].total, "gibibyte")}
/>
);
export const WorkerDisk: WorkerFeatureComponent = () => (
<Typography color="textSecondary" component="span" variant="inherit">
N/A
</Typography>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Errors.tsx
|
TypeScript (TSX)
|
import Link from "@material-ui/core/Link";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { Link as RouterLink } from "react-router-dom";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const makeClusterErrors = (errorCounts: {
[ip: string]: {
perWorker: {
[pid: string]: number;
};
total: number;
};
}): ClusterFeatureComponent => ({ nodes }) => {
let totalErrorCount = 0;
for (const node of nodes) {
if (node.ip in errorCounts) {
totalErrorCount += errorCounts[node.ip].total;
}
}
return totalErrorCount === 0 ? (
<Typography color="textSecondary" component="span" variant="inherit">
No errors
</Typography>
) : (
<React.Fragment>
{totalErrorCount.toLocaleString()}{" "}
{totalErrorCount === 1 ? "error" : "errors"}
</React.Fragment>
);
};
export const makeNodeErrors = (errorCounts: {
perWorker: { [pid: string]: number };
total: number;
}): NodeFeatureComponent => ({ node }) =>
errorCounts.total === 0 ? (
<Typography color="textSecondary" component="span" variant="inherit">
No errors
</Typography>
) : (
<Link component={RouterLink} to={`/errors/${node.hostname}`}>
View all errors ({errorCounts.total.toLocaleString()})
</Link>
);
export const makeWorkerErrors = (errorCounts: {
perWorker: { [pid: string]: number };
total: number;
}): WorkerFeatureComponent => ({ node, worker }) =>
errorCounts.perWorker[worker.pid] === 0 ? (
<Typography color="textSecondary" component="span" variant="inherit">
No errors
</Typography>
) : (
<Link component={RouterLink} to={`/errors/${node.hostname}/${worker.pid}`}>
View errors ({errorCounts.perWorker[worker.pid].toLocaleString()})
</Link>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Host.tsx
|
TypeScript (TSX)
|
import React from "react";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const ClusterHost: ClusterFeatureComponent = ({ nodes }) => (
<React.Fragment>
Totals ({nodes.length.toLocaleString()}{" "}
{nodes.length === 1 ? "host" : "hosts"})
</React.Fragment>
);
export const NodeHost: NodeFeatureComponent = ({ node }) => (
<React.Fragment>
{node.hostname} ({node.ip})
</React.Fragment>
);
// Ray worker process titles have one of the following forms: `ray::IDLE`,
// `ray::function()`, `ray::Class`, or `ray::Class.method()`. We extract the
// first portion here for display in the "Host" column. Note that this will
// always be `ray` under the current setup, but it may vary in the future.
export const WorkerHost: WorkerFeatureComponent = ({ worker }) => (
<React.Fragment>
{worker.cmdline[0].split("::", 2)[0]} (PID: {worker.pid})
</React.Fragment>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Logs.tsx
|
TypeScript (TSX)
|
import Link from "@material-ui/core/Link";
import Typography from "@material-ui/core/Typography";
import React from "react";
import { Link as RouterLink } from "react-router-dom";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const makeClusterLogs = (logCounts: {
[ip: string]: {
perWorker: {
[pid: string]: number;
};
total: number;
};
}): ClusterFeatureComponent => ({ nodes }) => {
let totalLogCount = 0;
for (const node of nodes) {
if (node.ip in logCounts) {
totalLogCount += logCounts[node.ip].total;
}
}
return totalLogCount === 0 ? (
<Typography color="textSecondary" component="span" variant="inherit">
No logs
</Typography>
) : (
<React.Fragment>
{totalLogCount.toLocaleString()} {totalLogCount === 1 ? "line" : "lines"}
</React.Fragment>
);
};
export const makeNodeLogs = (logCounts: {
perWorker: { [pid: string]: number };
total: number;
}): NodeFeatureComponent => ({ node }) =>
logCounts.total === 0 ? (
<Typography color="textSecondary" component="span" variant="inherit">
No logs
</Typography>
) : (
<Link component={RouterLink} to={`/logs/${node.hostname}`}>
View all logs ({logCounts.total.toLocaleString()}{" "}
{logCounts.total === 1 ? "line" : "lines"})
</Link>
);
export const makeWorkerLogs = (logCounts: {
perWorker: { [pid: string]: number };
total: number;
}): WorkerFeatureComponent => ({ node, worker }) =>
logCounts.perWorker[worker.pid] === 0 ? (
<Typography color="textSecondary" component="span" variant="inherit">
No logs
</Typography>
) : (
<Link component={RouterLink} to={`/logs/${node.hostname}/${worker.pid}`}>
View log ({logCounts.perWorker[worker.pid].toLocaleString()}{" "}
{logCounts.perWorker[worker.pid] === 1 ? "line" : "lines"})
</Link>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/RAM.tsx
|
TypeScript (TSX)
|
import React from "react";
import { formatByteAmount, formatUsage } from "../../../../common/formatUtils";
import UsageBar from "../../../../common/UsageBar";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const ClusterRAM: ClusterFeatureComponent = ({ nodes }) => {
let used = 0;
let total = 0;
for (const node of nodes) {
used += node.mem[0] - node.mem[1];
total += node.mem[0];
}
return (
<UsageBar
percent={(100 * used) / total}
text={formatUsage(used, total, "gibibyte")}
/>
);
};
export const NodeRAM: NodeFeatureComponent = ({ node }) => (
<UsageBar
percent={(100 * (node.mem[0] - node.mem[1])) / node.mem[0]}
text={formatUsage(node.mem[0] - node.mem[1], node.mem[0], "gibibyte")}
/>
);
export const WorkerRAM: WorkerFeatureComponent = ({ node, worker }) => (
<UsageBar
percent={(100 * worker.memory_info.rss) / node.mem[0]}
text={formatByteAmount(worker.memory_info.rss, "mebibyte")}
/>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Received.tsx
|
TypeScript (TSX)
|
import Typography from "@material-ui/core/Typography";
import React from "react";
import { formatByteAmount } from "../../../../common/formatUtils";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const ClusterReceived: ClusterFeatureComponent = ({ nodes }) => {
let totalReceived = 0;
for (const node of nodes) {
totalReceived += node.net[1];
}
return (
<React.Fragment>
{formatByteAmount(totalReceived, "mebibyte")}/s
</React.Fragment>
);
};
export const NodeReceived: NodeFeatureComponent = ({ node }) => (
<React.Fragment>{formatByteAmount(node.net[1], "mebibyte")}/s</React.Fragment>
);
export const WorkerReceived: WorkerFeatureComponent = () => (
<Typography color="textSecondary" component="span" variant="inherit">
N/A
</Typography>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Sent.tsx
|
TypeScript (TSX)
|
import Typography from "@material-ui/core/Typography";
import React from "react";
import { formatByteAmount } from "../../../../common/formatUtils";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const ClusterSent: ClusterFeatureComponent = ({ nodes }) => {
let totalSent = 0;
for (const node of nodes) {
totalSent += node.net[0];
}
return (
<React.Fragment>{formatByteAmount(totalSent, "mebibyte")}/s</React.Fragment>
);
};
export const NodeSent: NodeFeatureComponent = ({ node }) => (
<React.Fragment>{formatByteAmount(node.net[0], "mebibyte")}/s</React.Fragment>
);
export const WorkerSent: WorkerFeatureComponent = () => (
<Typography color="textSecondary" component="span" variant="inherit">
N/A
</Typography>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Uptime.tsx
|
TypeScript (TSX)
|
import Typography from "@material-ui/core/Typography";
import React from "react";
import { formatDuration } from "../../../../common/formatUtils";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
const getUptime = (bootTime: number) => Date.now() / 1000 - bootTime;
export const ClusterUptime: ClusterFeatureComponent = ({ nodes }) => (
<Typography color="textSecondary" component="span" variant="inherit">
N/A
</Typography>
);
export const NodeUptime: NodeFeatureComponent = ({ node }) => (
<React.Fragment>{formatDuration(getUptime(node.boot_time))}</React.Fragment>
);
export const WorkerUptime: WorkerFeatureComponent = ({ worker }) => (
<React.Fragment>
{formatDuration(getUptime(worker.create_time))}
</React.Fragment>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/Workers.tsx
|
TypeScript (TSX)
|
import React from "react";
import {
ClusterFeatureComponent,
NodeFeatureComponent,
WorkerFeatureComponent
} from "./types";
export const ClusterWorkers: ClusterFeatureComponent = ({ nodes }) => {
let totalWorkers = 0;
let totalCpus = 0;
for (const node of nodes) {
totalWorkers += node.workers.length;
totalCpus += node.cpus[0];
}
return (
<React.Fragment>
{totalWorkers.toLocaleString()}{" "}
{totalWorkers === 1 ? "worker" : "workers"} / {totalCpus.toLocaleString()}{" "}
{totalCpus === 1 ? "core" : "cores"}
</React.Fragment>
);
};
export const NodeWorkers: NodeFeatureComponent = ({ node }) => {
const workers = node.workers.length;
const cpus = node.cpus[0];
return (
<React.Fragment>
{workers.toLocaleString()} {workers === 1 ? "worker" : "workers"} /{" "}
{cpus.toLocaleString()} {cpus === 1 ? "core" : "cores"}
</React.Fragment>
);
};
// Ray worker process titles have one of the following forms: `ray::IDLE`,
// `ray::function()`, `ray::Class`, or `ray::Class.method()`. We extract the
// second portion here for display in the "Workers" column.
export const WorkerWorkers: WorkerFeatureComponent = ({ worker }) => (
<React.Fragment>{worker.cmdline[0].split("::", 2)[1]}</React.Fragment>
);
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/node-info/features/types.tsx
|
TypeScript (TSX)
|
import React from "react";
import { NodeInfoResponse } from "../../../../api";
type ArrayType<T> = T extends Array<infer U> ? U : never;
type Node = ArrayType<NodeInfoResponse["clients"]>;
type Worker = ArrayType<Node["workers"]>;
type ClusterFeatureData = { nodes: Node[] };
type NodeFeatureData = { node: Node };
type WorkerFeatureData = { node: Node; worker: Worker };
export type ClusterFeatureComponent = (
data: ClusterFeatureData
) => React.ReactElement;
export type NodeFeatureComponent = (
data: NodeFeatureData
) => React.ReactElement;
export type WorkerFeatureComponent = (
data: WorkerFeatureData
) => React.ReactElement;
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/ray-config/RayConfig.tsx
|
TypeScript (TSX)
|
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import createStyles from "@material-ui/core/styles/createStyles";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Typography from "@material-ui/core/Typography";
import classNames from "classnames";
import React from "react";
import { connect } from "react-redux";
import { getRayConfig } from "../../../api";
import { StoreState } from "../../../store";
import { dashboardActions } from "../state";
const styles = (theme: Theme) =>
createStyles({
table: {
marginTop: theme.spacing(1),
width: "auto"
},
cell: {
paddingTop: theme.spacing(1),
paddingBottom: theme.spacing(1),
paddingLeft: theme.spacing(3),
paddingRight: theme.spacing(3),
textAlign: "center",
"&:last-child": {
paddingRight: theme.spacing(3)
}
},
key: {
color: theme.palette.text.secondary
}
});
const mapStateToProps = (state: StoreState) => ({
rayConfig: state.dashboard.rayConfig
});
const mapDispatchToProps = dashboardActions;
class RayConfig extends React.Component<
WithStyles<typeof styles> &
ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps
> {
refreshRayConfig = async () => {
try {
const rayConfig = await getRayConfig();
this.props.setRayConfig(rayConfig);
} catch (error) {
} finally {
setTimeout(this.refreshRayConfig, 10 * 1000);
}
};
async componentDidMount() {
await this.refreshRayConfig();
}
render() {
const { classes, rayConfig } = this.props;
if (rayConfig === null) {
return (
<Typography color="textSecondary">
No Ray configuration detected.
</Typography>
);
}
const formattedRayConfig = [
{
key: "Autoscaling mode",
value: rayConfig.autoscaling_mode
},
{
key: "Head node type",
value: rayConfig.head_type
},
{
key: "Worker node type",
value: rayConfig.worker_type
},
{
key: "Min worker nodes",
value: rayConfig.min_workers
},
{
key: "Initial worker nodes",
value: rayConfig.initial_workers
},
{
key: "Max worker nodes",
value: rayConfig.max_workers
},
{
key: "Idle timeout",
value: `${rayConfig.idle_timeout_minutes} ${
rayConfig.idle_timeout_minutes === 1 ? "minute" : "minutes"
}`
}
];
return (
<div>
<Typography>Ray cluster configuration:</Typography>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell className={classes.cell}>Setting</TableCell>
<TableCell className={classes.cell}>Value</TableCell>
</TableRow>
</TableHead>
<TableBody>
{formattedRayConfig.map(({ key, value }, index) => (
<TableRow key={index}>
<TableCell className={classNames(classes.cell, classes.key)}>
{key}
</TableCell>
<TableCell className={classes.cell}>{value}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(RayConfig));
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/pages/dashboard/state.ts
|
TypeScript
|
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import {
NodeInfoResponse,
RayConfigResponse,
RayletInfoResponse
} from "../../api";
const name = "dashboard";
interface State {
tab: number;
rayConfig: RayConfigResponse | null;
nodeInfo: NodeInfoResponse | null;
rayletInfo: RayletInfoResponse | null;
lastUpdatedAt: number | null;
error: string | null;
}
const initialState: State = {
tab: 0,
rayConfig: null,
nodeInfo: null,
rayletInfo: null,
lastUpdatedAt: null,
error: null
};
const slice = createSlice({
name,
initialState,
reducers: {
setTab: (state, action: PayloadAction<number>) => {
state.tab = action.payload;
},
setRayConfig: (state, action: PayloadAction<RayConfigResponse>) => {
state.rayConfig = action.payload;
},
setNodeAndRayletInfo: (
state,
action: PayloadAction<{
nodeInfo: NodeInfoResponse;
rayletInfo: RayletInfoResponse;
}>
) => {
state.nodeInfo = action.payload.nodeInfo;
state.rayletInfo = action.payload.rayletInfo;
state.lastUpdatedAt = Date.now();
},
setError: (state, action: PayloadAction<string | null>) => {
state.error = action.payload;
}
}
});
export const dashboardActions = slice.actions;
export const dashboardReducer = slice.reducer;
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/react-app-env.d.ts
|
TypeScript
|
/// <reference types="react-scripts" />
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/client/src/store.ts
|
TypeScript
|
import { configureStore } from "@reduxjs/toolkit";
import { dashboardReducer } from "./pages/dashboard/state";
export const store = configureStore({
reducer: {
dashboard: dashboardReducer
},
devTools: process.env.NODE_ENV === "development"
});
export type StoreState = ReturnType<typeof store.getState>;
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/dashboard.py
|
Python
|
try:
import aiohttp.web
except ImportError:
print("The dashboard requires aiohttp to run.")
import sys
sys.exit(1)
import argparse
import copy
import datetime
import json
import logging
import os
import re
import threading
import time
import traceback
import yaml
from base64 import b64decode
from collections import defaultdict
from operator import itemgetter
from typing import Dict
import grpc
from google.protobuf.json_format import MessageToDict
import ray
from ray.core.generated import node_manager_pb2
from ray.core.generated import node_manager_pb2_grpc
import ray.ray_constants as ray_constants
# Logger for this module. It should be configured at the entry point
# into the program using Ray. Ray provides a default configuration at
# entry/init points.
logger = logging.getLogger(__name__)
def to_unix_time(dt):
return (dt - datetime.datetime(1970, 1, 1)).total_seconds()
def round_resource_value(quantity):
if quantity.is_integer():
return int(quantity)
else:
return round(quantity, 2)
def format_resource(resource_name, quantity):
if resource_name == "object_store_memory" or resource_name == "memory":
# Convert to 50MiB chunks and then to GiB
quantity = quantity * (50 * 1024 * 1024) / (1024 * 1024 * 1024)
return "{} GiB".format(round_resource_value(quantity))
return "{}".format(round_resource_value(quantity))
def format_reply(reply):
if isinstance(reply, dict):
for k, v in reply.items():
if isinstance(v, dict) or isinstance(v, list):
format_reply(v)
else:
if k.endswith("Id"):
v = b64decode(v)
reply[k] = ray.utils.binary_to_hex(v)
elif isinstance(reply, list):
for item in reply:
format_reply(item)
def measures_to_dict(measures):
measures_dict = {}
for measure in measures:
tags = measure["tags"].split(",")[-1]
if "intValue" in measure:
measures_dict[tags] = measure["intValue"]
elif "doubleValue" in measure:
measures_dict[tags] = measure["doubleValue"]
return measures_dict
def b64_decode(reply):
return b64decode(reply).decode("utf-8")
class Dashboard(object):
"""A dashboard process for monitoring Ray nodes.
This dashboard is made up of a REST API which collates data published by
Reporter processes on nodes into a json structure, and a webserver
which polls said API for display purposes.
Attributes:
redis_client: A client used to communicate with the Redis server.
"""
def __init__(self,
host,
port,
redis_address,
temp_dir,
redis_password=None):
"""Initialize the dashboard object."""
self.host = host
self.port = port
self.redis_client = ray.services.create_redis_client(
redis_address, password=redis_password)
self.temp_dir = temp_dir
self.node_stats = NodeStats(redis_address, redis_password)
self.raylet_stats = RayletStats(redis_address, redis_password)
# Setting the environment variable RAY_DASHBOARD_DEV=1 disables some
# security checks in the dashboard server to ease development while
# using the React dev server. Specifically, when this option is set, we
# allow cross-origin requests to be made.
self.is_dev = os.environ.get("RAY_DASHBOARD_DEV") == "1"
self.app = aiohttp.web.Application()
self.setup_routes()
def setup_routes(self):
def forbidden() -> aiohttp.web.Response:
return aiohttp.web.Response(status=403, text="403 Forbidden")
def get_forbidden(_) -> aiohttp.web.Response:
return forbidden()
async def get_index(req) -> aiohttp.web.Response:
return aiohttp.web.FileResponse(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"client/build/index.html"))
async def get_favicon(req) -> aiohttp.web.Response:
return aiohttp.web.FileResponse(
os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"client/build/favicon.ico"))
async def json_response(result=None, error=None,
ts=None) -> aiohttp.web.Response:
if ts is None:
ts = datetime.datetime.utcnow()
headers = None
if self.is_dev:
headers = {"Access-Control-Allow-Origin": "*"}
return aiohttp.web.json_response(
{
"result": result,
"timestamp": to_unix_time(ts),
"error": error,
},
headers=headers)
async def ray_config(_) -> aiohttp.web.Response:
try:
config_path = os.path.expanduser("~/ray_bootstrap_config.yaml")
with open(config_path) as f:
cfg = yaml.safe_load(f)
except Exception:
return await json_response(error="No config")
D = {
"min_workers": cfg["min_workers"],
"max_workers": cfg["max_workers"],
"initial_workers": cfg["initial_workers"],
"autoscaling_mode": cfg["autoscaling_mode"],
"idle_timeout_minutes": cfg["idle_timeout_minutes"],
}
try:
D["head_type"] = cfg["head_node"]["InstanceType"]
except KeyError:
D["head_type"] = "unknown"
try:
D["worker_type"] = cfg["worker_nodes"]["InstanceType"]
except KeyError:
D["worker_type"] = "unknown"
return await json_response(result=D)
async def node_info(req) -> aiohttp.web.Response:
now = datetime.datetime.utcnow()
D = self.node_stats.get_node_stats()
return await json_response(result=D, ts=now)
async def raylet_info(req) -> aiohttp.web.Response:
D = self.raylet_stats.get_raylet_stats()
workers_info = sum(
(data.get("workersStats", []) for data in D.values()), [])
infeasible_tasks = sum(
(data.get("infeasibleTasks", []) for data in D.values()), [])
actor_tree = self.node_stats.get_actor_tree(
workers_info, infeasible_tasks)
for address, data in D.items():
# process view data
measures_dicts = {}
for view_data in data["viewData"]:
view_name = view_data["viewName"]
if view_name in ("local_available_resource",
"local_total_resource",
"object_manager_stats"):
measures_dicts[view_name] = measures_to_dict(
view_data["measures"])
# process resources info
extra_info_strings = []
prefix = "ResourceName:"
for resource_name, total_resource in measures_dicts[
"local_total_resource"].items():
available_resource = measures_dicts[
"local_available_resource"].get(resource_name, .0)
resource_name = resource_name[len(prefix):]
extra_info_strings.append("{}: {} / {}".format(
resource_name,
format_resource(resource_name,
total_resource - available_resource),
format_resource(resource_name, total_resource)))
data["extraInfo"] = ", ".join(extra_info_strings) + "\n"
if os.environ.get("RAY_DASHBOARD_DEBUG"):
# process object store info
extra_info_strings = []
prefix = "ValueType:"
for stats_name in [
"used_object_store_memory", "num_local_objects"
]:
stats_value = measures_dicts[
"object_manager_stats"].get(
prefix + stats_name, .0)
extra_info_strings.append("{}: {}".format(
stats_name, stats_value))
data["extraInfo"] += ", ".join(extra_info_strings)
# process actor info
actor_tree_str = json.dumps(
actor_tree, indent=2, sort_keys=True)
lines = actor_tree_str.split("\n")
max_line_length = max(map(len, lines))
to_print = []
for line in lines:
to_print.append(line +
(max_line_length - len(line)) * " ")
data["extraInfo"] += "\n" + "\n".join(to_print)
result = {"nodes": D, "actors": actor_tree}
return await json_response(result=result)
async def logs(req) -> aiohttp.web.Response:
hostname = req.query.get("hostname")
pid = req.query.get("pid")
result = self.node_stats.get_logs(hostname, pid)
return await json_response(result=result)
async def errors(req) -> aiohttp.web.Response:
hostname = req.query.get("hostname")
pid = req.query.get("pid")
result = self.node_stats.get_errors(hostname, pid)
return await json_response(result=result)
self.app.router.add_get("/", get_index)
self.app.router.add_get("/favicon.ico", get_favicon)
build_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "client/build")
if not os.path.isdir(build_dir):
raise ValueError(
"Dashboard build directory not found at '{}'. If installing "
"from source, please follow the additional steps required to "
"build the dashboard: "
"cd python/ray/dashboard/client && npm ci && npm run build"
.format(build_dir))
static_dir = os.path.join(build_dir, "static")
self.app.router.add_static("/static", static_dir)
speedscope_dir = os.path.join(build_dir, "speedscope-1.5.3")
self.app.router.add_static("/speedscope", speedscope_dir)
self.app.router.add_get("/api/ray_config", ray_config)
self.app.router.add_get("/api/node_info", node_info)
self.app.router.add_get("/api/raylet_info", raylet_info)
self.app.router.add_get("/api/logs", logs)
self.app.router.add_get("/api/errors", errors)
self.app.router.add_get("/{_}", get_forbidden)
def log_dashboard_url(self):
url = ray.services.get_webui_url_from_redis(self.redis_client)
with open(os.path.join(self.temp_dir, "dashboard_url"), "w") as f:
f.write(url)
logger.info("Dashboard running on {}".format(url))
def run(self):
self.log_dashboard_url()
self.node_stats.start()
self.raylet_stats.start()
aiohttp.web.run_app(self.app, host=self.host, port=self.port)
class NodeStats(threading.Thread):
def __init__(self, redis_address, redis_password=None):
self.redis_key = "{}.*".format(ray.gcs_utils.REPORTER_CHANNEL)
self.redis_client = ray.services.create_redis_client(
redis_address, password=redis_password)
self._node_stats = {}
self._addr_to_owner_addr = {}
self._addr_to_actor_id = {}
self._addr_to_extra_info_dict = {}
self._node_stats_lock = threading.Lock()
self._default_info = {
"actorId": "",
"children": {},
"ipAddress": "",
"isDirectCall": False,
"jobId": "",
"numExecutedTasks": 0,
"numLocalObjects": 0,
"numObjectIdsInScope": 0,
"port": 0,
"state": 0,
"taskQueueLength": 0,
"usedObjectStoreMemory": 0,
"usedResources": {},
}
# Mapping from IP address to PID to list of log lines
self._logs = defaultdict(lambda: defaultdict(list))
# Mapping from IP address to PID to list of error messages
self._errors = defaultdict(lambda: defaultdict(list))
ray.state.state._initialize_global_state(
redis_address=redis_address, redis_password=redis_password)
super().__init__()
def calculate_log_counts(self):
return {
ip: {
pid: len(logs_for_pid)
for pid, logs_for_pid in logs_for_ip.items()
}
for ip, logs_for_ip in self._logs.items()
}
def calculate_error_counts(self):
return {
ip: {
pid: len(errors_for_pid)
for pid, errors_for_pid in errors_for_ip.items()
}
for ip, errors_for_ip in self._errors.items()
}
def purge_outdated_stats(self):
def current(then, now):
if (now - then) > 5:
return False
return True
now = to_unix_time(datetime.datetime.utcnow())
self._node_stats = {
k: v
for k, v in self._node_stats.items() if current(v["now"], now)
}
def get_node_stats(self) -> Dict:
with self._node_stats_lock:
self.purge_outdated_stats()
node_stats = sorted(
(v for v in self._node_stats.values()),
key=itemgetter("boot_time"))
return {
"clients": node_stats,
"log_counts": self.calculate_log_counts(),
"error_counts": self.calculate_error_counts(),
}
def get_actor_tree(self, workers_info, infeasible_tasks) -> Dict:
now = time.time()
# construct flattened actor tree
flattened_tree = {"root": {"children": {}}}
child_to_parent = {}
with self._node_stats_lock:
for addr, actor_id in self._addr_to_actor_id.items():
flattened_tree[actor_id] = copy.deepcopy(self._default_info)
flattened_tree[actor_id].update(
self._addr_to_extra_info_dict[addr])
parent_id = self._addr_to_actor_id.get(
self._addr_to_owner_addr[addr], "root")
child_to_parent[actor_id] = parent_id
for worker_info in workers_info:
if "coreWorkerStats" in worker_info:
core_worker_stats = worker_info["coreWorkerStats"]
addr = (core_worker_stats["ipAddress"],
str(core_worker_stats["port"]))
if addr in self._addr_to_actor_id:
actor_info = flattened_tree[self._addr_to_actor_id[
addr]]
if "currentTaskFuncDesc" in core_worker_stats:
core_worker_stats["currentTaskFuncDesc"] = list(
map(b64_decode,
core_worker_stats["currentTaskFuncDesc"]))
format_reply(core_worker_stats)
actor_info.update(core_worker_stats)
actor_info["averageTaskExecutionSpeed"] = round(
actor_info["numExecutedTasks"] /
(now - actor_info["timestamp"] / 1000), 2)
for infeasible_task in infeasible_tasks:
actor_id = ray.utils.binary_to_hex(
b64decode(
infeasible_task["actorCreationTaskSpec"]["actorId"]))
caller_addr = (infeasible_task["callerAddress"]["ipAddress"],
str(infeasible_task["callerAddress"]["port"]))
caller_id = self._addr_to_actor_id.get(caller_addr, "root")
child_to_parent[actor_id] = caller_id
infeasible_task["state"] = -1
infeasible_task["functionDescriptor"] = list(
map(b64_decode, infeasible_task["functionDescriptor"]))
format_reply(infeasible_tasks)
flattened_tree[actor_id] = infeasible_task
# construct actor tree
actor_tree = flattened_tree
for actor_id, parent_id in child_to_parent.items():
actor_tree[parent_id]["children"][actor_id] = actor_tree[actor_id]
return actor_tree["root"]["children"]
def get_logs(self, hostname, pid):
ip = self._node_stats.get(hostname, {"ip": None})["ip"]
logs = self._logs.get(ip, {})
if pid:
logs = {pid: logs.get(pid, [])}
return logs
def get_errors(self, hostname, pid):
ip = self._node_stats.get(hostname, {"ip": None})["ip"]
errors = self._errors.get(ip, {})
if pid:
errors = {pid: errors.get(pid, [])}
return errors
def run(self):
p = self.redis_client.pubsub(ignore_subscribe_messages=True)
p.psubscribe(self.redis_key)
logger.info("NodeStats: subscribed to {}".format(self.redis_key))
log_channel = ray.gcs_utils.LOG_FILE_CHANNEL
p.subscribe(log_channel)
logger.info("NodeStats: subscribed to {}".format(log_channel))
error_channel = ray.gcs_utils.TablePubsub.Value("ERROR_INFO_PUBSUB")
p.subscribe(error_channel)
logger.info("NodeStats: subscribed to {}".format(error_channel))
actor_channel = ray.gcs_utils.TablePubsub.Value("ACTOR_PUBSUB")
p.subscribe(actor_channel)
logger.info("NodeStats: subscribed to {}".format(actor_channel))
current_actor_table = ray.actors()
with self._node_stats_lock:
for actor_data in current_actor_table.values():
addr = (actor_data["Address"]["IPAddress"],
str(actor_data["Address"]["Port"]))
owner_addr = (actor_data["OwnerAddress"]["IPAddress"],
str(actor_data["OwnerAddress"]["Port"]))
self._addr_to_owner_addr[addr] = owner_addr
self._addr_to_actor_id[addr] = actor_data["ActorID"]
self._addr_to_extra_info_dict[addr] = {
"jobId": actor_data["JobID"],
"state": actor_data["State"],
"isDirectCall": actor_data["IsDirectCall"],
"timestamp": actor_data["Timestamp"]
}
for x in p.listen():
try:
with self._node_stats_lock:
channel = ray.utils.decode(x["channel"])
data = x["data"]
if channel == log_channel:
data = json.loads(ray.utils.decode(data))
ip = data["ip"]
pid = str(data["pid"])
self._logs[ip][pid].extend(data["lines"])
elif channel == str(error_channel):
gcs_entry = ray.gcs_utils.GcsEntry.FromString(data)
error_data = ray.gcs_utils.ErrorTableData.FromString(
gcs_entry.entries[0])
message = error_data.error_message
message = re.sub(r"\x1b\[\d+m", "", message)
match = re.search(r"\(pid=(\d+), ip=(.*?)\)", message)
if match:
pid = match.group(1)
ip = match.group(2)
self._errors[ip][pid].append({
"message": message,
"timestamp": error_data.timestamp,
"type": error_data.type
})
elif channel == str(actor_channel):
gcs_entry = ray.gcs_utils.GcsEntry.FromString(data)
actor_data = ray.gcs_utils.ActorTableData.FromString(
gcs_entry.entries[0])
addr = (actor_data.address.ip_address,
str(actor_data.address.port))
owner_addr = (actor_data.owner_address.ip_address,
str(actor_data.owner_address.port))
self._addr_to_owner_addr[addr] = owner_addr
self._addr_to_actor_id[addr] = ray.utils.binary_to_hex(
actor_data.actor_id)
self._addr_to_extra_info_dict[addr] = {
"jobId": ray.utils.binary_to_hex(
actor_data.job_id),
"state": actor_data.state,
"isDirectCall": actor_data.is_direct_call,
"timestamp": actor_data.timestamp
}
else:
data = json.loads(ray.utils.decode(data))
self._node_stats[data["hostname"]] = data
except Exception:
logger.exception(traceback.format_exc())
continue
class RayletStats(threading.Thread):
def __init__(self, redis_address, redis_password=None):
self.nodes_lock = threading.Lock()
self.nodes = []
self.stubs = {}
self._raylet_stats_lock = threading.Lock()
self._raylet_stats = {}
self.update_nodes()
super().__init__()
def update_nodes(self):
with self.nodes_lock:
self.nodes = ray.nodes()
node_ids = [node["NodeID"] for node in self.nodes]
# First remove node connections of disconnected nodes.
for node_id in self.stubs.keys():
if node_id not in node_ids:
stub = self.stubs.pop(node_id)
stub.close()
# Now add node connections of new nodes.
for node in self.nodes:
node_id = node["NodeID"]
if node_id not in self.stubs:
channel = grpc.insecure_channel("{}:{}".format(
node["NodeManagerAddress"], node["NodeManagerPort"]))
stub = node_manager_pb2_grpc.NodeManagerServiceStub(
channel)
self.stubs[node_id] = stub
def get_raylet_stats(self) -> Dict:
with self._raylet_stats_lock:
return copy.deepcopy(self._raylet_stats)
def run(self):
counter = 0
while True:
time.sleep(1.0)
replies = {}
for node in self.nodes:
node_id = node["NodeID"]
stub = self.stubs[node_id]
reply = stub.GetNodeStats(
node_manager_pb2.GetNodeStatsRequest(), timeout=2)
replies[node["NodeManagerAddress"]] = reply
with self._raylet_stats_lock:
for address, reply in replies.items():
self._raylet_stats[address] = MessageToDict(reply)
counter += 1
# From time to time, check if new nodes have joined the cluster
# and update self.nodes
if counter % 10:
self.update_nodes()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=("Parse Redis server for the "
"dashboard to connect to."))
parser.add_argument(
"--host",
required=True,
type=str,
help="The host to use for the HTTP server.")
parser.add_argument(
"--port",
required=True,
type=int,
help="The port to use for the HTTP server.")
parser.add_argument(
"--redis-address",
required=True,
type=str,
help="The address to use for Redis.")
parser.add_argument(
"--redis-password",
required=False,
type=str,
default=None,
help="the password to use for Redis")
parser.add_argument(
"--logging-level",
required=False,
type=str,
default=ray_constants.LOGGER_LEVEL,
choices=ray_constants.LOGGER_LEVEL_CHOICES,
help=ray_constants.LOGGER_LEVEL_HELP)
parser.add_argument(
"--logging-format",
required=False,
type=str,
default=ray_constants.LOGGER_FORMAT,
help=ray_constants.LOGGER_FORMAT_HELP)
parser.add_argument(
"--temp-dir",
required=False,
type=str,
default=None,
help="Specify the path of the temporary directory use by Ray process.")
args = parser.parse_args()
ray.utils.setup_logger(args.logging_level, args.logging_format)
try:
dashboard = Dashboard(
args.host,
args.port,
args.redis_address,
args.temp_dir,
redis_password=args.redis_password,
)
dashboard.run()
except Exception as e:
# Something went wrong, so push an error to all drivers.
redis_client = ray.services.create_redis_client(
args.redis_address, password=args.redis_password)
traceback_str = ray.utils.format_error_message(traceback.format_exc())
message = ("The dashboard on node {} failed with the following "
"error:\n{}".format(os.uname()[1], traceback_str))
ray.utils.push_error_to_driver_through_redis(
redis_client, ray_constants.DASHBOARD_DIED_ERROR, message)
raise e
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/index.html
|
HTML
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ray dashboard</title>
<meta name="description" content="ray dashboard"</meta>
<link rel="stylesheet" href="res/main.css">
<meta name="referrer" content="same-origin">
<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.4/vue.min.js"
integrity="sha384-rldcjlIPDkF0mEihgyEOIFhd2NW5YL717okjKC5YF2LrqoiBeMk4tpcgbRrlDHj5"
crossorigin="anonymous"></script>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.4/vue.js"
integrity="sha384-94H2I+MU5hfBDUinQG+/Y9JbHALTPlQmHO26R3Jv60MT6WWkOD5hlYNyT9ciiLsR"
crossorigin="anonymous"></script>
</head>
<body>
<div id="dashboard">
<table v-if="clients && !error" class="ray_node_grid">
<thead>
<tr>
<th class="hostname">Hostname</th>
<th class="uptime">Uptime</th>
<th class="workers">Workers</th>
<th class="mem">RAM</th>
<th class="storage">Disk</th>
<th class="load">Load (1m, 5m, 15m)</th>
<th class="netsent">Sent (M/s)</th>
<th class="netrecv">Recv (M/s)</th>
</tr>
</thead>
<tbody is="node"
v-for="v in clients"
:key="v.hostname"
:now="now"
:hostname="v.hostname"
:boot_time="v.boot_time"
:n_workers="v.workers.length"
:n_cores="v.cpus[0]"
:m_avail="v.mem[1]"
:m_total="v.mem[0]"
:d_avail="v.disk['/'].free"
:d_total="v.disk['/'].total"
:load="v.load_avg[0]"
:n_sent="v.net[0]"
:n_recv="v.net[1]"
:workers="v.workers"
></tbody>
<tbody is="node"
class="totals"
v-if="totals"
:now="now"
:hostname="Object.keys(clients).length"
:boot_time="totals.boot_time"
:n_workers="totals.n_workers"
:n_cores="totals.n_cores"
:m_avail="totals.m_avail"
:m_total="totals.m_total"
:d_avail="totals.d_avail"
:d_total="totals.d_total"
:load="totals.load"
:n_sent="totals.n_sent"
:n_recv="totals.n_recv"
:workers="[]"
></tbody>
</table>
<template v-if="error">
<h2>{{error}}</h2>
</template>
<h2 v-if="last_update" :class="outdated_cls">Last updated {{age}} ago</h2>
<div class="cols">
<div class="tasks">
<template v-if="tasks && !error">
<h2>tasks</h2>
<ul>
<li v-for="v, k, _ in tasks">{{k}}: {{v}}</li>
</ul>
</template>
</div>
<div class="ray_config">
<template v-if="ray_config">
<h2>ray config</h2>
<pre>{{ray_config}}</pre>
</template>
</div>
</div>
</div>
</body>
<script src="res/main.js"></script>
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/res/main.css
|
CSS
|
* { font-family: monospace; margin: 0; padding: 0; }
h1, h2 { text-align: center; margin: 1rem 0; }
h1 { font-size: 3rem; margin: 0.5rem auto; text-align: center; }
h2 { font-size: 2rem; margin: 1rem auto; text-align: center; }
div#dashboard {
width: 116rem; margin: 1rem auto;
}
table, tbody, thead {
width: 100%;
margin: 0;
padding: 0;
}
tr {
cursor: pointer;
}
tr.workerlist td, tr.workerlist th {
font-size: 0.8rem;
}
tr:hover {
filter: brightness(0.85);
}
td, th {
padding: 0.3rem;
font-size: 1.4rem;
font-family: monospace;
text-align: center;
background-color: white;
}
th {
background-color: #eeeeee;
border: 1px solid black;
}
tbody.totals {
font-weight: bold;
font-size: 1.5rem;
}
ul { list-style-position: inside; }
.critical { background-color: magenta; }
.bad { background-color: red; }
.high { background-color: orange; }
.average { background-color: limegreen; }
.low { background-color: aquamarine; }
div.cols {
width: 100%;
margin: 1rem 0;
display: grid;
grid-template-columns: 1fr 1fr;
}
div.cols div {
padding: 1rem 0;
}
.outdated { background-color: red; }
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dashboard/res/main.js
|
JavaScript
|
let dashboard = new Vue({
el: "#dashboard",
data: {
now: (new Date()).getTime() / 1000,
shown: {},
error: "loading...",
last_update: undefined,
clients: undefined,
totals: undefined,
tasks: undefined,
ray_config: undefined,
},
methods: {
updateNodeInfo: function() {
var self = this;
fetch("/api/node_info").then(function (resp) {
return resp.json();
}).then(function(data) {
self.error = data.error;
if (data.error) {
self.clients = undefined;
self.tasks = undefined;
self.totals = undefined;
return;
}
self.last_update = data.timestamp;
self.clients = data.result.clients;
self.tasks = data.result.tasks;
self.totals = data.result.totals;
}).catch(function() {
self.error = "request error"
self.clients = undefined;
self.tasks = undefined;
self.totals = undefined;
}).finally(function() {
setTimeout(self.updateNodeInfo, 500);
});
},
updateRayConfig: function() {
var self = this;
fetch("/api/ray_config").then(function (resp) {
return resp.json();
}).then(function(data) {
if (data.error) {
self.ray_config = undefined;
return;
}
self.ray_config = data.result;
}).catch(function() {
self.error = "request error"
self.ray_config = undefined;
}).finally(function() {
setTimeout(self.updateRayConfig, 10000);
});
},
updateAll: function() {
this.updateNodeInfo();
this.updateRayConfig();
},
tickClock: function() {
this.now = (new Date()).getTime() / 1000;
}
},
computed: {
outdated_cls: function(ts) {
if ((this.now - this.last_update) > 5) {
return "outdated";
}
return "";
},
age: function(ts) {
return (this.now - this.last_update | 0) + "s";
},
},
filters: {
si: function(x) {
let prefixes = ["B", "K", "M", "G", "T"]
let i = 0;
while (x > 1024) {
x /= 1024;
i += 1;
}
return `${x.toFixed(1)}${prefixes[i]}`;
},
},
});
Vue.component("worker-usage", {
props: ['cores', 'workers'],
computed: {
frac: function() {
return this.workers / this.cores;
},
cls: function() {
if (this.frac > 3) { return "critical"; }
if (this.frac > 2) { return "bad"; }
if (this.frac > 1.5) { return "high"; }
if (this.frac > 1) { return "average"; }
return "low";
},
},
template: `
<td class="workers" :class="cls">
{{workers}}/{{cores}} {{(frac*100).toFixed(0)}}%
</td>
`,
});
Vue.component("node", {
props: [
"now",
"hostname",
"boot_time",
"n_workers",
"n_cores",
"m_avail",
"m_total",
"d_avail",
"d_total",
"load",
"n_sent",
"n_recv",
"workers",
],
data: function() {
return {
hidden: true,
};
},
computed: {
age: function() {
if (this.boot_time) {
let n = this.now;
if (this.boot_time > 2840140800) {
// Hack. It's a sum of multiple nodes.
n *= this.hostname;
}
let rs = n - this.boot_time | 0;
let s = rs % 60;
let m = ((rs / 60) % 60) | 0;
let h = (rs / 3600) | 0;
if (h) {
return `${h}h ${m}m ${s}s`;
}
if (m) {
return `${m}m ${s}s`;
}
return `${s}s`;
}
return "?"
},
},
methods: {
toggleHide: function() {
this.hidden = !this.hidden;
}
},
filters: {
mib(x) {
return `${(x/(1024**2)).toFixed(3)}M`;
},
hostnamefilter(x) {
if (isNaN(x)) {
return x;
}
return `Totals: ${x} nodes`;
},
},
template: `
<tbody v-on:click="toggleHide()">
<tr class="ray_node">
<td class="hostname">{{hostname | hostnamefilter}}</td>
<td class="uptime">{{age}}</td>
<worker-usage
:workers="n_workers"
:cores="n_cores"
></worker-usage>
<usagebar
:avail="m_avail" :total="m_total"
stat="mem"
></usagebar>
<usagebar
:avail="d_avail" :total="d_total"
stat="storage"
></usagebar>
<loadbar
:cores="n_cores"
:onem="load[0]"
:fivem="load[1]"
:fifteenm="load[2]"
>
</loadbar>
<td class="netsent">{{n_sent | mib}}/s</td>
<td class="netrecv">{{n_recv | mib}}/s</td>
</tr>
<template v-if="!hidden && workers">
<tr class="workerlist">
<th>time</th>
<th>name</th>
<th>pid</th>
<th>uss</th>
</tr>
<tr class="workerlist" v-for="x in workers">
<td>user: {{x.cpu_times.user}}s</td>
<td>{{x.name}}</td>
<td>{{x.pid}}</td>
<td>{{(x.memory_full_info.uss/1048576).toFixed(0)}}MiB</td>
</tr>
</template>
</tbody>
`,
});
Vue.component("usagebar", {
props: ['stat', 'avail', 'total'], // e.g. free -m avail
computed: {
used: function() { return this.total - this.avail; },
frac: function() { return (this.total - this.avail)/this.total; },
cls: function() {
if (this.frac > 0.95) { return "critical"; }
if (this.frac > 0.9) { return "bad"; }
if (this.frac > 0.8) { return "high"; }
if (this.frac > 0.5) { return "average"; }
return "low";
},
tcls: function() {
return `${this.stat} ${this.cls}`;
}
},
filters: {
gib(x) {
return `${(x/(1024**3)).toFixed(1)}G`;
},
pct(x) {
return `${(x*100).toFixed(0)}%`;
},
},
template: `
<td class="usagebar" :class="tcls">
{{used | gib}}/{{total | gib}} {{ frac | pct }}
</td>
`,
});
Vue.component("loadbar", {
props: ['cores', 'onem', 'fivem', 'fifteenm'],
computed: {
frac: function() { return this.onem/this.cores; },
cls: function() {
if (this.frac > 3) { return "critical"; }
if (this.frac > 2.5) { return "bad"; }
if (this.frac > 2) { return "high"; }
if (this.frac > 1.5) { return "average"; }
return "low";
},
},
template: `
<td class="load loadbar" :class="cls">
{{onem.toFixed(2)}}, {{fivem.toFixed(2)}}, {{fifteenm.toFixed(2)}}
</td>
`,
});
setInterval(dashboard.tickClock, 1000);
dashboard.updateAll();
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/dataframe/__init__.py
|
Python
|
raise DeprecationWarning("Pandas on Ray has moved to Modin: "
"github.com/modin-project/modin")
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/exceptions.py
|
Python
|
import os
import colorama
try:
import setproctitle
except ImportError:
setproctitle = None
import ray
class RayError(Exception):
"""Super class of all ray exception types."""
pass
class RayTaskError(RayError):
"""Indicates that a task threw an exception during execution.
If a task throws an exception during execution, a RayTaskError is stored in
the object store for each of the task's outputs. When an object is
retrieved from the object store, the Python method that retrieved it checks
to see if the object is a RayTaskError and if it is then an exception is
thrown propagating the error message.
Attributes:
function_name (str): The name of the function that failed and produced
the RayTaskError.
traceback_str (str): The traceback from the exception.
"""
def __init__(self,
function_name,
traceback_str,
cause_cls,
proctitle=None,
pid=None,
ip=None):
"""Initialize a RayTaskError."""
if proctitle:
self.proctitle = proctitle
elif setproctitle:
self.proctitle = setproctitle.getproctitle()
else:
self.proctitle = "ray_worker"
self.pid = pid or os.getpid()
self.ip = ip or ray.services.get_node_ip_address()
self.function_name = function_name
self.traceback_str = traceback_str
self.cause_cls = cause_cls
assert traceback_str is not None
def as_instanceof_cause(self):
"""Returns copy that is an instance of the cause's Python class.
The returned exception will inherit from both RayTaskError and the
cause class.
"""
if issubclass(RayTaskError, self.cause_cls):
return self # already satisfied
if issubclass(self.cause_cls, RayError):
return self # don't try to wrap ray internal errors
class cls(RayTaskError, self.cause_cls):
def __init__(self, function_name, traceback_str, cause_cls,
proctitle, pid, ip):
RayTaskError.__init__(self, function_name, traceback_str,
cause_cls, proctitle, pid, ip)
name = "RayTaskError({})".format(self.cause_cls.__name__)
cls.__name__ = name
cls.__qualname__ = name
return cls(self.function_name, self.traceback_str, self.cause_cls,
self.proctitle, self.pid, self.ip)
def __str__(self):
"""Format a RayTaskError as a string."""
lines = self.traceback_str.strip().split("\n")
out = []
in_worker = False
for line in lines:
if line.startswith("Traceback "):
out.append("{}{}{} (pid={}, ip={})".format(
colorama.Fore.CYAN, self.proctitle, colorama.Fore.RESET,
self.pid, self.ip))
elif in_worker:
in_worker = False
elif "ray/worker.py" in line or "ray/function_manager.py" in line:
in_worker = True
else:
out.append(line)
return "\n".join(out)
class RayWorkerError(RayError):
"""Indicates that the worker died unexpectedly while executing a task."""
def __str__(self):
return "The worker died unexpectedly while executing this task."
class RayActorError(RayError):
"""Indicates that the actor died unexpectedly before finishing a task.
This exception could happen either because the actor process dies while
executing a task, or because a task is submitted to a dead actor.
"""
def __str__(self):
return "The actor died unexpectedly before finishing this task."
class RayletError(RayError):
"""Indicates that the Raylet client has errored.
This exception can be thrown when the raylet is killed.
"""
def __init__(self, client_exc):
self.client_exc = client_exc
def __str__(self):
return "The Raylet died with this message: {}".format(self.client_exc)
class ObjectStoreFullError(RayError):
"""Indicates that the object store is full.
This is raised if the attempt to store the object fails
because the object store is full even after multiple retries.
"""
pass
class UnreconstructableError(RayError):
"""Indicates that an object is lost and cannot be reconstructed.
Note, this exception only happens for actor objects. If actor's current
state is after object's creating task, the actor cannot re-run the task to
reconstruct the object.
Attributes:
object_id: ID of the object.
"""
def __init__(self, object_id):
self.object_id = object_id
def __str__(self):
return (
"Object {} is lost (either LRU evicted or deleted by user) and "
"cannot be reconstructed. Try increasing the object store "
"memory available with ray.init(object_store_memory=<bytes>) "
"or setting object store limits with "
"ray.remote(object_store_memory=<bytes>). See also: {}".format(
self.object_id.hex(),
"https://ray.readthedocs.io/en/latest/memory-management.html"))
class RayTimeoutError(RayError):
"""Indicates that a call to the worker timed out."""
pass
RAY_EXCEPTION_TYPES = [
RayError,
RayTaskError,
RayWorkerError,
RayActorError,
ObjectStoreFullError,
UnreconstructableError,
RayTimeoutError,
]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/__init__.py
|
Python
|
from .gcs_flush_policy import (set_flushing_policy, GcsFlushPolicy,
SimpleGcsFlushPolicy)
from .named_actors import get_actor, register_actor
from .api import get, wait
from .actor_pool import ActorPool
from .dynamic_resources import set_resource
from . import iter
def TensorFlowVariables(*args, **kwargs):
raise DeprecationWarning(
"'ray.experimental.TensorFlowVariables' is deprecated. Instead, please"
" do 'from ray.experimental.tf_utils import TensorFlowVariables'.")
__all__ = [
"TensorFlowVariables",
"get_actor",
"register_actor",
"get",
"wait",
"set_flushing_policy",
"GcsFlushPolicy",
"SimpleGcsFlushPolicy",
"set_resource",
"ActorPool",
"iter",
]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/actor_pool.py
|
Python
|
import ray
class ActorPool:
"""Utility class to operate on a fixed pool of actors.
Arguments:
actors (list): List of Ray actor handles to use in this pool.
Examples:
>>> a1, a2 = Actor.remote(), Actor.remote()
>>> pool = ActorPool([a1, a2])
>>> print(pool.map(lambda a, v: a.double.remote(v), [1, 2, 3, 4]))
[2, 4, 6, 8]
"""
def __init__(self, actors):
# actors to be used
self._idle_actors = list(actors)
# get actor from future
self._future_to_actor = {}
# get future from index
self._index_to_future = {}
# next task to do
self._next_task_index = 0
# next task to return
self._next_return_index = 0
# next work depending when actors free
self._pending_submits = []
def map(self, fn, values):
"""Apply the given function in parallel over the actors and values.
This returns an ordered iterator that will return results of the map
as they finish. Note that you must iterate over the iterator to force
the computation to finish.
Arguments:
fn (func): Function that takes (actor, value) as argument and
returns an ObjectID computing the result over the value. The
actor will be considered busy until the ObjectID completes.
values (list): List of values that fn(actor, value) should be
applied to.
Returns:
Iterator over results from applying fn to the actors and values.
Examples:
>>> pool = ActorPool(...)
>>> print(pool.map(lambda a, v: a.double.remote(v), [1, 2, 3, 4]))
[2, 4, 6, 8]
"""
for v in values:
self.submit(fn, v)
while self.has_next():
yield self.get_next()
def map_unordered(self, fn, values):
"""Similar to map(), but returning an unordered iterator.
This returns an unordered iterator that will return results of the map
as they finish. This can be more efficient that map() if some results
take longer to compute than others.
Arguments:
fn (func): Function that takes (actor, value) as argument and
returns an ObjectID computing the result over the value. The
actor will be considered busy until the ObjectID completes.
values (list): List of values that fn(actor, value) should be
applied to.
Returns:
Iterator over results from applying fn to the actors and values.
Examples:
>>> pool = ActorPool(...)
>>> print(pool.map(lambda a, v: a.double.remote(v), [1, 2, 3, 4]))
[6, 2, 4, 8]
"""
for v in values:
self.submit(fn, v)
while self.has_next():
yield self.get_next_unordered()
def submit(self, fn, value):
"""Schedule a single task to run in the pool.
This has the same argument semantics as map(), but takes on a single
value instead of a list of values. The result can be retrieved using
get_next() / get_next_unordered().
Arguments:
fn (func): Function that takes (actor, value) as argument and
returns an ObjectID computing the result over the value. The
actor will be considered busy until the ObjectID completes.
value (object): Value to compute a result for.
Examples:
>>> pool = ActorPool(...)
>>> pool.submit(lambda a, v: a.double.remote(v), 1)
>>> pool.submit(lambda a, v: a.double.remote(v), 2)
>>> print(pool.get_next(), pool.get_next())
2, 4
"""
if self._idle_actors:
actor = self._idle_actors.pop()
future = fn(actor, value)
self._future_to_actor[future] = (self._next_task_index, actor)
self._index_to_future[self._next_task_index] = future
self._next_task_index += 1
else:
self._pending_submits.append((fn, value))
def has_next(self):
"""Returns whether there are any pending results to return.
Returns:
True if there are any pending results not yet returned.
Examples:
>>> pool = ActorPool(...)
>>> pool.submit(lambda a, v: a.double.remote(v), 1)
>>> print(pool.has_next())
True
>>> print(pool.get_next())
2
>>> print(pool.has_next())
False
"""
return bool(self._future_to_actor)
def get_next(self, timeout=None):
"""Returns the next pending result in order.
This returns the next result produced by submit(), blocking for up to
the specified timeout until it is available.
Returns:
The next result.
Raises:
TimeoutError if the timeout is reached.
Examples:
>>> pool = ActorPool(...)
>>> pool.submit(lambda a, v: a.double.remote(v), 1)
>>> print(pool.get_next())
2
"""
if not self.has_next():
raise StopIteration("No more results to get")
if self._next_return_index >= self._next_task_index:
raise ValueError("It is not allowed to call get_next() after "
"get_next_unordered().")
future = self._index_to_future[self._next_return_index]
if timeout is not None:
res, _ = ray.wait([future], timeout=timeout)
if not res:
raise TimeoutError("Timed out waiting for result")
del self._index_to_future[self._next_return_index]
self._next_return_index += 1
i, a = self._future_to_actor.pop(future)
self._return_actor(a)
return ray.get(future)
def get_next_unordered(self, timeout=None):
"""Returns any of the next pending results.
This returns some result produced by submit(), blocking for up to
the specified timeout until it is available. Unlike get_next(), the
results are not always returned in same order as submitted, which can
improve performance.
Returns:
The next result.
Raises:
TimeoutError if the timeout is reached.
Examples:
>>> pool = ActorPool(...)
>>> pool.submit(lambda a, v: a.double.remote(v), 1)
>>> pool.submit(lambda a, v: a.double.remote(v), 2)
>>> print(pool.get_next_unordered())
4
>>> print(pool.get_next_unordered())
2
"""
if not self.has_next():
raise StopIteration("No more results to get")
# TODO(ekl) bulk wait for performance
res, _ = ray.wait(
list(self._future_to_actor), num_returns=1, timeout=timeout)
if res:
[future] = res
else:
raise TimeoutError("Timed out waiting for result")
i, a = self._future_to_actor.pop(future)
self._return_actor(a)
del self._index_to_future[i]
self._next_return_index = max(self._next_return_index, i + 1)
return ray.get(future)
def _return_actor(self, actor):
self._idle_actors.append(actor)
if self._pending_submits:
self.submit(*self._pending_submits.pop(0))
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/api.py
|
Python
|
import ray
import numpy as np
def get(object_ids):
"""Get a single or a collection of remote objects from the object store.
This method is identical to `ray.get` except it adds support for tuples,
ndarrays and dictionaries.
Args:
object_ids: Object ID of the object to get, a list, tuple, ndarray of
object IDs to get or a dict of {key: object ID}.
Returns:
A Python object, a list of Python objects or a dict of {key: object}.
"""
if isinstance(object_ids, (tuple, np.ndarray)):
return ray.get(list(object_ids))
elif isinstance(object_ids, dict):
keys_to_get = [
k for k, v in object_ids.items() if isinstance(v, ray.ObjectID)
]
ids_to_get = [
v for k, v in object_ids.items() if isinstance(v, ray.ObjectID)
]
values = ray.get(ids_to_get)
result = object_ids.copy()
for key, value in zip(keys_to_get, values):
result[key] = value
return result
else:
return ray.get(object_ids)
def wait(object_ids, num_returns=1, timeout=None):
"""Return a list of IDs that are ready and a list of IDs that are not.
This method is identical to `ray.wait` except it adds support for tuples
and ndarrays.
Args:
object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)):
List like of object IDs for objects that may or may not be ready.
Note that these IDs must be unique.
num_returns (int): The number of object IDs that should be returned.
timeout (float): The maximum amount of time in seconds to wait before
returning.
Returns:
A list of object IDs that are ready and a list of the remaining object
IDs.
"""
if isinstance(object_ids, (tuple, np.ndarray)):
return ray.wait(
list(object_ids), num_returns=num_returns, timeout=timeout)
return ray.wait(object_ids, num_returns=num_returns, timeout=timeout)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/distributed/__init__.py
|
Python
|
from . import random
from . import linalg
from .core import (BLOCK_SIZE, DistArray, assemble, zeros, ones, copy, eye,
triu, tril, blockwise_dot, dot, transpose, add, subtract,
numpy_to_dist, subblocks)
__all__ = [
"random", "linalg", "BLOCK_SIZE", "DistArray", "assemble", "zeros", "ones",
"copy", "eye", "triu", "tril", "blockwise_dot", "dot", "transpose", "add",
"subtract", "numpy_to_dist", "subblocks"
]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/distributed/core.py
|
Python
|
import numpy as np
import ray.experimental.array.remote as ra
import ray
BLOCK_SIZE = 10
class DistArray:
def __init__(self, shape, objectids=None):
self.shape = shape
self.ndim = len(shape)
self.num_blocks = [
int(np.ceil(1.0 * a / BLOCK_SIZE)) for a in self.shape
]
if objectids is not None:
self.objectids = objectids
else:
self.objectids = np.empty(self.num_blocks, dtype=object)
if self.num_blocks != list(self.objectids.shape):
raise Exception("The fields `num_blocks` and `objectids` are "
"inconsistent, `num_blocks` is {} and `objectids` "
"has shape {}".format(self.num_blocks,
list(self.objectids.shape)))
@staticmethod
def compute_block_lower(index, shape):
if len(index) != len(shape):
raise Exception("The fields `index` and `shape` must have the "
"same length, but `index` is {} and `shape` is "
"{}.".format(index, shape))
return [elem * BLOCK_SIZE for elem in index]
@staticmethod
def compute_block_upper(index, shape):
if len(index) != len(shape):
raise Exception("The fields `index` and `shape` must have the "
"same length, but `index` is {} and `shape` is "
"{}.".format(index, shape))
upper = []
for i in range(len(shape)):
upper.append(min((index[i] + 1) * BLOCK_SIZE, shape[i]))
return upper
@staticmethod
def compute_block_shape(index, shape):
lower = DistArray.compute_block_lower(index, shape)
upper = DistArray.compute_block_upper(index, shape)
return [u - l for (l, u) in zip(lower, upper)]
@staticmethod
def compute_num_blocks(shape):
return [int(np.ceil(1.0 * a / BLOCK_SIZE)) for a in shape]
def assemble(self):
"""Assemble an array from a distributed array of object IDs."""
first_block = ray.get(self.objectids[(0, ) * self.ndim])
dtype = first_block.dtype
result = np.zeros(self.shape, dtype=dtype)
for index in np.ndindex(*self.num_blocks):
lower = DistArray.compute_block_lower(index, self.shape)
upper = DistArray.compute_block_upper(index, self.shape)
value = ray.get(self.objectids[index])
result[tuple(slice(l, u) for (l, u) in zip(lower, upper))] = value
return result
def __getitem__(self, sliced):
# TODO(rkn): Fix this, this is just a placeholder that should work but
# is inefficient.
a = self.assemble()
return a[sliced]
@ray.remote
def assemble(a):
return a.assemble()
# TODO(rkn): What should we call this method?
@ray.remote
def numpy_to_dist(a):
result = DistArray(a.shape)
for index in np.ndindex(*result.num_blocks):
lower = DistArray.compute_block_lower(index, a.shape)
upper = DistArray.compute_block_upper(index, a.shape)
idx = tuple(slice(l, u) for (l, u) in zip(lower, upper))
result.objectids[index] = ray.put(a[idx])
return result
@ray.remote
def zeros(shape, dtype_name="float"):
result = DistArray(shape)
for index in np.ndindex(*result.num_blocks):
result.objectids[index] = ra.zeros.remote(
DistArray.compute_block_shape(index, shape), dtype_name=dtype_name)
return result
@ray.remote
def ones(shape, dtype_name="float"):
result = DistArray(shape)
for index in np.ndindex(*result.num_blocks):
result.objectids[index] = ra.ones.remote(
DistArray.compute_block_shape(index, shape), dtype_name=dtype_name)
return result
@ray.remote
def copy(a):
result = DistArray(a.shape)
for index in np.ndindex(*result.num_blocks):
# We don't need to actually copy the objects because remote objects are
# immutable.
result.objectids[index] = a.objectids[index]
return result
@ray.remote
def eye(dim1, dim2=-1, dtype_name="float"):
dim2 = dim1 if dim2 == -1 else dim2
shape = [dim1, dim2]
result = DistArray(shape)
for (i, j) in np.ndindex(*result.num_blocks):
block_shape = DistArray.compute_block_shape([i, j], shape)
if i == j:
result.objectids[i, j] = ra.eye.remote(
block_shape[0], block_shape[1], dtype_name=dtype_name)
else:
result.objectids[i, j] = ra.zeros.remote(
block_shape, dtype_name=dtype_name)
return result
@ray.remote
def triu(a):
if a.ndim != 2:
raise Exception("Input must have 2 dimensions, but a.ndim is "
"{}.".format(a.ndim))
result = DistArray(a.shape)
for (i, j) in np.ndindex(*result.num_blocks):
if i < j:
result.objectids[i, j] = ra.copy.remote(a.objectids[i, j])
elif i == j:
result.objectids[i, j] = ra.triu.remote(a.objectids[i, j])
else:
result.objectids[i, j] = ra.zeros_like.remote(a.objectids[i, j])
return result
@ray.remote
def tril(a):
if a.ndim != 2:
raise Exception("Input must have 2 dimensions, but a.ndim is "
"{}.".format(a.ndim))
result = DistArray(a.shape)
for (i, j) in np.ndindex(*result.num_blocks):
if i > j:
result.objectids[i, j] = ra.copy.remote(a.objectids[i, j])
elif i == j:
result.objectids[i, j] = ra.tril.remote(a.objectids[i, j])
else:
result.objectids[i, j] = ra.zeros_like.remote(a.objectids[i, j])
return result
@ray.remote
def blockwise_dot(*matrices):
n = len(matrices)
if n % 2 != 0:
raise Exception("blockwise_dot expects an even number of arguments, "
"but len(matrices) is {}.".format(n))
shape = (matrices[0].shape[0], matrices[n // 2].shape[1])
result = np.zeros(shape)
for i in range(n // 2):
result += np.dot(matrices[i], matrices[n // 2 + i])
return result
@ray.remote
def dot(a, b):
if a.ndim != 2:
raise Exception("dot expects its arguments to be 2-dimensional, but "
"a.ndim = {}.".format(a.ndim))
if b.ndim != 2:
raise Exception("dot expects its arguments to be 2-dimensional, but "
"b.ndim = {}.".format(b.ndim))
if a.shape[1] != b.shape[0]:
raise Exception("dot expects a.shape[1] to equal b.shape[0], but "
"a.shape = {} and b.shape = {}.".format(
a.shape, b.shape))
shape = [a.shape[0], b.shape[1]]
result = DistArray(shape)
for (i, j) in np.ndindex(*result.num_blocks):
args = list(a.objectids[i, :]) + list(b.objectids[:, j])
result.objectids[i, j] = blockwise_dot.remote(*args)
return result
@ray.remote
def subblocks(a, *ranges):
"""
This function produces a distributed array from a subset of the blocks in
the `a`. The result and `a` will have the same number of dimensions. For
example,
subblocks(a, [0, 1], [2, 4])
will produce a DistArray whose objectids are
[[a.objectids[0, 2], a.objectids[0, 4]],
[a.objectids[1, 2], a.objectids[1, 4]]]
We allow the user to pass in an empty list [] to indicate the full range.
"""
ranges = list(ranges)
if len(ranges) != a.ndim:
raise Exception("sub_blocks expects to receive a number of ranges "
"equal to a.ndim, but it received {} ranges and "
"a.ndim = {}.".format(len(ranges), a.ndim))
for i in range(len(ranges)):
# We allow the user to pass in an empty list to indicate the full
# range.
if ranges[i] == []:
ranges[i] = range(a.num_blocks[i])
if not np.alltrue(ranges[i] == np.sort(ranges[i])):
raise Exception("Ranges passed to sub_blocks must be sorted, but "
"the {}th range is {}.".format(i, ranges[i]))
if ranges[i][0] < 0:
raise Exception("Values in the ranges passed to sub_blocks must "
"be at least 0, but the {}th range is {}.".format(
i, ranges[i]))
if ranges[i][-1] >= a.num_blocks[i]:
raise Exception("Values in the ranges passed to sub_blocks must "
"be less than the relevant number of blocks, but "
"the {}th range is {}, and a.num_blocks = {}."
.format(i, ranges[i], a.num_blocks))
last_index = [r[-1] for r in ranges]
last_block_shape = DistArray.compute_block_shape(last_index, a.shape)
shape = [(len(ranges[i]) - 1) * BLOCK_SIZE + last_block_shape[i]
for i in range(a.ndim)]
result = DistArray(shape)
for index in np.ndindex(*result.num_blocks):
result.objectids[index] = a.objectids[tuple(
ranges[i][index[i]] for i in range(a.ndim))]
return result
@ray.remote
def transpose(a):
if a.ndim != 2:
raise Exception("transpose expects its argument to be 2-dimensional, "
"but a.ndim = {}, a.shape = {}.".format(
a.ndim, a.shape))
result = DistArray([a.shape[1], a.shape[0]])
for i in range(result.num_blocks[0]):
for j in range(result.num_blocks[1]):
result.objectids[i, j] = ra.transpose.remote(a.objectids[j, i])
return result
# TODO(rkn): support broadcasting?
@ray.remote
def add(x1, x2):
if x1.shape != x2.shape:
raise Exception("add expects arguments `x1` and `x2` to have the same "
"shape, but x1.shape = {}, and x2.shape = {}.".format(
x1.shape, x2.shape))
result = DistArray(x1.shape)
for index in np.ndindex(*result.num_blocks):
result.objectids[index] = ra.add.remote(x1.objectids[index],
x2.objectids[index])
return result
# TODO(rkn): support broadcasting?
@ray.remote
def subtract(x1, x2):
if x1.shape != x2.shape:
raise Exception("subtract expects arguments `x1` and `x2` to have the "
"same shape, but x1.shape = {}, and x2.shape = {}."
.format(x1.shape, x2.shape))
result = DistArray(x1.shape)
for index in np.ndindex(*result.num_blocks):
result.objectids[index] = ra.subtract.remote(x1.objectids[index],
x2.objectids[index])
return result
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/distributed/linalg.py
|
Python
|
import numpy as np
import ray.experimental.array.remote as ra
import ray
from . import core
__all__ = ["tsqr", "modified_lu", "tsqr_hr", "qr"]
@ray.remote(num_return_vals=2)
def tsqr(a):
"""Perform a QR decomposition of a tall-skinny matrix.
Args:
a: A distributed matrix with shape MxN (suppose K = min(M, N)).
Returns:
A tuple of q (a DistArray) and r (a numpy array) satisfying the
following.
- If q_full = ray.get(DistArray, q).assemble(), then
q_full.shape == (M, K).
- np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True.
- If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N).
- np.allclose(r, np.triu(r)) == True.
"""
if len(a.shape) != 2:
raise Exception("tsqr requires len(a.shape) == 2, but a.shape is "
"{}".format(a.shape))
if a.num_blocks[1] != 1:
raise Exception("tsqr requires a.num_blocks[1] == 1, but a.num_blocks "
"is {}".format(a.num_blocks))
num_blocks = a.num_blocks[0]
K = int(np.ceil(np.log2(num_blocks))) + 1
q_tree = np.empty((num_blocks, K), dtype=object)
current_rs = []
for i in range(num_blocks):
block = a.objectids[i, 0]
q, r = ra.linalg.qr.remote(block)
q_tree[i, 0] = q
current_rs.append(r)
for j in range(1, K):
new_rs = []
for i in range(int(np.ceil(1.0 * len(current_rs) / 2))):
stacked_rs = ra.vstack.remote(*current_rs[(2 * i):(2 * i + 2)])
q, r = ra.linalg.qr.remote(stacked_rs)
q_tree[i, j] = q
new_rs.append(r)
current_rs = new_rs
assert len(current_rs) == 1, "len(current_rs) = " + str(len(current_rs))
# handle the special case in which the whole DistArray "a" fits in one
# block and has fewer rows than columns, this is a bit ugly so think about
# how to remove it
if a.shape[0] >= a.shape[1]:
q_shape = a.shape
else:
q_shape = [a.shape[0], a.shape[0]]
q_num_blocks = core.DistArray.compute_num_blocks(q_shape)
q_objectids = np.empty(q_num_blocks, dtype=object)
q_result = core.DistArray(q_shape, q_objectids)
# reconstruct output
for i in range(num_blocks):
q_block_current = q_tree[i, 0]
ith_index = i
for j in range(1, K):
if np.mod(ith_index, 2) == 0:
lower = [0, 0]
upper = [a.shape[1], core.BLOCK_SIZE]
else:
lower = [a.shape[1], 0]
upper = [2 * a.shape[1], core.BLOCK_SIZE]
ith_index //= 2
q_block_current = ra.dot.remote(
q_block_current,
ra.subarray.remote(q_tree[ith_index, j], lower, upper))
q_result.objectids[i] = q_block_current
r = current_rs[0]
return q_result, ray.get(r)
# TODO(rkn): This is unoptimized, we really want a block version of this.
# This is Algorithm 5 from
# http://www.eecs.berkeley.edu/Pubs/TechRpts/2013/EECS-2013-175.pdf.
@ray.remote(num_return_vals=3)
def modified_lu(q):
"""Perform a modified LU decomposition of a matrix.
This takes a matrix q with orthonormal columns, returns l, u, s such that
q - s = l * u.
Args:
q: A two dimensional orthonormal matrix q.
Returns:
A tuple of a lower triangular matrix l, an upper triangular matrix u,
and a a vector representing a diagonal matrix s such that
q - s = l * u.
"""
q = q.assemble()
m, b = q.shape[0], q.shape[1]
S = np.zeros(b)
q_work = np.copy(q)
for i in range(b):
S[i] = -1 * np.sign(q_work[i, i])
q_work[i, i] -= S[i]
# Scale ith column of L by diagonal element.
q_work[(i + 1):m, i] /= q_work[i, i]
# Perform Schur complement update.
q_work[(i + 1):m, (i + 1):b] -= np.outer(q_work[(i + 1):m, i],
q_work[i, (i + 1):b])
L = np.tril(q_work)
for i in range(b):
L[i, i] = 1
U = np.triu(q_work)[:b, :]
# TODO(rkn): Get rid of the put below.
return ray.get(core.numpy_to_dist.remote(ray.put(L))), U, S
@ray.remote(num_return_vals=2)
def tsqr_hr_helper1(u, s, y_top_block, b):
y_top = y_top_block[:b, :b]
s_full = np.diag(s)
t = -1 * np.dot(u, np.dot(s_full, np.linalg.inv(y_top).T))
return t, y_top
@ray.remote
def tsqr_hr_helper2(s, r_temp):
s_full = np.diag(s)
return np.dot(s_full, r_temp)
# This is Algorithm 6 from
# http://www.eecs.berkeley.edu/Pubs/TechRpts/2013/EECS-2013-175.pdf.
@ray.remote(num_return_vals=4)
def tsqr_hr(a):
q, r_temp = tsqr.remote(a)
y, u, s = modified_lu.remote(q)
y_blocked = ray.get(y)
t, y_top = tsqr_hr_helper1.remote(u, s, y_blocked.objectids[0, 0],
a.shape[1])
r = tsqr_hr_helper2.remote(s, r_temp)
return ray.get(y), ray.get(t), ray.get(y_top), ray.get(r)
@ray.remote
def qr_helper1(a_rc, y_ri, t, W_c):
return a_rc - np.dot(y_ri, np.dot(t.T, W_c))
@ray.remote
def qr_helper2(y_ri, a_rc):
return np.dot(y_ri.T, a_rc)
# This is Algorithm 7 from
# http://www.eecs.berkeley.edu/Pubs/TechRpts/2013/EECS-2013-175.pdf.
@ray.remote(num_return_vals=2)
def qr(a):
m, n = a.shape[0], a.shape[1]
k = min(m, n)
# we will store our scratch work in a_work
a_work = core.DistArray(a.shape, np.copy(a.objectids))
result_dtype = np.linalg.qr(ray.get(a.objectids[0, 0]))[0].dtype.name
# TODO(rkn): It would be preferable not to get this right after creating
# it.
r_res = ray.get(core.zeros.remote([k, n], result_dtype))
# TODO(rkn): It would be preferable not to get this right after creating
# it.
y_res = ray.get(core.zeros.remote([m, k], result_dtype))
Ts = []
# The for loop differs from the paper, which says
# "for i in range(a.num_blocks[1])", but that doesn't seem to make any
# sense when a.num_blocks[1] > a.num_blocks[0].
for i in range(min(a.num_blocks[0], a.num_blocks[1])):
sub_dist_array = core.subblocks.remote(
a_work, list(range(i, a_work.num_blocks[0])), [i])
y, t, _, R = tsqr_hr.remote(sub_dist_array)
y_val = ray.get(y)
for j in range(i, a.num_blocks[0]):
y_res.objectids[j, i] = y_val.objectids[j - i, 0]
if a.shape[0] > a.shape[1]:
# in this case, R needs to be square
R_shape = ray.get(ra.shape.remote(R))
eye_temp = ra.eye.remote(
R_shape[1], R_shape[0], dtype_name=result_dtype)
r_res.objectids[i, i] = ra.dot.remote(eye_temp, R)
else:
r_res.objectids[i, i] = R
Ts.append(core.numpy_to_dist.remote(t))
for c in range(i + 1, a.num_blocks[1]):
W_rcs = []
for r in range(i, a.num_blocks[0]):
y_ri = y_val.objectids[r - i, 0]
W_rcs.append(qr_helper2.remote(y_ri, a_work.objectids[r, c]))
W_c = ra.sum_list.remote(*W_rcs)
for r in range(i, a.num_blocks[0]):
y_ri = y_val.objectids[r - i, 0]
A_rc = qr_helper1.remote(a_work.objectids[r, c], y_ri, t, W_c)
a_work.objectids[r, c] = A_rc
r_res.objectids[i, c] = a_work.objectids[i, c]
# construct q_res from Ys and Ts
q = core.eye.remote(m, k, dtype_name=result_dtype)
for i in range(len(Ts))[::-1]:
y_col_block = core.subblocks.remote(y_res, [], [i])
q = core.subtract.remote(
q,
core.dot.remote(
y_col_block,
core.dot.remote(
Ts[i],
core.dot.remote(core.transpose.remote(y_col_block), q))))
return ray.get(q), r_res
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/distributed/random.py
|
Python
|
import numpy as np
import ray.experimental.array.remote as ra
import ray
from .core import DistArray
@ray.remote
def normal(shape):
num_blocks = DistArray.compute_num_blocks(shape)
objectids = np.empty(num_blocks, dtype=object)
for index in np.ndindex(*num_blocks):
objectids[index] = ra.random.normal.remote(
DistArray.compute_block_shape(index, shape))
result = DistArray(shape, objectids)
return result
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/remote/__init__.py
|
Python
|
from . import random
from . import linalg
from .core import (zeros, zeros_like, ones, eye, dot, vstack, hstack, subarray,
copy, tril, triu, diag, transpose, add, subtract, sum,
shape, sum_list)
__all__ = [
"random", "linalg", "zeros", "zeros_like", "ones", "eye", "dot", "vstack",
"hstack", "subarray", "copy", "tril", "triu", "diag", "transpose", "add",
"subtract", "sum", "shape", "sum_list"
]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/remote/core.py
|
Python
|
import numpy as np
import ray
@ray.remote
def zeros(shape, dtype_name="float", order="C"):
return np.zeros(shape, dtype=np.dtype(dtype_name), order=order)
@ray.remote
def zeros_like(a, dtype_name="None", order="K", subok=True):
dtype_val = None if dtype_name == "None" else np.dtype(dtype_name)
return np.zeros_like(a, dtype=dtype_val, order=order, subok=subok)
@ray.remote
def ones(shape, dtype_name="float", order="C"):
return np.ones(shape, dtype=np.dtype(dtype_name), order=order)
@ray.remote
def eye(N, M=-1, k=0, dtype_name="float"):
M = N if M == -1 else M
return np.eye(N, M=M, k=k, dtype=np.dtype(dtype_name))
@ray.remote
def dot(a, b):
return np.dot(a, b)
@ray.remote
def vstack(*xs):
return np.vstack(xs)
@ray.remote
def hstack(*xs):
return np.hstack(xs)
# TODO(rkn): Instead of this, consider implementing slicing.
# TODO(rkn): Be consistent about using "index" versus "indices".
@ray.remote
def subarray(a, lower_indices, upper_indices):
idx = tuple(slice(l, u) for (l, u) in zip(lower_indices, upper_indices))
return a[idx]
@ray.remote
def copy(a, order="K"):
return np.copy(a, order=order)
@ray.remote
def tril(m, k=0):
return np.tril(m, k=k)
@ray.remote
def triu(m, k=0):
return np.triu(m, k=k)
@ray.remote
def diag(v, k=0):
return np.diag(v, k=k)
@ray.remote
def transpose(a, axes=[]):
axes = None if axes == [] else axes
return np.transpose(a, axes=axes)
@ray.remote
def add(x1, x2):
return np.add(x1, x2)
@ray.remote
def subtract(x1, x2):
return np.subtract(x1, x2)
@ray.remote
def sum(x, axis=-1):
return np.sum(x, axis=axis if axis != -1 else None)
@ray.remote
def shape(a):
return np.shape(a)
@ray.remote
def sum_list(*xs):
return np.sum(xs, axis=0)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/remote/linalg.py
|
Python
|
import numpy as np
import ray
__all__ = [
"matrix_power", "solve", "tensorsolve", "tensorinv", "inv", "cholesky",
"eigvals", "eigvalsh", "pinv", "slogdet", "det", "svd", "eig", "eigh",
"lstsq", "norm", "qr", "cond", "matrix_rank", "multi_dot"
]
@ray.remote
def matrix_power(M, n):
return np.linalg.matrix_power(M, n)
@ray.remote
def solve(a, b):
return np.linalg.solve(a, b)
@ray.remote(num_return_vals=2)
def tensorsolve(a):
raise NotImplementedError
@ray.remote(num_return_vals=2)
def tensorinv(a):
raise NotImplementedError
@ray.remote
def inv(a):
return np.linalg.inv(a)
@ray.remote
def cholesky(a):
return np.linalg.cholesky(a)
@ray.remote
def eigvals(a):
return np.linalg.eigvals(a)
@ray.remote
def eigvalsh(a):
raise NotImplementedError
@ray.remote
def pinv(a):
return np.linalg.pinv(a)
@ray.remote
def slogdet(a):
raise NotImplementedError
@ray.remote
def det(a):
return np.linalg.det(a)
@ray.remote(num_return_vals=3)
def svd(a):
return np.linalg.svd(a)
@ray.remote(num_return_vals=2)
def eig(a):
return np.linalg.eig(a)
@ray.remote(num_return_vals=2)
def eigh(a):
return np.linalg.eigh(a)
@ray.remote(num_return_vals=4)
def lstsq(a, b):
return np.linalg.lstsq(a)
@ray.remote
def norm(x):
return np.linalg.norm(x)
@ray.remote(num_return_vals=2)
def qr(a):
return np.linalg.qr(a)
@ray.remote
def cond(x):
return np.linalg.cond(x)
@ray.remote
def matrix_rank(M):
return np.linalg.matrix_rank(M)
@ray.remote
def multi_dot(*a):
raise NotImplementedError
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/array/remote/random.py
|
Python
|
import numpy as np
import ray
@ray.remote
def normal(shape):
return np.random.normal(size=shape)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/async_api.py
|
Python
|
# Note: asyncio is only compatible with Python 3
import asyncio
import functools
import threading
import pyarrow.plasma as plasma
import ray
from ray.experimental.async_plasma import PlasmaProtocol, PlasmaEventHandler
from ray.services import logger
handler = None
transport = None
protocol = None
class _ThreadSafeProxy:
"""This class is used to create a thread-safe proxy for a given object.
Every method call will be guarded with a lock.
Attributes:
orig_obj (object): the original object.
lock (threading.Lock): the lock object.
_wrapper_cache (dict): a cache from original object's methods to
the proxy methods.
"""
def __init__(self, orig_obj, lock):
self.orig_obj = orig_obj
self.lock = lock
self._wrapper_cache = {}
def __getattr__(self, attr):
orig_attr = getattr(self.orig_obj, attr)
if not callable(orig_attr):
# If the original attr is a field, just return it.
return orig_attr
else:
# If the orginal attr is a method,
# return a wrapper that guards the original method with a lock.
wrapper = self._wrapper_cache.get(attr)
if wrapper is None:
@functools.wraps(orig_attr)
def _wrapper(*args, **kwargs):
with self.lock:
return orig_attr(*args, **kwargs)
self._wrapper_cache[attr] = _wrapper
wrapper = _wrapper
return wrapper
def thread_safe_client(client, lock=None):
"""Create a thread-safe proxy which locks every method call
for the given client.
Args:
client: the client object to be guarded.
lock: the lock object that will be used to lock client's methods.
If None, a new lock will be used.
Returns:
A thread-safe proxy for the given client.
"""
if lock is None:
lock = threading.Lock()
return _ThreadSafeProxy(client, lock)
async def _async_init():
global handler, transport, protocol
if handler is None:
worker = ray.worker.global_worker
plasma_client = thread_safe_client(
plasma.connect(worker.node.plasma_store_socket_name, 300))
loop = asyncio.get_event_loop()
plasma_client.subscribe()
rsock = plasma_client.get_notification_socket()
handler = PlasmaEventHandler(loop, worker)
transport, protocol = await loop.create_connection(
lambda: PlasmaProtocol(plasma_client, handler), sock=rsock)
logger.debug("AsyncPlasma Connection Created!")
def init():
"""
Initialize synchronously.
"""
assert ray.is_initialized(), "Please call ray.init before async_api.init"
# Noop when handler is set.
if handler is not None:
return
loop = asyncio.get_event_loop()
if loop.is_running():
assert loop._thread_id != threading.get_ident(), (
"You are using async_api inside a running event loop. "
"Please call `await _async_init()` to initialize inside "
"asynchrounous context.")
# If the loop is runing outside current thread, we actually need
# to do this to make sure the context is initialized.
asyncio.run_coroutine_threadsafe(_async_init(), loop=loop)
else:
asyncio.get_event_loop().run_until_complete(_async_init())
def as_future(object_id):
"""Turn an object_id into a Future object.
Args:
object_id: A Ray object_id.
Returns:
PlasmaObjectFuture: A future object that waits the object_id.
"""
if handler is None:
init()
return handler.as_future(object_id)
def shutdown():
"""Manually shutdown the async API.
Cancels all related tasks and all the socket transportation.
"""
global handler, transport, protocol
if handler is not None:
handler.close()
transport.close()
handler = None
transport = None
protocol = None
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/async_plasma.py
|
Python
|
import asyncio
import ctypes
import sys
import pyarrow.plasma as plasma
import ray
from ray.services import logger
INT64_SIZE = ctypes.sizeof(ctypes.c_int64)
def _release_waiter(waiter, *_):
if not waiter.done():
waiter.set_result(None)
class PlasmaProtocol(asyncio.Protocol):
"""Protocol control for the asyncio connection."""
def __init__(self, plasma_client, plasma_event_handler):
self.plasma_client = plasma_client
self.plasma_event_handler = plasma_event_handler
self.transport = None
self._buffer = b""
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
self._buffer += data
messages = []
i = 0
while i + INT64_SIZE <= len(self._buffer):
msg_len = int.from_bytes(self._buffer[i:i + INT64_SIZE],
sys.byteorder)
if i + INT64_SIZE + msg_len > len(self._buffer):
break
i += INT64_SIZE
segment = self._buffer[i:i + msg_len]
i += msg_len
(object_ids, object_sizes,
metadata_sizes) = self.plasma_client.decode_notifications(segment)
assert len(object_ids) == len(object_sizes) == len(metadata_sizes)
for j in range(len(object_ids)):
messages.append((object_ids[j], object_sizes[j],
metadata_sizes[j]))
self._buffer = self._buffer[i:]
self.plasma_event_handler.process_notifications(messages)
def connection_lost(self, exc):
# The socket has been closed
logger.debug("PlasmaProtocol - connection lost.")
def eof_received(self):
logger.debug("PlasmaProtocol - EOF received.")
self.transport.close()
class PlasmaObjectFuture(asyncio.Future):
"""This class manages the lifecycle of a Future contains an object_id.
Note:
This Future is an item in an linked list.
Attributes:
object_id: The object_id this Future contains.
"""
def __init__(self, loop, object_id):
super().__init__(loop=loop)
self.object_id = object_id
self.prev = None
self.next = None
@property
def ray_object_id(self):
return ray.ObjectID(self.object_id.binary())
def __repr__(self):
return super().__repr__() + "{object_id=%s}" % self.object_id
class PlasmaObjectLinkedList(asyncio.Future):
"""This class is a doubly-linked list.
It holds a ObjectID and maintains futures assigned to the ObjectID.
Args:
loop: an event loop.
plain_object_id (plasma.ObjectID):
The plasma ObjectID this class holds.
"""
def __init__(self, loop, plain_object_id):
super().__init__(loop=loop)
assert isinstance(plain_object_id, plasma.ObjectID)
self.object_id = plain_object_id
self.head = None
self.tail = None
def append(self, future):
"""Append an object to the linked list.
Args:
future (PlasmaObjectFuture): A PlasmaObjectFuture instance.
"""
future.prev = self.tail
if self.tail is None:
assert self.head is None
self.head = future
else:
self.tail.next = future
self.tail = future
# Once done, it will be removed from the list.
future.add_done_callback(self.remove)
def remove(self, future):
"""Remove an object from the linked list.
Args:
future (PlasmaObjectFuture): A PlasmaObjectFuture instance.
"""
if self._loop.get_debug():
logger.debug("Removing %s from the linked list.", future)
if future.prev is None:
assert future is self.head
self.head = future.next
if self.head is None:
self.tail = None
if not self.cancelled():
self.set_result(None)
else:
self.head.prev = None
elif future.next is None:
assert future is self.tail
self.tail = future.prev
if self.tail is None:
self.head = None
if not self.cancelled():
self.set_result(None)
else:
self.tail.prev = None
def cancel(self, *args, **kwargs):
"""Manually cancel all tasks assigned to this event loop."""
# Because remove all futures will trigger `set_result`,
# we cancel itself first.
super().cancel()
for future in self.traverse():
# All cancelled futures should have callbacks to removed itself
# from this linked list. However, these callbacks are scheduled in
# an event loop, so we could still find them in our list.
if not future.cancelled():
future.cancel()
def set_result(self, result):
"""Complete all tasks. """
for future in self.traverse():
# All cancelled futures should have callbacks to removed itself
# from this linked list. However, these callbacks are scheduled in
# an event loop, so we could still find them in our list.
future.set_result(result)
if not self.done():
super().set_result(result)
def traverse(self):
"""Traverse this linked list.
Yields:
PlasmaObjectFuture: PlasmaObjectFuture instances.
"""
current = self.head
while current is not None:
yield current
current = current.next
class PlasmaEventHandler:
"""This class is an event handler for Plasma."""
def __init__(self, loop, worker):
super().__init__()
self._loop = loop
self._worker = worker
self._waiting_dict = {}
def process_notifications(self, messages):
"""Process notifications."""
for object_id, object_size, metadata_size in messages:
if object_size > 0 and object_id in self._waiting_dict:
linked_list = self._waiting_dict[object_id]
self._complete_future(linked_list)
def close(self):
"""Clean up this handler."""
for linked_list in self._waiting_dict.values():
linked_list.cancel()
# All cancelled linked lists should have callbacks to removed itself
# from the waiting dict. However, these callbacks are scheduled in
# an event loop, so we don't check them now.
def _unregister_callback(self, fut):
del self._waiting_dict[fut.object_id]
def _complete_future(self, fut):
obj = self._worker.get_objects([ray.ObjectID(
fut.object_id.binary())])[0]
fut.set_result(obj)
def as_future(self, object_id, check_ready=True):
"""Turn an object_id into a Future object.
Args:
object_id: A Ray's object_id.
check_ready (bool): If true, check if the object_id is ready.
Returns:
PlasmaObjectFuture: A future object that waits the object_id.
"""
if not isinstance(object_id, ray.ObjectID):
raise TypeError("Input should be an ObjectID.")
plain_object_id = plasma.ObjectID(object_id.binary())
fut = PlasmaObjectFuture(loop=self._loop, object_id=plain_object_id)
if check_ready:
ready, _ = ray.wait([object_id], timeout=0)
if ready:
if self._loop.get_debug():
logger.debug("%s has been ready.", plain_object_id)
self._complete_future(fut)
return fut
if plain_object_id not in self._waiting_dict:
linked_list = PlasmaObjectLinkedList(self._loop, plain_object_id)
linked_list.add_done_callback(self._unregister_callback)
self._waiting_dict[plain_object_id] = linked_list
self._waiting_dict[plain_object_id].append(fut)
if self._loop.get_debug():
logger.debug("%s added to the waiting list.", fut)
return fut
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/dynamic_resources.py
|
Python
|
import ray
def set_resource(resource_name, capacity, client_id=None):
""" Set a resource to a specified capacity.
This creates, updates or deletes a custom resource for a target clientId.
If the resource already exists, it's capacity is updated to the new value.
If the capacity is set to 0, the resource is deleted.
If ClientID is not specified or set to None,
the resource is created on the local client where the actor is running.
Args:
resource_name (str): Name of the resource to be created
capacity (int): Capacity of the new resource. Resource is deleted if
capacity is 0.
client_id (str): The ClientId of the node where the resource is to be
set.
Returns:
None
Raises:
ValueError: This exception is raised when a non-negative capacity is
specified.
"""
if client_id is not None:
client_id_obj = ray.ClientID(ray.utils.hex_to_binary(client_id))
else:
client_id_obj = ray.ClientID.nil()
if (capacity < 0) or (capacity != int(capacity)):
raise ValueError(
"Capacity {} must be a non-negative integer.".format(capacity))
return ray.worker.global_worker.raylet_client.set_resource(
resource_name, capacity, client_id_obj)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/gcs_flush_policy.py
|
Python
|
import os
import time
import ray
import ray.cloudpickle as pickle
class GcsFlushPolicy:
"""Experimental: a policy to control GCS flushing.
Used by Monitor to enable automatic control of memory usage.
"""
def should_flush(self, redis_client):
"""Returns a bool, whether a flush request should be issued."""
pass
def num_entries_to_flush(self):
"""Returns an upper bound for number of entries to flush next."""
pass
def record_flush(self):
"""Must be called after a flush has been performed."""
pass
class SimpleGcsFlushPolicy(GcsFlushPolicy):
"""A simple policy with constant flush rate, after a warmup period.
Example policy values:
flush_when_at_least_bytes 2GB
flush_period_secs 10s
flush_num_entries_each_time 10k
This means: (1) If the GCS shard uses less than 2GB of memory,
no flushing would take place. This should cover most Ray runs. (2) The
GCS shard will only honor a flush request, if it's issued after 10
seconds since the last processed flush. In particular this means it's
okay for the Monitor to issue requests more frequently than this param.
(3) When processing a flush, the shard will flush at most 10k entries.
This is to control the latency of each request.
Note, flush rate == (flush period) * (num entries each time). So
applications that have a heavier GCS load can tune these params.
"""
def __init__(self,
flush_when_at_least_bytes=(1 << 31),
flush_period_secs=10,
flush_num_entries_each_time=10000):
self.flush_when_at_least_bytes = flush_when_at_least_bytes
self.flush_period_secs = flush_period_secs
self.flush_num_entries_each_time = flush_num_entries_each_time
self.last_flush_timestamp = time.time()
def should_flush(self, redis_client):
if time.time() - self.last_flush_timestamp < self.flush_period_secs:
return False
used_memory = redis_client.info("memory")["used_memory"]
assert used_memory > 0
return used_memory >= self.flush_when_at_least_bytes
def num_entries_to_flush(self):
return self.flush_num_entries_each_time
def record_flush(self):
self.last_flush_timestamp = time.time()
def serialize(self):
return pickle.dumps(self)
def set_flushing_policy(flushing_policy):
"""Serialize this policy for Monitor to pick up."""
if "RAY_USE_NEW_GCS" not in os.environ:
raise Exception(
"set_flushing_policy() is only available when environment "
"variable RAY_USE_NEW_GCS is present at both compile and run time."
)
ray.worker.global_worker.check_connected()
redis_client = ray.worker.global_worker.redis_client
serialized = pickle.dumps(flushing_policy)
redis_client.set("gcs_flushing_policy", serialized)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/internal_kv.py
|
Python
|
import ray
_local = {} # dict for local mode
def _internal_kv_initialized():
worker = ray.worker.get_global_worker()
return hasattr(worker, "mode") and worker.mode is not None
def _internal_kv_get(key):
"""Fetch the value of a binary key."""
worker = ray.worker.get_global_worker()
if worker.mode == ray.worker.LOCAL_MODE:
return _local.get(key)
return worker.redis_client.hget(key, "value")
def _internal_kv_put(key, value, overwrite=False):
"""Globally associates a value with a given binary key.
This only has an effect if the key does not already have a value.
Returns:
already_exists (bool): whether the value already exists.
"""
worker = ray.worker.get_global_worker()
if worker.mode == ray.worker.LOCAL_MODE:
exists = key in _local
if not exists or overwrite:
_local[key] = value
return exists
if overwrite:
updated = worker.redis_client.hset(key, "value", value)
else:
updated = worker.redis_client.hsetnx(key, "value", value)
return updated == 0 # already exists
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/iter.py
|
Python
|
from typing import TypeVar, Generic, Iterable, List, Callable, Any
import ray
# The type of an iterator element.
T = TypeVar("T")
U = TypeVar("U")
def from_items(items: List[T], num_shards: int = 2,
repeat: bool = False) -> "ParallelIterator[T]":
"""Create a parallel iterator from an existing set of objects.
The objects will be divided round-robin among the number of shards.
Arguments:
items (list): The list of items to iterate over.
num_shards (int): The number of worker actors to create.
repeat (bool): Whether to cycle over the items forever.
"""
shards = [[] for _ in range(num_shards)]
for i, item in enumerate(items):
shards[i % num_shards].append(item)
name = "from_items[{}, {}, shards={}{}]".format(
items and type(items[0]).__name__ or "None", len(items), num_shards,
", repeat=True" if repeat else "")
return from_iterators(shards, repeat=repeat, name=name)
def from_range(n: int, num_shards: int = 2,
repeat: bool = False) -> "ParallelIterator[int]":
"""Create a parallel iterator over the range 0..n.
The range will be partitioned sequentially among the number of shards.
Arguments:
n (int): The max end of the range of numbers.
num_shards (int): The number of worker actors to create.
repeat (bool): Whether to cycle over the range forever.
"""
generators = []
shard_size = n // num_shards
for i in range(num_shards):
start = i * shard_size
if i == num_shards - 1:
end = n
else:
end = (i + 1) * shard_size
generators.append(range(start, end))
name = "from_range[{}, shards={}{}]".format(
n, num_shards, ", repeat=True" if repeat else "")
return from_iterators(generators, repeat=repeat, name=name)
def from_iterators(generators: List[Iterable[T]],
repeat: bool = False,
name=None) -> "ParallelIterator[T]":
"""Create a parallel iterator from a set of iterators.
An actor will be created for each iterator.
Examples:
>>> # Create using a list of generators.
>>> from_iterators([range(100), range(100)])
>>> # Equivalent to the above.
>>> from_iterators([lambda: range(100), lambda: range(100)])
Arguments:
generators (list): A list of Python generator objects or lambda
functions that produced a generator when called. We allow lambda
functions since the generator itself might not be serializable,
but a lambda that returns it can be.
repeat (bool): Whether to cycle over the iterators forever.
name (str): Optional name to give the iterator.
"""
worker_cls = ray.remote(ParallelIteratorWorker)
actors = [worker_cls.remote(g, repeat) for g in generators]
if not name:
name = "from_iterators[shards={}{}]".format(
len(generators), ", repeat=True" if repeat else "")
return from_actors(actors, name=name)
def from_actors(actors: List["ray.actor.ActorHandle"],
name=None) -> "ParallelIterator[T]":
"""Create a parallel iterator from an existing set of actors.
Each actor must subclass the ParallelIteratorWorker interface.
Arguments:
actors (list): List of actors that each implement
ParallelIteratorWorker.
name (str): Optional name to give the iterator.
"""
if not name:
name = "from_actors[shards={}]".format(len(actors))
return ParallelIterator([_ActorSet(actors, [])], name)
class ParallelIterator(Generic[T]):
"""A parallel iterator over a set of remote actors.
This can be used to iterate over a fixed set of task results
(like an actor pool), or a stream of data (e.g., a fixed range of numbers,
an infinite stream of RLlib rollout results).
This class is **serializable** and can be passed to other remote
tasks and actors. However, each shard should be read from at most one
process at a time.
Examples:
>>> # Applying a function over items in parallel.
>>> it = ray.experimental.iter.from_items([1, 2, 3], num_shards=2)
... <__main__.ParallelIterator object>
>>> it = it.for_each(lambda x: x * 2).gather_sync()
... <__main__.LocalIterator object>
>>> print(list(it))
... [2, 4, 6]
>>> # Creating from generators.
>>> it = ray.experimental.iter.from_iterators([range(3), range(3)])
... <__main__.ParallelIterator object>
>>> print(list(it.gather_sync()))
... [0, 0, 1, 1, 2, 2]
>>> # Accessing the individual shards of an iterator.
>>> it = ray.experimental.iter.from_range(10, num_shards=2)
... <__main__.ParallelIterator object>
>>> it0 = it.get_shard(0)
... <__main__.LocalIterator object>
>>> print(list(it0))
... [0, 1, 2, 3, 4]
>>> it1 = it.get_shard(1)
... <__main__.LocalIterator object>
>>> print(list(it1))
... [5, 6, 7, 8, 9]
>>> # Gathering results from actors synchronously in parallel.
>>> it = ray.experimental.iter.from_actors(workers)
... <__main__.ParallelIterator object>
>>> it = it.batch_across_shards()
... <__main__.LocalIterator object>
>>> print(next(it))
... [worker_1_result_1, worker_2_result_1]
>>> print(next(it))
... [worker_1_result_2, worker_2_result_2]
"""
def __init__(self, actor_sets: List["_ActorSet"], name: str):
# We track multiple sets of actors to support parallel .union().
self.actor_sets = actor_sets
self.name = name
def __iter__(self):
raise TypeError(
"You must use it.gather_sync() or it.gather_async() to "
"iterate over the results of a ParallelIterator.")
def __str__(self):
return repr(self)
def __repr__(self):
return "ParallelIterator[{}]".format(self.name)
def for_each(self, fn: Callable[[T], U]) -> "ParallelIterator[U]":
"""Remotely apply fn to each item in this iterator.
Arguments:
fn (func): function to apply to each item.
Examples:
>>> next(from_range(4).for_each(lambda x: x * 2).gather_sync())
... [0, 2, 4, 8]
"""
return ParallelIterator(
[
a.with_transform(lambda local_it: local_it.for_each(fn))
for a in self.actor_sets
],
name=self.name + ".for_each()")
def filter(self, fn: Callable[[T], bool]) -> "ParallelIterator[T]":
"""Remotely filter items from this iterator.
Arguments:
fn (func): returns False for items to drop from the iterator.
Examples:
>>> it = from_items([0, 1, 2]).filter(lambda x: x > 0)
>>> next(it.gather_sync())
... [1, 2]
"""
return ParallelIterator(
[
a.with_transform(lambda local_it: local_it.filter(fn))
for a in self.actor_sets
],
name=self.name + ".filter()")
def batch(self, n: int) -> "ParallelIterator[List[T]]":
"""Remotely batch together items in this iterator.
Arguments:
n (int): Number of items to batch together.
Examples:
>>> next(from_range(10, 1).batch(4).gather_sync())
... [0, 1, 2, 3]
"""
return ParallelIterator(
[
a.with_transform(lambda local_it: local_it.batch(n))
for a in self.actor_sets
],
name=self.name + ".batch({})".format(n))
def flatten(self) -> "ParallelIterator[T[0]]":
"""Flatten batches of items into individual items.
Examples:
>>> next(from_range(10, 1).batch(4).flatten())
... 0
"""
return ParallelIterator(
[
a.with_transform(lambda local_it: local_it.flatten())
for a in self.actor_sets
],
name=self.name + ".flatten()")
def combine(self, fn: Callable[[T], List[U]]) -> "ParallelIterator[U]":
"""Transform and then combine items horizontally.
This is the equivalent of for_each(fn).flatten() (flat map).
"""
it = self.for_each(fn).flatten()
it.name = self.name + ".combine()"
return it
def gather_sync(self) -> "LocalIterator[T]":
"""Returns a local iterable for synchronous iteration.
New items will be fetched from the shards on-demand as the iterator
is stepped through.
This is the equivalent of batch_across_shards().flatten().
Examples:
>>> it = from_range(100, 1).gather_sync()
>>> next(it)
... 0
>>> next(it)
... 1
>>> next(it)
... 2
"""
it = self.batch_across_shards().flatten()
it.name = "{}.gather_sync()".format(self)
return it
def batch_across_shards(self) -> "LocalIterator[List[T]]":
"""Iterate over the results of multiple shards in parallel.
Examples:
>>> it = from_iterators([range(3), range(3)])
>>> next(it.batch_across_shards())
... [0, 0]
"""
def base_iterator(timeout=None):
active = []
for actor_set in self.actor_sets:
actor_set.init_actors()
active.extend(actor_set.actors)
futures = [a.par_iter_next.remote() for a in active]
while active:
try:
yield ray.get(futures, timeout=timeout)
futures = [a.par_iter_next.remote() for a in active]
# Always yield after each round of gets with timeout.
if timeout is not None:
yield _NextValueNotReady()
except TimeoutError:
yield _NextValueNotReady()
except StopIteration:
# Find and remove the actor that produced StopIteration.
results = []
for a, f in zip(list(active), futures):
try:
results.append(ray.get(f))
except StopIteration:
active.remove(a)
if results:
yield results
futures = [a.par_iter_next.remote() for a in active]
name = "{}.batch_across_shards()".format(self)
return LocalIterator(base_iterator, name=name)
def gather_async(self) -> "LocalIterator[T]":
"""Returns a local iterable for asynchronous iteration.
New items will be fetched from the shards asynchronously as soon as
the previous one is computed. Items arrive in non-deterministic order.
Examples:
>>> it = from_range(100, 1).gather_async()
>>> next(it)
... 3
>>> next(it)
... 0
>>> next(it)
... 1
"""
def base_iterator(timeout=None):
all_actors = []
for actor_set in self.actor_sets:
actor_set.init_actors()
all_actors.extend(actor_set.actors)
futures = {}
for a in all_actors:
futures[a.par_iter_next.remote()] = a
while futures:
pending = list(futures)
if timeout is None:
# First try to do a batch wait for efficiency.
ready, _ = ray.wait(
pending, num_returns=len(pending), timeout=0)
# Fall back to a blocking wait.
if not ready:
ready, _ = ray.wait(pending, num_returns=1)
else:
ready, _ = ray.wait(
pending, num_returns=len(pending), timeout=timeout)
for obj_id in ready:
actor = futures.pop(obj_id)
try:
yield ray.get(obj_id)
futures[actor.par_iter_next.remote()] = actor
except StopIteration:
pass
# Always yield after each round of wait with timeout.
if timeout is not None:
yield _NextValueNotReady()
name = "{}.gather_async()".format(self)
return LocalIterator(base_iterator, name=name)
def take(self, n: int) -> List[T]:
"""Return up to the first n items from this iterator."""
return self.gather_sync().take(n)
def show(self, n: int = 20):
"""Print up to the first n items from this iterator."""
return self.gather_sync().show(n)
def union(self, other: "ParallelIterator[T]") -> "ParallelIterator[T]":
"""Return an iterator that is the union of this and the other."""
if not isinstance(other, ParallelIterator):
raise ValueError(
"other must be of type ParallelIterator, got {}".format(
type(other)))
actor_sets = []
actor_sets.extend(self.actor_sets)
actor_sets.extend(other.actor_sets)
return ParallelIterator(actor_sets, "ParallelUnion[{}, {}]".format(
self, other))
def num_shards(self) -> int:
"""Return the number of worker actors backing this iterator."""
return sum(len(a.actors) for a in self.actor_sets)
def shards(self) -> List["LocalIterator[T]"]:
"""Return the list of all shards."""
return [self.get_shard(i) for i in range(self.num_shards())]
def get_shard(self, shard_index: int) -> "LocalIterator[T]":
"""Return a local iterator for the given shard.
The iterator is guaranteed to be serializable and can be passed to
remote tasks or actors.
"""
a, t = None, None
i = shard_index
for actor_set in self.actor_sets:
if i < len(actor_set.actors):
a = actor_set.actors[i]
t = actor_set.transforms
break
else:
i -= len(actor_set.actors)
if a is None:
raise ValueError("Shard index out of range", shard_index,
self.num_shards())
def base_iterator(timeout=None):
ray.get(a.par_iter_init.remote(t))
while True:
try:
yield ray.get(a.par_iter_next.remote(), timeout=timeout)
# Always yield after each round of gets with timeout.
if timeout is not None:
yield _NextValueNotReady()
except TimeoutError:
yield _NextValueNotReady()
except StopIteration:
break
name = self.name + ".shard[{}]".format(shard_index)
return LocalIterator(base_iterator, name=name)
class LocalIterator(Generic[T]):
"""An iterator over a single shard of data.
It implements similar transformations as ParallelIterator[T], but the
transforms will be applied locally and not remotely in parallel.
This class is **serializable** and can be passed to other remote
tasks and actors. However, it should be read from at most one process at
a time."""
def __init__(self,
base_iterator: Callable[[], Iterable[T]],
local_transforms: List[Callable[[Iterable], Any]] = None,
timeout: int = None,
name=None):
"""Create a local iterator (this is an internal function).
Arguments:
base_iterator (func): A function that produces the base iterator.
This is a function so that we can ensure LocalIterator is
serializable.
local_transforms (list): A list of transformation functions to be
applied on top of the base iterator. When iteration begins, we
create the base iterator and apply these functions. This lazy
creation ensures LocalIterator is serializable until you start
iterating over it.
timeout (int): Optional timeout in seconds for this iterator, after
which _NextValueNotReady will be returned. This avoids
blocking.
name (str): Optional name for this iterator.
"""
self.base_iterator = base_iterator
self.built_iterator = None
self.local_transforms = local_transforms or []
self.timeout = timeout
self.name = name or "unknown"
def _build_once(self):
if self.built_iterator is None:
it = iter(self.base_iterator(self.timeout))
for fn in self.local_transforms:
it = fn(it)
self.built_iterator = it
def __iter__(self):
self._build_once()
return self.built_iterator
def __next__(self):
self._build_once()
return next(self.built_iterator)
def __str__(self):
return repr(self)
def __repr__(self):
return "LocalIterator[{}]".format(self.name)
def for_each(self, fn: Callable[[T], U]) -> "LocalIterator[U]":
def apply_foreach(it):
for item in it:
if isinstance(item, _NextValueNotReady):
yield item
else:
yield fn(item)
return LocalIterator(
self.base_iterator,
self.local_transforms + [apply_foreach],
name=self.name + ".for_each()")
def filter(self, fn: Callable[[T], bool]) -> "LocalIterator[T]":
def apply_filter(it):
for item in it:
if isinstance(item, _NextValueNotReady) or fn(item):
yield item
return LocalIterator(
self.base_iterator,
self.local_transforms + [apply_filter],
name=self.name + ".filter()")
def batch(self, n: int) -> "LocalIterator[List[T]]":
def apply_batch(it):
batch = []
for item in it:
if isinstance(item, _NextValueNotReady):
yield item
else:
batch.append(item)
if len(batch) >= n:
yield batch
batch = []
if batch:
yield batch
return LocalIterator(
self.base_iterator,
self.local_transforms + [apply_batch],
name=self.name + ".batch({})".format(n))
def flatten(self) -> "LocalIterator[T[0]]":
def apply_flatten(it):
for item in it:
if isinstance(item, _NextValueNotReady):
yield item
else:
for subitem in item:
yield subitem
return LocalIterator(
self.base_iterator,
self.local_transforms + [apply_flatten],
name=self.name + ".flatten()")
def combine(self, fn: Callable[[T], List[U]]) -> "LocalIterator[U]":
it = self.for_each(fn).flatten()
it.name = self.name + ".combine()"
return it
def take(self, n: int) -> List[T]:
"""Return up to the first n items from this iterator."""
out = []
for item in self:
out.append(item)
if len(out) >= n:
break
return out
def show(self, n: int = 20):
"""Print up to the first n items from this iterator."""
i = 0
for item in self:
print(item)
i += 1
if i >= n:
break
def union(self, other: "LocalIterator[T]") -> "LocalIterator[T]":
"""Return an iterator that is the union of this and the other.
There are no ordering guarantees between the two iterators. We make a
best-effort attempt to return items from both as they become ready,
preventing starvation of any particular iterator.
"""
if not isinstance(other, LocalIterator):
raise ValueError(
"other must be of type LocalIterator, got {}".format(
type(other)))
it1 = LocalIterator(
self.base_iterator, self.local_transforms, timeout=0)
it2 = LocalIterator(
other.base_iterator, other.local_transforms, timeout=0)
active = [it1, it2]
def build_union(timeout=None):
while True:
for it in list(active):
# Yield items from the iterator until _NextValueNotReady is
# found, then switch to the next iterator.
try:
while True:
item = next(it)
if isinstance(item, _NextValueNotReady):
break
else:
yield item
except StopIteration:
active.remove(it)
if not active:
break
return LocalIterator(
build_union, [], name="LocalUnion[{}, {}]".format(self, other))
class ParallelIteratorWorker(object):
"""Worker actor for a ParallelIterator.
Actors that are passed to iter.from_actors() must subclass this interface.
"""
def __init__(self, item_generator: Any, repeat: bool):
"""Create an iterator worker.
Subclasses must call this init function.
Arguments:
item_generator (obj): A Python generator objects or lambda function
that produces a generator when called. We allow lambda
functions since the generator itself might not be serializable,
but a lambda that returns it can be.
repeat (bool): Whether to loop over the iterator forever.
"""
def make_iterator():
if callable(item_generator):
return item_generator()
else:
return item_generator
if repeat:
def cycle():
while True:
it = make_iterator()
for item in it:
yield item
self.item_generator = cycle()
else:
self.item_generator = make_iterator()
self.transforms = []
self.local_it = None
def par_iter_init(self, transforms):
"""Implements ParallelIterator worker init."""
it = LocalIterator(lambda timeout: self.item_generator)
for fn in transforms:
it = fn(it)
assert it is not None, fn
self.local_it = iter(it)
def par_iter_next(self):
"""Implements ParallelIterator worker item fetch."""
assert self.local_it is not None, "must call par_iter_init()"
return next(self.local_it)
class _NextValueNotReady(Exception):
"""Indicates that a local iterator has no value currently available.
This is used internally to implement the union() of multiple blocking
local generators."""
pass
class _ActorSet(object):
"""Helper class that represents a set of actors and transforms."""
def __init__(
self, actors: List["ray.actor.ActorHandle"],
transforms: List[Callable[["LocalIterator"], "LocalIterator"]]):
self.actors = actors
self.transforms = transforms
def init_actors(self):
ray.get([a.par_iter_init.remote(self.transforms) for a in self.actors])
def with_transform(self, fn):
return _ActorSet(self.actors, self.transforms + [fn])
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/multiprocessing/__init__.py
|
Python
|
from multiprocessing import TimeoutError
from .pool import Pool
__all__ = ["Pool", "TimeoutError"]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/multiprocessing/pool.py
|
Python
|
import logging
from multiprocessing import TimeoutError
import os
import time
import random
import collections
import threading
import queue
import copy
import ray
logger = logging.getLogger(__name__)
RAY_ADDRESS_ENV = "RAY_ADDRESS"
# Helper function to divide a by b and round the result up.
def div_round_up(a, b):
return -(-a // b)
class PoolTaskError(Exception):
def __init__(self, underlying):
self.underlying = underlying
class ResultThread(threading.Thread):
def __init__(self,
object_ids,
callback=None,
error_callback=None,
total_object_ids=None):
threading.Thread.__init__(self)
self._got_error = False
self._object_ids = []
self._num_ready = 0
self._results = []
self._ready_index_queue = queue.Queue()
self._callback = callback
self._error_callback = error_callback
self._total_object_ids = total_object_ids or len(object_ids)
self._indices = {}
# Thread-safe queue used to add ObjectIDs to fetch after creating
# this thread (used to lazily submit for imap and imap_unordered).
self._new_object_ids = queue.Queue()
for object_id in object_ids:
self._add_object_id(object_id)
def _add_object_id(self, object_id):
self._indices[object_id] = len(self._object_ids)
self._object_ids.append(object_id)
self._results.append(None)
def add_object_id(self, object_id):
self._new_object_ids.put(object_id)
def run(self):
unready = copy.copy(self._object_ids)
while self._num_ready < self._total_object_ids:
# Get as many new IDs from the queue as possible without blocking,
# unless we have no IDs to wait on, in which case we block.
while True:
try:
block = len(unready) == 0
new_object_id = self._new_object_ids.get(block=block)
self._add_object_id(new_object_id)
unready.append(new_object_id)
except queue.Empty:
# queue.Empty means no result was retrieved if block=False.
break
[ready_id], unready = ray.wait(unready, num_returns=1)
batch = ray.get(ready_id)
for result in batch:
if isinstance(result, Exception):
self._got_error = True
if self._error_callback is not None:
self._error_callback(result)
elif self._callback is not None:
self._callback(result)
self._num_ready += 1
self._results[self._indices[ready_id]] = batch
self._ready_index_queue.put(self._indices[ready_id])
def got_error(self):
# Should only be called after the thread finishes.
return self._got_error
def result(self, index):
# Should only be called on results that are ready.
return self._results[index]
def results(self):
# Should only be called after the thread finishes.
return self._results
def next_ready_index(self, timeout=None):
try:
return self._ready_index_queue.get(timeout=timeout)
except queue.Empty:
# queue.Queue signals a timeout by raising queue.Empty.
raise TimeoutError
class AsyncResult:
"""An asynchronous interface to task results.
This should not be constructed directly.
"""
def __init__(self,
chunk_object_ids,
callback=None,
error_callback=None,
single_result=False):
self._single_result = single_result
self._result_thread = ResultThread(chunk_object_ids, callback,
error_callback)
self._result_thread.start()
def wait(self, timeout=None):
"""
Returns once the result is ready or the timeout expires (does not
raise TimeoutError).
Args:
timeout: timeout in milliseconds.
"""
self._result_thread.join(timeout)
def get(self, timeout=None):
self.wait(timeout)
if self._result_thread.is_alive():
raise TimeoutError
results = []
for batch in self._result_thread.results():
for result in batch:
if isinstance(result, PoolTaskError):
raise result.underlying
results.extend(batch)
if self._single_result:
return results[0]
return results
def ready(self):
"""
Returns true if the result is ready, else false if the tasks are still
running.
"""
return not self._result_thread.is_alive()
def successful(self):
"""
Returns true if none of the submitted tasks errored, else false. Should
only be called once the result is ready (can be checked using `ready`).
"""
if not self.ready():
raise ValueError("{0!r} not ready".format(self))
return not self._result_thread.got_error()
class IMapIterator:
"""Base class for OrderedIMapIterator and UnorderedIMapIterator."""
def __init__(self, pool, func, iterable, chunksize=None):
self._pool = pool
self._func = func
self._next_chunk_index = 0
# List of bools indicating if the given chunk is ready or not for all
# submitted chunks. Ordering mirrors that in the in the ResultThread.
self._submitted_chunks = []
self._ready_objects = collections.deque()
if not hasattr(iterable, "__len__"):
iterable = [iterable]
self._iterator = iter(iterable)
self._chunksize = chunksize or pool._calculate_chunksize(iterable)
self._total_chunks = div_round_up(len(iterable), chunksize)
self._result_thread = ResultThread(
[], total_object_ids=self._total_chunks)
self._result_thread.start()
for _ in range(len(self._pool._actor_pool)):
self._submit_next_chunk()
def _submit_next_chunk(self):
# The full iterable has been submitted, so no-op.
if len(self._submitted_chunks) >= self._total_chunks:
return
actor_index = len(self._submitted_chunks) % len(self._pool._actor_pool)
new_chunk_id = self._pool._submit_chunk(self._func, self._iterator,
self._chunksize, actor_index)
self._submitted_chunks.append(False)
self._result_thread.add_object_id(new_chunk_id)
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
# Should be implemented by subclasses.
raise NotImplementedError
class OrderedIMapIterator(IMapIterator):
"""Iterator to the results of tasks submitted using `imap`.
The results are returned in the same order that they were submitted, even
if they don't finish in that order. Only one batch of tasks per actor
process is submitted at a time - the rest are submitted as results come in.
Should not be constructed directly.
"""
def next(self, timeout=None):
if len(self._ready_objects) == 0:
if self._next_chunk_index == self._total_chunks:
raise StopIteration
while timeout is None or timeout > 0:
start = time.time()
index = self._result_thread.next_ready_index(timeout=timeout)
self._submit_next_chunk()
self._submitted_chunks[index] = True
if index == self._next_chunk_index:
break
if timeout is not None:
timeout = max(0, timeout - (time.time() - start))
while self._next_chunk_index < len(
self._submitted_chunks
) and self._submitted_chunks[self._next_chunk_index]:
for result in self._result_thread.result(
self._next_chunk_index):
self._ready_objects.append(result)
self._next_chunk_index += 1
return self._ready_objects.popleft()
class UnorderedIMapIterator(IMapIterator):
"""Iterator to the results of tasks submitted using `imap`.
The results are returned in the order that they finish. Only one batch of
tasks per actor process is submitted at a time - the rest are submitted as
results come in.
Should not be constructed directly.
"""
def next(self, timeout=None):
if len(self._ready_objects) == 0:
if self._next_chunk_index == self._total_chunks:
raise StopIteration
index = self._result_thread.next_ready_index(timeout=timeout)
self._submit_next_chunk()
for result in self._result_thread.result(index):
self._ready_objects.append(result)
self._next_chunk_index += 1
return self._ready_objects.popleft()
@ray.remote(num_cpus=1)
class PoolActor:
"""Actor used to process tasks submitted to a Pool."""
def __init__(self, initializer=None, initargs=None):
if initializer:
initargs = initargs or ()
initializer(*initargs)
def ping(self):
# Used to wait for this actor to be initialized.
pass
def run_batch(self, func, batch):
results = []
for args, kwargs in batch:
args = args or ()
kwargs = kwargs or {}
try:
results.append(func(*args, **kwargs))
except Exception as e:
results.append(PoolTaskError(e))
return results
# https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool
class Pool:
"""A pool of actor processes that is used to process tasks in parallel.
Args:
processes: number of actor processes to start in the pool. Defaults to
the number of cores in the Ray cluster if one is already running,
otherwise the number of cores on this machine.
initializer: function to be run in each actor when it starts up.
initargs: iterable of arguments to the initializer function.
maxtasksperchild: maximum number of tasks to run in each actor process.
After a process has executed this many tasks, it will be killed and
replaced with a new one.
ray_address: address of the Ray cluster to run on. If None, a new local
Ray cluster will be started on this machine. Otherwise, this will
be passed to `ray.init()` to connect to a running cluster. This may
also be specified using the `RAY_ADDRESS` environment variable.
"""
def __init__(self,
processes=None,
initializer=None,
initargs=None,
maxtasksperchild=None,
context=None,
ray_address=None):
self._closed = False
self._initializer = initializer
self._initargs = initargs
self._maxtasksperchild = maxtasksperchild or -1
self._actor_deletion_ids = []
if context:
logger.warning("The 'context' argument is not supported using "
"ray. Please refer to the documentation for how "
"to control ray initialization.")
processes = self._init_ray(processes, ray_address)
self._start_actor_pool(processes)
def _init_ray(self, processes=None, ray_address=None):
# Initialize ray. If ray is already initialized, we do nothing.
# Else, the priority is:
# ray_address argument > RAY_ADDRESS > start new local cluster.
if not ray.is_initialized():
if ray_address is None and RAY_ADDRESS_ENV in os.environ:
ray_address = os.environ[RAY_ADDRESS_ENV]
# Cluster mode.
if ray_address is not None:
logger.info("Connecting to ray cluster at address='{}'".format(
ray_address))
ray.init(address=ray_address)
# Local mode.
else:
logger.info("Starting local ray cluster")
ray.init(num_cpus=processes)
ray_cpus = int(ray.state.cluster_resources()["CPU"])
if processes is None:
processes = ray_cpus
if processes <= 0:
raise ValueError("Processes in the pool must be >0.")
if ray_cpus < processes:
raise ValueError("Tried to start a pool with {} processes on an "
"existing ray cluster, but there are only {} "
"CPUs in the ray cluster.".format(
processes, ray_cpus))
return processes
def _start_actor_pool(self, processes):
self._actor_pool = [self._new_actor_entry() for _ in range(processes)]
ray.get([actor.ping.remote() for actor, _ in self._actor_pool])
def _wait_for_stopping_actors(self, timeout=None):
if len(self._actor_deletion_ids) == 0:
return
if timeout is not None:
timeout = float(timeout)
_, deleting = ray.wait(
self._actor_deletion_ids,
num_returns=len(self._actor_deletion_ids),
timeout=timeout)
self._actor_deletion_ids = deleting
def _stop_actor(self, actor):
# Check and clean up any outstanding IDs corresponding to deletions.
self._wait_for_stopping_actors(timeout=0.0)
# The deletion task will block until the actor has finished executing
# all pending tasks.
self._actor_deletion_ids.append(actor.__ray_terminate__.remote())
def _new_actor_entry(self):
# NOTE(edoakes): The initializer function can't currently be used to
# modify the global namespace (e.g., import packages or set globals)
# due to a limitation in cloudpickle.
return (PoolActor.remote(self._initializer, self._initargs), 0)
def _random_actor_index(self):
return random.randrange(len(self._actor_pool))
# Batch should be a list of tuples: (args, kwargs).
def _run_batch(self, actor_index, func, batch):
actor, count = self._actor_pool[actor_index]
object_id = actor.run_batch.remote(func, batch)
count += 1
assert self._maxtasksperchild == -1 or count <= self._maxtasksperchild
if count == self._maxtasksperchild:
self._stop_actor(actor)
actor, count = self._new_actor_entry()
self._actor_pool[actor_index] = (actor, count)
return object_id
def apply(self, func, args=None, kwargs=None):
"""Run the given function on a random actor process and return the
result synchronously.
Args:
func: function to run.
args: optional arguments to the function.
kwargs: optional keyword arguments to the function.
Returns:
The result.
"""
return self.apply_async(func, args, kwargs).get()
def apply_async(self,
func,
args=None,
kwargs=None,
callback=None,
error_callback=None):
"""Run the given function on a random actor process and return an
asynchronous interface to the result.
Args:
func: function to run.
args: optional arguments to the function.
kwargs: optional keyword arguments to the function.
callback: callback to be executed on the result once it is finished
if it succeeds.
error_callback: callback to be executed the result once it is
finished if the task errors. The exception raised by the
task will be passed as the only argument to the callback.
Returns:
AsyncResult containing the result.
"""
self._check_running()
object_id = self._run_batch(self._random_actor_index(), func,
[(args, kwargs)])
return AsyncResult(
[object_id], callback, error_callback, single_result=True)
def _calculate_chunksize(self, iterable):
chunksize, extra = divmod(len(iterable), len(self._actor_pool) * 4)
if extra:
chunksize += 1
return chunksize
def _submit_chunk(self,
func,
iterator,
chunksize,
actor_index,
unpack_args=False):
chunk = []
while len(chunk) < chunksize:
try:
args = next(iterator)
if not unpack_args:
args = (args, )
chunk.append((args, {}))
except StopIteration:
break
# Nothing to submit. The caller should prevent this.
assert len(chunk) > 0
return self._run_batch(actor_index, func, chunk)
def _chunk_and_run(self, func, iterable, chunksize=None,
unpack_args=False):
if not hasattr(iterable, "__len__"):
iterable = [iterable]
if chunksize is None:
chunksize = self._calculate_chunksize(iterable)
iterator = iter(iterable)
chunk_object_ids = []
while len(chunk_object_ids) * chunksize < len(iterable):
actor_index = len(chunk_object_ids) % len(self._actor_pool)
chunk_object_ids.append(
self._submit_chunk(
func,
iterator,
chunksize,
actor_index,
unpack_args=unpack_args))
return chunk_object_ids
def _map_async(self,
func,
iterable,
chunksize=None,
unpack_args=False,
callback=None,
error_callback=None):
self._check_running()
object_ids = self._chunk_and_run(
func, iterable, chunksize=chunksize, unpack_args=unpack_args)
return AsyncResult(object_ids, callback, error_callback)
def map(self, func, iterable, chunksize=None):
"""Run the given function on each element in the iterable round-robin
on the actor processes and return the results synchronously.
Args:
func: function to run.
iterable: iterable of objects to be passed as the sole argument to
func.
chunksize: number of tasks to submit as a batch to each actor
process. If unspecified, a suitable chunksize will be chosen.
Returns:
A list of results.
"""
return self._map_async(
func, iterable, chunksize=chunksize, unpack_args=False).get()
def map_async(self,
func,
iterable,
chunksize=None,
callback=None,
error_callback=None):
"""Run the given function on each element in the iterable round-robin
on the actor processes and return an asynchronous interface to the
results.
Args:
func: function to run.
iterable: iterable of objects to be passed as the only argument to
func.
chunksize: number of tasks to submit as a batch to each actor
process. If unspecified, a suitable chunksize will be chosen.
callback: callback to be executed on each successful result once it
is finished.
error_callback: callback to be executed on each errored result once
it is finished. The exception raised by the task will be passed
as the only argument to the callback.
Returns:
AsyncResult
"""
return self._map_async(
func,
iterable,
chunksize=chunksize,
unpack_args=False,
callback=callback,
error_callback=error_callback)
def starmap(self, func, iterable, chunksize=None):
"""Same as `map`, but unpacks each element of the iterable as the
arguments to func like: [func(*args) for args in iterable].
"""
return self._map_async(
func, iterable, chunksize=chunksize, unpack_args=True).get()
def starmap_async(self, func, iterable, callback=None,
error_callback=None):
"""Same as `map_async`, but unpacks each element of the iterable as the
arguments to func like: [func(*args) for args in iterable].
"""
return self._map_async(
func,
iterable,
unpack_args=True,
callback=callback,
error_callback=error_callback)
def imap(self, func, iterable, chunksize=1):
"""Same as `map`, but only submits one batch of tasks to each actor
process at a time.
This can be useful if the iterable of arguments is very large or each
task's arguments consumes a large amount of resources.
The results are returned in the order corresponding to their arguments
in the iterable.
Returns:
OrderedIMapIterator
"""
self._check_running()
return OrderedIMapIterator(self, func, iterable, chunksize=chunksize)
def imap_unordered(self, func, iterable, chunksize=1):
"""Same as `map`, but only submits one batch of tasks to each actor
process at a time.
This can be useful if the iterable of arguments is very large or each
task's arguments consumes a large amount of resources.
The results are returned in the order that they finish.
Returns:
UnorderedIMapIterator
"""
self._check_running()
return UnorderedIMapIterator(self, func, iterable, chunksize=chunksize)
def _check_running(self):
if self._closed:
raise ValueError("Pool not running")
def __enter__(self):
self._check_running()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.terminate()
def close(self):
"""Close the pool.
Prevents any more tasks from being submitted on the pool but allows
outstanding work to finish.
"""
for actor, _ in self._actor_pool:
self._stop_actor(actor)
self._closed = True
def terminate(self):
"""Close the pool.
Prevents any more tasks from being submitted on the pool and stops
outstanding work.
"""
if not self._closed:
self.close()
for actor, _ in self._actor_pool:
actor.__ray_kill__()
def join(self):
"""Wait for the actors in a closed pool to exit.
If the pool was closed using `close`, this will return once all
outstanding work is completed.
If the pool was closed using `terminate`, this will return quickly.
"""
if not self._closed:
raise ValueError("Pool is still running")
self._wait_for_stopping_actors()
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/named_actors.py
|
Python
|
import ray
import ray.cloudpickle as pickle
from ray.experimental.internal_kv import _internal_kv_get, _internal_kv_put
def _calculate_key(name):
"""Generate a Redis key with the given name.
Args:
name: The name of the named actor.
Returns:
The key to use for storing a named actor in Redis.
"""
return b"Actor:" + name.encode("ascii")
def get_actor(name):
"""Get a named actor which was previously created.
If the actor doesn't exist, an exception will be raised.
Args:
name: The name of the named actor.
Returns:
The ActorHandle object corresponding to the name.
"""
actor_name = _calculate_key(name)
pickled_state = _internal_kv_get(actor_name)
if pickled_state is None:
raise ValueError("The actor with name={} doesn't exist".format(name))
handle = pickle.loads(pickled_state)
return handle
def register_actor(name, actor_handle):
"""Register a named actor under a string key.
Args:
name: The name of the named actor.
actor_handle: The actor object to be associated with this name
"""
if not isinstance(name, str):
raise TypeError("The name argument must be a string.")
if not isinstance(actor_handle, ray.actor.ActorHandle):
raise TypeError("The actor_handle argument must be an ActorHandle "
"object.")
actor_name = _calculate_key(name)
# First check if the actor already exists.
try:
get_actor(name)
exists = True
except ValueError:
exists = False
if exists:
raise ValueError("An actor with name={} already exists".format(name))
# Add the actor to Redis if it does not already exist.
_internal_kv_put(actor_name, pickle.dumps(actor_handle))
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/no_return.py
|
Python
|
class NoReturn:
"""Do not store the return value in the object store.
If a task returns this object, then Ray will not store this object in the
object store. Calling `ray.get` on the task's return ObjectIDs may block
indefinitely unless the task manually stores an object for the
corresponding ObjectID.
"""
def __init__(self):
raise TypeError("The `NoReturn` object should not be instantiated")
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/queue.py
|
Python
|
from collections import deque
import time
import ray
class Empty(Exception):
pass
class Full(Exception):
pass
class Queue:
"""Queue implementation on Ray.
Args:
maxsize (int): maximum size of the queue. If zero, size is unboundend.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self.actor = _QueueActor.remote(maxsize)
def __len__(self):
return self.size()
def size(self):
"""The size of the queue."""
return ray.get(self.actor.qsize.remote())
def qsize(self):
"""The size of the queue."""
return self.size()
def empty(self):
"""Whether the queue is empty."""
return ray.get(self.actor.qsize.remote())
def full(self):
"""Whether the queue is full."""
return ray.get(self.actor.full.remote())
def put(self, item, block=True, timeout=None):
"""Adds an item to the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple producers put to the same full queue.
Raises:
Full if the queue is full and blocking is False.
"""
if self.maxsize <= 0:
self.actor.put.remote(item)
elif not block:
if not ray.get(self.actor.put.remote(item)):
raise Full
elif timeout is None:
# Polling
# Use a not_full condition variable or promise?
while not ray.get(self.actor.put.remote(item)):
# Consider adding time.sleep here
pass
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time.time() + timeout
# Polling
# Use a condition variable or switch to promise?
success = False
while not success and time.time() < endtime:
success = ray.get(self.actor.put.remote(item))
if not success:
raise Full
def get(self, block=True, timeout=None):
"""Gets an item from the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple consumers get from the same empty queue.
Returns:
The next item in the queue.
Raises:
Empty if the queue is empty and blocking is False.
"""
if not block:
success, item = ray.get(self.actor.get.remote())
if not success:
raise Empty
elif timeout is None:
# Polling
# Use a not_empty condition variable or return a promise?
success, item = ray.get(self.actor.get.remote())
while not success:
# Consider adding time.sleep here
success, item = ray.get(self.actor.get.remote())
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time.time() + timeout
# Polling
# Use a not_full condition variable or return a promise?
success = False
while not success and time.time() < endtime:
success, item = ray.get(self.actor.get.remote())
if not success:
raise Empty
return item
def put_nowait(self, item):
"""Equivalent to put(item, block=False).
Raises:
Full if the queue is full.
"""
return self.put(item, block=False)
def get_nowait(self):
"""Equivalent to get(item, block=False).
Raises:
Empty if the queue is empty.
"""
return self.get(block=False)
@ray.remote
class _QueueActor:
def __init__(self, maxsize):
self.maxsize = maxsize
self._init(maxsize)
def qsize(self):
return self._qsize()
def empty(self):
return not self._qsize()
def full(self):
return 0 < self.maxsize <= self._qsize()
def put(self, item):
if self.maxsize > 0 and self._qsize() >= self.maxsize:
return False
self._put(item)
return True
def get(self):
if not self._qsize():
return False, None
return True, self._get()
# Override these for different queue implementations
def _init(self, maxsize):
self.queue = deque()
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.popleft()
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/__init__.py
|
Python
|
from ray.experimental.serve.backend_config import BackendConfig
from ray.experimental.serve.policy import RoutePolicy
from ray.experimental.serve.api import (
init, create_backend, create_endpoint, link, split, get_handle, stat,
set_backend_config, get_backend_config, accept_batch) # noqa: E402
__all__ = [
"init", "create_backend", "create_endpoint", "link", "split", "get_handle",
"stat", "set_backend_config", "get_backend_config", "BackendConfig",
"RoutePolicy", "accept_batch"
]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/api.py
|
Python
|
import inspect
from functools import wraps
from tempfile import mkstemp
import numpy as np
import ray
from ray.experimental.serve.constants import (
DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT, SERVE_NURSERY_NAME)
from ray.experimental.serve.global_state import (GlobalState,
start_initial_state)
from ray.experimental.serve.kv_store_service import SQLiteKVStore
from ray.experimental.serve.task_runner import RayServeMixin, TaskRunnerActor
from ray.experimental.serve.utils import (block_until_http_ready,
get_random_letters)
from ray.experimental.serve.exceptions import RayServeException
from ray.experimental.serve.backend_config import BackendConfig
from ray.experimental.serve.policy import RoutePolicy
global_state = None
def _get_global_state():
"""Used for internal purpose. Because just import serve.global_state
will always reference the original None object
"""
return global_state
def _ensure_connected(f):
@wraps(f)
def check(*args, **kwargs):
if _get_global_state() is None:
raise RayServeException("Please run serve.init to initialize or "
"connect to existing ray serve cluster.")
return f(*args, **kwargs)
return check
def accept_batch(f):
"""Annotation to mark a serving function that batch is accepted.
This annotation need to be used to mark a function expect all arguments
to be passed into a list.
Example:
>>> @serve.accept_batch
def serving_func(flask_request):
assert isinstance(flask_request, list)
...
>>> class ServingActor:
@serve.accept_batch
def __call__(self, *, python_arg=None):
assert isinstance(python_arg, list)
"""
f.serve_accept_batch = True
return f
def init(kv_store_connector=None,
kv_store_path=None,
blocking=False,
http_host=DEFAULT_HTTP_HOST,
http_port=DEFAULT_HTTP_PORT,
ray_init_kwargs={"object_store_memory": int(1e8)},
gc_window_seconds=3600,
queueing_policy=RoutePolicy.Random,
policy_kwargs={}):
"""Initialize a serve cluster.
If serve cluster has already initialized, this function will just return.
Calling `ray.init` before `serve.init` is optional. When there is not a ray
cluster initialized, serve will call `ray.init` with `object_store_memory`
requirement.
Args:
kv_store_connector (callable): Function of (namespace) => TableObject.
We will use a SQLite connector that stores to /tmp by default.
kv_store_path (str, path): Path to the SQLite table.
blocking (bool): If true, the function will wait for the HTTP server to
be healthy, and other components to be ready before returns.
http_host (str): Host for HTTP server. Default to "0.0.0.0".
http_port (int): Port for HTTP server. Default to 8000.
ray_init_kwargs (dict): Argument passed to ray.init, if there is no ray
connection. Default to {"object_store_memory": int(1e8)} for
performance stability reason
gc_window_seconds(int): How long will we keep the metric data in
memory. Data older than the gc_window will be deleted. The default
is 3600 seconds, which is 1 hour.
queueing_policy(RoutePolicy): Define the queueing policy for selecting
the backend for a service. (Default: RoutePolicy.Random)
policy_kwargs: Arguments required to instantiate a queueing policy
"""
global global_state
# Noop if global_state is no longer None
if global_state is not None:
return
# Initialize ray if needed.
if not ray.is_initialized():
ray.init(**ray_init_kwargs)
# Try to get serve nursery if there exists
try:
ray.experimental.get_actor(SERVE_NURSERY_NAME)
global_state = GlobalState()
return
except ValueError:
pass
if kv_store_path is None:
_, kv_store_path = mkstemp()
# Serve has not been initialized, perform init sequence
# Todo, move the db to session_dir
# ray.worker._global_node.address_info["session_dir"]
def kv_store_connector(namespace):
return SQLiteKVStore(namespace, db_path=kv_store_path)
nursery = start_initial_state(kv_store_connector)
global_state = GlobalState(nursery)
global_state.init_or_get_http_server(host=http_host, port=http_port)
global_state.init_or_get_router(
queueing_policy=queueing_policy, policy_kwargs=policy_kwargs)
global_state.init_or_get_metric_monitor(
gc_window_seconds=gc_window_seconds)
if blocking:
block_until_http_ready("http://{}:{}".format(http_host, http_port))
@_ensure_connected
def create_endpoint(endpoint_name, route, blocking=True):
"""Create a service endpoint given route_expression.
Args:
endpoint_name (str): A name to associate to the endpoint. It will be
used as key to set traffic policy.
route (str): A string begin with "/". HTTP server will use
the string to match the path.
blocking (bool): If true, the function will wait for service to be
registered before returning
"""
global_state.route_table.register_service(route, endpoint_name)
@_ensure_connected
def set_backend_config(backend_tag, backend_config):
"""Set a backend configuration for a backend tag
Args:
backend_tag(str): A registered backend.
backend_config(BackendConfig) : Desired backend configuration.
"""
assert backend_tag in global_state.backend_table.list_backends(), (
"Backend {} is not registered.".format(backend_tag))
assert isinstance(backend_config,
BackendConfig), ("backend_config must be"
" of instance BackendConfig")
backend_config_dict = dict(backend_config)
old_backend_config_dict = global_state.backend_table.get_info(backend_tag)
global_state.backend_table.register_info(backend_tag, backend_config_dict)
# inform the router about change in configuration
# particularly for setting max_batch_size
ray.get(global_state.init_or_get_router().set_backend_config.remote(
backend_tag, backend_config_dict))
# checking if replicas need to be restarted
# Replicas are restarted if there is any change in the backend config
# related to restart_configs
# TODO(alind) : have replica restarting policies selected by the user
need_to_restart_replicas = any(
old_backend_config_dict[k] != backend_config_dict[k]
for k in BackendConfig.restart_on_change_fields)
if need_to_restart_replicas:
# kill all the replicas for restarting with new configurations
scale(backend_tag, 0)
# scale the replicas with new configuration
scale(backend_tag, backend_config_dict["num_replicas"])
@_ensure_connected
def get_backend_config(backend_tag):
"""get the backend configuration for a backend tag
Args:
backend_tag(str): A registered backend.
"""
assert backend_tag in global_state.backend_table.list_backends(), (
"Backend {} is not registered.".format(backend_tag))
backend_config_dict = global_state.backend_table.get_info(backend_tag)
return BackendConfig(**backend_config_dict)
@_ensure_connected
def create_backend(func_or_class,
backend_tag,
*actor_init_args,
backend_config=BackendConfig()):
"""Create a backend using func_or_class and assign backend_tag.
Args:
func_or_class (callable, class): a function or a class implements
__call__ protocol.
backend_tag (str): a unique tag assign to this backend. It will be used
to associate services in traffic policy.
backend_config (BackendConfig): An object defining backend properties
for starting a backend.
*actor_init_args (optional): the argument to pass to the class
initialization method.
"""
assert isinstance(backend_config,
BackendConfig), ("backend_config must be"
" of instance BackendConfig")
backend_config_dict = dict(backend_config)
should_accept_batch = (True if backend_config.max_batch_size is not None
else False)
batch_annotation_not_found = RayServeException(
"max_batch_size is set in config but the function or method does not "
"accept batching. Please use @serve.accept_batch to explicitly mark "
"the function or method as batchable and takes in list as arguments.")
arg_list = []
if inspect.isfunction(func_or_class):
if should_accept_batch and not hasattr(func_or_class,
"serve_accept_batch"):
raise batch_annotation_not_found
# arg list for a fn is function itself
arg_list = [func_or_class]
# ignore lint on lambda expression
creator = lambda kwrgs: TaskRunnerActor._remote(**kwrgs) # noqa: E731
elif inspect.isclass(func_or_class):
if should_accept_batch and not hasattr(func_or_class.__call__,
"serve_accept_batch"):
raise batch_annotation_not_found
# Python inheritance order is right-to-left. We put RayServeMixin
# on the left to make sure its methods are not overriden.
@ray.remote
class CustomActor(RayServeMixin, func_or_class):
pass
arg_list = actor_init_args
# ignore lint on lambda expression
creator = lambda kwargs: CustomActor._remote(**kwargs) # noqa: E731
else:
raise TypeError(
"Backend must be a function or class, it is {}.".format(
type(func_or_class)))
# save creator which starts replicas
global_state.backend_table.register_backend(backend_tag, creator)
# save information about configurations needed to start the replicas
global_state.backend_table.register_info(backend_tag, backend_config_dict)
# save the initial arguments needed by replicas
global_state.backend_table.save_init_args(backend_tag, arg_list)
# set the backend config inside the router
# particularly for max-batch-size
ray.get(global_state.init_or_get_router().set_backend_config.remote(
backend_tag, backend_config_dict))
scale(backend_tag, backend_config_dict["num_replicas"])
def _start_replica(backend_tag):
assert backend_tag in global_state.backend_table.list_backends(), (
"Backend {} is not registered.".format(backend_tag))
replica_tag = "{}#{}".format(backend_tag, get_random_letters(length=6))
# get the info which starts the replicas
creator = global_state.backend_table.get_backend_creator(backend_tag)
backend_config_dict = global_state.backend_table.get_info(backend_tag)
backend_config = BackendConfig(**backend_config_dict)
init_args = global_state.backend_table.get_init_args(backend_tag)
# get actor creation kwargs
actor_kwargs = backend_config.get_actor_creation_args(init_args)
# Create the runner in the nursery
[runner_handle] = ray.get(
global_state.actor_nursery_handle.start_actor_with_creator.remote(
creator, actor_kwargs, replica_tag))
# Setup the worker
ray.get(
runner_handle._ray_serve_setup.remote(
backend_tag, global_state.init_or_get_router(), runner_handle))
runner_handle._ray_serve_fetch.remote()
# Register the worker in config tables as well as metric monitor
global_state.backend_table.add_replica(backend_tag, replica_tag)
global_state.init_or_get_metric_monitor().add_target.remote(runner_handle)
def _remove_replica(backend_tag):
assert backend_tag in global_state.backend_table.list_backends(), (
"Backend {} is not registered.".format(backend_tag))
assert len(global_state.backend_table.list_replicas(backend_tag)) > 0, (
"Backend {} does not have enough replicas to be removed.".format(
backend_tag))
replica_tag = global_state.backend_table.remove_replica(backend_tag)
[replica_handle] = ray.get(
global_state.actor_nursery_handle.get_handle.remote(replica_tag))
# Remove the replica from metric monitor.
ray.get(global_state.init_or_get_metric_monitor().remove_target.remote(
replica_handle))
# Remove the replica from actor nursery.
ray.get(
global_state.actor_nursery_handle.remove_handle.remote(replica_tag))
# Remove the replica from router.
# This will also destory the actor handle.
ray.get(global_state.init_or_get_router()
.remove_and_destory_replica.remote(backend_tag, replica_handle))
@_ensure_connected
def scale(backend_tag, num_replicas):
"""Set the number of replicas for backend_tag.
Args:
backend_tag (str): A registered backend.
num_replicas (int): Desired number of replicas
"""
assert backend_tag in global_state.backend_table.list_backends(), (
"Backend {} is not registered.".format(backend_tag))
assert num_replicas >= 0, ("Number of replicas must be"
" greater than or equal to 0.")
replicas = global_state.backend_table.list_replicas(backend_tag)
current_num_replicas = len(replicas)
delta_num_replicas = num_replicas - current_num_replicas
if delta_num_replicas > 0:
for _ in range(delta_num_replicas):
_start_replica(backend_tag)
elif delta_num_replicas < 0:
for _ in range(-delta_num_replicas):
_remove_replica(backend_tag)
@_ensure_connected
def link(endpoint_name, backend_tag):
"""Associate a service endpoint with backend tag.
Example:
>>> serve.link("service-name", "backend:v1")
Note:
This is equivalent to
>>> serve.split("service-name", {"backend:v1": 1.0})
"""
split(endpoint_name, {backend_tag: 1.0})
@_ensure_connected
def split(endpoint_name, traffic_policy_dictionary):
"""Associate a service endpoint with traffic policy.
Example:
>>> serve.split("service-name", {
"backend:v1": 0.5,
"backend:v2": 0.5
})
Args:
endpoint_name (str): A registered service endpoint.
traffic_policy_dictionary (dict): a dictionary maps backend names
to their traffic weights. The weights must sum to 1.
"""
assert endpoint_name in global_state.route_table.list_service().values()
assert isinstance(traffic_policy_dictionary,
dict), "Traffic policy must be dictionary"
prob = 0
for backend, weight in traffic_policy_dictionary.items():
prob += weight
assert (backend in global_state.backend_table.list_backends()
), "backend {} is not registered".format(backend)
assert np.isclose(
prob, 1,
atol=0.02), "weights must sum to 1, currently it sums to {}".format(
prob)
global_state.policy_table.register_traffic_policy(
endpoint_name, traffic_policy_dictionary)
global_state.init_or_get_router().set_traffic.remote(
endpoint_name, traffic_policy_dictionary)
@_ensure_connected
def get_handle(endpoint_name):
"""Retrieve RayServeHandle for service endpoint to invoke it from Python.
Args:
endpoint_name (str): A registered service endpoint.
Returns:
RayServeHandle
"""
assert endpoint_name in global_state.route_table.list_service().values()
# Delay import due to it's dependency on global_state
from ray.experimental.serve.handle import RayServeHandle
return RayServeHandle(global_state.init_or_get_router(), endpoint_name)
@_ensure_connected
def stat(percentiles=[50, 90, 95],
agg_windows_seconds=[10, 60, 300, 600, 3600]):
"""Retrieve metric statistics about ray serve system.
Args:
percentiles(List[int]): The percentiles for aggregation operations.
Default is 50th, 90th, 95th percentile.
agg_windows_seconds(List[int]): The aggregation windows in seconds.
The longest aggregation window must be shorter or equal to the
gc_window_seconds.
"""
return ray.get(global_state.init_or_get_metric_monitor().collect.remote(
percentiles, agg_windows_seconds))
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/backend_config.py
|
Python
|
from copy import deepcopy
class BackendConfig:
# configs not needed for actor creation when
# instantiating a replica
_serve_configs = ["_num_replicas", "max_batch_size"]
# configs which when changed leads to restarting
# the existing replicas.
restart_on_change_fields = ["resources", "num_cpus", "num_gpus"]
def __init__(self,
num_replicas=1,
resources=None,
max_batch_size=None,
num_cpus=None,
num_gpus=None,
memory=None,
object_store_memory=None):
"""
Class for defining backend configuration.
"""
# serve configs
self.num_replicas = num_replicas
self.max_batch_size = max_batch_size
# ray actor configs
self.resources = resources
self.num_cpus = num_cpus
self.num_gpus = num_gpus
self.memory = memory
self.object_store_memory = object_store_memory
@property
def num_replicas(self):
return self._num_replicas
@num_replicas.setter
def num_replicas(self, val):
if not (val > 0):
raise Exception("num_replicas must be greater than zero")
self._num_replicas = val
def __iter__(self):
for k in self.__dict__.keys():
key, val = k, self.__dict__[k]
if key == "_num_replicas":
key = "num_replicas"
yield key, val
def get_actor_creation_args(self, init_args):
ret_d = deepcopy(self.__dict__)
for k in self._serve_configs:
ret_d.pop(k)
ret_d["args"] = init_args
return ret_d
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/constants.py
|
Python
|
#: The interval which http server refreshes its routing table
HTTP_ROUTER_CHECKER_INTERVAL_S = 2
#: Actor name used to register actor nursery
SERVE_NURSERY_NAME = "SERVE_ACTOR_NURSERY"
#: KVStore connector key in bootstrap config
BOOTSTRAP_KV_STORE_CONN_KEY = "kv_store_connector"
#: HTTP Address
DEFAULT_HTTP_ADDRESS = "http://0.0.0.0:8000"
#: HTTP Host
DEFAULT_HTTP_HOST = "0.0.0.0"
#: HTTP Port
DEFAULT_HTTP_PORT = 8000
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/context.py
|
Python
|
from enum import IntEnum
from ray.experimental.serve.exceptions import RayServeException
class TaskContext(IntEnum):
"""TaskContext constants for queue.enqueue method"""
Web = 1
Python = 2
# Global variable will be modified in worker
# web == True: currrently processing a request from web server
# web == False: currently processing a request from python
web = False
# batching information in serve context
# batch_size == None : the backend doesn't support batching
# batch_size(int) : the number of elements of input list
batch_size = None
_not_in_web_context_error = """
Accessing the request object outside of the web context. Please use
"serve.context.web" to determine when the function is called within
a web context.
"""
class FakeFlaskRequest:
def __getattribute__(self, name):
raise RayServeException(_not_in_web_context_error)
def __setattr__(self, name, value):
raise RayServeException(_not_in_web_context_error)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo.py
|
Python
|
"""
Example service that prints out http context.
"""
import time
import requests
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
def echo(flask_request):
return "hello " + flask_request.args.get("name", "serve!")
serve.init(blocking=True)
serve.create_endpoint("my_endpoint", "/echo", blocking=True)
serve.create_backend(echo, "echo:v1")
serve.link("my_endpoint", "echo:v1")
while True:
resp = requests.get("http://127.0.0.1:8000/echo").json()
print(pformat_color_json(resp))
print("...Sleeping for 2 seconds...")
time.sleep(2)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_actor.py
|
Python
|
"""
Example actor that adds an increment to a number. This number can
come from either web (parsing Flask request) or python call.
This actor can be called from HTTP as well as from Python.
"""
import time
import requests
import ray
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
class MagicCounter:
def __init__(self, increment):
self.increment = increment
def __call__(self, flask_request, base_number=None):
if serve.context.web:
base_number = int(flask_request.args.get("base_number", "0"))
return base_number + self.increment
serve.init(blocking=True)
serve.create_endpoint("magic_counter", "/counter", blocking=True)
serve.create_backend(MagicCounter, "counter:v1", 42) # increment=42
serve.link("magic_counter", "counter:v1")
print("Sending ten queries via HTTP")
for i in range(10):
url = "http://127.0.0.1:8000/counter?base_number={}".format(i)
print("> Pinging {}".format(url))
resp = requests.get(url).json()
print(pformat_color_json(resp))
time.sleep(0.2)
print("Sending ten queries via Python")
handle = serve.get_handle("magic_counter")
for i in range(10):
print("> Pinging handle.remote(base_number={})".format(i))
result = ray.get(handle.remote(base_number=i))
print("< Result {}".format(result))
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_actor_batch.py
|
Python
|
"""
Example actor that adds an increment to a number. This number can
come from either web (parsing Flask request) or python call.
The queries incoming to this actor are batched.
This actor can be called from HTTP as well as from Python.
"""
import time
import requests
import ray
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
from ray.experimental.serve import BackendConfig
class MagicCounter:
def __init__(self, increment):
self.increment = increment
@serve.accept_batch
def __call__(self, flask_request_list, base_number=None):
# batch_size = serve.context.batch_size
if serve.context.web:
result = []
for flask_request in flask_request_list:
base_number = int(flask_request.args.get("base_number", "0"))
result.append(base_number)
return list(map(lambda x: x + self.increment, result))
else:
result = []
for b in base_number:
ans = b + self.increment
result.append(ans)
return result
serve.init(blocking=True)
serve.create_endpoint("magic_counter", "/counter", blocking=True)
b_config = BackendConfig(max_batch_size=5)
serve.create_backend(
MagicCounter, "counter:v1", 42, backend_config=b_config) # increment=42
serve.link("magic_counter", "counter:v1")
print("Sending ten queries via HTTP")
for i in range(10):
url = "http://127.0.0.1:8000/counter?base_number={}".format(i)
print("> Pinging {}".format(url))
resp = requests.get(url).json()
print(pformat_color_json(resp))
time.sleep(0.2)
print("Sending ten queries via Python")
handle = serve.get_handle("magic_counter")
for i in range(10):
print("> Pinging handle.remote(base_number={})".format(i))
result = ray.get(handle.remote(base_number=i))
print("< Result {}".format(result))
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_batching.py
|
Python
|
"""
This example has backend which has batching functionality enabled.
"""
import ray
from ray.experimental import serve
from ray.experimental.serve import BackendConfig
class MagicCounter:
def __init__(self, increment):
self.increment = increment
@serve.accept_batch
def __call__(self, flask_request, base_number=None):
# __call__ fn should preserve the batch size
# base_number is a python list
if serve.context.batch_size is not None:
batch_size = serve.context.batch_size
result = []
for base_num in base_number:
ret_str = "Number: {} Batch size: {}".format(
base_num, batch_size)
result.append(ret_str)
return result
return ""
serve.init(blocking=True)
serve.create_endpoint("magic_counter", "/counter", blocking=True)
# specify max_batch_size in BackendConfig
b_config = BackendConfig(max_batch_size=5)
serve.create_backend(
MagicCounter, "counter:v1", 42, backend_config=b_config) # increment=42
print("Backend Config for backend: 'counter:v1'")
print(b_config)
serve.link("magic_counter", "counter:v1")
handle = serve.get_handle("magic_counter")
future_list = []
# fire 30 requests
for r in range(30):
print("> [REMOTE] Pinging handle.remote(base_number={})".format(r))
f = handle.remote(base_number=r)
future_list.append(f)
# get results of queries as they complete
left_futures = future_list
while left_futures:
completed_futures, remaining_futures = ray.wait(left_futures, timeout=0.05)
if len(completed_futures) > 0:
result = ray.get(completed_futures[0])
print("< " + result)
left_futures = remaining_futures
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_error.py
|
Python
|
"""
Example of error handling mechanism in ray serve.
We are going to define a buggy function that raise some exception:
>>> def echo(_):
raise Exception("oh no")
The expected behavior is:
- HTTP server should respond with "internal error" in the response JSON
- ray.get(handle.remote()) should raise RayTaskError with traceback.
This shows that error is hidden from HTTP side but always visible when calling
from Python.
"""
import time
import requests
import ray
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
def echo(_):
raise Exception("Something went wrong...")
serve.init(blocking=True)
serve.create_endpoint("my_endpoint", "/echo", blocking=True)
serve.create_backend(echo, "echo:v1")
serve.link("my_endpoint", "echo:v1")
for _ in range(2):
resp = requests.get("http://127.0.0.1:8000/echo").json()
print(pformat_color_json(resp))
print("...Sleeping for 2 seconds...")
time.sleep(2)
handle = serve.get_handle("my_endpoint")
print("Invoke from python will raise exception with traceback:")
ray.get(handle.remote())
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_fixed_packing.py
|
Python
|
"""
Example showing fixed packing policy. The outputs from
v1 and v2 will be coming according to packing_num specified!
This is a packed round robin example. First batch of packing_num
(five in this example) queries would go to 'echo:v1' backend and
then next batch of packing_num queries would go to 'echo:v2'
backend.
"""
import time
import requests
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
def echo_v1(_):
return "v1"
def echo_v2(_):
return "v2"
# specify the router policy as FixedPacking with packing num as 5
serve.init(
blocking=True,
queueing_policy=serve.RoutePolicy.FixedPacking,
policy_kwargs={"packing_num": 5})
# create a service
serve.create_endpoint("my_endpoint", "/echo", blocking=True)
# create first backend
serve.create_backend(echo_v1, "echo:v1")
# create second backend
serve.create_backend(echo_v2, "echo:v2")
# link and split the service to two backends
serve.split("my_endpoint", {"echo:v1": 0.5, "echo:v2": 0.5})
while True:
resp = requests.get("http://127.0.0.1:8000/echo").json()
print(pformat_color_json(resp))
print("...Sleeping for 2 seconds...")
time.sleep(2)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_full.py
|
Python
|
"""
Full example of ray.serve module
"""
import time
import requests
import ray
import ray.experimental.serve as serve
from ray.experimental.serve.utils import pformat_color_json
# initialize ray serve system.
# blocking=True will wait for HTTP server to be ready to serve request.
serve.init(blocking=True)
# an endpoint is associated with an http URL.
serve.create_endpoint("my_endpoint", "/echo")
# a backend can be a function or class.
# it can be made to be invoked from web as well as python.
def echo_v1(flask_request, response="hello from python!"):
if serve.context.web:
response = flask_request.url
return response
serve.create_backend(echo_v1, "echo:v1")
backend_config_v1 = serve.get_backend_config("echo:v1")
# We can link an endpoint to a backend, the means all the traffic
# goes to my_endpoint will now goes to echo:v1 backend.
serve.link("my_endpoint", "echo:v1")
print(requests.get("http://127.0.0.1:8000/echo").json())
# The service will be reachable from http
print(ray.get(serve.get_handle("my_endpoint").remote(response="hello")))
# as well as within the ray system.
# We can also add a new backend and split the traffic.
def echo_v2(flask_request):
# magic, only from web.
return "something new"
serve.create_backend(echo_v2, "echo:v2")
backend_config_v2 = serve.get_backend_config("echo:v2")
# The two backend will now split the traffic 50%-50%.
serve.split("my_endpoint", {"echo:v1": 0.5, "echo:v2": 0.5})
# Observe requests are now split between two backends.
for _ in range(10):
print(requests.get("http://127.0.0.1:8000/echo").json())
time.sleep(0.5)
# You can also change number of replicas
# for each backend independently.
backend_config_v1.num_replicas = 2
serve.set_backend_config("echo:v1", backend_config_v1)
backend_config_v2.num_replicas = 2
serve.set_backend_config("echo:v2", backend_config_v2)
# As well as retrieving relevant system metrics
print(pformat_color_json(serve.stat()))
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_round_robin.py
|
Python
|
"""
Example showing round robin policy. The outputs from
v1 and v2 will be (almost) interleaved as queries get processed.
"""
import time
import requests
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
def echo_v1(_):
return "v1"
def echo_v2(_):
return "v2"
# specify the router policy as RoundRobin
serve.init(blocking=True, queueing_policy=serve.RoutePolicy.RoundRobin)
# create a service
serve.create_endpoint("my_endpoint", "/echo", blocking=True)
# create first backend
serve.create_backend(echo_v1, "echo:v1")
# create second backend
serve.create_backend(echo_v2, "echo:v2")
# link and split the service to two backends
serve.split("my_endpoint", {"echo:v1": 0.5, "echo:v2": 0.5})
while True:
resp = requests.get("http://127.0.0.1:8000/echo").json()
print(pformat_color_json(resp))
print("...Sleeping for 2 seconds...")
time.sleep(2)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_slo_reverse.py
|
Python
|
"""
SLO [reverse] example of ray.serve module
"""
import time
import requests
import ray
import ray.experimental.serve as serve
# initialize ray serve system.
# blocking=True will wait for HTTP server to be ready to serve request.
serve.init(blocking=True)
# an endpoint is associated with an http URL.
serve.create_endpoint("my_endpoint", "/echo")
# a backend can be a function or class.
# it can be made to be invoked from web as well as python.
def echo_v1(flask_request, response="hello from python!"):
if serve.context.web:
response = flask_request.url
return response
serve.create_backend(echo_v1, "echo:v1")
serve.link("my_endpoint", "echo:v1")
# wait for routing table to get populated
time.sleep(2)
# slo (10 milliseconds deadline) can be specified via http
slo_ms = 10.0
print("> [HTTP] Pinging http://127.0.0.1:8000/echo?slo_ms={}".format(slo_ms))
print(
requests.get("http://127.0.0.1:8000/echo?slo_ms={}".format(slo_ms)).json())
# get the handle of the endpoint
handle = serve.get_handle("my_endpoint")
future_list = []
# fire 10 requests with slo's in the (almost) reverse order of the order in
# which remote procedure call is done
for r in range(10):
slo_ms = 1000 - 100 * r
response = "hello from request: {} slo: {}".format(r, slo_ms)
print("> [REMOTE] Pinging handle.remote(response='{}',slo_ms={})".format(
response, slo_ms))
# slo can be specified via remote function
f = handle.remote(response=response, slo_ms=slo_ms)
future_list.append(f)
# get results of queries as they complete
# should be completed (almost) according to the order of their slo time
left_futures = future_list
while left_futures:
completed_futures, remaining_futures = ray.wait(left_futures, timeout=0.05)
if len(completed_futures) > 0:
result = ray.get(completed_futures[0])
print(result)
left_futures = remaining_futures
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/examples/echo_split.py
|
Python
|
"""
Example of traffic splitting. We will first use echo:v1. Then v1 and v2
will split the incoming traffic evenly.
"""
import time
import requests
from ray.experimental import serve
from ray.experimental.serve.utils import pformat_color_json
def echo_v1(_):
return "v1"
def echo_v2(_):
return "v2"
serve.init(blocking=True)
serve.create_endpoint("my_endpoint", "/echo", blocking=True)
serve.create_backend(echo_v1, "echo:v1")
serve.link("my_endpoint", "echo:v1")
for _ in range(3):
resp = requests.get("http://127.0.0.1:8000/echo").json()
print(pformat_color_json(resp))
print("...Sleeping for 2 seconds...")
time.sleep(2)
serve.create_backend(echo_v2, "echo:v2")
serve.split("my_endpoint", {"echo:v1": 0.5, "echo:v2": 0.5})
while True:
resp = requests.get("http://127.0.0.1:8000/echo").json()
print(pformat_color_json(resp))
print("...Sleeping for 2 seconds...")
time.sleep(2)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/exceptions.py
|
Python
|
class RayServeException(Exception):
pass
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/global_state.py
|
Python
|
import ray
from ray.experimental.serve.constants import (
BOOTSTRAP_KV_STORE_CONN_KEY, DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT,
SERVE_NURSERY_NAME)
from ray.experimental.serve.kv_store_service import (
BackendTable, RoutingTable, TrafficPolicyTable)
from ray.experimental.serve.metric import (MetricMonitor,
start_metric_monitor_loop)
from ray.experimental.serve.policy import RoutePolicy
from ray.experimental.serve.server import HTTPActor
def start_initial_state(kv_store_connector):
nursery_handle = ActorNursery.remote()
ray.experimental.register_actor(SERVE_NURSERY_NAME, nursery_handle)
ray.get(
nursery_handle.store_bootstrap_state.remote(
BOOTSTRAP_KV_STORE_CONN_KEY, kv_store_connector))
return nursery_handle
@ray.remote
class ActorNursery:
"""Initialize and store all actor handles.
Note:
This actor is necessary because ray will destory actors when the
original actor handle goes out of scope (when driver exit). Therefore
we need to initialize and store actor handles in a seperate actor.
"""
def __init__(self):
# Dict: Actor handles -> tag
self.actor_handles = dict()
self.bootstrap_state = dict()
def start_actor(self, actor_cls, tag, init_args=(), init_kwargs={}):
"""Start an actor and add it to the nursery"""
handle = actor_cls.remote(*init_args, **init_kwargs)
self.actor_handles[handle] = tag
return [handle]
def start_actor_with_creator(self, creator, kwargs, tag):
"""
Args:
creator (Callable[Dict]): a closure that should return
a newly created actor handle when called with kwargs.
The kwargs input is passed to `ActorCls_remote` method.
"""
handle = creator(kwargs)
self.actor_handles[handle] = tag
return [handle]
def get_all_handles(self):
return {tag: handle for handle, tag in self.actor_handles.items()}
def get_handle(self, actor_tag):
return [self.get_all_handles()[actor_tag]]
def remove_handle(self, actor_tag):
[handle] = self.get_handle(actor_tag)
self.actor_handles.pop(handle)
del handle
def store_bootstrap_state(self, key, value):
self.bootstrap_state[key] = value
def get_bootstrap_state_dict(self):
return self.bootstrap_state
class GlobalState:
"""Encapsulate all global state in the serving system.
The information is fetch lazily from
1. A collection of namespaced key value stores
2. A actor supervisor service
"""
def __init__(self, actor_nursery_handle=None):
# Get actor nursery handle
if actor_nursery_handle is None:
actor_nursery_handle = ray.experimental.get_actor(
SERVE_NURSERY_NAME)
self.actor_nursery_handle = actor_nursery_handle
# Connect to all the table
bootstrap_config = ray.get(
self.actor_nursery_handle.get_bootstrap_state_dict.remote())
kv_store_connector = bootstrap_config[BOOTSTRAP_KV_STORE_CONN_KEY]
self.route_table = RoutingTable(kv_store_connector)
self.backend_table = BackendTable(kv_store_connector)
self.policy_table = TrafficPolicyTable(kv_store_connector)
self.refresh_actor_handle_cache()
def refresh_actor_handle_cache(self):
self.actor_handle_cache = ray.get(
self.actor_nursery_handle.get_all_handles.remote())
def init_or_get_http_server(self,
host=DEFAULT_HTTP_HOST,
port=DEFAULT_HTTP_PORT):
if "http_server" not in self.actor_handle_cache:
[handle] = ray.get(
self.actor_nursery_handle.start_actor.remote(
HTTPActor, tag="http_server"))
handle.run.remote(host=host, port=port)
self.refresh_actor_handle_cache()
return self.actor_handle_cache["http_server"]
def _get_queueing_policy(self, default_policy):
return_policy = default_policy
# check if there is already a queue_actor running
# with policy as p.name for the case where
# serve nursery exists: ray.experimental.get_actor(SERVE_NURSERY_NAME)
for p in RoutePolicy:
queue_actor_tag = "queue_actor::" + p.name
if queue_actor_tag in self.actor_handle_cache:
return_policy = p
break
return return_policy
def init_or_get_router(self,
queueing_policy=RoutePolicy.Random,
policy_kwargs={}):
# get queueing policy
self.queueing_policy = self._get_queueing_policy(
default_policy=queueing_policy)
queue_actor_tag = "queue_actor::" + self.queueing_policy.name
if queue_actor_tag not in self.actor_handle_cache:
[handle] = ray.get(
self.actor_nursery_handle.start_actor.remote(
self.queueing_policy.value,
init_kwargs=policy_kwargs,
tag=queue_actor_tag))
handle.register_self_handle.remote(handle)
self.refresh_actor_handle_cache()
return self.actor_handle_cache[queue_actor_tag]
def init_or_get_metric_monitor(self, gc_window_seconds=3600):
if "metric_monitor" not in self.actor_handle_cache:
[handle] = ray.get(
self.actor_nursery_handle.start_actor.remote(
MetricMonitor,
init_args=(gc_window_seconds, ),
tag="metric_monitor"))
start_metric_monitor_loop.remote(handle)
if "queue_actor" in self.actor_handle_cache:
handle.add_target.remote(
self.actor_handle_cache["queue_actor"])
self.refresh_actor_handle_cache()
return self.actor_handle_cache["metric_monitor"]
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/handle.py
|
Python
|
import ray
from ray.experimental import serve
from ray.experimental.serve.context import TaskContext
from ray.experimental.serve.exceptions import RayServeException
from ray.experimental.serve.constants import DEFAULT_HTTP_ADDRESS
class RayServeHandle:
"""A handle to a service endpoint.
Invoking this endpoint with .remote is equivalent to pinging
an HTTP endpoint.
Example:
>>> handle = serve.get_handle("my_endpoint")
>>> handle
RayServeHandle(
Endpoint="my_endpoint",
URL="...",
Traffic=...
)
>>> handle.remote(my_request_content)
ObjectID(...)
>>> ray.get(handle.remote(...))
# result
>>> ray.get(handle.remote(let_it_crash_request))
# raises RayTaskError Exception
"""
def __init__(self, router_handle, endpoint_name):
self.router_handle = router_handle
self.endpoint_name = endpoint_name
def remote(self, *args, **kwargs):
if len(args) != 0:
raise RayServeException(
"handle.remote must be invoked with keyword arguments.")
# get slo_ms before enqueuing the query
request_slo_ms = kwargs.pop("slo_ms", None)
if request_slo_ms is not None:
try:
request_slo_ms = float(request_slo_ms)
if request_slo_ms < 0:
raise ValueError(
"Request SLO must be positive, it is {}".format(
request_slo_ms))
except ValueError as e:
raise RayServeException(str(e))
result_object_id_bytes = ray.get(
self.router_handle.enqueue_request.remote(
service=self.endpoint_name,
request_args=(),
request_kwargs=kwargs,
request_context=TaskContext.Python,
request_slo_ms=request_slo_ms))
return ray.ObjectID(result_object_id_bytes)
def get_traffic_policy(self):
# TODO(simon): This method is implemented via checking global state
# because we are sure handle and global_state are in the same process.
# However, once global_state is deprecated, this method need to be
# updated accordingly.
history = serve.global_state.policy_action_history[self.endpoint_name]
if len(history):
return history[-1]
else:
return None
def get_http_endpoint(self):
return DEFAULT_HTTP_ADDRESS
def __repr__(self):
return """
RayServeHandle(
Endpoint="{endpoint_name}",
URL="{http_endpoint}/{endpoint_name}",
Traffic={traffic_policy}
)
""".format(endpoint_name=self.endpoint_name,
http_endpoint=self.get_http_endpoint(),
traffic_policy=self.get_traffic_policy())
# TODO(simon): a convenience function that dumps equivalent requests
# code for a given call.
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/http_util.py
|
Python
|
import io
import flask
def build_flask_request(asgi_scope_dict, request_body):
"""Build and return a flask request from ASGI payload
This function is indented to be used immediately before task invocation
happen.
"""
wsgi_environ = build_wsgi_environ(asgi_scope_dict, request_body)
return flask.Request(wsgi_environ)
def build_wsgi_environ(scope, body):
"""
Builds a scope and request body into a WSGI environ object.
This code snippet is taken from https://github.com/django/asgiref/blob
/36c3e8dc70bf38fe2db87ac20b514f21aaf5ea9d/asgiref/wsgi.py#L52
WSGI specification can be found at
https://www.python.org/dev/peps/pep-0333/
This function helps translate ASGI scope and body into a flask request.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", ""),
"PATH_INFO": scope["path"],
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": "HTTP/{}".format(scope["http_version"]),
"wsgi.version": (1, 0),
"wsgi.url_scheme": scope.get("scheme", "http"),
"wsgi.input": body,
"wsgi.errors": io.BytesIO(),
"wsgi.multithread": True,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
}
# Get server name and port - required in WSGI, not in ASGI
environ["SERVER_NAME"] = scope["server"][0]
environ["SERVER_PORT"] = str(scope["server"][1])
environ["REMOTE_ADDR"] = scope["client"][0]
# Transforms headers into environ entries.
for name, value in scope.get("headers", []):
# name, values are both bytes, we need to decode them to string
name = name.decode("latin1")
value = value.decode("latin1")
# Handle name correction to conform to WSGI spec
# https://www.python.org/dev/peps/pep-0333/#environ-variables
if name == "content-length":
corrected_name = "CONTENT_LENGTH"
elif name == "content-type":
corrected_name = "CONTENT_TYPE"
else:
corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
# If the header value repeated,
# we will just concatenate it to the field.
if corrected_name in environ:
value = environ[corrected_name] + "," + value
environ[corrected_name] = value
return environ
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/kv_store_service.py
|
Python
|
import json
import sqlite3
from abc import ABC
from ray import cloudpickle as pickle
import ray.experimental.internal_kv as ray_kv
from ray.experimental.serve.utils import logger
class NamespacedKVStore(ABC):
"""Abstract base class for a namespaced key-value store.
The idea is that multiple key-value stores can be created while sharing
the same storage system. The keys of each instance are namespaced to avoid
object_id key collision.
Example:
>>> store_ns1 = NamespacedKVStore(namespace="ns1")
>>> store_ns2 = NamespacedKVStore(namespace="ns2")
# Two stores can share the same connection like Redis or SQL Table
>>> store_ns1.put("same-key", 1)
>>> store_ns1.get("same-key")
1
>>> store_ns2.put("same-key", 2)
>>> store_ns2.get("same-key", 2)
2
"""
def __init__(self, namespace):
raise NotImplementedError()
def get(self, key):
"""Retrieve the value for the given key.
Args:
key (str)
"""
raise NotImplementedError()
def put(self, key, value):
"""Serialize the value and store it under the given key.
Args:
key (str)
value (object): any serializable object. The serialization method
is determined by the subclass implementation.
"""
raise NotImplementedError()
def as_dict(self):
"""Return the entire namespace as a dictionary.
Returns:
data (dict): key value pairs in current namespace
"""
raise NotImplementedError()
class InMemoryKVStore(NamespacedKVStore):
"""A reference implementation used for testing."""
def __init__(self, namespace):
self.data = dict()
# Namespace is ignored, because each namespace is backed by
# an in-memory Python dictionary.
self.namespace = namespace
def get(self, key):
return self.data[key]
def put(self, key, value):
self.data[key] = value
def as_dict(self):
return self.data.copy()
class RayInternalKVStore(NamespacedKVStore):
"""A NamespacedKVStore implementation using ray's `internal_kv`."""
def __init__(self, namespace):
assert ray_kv._internal_kv_initialized()
self.index_key = "RAY_SERVE_INDEX"
self.namespace = namespace
self._put(self.index_key, [])
def _format_key(self, key):
return "{ns}-{key}".format(ns=self.namespace, key=key)
def _remove_format_key(self, formatted_key):
return formatted_key.replace(self.namespace + "-", "", 1)
def _serialize(self, obj):
return json.dumps(obj)
def _deserialize(self, buffer):
return json.loads(buffer)
def _put(self, key, value):
ray_kv._internal_kv_put(
self._format_key(self._serialize(key)),
self._serialize(value),
overwrite=True,
)
def _get(self, key):
return self._deserialize(
ray_kv._internal_kv_get(self._format_key(self._serialize(key))))
def get(self, key):
return self._get(key)
def put(self, key, value):
assert isinstance(key, str), "Key must be a string."
self._put(key, value)
all_keys = set(self._get(self.index_key))
all_keys.add(key)
self._put(self.index_key, list(all_keys))
def as_dict(self):
data = {}
all_keys = self._get(self.index_key)
for key in all_keys:
data[self._remove_format_key(key)] = self._get(key)
return data
class SQLiteKVStore(NamespacedKVStore):
def __init__(self, namespace, db_path):
self.namespace = namespace
self.conn = sqlite3.connect(db_path)
cursor = self.conn.cursor()
cursor.execute(
"CREATE TABLE IF NOT EXISTS {} (key TEXT UNIQUE, value TEXT)".
format(self.namespace))
self.conn.commit()
def put(self, key, value):
cursor = self.conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO {} (key, value) VALUES (?,?)".format(
self.namespace), (key, value))
self.conn.commit()
def get(self, key, default=None):
cursor = self.conn.cursor()
result = list(
cursor.execute(
"SELECT value FROM {} WHERE key = (?)".format(self.namespace),
(key, )))
if len(result) == 0:
return default
else:
# Due to UNIQUE constraint, there can only be one value.
value, *_ = result[0]
return value
def as_dict(self):
cursor = self.conn.cursor()
result = list(
cursor.execute("SELECT key, value FROM {}".format(self.namespace)))
return dict(result)
# Tables
class RoutingTable:
def __init__(self, kv_connector):
self.routing_table = kv_connector("routing_table")
self.request_count = 0
def register_service(self, route: str, service: str):
"""Create an entry in the routing table
Args:
route: http path name. Must begin with '/'.
service: service name. This is the name http actor will push
the request to.
"""
logger.debug("[KV] Registering route {} to service {}.".format(
route, service))
self.routing_table.put(route, service)
def list_service(self):
"""Returns the routing table."""
self.request_count += 1
table = self.routing_table.as_dict()
return table
def get_request_count(self):
"""Return the number of requests that fetched the routing table.
This method is used for two purpose:
1. Make sure HTTP server has started and healthy. Incremented request
count means HTTP server is actively fetching routing table.
2. Make sure HTTP server does not have stale routing table. This number
should be incremented every HTTP_ROUTER_CHECKER_INTERVAL_S seconds.
Supervisor should check this number as indirect indicator of http
server's health.
"""
return self.request_count
class BackendTable:
def __init__(self, kv_connector):
self.backend_table = kv_connector("backend_creator")
self.replica_table = kv_connector("replica_table")
self.backend_info = kv_connector("backend_info")
self.backend_init_args = kv_connector("backend_init_args")
def register_backend(self, backend_tag: str, backend_creator):
backend_creator_serialized = pickle.dumps(backend_creator)
self.backend_table.put(backend_tag, backend_creator_serialized)
def save_init_args(self, backend_tag: str, arg_list):
serialized_arg_list = pickle.dumps(arg_list)
self.backend_init_args.put(backend_tag, serialized_arg_list)
def get_init_args(self, backend_tag):
return pickle.loads(self.backend_init_args.get(backend_tag))
def register_info(self, backend_tag: str, backend_info_d):
self.backend_info.put(backend_tag, json.dumps(backend_info_d))
def get_info(self, backend_tag):
return json.loads(self.backend_info.get(backend_tag, "{}"))
def get_backend_creator(self, backend_tag):
return pickle.loads(self.backend_table.get(backend_tag))
def list_backends(self):
return list(self.backend_table.as_dict().keys())
def list_replicas(self, backend_tag: str):
return json.loads(self.replica_table.get(backend_tag, "[]"))
def add_replica(self, backend_tag: str, new_replica_tag: str):
replica_tags = self.list_replicas(backend_tag)
replica_tags.append(new_replica_tag)
self.replica_table.put(backend_tag, json.dumps(replica_tags))
def remove_replica(self, backend_tag):
replica_tags = self.list_replicas(backend_tag)
removed_replica = replica_tags.pop()
self.replica_table.put(backend_tag, json.dumps(replica_tags))
return removed_replica
class TrafficPolicyTable:
def __init__(self, kv_connector):
self.traffic_policy_table = kv_connector("traffic_policy")
def register_traffic_policy(self, service_name, policy_dict):
self.traffic_policy_table.put(service_name, json.dumps(policy_dict))
def list_traffic_policy(self):
return {
service: json.loads(policy)
for service, policy in self.traffic_policy_table.as_dict()
}
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/metric.py
|
Python
|
import time
import numpy as np
import pandas as pd
import ray
@ray.remote(num_cpus=0)
class MetricMonitor:
def __init__(self, gc_window_seconds=3600):
"""Metric monitor scrapes metrics from ray serve actors
and allow windowed query operations.
Args:
gc_window_seconds(int): How long will we keep the metric data in
memory. Data older than the gc_window will be deleted.
"""
#: Mapping actor ID (hex) -> actor handle
self.actor_handles = dict()
self.data_entries = []
self.gc_window_seconds = gc_window_seconds
self.latest_gc_time = time.time()
def is_ready(self):
return True
def add_target(self, target_handle):
hex_id = target_handle._actor_id.hex()
self.actor_handles[hex_id] = target_handle
def remove_target(self, target_handle):
hex_id = target_handle._actor_id.hex()
self.actor_handles.pop(hex_id)
def scrape(self):
# If expected gc time has passed, we will perform metric value GC.
expected_gc_time = self.latest_gc_time + self.gc_window_seconds
if expected_gc_time < time.time():
self._perform_gc()
self.latest_gc_time = time.time()
curr_time = time.time()
result = [
handle._serve_metric.remote()
for handle in self.actor_handles.values()
]
# TODO(simon): handle the possibility that an actor_handle is removed
for handle_result in ray.get(result):
for metric_name, metric_info in handle_result.items():
data_entry = {
"retrieved_at": curr_time,
"name": metric_name,
"type": metric_info["type"],
}
if metric_info["type"] == "counter":
data_entry["value"] = metric_info["value"]
self.data_entries.append(data_entry)
elif metric_info["type"] == "list":
for metric_value in metric_info["value"]:
new_entry = data_entry.copy()
new_entry["value"] = metric_value
self.data_entries.append(new_entry)
def _perform_gc(self):
curr_time = time.time()
earliest_time_allowed = curr_time - self.gc_window_seconds
# If we don"t have any data at hand, no need to gc.
if len(self.data_entries) == 0:
return
df = pd.DataFrame(self.data_entries)
df = df[df["retrieved_at"] >= earliest_time_allowed]
self.data_entries = df.to_dict(orient="record")
def _get_dataframe(self):
return pd.DataFrame(self.data_entries)
def collect(self,
percentiles=[50, 90, 95],
agg_windows_seconds=[10, 60, 300, 600, 3600]):
"""Collect and perform aggregation on all metrics.
Args:
percentiles(List[int]): The percentiles for aggregation operations.
Default is 50th, 90th, 95th percentile.
agg_windows_seconds(List[int]): The aggregation windows in seconds.
The longest aggregation window must be shorter or equal to the
gc_window_seconds.
"""
result = {}
df = pd.DataFrame(self.data_entries)
if len(df) == 0: # no metric to report
return {}
# Retrieve the {metric_name -> metric_type} mapping
metric_types = df[["name",
"type"]].set_index("name").squeeze().to_dict()
for metric_name, metric_type in metric_types.items():
if metric_type == "counter":
result[metric_name] = df.loc[df["name"] == metric_name,
"value"].tolist()[-1]
if metric_type == "list":
result.update(
self._aggregate(metric_name, percentiles,
agg_windows_seconds))
return result
def _aggregate(self, metric_name, percentiles, agg_windows_seconds):
"""Perform aggregation over a metric.
Note:
This metric must have type `list`.
"""
assert max(agg_windows_seconds) <= self.gc_window_seconds, (
"Aggregation window exceeds gc window. You should set a longer gc "
"window or shorter aggregation window.")
curr_time = time.time()
df = pd.DataFrame(self.data_entries)
filtered_df = df[df["name"] == metric_name]
if len(filtered_df) == 0:
return dict()
data_types = filtered_df["type"].unique().tolist()
assert data_types == [
"list"
], ("Can't aggreagte over non-list type. {} has type {}".format(
metric_name, data_types))
aggregated_metric = {}
for window in agg_windows_seconds:
earliest_time = curr_time - window
windowed_df = filtered_df[
filtered_df["retrieved_at"] > earliest_time]
percentile_values = np.percentile(windowed_df["value"],
percentiles)
for percentile, value in zip(percentiles, percentile_values):
result_key = "{name}_{perc}th_perc_{window}_window".format(
name=metric_name, perc=percentile, window=window)
aggregated_metric[result_key] = value
return aggregated_metric
@ray.remote(num_cpus=0)
def start_metric_monitor_loop(monitor_handle, duration_s=5):
while True:
ray.get(monitor_handle.scrape.remote())
time.sleep(duration_s)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/policy.py
|
Python
|
from enum import Enum
from ray.experimental.serve.queues import (
RoundRobinPolicyQueueActor, RandomPolicyQueueActor,
PowerOfTwoPolicyQueueActor, FixedPackingPolicyQueueActor)
class RoutePolicy(Enum):
"""
A class for registering the backend selection policy.
Add a name and the corresponding class.
Serve will support the added policy and policy can be accessed
in `serve.init` method through name provided here.
"""
Random = RandomPolicyQueueActor
RoundRobin = RoundRobinPolicyQueueActor
PowerOfTwo = PowerOfTwoPolicyQueueActor
FixedPacking = FixedPackingPolicyQueueActor
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/queues.py
|
Python
|
from collections import defaultdict, deque
import numpy as np
import ray
from ray.experimental.serve.utils import logger
import itertools
from blist import sortedlist
import time
class Query:
def __init__(self,
request_args,
request_kwargs,
request_context,
request_slo_ms,
result_object_id=None):
self.request_args = request_args
self.request_kwargs = request_kwargs
self.request_context = request_context
if result_object_id is None:
self.result_object_id = ray.ObjectID.from_random()
else:
self.result_object_id = result_object_id
# Service level objective in milliseconds. This is expected to be the
# absolute time since unix epoch.
self.request_slo_ms = request_slo_ms
# adding comparator fn for maintaining an
# ascending order sorted list w.r.t request_slo_ms
def __lt__(self, other):
return self.request_slo_ms < other.request_slo_ms
class WorkIntent:
def __init__(self, replica_handle):
self.replica_handle = replica_handle
class CentralizedQueues:
"""A router that routes request to available workers.
Router aceepts each request from the `enqueue_request` method and enqueues
it. It also accepts worker request to work (called work_intention in code)
from workers via the `dequeue_request` method. The traffic policy is used
to match requests with their corresponding workers.
Behavior:
>>> # psuedo-code
>>> queue = CentralizedQueues()
>>> queue.enqueue_request(
"service-name", request_args, request_kwargs, request_context)
# nothing happens, request is queued.
# returns result ObjectID, which will contains the final result
>>> queue.dequeue_request('backend-1', replica_handle)
# nothing happens, work intention is queued.
# return work ObjectID, which will contains the future request payload
>>> queue.link('service-name', 'backend-1')
# here the enqueue_requester is matched with replica, request
# data is put into work ObjectID, and the replica processes the request
# and store the result into result ObjectID
Traffic policy splits the traffic among different replicas
probabilistically:
1. When all backends are ready to receive traffic, we will randomly
choose a backend based on the weights assigned by the traffic policy
dictionary.
2. When more than 1 but not all backends are ready, we will normalize the
weights of the ready backends to 1 and choose a backend via sampling.
3. When there is only 1 backend ready, we will only use that backend.
"""
def __init__(self):
# service_name -> request queue
self.queues = defaultdict(deque)
# service_name -> traffic_policy
self.traffic = defaultdict(dict)
# backend_name -> backend_config
self.backend_info = dict()
# backend_name -> worker request queue
self.workers = defaultdict(deque)
# backend_name -> worker payload queue
# using blist sortedlist for deadline awareness
# blist is chosen because:
# 1. pop operation should be O(1) (amortized)
# (helpful even for batched pop)
# 2. There should not be significant overhead in
# maintaining the sorted list.
# 3. The blist implementation is fast and uses C extensions.
self.buffer_queues = defaultdict(sortedlist)
def is_ready(self):
return True
def _serve_metric(self):
return {
"backend_{}_queue_size".format(backend_name): {
"value": len(queue),
"type": "counter",
}
for backend_name, queue in self.buffer_queues.items()
}
# request_slo_ms is time specified in milliseconds till which the
# answer of the query should be calculated
def enqueue_request(self,
service,
request_args,
request_kwargs,
request_context,
request_slo_ms=None):
if request_slo_ms is None:
# if request_slo_ms is not specified then set it to a high level
request_slo_ms = 1e9
# add wall clock time to specify the deadline for completion of query
# this also assures FIFO behaviour if request_slo_ms is not specified
request_slo_ms += (time.time() * 1000)
query = Query(request_args, request_kwargs, request_context,
request_slo_ms)
self.queues[service].append(query)
self.flush()
return query.result_object_id.binary()
def dequeue_request(self, backend, replica_handle):
intention = WorkIntent(replica_handle)
self.workers[backend].append(intention)
self.flush()
def remove_and_destory_replica(self, backend, replica_handle):
# NOTE: this function scale by O(#replicas for the backend)
new_queue = deque()
target_id = replica_handle._actor_id
for work_intent in self.workers[backend]:
if work_intent.replica_handle._actor_id != target_id:
new_queue.append(work_intent)
self.workers[backend] = new_queue
replica_handle.__ray_terminate__.remote()
def link(self, service, backend):
logger.debug("Link %s with %s", service, backend)
self.set_traffic(service, {backend: 1.0})
def set_traffic(self, service, traffic_dict):
logger.debug("Setting traffic for service %s to %s", service,
traffic_dict)
self.traffic[service] = traffic_dict
self.flush()
def set_backend_config(self, backend, config_dict):
logger.debug("Setting backend config for "
"backend {} to {}".format(backend, config_dict))
self.backend_info[backend] = config_dict
def flush(self):
"""In the default case, flush calls ._flush.
When this class is a Ray actor, .flush can be scheduled as a remote
method invocation.
"""
self._flush()
def _get_available_backends(self, service):
backends_in_policy = set(self.traffic[service].keys())
available_workers = {
backend
for backend, queues in self.workers.items() if len(queues) > 0
}
return list(backends_in_policy.intersection(available_workers))
# flushes the buffer queue and assigns work to workers
def _flush_buffer(self):
for service in self.queues.keys():
ready_backends = self._get_available_backends(service)
for backend in ready_backends:
# no work available
if len(self.buffer_queues[backend]) == 0:
continue
buffer_queue = self.buffer_queues[backend]
work_queue = self.workers[backend]
max_batch_size = None
if backend in self.backend_info:
max_batch_size = self.backend_info[backend][
"max_batch_size"]
while len(buffer_queue) and len(work_queue):
# get the work from work intent queue
work = work_queue.popleft()
# see if backend accepts batched queries
if max_batch_size is not None:
pop_size = min(len(buffer_queue), max_batch_size)
request = [
buffer_queue.pop(0) for _ in range(pop_size)
]
else:
request = buffer_queue.pop(0)
work.replica_handle._ray_serve_call.remote(request)
# selects the backend and puts the service queue query to the buffer
# different policies will implement different backend selection policies
def _flush_service_queue(self):
"""
Expected Implementation:
The implementer is expected to access and manipulate
self.queues : dict[str,Deque]
self.buffer_queues : dict[str,sortedlist]
For registering the implemented policies register at policy.py!
Expected Behavior:
the Deque of all services in self.queues linked with
atleast one backend must be empty irrespective of whatever
backend policy is implemented.
"""
pass
# _flush function has to flush the service and buffer queues.
def _flush(self):
self._flush_service_queue()
self._flush_buffer()
class CentralizedQueuesActor(CentralizedQueues):
"""
A wrapper class for converting wrapper policy classes to ray
actors. This is needed to make `flush` call asynchronous.
"""
self_handle = None
def register_self_handle(self, handle_to_this_actor):
self.self_handle = handle_to_this_actor
def flush(self):
if self.self_handle:
self.self_handle._flush.remote()
else:
self._flush()
class RandomPolicyQueue(CentralizedQueues):
"""
A wrapper class for Random policy.This backend selection policy is
`Stateless` meaning the current decisions of selecting backend are
not dependent on previous decisions. Random policy (randomly) samples
backends based on backend weights for every query. This policy uses the
weights assigned to backends.
"""
def _flush_service_queue(self):
# perform traffic splitting for requests
for service, queue in self.queues.items():
# while there are incoming requests and there are backends
while len(queue) and len(self.traffic[service]):
backend_names = list(self.traffic[service].keys())
backend_weights = list(self.traffic[service].values())
# randomly choose a backend for every query
chosen_backend = np.random.choice(
backend_names, p=backend_weights).squeeze()
request = queue.popleft()
self.buffer_queues[chosen_backend].add(request)
@ray.remote
class RandomPolicyQueueActor(RandomPolicyQueue, CentralizedQueuesActor):
pass
class RoundRobinPolicyQueue(CentralizedQueues):
"""
A wrapper class for RoundRobin policy. This backend selection policy
is `Stateful` meaning the current decisions of selecting backend are
dependent on previous decisions. RoundRobinPolicy assigns queries in
an interleaved manner to every backend serving for a service. Consider
backend A,B linked to a service. Now queries will be assigned to backends
in the following order - [ A, B, A, B ... ] . This policy doesn't use the
weights assigned to backends.
"""
# Saves the information about last assigned
# backend for every service
round_robin_iterator_map = {}
def set_traffic(self, service, traffic_dict):
logger.debug("Setting traffic for service %s to %s", service,
traffic_dict)
self.traffic[service] = traffic_dict
backend_names = list(self.traffic[service].keys())
self.round_robin_iterator_map[service] = itertools.cycle(backend_names)
self.flush()
def _flush_service_queue(self):
# perform traffic splitting for requests
for service, queue in self.queues.items():
# if there are incoming requests and there are backends
if len(queue) and len(self.traffic[service]):
while len(queue):
# choose the next backend available from persistent
# information
chosen_backend = next(
self.round_robin_iterator_map[service])
request = queue.popleft()
self.buffer_queues[chosen_backend].add(request)
@ray.remote
class RoundRobinPolicyQueueActor(RoundRobinPolicyQueue,
CentralizedQueuesActor):
pass
class PowerOfTwoPolicyQueue(CentralizedQueues):
"""
A wrapper class for powerOfTwo policy. This backend selection policy is
`Stateless` meaning the current decisions of selecting backend are
dependent on previous decisions. PowerOfTwo policy (randomly) samples two
backends (say Backend A,B among A,B,C) based on the backend weights
specified and chooses the backend which is less loaded. This policy uses
the weights assigned to backends.
"""
def _flush_service_queue(self):
# perform traffic splitting for requests
for service, queue in self.queues.items():
# while there are incoming requests and there are backends
while len(queue) and len(self.traffic[service]):
backend_names = list(self.traffic[service].keys())
backend_weights = list(self.traffic[service].values())
if len(self.traffic[service]) >= 2:
# randomly pick 2 backends
backend1, backend2 = np.random.choice(
backend_names, 2, p=backend_weights)
# see the length of buffer queues of the two backends
# and pick the one which has less no. of queries
# in the buffer
if (len(self.buffer_queues[backend1]) <= len(
self.buffer_queues[backend2])):
chosen_backend = backend1
else:
chosen_backend = backend2
else:
chosen_backend = np.random.choice(
backend_names, p=backend_weights).squeeze()
request = queue.popleft()
self.buffer_queues[chosen_backend].add(request)
@ray.remote
class PowerOfTwoPolicyQueueActor(PowerOfTwoPolicyQueue,
CentralizedQueuesActor):
pass
class FixedPackingPolicyQueue(CentralizedQueues):
"""
A wrapper class for FixedPacking policy. This backend selection policy is
`Stateful` meaning the current decisions of selecting backend are dependent
on previous decisions. FixedPackingPolicy is k RoundRobin policy where
first packing_num queries are handled by 'backend-1' and next k queries are
handled by 'backend-2' and so on ... where 'backend-1' and 'backend-2' are
served by the same service. This policy doesn't use the weights assigned to
backends.
"""
def __init__(self, packing_num=3):
# Saves the information about last assigned
# backend for every service
self.fixed_packing_iterator_map = {}
self.packing_num = packing_num
super().__init__()
def set_traffic(self, service, traffic_dict):
logger.debug("Setting traffic for service %s to %s", service,
traffic_dict)
self.traffic[service] = traffic_dict
backend_names = list(self.traffic[service].keys())
self.fixed_packing_iterator_map[service] = itertools.cycle(
itertools.chain.from_iterable(
itertools.repeat(x, self.packing_num) for x in backend_names))
self.flush()
def _flush_service_queue(self):
# perform traffic splitting for requests
for service, queue in self.queues.items():
# if there are incoming requests and there are backends
if len(queue) and len(self.traffic[service]):
while len(queue):
# choose the next backend available from persistent
# information
chosen_backend = next(
self.fixed_packing_iterator_map[service])
request = queue.popleft()
self.buffer_queues[chosen_backend].add(request)
@ray.remote
class FixedPackingPolicyQueueActor(FixedPackingPolicyQueue,
CentralizedQueuesActor):
pass
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/scripts.py
|
Python
|
import json
import click
import ray
import ray.experimental.serve as serve
@click.group("serve", help="Commands working with ray serve")
def serve_cli():
pass
@serve_cli.command(help="Initialize ray serve components")
def init():
ray.init(address="auto")
serve.init(blocking=True)
@serve_cli.command(help="Split traffic for a endpoint")
@click.argument("endpoint", required=True, type=str)
# TODO(simon): Make traffic dictionary more ergonomic. e.g.
# --traffic backend1=0.5 --traffic backend2=0.5
@click.option(
"--traffic",
required=True,
type=str,
help="Traffic dictionary in JSON format")
def split(endpoint, traffic):
ray.init(address="auto")
serve.init()
serve.split(endpoint, json.loads(traffic))
@serve_cli.command(help="Scale the number of replicas for a backend")
@click.argument("backend", required=True, type=str)
@click.option(
"--num-replicas",
required=True,
type=int,
help="New number of replicas to set")
def scale(backend_tag, num_replicas):
if num_replicas <= 0:
click.Abort(
"Cannot set number of replicas to be smaller or equal to 0.")
ray.init(address="auto")
serve.init()
serve.scale(backend_tag, num_replicas)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/server.py
|
Python
|
import asyncio
import json
import uvicorn
import ray
from ray.experimental.async_api import _async_init
from ray.experimental.serve.constants import HTTP_ROUTER_CHECKER_INTERVAL_S
from ray.experimental.serve.context import TaskContext
from ray.experimental.serve.utils import BytesEncoder
from urllib.parse import parse_qs
class JSONResponse:
"""ASGI compliant response class.
It is expected to be called in async context and pass along
`scope, receive, send` as in ASGI spec.
>>> await JSONResponse({"k": "v"})(scope, receive, send)
"""
def __init__(self, content=None, status_code=200):
"""Construct a JSON HTTP Response.
Args:
content (optional): Any JSON serializable object.
status_code (int, optional): Default status code is 200.
"""
self.body = self.render(content)
self.status_code = status_code
self.raw_headers = [[b"content-type", b"application/json"]]
def render(self, content):
if content is None:
return b""
if isinstance(content, bytes):
return content
return json.dumps(content, cls=BytesEncoder, indent=2).encode()
async def __call__(self, scope, receive, send):
await send({
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
})
await send({"type": "http.response.body", "body": self.body})
class HTTPProxy:
"""
This class should be instantiated and ran by ASGI server.
>>> import uvicorn
>>> uvicorn.run(HTTPProxy(kv_store_actor_handle, router_handle))
# blocks forever
"""
def __init__(self):
assert ray.is_initialized()
# Delay import due to GlobalState depends on HTTP actor
from ray.experimental.serve.global_state import GlobalState
self.serve_global_state = GlobalState()
self.route_table_cache = dict()
self.route_checker_should_shutdown = False
async def route_checker(self, interval):
while True:
if self.route_checker_should_shutdown:
return
self.route_table_cache = (
self.serve_global_state.route_table.list_service())
await asyncio.sleep(interval)
async def handle_lifespan_message(self, scope, receive, send):
assert scope["type"] == "lifespan"
message = await receive()
if message["type"] == "lifespan.startup":
await _async_init()
asyncio.ensure_future(
self.route_checker(interval=HTTP_ROUTER_CHECKER_INTERVAL_S))
await send({"type": "lifespan.startup.complete"})
elif message["type"] == "lifespan.shutdown":
self.route_checker_should_shutdown = True
await send({"type": "lifespan.shutdown.complete"})
async def receive_http_body(self, scope, receive, send):
body_buffer = []
more_body = True
while more_body:
message = await receive()
assert message["type"] == "http.request"
more_body = message["more_body"]
body_buffer.append(message["body"])
return b"".join(body_buffer)
async def __call__(self, scope, receive, send):
# NOTE: This implements ASGI protocol specified in
# https://asgi.readthedocs.io/en/latest/specs/index.html
if scope["type"] == "lifespan":
await self.handle_lifespan_message(scope, receive, send)
return
assert scope["type"] == "http"
current_path = scope["path"]
if current_path == "/":
await JSONResponse(self.route_table_cache)(scope, receive, send)
return
# TODO(simon): Use werkzeug route mapper to support variable path
if current_path not in self.route_table_cache:
error_message = ("Path {} not found. "
"Please ping http://.../ for routing table"
).format(current_path)
await JSONResponse(
{
"error": error_message
}, status_code=404)(scope, receive, send)
return
endpoint_name = self.route_table_cache[current_path]
http_body_bytes = await self.receive_http_body(scope, receive, send)
# get slo_ms before enqueuing the query
query_string = scope["query_string"].decode("ascii")
query_kwargs = parse_qs(query_string)
request_slo_ms = query_kwargs.pop("slo_ms", None)
if request_slo_ms is not None:
try:
if len(request_slo_ms) != 1:
raise ValueError(
"Multiple SLO specified, please specific only one.")
request_slo_ms = request_slo_ms[0]
request_slo_ms = float(request_slo_ms)
if request_slo_ms < 0:
raise ValueError(
"Request SLO must be positive, it is {}".format(
request_slo_ms))
except ValueError as e:
await JSONResponse({"error": str(e)})(scope, receive, send)
return
result_object_id_bytes = await (
self.serve_global_state.init_or_get_router()
.enqueue_request.remote(
service=endpoint_name,
request_args=(scope, http_body_bytes),
request_kwargs=dict(),
request_context=TaskContext.Web,
request_slo_ms=request_slo_ms))
result = await ray.ObjectID(result_object_id_bytes)
if isinstance(result, ray.exceptions.RayTaskError):
await JSONResponse({
"error": "internal error, please use python API to debug"
})(scope, receive, send)
else:
await JSONResponse({"result": result})(scope, receive, send)
@ray.remote
class HTTPActor:
def __init__(self):
self.app = HTTPProxy()
def run(self, host="0.0.0.0", port=8000):
uvicorn.run(
self.app, host=host, port=port, lifespan="on", access_log=False)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/task_runner.py
|
Python
|
import time
import traceback
import ray
from ray.experimental.serve import context as serve_context
from ray.experimental.serve.context import FakeFlaskRequest
from collections import defaultdict
from ray.experimental.serve.utils import parse_request_item
from ray.experimental.serve.exceptions import RayServeException
class TaskRunner:
"""A simple class that runs a function.
The purpose of this class is to model what the most basic actor could be.
That is, a ray serve actor should implement the TaskRunner interface.
"""
def __init__(self, func_to_run):
self.func = func_to_run
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def wrap_to_ray_error(exception):
"""Utility method that catch and seal exceptions in execution"""
try:
# Raise and catch so we can access traceback.format_exc()
raise exception
except Exception as e:
traceback_str = ray.utils.format_error_message(traceback.format_exc())
return ray.exceptions.RayTaskError(str(e), traceback_str, e.__class__)
class RayServeMixin:
"""This mixin class adds the functionality to fetch from router queues.
Warning:
It assumes the main execution method is `__call__` of the user defined
class. This means that serve will call `your_instance.__call__` when
each request comes in. This behavior will be fixed in the future to
allow assigning artibrary methods.
Example:
>>> # Use ray.remote decorator and RayServeMixin
>>> # to make MyClass servable.
>>> @ray.remote
class RayServeActor(RayServeMixin, MyClass):
pass
"""
_ray_serve_self_handle = None
_ray_serve_router_handle = None
_ray_serve_setup_completed = False
_ray_serve_dequeue_requester_name = None
# Work token can be unfullfilled from last iteration.
# This cache will be used to determine whether or not we should
# work on the same task as previous iteration or we are ready to
# move on.
_ray_serve_cached_work_token = None
_serve_metric_error_counter = 0
_serve_metric_latency_list = []
def _serve_metric(self):
# Make a copy of the latency list and clear current list
latency_lst = self._serve_metric_latency_list[:]
self._serve_metric_latency_list = []
my_name = self._ray_serve_dequeue_requester_name
return {
"{}_error_counter".format(my_name): {
"value": self._serve_metric_error_counter,
"type": "counter",
},
"{}_latency_s".format(my_name): {
"value": latency_lst,
"type": "list",
},
}
def _ray_serve_setup(self, my_name, router_handle, my_handle):
self._ray_serve_dequeue_requester_name = my_name
self._ray_serve_router_handle = router_handle
self._ray_serve_self_handle = my_handle
self._ray_serve_setup_completed = True
def _ray_serve_fetch(self):
assert self._ray_serve_setup_completed
self._ray_serve_router_handle.dequeue_request.remote(
self._ray_serve_dequeue_requester_name,
self._ray_serve_self_handle)
def invoke_single(self, request_item):
args, kwargs, is_web_context, result_object_id = parse_request_item(
request_item)
serve_context.web = is_web_context
start_timestamp = time.time()
try:
result = self.__call__(*args, **kwargs)
ray.worker.global_worker.put_object(result, result_object_id)
except Exception as e:
wrapped_exception = wrap_to_ray_error(e)
self._serve_metric_error_counter += 1
ray.worker.global_worker.put_object(wrapped_exception,
result_object_id)
self._serve_metric_latency_list.append(time.time() - start_timestamp)
def invoke_batch(self, request_item_list):
# TODO(alind) : create no-http services. The enqueues
# from such services will always be TaskContext.Python.
# Assumption : all the requests in a bacth
# have same serve context.
# For batching kwargs are modified as follows -
# kwargs [Python Context] : key,val
# kwargs_list : key, [val1,val2, ... , valn]
# or
# args[Web Context] : val
# args_list : [val1,val2, ...... , valn]
# where n (current batch size) <= max_batch_size of a backend
kwargs_list = defaultdict(list)
result_object_ids, context_flag_list, arg_list = [], [], []
curr_batch_size = len(request_item_list)
for item in request_item_list:
args, kwargs, is_web_context, result_object_id = (
parse_request_item(item))
context_flag_list.append(is_web_context)
# Python context only have kwargs
# Web context only have one positional argument
if is_web_context:
arg_list.append(args[0])
else:
for k, v in kwargs.items():
kwargs_list[k].append(v)
result_object_ids.append(result_object_id)
try:
# check mixing of query context
# unified context needed
if len(set(context_flag_list)) != 1:
raise RayServeException(
"Batched queries contain mixed context.")
serve_context.web = all(context_flag_list)
if serve_context.web:
args = (arg_list, )
else:
# Set the flask request as a list to conform
# with batching semantics: when in batching
# mode, each argument it turned into list.
fake_flask_request_lst = [
FakeFlaskRequest() for _ in range(curr_batch_size)
]
args = (fake_flask_request_lst, )
# set the current batch size (n) for serve_context
serve_context.batch_size = len(result_object_ids)
start_timestamp = time.time()
result_list = self.__call__(*args, **kwargs_list)
if (not isinstance(result_list, list)) or (len(result_list) !=
len(result_object_ids)):
raise RayServeException("__call__ function "
"doesn't preserve batch-size. "
"Please return a list of result "
"with length equals to the batch "
"size.")
for result, result_object_id in zip(result_list,
result_object_ids):
ray.worker.global_worker.put_object(result, result_object_id)
self._serve_metric_latency_list.append(time.time() -
start_timestamp)
except Exception as e:
wrapped_exception = wrap_to_ray_error(e)
self._serve_metric_error_counter += len(result_object_ids)
for result_object_id in result_object_ids:
ray.worker.global_worker.put_object(wrapped_exception,
result_object_id)
def _ray_serve_call(self, request):
work_item = request
# check if work_item is a list or not
# if it is list: then batching supported
if not isinstance(work_item, list):
self.invoke_single(work_item)
else:
self.invoke_batch(work_item)
# re-assign to default values
serve_context.web = False
serve_context.batch_size = None
self._ray_serve_fetch()
class TaskRunnerBackend(TaskRunner, RayServeMixin):
"""A simple function serving backend
Note that this is not yet an actor. To make it an actor:
>>> @ray.remote
class TaskRunnerActor(TaskRunnerBackend):
pass
Note:
This class is not used in the actual ray serve system. It exists
for documentation purpose.
"""
@ray.remote
class TaskRunnerActor(TaskRunnerBackend):
pass
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/tests/conftest.py
|
Python
|
import os
import tempfile
import pytest
import ray
from ray.experimental import serve
@pytest.fixture(scope="session")
def serve_instance():
_, new_db_path = tempfile.mkstemp(suffix=".test.db")
serve.init(
kv_store_path=new_db_path,
blocking=True,
ray_init_kwargs={"num_cpus": 36})
yield
os.remove(new_db_path)
@pytest.fixture(scope="session")
def ray_instance():
ray_already_initialized = ray.is_initialized()
if not ray_already_initialized:
ray.init(object_store_memory=int(1e8))
yield
if not ray_already_initialized:
ray.shutdown()
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/tests/test_api.py
|
Python
|
import time
import pytest
import requests
from ray.experimental import serve
from ray.experimental.serve import BackendConfig
import ray
def test_e2e(serve_instance):
serve.init() # so we have access to global state
serve.create_endpoint("endpoint", "/api", blocking=True)
result = serve.api._get_global_state().route_table.list_service()
assert result["/api"] == "endpoint"
retry_count = 5
timeout_sleep = 0.5
while True:
try:
resp = requests.get("http://127.0.0.1:8000/").json()
assert resp == result
break
except Exception:
time.sleep(timeout_sleep)
timeout_sleep *= 2
retry_count -= 1
if retry_count == 0:
assert False, "Route table hasn't been updated after 3 tries."
def function(flask_request):
return "OK"
serve.create_backend(function, "echo:v1")
serve.link("endpoint", "echo:v1")
resp = requests.get("http://127.0.0.1:8000/api").json()["result"]
assert resp == "OK"
def test_scaling_replicas(serve_instance):
class Counter:
def __init__(self):
self.count = 0
def __call__(self, _):
self.count += 1
return self.count
serve.create_endpoint("counter", "/increment")
# Keep checking the routing table until /increment is populated
while "/increment" not in requests.get("http://127.0.0.1:8000/").json():
time.sleep(0.2)
b_config = BackendConfig(num_replicas=2)
serve.create_backend(Counter, "counter:v1", backend_config=b_config)
serve.link("counter", "counter:v1")
counter_result = []
for _ in range(10):
resp = requests.get("http://127.0.0.1:8000/increment").json()["result"]
counter_result.append(resp)
# If the load is shared among two replicas. The max result cannot be 10.
assert max(counter_result) < 10
b_config = serve.get_backend_config("counter:v1")
b_config.num_replicas = 1
serve.set_backend_config("counter:v1", b_config)
counter_result = []
for _ in range(10):
resp = requests.get("http://127.0.0.1:8000/increment").json()["result"]
counter_result.append(resp)
# Give some time for a replica to spin down. But majority of the request
# should be served by the only remaining replica.
assert max(counter_result) - min(counter_result) > 6
def test_batching(serve_instance):
class BatchingExample:
def __init__(self):
self.count = 0
@serve.accept_batch
def __call__(self, flask_request, temp=None):
self.count += 1
batch_size = serve.context.batch_size
return [self.count] * batch_size
serve.create_endpoint("counter1", "/increment")
# Keep checking the routing table until /increment is populated
while "/increment" not in requests.get("http://127.0.0.1:8000/").json():
time.sleep(0.2)
# set the max batch size
b_config = BackendConfig(max_batch_size=5)
serve.create_backend(
BatchingExample, "counter:v11", backend_config=b_config)
serve.link("counter1", "counter:v11")
future_list = []
handle = serve.get_handle("counter1")
for _ in range(20):
f = handle.remote(temp=1)
future_list.append(f)
counter_result = ray.get(future_list)
# since count is only updated per batch of queries
# If there atleast one __call__ fn call with batch size greater than 1
# counter result will always be less than 20
assert max(counter_result) < 20
def test_batching_exception(serve_instance):
class NoListReturned:
def __init__(self):
self.count = 0
@serve.accept_batch
def __call__(self, flask_request, temp=None):
batch_size = serve.context.batch_size
return batch_size
serve.create_endpoint("exception-test", "/noListReturned")
# set the max batch size
b_config = BackendConfig(max_batch_size=5)
serve.create_backend(
NoListReturned, "exception:v1", backend_config=b_config)
serve.link("exception-test", "exception:v1")
handle = serve.get_handle("exception-test")
with pytest.raises(ray.exceptions.RayTaskError):
assert ray.get(handle.remote(temp=1))
def test_killing_replicas(serve_instance):
class Simple:
def __init__(self):
self.count = 0
def __call__(self, flask_request, temp=None):
return temp
serve.create_endpoint("simple", "/simple")
b_config = BackendConfig(num_replicas=3, num_cpus=2)
serve.create_backend(Simple, "simple:v1", backend_config=b_config)
global_state = serve.api._get_global_state()
old_replica_tag_list = global_state.backend_table.list_replicas(
"simple:v1")
bnew_config = serve.get_backend_config("simple:v1")
# change the config
bnew_config.num_cpus = 1
# set the config
serve.set_backend_config("simple:v1", bnew_config)
new_replica_tag_list = global_state.backend_table.list_replicas(
"simple:v1")
global_state.refresh_actor_handle_cache()
new_all_tag_list = list(global_state.actor_handle_cache.keys())
# the new_replica_tag_list must be subset of all_tag_list
assert set(new_replica_tag_list) <= set(new_all_tag_list)
# the old_replica_tag_list must not be subset of all_tag_list
assert not set(old_replica_tag_list) <= set(new_all_tag_list)
def test_not_killing_replicas(serve_instance):
class BatchSimple:
def __init__(self):
self.count = 0
@serve.accept_batch
def __call__(self, flask_request, temp=None):
batch_size = serve.context.batch_size
return [1] * batch_size
serve.create_endpoint("bsimple", "/bsimple")
b_config = BackendConfig(num_replicas=3, max_batch_size=2)
serve.create_backend(BatchSimple, "bsimple:v1", backend_config=b_config)
global_state = serve.api._get_global_state()
old_replica_tag_list = global_state.backend_table.list_replicas(
"bsimple:v1")
bnew_config = serve.get_backend_config("bsimple:v1")
# change the config
bnew_config.max_batch_size = 5
# set the config
serve.set_backend_config("bsimple:v1", bnew_config)
new_replica_tag_list = global_state.backend_table.list_replicas(
"bsimple:v1")
global_state.refresh_actor_handle_cache()
new_all_tag_list = list(global_state.actor_handle_cache.keys())
# the old and new replica tag list should be identical
# and should be subset of all_tag_list
assert set(old_replica_tag_list) <= set(new_all_tag_list)
assert set(old_replica_tag_list) == set(new_replica_tag_list)
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
|
python/ray/experimental/serve/tests/test_metric.py
|
Python
|
import numpy as np
import pytest
import ray
from ray.experimental.serve.metric import MetricMonitor
@pytest.fixture(scope="session")
def start_target_actor(ray_instance):
@ray.remote
class Target:
def __init__(self):
self.counter_value = 0
def _serve_metric(self):
self.counter_value += 1
return {
"latency_list": {
"type": "list",
# Generate 0 to 100 inclusive.
# This means total of 101 items.
"value": np.arange(101).tolist()
},
"counter": {
"type": "counter",
"value": self.counter_value
}
}
def get_counter_value(self):
return self.counter_value
yield Target.remote()
def test_metric_gc(ray_instance, start_target_actor):
target_actor = start_target_actor
# this means when new scrapes are invoked, the
metric_monitor = MetricMonitor.remote(gc_window_seconds=0)
ray.get(metric_monitor.add_target.remote(target_actor))
ray.get(metric_monitor.scrape.remote())
df = ray.get(metric_monitor._get_dataframe.remote())
assert len(df) == 102
# Old metric sould be cleared. So only 1 counter + 101 list values left.
ray.get(metric_monitor.scrape.remote())
df = ray.get(metric_monitor._get_dataframe.remote())
assert len(df) == 102
def test_metric_system(ray_instance, start_target_actor):
target_actor = start_target_actor
metric_monitor = MetricMonitor.remote()
ray.get(metric_monitor.add_target.remote(target_actor))
# Scrape once
ray.get(metric_monitor.scrape.remote())
percentiles = [50, 90, 95]
agg_windows_seconds = [60]
result = ray.get(
metric_monitor.collect.remote(percentiles, agg_windows_seconds))
real_counter_value = ray.get(target_actor.get_counter_value.remote())
expected_result = {
"counter": real_counter_value,
"latency_list_50th_perc_60_window": 50.0,
"latency_list_90th_perc_60_window": 90.0,
"latency_list_95th_perc_60_window": 95.0,
}
assert result == expected_result
|
zhuohan123/hoplite-rllib
| 3
|
Python
|
zhuohan123
|
Zhuohan Li
|
vLLM / Meta
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.