diff --git a/.ci/deps_tests/boot.py b/.ci/deps_tests/boot.py deleted file mode 100644 index eedd41b87a..0000000000 --- a/.ci/deps_tests/boot.py +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/python -## -import os -import sys -import re -from bs4 import BeautifulSoup - -## get all test catalog -def get_test_all_catalog(name): - CatalogList = [] - PackageNameList = [] - filepath = os.path.join(os.getcwd(), name) - packagenames = os.listdir(name) - for packagename in packagenames: - tmp_path = os.path.join(filepath, packagename) - if os.path.isdir(tmp_path): - CatalogList.append(tmp_path) - PackageNameList.append(packagename) - return CatalogList, PackageNameList - -## Start Galaxy Engine -## Save index. d by extracting important information from index.html. -## extract index.html and deal with path information in index.html -def extract_core_content(path, filename, packagename): - filepath = os.path.join(path, filename) - if os.path.exists(filepath): - fopen = open(filepath) - filecontent = fopen.read() - original_core_content = re.findall(r"<\s*body[^>]*>(.+?)
Copyright", filecontent, re.S) - content = original_core_content[0] - core_content = content.replace('Copyright(.+?)<\s*/\s*html\s*>", re.S) - original_core_content = re_data.sub('', filecontent) - replacecontent = original_core_content.replace('(.+?)", re.S) - replacecontent = ra_title.sub(' Test Result ', replacecontent) - return replacecontent - -# Splicing content -def splicing_content(name, filename): - CoreContent = [] - index = 0, - CatalogList, PackageNameList = get_test_all_catalog(name) - for catalog, packageName in zip(CatalogList, PackageNameList): - if(index == (0,)): - Content = replace_href(catalog, filename, packageName) - CoreContent.append(Content) - index = 1 - else: - Content = extract_core_content(catalog, filename, packageName) - CoreContent.append(Content) - str = "" - con = str.join('%s' % id for id in CoreContent) - con = con + "" - return con - -## process data statistics -def data_statistics(filestream): - soup_string = BeautifulSoup(filestream, "html.parser") - body_datas = soup_string.find_all("tbody") - testpluginList = [] - testmoudleList = [] - testsuccessList = [] - testfailList = [] - testskipList = [] - allsuccessValue = allfailValue = allSkipValue = 0 - for body_data in body_datas: - ## test moudle data - # testmoudledata = body_data.find_all("a") - testplugindata = body_data.find_all("tr") - for testplugin in testplugindata: - data = testplugin.find_all("td") - testpluginname = data[8] - con = testpluginname.find("a")['href'] - re_data = re.compile(r"\\ct_run(.+?).html", re.S) - re_data = re_data.sub('', con) - testpluginList.append(str(re_data)) - testmoudledata = testplugin.find_all("a")[0] - testmoudleList.append(testmoudledata) - successdata = data[3] - testsuccessList.append(successdata) - faildata = data[4] - testfailList.append(faildata) - skipdata = data[5] - testskipList.append(skipdata) - ## get all value - testallvalues = soup_string.find_all("tfoot") - for testallvalue in testallvalues: - data = testallvalue.find_all("td") - allsuccessValue += int(data[3].string) - allfailValue += int(data[4].string) - datas = str(data[5].string) - re_skipdata = re.compile("(.+?)/", re.S) - datas = str(re_skipdata.sub('', datas)).replace(")", "") - allSkipValue += int(datas) - tbody = "" - table_head = "

Data Outline


" - for testplugin, testmoudle, testsuccess, testfail, testskip in zip(testpluginList, testmoudleList, testsuccessList, testfailList, testskipList): - moudlebody = "".format(testmoudle) - successbody = "{}".format(testsuccess) - failbody = "{}".format(testfail) - skipbody = "{}".format(testskip) - pluginbody = "".format(testplugin) - tbody += str(moudlebody) + str(successbody) +str(failbody) + str(skipbody) + str(pluginbody) - totalbody = "
Test NameSuccessFailedSkipedPlugin Name
{}{}
Total{}{}{} 
".format(allsuccessValue, allfailValue, allSkipValue) - outline_head = "

Executing Plugin Name


" - catalogList, packageNameList = get_test_all_catalog("logs") - successPluginData = "" - failedPluginData = "" - for catalog, packagename in zip(catalogList, packageNameList): - successPlugin, failedPlugin = outline_value(catalog, packagename) - successPluginData += successPlugin + " " - failedPluginData += failedPlugin +" " - outline_body_value = "
All Test Plugin NameSuccess extract Log plugin nameEmpty plugin name
{}{}{}
".format(packageNameList, successPluginData, failedPluginData) - data_outline_html = outline_head + outline_body_value + table_head + tbody + totalbody - - return data_outline_html, allfailValue - -def outline_value(path, pluginName): - filepath = os.path.join(path, "index.html") - successPlugin = "" - failedPlugin = "" - if os.path.exists(filepath): - successPlugin = pluginName - else: - failedPlugin = pluginName - return successPlugin, failedPlugin - -def produceHtml(): - htmldata = splicing_content("logs", "index.html") - data_outline_html, allfailValue = data_statistics(htmldata) - headdatamatch = re.match(r"]*>", htmldata, re.S) - headdata = "" - if headdatamatch: - headdata = headdatamatch.group() - # re_data = re.compile(r"]*>", re.S) - replacedata = headdata + data_outline_html - htmldata = htmldata.replace(headdata, replacedata) - savepath = os.path.join(os.getcwd(), "logs") - savepath = os.path.join(savepath, "index.html") - if os.path.exists(savepath): - os.remove(savepath) - f = open(savepath, 'w') - f.write(htmldata) - f.close - - ## send exit message when failed - if allfailValue >0 : - exit(1) -# htmldata = splicing_content("logs", "index.html") -# data_statistics(htmldata) -produceHtml() \ No newline at end of file diff --git a/.ci/deps_tests/docker-compose.yaml b/.ci/deps_tests/docker-compose.yaml deleted file mode 100644 index 9ffd44f364..0000000000 --- a/.ci/deps_tests/docker-compose.yaml +++ /dev/null @@ -1,101 +0,0 @@ -version: '3' - -services: - nginx: - build: ./emqx-nginx - image: emqx-nginx:1.15 - restart: always - ports: - - "18080:80" - networks: - - emqx-bridge - volumes: - - ../../tests/logs:/usr/share/nginx/html - - emqx: - build: ./emqx-erlang - image: emqx-erlang - depends_on: - - mysql_server - - redis_server - - mongo_server - - pgsql_server - - ldap_server - networks: - - emqx-bridge - volumes: - - ../../.:/emqx-rel - tty: true - - python: - image: python:3.7.2 - networks: - - emqx-bridge - volumes: - - ../../.:/emqx-rel - tty: true - - mysql_server: - image: mysql:5.7 - restart: always - environment: - MYSQL_ROOT_PASSWORD: public - MYSQL_DATABASE: mqtt - volumes: - - ../../_build/emqx/lib/emqx_auth_mysql/test/emqx_auth_mysql_SUITE_data/ca.pem:/etc/certs/ca-cert.pem - - ../../_build/emqx/lib/emqx_auth_mysql/test/emqx_auth_mysql_SUITE_data/server-cert.pem:/etc/certs/server-cert.pem - - ../../_build/emqx/lib/emqx_auth_mysql/test/emqx_auth_mysql_SUITE_data/server-key.pem:/etc/certs/server-key.pem - networks: - - emqx-bridge - command: - --bind-address 0.0.0.0 - --default-authentication-plugin=mysql_native_password - --character-set-server=utf8mb4 - --collation-server=utf8mb4_general_ci - --explicit_defaults_for_timestamp=true - --lower_case_table_names=1 - --max_allowed_packet=128M - --skip-symbolic-links - --ssl-ca=/etc/certs/ca.pem - --ssl-cert=/etc/certs/server-cert.pem - --ssl-key=/etc/certs/server-key.pem - - redis_server: - build: ./emqx-redis - image: emqx-redis:5 - restart: always - networks: - - emqx-bridge - - mongo_server: - image: mongo:4.1 - restart: always - environment: - MONGO_INITDB_DATABASE: mqtt - networks: - - emqx-bridge - command: --bind_ip_all - - pgsql_server: - image: postgres:11 - restart: always - environment: - POSTGRES_PASSWORD: public - POSTGRES_USER: root - POSTGRES_DB: mqtt - networks: - - emqx-bridge - - ldap_server: - build: ./emqx-ldap - image: emqx-ldap:1.0 - restart: always - networks: - - emqx-bridge - -networks: - emqx-bridge: - driver: bridge - -volumes: - logs-volumes: \ No newline at end of file diff --git a/.ci/deps_tests/emqx-erlang/Dockerfile b/.ci/deps_tests/emqx-erlang/Dockerfile deleted file mode 100644 index fecf29ec28..0000000000 --- a/.ci/deps_tests/emqx-erlang/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ -FROM erlang:22.3 - -# RUN curl -L -o /tmp/openjdk-14.0.1_linux-x64_bin.tar.gz https://download.java.net/java/GA/jdk14.0.1/664493ef4a6946b186ff29eb326336a2/7/GPL/openjdk-14.0.1_linux-x64_bin.tar.gz \ -# && tar xvf /tmp/openjdk-14.0.1_linux-x64_bin.tar.gz -C /usr/local - -# ENV PATH=/usr/local/jdk-14.0.1/bin:$PATH - -RUN wget --no-cookies \ - --no-check-certificate \ - --header "Cookie: oraclelicense=accept-securebackup-cookie" \ - https://download.oracle.com/otn-pub/java/jdk/8u251-b08/3d5a2bb8f8d4428bbe94aed7ec7ae784/jdk-8u251-linux-x64.tar.gz \ - -O /tmp/jdk-8u251-linux-x64.tar.gz \ - && tar xvf /tmp/jdk-8u251-linux-x64.tar.gz -C /usr/local - -ENV PATH=/usr/local/jdk1.8.0_251/bin:$PATH \ No newline at end of file diff --git a/.ci/deps_tests/emqx-ldap/Dockerfile b/.ci/deps_tests/emqx-ldap/Dockerfile deleted file mode 100644 index 6e81754545..0000000000 --- a/.ci/deps_tests/emqx-ldap/Dockerfile +++ /dev/null @@ -1,22 +0,0 @@ -FROM buildpack-deps:stretch - -ENV VERSION=2.4.47 - -RUN apt-get update && apt-get install -y groff groff-base -RUN wget ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/openldap-${VERSION}.tgz \ - && gunzip -c openldap-${VERSION}.tgz | tar xvfB - \ - && cd openldap-${VERSION} \ - && ./configure && make depend && make && make install \ - && cd .. && rm -rf openldap-${VERSION} - -COPY slapd.conf /usr/local/etc/openldap/slapd.conf -COPY schema/emqx.io.ldif /usr/local/etc/openldap/schema/emqx.io.ldif -COPY schema/emqx.schema /usr/local/etc/openldap/schema/emqx.schema - -RUN mkdir -p /usr/local/etc/openldap/data \ - && slapadd -l /usr/local/etc/openldap/schema/emqx.io.ldif -f /usr/local/etc/openldap/slapd.conf - -WORKDIR /usr/local/etc/ -EXPOSE 389 - -CMD [ "/usr/local/libexec/slapd", "-d", "3" ] \ No newline at end of file diff --git a/.ci/deps_tests/emqx-ldap/schema/emqx.io.ldif b/.ci/deps_tests/emqx-ldap/schema/emqx.io.ldif deleted file mode 100644 index 0931354e89..0000000000 --- a/.ci/deps_tests/emqx-ldap/schema/emqx.io.ldif +++ /dev/null @@ -1,132 +0,0 @@ -## create emqx.io - -dn:dc=emqx,dc=io -objectclass: top -objectclass: dcobject -objectclass: organization -dc:emqx -o:emqx,Inc. - -# create testdevice.emqx.io -dn:ou=testdevice,dc=emqx,dc=io -objectClass: top -objectclass:organizationalUnit -ou:testdevice - -# create user admin -dn:uid=admin,ou=testdevice,dc=emqx,dc=io -objectClass: top -objectClass: simpleSecurityObject -objectClass: account -userPassword:: e1NIQX1XNnBoNU1tNVB6OEdnaVVMYlBnekczN21qOWc9 -uid: admin - -## create user=mqttuser0001, -# password=mqttuser0001, -# passhash={SHA}mlb3fat40MKBTXUVZwCKmL73R/0= -# base64passhash=e1NIQX1tbGIzZmF0NDBNS0JUWFVWWndDS21MNzNSLzA9 -dn:uid=mqttuser0001,ou=testdevice,dc=emqx,dc=io -objectClass: top -objectClass: mqttUser -objectClass: mqttDevice -objectClass: mqttSecurity -uid: mqttuser0001 -isEnabled: TRUE -mqttPublishTopic: mqttuser0001/pub/1 -mqttPublishTopic: mqttuser0001/pub/+ -mqttPublishTopic: mqttuser0001/pub/# -mqttSubscriptionTopic: mqttuser0001/sub/1 -mqttSubscriptionTopic: mqttuser0001/sub/+ -mqttSubscriptionTopic: mqttuser0001/sub/# -mqttPubSubTopic: mqttuser0001/pubsub/1 -mqttPubSubTopic: mqttuser0001/pubsub/+ -mqttPubSubTopic: mqttuser0001/pubsub/# -userPassword:: e1NIQX1tbGIzZmF0NDBNS0JUWFVWWndDS21MNzNSLzA9 - -## create user=mqttuser0002 -# password=mqttuser0002, -# passhash={SSHA}n9XdtoG4Q/TQ3TQF4Y+khJbMBH4qXj4M -# base64passhash=e1NTSEF9bjlYZHRvRzRRL1RRM1RRRjRZK2toSmJNQkg0cVhqNE0= -dn:uid=mqttuser0002,ou=testdevice,dc=emqx,dc=io -objectClass: top -objectClass: mqttUser -objectClass: mqttDevice -objectClass: mqttSecurity -uid: mqttuser0002 -isEnabled: TRUE -mqttPublishTopic: mqttuser0002/pub/1 -mqttPublishTopic: mqttuser0002/pub/+ -mqttPublishTopic: mqttuser0002/pub/# -mqttSubscriptionTopic: mqttuser0002/sub/1 -mqttSubscriptionTopic: mqttuser0002/sub/+ -mqttSubscriptionTopic: mqttuser0002/sub/# -mqttPubSubTopic: mqttuser0002/pubsub/1 -mqttPubSubTopic: mqttuser0002/pubsub/+ -mqttPubSubTopic: mqttuser0002/pubsub/# -userPassword:: e1NTSEF9bjlYZHRvRzRRL1RRM1RRRjRZK2toSmJNQkg0cVhqNE0= - -## create user mqttuser0003 -# password=mqttuser0003, -# passhash={MD5}ybsPGoaK3nDyiQvveiCOIw== -# base64passhash=e01ENX15YnNQR29hSzNuRHlpUXZ2ZWlDT0l3PT0= -dn:uid=mqttuser0003,ou=testdevice,dc=emqx,dc=io -objectClass: top -objectClass: mqttUser -objectClass: mqttDevice -objectClass: mqttSecurity -uid: mqttuser0003 -isEnabled: TRUE -mqttPublishTopic: mqttuser0003/pub/1 -mqttPublishTopic: mqttuser0003/pub/+ -mqttPublishTopic: mqttuser0003/pub/# -mqttSubscriptionTopic: mqttuser0003/sub/1 -mqttSubscriptionTopic: mqttuser0003/sub/+ -mqttSubscriptionTopic: mqttuser0003/sub/# -mqttPubSubTopic: mqttuser0003/pubsub/1 -mqttPubSubTopic: mqttuser0003/pubsub/+ -mqttPubSubTopic: mqttuser0003/pubsub/# -userPassword:: e01ENX15YnNQR29hSzNuRHlpUXZ2ZWlDT0l3PT0= - -## create user mqttuser0004 -# password=mqttuser0004, -# passhash={MD5}2Br6pPDSEDIEvUlu9+s+MA== -# base64passhash=e01ENX0yQnI2cFBEU0VESUV2VWx1OStzK01BPT0= -dn:uid=mqttuser0004,ou=testdevice,dc=emqx,dc=io -objectClass: top -objectClass: mqttUser -objectClass: mqttDevice -objectClass: mqttSecurity -uid: mqttuser0004 -isEnabled: TRUE -mqttPublishTopic: mqttuser0004/pub/1 -mqttPublishTopic: mqttuser0004/pub/+ -mqttPublishTopic: mqttuser0004/pub/# -mqttSubscriptionTopic: mqttuser0004/sub/1 -mqttSubscriptionTopic: mqttuser0004/sub/+ -mqttSubscriptionTopic: mqttuser0004/sub/# -mqttPubSubTopic: mqttuser0004/pubsub/1 -mqttPubSubTopic: mqttuser0004/pubsub/+ -mqttPubSubTopic: mqttuser0004/pubsub/# -userPassword: {MD5}2Br6pPDSEDIEvUlu9+s+MA== - -## create user mqttuser0005 -# password=mqttuser0005, -# passhash={SHA}jKnxeEDGR14kE8AR7yuVFOelhz4= -# base64passhash=e1NIQX1qS254ZUVER1IxNGtFOEFSN3l1VkZPZWxoejQ9 -objectClass: top -dn:uid=mqttuser0005,ou=testdevice,dc=emqx,dc=io -objectClass: mqttUser -objectClass: mqttDevice -objectClass: mqttSecurity -uid: mqttuser0005 -isEnabled: TRUE -mqttPublishTopic: mqttuser0005/pub/1 -mqttPublishTopic: mqttuser0005/pub/+ -mqttPublishTopic: mqttuser0005/pub/# -mqttSubscriptionTopic: mqttuser0005/sub/1 -mqttSubscriptionTopic: mqttuser0005/sub/+ -mqttSubscriptionTopic: mqttuser0005/sub/# -mqttPubSubTopic: mqttuser0005/pubsub/1 -mqttPubSubTopic: mqttuser0005/pubsub/+ -mqttPubSubTopic: mqttuser0005/pubsub/# -userPassword: {SHA}jKnxeEDGR14kE8AR7yuVFOelhz4= \ No newline at end of file diff --git a/.ci/deps_tests/emqx-ldap/schema/emqx.schema b/.ci/deps_tests/emqx-ldap/schema/emqx.schema deleted file mode 100644 index 5932390b2a..0000000000 --- a/.ci/deps_tests/emqx-ldap/schema/emqx.schema +++ /dev/null @@ -1,40 +0,0 @@ -# -# Preliminary Apple OS X Native LDAP Schema -# This file is subject to change. -# -attributetype ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.1.3 NAME 'isEnabled' - EQUALITY booleanMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 - SINGLE-VALUE - USAGE userApplications ) - -attributetype ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.4.1 NAME ( 'mqttPublishTopic' 'mpt' ) - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 - USAGE userApplications ) -attributetype ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.4.2 NAME ( 'mqttSubscriptionTopic' 'mst' ) - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 - USAGE userApplications ) -attributetype ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.4.3 NAME ( 'mqttPubSubTopic' 'mpst' ) - EQUALITY caseIgnoreMatch - SUBSTR caseIgnoreSubstringsMatch - SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 - USAGE userApplications ) - -objectclass ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.4 NAME 'mqttUser' - AUXILIARY - MAY ( mqttPublishTopic $ mqttSubscriptionTopic $ mqttPubSubTopic) ) - -objectclass ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.2 NAME 'mqttDevice' - SUP top - STRUCTURAL - MUST ( uid ) - MAY ( isEnabled ) ) - -objectclass ( 1.3.6.1.4.1.11.2.53.2.2.3.1.2.3.3 NAME 'mqttSecurity' - SUP top - AUXILIARY - MAY ( userPassword $ userPKCS12 $ pwdAttribute $ pwdLockout ) ) \ No newline at end of file diff --git a/.ci/deps_tests/emqx-ldap/slapd.conf b/.ci/deps_tests/emqx-ldap/slapd.conf deleted file mode 100644 index 2d76a7509e..0000000000 --- a/.ci/deps_tests/emqx-ldap/slapd.conf +++ /dev/null @@ -1,12 +0,0 @@ -include /usr/local/etc/openldap/schema/core.schema -include /usr/local/etc/openldap/schema/cosine.schema -include /usr/local/etc/openldap/schema/inetorgperson.schema -include /usr/local/etc/openldap/schema/ppolicy.schema -include /usr/local/etc/openldap/schema/emqx.schema - -database bdb -suffix "dc=emqx,dc=io" -rootdn "cn=root,dc=emqx,dc=io" -rootpw {SSHA}eoF7NhNrejVYYyGHqnt+MdKNBh4r1w3W - -directory /usr/local/etc/openldap/data \ No newline at end of file diff --git a/.ci/deps_tests/emqx-nginx/Dockerfile b/.ci/deps_tests/emqx-nginx/Dockerfile deleted file mode 100644 index 8ab9c01b87..0000000000 --- a/.ci/deps_tests/emqx-nginx/Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM nginx:1.15 -COPY default.conf /etc/nginx/conf.d/default.conf \ No newline at end of file diff --git a/.ci/deps_tests/emqx-nginx/default.conf b/.ci/deps_tests/emqx-nginx/default.conf deleted file mode 100644 index 26da737cac..0000000000 --- a/.ci/deps_tests/emqx-nginx/default.conf +++ /dev/null @@ -1,46 +0,0 @@ -server { - listen 80; - server_name localhost; - autoindex on; - - #charset koi8-r; - #access_log /var/log/nginx/host.access.log main; - - location / { - root /usr/share/nginx/html; - index index.html index.htm; - } - - #error_page 404 /404.html; - - # redirect server error pages to the static page /50x.html - # - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root /usr/share/nginx/html; - } - - # proxy the PHP scripts to Apache listening on 127.0.0.1:80 - # - #location ~ \.php$ { - # proxy_pass http://127.0.0.1; - #} - - # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 - # - #location ~ \.php$ { - # root html; - # fastcgi_pass 127.0.0.1:9000; - # fastcgi_index index.php; - # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; - # include fastcgi_params; - #} - - # deny access to .htaccess files, if Apache's document root - # concurs with nginx's one - # - #location ~ /\.ht { - # deny all; - #} -} - diff --git a/.ci/deps_tests/emqx-redis/Dockerfile b/.ci/deps_tests/emqx-redis/Dockerfile deleted file mode 100644 index c81882d7c7..0000000000 --- a/.ci/deps_tests/emqx-redis/Dockerfile +++ /dev/null @@ -1,3 +0,0 @@ -FROM redis:5 -COPY redis.conf /usr/local/etc/redis/redis.conf -CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ] \ No newline at end of file diff --git a/.ci/deps_tests/emqx-redis/redis.conf b/.ci/deps_tests/emqx-redis/redis.conf deleted file mode 100644 index f61c1256c9..0000000000 --- a/.ci/deps_tests/emqx-redis/redis.conf +++ /dev/null @@ -1,1377 +0,0 @@ -# Redis configuration file example. -# -# Note that in order to read the configuration file, Redis must be -# started with the file path as first argument: -# -# ./redis-server /path/to/redis.conf - -# Note on units: when memory size is needed, it is possible to specify -# it in the usual form of 1k 5GB 4M and so forth: -# -# 1k => 1000 bytes -# 1kb => 1024 bytes -# 1m => 1000000 bytes -# 1mb => 1024*1024 bytes -# 1g => 1000000000 bytes -# 1gb => 1024*1024*1024 bytes -# -# units are case insensitive so 1GB 1Gb 1gB are all the same. - -################################## INCLUDES ################################### - -# Include one or more other config files here. This is useful if you -# have a standard template that goes to all Redis servers but also need -# to customize a few per-server settings. Include files can include -# other files, so use this wisely. -# -# Notice option "include" won't be rewritten by command "CONFIG REWRITE" -# from admin or Redis Sentinel. Since Redis always uses the last processed -# line as value of a configuration directive, you'd better put includes -# at the beginning of this file to avoid overwriting config change at runtime. -# -# If instead you are interested in using includes to override configuration -# options, it is better to use include as the last line. -# -# include /path/to/local.conf -# include /path/to/other.conf - -################################## MODULES ##################################### - -# Load modules at startup. If the server is not able to load modules -# it will abort. It is possible to use multiple loadmodule directives. -# -# loadmodule /path/to/my_module.so -# loadmodule /path/to/other_module.so - -################################## NETWORK ##################################### - -# By default, if no "bind" configuration directive is specified, Redis listens -# for connections from all the network interfaces available on the server. -# It is possible to listen to just one or multiple selected interfaces using -# the "bind" configuration directive, followed by one or more IP addresses. -# -# Examples: -# -# bind 192.168.1.100 10.0.0.1 -# bind 127.0.0.1 ::1 -# -# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the -# internet, binding to all the interfaces is dangerous and will expose the -# instance to everybody on the internet. So by default we uncomment the -# following bind directive, that will force Redis to listen only into -# the IPv4 loopback interface address (this means Redis will be able to -# accept connections only from clients running into the same computer it -# is running). -# -# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES -# JUST COMMENT THE FOLLOWING LINE. -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# bind 0.0.0.0 - -# Protected mode is a layer of security protection, in order to avoid that -# Redis instances left open on the internet are accessed and exploited. -# -# When protected mode is on and if: -# -# 1) The server is not binding explicitly to a set of addresses using the -# "bind" directive. -# 2) No password is configured. -# -# The server only accepts connections from clients connecting from the -# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain -# sockets. -# -# By default protected mode is enabled. You should disable it only if -# you are sure you want clients from other hosts to connect to Redis -# even if no authentication is configured, nor a specific set of interfaces -# are explicitly listed using the "bind" directive. -protected-mode no - -# Accept connections on the specified port, default is 6379 (IANA #815344). -# If port 0 is specified Redis will not listen on a TCP socket. -port 6379 - -# TCP listen() backlog. -# -# In high requests-per-second environments you need an high backlog in order -# to avoid slow clients connections issues. Note that the Linux kernel -# will silently truncate it to the value of /proc/sys/net/core/somaxconn so -# make sure to raise both the value of somaxconn and tcp_max_syn_backlog -# in order to get the desired effect. -tcp-backlog 511 - -# Unix socket. -# -# Specify the path for the Unix socket that will be used to listen for -# incoming connections. There is no default, so Redis will not listen -# on a unix socket when not specified. -# -# unixsocket /tmp/redis.sock -# unixsocketperm 700 - -# Close the connection after a client is idle for N seconds (0 to disable) -timeout 0 - -# TCP keepalive. -# -# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence -# of communication. This is useful for two reasons: -# -# 1) Detect dead peers. -# 2) Take the connection alive from the point of view of network -# equipment in the middle. -# -# On Linux, the specified value (in seconds) is the period used to send ACKs. -# Note that to close the connection the double of the time is needed. -# On other kernels the period depends on the kernel configuration. -# -# A reasonable value for this option is 300 seconds, which is the new -# Redis default starting with Redis 3.2.1. -tcp-keepalive 300 - -################################# GENERAL ##################################### - -# By default Redis does not run as a daemon. Use 'yes' if you need it. -# Note that Redis will write a pid file in /var/run/redis.pid when daemonized. -daemonize no - -# If you run Redis from upstart or systemd, Redis can interact with your -# supervision tree. Options: -# supervised no - no supervision interaction -# supervised upstart - signal upstart by putting Redis into SIGSTOP mode -# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET -# supervised auto - detect upstart or systemd method based on -# UPSTART_JOB or NOTIFY_SOCKET environment variables -# Note: these supervision methods only signal "process is ready." -# They do not enable continuous liveness pings back to your supervisor. -supervised no - -# If a pid file is specified, Redis writes it where specified at startup -# and removes it at exit. -# -# When the server runs non daemonized, no pid file is created if none is -# specified in the configuration. When the server is daemonized, the pid file -# is used even if not specified, defaulting to "/var/run/redis.pid". -# -# Creating a pid file is best effort: if Redis is not able to create it -# nothing bad happens, the server will start and run normally. -pidfile /var/run/redis_6379.pid - -# Specify the server verbosity level. -# This can be one of: -# debug (a lot of information, useful for development/testing) -# verbose (many rarely useful info, but not a mess like the debug level) -# notice (moderately verbose, what you want in production probably) -# warning (only very important / critical messages are logged) -loglevel notice - -# Specify the log file name. Also the empty string can be used to force -# Redis to log on the standard output. Note that if you use standard -# output for logging but daemonize, logs will be sent to /dev/null -logfile "" - -# To enable logging to the system logger, just set 'syslog-enabled' to yes, -# and optionally update the other syslog parameters to suit your needs. -# syslog-enabled no - -# Specify the syslog identity. -# syslog-ident redis - -# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. -# syslog-facility local0 - -# Set the number of databases. The default database is DB 0, you can select -# a different one on a per-connection basis using SELECT where -# dbid is a number between 0 and 'databases'-1 -databases 16 - -# By default Redis shows an ASCII art logo only when started to log to the -# standard output and if the standard output is a TTY. Basically this means -# that normally a logo is displayed only in interactive sessions. -# -# However it is possible to force the pre-4.0 behavior and always show a -# ASCII art logo in startup logs by setting the following option to yes. -always-show-logo yes - -################################ SNAPSHOTTING ################################ -# -# Save the DB on disk: -# -# save -# -# Will save the DB if both the given number of seconds and the given -# number of write operations against the DB occurred. -# -# In the example below the behaviour will be to save: -# after 900 sec (15 min) if at least 1 key changed -# after 300 sec (5 min) if at least 10 keys changed -# after 60 sec if at least 10000 keys changed -# -# Note: you can disable saving completely by commenting out all "save" lines. -# -# It is also possible to remove all the previously configured save -# points by adding a save directive with a single empty string argument -# like in the following example: -# -# save "" - -save 900 1 -save 300 10 -save 60 10000 - -# By default Redis will stop accepting writes if RDB snapshots are enabled -# (at least one save point) and the latest background save failed. -# This will make the user aware (in a hard way) that data is not persisting -# on disk properly, otherwise chances are that no one will notice and some -# disaster will happen. -# -# If the background saving process will start working again Redis will -# automatically allow writes again. -# -# However if you have setup your proper monitoring of the Redis server -# and persistence, you may want to disable this feature so that Redis will -# continue to work as usual even if there are problems with disk, -# permissions, and so forth. -stop-writes-on-bgsave-error yes - -# Compress string objects using LZF when dump .rdb databases? -# For default that's set to 'yes' as it's almost always a win. -# If you want to save some CPU in the saving child set it to 'no' but -# the dataset will likely be bigger if you have compressible values or keys. -rdbcompression yes - -# Since version 5 of RDB a CRC64 checksum is placed at the end of the file. -# This makes the format more resistant to corruption but there is a performance -# hit to pay (around 10%) when saving and loading RDB files, so you can disable it -# for maximum performances. -# -# RDB files created with checksum disabled have a checksum of zero that will -# tell the loading code to skip the check. -rdbchecksum yes - -# The filename where to dump the DB -dbfilename dump.rdb - -# The working directory. -# -# The DB will be written inside this directory, with the filename specified -# above using the 'dbfilename' configuration directive. -# -# The Append Only File will also be created inside this directory. -# -# Note that you must specify a directory here, not a file name. -dir ./ - -################################# REPLICATION ################################# - -# Master-Replica replication. Use replicaof to make a Redis instance a copy of -# another Redis server. A few things to understand ASAP about Redis replication. -# -# +------------------+ +---------------+ -# | Master | ---> | Replica | -# | (receive writes) | | (exact copy) | -# +------------------+ +---------------+ -# -# 1) Redis replication is asynchronous, but you can configure a master to -# stop accepting writes if it appears to be not connected with at least -# a given number of replicas. -# 2) Redis replicas are able to perform a partial resynchronization with the -# master if the replication link is lost for a relatively small amount of -# time. You may want to configure the replication backlog size (see the next -# sections of this file) with a sensible value depending on your needs. -# 3) Replication is automatic and does not need user intervention. After a -# network partition replicas automatically try to reconnect to masters -# and resynchronize with them. -# -# replicaof - -# If the master is password protected (using the "requirepass" configuration -# directive below) it is possible to tell the replica to authenticate before -# starting the replication synchronization process, otherwise the master will -# refuse the replica request. -# -# masterauth - -# When a replica loses its connection with the master, or when the replication -# is still in progress, the replica can act in two different ways: -# -# 1) if replica-serve-stale-data is set to 'yes' (the default) the replica will -# still reply to client requests, possibly with out of date data, or the -# data set may just be empty if this is the first synchronization. -# -# 2) if replica-serve-stale-data is set to 'no' the replica will reply with -# an error "SYNC with master in progress" to all the kind of commands -# but to INFO, replicaOF, AUTH, PING, SHUTDOWN, REPLCONF, ROLE, CONFIG, -# SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB, -# COMMAND, POST, HOST: and LATENCY. -# -replica-serve-stale-data yes - -# You can configure a replica instance to accept writes or not. Writing against -# a replica instance may be useful to store some ephemeral data (because data -# written on a replica will be easily deleted after resync with the master) but -# may also cause problems if clients are writing to it because of a -# misconfiguration. -# -# Since Redis 2.6 by default replicas are read-only. -# -# Note: read only replicas are not designed to be exposed to untrusted clients -# on the internet. It's just a protection layer against misuse of the instance. -# Still a read only replica exports by default all the administrative commands -# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve -# security of read only replicas using 'rename-command' to shadow all the -# administrative / dangerous commands. -replica-read-only yes - -# Replication SYNC strategy: disk or socket. -# -# ------------------------------------------------------- -# WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY -# ------------------------------------------------------- -# -# New replicas and reconnecting replicas that are not able to continue the replication -# process just receiving differences, need to do what is called a "full -# synchronization". An RDB file is transmitted from the master to the replicas. -# The transmission can happen in two different ways: -# -# 1) Disk-backed: The Redis master creates a new process that writes the RDB -# file on disk. Later the file is transferred by the parent -# process to the replicas incrementally. -# 2) Diskless: The Redis master creates a new process that directly writes the -# RDB file to replica sockets, without touching the disk at all. -# -# With disk-backed replication, while the RDB file is generated, more replicas -# can be queued and served with the RDB file as soon as the current child producing -# the RDB file finishes its work. With diskless replication instead once -# the transfer starts, new replicas arriving will be queued and a new transfer -# will start when the current one terminates. -# -# When diskless replication is used, the master waits a configurable amount of -# time (in seconds) before starting the transfer in the hope that multiple replicas -# will arrive and the transfer can be parallelized. -# -# With slow disks and fast (large bandwidth) networks, diskless replication -# works better. -repl-diskless-sync no - -# When diskless replication is enabled, it is possible to configure the delay -# the server waits in order to spawn the child that transfers the RDB via socket -# to the replicas. -# -# This is important since once the transfer starts, it is not possible to serve -# new replicas arriving, that will be queued for the next RDB transfer, so the server -# waits a delay in order to let more replicas arrive. -# -# The delay is specified in seconds, and by default is 5 seconds. To disable -# it entirely just set it to 0 seconds and the transfer will start ASAP. -repl-diskless-sync-delay 5 - -# Replicas send PINGs to server in a predefined interval. It's possible to change -# this interval with the repl_ping_replica_period option. The default value is 10 -# seconds. -# -# repl-ping-replica-period 10 - -# The following option sets the replication timeout for: -# -# 1) Bulk transfer I/O during SYNC, from the point of view of replica. -# 2) Master timeout from the point of view of replicas (data, pings). -# 3) Replica timeout from the point of view of masters (REPLCONF ACK pings). -# -# It is important to make sure that this value is greater than the value -# specified for repl-ping-replica-period otherwise a timeout will be detected -# every time there is low traffic between the master and the replica. -# -# repl-timeout 60 - -# Disable TCP_NODELAY on the replica socket after SYNC? -# -# If you select "yes" Redis will use a smaller number of TCP packets and -# less bandwidth to send data to replicas. But this can add a delay for -# the data to appear on the replica side, up to 40 milliseconds with -# Linux kernels using a default configuration. -# -# If you select "no" the delay for data to appear on the replica side will -# be reduced but more bandwidth will be used for replication. -# -# By default we optimize for low latency, but in very high traffic conditions -# or when the master and replicas are many hops away, turning this to "yes" may -# be a good idea. -repl-disable-tcp-nodelay no - -# Set the replication backlog size. The backlog is a buffer that accumulates -# replica data when replicas are disconnected for some time, so that when a replica -# wants to reconnect again, often a full resync is not needed, but a partial -# resync is enough, just passing the portion of data the replica missed while -# disconnected. -# -# The bigger the replication backlog, the longer the time the replica can be -# disconnected and later be able to perform a partial resynchronization. -# -# The backlog is only allocated once there is at least a replica connected. -# -# repl-backlog-size 1mb - -# After a master has no longer connected replicas for some time, the backlog -# will be freed. The following option configures the amount of seconds that -# need to elapse, starting from the time the last replica disconnected, for -# the backlog buffer to be freed. -# -# Note that replicas never free the backlog for timeout, since they may be -# promoted to masters later, and should be able to correctly "partially -# resynchronize" with the replicas: hence they should always accumulate backlog. -# -# A value of 0 means to never release the backlog. -# -# repl-backlog-ttl 3600 - -# The replica priority is an integer number published by Redis in the INFO output. -# It is used by Redis Sentinel in order to select a replica to promote into a -# master if the master is no longer working correctly. -# -# A replica with a low priority number is considered better for promotion, so -# for instance if there are three replicas with priority 10, 100, 25 Sentinel will -# pick the one with priority 10, that is the lowest. -# -# However a special priority of 0 marks the replica as not able to perform the -# role of master, so a replica with priority of 0 will never be selected by -# Redis Sentinel for promotion. -# -# By default the priority is 100. -replica-priority 100 - -# It is possible for a master to stop accepting writes if there are less than -# N replicas connected, having a lag less or equal than M seconds. -# -# The N replicas need to be in "online" state. -# -# The lag in seconds, that must be <= the specified value, is calculated from -# the last ping received from the replica, that is usually sent every second. -# -# This option does not GUARANTEE that N replicas will accept the write, but -# will limit the window of exposure for lost writes in case not enough replicas -# are available, to the specified number of seconds. -# -# For example to require at least 3 replicas with a lag <= 10 seconds use: -# -# min-replicas-to-write 3 -# min-replicas-max-lag 10 -# -# Setting one or the other to 0 disables the feature. -# -# By default min-replicas-to-write is set to 0 (feature disabled) and -# min-replicas-max-lag is set to 10. - -# A Redis master is able to list the address and port of the attached -# replicas in different ways. For example the "INFO replication" section -# offers this information, which is used, among other tools, by -# Redis Sentinel in order to discover replica instances. -# Another place where this info is available is in the output of the -# "ROLE" command of a master. -# -# The listed IP and address normally reported by a replica is obtained -# in the following way: -# -# IP: The address is auto detected by checking the peer address -# of the socket used by the replica to connect with the master. -# -# Port: The port is communicated by the replica during the replication -# handshake, and is normally the port that the replica is using to -# listen for connections. -# -# However when port forwarding or Network Address Translation (NAT) is -# used, the replica may be actually reachable via different IP and port -# pairs. The following two options can be used by a replica in order to -# report to its master a specific set of IP and port, so that both INFO -# and ROLE will report those values. -# -# There is no need to use both the options if you need to override just -# the port or the IP address. -# -# replica-announce-ip 5.5.5.5 -# replica-announce-port 1234 - -################################## SECURITY ################################### - -# Require clients to issue AUTH before processing any other -# commands. This might be useful in environments in which you do not trust -# others with access to the host running redis-server. -# -# This should stay commented out for backward compatibility and because most -# people do not need auth (e.g. they run their own servers). -# -# Warning: since Redis is pretty fast an outside user can try up to -# 150k passwords per second against a good box. This means that you should -# use a very strong password otherwise it will be very easy to break. -# -# requirepass foobared - -# Command renaming. -# -# It is possible to change the name of dangerous commands in a shared -# environment. For instance the CONFIG command may be renamed into something -# hard to guess so that it will still be available for internal-use tools -# but not available for general clients. -# -# Example: -# -# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 -# -# It is also possible to completely kill a command by renaming it into -# an empty string: -# -# rename-command CONFIG "" -# -# Please note that changing the name of commands that are logged into the -# AOF file or transmitted to replicas may cause problems. - -################################### CLIENTS #################################### - -# Set the max number of connected clients at the same time. By default -# this limit is set to 10000 clients, however if the Redis server is not -# able to configure the process file limit to allow for the specified limit -# the max number of allowed clients is set to the current file limit -# minus 32 (as Redis reserves a few file descriptors for internal uses). -# -# Once the limit is reached Redis will close all the new connections sending -# an error 'max number of clients reached'. -# -# maxclients 10000 - -############################## MEMORY MANAGEMENT ################################ - -# Set a memory usage limit to the specified amount of bytes. -# When the memory limit is reached Redis will try to remove keys -# according to the eviction policy selected (see maxmemory-policy). -# -# If Redis can't remove keys according to the policy, or if the policy is -# set to 'noeviction', Redis will start to reply with errors to commands -# that would use more memory, like SET, LPUSH, and so on, and will continue -# to reply to read-only commands like GET. -# -# This option is usually useful when using Redis as an LRU or LFU cache, or to -# set a hard memory limit for an instance (using the 'noeviction' policy). -# -# WARNING: If you have replicas attached to an instance with maxmemory on, -# the size of the output buffers needed to feed the replicas are subtracted -# from the used memory count, so that network problems / resyncs will -# not trigger a loop where keys are evicted, and in turn the output -# buffer of replicas is full with DELs of keys evicted triggering the deletion -# of more keys, and so forth until the database is completely emptied. -# -# In short... if you have replicas attached it is suggested that you set a lower -# limit for maxmemory so that there is some free RAM on the system for replica -# output buffers (but this is not needed if the policy is 'noeviction'). -# -# maxmemory - -# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory -# is reached. You can select among five behaviors: -# -# volatile-lru -> Evict using approximated LRU among the keys with an expire set. -# allkeys-lru -> Evict any key using approximated LRU. -# volatile-lfu -> Evict using approximated LFU among the keys with an expire set. -# allkeys-lfu -> Evict any key using approximated LFU. -# volatile-random -> Remove a random key among the ones with an expire set. -# allkeys-random -> Remove a random key, any key. -# volatile-ttl -> Remove the key with the nearest expire time (minor TTL) -# noeviction -> Don't evict anything, just return an error on write operations. -# -# LRU means Least Recently Used -# LFU means Least Frequently Used -# -# Both LRU, LFU and volatile-ttl are implemented using approximated -# randomized algorithms. -# -# Note: with any of the above policies, Redis will return an error on write -# operations, when there are no suitable keys for eviction. -# -# At the date of writing these commands are: set setnx setex append -# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd -# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby -# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby -# getset mset msetnx exec sort -# -# The default is: -# -# maxmemory-policy noeviction - -# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated -# algorithms (in order to save memory), so you can tune it for speed or -# accuracy. For default Redis will check five keys and pick the one that was -# used less recently, you can change the sample size using the following -# configuration directive. -# -# The default of 5 produces good enough results. 10 Approximates very closely -# true LRU but costs more CPU. 3 is faster but not very accurate. -# -# maxmemory-samples 5 - -# Starting from Redis 5, by default a replica will ignore its maxmemory setting -# (unless it is promoted to master after a failover or manually). It means -# that the eviction of keys will be just handled by the master, sending the -# DEL commands to the replica as keys evict in the master side. -# -# This behavior ensures that masters and replicas stay consistent, and is usually -# what you want, however if your replica is writable, or you want the replica to have -# a different memory setting, and you are sure all the writes performed to the -# replica are idempotent, then you may change this default (but be sure to understand -# what you are doing). -# -# Note that since the replica by default does not evict, it may end using more -# memory than the one set via maxmemory (there are certain buffers that may -# be larger on the replica, or data structures may sometimes take more memory and so -# forth). So make sure you monitor your replicas and make sure they have enough -# memory to never hit a real out-of-memory condition before the master hits -# the configured maxmemory setting. -# -# replica-ignore-maxmemory yes - -############################# LAZY FREEING #################################### - -# Redis has two primitives to delete keys. One is called DEL and is a blocking -# deletion of the object. It means that the server stops processing new commands -# in order to reclaim all the memory associated with an object in a synchronous -# way. If the key deleted is associated with a small object, the time needed -# in order to execute the DEL command is very small and comparable to most other -# O(1) or O(log_N) commands in Redis. However if the key is associated with an -# aggregated value containing millions of elements, the server can block for -# a long time (even seconds) in order to complete the operation. -# -# For the above reasons Redis also offers non blocking deletion primitives -# such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and -# FLUSHDB commands, in order to reclaim memory in background. Those commands -# are executed in constant time. Another thread will incrementally free the -# object in the background as fast as possible. -# -# DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled. -# It's up to the design of the application to understand when it is a good -# idea to use one or the other. However the Redis server sometimes has to -# delete keys or flush the whole database as a side effect of other operations. -# Specifically Redis deletes objects independently of a user call in the -# following scenarios: -# -# 1) On eviction, because of the maxmemory and maxmemory policy configurations, -# in order to make room for new data, without going over the specified -# memory limit. -# 2) Because of expire: when a key with an associated time to live (see the -# EXPIRE command) must be deleted from memory. -# 3) Because of a side effect of a command that stores data on a key that may -# already exist. For example the RENAME command may delete the old key -# content when it is replaced with another one. Similarly SUNIONSTORE -# or SORT with STORE option may delete existing keys. The SET command -# itself removes any old content of the specified key in order to replace -# it with the specified string. -# 4) During replication, when a replica performs a full resynchronization with -# its master, the content of the whole database is removed in order to -# load the RDB file just transferred. -# -# In all the above cases the default is to delete objects in a blocking way, -# like if DEL was called. However you can configure each case specifically -# in order to instead release memory in a non-blocking way like if UNLINK -# was called, using the following configuration directives: - -lazyfree-lazy-eviction no -lazyfree-lazy-expire no -lazyfree-lazy-server-del no -replica-lazy-flush no - -############################## APPEND ONLY MODE ############################### - -# By default Redis asynchronously dumps the dataset on disk. This mode is -# good enough in many applications, but an issue with the Redis process or -# a power outage may result into a few minutes of writes lost (depending on -# the configured save points). -# -# The Append Only File is an alternative persistence mode that provides -# much better durability. For instance using the default data fsync policy -# (see later in the config file) Redis can lose just one second of writes in a -# dramatic event like a server power outage, or a single write if something -# wrong with the Redis process itself happens, but the operating system is -# still running correctly. -# -# AOF and RDB persistence can be enabled at the same time without problems. -# If the AOF is enabled on startup Redis will load the AOF, that is the file -# with the better durability guarantees. -# -# Please check http://redis.io/topics/persistence for more information. - -appendonly no - -# The name of the append only file (default: "appendonly.aof") - -appendfilename "appendonly.aof" - -# The fsync() call tells the Operating System to actually write data on disk -# instead of waiting for more data in the output buffer. Some OS will really flush -# data on disk, some other OS will just try to do it ASAP. -# -# Redis supports three different modes: -# -# no: don't fsync, just let the OS flush the data when it wants. Faster. -# always: fsync after every write to the append only log. Slow, Safest. -# everysec: fsync only one time every second. Compromise. -# -# The default is "everysec", as that's usually the right compromise between -# speed and data safety. It's up to you to understand if you can relax this to -# "no" that will let the operating system flush the output buffer when -# it wants, for better performances (but if you can live with the idea of -# some data loss consider the default persistence mode that's snapshotting), -# or on the contrary, use "always" that's very slow but a bit safer than -# everysec. -# -# More details please check the following article: -# http://antirez.com/post/redis-persistence-demystified.html -# -# If unsure, use "everysec". - -# appendfsync always -appendfsync everysec -# appendfsync no - -# When the AOF fsync policy is set to always or everysec, and a background -# saving process (a background save or AOF log background rewriting) is -# performing a lot of I/O against the disk, in some Linux configurations -# Redis may block too long on the fsync() call. Note that there is no fix for -# this currently, as even performing fsync in a different thread will block -# our synchronous write(2) call. -# -# In order to mitigate this problem it's possible to use the following option -# that will prevent fsync() from being called in the main process while a -# BGSAVE or BGREWRITEAOF is in progress. -# -# This means that while another child is saving, the durability of Redis is -# the same as "appendfsync none". In practical terms, this means that it is -# possible to lose up to 30 seconds of log in the worst scenario (with the -# default Linux settings). -# -# If you have latency problems turn this to "yes". Otherwise leave it as -# "no" that is the safest pick from the point of view of durability. - -no-appendfsync-on-rewrite no - -# Automatic rewrite of the append only file. -# Redis is able to automatically rewrite the log file implicitly calling -# BGREWRITEAOF when the AOF log size grows by the specified percentage. -# -# This is how it works: Redis remembers the size of the AOF file after the -# latest rewrite (if no rewrite has happened since the restart, the size of -# the AOF at startup is used). -# -# This base size is compared to the current size. If the current size is -# bigger than the specified percentage, the rewrite is triggered. Also -# you need to specify a minimal size for the AOF file to be rewritten, this -# is useful to avoid rewriting the AOF file even if the percentage increase -# is reached but it is still pretty small. -# -# Specify a percentage of zero in order to disable the automatic AOF -# rewrite feature. - -auto-aof-rewrite-percentage 100 -auto-aof-rewrite-min-size 64mb - -# An AOF file may be found to be truncated at the end during the Redis -# startup process, when the AOF data gets loaded back into memory. -# This may happen when the system where Redis is running -# crashes, especially when an ext4 filesystem is mounted without the -# data=ordered option (however this can't happen when Redis itself -# crashes or aborts but the operating system still works correctly). -# -# Redis can either exit with an error when this happens, or load as much -# data as possible (the default now) and start if the AOF file is found -# to be truncated at the end. The following option controls this behavior. -# -# If aof-load-truncated is set to yes, a truncated AOF file is loaded and -# the Redis server starts emitting a log to inform the user of the event. -# Otherwise if the option is set to no, the server aborts with an error -# and refuses to start. When the option is set to no, the user requires -# to fix the AOF file using the "redis-check-aof" utility before to restart -# the server. -# -# Note that if the AOF file will be found to be corrupted in the middle -# the server will still exit with an error. This option only applies when -# Redis will try to read more data from the AOF file but not enough bytes -# will be found. -aof-load-truncated yes - -# When rewriting the AOF file, Redis is able to use an RDB preamble in the -# AOF file for faster rewrites and recoveries. When this option is turned -# on the rewritten AOF file is composed of two different stanzas: -# -# [RDB file][AOF tail] -# -# When loading Redis recognizes that the AOF file starts with the "REDIS" -# string and loads the prefixed RDB file, and continues loading the AOF -# tail. -aof-use-rdb-preamble yes - -################################ LUA SCRIPTING ############################### - -# Max execution time of a Lua script in milliseconds. -# -# If the maximum execution time is reached Redis will log that a script is -# still in execution after the maximum allowed time and will start to -# reply to queries with an error. -# -# When a long running script exceeds the maximum execution time only the -# SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be -# used to stop a script that did not yet called write commands. The second -# is the only way to shut down the server in the case a write command was -# already issued by the script but the user doesn't want to wait for the natural -# termination of the script. -# -# Set it to 0 or a negative value for unlimited execution without warnings. -lua-time-limit 5000 - -################################ REDIS CLUSTER ############################### -# -# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -# WARNING EXPERIMENTAL: Redis Cluster is considered to be stable code, however -# in order to mark it as "mature" we need to wait for a non trivial percentage -# of users to deploy it in production. -# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -# -# Normal Redis instances can't be part of a Redis Cluster; only nodes that are -# started as cluster nodes can. In order to start a Redis instance as a -# cluster node enable the cluster support uncommenting the following: -# -# cluster-enabled yes - -# Every cluster node has a cluster configuration file. This file is not -# intended to be edited by hand. It is created and updated by Redis nodes. -# Every Redis Cluster node requires a different cluster configuration file. -# Make sure that instances running in the same system do not have -# overlapping cluster configuration file names. -# -# cluster-config-file nodes-6379.conf - -# Cluster node timeout is the amount of milliseconds a node must be unreachable -# for it to be considered in failure state. -# Most other internal time limits are multiple of the node timeout. -# -# cluster-node-timeout 15000 - -# A replica of a failing master will avoid to start a failover if its data -# looks too old. -# -# There is no simple way for a replica to actually have an exact measure of -# its "data age", so the following two checks are performed: -# -# 1) If there are multiple replicas able to failover, they exchange messages -# in order to try to give an advantage to the replica with the best -# replication offset (more data from the master processed). -# Replicas will try to get their rank by offset, and apply to the start -# of the failover a delay proportional to their rank. -# -# 2) Every single replica computes the time of the last interaction with -# its master. This can be the last ping or command received (if the master -# is still in the "connected" state), or the time that elapsed since the -# disconnection with the master (if the replication link is currently down). -# If the last interaction is too old, the replica will not try to failover -# at all. -# -# The point "2" can be tuned by user. Specifically a replica will not perform -# the failover if, since the last interaction with the master, the time -# elapsed is greater than: -# -# (node-timeout * replica-validity-factor) + repl-ping-replica-period -# -# So for example if node-timeout is 30 seconds, and the replica-validity-factor -# is 10, and assuming a default repl-ping-replica-period of 10 seconds, the -# replica will not try to failover if it was not able to talk with the master -# for longer than 310 seconds. -# -# A large replica-validity-factor may allow replicas with too old data to failover -# a master, while a too small value may prevent the cluster from being able to -# elect a replica at all. -# -# For maximum availability, it is possible to set the replica-validity-factor -# to a value of 0, which means, that replicas will always try to failover the -# master regardless of the last time they interacted with the master. -# (However they'll always try to apply a delay proportional to their -# offset rank). -# -# Zero is the only value able to guarantee that when all the partitions heal -# the cluster will always be able to continue. -# -# cluster-replica-validity-factor 10 - -# Cluster replicas are able to migrate to orphaned masters, that are masters -# that are left without working replicas. This improves the cluster ability -# to resist to failures as otherwise an orphaned master can't be failed over -# in case of failure if it has no working replicas. -# -# Replicas migrate to orphaned masters only if there are still at least a -# given number of other working replicas for their old master. This number -# is the "migration barrier". A migration barrier of 1 means that a replica -# will migrate only if there is at least 1 other working replica for its master -# and so forth. It usually reflects the number of replicas you want for every -# master in your cluster. -# -# Default is 1 (replicas migrate only if their masters remain with at least -# one replica). To disable migration just set it to a very large value. -# A value of 0 can be set but is useful only for debugging and dangerous -# in production. -# -# cluster-migration-barrier 1 - -# By default Redis Cluster nodes stop accepting queries if they detect there -# is at least an hash slot uncovered (no available node is serving it). -# This way if the cluster is partially down (for example a range of hash slots -# are no longer covered) all the cluster becomes, eventually, unavailable. -# It automatically returns available as soon as all the slots are covered again. -# -# However sometimes you want the subset of the cluster which is working, -# to continue to accept queries for the part of the key space that is still -# covered. In order to do so, just set the cluster-require-full-coverage -# option to no. -# -# cluster-require-full-coverage yes - -# This option, when set to yes, prevents replicas from trying to failover its -# master during master failures. However the master can still perform a -# manual failover, if forced to do so. -# -# This is useful in different scenarios, especially in the case of multiple -# data center operations, where we want one side to never be promoted if not -# in the case of a total DC failure. -# -# cluster-replica-no-failover no - -# In order to setup your cluster make sure to read the documentation -# available at http://redis.io web site. - -########################## CLUSTER DOCKER/NAT support ######################## - -# In certain deployments, Redis Cluster nodes address discovery fails, because -# addresses are NAT-ted or because ports are forwarded (the typical case is -# Docker and other containers). -# -# In order to make Redis Cluster working in such environments, a static -# configuration where each node knows its public address is needed. The -# following two options are used for this scope, and are: -# -# * cluster-announce-ip -# * cluster-announce-port -# * cluster-announce-bus-port -# -# Each instruct the node about its address, client port, and cluster message -# bus port. The information is then published in the header of the bus packets -# so that other nodes will be able to correctly map the address of the node -# publishing the information. -# -# If the above options are not used, the normal Redis Cluster auto-detection -# will be used instead. -# -# Note that when remapped, the bus port may not be at the fixed offset of -# clients port + 10000, so you can specify any port and bus-port depending -# on how they get remapped. If the bus-port is not set, a fixed offset of -# 10000 will be used as usually. -# -# Example: -# -# cluster-announce-ip 10.1.1.5 -# cluster-announce-port 6379 -# cluster-announce-bus-port 6380 - -################################## SLOW LOG ################################### - -# The Redis Slow Log is a system to log queries that exceeded a specified -# execution time. The execution time does not include the I/O operations -# like talking with the client, sending the reply and so forth, -# but just the time needed to actually execute the command (this is the only -# stage of command execution where the thread is blocked and can not serve -# other requests in the meantime). -# -# You can configure the slow log with two parameters: one tells Redis -# what is the execution time, in microseconds, to exceed in order for the -# command to get logged, and the other parameter is the length of the -# slow log. When a new command is logged the oldest one is removed from the -# queue of logged commands. - -# The following time is expressed in microseconds, so 1000000 is equivalent -# to one second. Note that a negative number disables the slow log, while -# a value of zero forces the logging of every command. -slowlog-log-slower-than 10000 - -# There is no limit to this length. Just be aware that it will consume memory. -# You can reclaim memory used by the slow log with SLOWLOG RESET. -slowlog-max-len 128 - -################################ LATENCY MONITOR ############################## - -# The Redis latency monitoring subsystem samples different operations -# at runtime in order to collect data related to possible sources of -# latency of a Redis instance. -# -# Via the LATENCY command this information is available to the user that can -# print graphs and obtain reports. -# -# The system only logs operations that were performed in a time equal or -# greater than the amount of milliseconds specified via the -# latency-monitor-threshold configuration directive. When its value is set -# to zero, the latency monitor is turned off. -# -# By default latency monitoring is disabled since it is mostly not needed -# if you don't have latency issues, and collecting data has a performance -# impact, that while very small, can be measured under big load. Latency -# monitoring can easily be enabled at runtime using the command -# "CONFIG SET latency-monitor-threshold " if needed. -latency-monitor-threshold 0 - -############################# EVENT NOTIFICATION ############################## - -# Redis can notify Pub/Sub clients about events happening in the key space. -# This feature is documented at http://redis.io/topics/notifications -# -# For instance if keyspace events notification is enabled, and a client -# performs a DEL operation on key "foo" stored in the Database 0, two -# messages will be published via Pub/Sub: -# -# PUBLISH __keyspace@0__:foo del -# PUBLISH __keyevent@0__:del foo -# -# It is possible to select the events that Redis will notify among a set -# of classes. Every class is identified by a single character: -# -# K Keyspace events, published with __keyspace@__ prefix. -# E Keyevent events, published with __keyevent@__ prefix. -# g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... -# $ String commands -# l List commands -# s Set commands -# h Hash commands -# z Sorted set commands -# x Expired events (events generated every time a key expires) -# e Evicted events (events generated when a key is evicted for maxmemory) -# A Alias for g$lshzxe, so that the "AKE" string means all the events. -# -# The "notify-keyspace-events" takes as argument a string that is composed -# of zero or multiple characters. The empty string means that notifications -# are disabled. -# -# Example: to enable list and generic events, from the point of view of the -# event name, use: -# -# notify-keyspace-events Elg -# -# Example 2: to get the stream of the expired keys subscribing to channel -# name __keyevent@0__:expired use: -# -# notify-keyspace-events Ex -# -# By default all notifications are disabled because most users don't need -# this feature and the feature has some overhead. Note that if you don't -# specify at least one of K or E, no events will be delivered. -notify-keyspace-events "" - -############################### ADVANCED CONFIG ############################### - -# Hashes are encoded using a memory efficient data structure when they have a -# small number of entries, and the biggest entry does not exceed a given -# threshold. These thresholds can be configured using the following directives. -hash-max-ziplist-entries 512 -hash-max-ziplist-value 64 - -# Lists are also encoded in a special way to save a lot of space. -# The number of entries allowed per internal list node can be specified -# as a fixed maximum size or a maximum number of elements. -# For a fixed maximum size, use -5 through -1, meaning: -# -5: max size: 64 Kb <-- not recommended for normal workloads -# -4: max size: 32 Kb <-- not recommended -# -3: max size: 16 Kb <-- probably not recommended -# -2: max size: 8 Kb <-- good -# -1: max size: 4 Kb <-- good -# Positive numbers mean store up to _exactly_ that number of elements -# per list node. -# The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size), -# but if your use case is unique, adjust the settings as necessary. -list-max-ziplist-size -2 - -# Lists may also be compressed. -# Compress depth is the number of quicklist ziplist nodes from *each* side of -# the list to *exclude* from compression. The head and tail of the list -# are always uncompressed for fast push/pop operations. Settings are: -# 0: disable all list compression -# 1: depth 1 means "don't start compressing until after 1 node into the list, -# going from either the head or tail" -# So: [head]->node->node->...->node->[tail] -# [head], [tail] will always be uncompressed; inner nodes will compress. -# 2: [head]->[next]->node->node->...->node->[prev]->[tail] -# 2 here means: don't compress head or head->next or tail->prev or tail, -# but compress all nodes between them. -# 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail] -# etc. -list-compress-depth 0 - -# Sets have a special encoding in just one case: when a set is composed -# of just strings that happen to be integers in radix 10 in the range -# of 64 bit signed integers. -# The following configuration setting sets the limit in the size of the -# set in order to use this special memory saving encoding. -set-max-intset-entries 512 - -# Similarly to hashes and lists, sorted sets are also specially encoded in -# order to save a lot of space. This encoding is only used when the length and -# elements of a sorted set are below the following limits: -zset-max-ziplist-entries 128 -zset-max-ziplist-value 64 - -# HyperLogLog sparse representation bytes limit. The limit includes the -# 16 bytes header. When an HyperLogLog using the sparse representation crosses -# this limit, it is converted into the dense representation. -# -# A value greater than 16000 is totally useless, since at that point the -# dense representation is more memory efficient. -# -# The suggested value is ~ 3000 in order to have the benefits of -# the space efficient encoding without slowing down too much PFADD, -# which is O(N) with the sparse encoding. The value can be raised to -# ~ 10000 when CPU is not a concern, but space is, and the data set is -# composed of many HyperLogLogs with cardinality in the 0 - 15000 range. -hll-sparse-max-bytes 3000 - -# Streams macro node max size / items. The stream data structure is a radix -# tree of big nodes that encode multiple items inside. Using this configuration -# it is possible to configure how big a single node can be in bytes, and the -# maximum number of items it may contain before switching to a new node when -# appending new stream entries. If any of the following settings are set to -# zero, the limit is ignored, so for instance it is possible to set just a -# max entires limit by setting max-bytes to 0 and max-entries to the desired -# value. -stream-node-max-bytes 4096 -stream-node-max-entries 100 - -# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in -# order to help rehashing the main Redis hash table (the one mapping top-level -# keys to values). The hash table implementation Redis uses (see dict.c) -# performs a lazy rehashing: the more operation you run into a hash table -# that is rehashing, the more rehashing "steps" are performed, so if the -# server is idle the rehashing is never complete and some more memory is used -# by the hash table. -# -# The default is to use this millisecond 10 times every second in order to -# actively rehash the main dictionaries, freeing memory when possible. -# -# If unsure: -# use "activerehashing no" if you have hard latency requirements and it is -# not a good thing in your environment that Redis can reply from time to time -# to queries with 2 milliseconds delay. -# -# use "activerehashing yes" if you don't have such hard requirements but -# want to free memory asap when possible. -activerehashing yes - -# The client output buffer limits can be used to force disconnection of clients -# that are not reading data from the server fast enough for some reason (a -# common reason is that a Pub/Sub client can't consume messages as fast as the -# publisher can produce them). -# -# The limit can be set differently for the three different classes of clients: -# -# normal -> normal clients including MONITOR clients -# replica -> replica clients -# pubsub -> clients subscribed to at least one pubsub channel or pattern -# -# The syntax of every client-output-buffer-limit directive is the following: -# -# client-output-buffer-limit -# -# A client is immediately disconnected once the hard limit is reached, or if -# the soft limit is reached and remains reached for the specified number of -# seconds (continuously). -# So for instance if the hard limit is 32 megabytes and the soft limit is -# 16 megabytes / 10 seconds, the client will get disconnected immediately -# if the size of the output buffers reach 32 megabytes, but will also get -# disconnected if the client reaches 16 megabytes and continuously overcomes -# the limit for 10 seconds. -# -# By default normal clients are not limited because they don't receive data -# without asking (in a push way), but just after a request, so only -# asynchronous clients may create a scenario where data is requested faster -# than it can read. -# -# Instead there is a default limit for pubsub and replica clients, since -# subscribers and replicas receive data in a push fashion. -# -# Both the hard or the soft limit can be disabled by setting them to zero. -client-output-buffer-limit normal 0 0 0 -client-output-buffer-limit replica 256mb 64mb 60 -client-output-buffer-limit pubsub 32mb 8mb 60 - -# Client query buffers accumulate new commands. They are limited to a fixed -# amount by default in order to avoid that a protocol desynchronization (for -# instance due to a bug in the client) will lead to unbound memory usage in -# the query buffer. However you can configure it here if you have very special -# needs, such us huge multi/exec requests or alike. -# -# client-query-buffer-limit 1gb - -# In the Redis protocol, bulk requests, that are, elements representing single -# strings, are normally limited ot 512 mb. However you can change this limit -# here. -# -# proto-max-bulk-len 512mb - -# Redis calls an internal function to perform many background tasks, like -# closing connections of clients in timeout, purging expired keys that are -# never requested, and so forth. -# -# Not all tasks are performed with the same frequency, but Redis checks for -# tasks to perform according to the specified "hz" value. -# -# By default "hz" is set to 10. Raising the value will use more CPU when -# Redis is idle, but at the same time will make Redis more responsive when -# there are many keys expiring at the same time, and timeouts may be -# handled with more precision. -# -# The range is between 1 and 500, however a value over 100 is usually not -# a good idea. Most users should use the default of 10 and raise this up to -# 100 only in environments where very low latency is required. -hz 10 - -# Normally it is useful to have an HZ value which is proportional to the -# number of clients connected. This is useful in order, for instance, to -# avoid too many clients are processed for each background task invocation -# in order to avoid latency spikes. -# -# Since the default HZ value by default is conservatively set to 10, Redis -# offers, and enables by default, the ability to use an adaptive HZ value -# which will temporary raise when there are many connected clients. -# -# When dynamic HZ is enabled, the actual configured HZ will be used as -# as a baseline, but multiples of the configured HZ value will be actually -# used as needed once more clients are connected. In this way an idle -# instance will use very little CPU time while a busy instance will be -# more responsive. -dynamic-hz yes - -# When a child rewrites the AOF file, if the following option is enabled -# the file will be fsync-ed every 32 MB of data generated. This is useful -# in order to commit the file to the disk more incrementally and avoid -# big latency spikes. -aof-rewrite-incremental-fsync yes - -# When redis saves RDB file, if the following option is enabled -# the file will be fsync-ed every 32 MB of data generated. This is useful -# in order to commit the file to the disk more incrementally and avoid -# big latency spikes. -rdb-save-incremental-fsync yes - -# Redis LFU eviction (see maxmemory setting) can be tuned. However it is a good -# idea to start with the default settings and only change them after investigating -# how to improve the performances and how the keys LFU change over time, which -# is possible to inspect via the OBJECT FREQ command. -# -# There are two tunable parameters in the Redis LFU implementation: the -# counter logarithm factor and the counter decay time. It is important to -# understand what the two parameters mean before changing them. -# -# The LFU counter is just 8 bits per key, it's maximum value is 255, so Redis -# uses a probabilistic increment with logarithmic behavior. Given the value -# of the old counter, when a key is accessed, the counter is incremented in -# this way: -# -# 1. A random number R between 0 and 1 is extracted. -# 2. A probability P is calculated as 1/(old_value*lfu_log_factor+1). -# 3. The counter is incremented only if R < P. -# -# The default lfu-log-factor is 10. This is a table of how the frequency -# counter changes with a different number of accesses with different -# logarithmic factors: -# -# +--------+------------+------------+------------+------------+------------+ -# | factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits | -# +--------+------------+------------+------------+------------+------------+ -# | 0 | 104 | 255 | 255 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 1 | 18 | 49 | 255 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 10 | 10 | 18 | 142 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 100 | 8 | 11 | 49 | 143 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# -# NOTE: The above table was obtained by running the following commands: -# -# redis-benchmark -n 1000000 incr foo -# redis-cli object freq foo -# -# NOTE 2: The counter initial value is 5 in order to give new objects a chance -# to accumulate hits. -# -# The counter decay time is the time, in minutes, that must elapse in order -# for the key counter to be divided by two (or decremented if it has a value -# less <= 10). -# -# The default value for the lfu-decay-time is 1. A Special value of 0 means to -# decay the counter every time it happens to be scanned. -# -# lfu-log-factor 10 -# lfu-decay-time 1 - -########################### ACTIVE DEFRAGMENTATION ####################### -# -# WARNING THIS FEATURE IS EXPERIMENTAL. However it was stress tested -# even in production and manually tested by multiple engineers for some -# time. -# -# What is active defragmentation? -# ------------------------------- -# -# Active (online) defragmentation allows a Redis server to compact the -# spaces left between small allocations and deallocations of data in memory, -# thus allowing to reclaim back memory. -# -# Fragmentation is a natural process that happens with every allocator (but -# less so with Jemalloc, fortunately) and certain workloads. Normally a server -# restart is needed in order to lower the fragmentation, or at least to flush -# away all the data and create it again. However thanks to this feature -# implemented by Oran Agra for Redis 4.0 this process can happen at runtime -# in an "hot" way, while the server is running. -# -# Basically when the fragmentation is over a certain level (see the -# configuration options below) Redis will start to create new copies of the -# values in contiguous memory regions by exploiting certain specific Jemalloc -# features (in order to understand if an allocation is causing fragmentation -# and to allocate it in a better place), and at the same time, will release the -# old copies of the data. This process, repeated incrementally for all the keys -# will cause the fragmentation to drop back to normal values. -# -# Important things to understand: -# -# 1. This feature is disabled by default, and only works if you compiled Redis -# to use the copy of Jemalloc we ship with the source code of Redis. -# This is the default with Linux builds. -# -# 2. You never need to enable this feature if you don't have fragmentation -# issues. -# -# 3. Once you experience fragmentation, you can enable this feature when -# needed with the command "CONFIG SET activedefrag yes". -# -# The configuration parameters are able to fine tune the behavior of the -# defragmentation process. If you are not sure about what they mean it is -# a good idea to leave the defaults untouched. - -# Enabled active defragmentation -# activedefrag yes - -# Minimum amount of fragmentation waste to start active defrag -# active-defrag-ignore-bytes 100mb - -# Minimum percentage of fragmentation to start active defrag -# active-defrag-threshold-lower 10 - -# Maximum percentage of fragmentation at which we use maximum effort -# active-defrag-threshold-upper 100 - -# Minimal effort for defrag in CPU percentage -# active-defrag-cycle-min 5 - -# Maximal effort for defrag in CPU percentage -# active-defrag-cycle-max 75 - -# Maximum number of set/hash/zset/list fields that will be processed from -# the main dictionary scan -# active-defrag-max-scan-fields 1000 diff --git a/.ci/paho_tests/.env b/.ci/paho_tests/.env deleted file mode 100644 index 154ffe0911..0000000000 --- a/.ci/paho_tests/.env +++ /dev/null @@ -1 +0,0 @@ -IMAGE=emqx/emqx:latest \ No newline at end of file diff --git a/.ci/paho_tests/Makefile b/.ci/paho_tests/Makefile deleted file mode 100644 index b0bc071f8e..0000000000 --- a/.ci/paho_tests/Makefile +++ /dev/null @@ -1,54 +0,0 @@ -## default globals -TARGET ?= emqx/emqx -EMQX_NAME = $(subst emqx/,,$(TARGET)) - -## versioning -EMQX_DEPS_DEFAULT_VSN ?= develop -PAHO_BRANCH ?= develop-4.0 - - -.PHONY: all -all: test - -define wait_emqx - @while [ "$$(docker inspect -f '{{ .State.Health.Status}}' $$(docker ps -a -q -f name=paho_test_emqx1))" != "healthy" ] || [ "$$(docker inspect -f '{{ .State.Health.Status}}' $$(docker ps -a -q -f name=paho_test_emqx2))" != "healthy" ]; do \ - if [ $$(docker ps -a -f name=paho_test_emqx -f status=exited -q | wc -l) -ne 0 ]; then \ - echo "['$$(date -u +"%Y-%m-%dT%H:%M:%SZ")']:emqx stop"; \ - exit; \ - else \ - echo "['$$(date -u +"%Y-%m-%dT%H:%M:%SZ")']:waiting emqx"; \ - sleep 5; \ - fi; \ - done -endef - -.PHONY: create_container -create_container: clean - @sed -i "/IMAGE=/c\IMAGE=$(TARGET):$(EMQX_DEPS_DEFAULT_VSN:v%=%)" .env - - @docker-compose -p paho_test up -d - - $(call wait_emqx) - -.PHONY: test -test: create_container - @docker exec -i $$(docker ps -a -q -f name=paho_test_client) sh -c "apk update && apk add git curl \ - && git clone -b $(PAHO_BRANCH) https://hub.fastgit.org/emqx/paho.mqtt.testing.git /paho.mqtt.testing \ - && pip install pytest \ - && pytest -v /paho.mqtt.testing/interoperability/test_client/ --host node1.emqx.io" - - @docker-compose -p paho_test down - -.PHONY: cluster_test -cluster_test: create_container - @docker exec -i $$(docker ps -a -q -f name=paho_test_client) sh -c "apk update && apk add git curl \ - && git clone -b $(PAHO_BRANCH) https://hub.fastgit.org/emqx/paho.mqtt.testing.git /paho.mqtt.testing \ - && pip install pytest \ - && pytest -v /paho.mqtt.testing/interoperability/test_client/V5/test_connect.py -k test_basic --host node1.emqx.io \ - && pytest -v /paho.mqtt.testing/interoperability/test_cluster --host1 node1.emqx.io --host2 node2.emqx.io" - - @docker-compose -p paho_test down - -.PHONY: clean -clean: - @if [ ! -z "$$(docker ps -a -q -f name=paho_test)" ]; then docker-compose -p paho_test down; fi \ No newline at end of file diff --git a/.ci/paho_tests/docker-compose.yaml b/.ci/paho_tests/docker-compose.yaml deleted file mode 100644 index c316c64d21..0000000000 --- a/.ci/paho_tests/docker-compose.yaml +++ /dev/null @@ -1,65 +0,0 @@ -version: '3' - -services: - emqx1: - image: ${IMAGE} - environment: - - "EMQX_NAME=emqx" - - "EMQX_HOST=node1.emqx.io" - - "EMQX_CLUSTER__DISCOVERY=static" - - "EMQX_CLUSTER__STATIC__SEEDS=emqx@node1.emqx.io, emqx@node2.emqx.io" - - "EMQX_ZONE__EXTERNAL__RETRY_INTERVAL=2s" - - "EMQX_MQTT__MAX_TOPIC_ALIAS=10" - command: - - /bin/sh - - -c - - | - sed -i "s 127.0.0.1 $$(ip route show |grep "link" |awk '{print $$1}') g" /opt/emqx/etc/acl.conf - /usr/bin/start.sh - healthcheck: - test: ["CMD", "/opt/emqx/bin/emqx_ctl", "status"] - interval: 5s - timeout: 25s - retries: 5 - networks: - emqx-bridge: - aliases: - - node1.emqx.io - - emqx2: - image: ${IMAGE} - environment: - - "EMQX_NAME=emqx" - - "EMQX_HOST=node2.emqx.io" - - "EMQX_CLUSTER__DISCOVERY=static" - - "EMQX_CLUSTER__STATIC__SEEDS=emqx@node1.emqx.io, emqx@node2.emqx.io" - - "EMQX_ZONE__EXTERNAL__RETRY_INTERVAL=2s" - - "EMQX_MQTT__MAX_TOPIC_ALIAS=10" - command: - - /bin/sh - - -c - - | - sed -i "s 127.0.0.1 $$(ip route show |grep "link" |awk '{print $$1}') g" /opt/emqx/etc/acl.conf - /usr/bin/start.sh - healthcheck: - test: ["CMD", "/opt/emqx/bin/emqx_ctl", "status"] - interval: 5s - timeout: 25s - retries: 5 - networks: - emqx-bridge: - aliases: - - node2.emqx.io - - client: - image: python:3.7.2-alpine3.9 - depends_on: - - emqx1 - - emqx2 - tty: true - networks: - emqx-bridge: - -networks: - emqx-bridge: - driver: bridge diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 44446e3517..0000000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 9661ac7134..0000000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Makefile b/Makefile index 346a144c0c..1144648098 100644 --- a/Makefile +++ b/Makefile @@ -22,36 +22,11 @@ REBAR_URL = https://s3.amazonaws.com/rebar3/rebar3 export EMQX_DEPS_DEFAULT_VSN -PROFILE ?= emqx -PROFILES := emqx emqx-edge -PKG_PROFILES := emqx-pkg emqx-edge-pkg - -CT_APPS := emqx \ - emqx_auth_clientid \ - emqx_auth_http \ - emqx_auth_jwt \ - emqx_auth_ldap \ - emqx_auth_mongo \ - emqx_auth_mysql \ - emqx_auth_pgsql \ - emqx_auth_redis \ - emqx_auth_username \ - emqx_auth_mnesia \ - emqx_sasl \ - emqx_coap \ - emqx_recon \ - emqx_dashboard \ - emqx_delayed_publish \ - emqx_lua_hook \ - emqx_lwm2m \ - emqx_management \ - emqx_retainer \ - emqx_sn \ - emqx_stomp \ - emqx_web_hook \ - emqx_bridge_mqtt \ - emqx_rule_engine \ - emqx_extension_hook +PROFILE ?= dgiot +PROFILES := dgiot dgiot-edge +PKG_PROFILES := dgiot-pkg dgiot-edge-pkg + +CT_APPS := dgiot .PHONY: default default: $(REBAR) $(PROFILE) @@ -115,9 +90,9 @@ checkout: .PHONY: $(REBAR) $(CT_APPS:%=ct-%) ct: $(CT_APPS:%=ct-%) $(CT_APPS:%=ct-%): checkout-$(PROFILE) - -make -C _build/emqx/lib/$(@:ct-%=%) ct + -make -C _build/dgiot/lib/$(@:ct-%=%) ct @mkdir -p tests/logs/$(@:ct-%=%) - @if [ -d _build/emqx/lib/$(@:ct-%=%)/_build/test/logs ]; then cp -r _build/emqx/lib/$(@:ct-%=%)/_build/test/logs/* tests/logs/$(@:ct-%=%); fi + @if [ -d _build/dgiot/lib/$(@:ct-%=%)/_build/test/logs ]; then cp -r _build/dgiot/lib/$(@:ct-%=%)/_build/test/logs/* tests/logs/$(@:ct-%=%); fi $(REBAR): ifneq ($(wildcard rebar3),rebar3) @@ -129,44 +104,44 @@ endif .PHONY: $(PKG_PROFILES) $(PKG_PROFILES:%=%): $(REBAR) ln -snf _build/$(@)/lib ./_checkouts - @if [ $$(echo $(@) |grep edge) ];then export EMQX_DESC="EMQ X Edge";else export EMQX_DESC="EMQ X Broker"; fi;\ + @if [ $$(echo $(@) |grep edge) ];then export DGIOT_DESC="DGIOT X Edge";else export DGIOT_DESC="DGIOT X Broker"; fi;\ $(REBAR) as $(@) release - EMQX_REL=$$(pwd) EMQX_BUILD=$(@) EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/packages + DGIOT_REL=$$(pwd) DGIOT_BUILD=$(@) EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/packages # Build docker image .PHONY: $(PROFILES:%=%-docker-build) $(PROFILES:%=%-docker-build): @if [ ! -z `echo $(@) |grep -oE edge` ]; then \ - TARGET=emqx/emqx-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker; \ + TARGET=dgiot/dgiot-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker; \ else \ - TARGET=emqx/emqx EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker; \ + TARGET=dgiot/dgiot EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker; \ fi; # Save docker images .PHONY: $(PROFILES:%=%-docker-save) $(PROFILES:%=%-docker-save): @if [ ! -z `echo $(@) |grep -oE edge` ]; then \ - TARGET=emqx/emqx-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker save; \ + TARGET=dgiot/dgiot-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker save; \ else \ - TARGET=emqx/emqx EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker save; \ + TARGET=dgiot/dgiot EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker save; \ fi; # Push docker image .PHONY: $(PROFILES:%=%-docker-push) $(PROFILES:%=%-docker-push): @if [ ! -z `echo $(@) |grep -oE edge` ]; then \ - TARGET=emqx/emqx-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker push; \ - TARGET=emqx/emqx-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker manifest_list; \ + TARGET=dgiot/dgiot-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker push; \ + TARGET=dgiot/dgiot-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker manifest_list; \ else \ - TARGET=emqx/emqx EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker push; \ - TARGET=emqx/emqx EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker manifest_list; \ + TARGET=dgiot/dgiot EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker push; \ + TARGET=dgiot/dgiot EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker manifest_list; \ fi; # Clean docker image .PHONY: $(PROFILES:%=%-docker-clean) $(PROFILES:%=%-docker-clean): @if [ ! -z `echo $(@) |grep -oE edge` ]; then \ - TARGET=emqx/emqx-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker clean; \ + TARGET=dgiot/dgiot-edge EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker clean; \ else \ - TARGET=emqx/emqx EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker clean; \ + TARGET=dgiot/dgiot EMQX_DEPS_DEFAULT_VSN=$(EMQX_DEPS_DEFAULT_VSN) make -C deploy/docker clean; \ fi; diff --git a/_build/default/plugins/coveralls/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/coveralls/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index 63d749706f..0000000000 Binary files a/_build/default/plugins/coveralls/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/coveralls/README.md b/_build/default/plugins/coveralls/README.md deleted file mode 100644 index eecfbb037b..0000000000 --- a/_build/default/plugins/coveralls/README.md +++ /dev/null @@ -1,126 +0,0 @@ -coveralls-erl -============= -[![Build Status](https://travis-ci.org/markusn/coveralls-erl.png?branch=master)](https://travis-ci.org/markusn/coveralls-erl) -[![Coverage Status](https://coveralls.io/repos/markusn/coveralls-erl/badge.png?branch=master)](https://coveralls.io/r/markusn/coveralls-erl?branch=master) -[![Hex.pm](https://img.shields.io/hexpm/v/coveralls.svg?style=flat)](https://hex.pm/packages/coveralls) - -Erlang module to convert and send cover data to coveralls. Available as a hex package on https://hex.pm/packages/coveralls. - -## Example usage: rebar3 and Travis CI -In order to use coveralls-erl + Travis CI in your project you will need to add the following lines to your -`rebar.config.script`: - -```erlang -case os:getenv("TRAVIS") of - "true" -> - JobId = os:getenv("TRAVIS_JOB_ID"), - lists:keystore(coveralls_service_job_id, 1, CONFIG, {coveralls_service_job_id, JobId}); - _ -> - CONFIG -end. -``` - -This will ensure that the rebar coveralls plugin will have access to the needed JobId and that the plugin is only run from Travis CI. - -You will also need to add the following lines to your `rebar.config`: -```erlang -{plugins , [coveralls]}. % use hex package -{cover_enabled , true}. -{cover_export_enabled , true}. -{coveralls_coverdata , "_build/test/cover/eunit.coverdata"}. % or a string with wildcards or a list of files -{coveralls_service_name , "travis-ci"}. % use "travis-pro" when using with travis-ci.com -``` -When using with travis-ci.com coveralls repo token also has to be added as `{coveralls_repo_token, "token_goes_here"}` - -These changes will add `coveralls-erl` as a dependency, tell `rebar3` where to find the plugin, make sure that the coverage data is produced and exported and configure `coveralls-erl` to use this data and the service `travis-ci`. - -And you send the coverdata to coveralls by issuing: `rebar3 as test coveralls send` - -**Note:** -If you have dependencies specific to the test profile, or if you only add the coveralls dependency or any of its' configuration variables to the test profile you need to run coveralls using: `rebar3 as test coveralls send` - -## Example: rebar3 and CircleCI -Example `rebar.config.script`: - -```erlang -case {os:getenv("CIRCLECI"), os:getenv("COVERALLS_REPO_TOKEN")} of - {"true", Token} when is_list(Token) -> - JobId = os:getenv("CIRCLE_BUILD_NUM"), - CONFIG1 = lists:keystore(coveralls_service_job_id, 1, CONFIG, {coveralls_service_job_id, JobId}), - lists:keystore(coveralls_repo_token, 1, CONFIG1, {coveralls_repo_token, Token}); - _ -> - CONFIG -end. -``` - -Example `rebar.config`: - -```erlang - -{plugins , [coveralls]}. % use hex package -{cover_enabled , true}. -{cover_export_enabled , true}. -{coveralls_coverdata , "_build/test/cover/ct.coverdata"}. -{coveralls_service_name , "circle-ci"}. -``` - -Note that you'll need to set `COVERALLS_REPO_TOKEN` in your CircleCI environment variables! - -## Example usage: rebar3 and GitHub Actions - -In order to use coveralls-erl + GitHub Actions in your project, you will need to add the following lines to your -`rebar.config.script`: - -```erlang -case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of - {"true", Token} when is_list(Token) -> - CONFIG1 = [{coveralls_repo_token, Token}, - {coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")}, - {coveralls_commit_sha, os:getenv("GITHUB_SHA")}, - {coveralls_service_number, os:getenv("GITHUB_RUN_NUMBER")} | CONFIG], - case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request" - andalso string:tokens(os:getenv("GITHUB_REF"), "/") of - [_, "pull", PRNO, _] -> - [{coveralls_service_pull_request, PRNO} | CONFIG1]; - _ -> - CONFIG1 - end; - _ -> - CONFIG -end. -``` - -This will ensure that the rebar coveralls plugin will have access to the needed JobId and that the plugin is only run from GitHub Actions. - -You will also need to add the following lines to your `rebar.config`: -```erlang -{plugins , [coveralls]}. % use hex package -{cover_enabled , true}. -{cover_export_enabled , true}. -{coveralls_coverdata , "_build/test/cover/eunit.coverdata"}. % or a string with wildcards or a list of files -{coveralls_service_name , "github"}. -``` - -These changes will add `coveralls-erl` as a dependency, tell `rebar3` where to find the plugin, make sure that the coverage data is produced and exported and configure `coveralls-erl` to use this data and the service `github`. - -And you send the coverdata to coveralls by adding a step like: - -``` -- name: Coveralls - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: rebar3 as test coveralls send -``` - -Other available GitHub Actions Environment Variables are available [here](https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables) - -## Optional settings - -The pluging also support the `coveralls_service_pull_request` and `coveralls_parallel` settings. -See the Coveralls documentation for the meaning of those. - -## Author -Markus Ekholm (markus at botten dot org). - -## License -3-clause BSD. For details see `COPYING`. diff --git a/_build/default/plugins/coveralls/hex_metadata.config b/_build/default/plugins/coveralls/hex_metadata.config deleted file mode 100644 index 986fcae0ef..0000000000 --- a/_build/default/plugins/coveralls/hex_metadata.config +++ /dev/null @@ -1,17 +0,0 @@ -{<<"name">>,<<"coveralls">>}. -{<<"version">>,<<"2.2.0">>}. -{<<"requirements">>, - #{<<"jsx">> => - #{<<"app">> => <<"jsx">>,<<"optional">> => false, - <<"requirement">> => <<"2.10.0">>}}}. -{<<"app">>,<<"coveralls">>}. -{<<"maintainers">>,[<<"Markus Ekholm">>]}. -{<<"precompiled">>,false}. -{<<"description">>,<<"Coveralls for Erlang">>}. -{<<"files">>, - [<<"src/coveralls.app.src">>,<<"README.md">>,<<"rebar.config">>, - <<"rebar.config.script">>,<<"rebar.lock">>,<<"src/coveralls.erl">>, - <<"src/rebar3_coveralls.erl">>]}. -{<<"licenses">>,[<<"BSD">>]}. -{<<"links">>,[{<<"Github">>,<<"https://hub.fastgit.org/markusn/coveralls-erl">>}]}. -{<<"build_tools">>,[<<"rebar3">>]}. diff --git a/_build/default/plugins/coveralls/rebar.config b/_build/default/plugins/coveralls/rebar.config deleted file mode 100644 index 9e9a508781..0000000000 --- a/_build/default/plugins/coveralls/rebar.config +++ /dev/null @@ -1,7 +0,0 @@ -{deps, [{jsx, "2.10.0"}]}. -{profiles, [{test, [{plugins, [{coveralls, {git, "https://hub.fastgit.org/markusn/coveralls-erl", {branch, "master"}}}]}]}]}. -{cover_enabled , true}. -{cover_export_enabled , true}. -{coveralls_coverdata , "_build/test/cover/eunit.coverdata"}. % or a string with wildcards or a list of files -{coveralls_service_name , "travis-ci"}. -{coveralls_parallel, true}. diff --git a/_build/default/plugins/coveralls/rebar.config.script b/_build/default/plugins/coveralls/rebar.config.script deleted file mode 100644 index 8886d94ce6..0000000000 --- a/_build/default/plugins/coveralls/rebar.config.script +++ /dev/null @@ -1,7 +0,0 @@ -case os:getenv("TRAVIS") of - "true" -> - JobId = os:getenv("TRAVIS_JOB_ID"), - lists:keystore(coveralls_service_job_id, 1, CONFIG, {coveralls_service_job_id, JobId}); - _ -> - CONFIG -end. \ No newline at end of file diff --git a/_build/default/plugins/coveralls/src/coveralls.app.src b/_build/default/plugins/coveralls/src/coveralls.app.src deleted file mode 100644 index 6767867a49..0000000000 --- a/_build/default/plugins/coveralls/src/coveralls.app.src +++ /dev/null @@ -1,11 +0,0 @@ -{application,coveralls, - [{description,"Coveralls for Erlang"}, - {vsn,"2.2.0"}, - {licenses,["BSD"]}, - {modules,[]}, - {registred,[]}, - {applications,[kernel,stdlib]}, - {env,[{providers,[rebar3_coveralls]}]}, - {maintainers,["Markus Ekholm"]}, - {links,[{"Github", - "https://hub.fastgit.org/markusn/coveralls-erl"}]}]}. diff --git a/_build/default/plugins/coveralls/src/coveralls.erl b/_build/default/plugins/coveralls/src/coveralls.erl deleted file mode 100644 index 90954c6d58..0000000000 --- a/_build/default/plugins/coveralls/src/coveralls.erl +++ /dev/null @@ -1,499 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%%% Copyright (c) 2013-2016, Markus Ekholm -%%% 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 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 MARKUS EKHOLM 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. -%%% -%%% @copyright 2013-2016 (c) Markus Ekholm -%%% @author Markus Ekholm -%%% @doc coveralls -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%%============================================================================= -%% Module declaration - --module(coveralls). - -%%============================================================================= -%% Exports - --export([ convert_file/2 - , convert_and_send_file/2 - ]). - -%%============================================================================= -%% Records - --record(s, { importer = fun cover:import/1 - , module_lister = fun cover:imported_modules/0 - , mod_info = fun module_info_compile/1 - , file_reader = fun file:read_file/1 - , wildcard_reader = fun filelib:wildcard/1 - , analyser = fun cover:analyse/3 - , poster = fun httpc:request/4 - , poster_init = start_wrapper([fun ssl:start/0, fun inets:start/0]) - }). - -%%============================================================================= -%% Defines - --define(COVERALLS_URL, "https://coveralls.io/api/v1/jobs"). -%%-define(COVERALLS_URL, "http://127.0.0.1:8080"). - --ifdef(random_only). --define(random, random). --else. --define(random, rand). --endif. - -%%============================================================================= -%% API functions - -%% @doc Import and convert cover file(s) `Filenames' to a json string -%% representation suitable to post to coveralls. -%% -%% Note that this function will crash if the modules mentioned in -%% any of the `Filenames' are not availabe on the node. -%% @end --spec convert_file(string() | [string()], map()) -> - string(). -convert_file(Filenames, Report) -> - convert_file(Filenames, Report, #s{}). - -%% @doc Import and convert cover files `Filenames' to a json string and send the -%% json to coveralls. -%% @end --spec convert_and_send_file(string() | [string()], map()) -> ok. -convert_and_send_file(Filenames, Report) -> - convert_and_send_file(Filenames, Report, #s{}). - -%%============================================================================= -%% Internal functions - -convert_file([L|_]=Filename, Report, S) when is_integer(L) -> - %% single file or wildcard was specified - WildcardReader = S#s.wildcard_reader, - Filenames = WildcardReader(Filename), - convert_file(Filenames, Report, S); -convert_file([[_|_]|_]=Filenames, Report, S) -> - ok = lists:foreach( - fun(Filename) -> ok = import(S, Filename) end, - Filenames), - ConvertedModules = convert_modules(S), - jsx:encode(Report#{source_files => ConvertedModules}, []). - -convert_and_send_file(Filenames, Report, S) -> - send(convert_file(Filenames, Report, S), S). - -send(Json, #s{poster=Poster, poster_init=Init}) -> - ok = Init(), - Boundary = ["----------", integer_to_list(?random:uniform(1000))], - Type = "multipart/form-data; boundary=" ++ Boundary, - Body = to_body(Json, Boundary), - R = Poster(post, {?COVERALLS_URL, [], Type, Body}, [], []), - {ok, {{_, ReturnCode, _}, _, Message}} = R, - case ReturnCode of - 200 -> ok; - ErrCode -> throw({error, {ErrCode, Message}}) - end. - -%%----------------------------------------------------------------------------- -%% HTTP helpers - -to_body(Json, Boundary) -> - iolist_to_binary(["--", Boundary, "\r\n", - "Content-Disposition: form-data; name=\"json_file\"; " - "filename=\"json_file.json\" \r\n" - "Content-Type: application/json\r\n\r\n", - Json, "\r\n", "--", Boundary, "--", "\r\n"]). - -%%----------------------------------------------------------------------------- -%% Callback mockery - -import(#s{importer=F}, File) -> F(File). - -imported_modules(#s{module_lister=F}) -> F(). - -analyze(#s{analyser=F}, Mod) -> F(Mod, calls, line). - -compile_info(#s{mod_info=F}, Mod) -> F(Mod). - --ifdef(TEST). -module_info_compile(Mod) -> Mod:module_info(compile). --else. -module_info_compile(Mod) -> - code:load_file(Mod), - case code:is_loaded(Mod) of - {file, _} -> Mod:module_info(compile); - _ -> [] - end. --endif. - -read_file(#s{file_reader=_F}, "") -> {ok, <<"">>}; -read_file(#s{file_reader=F}, SrcFile) -> F(SrcFile). - -start_wrapper(Funs) -> - fun() -> - lists:foreach(fun(F) -> ok = wrap_start(F) end, Funs) - end. - -wrap_start(StartFun) -> - case StartFun() of - {error,{already_started,_}} -> ok; - ok -> ok - end. - -digit(I) when I < 10 -> <<($0 + I):8>>; -digit(I) -> <<($a -10 + I):8>>. - -hex(<<>>) -> - <<>>; -hex(<>) -> - <<(digit(I))/binary, (hex(R))/binary>>. - -%%----------------------------------------------------------------------------- -%% Converting modules - -convert_modules(S) -> - F = fun(Mod, L) -> convert_module(Mod, S, L) end, - lists:foldr(F, [], imported_modules(S)). - -convert_module(Mod, S, L) -> - {ok, CoveredLines0} = analyze(S, Mod), - %% Remove strange 0 indexed line - FilterF = fun({{_, X}, _}) -> X =/= 0 end, - CoveredLines = lists:filter(FilterF, CoveredLines0), - case proplists:get_value(source, compile_info(S, Mod), "") of - "" -> L; - SrcFile -> - {ok, SrcBin} = read_file(S, SrcFile), - Src0 = lists:flatten(io_lib:format("~s", [SrcBin])), - SrcDigest = erlang:md5(SrcBin), - LinesCount = count_lines(Src0), - Cov = create_cov(CoveredLines, LinesCount), - [#{name => unicode:characters_to_binary(relative_to_cwd(SrcFile), utf8, utf8), - source_digest => hex(SrcDigest), - coverage => Cov} - | L] - end. - -expand(Path) -> expand(filename:split(Path), []). - -expand([], Acc) -> filename:join(lists:reverse(Acc)); -expand(["."|Tail], Acc) -> expand(Tail, Acc); -expand([".."|Tail], []) -> expand(Tail, []); -expand([".."|Tail], [_|Acc]) -> expand(Tail, Acc); -expand([Segment|Tail], Acc) -> expand(Tail, [Segment|Acc]). - -realpath(Path) -> realpath(filename:split(Path), "./"). - -realpath([], Acc) -> filename:absname(expand(Acc)); -realpath([Head | Tail], Acc) -> - NewAcc0 = filename:join([Acc, Head]), - NewAcc = case file:read_link(NewAcc0) of - {ok, Link} -> - case filename:pathtype(Link) of - absolute -> realpath(Link); - relative -> filename:join([Acc, Link]) - end; - _ -> NewAcc0 - end, - realpath(Tail, NewAcc). - -relative_to_cwd(Path) -> - case file:get_cwd() of - {ok, Base} -> relative_to(Path, Base); - _ -> Path - end. - -relative_to(Path, From) -> - Path1 = realpath(Path), - relative_to(filename:split(Path1), filename:split(From), Path). - -relative_to([H|T1], [H|T2], Original) -> relative_to(T1, T2, Original); -relative_to([_|_] = L1, [], _Original) -> filename:join(L1); -relative_to(_, _, Original) -> Original. - -create_cov(_CoveredLines, []) -> - []; -create_cov(CoveredLines, LinesCount) when is_integer(LinesCount) -> - create_cov(CoveredLines, lists:seq(1, LinesCount)); -create_cov([{{_,LineNo},Count}|CoveredLines], [LineNo|LineNos]) -> - [Count | create_cov(CoveredLines, LineNos)]; -create_cov(CoveredLines, [_|LineNos]) -> - [null | create_cov(CoveredLines, LineNos)]. - -%%----------------------------------------------------------------------------- -%% Generic helpers - -count_lines("") -> 1; -count_lines("\n") -> 1; -count_lines([$\n|S]) -> 1 + count_lines(S); -count_lines([_|S]) -> count_lines(S). - -%%============================================================================= -%% Tests - --ifdef(TEST). --define(DEBUG, true). --include_lib("eunit/include/eunit.hrl"). - -normalize_json_str(Str) when is_binary(Str) -> - jsx:encode(jsx:decode(Str, [return_maps, {labels, existing_atom}])); -normalize_json_str(Str) when is_list(Str) -> - normalize_json_str(iolist_to_binary(Str)). - -convert_file_test() -> - Expected = - jsx:decode( - <<"{\"service_job_id\": \"1234567890\"," - " \"service_name\": \"travis-ci\"," - " \"source_files\": [" - " {\"name\": \"example.rb\"," - " \"source_digest\": \"3feb892deff06e7accbe2457eec4cd8b\"," - " \"coverage\": [null,1,null]" - " }," - " {\"name\": \"two.rb\"," - " \"source_digest\": \"fce46ee19702bd262b2e4907a005aff4\"," - " \"coverage\": [null,1,0,null]" - " }" - " ]" - "}">>, [return_maps, {labels, existing_atom}]), - Report = #{service_job_id => <<"1234567890">>, - service_name => <<"travis-ci">>}, - Got = jsx:decode( - convert_file("example.rb", Report, mock_s()), - [return_maps, {labels, existing_atom}]), - ?assertEqual(Expected, Got). - -convert_and_send_file_test() -> - Expected = - normalize_json_str( - "{\"service_job_id\": \"1234567890\"," - " \"service_name\": \"travis-ci\"," - " \"source_files\": [" - " {\"name\": \"example.rb\"," - " \"source_digest\": \"3feb892deff06e7accbe2457eec4cd8b\"," - " \"coverage\": [null,1,null]" - " }," - " {\"name\": \"two.rb\"," - " \"source_digest\": \"fce46ee19702bd262b2e4907a005aff4\"," - " \"coverage\": [null,1,0,null]" - " }" - " ]" - "}"), - Report = #{service_job_id => <<"1234567890">>, - service_name => <<"travis-ci">>}, - ?assertEqual(ok, convert_and_send_file("example.rb", Report, mock_s(Expected))). - -send_test_() -> - Expected = - normalize_json_str( - "{\"service_job_id\": \"1234567890\",\n" - " \"service_name\": \"travis-ci\",\n" - " \"source_files\": [\n" - " {\"name\": \"example.rb\",\n" - " \"source_digest\": \"\tdef four\\n 4\\nend\",\n" - " \"coverage\": [null,1,null]\n" - " }" - " ]" - "}"), - [ ?_assertEqual(ok, send(Expected, mock_s(Expected))) - , ?_assertThrow({error, {_,_}}, send("foo", mock_s(<<"bar">>))) - ]. - -%%----------------------------------------------------------------------------- -%% Generic helpers tests - -count_lines_test_() -> - [ ?_assertEqual(1, count_lines("")) - , ?_assertEqual(1, count_lines("foo")) - , ?_assertEqual(1, count_lines("bar\n")) - , ?_assertEqual(2, count_lines("foo\nbar")) - , ?_assertEqual(3, count_lines("foo\n\nbar")) - , ?_assertEqual(2, count_lines("foo\nbar\n")) - ]. - -expand_test_() -> - [ ?_assertEqual("/a/b", expand(["/", "a", "b"], [])) - , ?_assertEqual("a/c" , expand(["a", "b", "..", ".", "c"], [])) - , ?_assertEqual("/" , expand(["..", ".", "/"], [])) - ]. - -realpath_and_relative_test_() -> - {setup, - fun() -> %% setup - {ok, Cwd} = file:get_cwd(), - Root = string:strip( - os:cmd("mktemp -d -t coveralls_tests.XXX"), right, $\n), - ok = file:set_cwd(Root), - {Cwd, Root} - end, - fun({Cwd, _Root}) -> %% teardown - ok = file:set_cwd(Cwd) - end, - fun({_Cwd, Root}) -> %% tests - Filename = "file", - Dir1 = filename:join([Root, "_test_src", "dir1"]), - Dir2 = filename:join([Root, "_test_src", "dir2"]), - File1 = filename:join([Dir1, Filename]), - File2 = filename:join([Dir2, Filename]), - Link1 = filename:join([ Root - , "_test_build" - , "default" - , "lib" - , "mylib" - , "src" - , "dir1" - ]), - Link2 = filename:join([ Root - , "_test_build" - , "default" - , "lib" - , "mylib" - , "src" - , "dir2" - ]), - [ ?_assertEqual(ok, - filelib:ensure_dir(filename:join([Dir1, "dummy"]))) - , ?_assertEqual(ok, - filelib:ensure_dir(filename:join([Dir2, "dummy"]))) - , ?_assertEqual(ok, - file:write_file(File1, "data")) - , ?_assertEqual(ok, - file:write_file(File2, "data")) - , ?_assertEqual(ok, - filelib:ensure_dir(Link1)) - , ?_assertEqual(ok, - filelib:ensure_dir(Link2)) - , ?_assertEqual(ok, - file:make_symlink(Dir1, Link1)) - , ?_assertEqual(ok, - file:make_symlink(filename:join([ ".." - , ".." - , ".." - , ".." - , ".." - , "_test_src" - , "dir2" - ]) - , Link2)) - , ?_assertEqual(realpath(File1), - realpath(filename:join([Link1, Filename]))) - , ?_assertEqual(realpath(File2), - realpath(filename:join([Link2, Filename]))) - , ?_assertEqual(realpath(File1), - filename:absname( - relative_to_cwd( - filename:join([Link1, Filename])))) - , ?_assertEqual(realpath(File2), - filename:absname( - relative_to_cwd( - filename:join([Link2, Filename])))) - ] - end}. - -%%----------------------------------------------------------------------------- -%% Callback mockery tests -module_info_compile_test() -> - ?assert(is_tuple(lists:keyfind(source, 1, module_info_compile(?MODULE)))). - -start_wrapper_test_() -> - F = fun() -> ok end, - StartedF = fun() -> {error,{already_started,mod}} end, - ErrorF = fun() -> {error, {error, mod}} end, - [ ?_assertEqual(ok, (start_wrapper([F, StartedF]))()) - , ?_assertError(_, (start_wrapper([F, StartedF, ErrorF]))()) - ]. - -%%----------------------------------------------------------------------------- -%% Converting modules tests - -create_cov_test() -> - ?assertEqual([null, 3, null, 4, null], - create_cov([{{foo, 2}, 3}, {{foo, 4}, 4}], 5)). - -convert_module_test() -> - Expected = - [#{name => <<"example.rb">>, - source_digest => <<"3feb892deff06e7accbe2457eec4cd8b">>, - coverage => [null,1,null]}], - ?assertEqual(Expected, convert_module('example.rb', mock_s(), [])). - -convert_modules_test() -> - Expected = - [#{name => <<"example.rb">>, - source_digest => <<"3feb892deff06e7accbe2457eec4cd8b">>, - coverage => [null,1,null] - }, - #{name => <<"two.rb">>, - source_digest => <<"fce46ee19702bd262b2e4907a005aff4">>, - coverage => [null,1,0,null] - }], - ?assertEqual(Expected, - convert_modules(mock_s())). - -%%----------------------------------------------------------------------------- -%% Setup helpers - -mock_s() -> mock_s(""). - -mock_s(Json) -> - #s{ importer = - fun(_) -> ok end - , module_lister = - fun() -> ['example.rb', 'two.rb'] end - , mod_info = - fun('example.rb') -> [{source,"example.rb"}]; - ('two.rb') -> [{source,"two.rb"}] - end - , file_reader = - fun("example.rb") -> - {ok, <<"def four\n 4\nend">>}; - ("two.rb") -> - {ok, <<"def seven\n eight\n nine\nend">>} - end - , wildcard_reader = fun(AnyFile) -> [AnyFile] end - , analyser = - fun('example.rb' , calls, line) -> {ok, [ {{'example.rb', 2}, 1} ]}; - ('two.rb' , calls, line) -> {ok, [ {{'two.rb', 2}, 1} - , {{'two.rb', 3}, 0} - ] - } - end - , poster_init = - fun() -> ok end - , poster = - fun(post, {_, _, _, Body}, _, _) -> - case binary:match(Body, Json) =/= nomatch of - true -> {ok, {{"", 200, ""}, "", ""}}; - false -> {ok, {{"", 666, ""}, "", "Not expected"}} - end - end - }. - --endif. - -%%% Local Variables: -%%% allout-layout: t -%%% erlang-indent-level: 2 -%%% End: diff --git a/_build/default/plugins/coveralls/src/rebar3_coveralls.erl b/_build/default/plugins/coveralls/src/rebar3_coveralls.erl deleted file mode 100644 index 01084ee3f6..0000000000 --- a/_build/default/plugins/coveralls/src/rebar3_coveralls.erl +++ /dev/null @@ -1,220 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%%% Copyright (c) 2013-2016, Markus Ekholm -%%% 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 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 MARKUS EKHOLM 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. -%%% -%%% @copyright 2013-2016 (c) Yury Gargay , -%%% Markus Ekholm -%%% @end -%%% @author Yury Gargay -%%% @author Markus Ekholm -%%% @doc coveralls plugin for rebar3 -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - --module(rebar3_coveralls). --behaviour(provider). - --export([ init/1 - , do/1 - , format_error/1 - ]). - --define(PROVIDER, send). --define(DEPS, [{default, app_discovery}]). - -%% =================================================================== -%% Public API -%% =================================================================== --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ {name, ?PROVIDER} - , {module, ?MODULE} - , {namespace, coveralls} - , {bare, true} - , {deps, ?DEPS} - , {example, "rebar3 coveralls send"} - , {short_desc, "Send coverdata to coveralls."} - , {desc, "Send coveralls to coveralls."} - , {opts, []} - ]), - {ok, rebar_state:add_provider(State, Provider)}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - rebar_api:info("Running coveralls...", []), - ConvertAndSend = fun coveralls:convert_and_send_file/2, - Get = fun(Key, Def) -> rebar_state:get(State, Key, Def) end, - GetLocal = fun(Key, Def) -> rebar_state:get(State, Key, Def) end, - MaybeSkip = fun() -> ok end, - ok = cover_paths(State), - try - do_coveralls(ConvertAndSend, - Get, - GetLocal, - MaybeSkip, - 'send-coveralls'), - {ok, State} - catch throw:{error, {ErrCode, Msg}} -> - io:format("Failed sending coverdata to coveralls, ~p: ~p", - [ErrCode, Msg]), - {error, rebar_abort} - end. - --spec format_error(any()) -> iolist(). -format_error(Reason) -> - io_lib:format("~p", [Reason]). - -cover_paths(State) -> - lists:foreach(fun(App) -> - AppDir = rebar_app_info:out_dir(App), - true = code:add_patha(filename:join([AppDir, "ebin"])), - _ = code:add_patha(filename:join([AppDir, "test"])) - end, - rebar_state:project_apps(State)), - _ = code:add_patha(filename:join([rebar_dir:base_dir(State), "test"])), - ok. - -%%============================================================================= -%% Internal functions - -to_binary(List) when is_list(List) -> - unicode:characters_to_binary(List, utf8, utf8); -to_binary(Atom) when is_atom(Atom) -> - atom_to_binary(Atom, utf8); -to_binary(Bin) when is_binary(Bin) -> - Bin. -to_boolean(true) -> true; -to_boolean(1) -> true; -to_boolean(_) -> false. - -do_coveralls(ConvertAndSend, Get, GetLocal, MaybeSkip, Task) -> - File = GetLocal(coveralls_coverdata, undef), - ServiceName = to_binary(GetLocal(coveralls_service_name, undef)), - ServiceJobId = to_binary(GetLocal(coveralls_service_job_id, undef)), - F = fun(X) -> X =:= undef orelse X =:= false end, - CoverExport = Get(cover_export_enabled, false), - case lists:any(F, [File, ServiceName, ServiceJobId, CoverExport]) of - true -> - throw({error, - "need to specify coveralls_* and cover_export_enabled " - "in rebar.config"}); - false -> - ok - end, - - Report0 = - #{service_job_id => ServiceJobId, - service_name => ServiceName}, - Opts = [{coveralls_repo_token, repo_token, string}, - {coveralls_service_pull_request, service_pull_request, string}, - {coveralls_commit_sha, commit_sha, string}, - {coveralls_service_number, service_number, string}, - {coveralls_parallel, parallel, boolean}], - Report = - lists:foldl(fun({Cfg, Key, Conv}, R) -> - case GetLocal(Cfg, undef) of - undef -> R; - Value when Conv =:= string -> maps:put(Key, to_binary(Value), R); - Value when Conv =:= boolean -> maps:put(Key, to_boolean(Value), R); - Value -> maps:put(Key, Value, R) - end - end, Report0, Opts), - - DoCoveralls = (GetLocal(do_coveralls_after_ct, true) andalso Task == ct) - orelse (GetLocal(do_coveralls_after_eunit, true) andalso Task == eunit) - orelse Task == 'send-coveralls', - case DoCoveralls of - true -> - io:format("rebar_coveralls:" - "Exporting cover data " - "from ~s using service ~s and jobid ~s~n", - [File, ServiceName, ServiceJobId]), - ok = ConvertAndSend(File, Report); - _ -> MaybeSkip() - end. - - -%%============================================================================= -%% Tests - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - -task_test_() -> - File = "foo", - ServiceJobId = "123", - ServiceName = "bar", - ConvertAndSend = fun("foo", #{service_job_id := <<"123">>, - service_name := <<"bar">>}) -> ok end, - ConvertWithOpts = fun("foo", #{service_job_id := <<"123">>, - service_name := <<"bar">>, - service_pull_request := <<"PR#1">>, - parallel := true}) -> ok - end, - Get = fun(cover_export_enabled, _) -> true end, - GetLocal = fun(coveralls_coverdata, _) -> File; - (coveralls_service_name, _) -> ServiceName; - (coveralls_service_job_id, _) -> ServiceJobId; - (do_coveralls_after_eunit, _) -> true; - (do_coveralls_after_ct, _) -> true; - (coveralls_repo_token, _) -> []; - (_, Default) -> Default - end, - GetLocalAllOpt = fun(coveralls_coverdata, _) -> File; - (coveralls_service_name, _) -> ServiceName; - (coveralls_service_job_id, _) -> ServiceJobId; - (coveralls_service_pull_request, _) -> "PR#1"; - (coveralls_parallel, _) -> true; - (do_coveralls_after_eunit, _) -> true; - (do_coveralls_after_ct, _) -> true; - (coveralls_repo_token, _) -> []; - (_, Default) -> Default - end, - GetLocalWithCoverallsTask - = fun(coveralls_coverdata, _) -> File; - (coveralls_service_name, _) -> ServiceName; - (coveralls_service_job_id, _) -> ServiceJobId; - (do_coveralls_after_eunit, _) -> false; - (do_coveralls_after_ct, _) -> false; - (coveralls_repo_token, _) -> []; - (_, Default) -> Default - end, - GetBroken = fun(cover_export_enabled, _) -> false end, - MaybeSkip = fun() -> skip end, - [ ?_assertEqual(ok, do_coveralls(ConvertAndSend, Get, GetLocal, MaybeSkip, eunit)) - , ?_assertEqual(ok, do_coveralls(ConvertAndSend, Get, GetLocal, MaybeSkip, ct)) - , ?_assertThrow({error, _}, do_coveralls(ConvertAndSend, GetBroken, GetLocal, MaybeSkip, eunit)) - , ?_assertThrow({error, _}, do_coveralls(ConvertAndSend, GetBroken, GetLocal, MaybeSkip, ct)) - , ?_assertEqual(skip, do_coveralls(ConvertAndSend, Get, GetLocalWithCoverallsTask, MaybeSkip, eunit)) - , ?_assertEqual(skip, do_coveralls(ConvertAndSend, Get, GetLocalWithCoverallsTask, MaybeSkip, ct)) - , ?_assertEqual(ok, do_coveralls(ConvertAndSend, Get, GetLocalWithCoverallsTask, MaybeSkip, 'send-coveralls')) - , ?_assertEqual(ok, do_coveralls(ConvertWithOpts, Get, GetLocalAllOpt, MaybeSkip, eunit)) - , ?_assertEqual(ok, do_coveralls(ConvertWithOpts, Get, GetLocalAllOpt, MaybeSkip, ct)) - ]. - --endif. - -%%% Local Variables: -%%% allout-layout: t -%%% erlang-indent-level: 2 -%%% End: diff --git a/_build/default/plugins/hex_core/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/hex_core/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index dd93d77240..0000000000 Binary files a/_build/default/plugins/hex_core/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/hex_core/.rebar3/rebar_compiler_xrl/source.dag b/_build/default/plugins/hex_core/.rebar3/rebar_compiler_xrl/source.dag deleted file mode 100644 index 747160d3b4..0000000000 Binary files a/_build/default/plugins/hex_core/.rebar3/rebar_compiler_xrl/source.dag and /dev/null differ diff --git a/_build/default/plugins/hex_core/CHANGELOG.md b/_build/default/plugins/hex_core/CHANGELOG.md deleted file mode 100644 index 2d03ca5ed0..0000000000 --- a/_build/default/plugins/hex_core/CHANGELOG.md +++ /dev/null @@ -1,117 +0,0 @@ -# CHANGELOG - -## 0.7.1 (2020-10-12) - -* Fix dialyzer warnings on OTP 23 - -## 0.7.0 (2020-10-20) - -* Fix compatibility with OTP 24 -* Change `hex_tarball:create/2` error value from `{error, too_big}` to `{tarball, {too_big_compressed | too_big_uncompressed, Size}}`. - -## 0.6.10 (2020-08-25) - -* Add configuration for max tarball size -* Do not create extraneous "memory" directory when unpacking - -## 0.6.9 (2020-05-24) - -* Add `hex_api_release:publish/3` - -## 0.6.8 (2020-02-04) - -* Fix tarball file extraction through symlinks - -## 0.6.7 (2020-02-03) - -* Fix compatibility with OTP 18 and 17 - -## 0.6.6 (2020-02-03) - -* Do not crash on empty tarballs -* Fix directory traversal vulnerability for symlinks in tarballs - -## 0.6.5 (2020-01-14) - -* Transition away from `http_uri` when using newer OTP releases -* Ensure `Role` is given as an atom in `hex_api_organization_member:add/3` -* Add `http_headers` to the `hex_core:config()` type -* Add default `http_headers` to `hex_core:default_config/0` -* Fix `hex_registry:decode_and_verify_signed/2` spec -* Fix `hex_tarball:files/0` type - -## 0.6.4 (2019-12-27) - -* Fix setting level and trasfer options in organization api - -## 0.6.3 (2019-12-16) - -* Add organization API -* Add level and transfer params to add owner API -* Add `hex_tarball:unpack_docs/2` -* Add `hex_api_auth:test_key/3` - -## 0.6.2 (2019-11-11) - -* Gracefully handle HTTP errors - -## 0.6.1 (2019-07-30) - -* Fix bug when publishing with configuration that does not have `repo_organization` key set - -## 0.6.0 (2019-07-27) - -* **Backwards-incompatible**: Change successful return value of `hex_tarball:create/2` from - `{ok, {Tarball, Checksum}}` to `{ok, Map}`. Currently, `Map` has `tarball`, `inner_tarball`, - and `outer_tarball` keys -* Rename existing tarball checksum to inner checksum and deprecate it -* Add tarball outer checksum -* Do not allow comments in `safe_erl_term` -* Forward compatible tarball contents by not failing on unknown files - -## 0.5.1 (2019-07-30) - -* Fix bug when publishing with configuration that does not have `repo_organization` key set - -## 0.5.0 (2019-02-26) - -* Fetch package data from proper repository organization and don't verify origin if configured -* **Backwards-incompatible**: Make `hex_api` module private -* **Backwards-incompatible**: `organization` config key has been replaced with `api_organization` - and `api_repository` keys -* Add `repo_organization` config key -* `vendor.sh`: Add missing `hex_pb_*.erl` files -* `vendor.sh`: Fix replacing `hex_core` - -## 0.4.0 (2018-12-30) - -* Revert swich from proto2 to proto3 -* Verify authenticity of signed payload -* Add `repo_verify_origin` config option - -## 0.3.0 (2018-12-14) - -* Swich from proto2 to proto3 -* Fix `hex_http:body` type -* Fix `hex_http:request` spec - -## 0.2.1 (2018-12-13) - -* Always return the whole response tuple from requests -* Guess rebar3 as build tool over rebar -* Return compressed tarball from hex_tarball:create_docs/1 -* Add package identity to registry records - -## 0.2.0 (2018-09-01) - -* Accept `{filename(), filename()}` in files list for tarballs -* Support httpc profile through adapter configs -* Update generated protobuf files with OTP 21 compatibility - -## 0.1.1 (2018-08-11) - -* Use `hex_core` project name in user agent string - -## 0.1.0 (2018-08-08) - -* First release diff --git a/_build/default/plugins/hex_core/LICENSE b/_build/default/plugins/hex_core/LICENSE deleted file mode 100644 index 4c82636099..0000000000 --- a/_build/default/plugins/hex_core/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2018, Six Colors AB - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/_build/default/plugins/hex_core/README.md b/_build/default/plugins/hex_core/README.md deleted file mode 100644 index 4c6557f644..0000000000 --- a/_build/default/plugins/hex_core/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# hex_core - -[![Build Status](https://hub.fastgit.org/hexpm/hex_core/workflows/CI/badge.svg)](https://hub.fastgit.org/hexpm/hex_core/actions) - -Reference implementation of Hex specifications: https://hub.fastgit.org/hexpm/specifications. - -## Usage - -Let's use default config for now. See "Configuration" section below for customization. - -```erlang -Config = hex_core:default_config(). -``` - -### Repository - -Get all package names: - -```erlang -> hex_repo:get_names(Config). -{ok, {200, ..., - #{packages => [ - #{name => <<"package1">>}, - #{name => <<"package2">>}, - ... - ]}}} -``` - -Get all package versions from repository: - -```erlang -> hex_repo:get_versions(Config). -{ok, {200, ..., - [ - #{name => <<"package1">>, retired => [], versions => [<<"1.0.0">>]}, - #{name => <<"package2">>, retired => [], versions => [<<"0.5.0">>]}, - ]}} -``` - -Get package releases from repository: - -```erlang -> hex_repo:get_package(Config, <<"package1">>). -{ok, {200, ..., - [ - #{checksum => ..., version => <<"0.5.0">>, dependencies => []}], - #{checksum => ..., version => <<"1.0.0">>, dependencies => []}], - ]}} -``` - -### API - -For a full list of all parameters and returned objects for the API, check out the API docs: https://hub.fastgit.org/hexpm/specifications/blob/master/http_api.md. - -Get package from HTTP API: - -```erlang -> hex_api_package:get(Config, <<"package1">>). -{ok, {200, ..., - #{ - <<"name">> => <<"package1">>, - <<"meta">> => #{ - <<"description">> => ..., - <<"licenses">> => ..., - <<"links">> => ..., - <<"maintainers">> => ..., - }, - ..., - <<"releases">> => [ - #{<<"url">> => ..., <<"version">> => <<"0.5.0">>}], - #{<<"url">> => ..., <<"version">> => <<"1.0.0">>}], - ... - ] - }}} -``` - -Get package tarball: - -```erlang -{ok, {200, _, Tarball}} = hex_repo:get_tarball(Config, <<"package1">>, <<"1.0.0">>). -``` - -Publish package tarball: - -```erlang -{ok, {200, _Headers, _Body} = hex_api_package:publish(Config, Tarball). -``` - -### Package tarballs - -Unpack package tarball: - -```erlang -{ok, #{outer_checksum := Checksum, contents := Contents, metadata := Metadata}} = hex_tarball:unpack(Tarball, memory). -``` - -Remember to verify the outer tarball checksum against the registry checksum -returned from `hex_repo:get_package(Config, Package)`. - -Create package tarball: - -```erlang -{ok, #{tarball := Tarball, - inner_checksum := InnerChecksum, - outer_checksum := OuterChecksum}} = hex_tarball:create(Metadata, Contents). -``` - -## Configuration - -The default configuration, provided by `hex_core:default_config/0`, uses built-in httpc-based adapter and Hex.pm APIs: - and . - -HTTP client configuration can be overridden as follows: - -```erlang -Config = maps:merge(hex_core:default_config(), #{ - http_adapter => {my_hackney_adapter, my_hackney_adapter_config}, - http_user_agent_fragment => <<"(my_app/0.1.0) (hackney/1.12.1) ">> -}), -hex_repo:get_names(Config). - -%% my_hackney_adapter.erl --module(my_hackney_adapter). --behaviour(hex_http). --exports([request/3]). - -request(Method, URI, ReqHeaders) -> - %% ... -``` - -See the [`hex_core` module](src/hex_core.erl) for more information about the configuration. - -## Wrapper Module - -It's recommended to write a wrapper module because a lot of decisions are left to the user, e.g.: -where to get configuration from, how to handle caching, failures etc. - -For a sample, see: [`examples/myapp_hex.erl`](examples/myapp_hex.erl). Here's an excerpt: - -```erlang --module(myapp_hex). --export([ - get_api_package/1, - get_repo_tarball/2, - get_repo_versions/0 -]). - -%%==================================================================== -%% API functions -%%==================================================================== - -get_api_package(Name) -> - case hex_api_package:get(config(), Name) of - {ok, {200, _Headers, Payload}} -> - {ok, Payload}; - - Other -> - Other - end. - -get_repo_versions() -> - case hex_repo:get_versions(config()) of - {ok, {200, _Headers, Payload}} -> - {ok, maps:get(packages, Payload)}; - - Other -> - Other - end. - -%%==================================================================== -%% Internal functions -%%==================================================================== - -config() -> - Config1 = hex_core:default_config(), - Config2 = put_http_config(Config1), - Config3 = maybe_put_api_key(Config2), - Config3. - -put_http_config(Config) -> - maps:put(http_user_agent_fragment, <<"(myapp/1.0.0) (httpc)">>, Config). - -maybe_put_api_key(Config) -> - case os:getenv("HEX_API_KEY") of - false -> Config; - Key -> maps:put(api_key, Key, Config) - end. -``` - -## Installation - -### Rebar3 - -Add to `rebar.config`: - -```erlang -{deps, [ - {hex_core, "0.7.1"} -]} -``` - -### Mix - -Add to `mix.exs`: - -```elixir -defp deps() do - [ - {:hex_core, "~> 0.7.1"} - ] -end -``` - -## Development - -* Run `rebar3 as dev compile` to re-generate protobuf files -* Run `rebar3 as test proper` for property-based tests -* Run `rebar3 as docs edoc` to generate documentation diff --git a/_build/default/plugins/hex_core/hex_metadata.config b/_build/default/plugins/hex_core/hex_metadata.config deleted file mode 100644 index b5865a4dfb..0000000000 --- a/_build/default/plugins/hex_core/hex_metadata.config +++ /dev/null @@ -1,25 +0,0 @@ -{<<"app">>,<<"hex_core">>}. -{<<"build_tools">>,[<<"rebar3">>]}. -{<<"description">>,<<"Reference implementation of Hex specifications">>}. -{<<"files">>, - [<<"CHANGELOG.md">>,<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>, - <<"rebar.config.script">>,<<"rebar.lock">>,<<"src/hex_api.erl">>, - <<"src/hex_api_auth.erl">>,<<"src/hex_api_key.erl">>, - <<"src/hex_api_organization.erl">>, - <<"src/hex_api_organization_member.erl">>,<<"src/hex_api_package.erl">>, - <<"src/hex_api_package_owner.erl">>,<<"src/hex_api_release.erl">>, - <<"src/hex_api_user.erl">>,<<"src/hex_core.app.src">>, - <<"src/hex_core.erl">>,<<"src/hex_core.hrl">>,<<"src/hex_erl_tar.erl">>, - <<"src/hex_erl_tar.hrl">>,<<"src/hex_filename.erl">>,<<"src/hex_http.erl">>, - <<"src/hex_http_httpc.erl">>,<<"src/hex_pb_names.erl">>, - <<"src/hex_pb_package.erl">>,<<"src/hex_pb_signed.erl">>, - <<"src/hex_pb_versions.erl">>,<<"src/hex_registry.erl">>, - <<"src/hex_repo.erl">>,<<"src/hex_tarball.erl">>, - <<"src/safe_erl_term.xrl">>]}. -{<<"licenses">>,[<<"Apache-2.0">>]}. -{<<"links">>, - [{<<"GitHub">>,<<"https://hub.fastgit.org/hexpm/hex_core">>}, - {<<"Hex specifications">>,<<"https://hub.fastgit.org/hexpm/specifications">>}]}. -{<<"name">>,<<"hex_core">>}. -{<<"requirements">>,[]}. -{<<"version">>,<<"0.7.1">>}. diff --git a/_build/default/plugins/hex_core/rebar.config b/_build/default/plugins/hex_core/rebar.config deleted file mode 100644 index 52aab9bac2..0000000000 --- a/_build/default/plugins/hex_core/rebar.config +++ /dev/null @@ -1,50 +0,0 @@ -{erl_opts, [ - debug_info, - {platform_define, "^19", 'OTP_19'} -]}. -{gpb_opts, [ - {i, "proto"}, - {o_erl, "src"}, - {o_hrl, "src"}, - {verify, always}, - {strings_as_binaries, true}, - {maps, true}, - {maps_unset_optional, omitted}, - {report_warnings, true}, - {target_erlang_version, 17} -]}. -{profiles, [ - {dev, [ - {plugins, [ - {rebar3_gpb_plugin, "2.12.0"} - ]}, - {provider_hooks, [ - {pre, [ - {compile, {protobuf, compile}}, - {clean, {protobuf, clean}} - ]} - ]} - ]}, - {test, [ - {erl_opts, [nowarn_export_all]}, - {ct_opts, [{create_priv_dir, auto_per_tc}, - {config, "test/ct.config"}]}, - {plugins, [ - rebar3_proper - ]}, - {deps, [ - {proper, {git, "git://github.com/proper-testing/proper", {tag, "v1.3"}}} - ]}, - {extra_src_dirs, ["test/support"]} - ]}, - {docs, [ - {deps, [{edown, "0.8.1"}]}, - {edoc_opts, [ - {doclet, edown_doclet}, - {preprocess, true}, - {dir, "doc"}, - {subpackages, true}]} - ]} -]}. - -{post_hooks, [{edoc, "doc/build.sh"}]}. diff --git a/_build/default/plugins/hex_core/rebar.config.script b/_build/default/plugins/hex_core/rebar.config.script deleted file mode 100644 index 314f3b57c3..0000000000 --- a/_build/default/plugins/hex_core/rebar.config.script +++ /dev/null @@ -1,9 +0,0 @@ -case os:getenv("TARGET_ERLANG_VERSION") of - false -> CONFIG; - [] -> CONFIG; - TargetErlangVersionString -> - GpbOpts = proplists:get_value(gpb_opts, CONFIG), - TargetErlangVersion = {target_erlang_version, list_to_integer(TargetErlangVersionString)}, - NewGpbOpts = lists:keystore(target_erlang_version, 1, GpbOpts, TargetErlangVersion), - lists:keystore(gpb_opts, 1, CONFIG, {gpb_opts, NewGpbOpts}) -end. diff --git a/_build/default/plugins/hex_core/src/hex_api.erl b/_build/default/plugins/hex_core/src/hex_api.erl deleted file mode 100644 index 250005f61e..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api.erl +++ /dev/null @@ -1,140 +0,0 @@ -%% @hidden - --module(hex_api). - --export([ - delete/2, - get/2, - post/3, - put/3, - encode_query_string/1, - build_repository_path/2, - build_organization_path/2, - join_path_segments/1 -]). --define(ERL_CONTENT_TYPE, <<"application/vnd.hex+erlang">>). - --export_type([body/0, response/0]). - --type response() :: {ok, {hex_http:status(), hex_http:headers(), body() | nil}} | {error, term()}. --type body() :: [body()] | #{binary() => body() | binary()}. - -get(Config, Path) -> - request(Config, get, Path, undefined). - -post(Config, Path, Body) -> - request(Config, post, Path, encode_body(Body)). - -put(Config, Path, Body) -> - request(Config, put, Path, encode_body(Body)). - -delete(Config, Path) -> - request(Config, delete, Path, undefined). - -%% @private -encode_query_string(List) -> - Pairs = lists:map(fun ({K, V}) -> {to_list(K), to_list(V)} end, List), - list_to_binary(compose_query(Pairs)). - -%% OTP 21+ --ifdef (OTP_RELEASE). -compose_query(Pairs) -> - uri_string:compose_query(Pairs). --else. -compose_query(Pairs) -> - String = join("&", lists:map(fun ({K, V}) -> K ++ "=" ++ V end, Pairs)), - http_uri:encode(String). --endif. - -%% @private -build_repository_path(#{api_repository := Repo}, Path) when is_binary(Repo) -> - ["repos", Repo | Path]; -build_repository_path(#{api_repository := undefined}, Path) -> - Path. - -%% @private -build_organization_path(#{api_organization := Org}, Path) when is_binary(Org) -> - ["orgs", Org | Path]; -build_organization_path(#{api_organization := undefined}, Path) -> - Path. - -%% @private -join_path_segments(Segments) -> - iolist_to_binary(recompose(Segments)). - -%% OTP 21+ --ifdef (OTP_RELEASE). -recompose(Segments) -> - Concatenated = join(<<"/">>, Segments), - %% uri_string:recompose/1 accepts path segments as a list, - %% both strings and binaries - uri_string:recompose(#{path => Concatenated}). --else. -recompose(Segments) -> - join(<<"/">>, lists:map(fun encode_segment/1, Segments)). - -encode_segment(Binary) when is_binary(Binary) -> - encode_segment(binary_to_list(Binary)); -encode_segment(String) when is_list(String) -> - http_uri:encode(String). --endif. - -%%==================================================================== -%% Internal functions -%%==================================================================== - -request(Config, Method, PathSegments, Body) when is_list(PathSegments) -> - Path = join_path_segments(PathSegments), - request(Config, Method, Path, Body); -request(Config, Method, Path, Body) when is_binary(Path) and is_map(Config) -> - DefaultHeaders = make_headers(Config), - ReqHeaders = maps:merge(maps:get(http_headers, Config, #{}), DefaultHeaders), - ReqHeaders2 = put_new(<<"accept">>, ?ERL_CONTENT_TYPE, ReqHeaders), - - case hex_http:request(Config, Method, build_url(Path, Config), ReqHeaders2, Body) of - {ok, {Status, RespHeaders, RespBody}} -> - ContentType = maps:get(<<"content-type">>, RespHeaders, <<"">>), - case binary:match(ContentType, ?ERL_CONTENT_TYPE) of - {_, _} -> - {ok, {Status, RespHeaders, binary_to_term(RespBody)}}; - - nomatch -> - {ok, {Status, RespHeaders, nil}} - end; - - Other -> - Other - end. - -build_url(Path, #{api_url := URI}) -> - <>. - -encode_body({_ContentType, _Body} = Body) -> - Body; -encode_body(Body) -> - {binary_to_list(?ERL_CONTENT_TYPE), term_to_binary(Body)}. - -%% TODO: copy-pasted from hex_repo -make_headers(Config) -> - maps:fold(fun set_header/3, #{}, Config). - -set_header(api_key, Token, Headers) when is_binary(Token) -> maps:put(<<"authorization">>, Token, Headers); -set_header(_, _, Headers) -> Headers. - -put_new(Key, Value, Map) -> - case maps:find(Key, Map) of - {ok, _} -> Map; - error -> maps:put(Key, Value, Map) - end. - -%% https://hub.fastgit.org/erlang/otp/blob/OTP-20.3/lib/stdlib/src/lists.erl#L1449:L1453 -join(_Sep, []) -> []; -join(Sep, [H|T]) -> [H|join_prepend(Sep, T)]. - -join_prepend(_Sep, []) -> []; -join_prepend(Sep, [H|T]) -> [Sep,H|join_prepend(Sep,T)]. - -to_list(A) when is_atom(A) -> atom_to_list(A); -to_list(B) when is_binary(B) -> unicode:characters_to_list(B); -to_list(I) when is_integer(I) -> integer_to_list(I); -to_list(Str) -> unicode:characters_to_list(Str). diff --git a/_build/default/plugins/hex_core/src/hex_api_auth.erl b/_build/default/plugins/hex_core/src/hex_api_auth.erl deleted file mode 100644 index 7c3100626d..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_auth.erl +++ /dev/null @@ -1,18 +0,0 @@ --module(hex_api_auth). --export([test/2]). - -%% @doc -%% Test an auth key against a given domain and resource. -%% -%% Examples: -%% -%% ``` -%% 1> Params = #{domain => <<"repository">>, resource => <<"gustafson_motors">>}. -%% 2> hex_api_auth:test_key(hex_core:default_config(), Params). -%% {ok,{204, ..., nil}} -%% ''' -%% @end --spec test(hex_core:config(), map()) -> hex_api:response(). -test(Config, #{domain := Domain, resource := Resource}) -> - URI = ["auth", "?domain=", Domain, "&resource=", Resource], - hex_api:get(Config, list_to_binary(URI)). diff --git a/_build/default/plugins/hex_core/src/hex_api_key.erl b/_build/default/plugins/hex_core/src/hex_api_key.erl deleted file mode 100644 index b9712af94e..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_key.erl +++ /dev/null @@ -1,157 +0,0 @@ --module(hex_api_key). --export([ - list/1, - get/2, - add/3, - delete/2, - delete_all/1 -]). - --export_type([permission/0]). - --type permission() :: api_permission() | repo_permission() | repos_permission(). --ifdef(OTP_19). --type api_permission() :: #{domain := api, resource => read | write}. --type repo_permission() :: #{domain := repository, resource := binary()}. --type repos_permission() :: #{domain := repositories}. --else. --type api_permission() :: #{domain => api, resource => read | write}. --type repo_permission() :: #{domain => repository, resource => binary()}. --type repos_permission() :: #{domain => repositories}. --endif. - -%% @doc -%% Lists the user's or organization's API and repository keys. -%% -%% Examples: -%% -%% ``` -%% > hex_api_key:list(hex_core:default_config()). -%% {ok, {200, ..., [#{ -%% <<"authing_key">> => true, -%% <<"inserted_at">> => <<"2019-02-27T11:15:32Z">>, -%% <<"last_use">> => -%% #{<<"ip">> => <<"1.2.3.4">>, -%% <<"used_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"user_agent">> => <<"hex_core/0.5.0 (httpc) (OTP/21) (erts/10.2)">>}, -%% <<"name">> => <<"hex_core">>, -%% <<"permissions">> => [#{<<"domain">> => <<"api">>,<<"resource">> => <<"read">>}], -%% <<"revoked_at">> => nil, -%% <<"updated_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"url">> => <<"https://hex.pm/api/keys/test">>}, -%% }]}} -%% ''' -%% @end --spec list(hex_core:config()) -> hex_api:response(). -list(Config) when is_map(Config) -> - Path = hex_api:build_organization_path(Config, ["keys"]), - hex_api:get(Config, Path). - -%% @doc -%% Gets an API or repository key by name. -%% -%% Examples: -%% -%% ``` -%% > hex_api_key:get(hex_core:default_config(), <<"test">>). -%% {ok, {200, ..., #{ -%% <<"authing_key">> => true, -%% <<"inserted_at">> => <<"2019-02-27T11:15:32Z">>, -%% <<"last_use">> => -%% #{<<"ip">> => <<"1.2.3.4">>, -%% <<"used_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"user_agent">> => <<"hex_core/0.5.0 (httpc) (OTP/21) (erts/10.2)">>}, -%% <<"name">> => <<"hex_core">>, -%% <<"permissions">> => [#{<<"domain">> => <<"api">>,<<"resource">> => <<"read">>}], -%% <<"revoked_at">> => nil, -%% <<"updated_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"url">> => <<"https://hex.pm/api/keys/test">>}, -%% }}} -%% ''' -%% @end --spec get(hex_core:config(), binary()) -> hex_api:response(). -get(Config, Name) when is_map(Config) and is_binary(Name) -> - Path = hex_api:build_organization_path(Config, ["keys", Name]), - hex_api:get(Config, Path). - -%% @doc -%% Adds a new API or repository key. -%% -%% Examples: -%% -%% ``` -%% > hex_api_key:add(hex_core:default_config(), <<"test">>, [...]). -%% {ok, {200, ..., #{ -%% <<"authing_key">> => true, -%% <<"inserted_at">> => <<"2019-02-27T11:15:32Z">>, -%% <<"last_use">> => -%% #{<<"ip">> => <<"1.2.3.4">>, -%% <<"used_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"user_agent">> => <<"hex_core/0.5.0 (httpc) (OTP/21) (erts/10.2)">>}, -%% <<"name">> => <<"hex_core">>, -%% <<"permissions">> => [#{<<"domain">> => <<"api">>,<<"resource">> => <<"read">>}], -%% <<"revoked_at">> => nil, -%% <<"updated_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"url">> => <<"https://hex.pm/api/keys/test">>}, -%% }}} -%% ''' -%% @end --spec add(hex_core:config(), binary(), [permission()]) -> hex_api:response(). -add(Config, Name, Permissions) when is_map(Config) and is_binary(Name) and is_list(Permissions) -> - Path = hex_api:build_organization_path(Config, ["keys"]), - Params = #{<<"name">> => Name, <<"permissions">> => Permissions}, - hex_api:post(Config, Path, Params). - -%% @doc -%% Deletes an API or repository key. -%% -%% Examples: -%% -%% ``` -%% > hex_api_key:delete(hex_core:default_config(), <<"test">>). -%% {ok, {200, ..., #{ -%% <<"authing_key">> => true, -%% <<"inserted_at">> => <<"2019-02-27T11:15:32Z">>, -%% <<"last_use">> => -%% #{<<"ip">> => <<"1.2.3.4">>, -%% <<"used_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"user_agent">> => <<"hex_core/0.5.0 (httpc) (OTP/21) (erts/10.2)">>}, -%% <<"name">> => <<"hex_core">>, -%% <<"permissions">> => [#{<<"domain">> => <<"api">>,<<"resource">> => <<"read">>}], -%% <<"revoked_at">> => nil, -%% <<"updated_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"url">> => <<"https://hex.pm/api/keys/test">>}, -%% }}} -%% ''' -%% @end --spec delete(hex_core:config(), binary()) -> hex_api:response(). -delete(Config, Name) when is_map(Config) and is_binary(Name) -> - Path = hex_api:build_organization_path(Config, ["keys", Name]), - hex_api:delete(Config, Path). - -%% @doc -%% Deletes all API and repository keys associated with the account. -%% -%% Examples: -%% -%% ``` -%% > hex_api_key:delete_all(hex_core:default_config()). -%% {ok, {200, ..., [#{ -%% <<"authing_key">> => true, -%% <<"inserted_at">> => <<"2019-02-27T11:15:32Z">>, -%% <<"last_use">> => -%% #{<<"ip">> => <<"1.2.3.4">>, -%% <<"used_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"user_agent">> => <<"hex_core/0.5.0 (httpc) (OTP/21) (erts/10.2)">>}, -%% <<"name">> => <<"hex_core">>, -%% <<"permissions">> => [#{<<"domain">> => <<"api">>,<<"resource">> => <<"read">>}], -%% <<"revoked_at">> => nil, -%% <<"updated_at">> => <<"2019-02-27T14:38:54Z">>, -%% <<"url">> => <<"https://hex.pm/api/keys/test">>}, -%% }]}} -%% ''' -%% @end --spec delete_all(hex_core:config()) -> hex_api:response(). -delete_all(Config) when is_map(Config) -> - Path = hex_api:build_organization_path(Config, ["keys"]), - hex_api:delete(Config, Path). diff --git a/_build/default/plugins/hex_core/src/hex_api_organization.erl b/_build/default/plugins/hex_core/src/hex_api_organization.erl deleted file mode 100644 index 57def31818..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_organization.erl +++ /dev/null @@ -1,66 +0,0 @@ --module(hex_api_organization). --export([ - get/1, - list/1, - update/2 -]). - -%% @doc -%% Lists all organizations you are member of. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization:list(hex_core:default_config()#{api_organization => <<"acme">>}). -%% {ok, {200, ..., [#{ -%% <<"billing_active">> => true, -%% <<"inserted_at">> => <<"2017-08-22T22:19:53Z">>, -%% <<"name">> => <<"acme">>, -%% <<"updated_at">> => <<"2019-01-18T08:47:29Z">>} -%% }]}} -%% ''' --spec list(hex_core:config()) -> hex_api:response(). -list(Config) when is_map(Config) -> - hex_api:get(Config, ["orgs"]). - -%% @doc -%% Gets an organzation. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization:get(hex_core:default_config()#{api_organization => <<"acme">>}). -%% {ok, {200, ..., #{ -%% <<"billing_active">> => true, -%% <<"inserted_at">> => <<"2017-08-22T22:19:53Z">>, -%% <<"name">> => <<"acme">>, -%% <<"seats">> => 42, -%% <<"updated_at">> => <<"2019-01-18T08:47:29Z">>} -%% }}} -%% ''' --spec get(hex_core:config()) -> hex_api:response(). -get(Config) when is_map(Config) -> - Path = hex_api:build_organization_path(Config, []), - hex_api:get(Config, Path). - - -%% @doc -%% Updates the number of seats in an organzation. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization:get(hex_core:default_config()#{api_organization => <<"acme">>}, 42). -%% {ok, {200, ..., #{ -%% <<"billing_active">> => true, -%% <<"inserted_at">> => <<"2017-08-22T22:19:53Z">>, -%% <<"name">> => <<"acme">>, -%% <<"seats">> => 42, -%% <<"updated_at">> => <<"2019-01-18T08:47:29Z">>} -%% }}} -%% ''' --spec update(hex_core:config(), pos_integer()) -> hex_api:response(). -update(Config, Seats) when is_map(Config) and is_integer(Seats)-> - Path = hex_api:build_organization_path(Config, []), - Params = #{<<"seats">> => Seats}, - hex_api:post(Config, Path, Params). diff --git a/_build/default/plugins/hex_core/src/hex_api_organization_member.erl b/_build/default/plugins/hex_core/src/hex_api_organization_member.erl deleted file mode 100644 index b09b449513..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_organization_member.erl +++ /dev/null @@ -1,107 +0,0 @@ --module(hex_api_organization_member). --export([ - add/3, - delete/2, - get/2, - list/1, - update/3 -]). - --type role() :: admin | write | read. - -%% @doc -%% Lists the organization's members. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization_member:list(hex_core:default_config()#{api_organization => <<"acme">>}). -%% {ok, {200, ..., [#{ -%% <<"email">> => <<"user@example.com">>, -%% <<"role">> => <<"admin">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }]}} -%% ''' -%% @end --spec list(hex_core:config()) -> hex_api:response(). -list(Config) when is_map(Config) -> - Path = hex_api:build_organization_path(Config, ["members"]), - hex_api:get(Config, Path). - -%% @doc -%% Gets an organization member. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization_member:get(hex_core:default_config()#{api_organization => <<"acme">>}, <<"user">>). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"role">> => <<"admin">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec get(hex_core:config(), binary()) -> hex_api:response(). -get(Config, UsernameOrEmail) when is_map(Config) and is_binary(UsernameOrEmail) -> - Path = hex_api:build_organization_path(Config, ["members", UsernameOrEmail]), - hex_api:get(Config, Path). - -%% @doc -%% Adds an organization member. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization_member:add(hex_core:default_config()#{api_organization => <<"acme">>}, <<"user">>, write). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"role">> => <<"write">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec add(hex_core:config(), binary(), role()) -> hex_api:response(). -add(Config, UsernameOrEmail, Role) when is_map(Config) and is_binary(UsernameOrEmail) and is_atom(Role) -> - Path = hex_api:build_organization_path(Config, ["members"]), - Params = #{<<"name">> => UsernameOrEmail, <<"role">> => Role}, - hex_api:post(Config, Path, Params). - -%% @doc -%% Updates an organization member's role. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization_member:update(hex_core:default_config()#{api_organization => <<"acme">>}, <<"user">>, read). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"role">> => <<"read">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec update(hex_core:config(), binary(), role()) -> hex_api:response(). -update(Config, UsernameOrEmail, Role) when is_map(Config) and is_binary(UsernameOrEmail) and is_atom(Role) -> - Path = hex_api:build_organization_path(Config, ["members", UsernameOrEmail]), - Params = #{<<"role">> => Role}, - hex_api:post(Config, Path, Params). - -%% @doc -%% Deletes an organization member. -%% -%% Examples: -%% -%% ``` -%% > hex_api_organization_member:delete(hex_core:default_config()#{api_organization => <<"acme">>}, <<"user">>). -%% {ok, {204, ..., nil}} -%% ''' -%% @end --spec delete(hex_core:config(), binary()) -> hex_api:response(). -delete(Config, UsernameOrEmail) when is_map(Config) and is_binary(UsernameOrEmail) -> - Path = hex_api:build_organization_path(Config, ["members", UsernameOrEmail]), - hex_api:delete(Config, Path). diff --git a/_build/default/plugins/hex_core/src/hex_api_package.erl b/_build/default/plugins/hex_core/src/hex_api_package.erl deleted file mode 100644 index 34d6567c3c..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_package.erl +++ /dev/null @@ -1,49 +0,0 @@ --module(hex_api_package). --export([get/2, search/3]). - -%% @doc -%% Gets a package. -%% -%% Examples: -%% -%% ``` -%% > hex_api_package:get(hex_core:default_config(), <<"package">>). -%% {ok, {200, ..., #{ -%% <<"name">> => <<"package1">>, -%% <<"meta">> => #{ -%% <<"description">> => ..., -%% <<"licenses">> => ..., -%% <<"links">> => ..., -%% <<"maintainers">> => ... -%% }, -%% ..., -%% <<"releases">> => [ -%% #{<<"url">> => ..., <<"version">> => <<"0.5.0">>}], -%% #{<<"url">> => ..., <<"version">> => <<"1.0.0">>}], -%% ... -%% ]}}} -%% ''' -%% @end --spec get(hex_core:config(), binary()) -> hex_api:response(). -get(Config, Name) when is_map(Config) and is_binary(Name)-> - Path = hex_api:build_repository_path(Config, ["packages", Name]), - hex_api:get(Config, Path). - -%% @doc -%% Searches packages. -%% -%% Examples: -%% -%% ``` -%% > hex_api_package:search(hex_core:default_config(), <<"package">>, []). -%% {ok, {200, ..., [ -%% #{<<"name">> => <<"package1">>, ...}, -%% ... -%% ]}} -%% ''' --spec search(hex_core:config(), binary(), list(binary())) -> hex_api:response(). -search(Config, Query, SearchParams) when is_map(Config) and is_binary(Query) and is_list(SearchParams) -> - QueryString = hex_api:encode_query_string([{search, Query} | SearchParams]), - Path = hex_api:join_path_segments(hex_api:build_repository_path(Config, ["packages"])), - PathQuery = <>, - hex_api:get(Config, PathQuery). diff --git a/_build/default/plugins/hex_core/src/hex_api_package_owner.erl b/_build/default/plugins/hex_core/src/hex_api_package_owner.erl deleted file mode 100644 index 9c0eb31675..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_package_owner.erl +++ /dev/null @@ -1,96 +0,0 @@ --module(hex_api_package_owner). --export([ - add/5, - delete/3, - get/3, - list/2 -]). - -%% @doc -%% Lists the packages owners. -%% -%% Examples: -%% -%% ``` -%% > hex_api_package_owner:list(hex_core:default_config(), <<"package">>). -%% {ok, {200, ..., [#{ -%% <<"email">> => <<"user@example.com">>, -%% <<"full_name">> => <<"John Doe">>, -%% <<"handles">> => #{...}, -%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, -%% <<"level">> => <<"full">>, -%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }]}} -%% ''' -%% @end --spec list(hex_core:config(), binary()) -> hex_api:response(). -list(Config, PackageName) when is_binary(PackageName) -> - Path = hex_api:build_repository_path(Config, ["packages", PackageName, "owners"]), - hex_api:get(Config, Path). - -%% @doc -%% Gets a packages owner. -%% -%% Examples: -%% -%% ``` -%% > hex_api_package_owner:get(hex_core:default_config(), <<"package">>, <<"user">>). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"full_name">> => <<"John Doe">>, -%% <<"handles">> => #{...}, -%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, -%% <<"level">> => <<"full">>, -%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec get(hex_core:config(), binary(), binary()) -> hex_api:response(). -get(Config, PackageName, UsernameOrEmail) when is_map(Config) and is_binary(PackageName) and is_binary(UsernameOrEmail) -> - Path = hex_api:build_repository_path(Config, ["packages", PackageName, "owners", UsernameOrEmail]), - hex_api:get(Config, Path). - -%% @doc -%% Adds a packages owner. -%% -%% Examples: -%% -%% ``` -%% > hex_api_package_owner:add(hex_core:default_config(), <<"package">>, <<"user">>, <<"full">>, false). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"full_name">> => <<"John Doe">>, -%% <<"handles">> => #{...}, -%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, -%% <<"level">> => <<"full">>, -%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec add(hex_core:config(), binary(), binary(), binary(), boolean()) -> hex_api:response(). -add(Config, PackageName, UsernameOrEmail, Level, Transfer) -when is_binary(PackageName) and is_binary(UsernameOrEmail) and is_map(Config) and is_binary(Level) and is_boolean(Transfer) -> - Path = hex_api:build_repository_path(Config, ["packages", PackageName, "owners", UsernameOrEmail]), - hex_api:put(Config, Path, #{<<"level">> => Level, <<"transfer">> => Transfer}). - - -%% @doc -%% Deletes a packages owner. -%% -%% Examples: -%% -%% ``` -%% > hex_api_package_owner:delete(hex_core:default_config(), <<"package">>, <<"user">>). -%% {ok, {204, ..., nil}} -%% ''' -%% @end --spec delete(hex_core:config(), binary(), binary()) -> hex_api:response(). -delete(Config, PackageName, UsernameOrEmail) when is_map(Config) and is_binary(PackageName) and is_binary(UsernameOrEmail) -> - Path = hex_api:build_repository_path(Config, ["packages", PackageName, "owners", UsernameOrEmail]), - hex_api:delete(Config, Path). diff --git a/_build/default/plugins/hex_core/src/hex_api_release.erl b/_build/default/plugins/hex_core/src/hex_api_release.erl deleted file mode 100644 index 0963748b3b..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_release.erl +++ /dev/null @@ -1,171 +0,0 @@ --module(hex_api_release). --export([ - delete/3, - get/3, - publish/2, - publish/3, - retire/4, - unretire/3 -]). - --export_type([publish_params/0, retirement_params/0, retirement_reason/0]). - --type publish_params() :: [{replace, boolean()}]. - --type retirement_reason() :: other | invalid | security | deprecated | renamed. - --ifdef(OTP_19). --type retirement_params() :: #{reason := retirement_reason(), message => binary()}. --else. --type retirement_params() :: #{reason => retirement_reason(), message => binary()}. --endif. -%% @doc -%% Gets a package release. -%% -%% Examples: -%% -%% ``` -%% > hex_api_release:get(hex_core:default_config(), <<"package">>, <<"1.0.0">>). -%% {ok, {200, ..., #{ -%% <<"checksum">> => <<"540d210d81f56f17f64309a4896430e727972499b37bd59342dc08d61dff74d8">>, -%% <<"docs_html_url">> => <<"https://hexdocs.pm/package/1.0.0/">>, -%% <<"downloads">> => 740,<<"has_docs">> => true, -%% <<"html_url">> => <<"https://hex.pm/packages/package/1.0.0">>, -%% <<"inserted_at">> => <<"2014-12-09T18:32:03Z">>, -%% <<"meta">> => -%% #{<<"app">> => <<"package">>, -%% <<"build_tools">> => [<<"mix">>]}, -%% <<"package_url">> => <<"https://hex.pm/api/packages/package">>, -%% <<"publisher">> => nil,<<"requirements">> => #{}, -%% <<"retirement">> => nil, -%% <<"updated_at">> => <<"2019-07-28T21:12:11Z">>, -%% <<"url">> => <<"https://hex.pm/api/packages/package/releases/1.0.0">>, -%% <<"version">> => <<"1.0.0">> -%% }}} -%% ''' -%% @end --spec get(hex_core:config(), binary(), binary()) -> hex_api:response(). -get(Config, Name, Version) when is_map(Config) and is_binary(Name) and is_binary(Version) -> - Path = hex_api:build_repository_path(Config, ["packages", Name, "releases", Version]), - hex_api:get(Config, Path). - -%% @doc -%% Publishes a new package release. -%% -%% Examples: -%% -%% ``` -%% > hex_api_release:publish(hex_core:default_config(), Tarball). -%% {ok, {200, ..., #{ -%% <<"checksum">> => <<"540d210d81f56f17f64309a4896430e727972499b37bd59342dc08d61dff74d8">>, -%% <<"docs_html_url">> => <<"https://hexdocs.pm/package/1.0.0/">>, -%% <<"downloads">> => 740,<<"has_docs">> => true, -%% <<"html_url">> => <<"https://hex.pm/packages/package/1.0.0">>, -%% <<"inserted_at">> => <<"2014-12-09T18:32:03Z">>, -%% <<"meta">> => -%% #{<<"app">> => <<"package">>, -%% <<"build_tools">> => [<<"mix">>]}, -%% <<"package_url">> => <<"https://hex.pm/api/packages/package">>, -%% <<"publisher">> => nil,<<"requirements">> => #{}, -%% <<"retirement">> => nil, -%% <<"updated_at">> => <<"2019-07-28T21:12:11Z">>, -%% <<"url">> => <<"https://hex.pm/api/packages/package/releases/1.0.0">>, -%% <<"version">> => <<"1.0.0">> -%% }}} -%% ''' -%% @end --spec publish(hex_core:config(), binary()) -> hex_api:response(). -publish(Config, Tarball) -> publish(Config, Tarball, []). - - -%% @doc -%% Publishes a new package release with query parameters. -%% -%% Supported query params : -%% - replace : boolean -%% -%% Examples: -%% -%% ``` -%% > hex_api_release:publish(hex_core:default_config(), Tarball, [{replace, true}]). -%% {ok, {201, ..., #{ -%% <<"checksum">> => <<"540d210d81f56f17f64309a4896430e727972499b37bd59342dc08d61dff74d8">>, -%% <<"docs_html_url">> => <<"https://hexdocs.pm/package/1.0.0/">>, -%% <<"downloads">> => 740,<<"has_docs">> => true, -%% <<"html_url">> => <<"https://hex.pm/packages/package/1.0.0">>, -%% <<"inserted_at">> => <<"2014-12-09T18:32:03Z">>, -%% <<"meta">> => -%% #{<<"app">> => <<"package">>, -%% <<"build_tools">> => [<<"mix">>]}, -%% <<"package_url">> => <<"https://hex.pm/api/packages/package">>, -%% <<"publisher">> => nil,<<"requirements">> => #{}, -%% <<"retirement">> => nil, -%% <<"updated_at">> => <<"2019-07-28T21:12:11Z">>, -%% <<"url">> => <<"https://hex.pm/api/packages/package/releases/1.0.0">>, -%% <<"version">> => <<"1.0.0">> -%% }}} -%% ''' -%% @end --spec publish(hex_core:config(), binary(), publish_params()) -> hex_api:response(). -publish(Config, Tarball, Params) when is_map(Config) andalso is_binary(Tarball) andalso is_list(Params)-> - QueryString = hex_api:encode_query_string([{replace, proplists:get_value(replace, Params, false)}]), - Path = hex_api:join_path_segments(hex_api:build_repository_path(Config, ["publish"])), - PathWithQuery = <>, - TarballContentType = "application/octet-stream", - Config2 = put_header(<<"content-length">>, integer_to_binary(byte_size(Tarball)), Config), - Body = {TarballContentType, Tarball}, - hex_api:post(Config2, PathWithQuery, Body). - -%% @doc -%% Deletes a package release. -%% -%% Examples: -%% -%% ``` -%% > hex_api_release:delete(hex_core:default_config(), <<"package">>, <<"1.0.0">>). -%% {ok, {204, ..., nil}} -%% ''' -%% @end --spec delete(hex_core:config(), binary(), binary()) -> hex_api:response(). -delete(Config, Name, Version) when is_map(Config) and is_binary(Name) and is_binary(Version) -> - Path = hex_api:build_repository_path(Config, ["packages", Name, "releases", Version]), - hex_api:delete(Config, Path). - -%% @doc -%% Retires a package release. -%% -%% Examples: -%% -%% ``` -%% > hex_api_release:retire(hex_core:default_config(), <<"package">>, <<"1.0.0">>, Params). -%% {ok, {204, ..., nil}} -%% ''' -%% @end --spec retire(hex_core:config(), binary(), binary(), retirement_params()) -> hex_api:response(). -retire(Config, Name, Version, Params) when is_map(Config) and is_binary(Name) and is_binary(Version) -> - Path = hex_api:build_repository_path(Config, ["packages", Name, "releases", Version, "retire"]), - hex_api:post(Config, Path, Params). - -%% @doc -%% Unretires a package release. -%% -%% Examples: -%% -%% ``` -%% > hex_api_release:unretire(hex_core:default_config(), <<"package">>, <<"1.0.0">>). -%% {ok, {204, ..., nil}} -%% ''' -%% @end --spec unretire(hex_core:config(), binary(), binary()) -> hex_api:response(). -unretire(Config, Name, Version) when is_map(Config) and is_binary(Name) and is_binary(Version) -> - Path = hex_api:build_repository_path(Config, ["packages", Name, "releases", Version, "retire"]), - hex_api:delete(Config, Path). - -%%==================================================================== -%% Internal functions -%%==================================================================== - -put_header(Name, Value, Config) -> - Headers = maps:get(http_headers, Config, #{}), - Headers2 = maps:put(Name, Value, Headers), - maps:put(http_headers, Headers2, Config). diff --git a/_build/default/plugins/hex_core/src/hex_api_user.erl b/_build/default/plugins/hex_core/src/hex_api_user.erl deleted file mode 100644 index 9994878880..0000000000 --- a/_build/default/plugins/hex_core/src/hex_api_user.erl +++ /dev/null @@ -1,96 +0,0 @@ --module(hex_api_user). --export([ - create/4, - get/2, - me/1, - reset_password/2 -]). - -%% @doc -%% Gets the authenticated user. -%% -%% Examples: -%% -%% ``` -%% > hex_api_user:me(hex_core:default_config()). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"full_name">> => <<"John Doe">>, -%% <<"handles">> => #{...}, -%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, -%% <<"level">> => <<"full">>, -%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec me(hex_core:config()) -> hex_api:response(). -me(Config) when is_map(Config) -> - hex_api:get(Config, ["users", "me"]). - -%% @doc -%% Creates a new user account. -%% -%% Examples: -%% -%% ``` -%% > hex_api_user:create(hex_core:default_config(), <<"user">>, <<"hunter42">>, <<"user@example.com">>). -%% {ok, {201, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"full_name">> => <<"John Doe">>, -%% <<"handles">> => #{...}, -%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, -%% <<"level">> => <<"full">>, -%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec create(hex_core:config(), binary(), binary(), binary()) -> hex_api:response(). -create(Config, Username, Password, Email) -when is_map(Config) and is_binary(Username) and is_binary(Password) and is_binary(Email) -> - Params = #{ - <<"username">> => Username, - <<"password">> => Password, - <<"email">> => Email - }, - hex_api:post(Config, ["users"], Params). - -%% @doc -%% Resets the user's password. -%% -%% Examples: -%% -%% ``` -%% > hex_api_user:reset_password(hex_core:default_config(), <<"user">>). -%% {ok, {204, ..., nil}} -%% ''' -%% @end --spec reset_password(hex_core:config(), binary()) -> hex_api:response(). -reset_password(Config, Username) when is_map(Config) and is_binary(Username) -> - hex_api:post(Config, ["users", Username, "reset"], #{}). - -%% @doc -%% Gets a user. -%% -%% Examples: -%% -%% ``` -%% > hex_api_user:get(hex_core:default_config()). -%% {ok, {200, ..., #{ -%% <<"email">> => <<"user@example.com">>, -%% <<"full_name">> => <<"John Doe">>, -%% <<"handles">> => #{...}, -%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, -%% <<"level">> => <<"full">>, -%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, -%% <<"url">> => <<"https://hex.pm/api/users/user">>, -%% <<"username">> => <<"user">> -%% }}} -%% ''' -%% @end --spec get(hex_core:config(), binary()) -> hex_api:response(). -get(Config, Username) when is_map(Config) and is_binary(Username) -> - hex_api:get(Config, ["users", Username]). diff --git a/_build/default/plugins/hex_core/src/hex_core.app.src b/_build/default/plugins/hex_core/src/hex_core.app.src deleted file mode 100644 index b4b1571926..0000000000 --- a/_build/default/plugins/hex_core/src/hex_core.app.src +++ /dev/null @@ -1,10 +0,0 @@ -{application,hex_core, - [{description,"Reference implementation of Hex specifications"}, - {vsn,"0.7.1"}, - {registered,[]}, - {applications,[kernel,stdlib]}, - {licenses,["Apache-2.0"]}, - {include_files,["CHANGELOG.md"]}, - {links,[{"GitHub","https://hub.fastgit.org/hexpm/hex_core"}, - {"Hex specifications", - "https://hub.fastgit.org/hexpm/specifications"}]}]}. diff --git a/_build/default/plugins/hex_core/src/hex_core.erl b/_build/default/plugins/hex_core/src/hex_core.erl deleted file mode 100644 index 0e2d16bea8..0000000000 --- a/_build/default/plugins/hex_core/src/hex_core.erl +++ /dev/null @@ -1,93 +0,0 @@ -%% @doc -%% hex_core entrypoint module. -%% -%% ### Config -%% -%% Most functions in the hex_core API takes a configuration. The configuration sets things -%% like HTTP client to use, and API and repository URL. Some of these configuration options -%% will likely be static for your application and some may change depending on the function -%% you call. -%% -%% ##### Options -%% -%% * `api_key' - Authentication key used when accessing the HTTP API. -%% * `api_organization' - Name of the organization endpoint in the API, this should -%% for example be set when accessing key for a specific organization. -%% * `api_repository' - Name of the repository endpoint in the API, this should -%% for example be set when accessing packages from a specific repository. -%% * `api_url' - URL to the HTTP API (default: `https://hex.pm/api'). -%% * `http_adapter' - A tuple of a callback module used for HTTP requests, see [`hex_http'](hex_http.html) -%% (default: `hex_http_httpc') and the configuration to pass to the HTTP adapter. -%% * `http_etag' - Sets the `if-none-match' HTTP header with the given value to do a -%% conditional HTTP request. -%% * `http_user_agent_fragment' - Will be appended to the `user-agent` HTTP header (default: `(httpc)'). -%% * `repo_key' - Authentication key used when accessing the repository. -%% * `repo_name' - Name of the repository, used for verifying the repository signature -%% authenticity (default: `hexpm'). -%% * `repo_public_key' - Public key used to verify the repository signature -%% (defaults to hexpm public key `https://hex.pm/docs/public_keys'). -%% * `repo_url' - URL to the repository (default: `https://repo.hex.pm'). -%% * `repo_organization' - Name of the organization repository, appends `/repos/:name' -%% to the repository URL and overrides the `repo_name' option. -%% * `repo_verify' - If `true' will verify the repository signature (default: `true'). -%% * `repo_verify_origin' - If `true' will verify the repository signature origin, -%% requires protobuf messages as of hex_core v0.4.0 (default: `true'). - --module(hex_core). --export([default_config/0]). - --export_type([config/0]). - -%% https://hex.pm/docs/public_keys --define(HEXPM_PUBLIC_KEY, <<"-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApqREcFDt5vV21JVe2QNB -Edvzk6w36aNFhVGWN5toNJRjRJ6m4hIuG4KaXtDWVLjnvct6MYMfqhC79HAGwyF+ -IqR6Q6a5bbFSsImgBJwz1oadoVKD6ZNetAuCIK84cjMrEFRkELtEIPNHblCzUkkM -3rS9+DPlnfG8hBvGi6tvQIuZmXGCxF/73hU0/MyGhbmEjIKRtG6b0sJYKelRLTPW -XgK7s5pESgiwf2YC/2MGDXjAJfpfCd0RpLdvd4eRiXtVlE9qO9bND94E7PgQ/xqZ -J1i2xWFndWa6nfFnRxZmCStCOZWYYPlaxr+FZceFbpMwzTNs4g3d4tLNUcbKAIH4 -0wIDAQAB ------END PUBLIC KEY-----">>). - - --type config() :: #{ - api_key => binary() | undefined, - api_organization => binary() | undefined, - api_repository => binary() | undefined, - api_url => binary(), - http_adapter => {module(), map()}, - http_etag => binary() | undefined, - http_headers => map(), - http_user_agent_fragment => binary(), - repo_key => binary() | undefined, - repo_name => binary(), - repo_public_key => binary(), - repo_url => binary(), - repo_organization => binary() | undefined, - repo_verify => boolean(), - repo_verify_origin => boolean(), - tarball_max_size => pos_integer(), - tarball_max_uncompressed_size => pos_integer() -}. - --spec default_config() -> config(). -default_config() -> - #{ - api_key => undefined, - api_organization => undefined, - api_repository => undefined, - api_url => <<"https://hex.pm/api">>, - http_adapter => {hex_http_httpc, #{profile => default}}, - http_etag => undefined, - http_headers => #{}, - http_user_agent_fragment => <<"(httpc)">>, - repo_key => undefined, - repo_name => <<"hexpm">>, - repo_public_key => ?HEXPM_PUBLIC_KEY, - repo_url => <<"https://repo.hex.pm">>, - repo_organization => undefined, - repo_verify => true, - repo_verify_origin => true, - tarball_max_size => 8 * 1024 * 1024, - tarball_max_uncompressed_size => 64 * 1024 * 1024 - }. diff --git a/_build/default/plugins/hex_core/src/hex_core.hrl b/_build/default/plugins/hex_core/src/hex_core.hrl deleted file mode 100644 index 1ea3142fc3..0000000000 --- a/_build/default/plugins/hex_core/src/hex_core.hrl +++ /dev/null @@ -1 +0,0 @@ --define(HEX_CORE_VERSION, "0.7.1"). diff --git a/_build/default/plugins/hex_core/src/hex_erl_tar.erl b/_build/default/plugins/hex_core/src/hex_erl_tar.erl deleted file mode 100644 index 295919c420..0000000000 --- a/_build/default/plugins/hex_core/src/hex_erl_tar.erl +++ /dev/null @@ -1,2014 +0,0 @@ -%% @private -%% Copied from https://hub.fastgit.org/erlang/otp/blob/OTP-20.0.1/lib/stdlib/src/erl_tar.erl -%% with modifications: -%% - Change module name to `hex_erl_tar` -%% - Set tar mtimes to 0 and remove dependency on :os.system_time/1 -%% - Preserve modes when building tarball -%% - Do not crash if failing to write tar -%% - Allow setting file_info opts on :hex_erl_tar.add -%% - Add safe_relative_path_links/2 to check directory traversal vulnerability when extracting files, -%% it differs from OTP's current fix (2020-02-04) in that it checks regular files instead of -%% symlink targets. This allows creating symlinks with relative path targets such as `../tmp/log` -%% - Remove ram_file usage (backported from OTP master) - -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 1997-2017. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%% -%% %CopyrightEnd% -%% -%% This module implements extraction/creation of tar archives. -%% It supports reading most common tar formats, namely V7, STAR, -%% USTAR, GNU, BSD/libarchive, and PAX. It produces archives in USTAR -%% format, unless it must use PAX headers, in which case it produces PAX -%% format. -%% -%% The following references where used: -%% http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5 -%% http://www.gnu.org/software/tar/manual/html_node/Standard.html -%% http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html --module(hex_erl_tar). - --export([init/3, - create/2, create/3, - extract/1, extract/2, - table/1, table/2, t/1, tt/1, - open/2, close/1, - add/3, add/4, add/5, - format_error/1]). - --include_lib("kernel/include/file.hrl"). --include_lib("hex_erl_tar.hrl"). - -%% Converts the short error reason to a descriptive string. --spec format_error(term()) -> string(). -format_error(invalid_tar_checksum) -> - "Checksum failed"; -format_error(bad_header) -> - "Unrecognized tar header format"; -format_error({bad_header, Reason}) -> - lists:flatten(io_lib:format("Unrecognized tar header format: ~p", [Reason])); -format_error({invalid_header, negative_size}) -> - "Invalid header: negative size"; -format_error(invalid_sparse_header_size) -> - "Invalid sparse header: negative size"; -format_error(invalid_sparse_map_entry) -> - "Invalid sparse map entry"; -format_error({invalid_sparse_map_entry, Reason}) -> - lists:flatten(io_lib:format("Invalid sparse map entry: ~p", [Reason])); -format_error(invalid_end_of_archive) -> - "Invalid end of archive"; -format_error(eof) -> - "Unexpected end of file"; -format_error(integer_overflow) -> - "Failed to parse numeric: integer overflow"; -format_error({misaligned_read, Pos}) -> - lists:flatten(io_lib:format("Read a block which was misaligned: block_size=~p pos=~p", - [?BLOCK_SIZE, Pos])); -format_error(invalid_gnu_1_0_sparsemap) -> - "Invalid GNU sparse map (version 1.0)"; -format_error({invalid_gnu_0_1_sparsemap, Format}) -> - lists:flatten(io_lib:format("Invalid GNU sparse map (version ~s)", [Format])); -format_error(unsafe_path) -> - "The path points above the current working directory"; -format_error({Name,Reason}) -> - lists:flatten(io_lib:format("~ts: ~ts", [Name,format_error(Reason)])); -format_error(Atom) when is_atom(Atom) -> - file:format_error(Atom); -format_error(Term) -> - lists:flatten(io_lib:format("~tp", [Term])). - -%% Initializes a new reader given a custom file handle and I/O wrappers --spec init(handle(), write | read, file_op()) -> {ok, reader()} | {error, badarg}. -init(Handle, AccessMode, Fun) when is_function(Fun, 2) -> - Reader = #reader{handle=Handle,access=AccessMode,func=Fun}, - {ok, Pos, Reader2} = do_position(Reader, {cur, 0}), - {ok, Reader2#reader{pos=Pos}}; -init(_Handle, _AccessMode, _Fun) -> - {error, badarg}. - -%%%================================================================ -%% Extracts all files from the tar file Name. --spec extract(open_handle()) -> ok | {error, term()}. -extract(Name) -> - extract(Name, []). - -%% Extracts (all) files from the tar file Name. -%% Options accepted: -%% - cooked: Opens the tar file without mode `raw` -%% - compressed: Uncompresses the tar file when reading -%% - memory: Returns the tar contents as a list of tuples {Name, Bin} -%% - keep_old_files: Extracted files will not overwrite the destination -%% - {files, ListOfFilesToExtract}: Only extract ListOfFilesToExtract -%% - verbose: Prints verbose information about the extraction, -%% - {cwd, AbsoluteDir}: Sets the current working directory for the extraction --spec extract(open_handle(), [extract_opt()]) -> - ok - | {ok, [{string(), binary()}]} - | {error, term()}. -extract({binary, Bin}, Opts) when is_list(Opts) -> - do_extract({binary, Bin}, Opts); -extract({file, Fd}, Opts) when is_list(Opts) -> - do_extract({file, Fd}, Opts); -extract(#reader{}=Reader, Opts) when is_list(Opts) -> - do_extract(Reader, Opts); -extract(Name, Opts) when is_list(Name); is_binary(Name), is_list(Opts) -> - do_extract(Name, Opts). - -do_extract(Handle, Opts) when is_list(Opts) -> - Opts2 = extract_opts(Opts), - Acc = if Opts2#read_opts.output =:= memory -> []; true -> ok end, - foldl_read(Handle, fun extract1/4, Acc, Opts2). - -extract1(eof, Reader, _, Acc) when is_list(Acc) -> - {ok, {ok, lists:reverse(Acc)}, Reader}; -extract1(eof, Reader, _, leading_slash) -> - error_logger:info_msg("erl_tar: removed leading '/' from member names\n"), - {ok, ok, Reader}; -extract1(eof, Reader, _, Acc) -> - {ok, Acc, Reader}; -extract1(#tar_header{name=Name,size=Size}=Header, Reader0, Opts, Acc0) -> - case check_extract(Name, Opts) of - true -> - case do_read(Reader0, Size) of - {ok, Bin, Reader1} -> - Acc = extract2(Header, Bin, Opts, Acc0), - {ok, Acc, Reader1}; - {error, _} = Err -> - throw(Err) - end; - false -> - {ok, Acc0, skip_file(Reader0)} - end. - -extract2(Header, Bin, Opts, Acc) -> - case write_extracted_element(Header, Bin, Opts) of - ok -> - case Header of - #tar_header{name="/"++_} -> - leading_slash; - #tar_header{} -> - Acc - end; - {ok, NameBin} when is_list(Acc) -> - [NameBin | Acc]; - {error, _} = Err -> - throw(Err) - end. - -%% Checks if the file Name should be extracted. -check_extract(_, #read_opts{files=all}) -> - true; -check_extract(Name, #read_opts{files=Files}) -> - ordsets:is_element(Name, Files). - -%%%================================================================ -%% The following table functions produce a list of information about -%% the files contained in the archive. --type filename() :: string(). --type typeflag() :: regular | link | symlink | - char | block | directory | - fifo | reserved | unknown. --type mode() :: non_neg_integer(). --type uid() :: non_neg_integer(). --type gid() :: non_neg_integer(). - --type tar_entry() :: {filename(), - typeflag(), - non_neg_integer(), - tar_time(), - mode(), - uid(), - gid()}. - -%% Returns a list of names of the files in the tar file Name. --spec table(open_handle()) -> {ok, [string()]} | {error, term()}. -table(Name) -> - table(Name, []). - -%% Returns a list of names of the files in the tar file Name. -%% Options accepted: compressed, verbose, cooked. --spec table(open_handle(), [compressed | verbose | cooked]) -> - {ok, [tar_entry()]} | {error, term()}. -table(Name, Opts) when is_list(Opts) -> - foldl_read(Name, fun table1/4, [], table_opts(Opts)). - -table1(eof, Reader, _, Result) -> - {ok, {ok, lists:reverse(Result)}, Reader}; -table1(#tar_header{}=Header, Reader, #read_opts{verbose=Verbose}, Result) -> - Attrs = table1_attrs(Header, Verbose), - Reader2 = skip_file(Reader), - {ok, [Attrs|Result], Reader2}. - -%% Extracts attributes relevant to table1's output -table1_attrs(#tar_header{typeflag=Typeflag,mode=Mode}=Header, true) -> - Type = typeflag(Typeflag), - Name = Header#tar_header.name, - Mtime = Header#tar_header.mtime, - Uid = Header#tar_header.uid, - Gid = Header#tar_header.gid, - Size = Header#tar_header.size, - {Name, Type, Size, Mtime, Mode, Uid, Gid}; -table1_attrs(#tar_header{name=Name}, _Verbose) -> - Name. - -typeflag(?TYPE_REGULAR) -> regular; -typeflag(?TYPE_REGULAR_A) -> regular; -typeflag(?TYPE_GNU_SPARSE) -> regular; -typeflag(?TYPE_CONT) -> regular; -typeflag(?TYPE_LINK) -> link; -typeflag(?TYPE_SYMLINK) -> symlink; -typeflag(?TYPE_CHAR) -> char; -typeflag(?TYPE_BLOCK) -> block; -typeflag(?TYPE_DIR) -> directory; -typeflag(?TYPE_FIFO) -> fifo; -typeflag(_) -> unknown. - -%%%================================================================ -%% Comments for printing the contents of a tape archive, -%% meant to be invoked from the shell. - -%% Prints each filename in the archive --spec t(file:filename()) -> ok | {error, term()}. -t(Name) when is_list(Name); is_binary(Name) -> - case table(Name) of - {ok, List} -> - lists:foreach(fun(N) -> ok = io:format("~ts\n", [N]) end, List); - Error -> - Error - end. - -%% Prints verbose information about each file in the archive --spec tt(open_handle()) -> ok | {error, term()}. -tt(Name) -> - case table(Name, [verbose]) of - {ok, List} -> - lists:foreach(fun print_header/1, List); - Error -> - Error - end. - -%% Used by tt/1 to print a tar_entry tuple --spec print_header(tar_entry()) -> ok. -print_header({Name, Type, Size, Mtime, Mode, Uid, Gid}) -> - io:format("~s~s ~4w/~-4w ~7w ~s ~s\n", - [type_to_string(Type), mode_to_string(Mode), - Uid, Gid, Size, time_to_string(Mtime), Name]). - -type_to_string(regular) -> "-"; -type_to_string(directory) -> "d"; -type_to_string(link) -> "l"; -type_to_string(symlink) -> "s"; -type_to_string(char) -> "c"; -type_to_string(block) -> "b"; -type_to_string(fifo) -> "f"; -type_to_string(unknown) -> "?". - -%% Converts a numeric mode to its human-readable representation -mode_to_string(Mode) -> - mode_to_string(Mode, "xwrxwrxwr", []). -mode_to_string(Mode, [C|T], Acc) when Mode band 1 =:= 1 -> - mode_to_string(Mode bsr 1, T, [C|Acc]); -mode_to_string(Mode, [_|T], Acc) -> - mode_to_string(Mode bsr 1, T, [$-|Acc]); -mode_to_string(_, [], Acc) -> - Acc. - -%% Converts a tar_time() (POSIX time) to a readable string -time_to_string(Secs0) -> - Epoch = calendar:datetime_to_gregorian_seconds(?EPOCH), - Secs = Epoch + Secs0, - DateTime0 = calendar:gregorian_seconds_to_datetime(Secs), - DateTime = calendar:universal_time_to_local_time(DateTime0), - {{Y, Mon, Day}, {H, Min, _}} = DateTime, - io_lib:format("~s ~2w ~s:~s ~w", [month(Mon), Day, two_d(H), two_d(Min), Y]). - -two_d(N) -> - tl(integer_to_list(N + 100)). - -month(1) -> "Jan"; -month(2) -> "Feb"; -month(3) -> "Mar"; -month(4) -> "Apr"; -month(5) -> "May"; -month(6) -> "Jun"; -month(7) -> "Jul"; -month(8) -> "Aug"; -month(9) -> "Sep"; -month(10) -> "Oct"; -month(11) -> "Nov"; -month(12) -> "Dec". - -%%%================================================================ -%% The open function with friends is to keep the file and binary api of this module --type open_handle() :: file:filename() - | {binary, binary()} - | {file, term()}. --spec open(open_handle(), [write | compressed | cooked]) -> - {ok, reader()} | {error, term()}. -open({binary, Bin}, Mode) when is_binary(Bin) -> - do_open({binary, Bin}, Mode); -open({file, Fd}, Mode) -> - do_open({file, Fd}, Mode); -open(Name, Mode) when is_list(Name); is_binary(Name) -> - do_open(Name, Mode). - -do_open(Name, Mode) when is_list(Mode) -> - case open_mode(Mode) of - {ok, Access, Raw, Opts} -> - open1(Name, Access, Raw, Opts); - {error, Reason} -> - {error, {Name, Reason}} - end. - -open1({binary,Bin0}, read, _Raw, Opts) when is_binary(Bin0) -> - Bin = case lists:member(compressed, Opts) of - true -> - try - zlib:gunzip(Bin0) - catch - _:_ -> Bin0 - end; - false -> - Bin0 - end, - case file:open(Bin, [ram,binary,read]) of - {ok,File} -> - {ok, #reader{handle=File,access=read,func=fun file_op/2}}; - Error -> - Error - end; -open1({file, Fd}, read, _Raw, _Opts) -> - Reader = #reader{handle=Fd,access=read,func=fun file_op/2}, - case do_position(Reader, {cur, 0}) of - {ok, Pos, Reader2} -> - {ok, Reader2#reader{pos=Pos}}; - {error, _} = Err -> - Err - end; -open1(Name, Access, Raw, Opts) when is_list(Name) or is_binary(Name) -> - case file:open(Name, Raw ++ [binary, Access|Opts]) of - {ok, File} -> - {ok, #reader{handle=File,access=Access,func=fun file_op/2}}; - {error, Reason} -> - {error, {Name, Reason}} - end. - -open_mode(Mode) -> - open_mode(Mode, false, [raw], []). - -open_mode(read, _, Raw, _) -> - {ok, read, Raw, []}; -open_mode(write, _, Raw, _) -> - {ok, write, Raw, []}; -open_mode([read|Rest], false, Raw, Opts) -> - open_mode(Rest, read, Raw, Opts); -open_mode([write|Rest], false, Raw, Opts) -> - open_mode(Rest, write, Raw, Opts); -open_mode([compressed|Rest], Access, Raw, Opts) -> - open_mode(Rest, Access, Raw, [compressed|Opts]); -open_mode([cooked|Rest], Access, _Raw, Opts) -> - open_mode(Rest, Access, [], Opts); -open_mode([], Access, Raw, Opts) -> - {ok, Access, Raw, Opts}; -open_mode(_, _, _, _) -> - {error, einval}. - -file_op(write, {Fd, Data}) -> - file:write(Fd, Data); -file_op(position, {Fd, Pos}) -> - file:position(Fd, Pos); -file_op(read2, {Fd, Size}) -> - file:read(Fd, Size); -file_op(close, Fd) -> - file:close(Fd). - -%% Closes a tar archive. --spec close(reader()) -> ok | {error, term()}. -close(#reader{access=read}=Reader) -> - ok = do_close(Reader); -close(#reader{access=write}=Reader) -> - {ok, Reader2} = pad_file(Reader), - ok = do_close(Reader2), - ok; -close(_) -> - {error, einval}. - -pad_file(#reader{pos=Pos}=Reader) -> - %% There must be at least two zero blocks at the end. - PadCurrent = skip_padding(Pos+?BLOCK_SIZE), - Padding = <<0:PadCurrent/unit:8>>, - do_write(Reader, [Padding, ?ZERO_BLOCK, ?ZERO_BLOCK]). - - -%%%================================================================ -%% Creation/modification of tar archives - -%% Creates a tar file Name containing the given files. --spec create(file:filename(), filelist()) -> ok | {error, {string(), term()}}. -create(Name, FileList) when is_list(Name); is_binary(Name) -> - create(Name, FileList, []). - -%% Creates a tar archive Name containing the given files. -%% Accepted options: verbose, compressed, cooked --spec create(file:filename(), filelist(), [create_opt()]) -> - ok | {error, term()} | {error, {string(), term()}}. -create(Name, FileList, Options) when is_list(Name); is_binary(Name) -> - Mode = lists:filter(fun(X) -> (X=:=compressed) or (X=:=cooked) - end, Options), - case open(Name, [write|Mode]) of - {ok, TarFile} -> - do_create(TarFile, FileList, Options); - {error, _} = Err -> - Err - end. - -do_create(TarFile, [], _Opts) -> - close(TarFile); -do_create(TarFile, [{NameInArchive, NameOrBin}|Rest], Opts) -> - case add(TarFile, NameOrBin, NameInArchive, Opts) of - ok -> - do_create(TarFile, Rest, Opts); - {error, _} = Err -> - _ = close(TarFile), - Err - end; -do_create(TarFile, [Name|Rest], Opts) -> - case add(TarFile, Name, Name, Opts) of - ok -> - do_create(TarFile, Rest, Opts); - {error, _} = Err -> - _ = close(TarFile), - Err - end. - -%% Adds a file to a tape archive. --type add_type() :: string() - | {string(), string()} - | {string(), binary()}. --spec add(reader(), add_type(), [add_opt()]) -> ok | {error, term()}. -add(Reader, {NameInArchive, Name}, Opts) - when is_list(NameInArchive), is_list(Name) -> - do_add(Reader, Name, NameInArchive, undefined, Opts); -add(Reader, {NameInArchive, Bin}, Opts) - when is_list(NameInArchive), is_binary(Bin) -> - do_add(Reader, Bin, NameInArchive, undefined, Opts); -add(Reader, {NameInArchive, Bin, Mode}, Opts) - when is_list(NameInArchive), is_binary(Bin), is_integer(Mode) -> - do_add(Reader, Bin, NameInArchive, Mode, Opts); -add(Reader, Name, Opts) when is_list(Name) -> - do_add(Reader, Name, Name, undefined, Opts). - - --spec add(reader(), string() | binary(), string(), [add_opt()]) -> - ok | {error, term()}. -add(Reader, NameOrBin, NameInArchive, Options) - when is_list(NameOrBin); is_binary(NameOrBin), - is_list(NameInArchive), is_list(Options) -> - do_add(Reader, NameOrBin, NameInArchive, undefined, Options). - --spec add(reader(), string() | binary(), string(), integer(), [add_opt()]) -> - ok | {error, term()}. -add(Reader, NameOrBin, NameInArchive, Mode, Options) - when is_list(NameOrBin); is_binary(NameOrBin), - is_list(NameInArchive), is_integer(Mode), is_list(Options) -> - do_add(Reader, NameOrBin, NameInArchive, Mode, Options). - -do_add(#reader{access=write}=Reader, Name, NameInArchive, Mode, Options) - when is_list(NameInArchive), is_list(Options) -> - RF = fun(F) -> apply_file_info_opts(Options, file:read_link_info(F, [{time, posix}])) end, - Opts = #add_opts{read_info=RF}, - add1(Reader, Name, NameInArchive, Mode, add_opts(Options, Options, Opts)); -do_add(#reader{access=read},_,_,_,_) -> - {error, eacces}; -do_add(Reader,_,_,_,_) -> - {error, {badarg, Reader}}. - -add_opts([dereference|T], AllOptions, Opts) -> - RF = fun(F) -> apply_file_info_opts(AllOptions, file:read_file_info(F, [{time, posix}])) end, - add_opts(T, AllOptions, Opts#add_opts{read_info=RF}); -add_opts([verbose|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{verbose=true}); -add_opts([{chunks,N}|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{chunk_size=N}); -add_opts([{atime,Value}|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{atime=Value}); -add_opts([{mtime,Value}|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{mtime=Value}); -add_opts([{ctime,Value}|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{ctime=Value}); -add_opts([{uid,Value}|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{uid=Value}); -add_opts([{gid,Value}|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts#add_opts{gid=Value}); -add_opts([_|T], AllOptions, Opts) -> - add_opts(T, AllOptions, Opts); -add_opts([], _AllOptions, Opts) -> - Opts. - -apply_file_info_opts(Opts, {ok, FileInfo}) -> - {ok, do_apply_file_info_opts(Opts, FileInfo)}; -apply_file_info_opts(_Opts, Other) -> - Other. - -do_apply_file_info_opts([{atime,Value}|T], FileInfo) -> - do_apply_file_info_opts(T, FileInfo#file_info{atime=Value}); -do_apply_file_info_opts([{mtime,Value}|T], FileInfo) -> - do_apply_file_info_opts(T, FileInfo#file_info{mtime=Value}); -do_apply_file_info_opts([{ctime,Value}|T], FileInfo) -> - do_apply_file_info_opts(T, FileInfo#file_info{ctime=Value}); -do_apply_file_info_opts([{uid,Value}|T], FileInfo) -> - do_apply_file_info_opts(T, FileInfo#file_info{uid=Value}); -do_apply_file_info_opts([{gid,Value}|T], FileInfo) -> - do_apply_file_info_opts(T, FileInfo#file_info{gid=Value}); -do_apply_file_info_opts([_|T], FileInfo) -> - do_apply_file_info_opts(T, FileInfo); -do_apply_file_info_opts([], FileInfo) -> - FileInfo. - -add1(#reader{}=Reader, Name, NameInArchive, undefined, #add_opts{read_info=ReadInfo}=Opts) - when is_list(Name) -> - Res = case ReadInfo(Name) of - {error, Reason0} -> - {error, {Name, Reason0}}; - {ok, #file_info{type=symlink}=Fi} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - {ok, Linkname} = file:read_link(Name), - Header = fileinfo_to_header(NameInArchive, Fi, Linkname), - add_header(Reader, Header, Opts); - {ok, #file_info{type=regular}=Fi} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - Header = fileinfo_to_header(NameInArchive, Fi, false), - {ok, Reader2} = add_header(Reader, Header, Opts), - FileSize = Header#tar_header.size, - {ok, FileSize, Reader3} = do_copy(Reader2, Name, Opts), - Padding = skip_padding(FileSize), - Pad = <<0:Padding/unit:8>>, - do_write(Reader3, Pad); - {ok, #file_info{type=directory}=Fi} -> - add_directory(Reader, Name, NameInArchive, Fi, Opts); - {ok, #file_info{}=Fi} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - Header = fileinfo_to_header(NameInArchive, Fi, false), - add_header(Reader, Header, Opts) - end, - case Res of - ok -> ok; - {ok, _Reader} -> ok; - {error, _Reason} = Err -> Err - end; -add1(Reader, Bin, NameInArchive, Mode, Opts) when is_binary(Bin) -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - Now = 0, - Header = #tar_header{ - name = NameInArchive, - size = byte_size(Bin), - typeflag = ?TYPE_REGULAR, - atime = add_opts_time(Opts#add_opts.atime, Now), - mtime = add_opts_time(Opts#add_opts.mtime, Now), - ctime = add_opts_time(Opts#add_opts.ctime, Now), - uid = Opts#add_opts.uid, - gid = Opts#add_opts.gid, - mode = default_mode(Mode, 8#100644)}, - {ok, Reader2} = add_header(Reader, Header, Opts), - Padding = skip_padding(byte_size(Bin)), - Data = [Bin, <<0:Padding/unit:8>>], - case do_write(Reader2, Data) of - {ok, _Reader3} -> ok; - {error, Reason} -> {error, {NameInArchive, Reason}} - end. - -add_opts_time(undefined, _Now) -> 0; -add_opts_time(Time, _Now) -> Time. - -default_mode(undefined, Mode) -> Mode; -default_mode(Mode, _) -> Mode. - -add_directory(Reader, DirName, NameInArchive, Info, Opts) -> - case file:list_dir(DirName) of - {ok, []} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - Header = fileinfo_to_header(NameInArchive, Info, false), - add_header(Reader, Header, Opts); - {ok, Files} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - try add_files(Reader, Files, DirName, NameInArchive, Opts) of - ok -> ok; - {error, _} = Err -> Err - catch - throw:{error, {_Name, _Reason}} = Err -> Err; - throw:{error, Reason} -> {error, {DirName, Reason}} - end; - {error, Reason} -> - {error, {DirName, Reason}} - end. - -add_files(_Reader, [], _Dir, _DirInArchive, _Opts) -> - ok; -add_files(Reader, [Name|Rest], Dir, DirInArchive, #add_opts{read_info=Info}=Opts) -> - FullName = filename:join(Dir, Name), - NameInArchive = filename:join(DirInArchive, Name), - Res = case Info(FullName) of - {error, Reason} -> - {error, {FullName, Reason}}; - {ok, #file_info{type=directory}=Fi} -> - add_directory(Reader, FullName, NameInArchive, Fi, Opts); - {ok, #file_info{type=symlink}=Fi} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - {ok, Linkname} = file:read_link(FullName), - Header = fileinfo_to_header(NameInArchive, Fi, Linkname), - add_header(Reader, Header, Opts); - {ok, #file_info{type=regular}=Fi} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - Header = fileinfo_to_header(NameInArchive, Fi, false), - {ok, Reader2} = add_header(Reader, Header, Opts), - FileSize = Header#tar_header.size, - {ok, FileSize, Reader3} = do_copy(Reader2, FullName, Opts), - Padding = skip_padding(FileSize), - Pad = <<0:Padding/unit:8>>, - do_write(Reader3, Pad); - {ok, #file_info{}=Fi} -> - add_verbose(Opts, "a ~ts~n", [NameInArchive]), - Header = fileinfo_to_header(NameInArchive, Fi, false), - add_header(Reader, Header, Opts) - end, - case Res of - ok -> add_files(Reader, Rest, Dir, DirInArchive, Opts); - {ok, ReaderNext} -> add_files(ReaderNext, Rest, Dir, DirInArchive, Opts); - {error, _} = Err -> Err - end. - -format_string(String, Size) when length(String) > Size -> - throw({error, {write_string, field_too_long}}); -format_string(String, Size) -> - Ascii = to_ascii(String), - if byte_size(Ascii) < Size -> - [Ascii, 0]; - true -> - Ascii - end. - -format_octal(Octal) -> - iolist_to_binary(io_lib:fwrite("~.8B", [Octal])). - -add_header(#reader{}=Reader, #tar_header{}=Header, Opts) -> - {ok, Iodata} = build_header(Header, Opts), - do_write(Reader, Iodata). - -write_to_block(Block, IoData, Start) when is_list(IoData) -> - write_to_block(Block, iolist_to_binary(IoData), Start); -write_to_block(Block, Bin, Start) when is_binary(Bin) -> - Size = byte_size(Bin), - <> = Block, - <>. - -build_header(#tar_header{}=Header, Opts) -> - #tar_header{ - name=Name, - mode=Mode, - uid=Uid, - gid=Gid, - size=Size, - typeflag=Type, - linkname=Linkname, - uname=Uname, - gname=Gname, - devmajor=Devmaj, - devminor=Devmin - } = Header, - Mtime = Header#tar_header.mtime, - - Block0 = ?ZERO_BLOCK, - {Block1, Pax0} = write_string(Block0, ?V7_NAME, ?V7_NAME_LEN, Name, ?PAX_PATH, #{}), - Block2 = write_octal(Block1, ?V7_MODE, ?V7_MODE_LEN, Mode), - {Block3, Pax1} = write_numeric(Block2, ?V7_UID, ?V7_UID_LEN, Uid, ?PAX_UID, Pax0), - {Block4, Pax2} = write_numeric(Block3, ?V7_GID, ?V7_GID_LEN, Gid, ?PAX_GID, Pax1), - {Block5, Pax3} = write_numeric(Block4, ?V7_SIZE, ?V7_SIZE_LEN, Size, ?PAX_SIZE, Pax2), - {Block6, Pax4} = write_numeric(Block5, ?V7_MTIME, ?V7_MTIME_LEN, Mtime, ?PAX_NONE, Pax3), - {Block7, Pax5} = write_string(Block6, ?V7_TYPE, ?V7_TYPE_LEN, <>, ?PAX_NONE, Pax4), - {Block8, Pax6} = write_string(Block7, ?V7_LINKNAME, ?V7_LINKNAME_LEN, - Linkname, ?PAX_LINKPATH, Pax5), - {Block9, Pax7} = write_string(Block8, ?USTAR_UNAME, ?USTAR_UNAME_LEN, - Uname, ?PAX_UNAME, Pax6), - {Block10, Pax8} = write_string(Block9, ?USTAR_GNAME, ?USTAR_GNAME_LEN, - Gname, ?PAX_GNAME, Pax7), - {Block11, Pax9} = write_numeric(Block10, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN, - Devmaj, ?PAX_NONE, Pax8), - {Block12, Pax10} = write_numeric(Block11, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN, - Devmin, ?PAX_NONE, Pax9), - {Block13, Pax11} = set_path(Block12, Pax10), - PaxEntry = case maps:size(Pax11) of - 0 -> []; - _ -> build_pax_entry(Header, Pax11, Opts) - end, - Block14 = set_format(Block13, ?FORMAT_USTAR), - Block15 = set_checksum(Block14), - {ok, [PaxEntry, Block15]}. - -set_path(Block0, Pax) -> - %% only use ustar header when name is too long - case maps:get(?PAX_PATH, Pax, nil) of - nil -> - {Block0, Pax}; - PaxPath -> - case split_ustar_path(PaxPath) of - {ok, UstarName, UstarPrefix} -> - {Block1, _} = write_string(Block0, ?V7_NAME, ?V7_NAME_LEN, - UstarName, ?PAX_NONE, #{}), - {Block2, _} = write_string(Block1, ?USTAR_PREFIX, ?USTAR_PREFIX_LEN, - UstarPrefix, ?PAX_NONE, #{}), - {Block2, maps:remove(?PAX_PATH, Pax)}; - false -> - {Block0, Pax} - end - end. - -set_format(Block0, Format) - when Format =:= ?FORMAT_USTAR; Format =:= ?FORMAT_PAX -> - Block1 = write_to_block(Block0, ?MAGIC_USTAR, ?USTAR_MAGIC), - write_to_block(Block1, ?VERSION_USTAR, ?USTAR_VERSION); -set_format(_Block, Format) -> - throw({error, {invalid_format, Format}}). - -set_checksum(Block) -> - Checksum = compute_checksum(Block), - write_octal(Block, ?V7_CHKSUM, ?V7_CHKSUM_LEN, Checksum). - -build_pax_entry(Header, PaxAttrs, Opts) -> - Path = Header#tar_header.name, - Filename = filename:basename(Path), - Dir = filename:dirname(Path), - Path2 = filename:join([Dir, "PaxHeaders.0", Filename]), - AsciiPath = to_ascii(Path2), - Path3 = if byte_size(AsciiPath) > ?V7_NAME_LEN -> - binary_part(AsciiPath, 0, ?V7_NAME_LEN - 1); - true -> - AsciiPath - end, - Keys = maps:keys(PaxAttrs), - SortedKeys = lists:sort(Keys), - PaxFile = build_pax_file(SortedKeys, PaxAttrs), - Size = byte_size(PaxFile), - Padding = (?BLOCK_SIZE - - (byte_size(PaxFile) rem ?BLOCK_SIZE)) rem ?BLOCK_SIZE, - Pad = <<0:Padding/unit:8>>, - PaxHeader = #tar_header{ - name=unicode:characters_to_list(Path3), - size=Size, - mtime=Header#tar_header.mtime, - atime=Header#tar_header.atime, - ctime=Header#tar_header.ctime, - typeflag=?TYPE_X_HEADER - }, - {ok, PaxHeaderData} = build_header(PaxHeader, Opts), - [PaxHeaderData, PaxFile, Pad]. - -build_pax_file(Keys, PaxAttrs) -> - build_pax_file(Keys, PaxAttrs, []). -build_pax_file([], _, Acc) -> - unicode:characters_to_binary(Acc); -build_pax_file([K|Rest], Attrs, Acc) -> - V = maps:get(K, Attrs), - Size = sizeof(K) + sizeof(V) + 3, - Size2 = sizeof(Size) + Size, - Key = to_string(K), - Value = to_string(V), - Record = unicode:characters_to_binary(io_lib:format("~B ~ts=~ts\n", [Size2, Key, Value])), - if byte_size(Record) =/= Size2 -> - Size3 = byte_size(Record), - Record2 = io_lib:format("~B ~ts=~ts\n", [Size3, Key, Value]), - build_pax_file(Rest, Attrs, [Acc, Record2]); - true -> - build_pax_file(Rest, Attrs, [Acc, Record]) - end. - -sizeof(Bin) when is_binary(Bin) -> - byte_size(Bin); -sizeof(List) when is_list(List) -> - length(List); -sizeof(N) when is_integer(N) -> - byte_size(integer_to_binary(N)); -sizeof(N) when is_float(N) -> - byte_size(float_to_binary(N)). - -to_string(Bin) when is_binary(Bin) -> - unicode:characters_to_list(Bin); -to_string(List) when is_list(List) -> - List; -to_string(N) when is_integer(N) -> - integer_to_list(N); -to_string(N) when is_float(N) -> - float_to_list(N). - -split_ustar_path(Path) -> - Len = length(Path), - NotAscii = not is_ascii(Path), - if Len =< ?V7_NAME_LEN; NotAscii -> - false; - true -> - PathBin = binary:list_to_bin(Path), - case binary:split(PathBin, [<<$/>>], [global, trim_all]) of - [Part] when byte_size(Part) >= ?V7_NAME_LEN -> - false; - Parts -> - case lists:last(Parts) of - Name when byte_size(Name) >= ?V7_NAME_LEN -> - false; - Name -> - Parts2 = lists:sublist(Parts, length(Parts) - 1), - join_split_ustar_path(Parts2, {ok, Name, nil}) - end - end - end. - -join_split_ustar_path([], Acc) -> - Acc; -join_split_ustar_path([Part|_], {ok, _, nil}) - when byte_size(Part) > ?USTAR_PREFIX_LEN -> - false; -join_split_ustar_path([Part|_], {ok, _Name, Acc}) - when (byte_size(Part)+byte_size(Acc)) > ?USTAR_PREFIX_LEN -> - false; -join_split_ustar_path([Part|Rest], {ok, Name, nil}) -> - join_split_ustar_path(Rest, {ok, Name, Part}); -join_split_ustar_path([Part|Rest], {ok, Name, Acc}) -> - join_split_ustar_path(Rest, {ok, Name, <>}). - -write_octal(Block, Pos, Size, X) -> - Octal = zero_pad(format_octal(X), Size-1), - if byte_size(Octal) < Size -> - write_to_block(Block, Octal, Pos); - true -> - throw({error, {write_failed, octal_field_too_long}}) - end. - -write_string(Block, Pos, Size, Str, PaxAttr, Pax0) -> - NotAscii = not is_ascii(Str), - if PaxAttr =/= ?PAX_NONE andalso (length(Str) > Size orelse NotAscii) -> - Pax1 = maps:put(PaxAttr, Str, Pax0), - {Block, Pax1}; - true -> - Formatted = format_string(Str, Size), - {write_to_block(Block, Formatted, Pos), Pax0} - end. -write_numeric(Block, Pos, Size, X, PaxAttr, Pax0) -> - %% attempt octal - Octal = zero_pad(format_octal(X), Size-1), - if byte_size(Octal) < Size -> - {write_to_block(Block, [Octal, 0], Pos), Pax0}; - PaxAttr =/= ?PAX_NONE -> - Pax1 = maps:put(PaxAttr, X, Pax0), - {Block, Pax1}; - true -> - throw({error, {write_failed, numeric_field_too_long}}) - end. - -zero_pad(Str, Size) when byte_size(Str) >= Size -> - Str; -zero_pad(Str, Size) -> - Padding = Size - byte_size(Str), - Pad = binary:copy(<<$0>>, Padding), - <>. - - -%%%================================================================ -%% Functions for creating or modifying tar archives - -read_block(Reader) -> - case do_read(Reader, ?BLOCK_SIZE) of - eof -> - throw({error, eof}); - %% Two zero blocks mark the end of the archive - {ok, ?ZERO_BLOCK, Reader1} -> - case do_read(Reader1, ?BLOCK_SIZE) of - eof -> - % This is technically a malformed end-of-archive marker, - % as two ZERO_BLOCKs are expected as the marker, - % but if we've already made it this far, we should just ignore it - eof; - {ok, ?ZERO_BLOCK, _Reader2} -> - eof; - {ok, _Block, _Reader2} -> - throw({error, invalid_end_of_archive}); - {error,_} = Err -> - throw(Err) - end; - {ok, Block, Reader1} when is_binary(Block) -> - {ok, Block, Reader1}; - {error, _} = Err -> - throw(Err) - end. - -get_header(#reader{}=Reader) -> - case read_block(Reader) of - eof -> - eof; - {ok, Block, Reader1} -> - convert_header(Block, Reader1) - end. - -%% Converts the tar header to a record. -to_v7(Bin) when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - #header_v7{ - name=binary_part(Bin, ?V7_NAME, ?V7_NAME_LEN), - mode=binary_part(Bin, ?V7_MODE, ?V7_MODE_LEN), - uid=binary_part(Bin, ?V7_UID, ?V7_UID_LEN), - gid=binary_part(Bin, ?V7_GID, ?V7_GID_LEN), - size=binary_part(Bin, ?V7_SIZE, ?V7_SIZE_LEN), - mtime=binary_part(Bin, ?V7_MTIME, ?V7_MTIME_LEN), - checksum=binary_part(Bin, ?V7_CHKSUM, ?V7_CHKSUM_LEN), - typeflag=binary:at(Bin, ?V7_TYPE), - linkname=binary_part(Bin, ?V7_LINKNAME, ?V7_LINKNAME_LEN) - }; -to_v7(_) -> - {error, header_block_too_small}. - -to_gnu(#header_v7{}=V7, Bin) - when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - #header_gnu{ - header_v7=V7, - magic=binary_part(Bin, ?GNU_MAGIC, ?GNU_MAGIC_LEN), - version=binary_part(Bin, ?GNU_VERSION, ?GNU_VERSION_LEN), - uname=binary_part(Bin, 265, 32), - gname=binary_part(Bin, 297, 32), - devmajor=binary_part(Bin, 329, 8), - devminor=binary_part(Bin, 337, 8), - atime=binary_part(Bin, 345, 12), - ctime=binary_part(Bin, 357, 12), - sparse=to_sparse_array(binary_part(Bin, 386, 24*4+1)), - real_size=binary_part(Bin, 483, 12) - }. - -to_star(#header_v7{}=V7, Bin) - when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - #header_star{ - header_v7=V7, - magic=binary_part(Bin, ?USTAR_MAGIC, ?USTAR_MAGIC_LEN), - version=binary_part(Bin, ?USTAR_VERSION, ?USTAR_VERSION_LEN), - uname=binary_part(Bin, ?USTAR_UNAME, ?USTAR_UNAME_LEN), - gname=binary_part(Bin, ?USTAR_GNAME, ?USTAR_GNAME_LEN), - devmajor=binary_part(Bin, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN), - devminor=binary_part(Bin, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN), - prefix=binary_part(Bin, 345, 131), - atime=binary_part(Bin, 476, 12), - ctime=binary_part(Bin, 488, 12), - trailer=binary_part(Bin, ?STAR_TRAILER, ?STAR_TRAILER_LEN) - }. - -to_ustar(#header_v7{}=V7, Bin) - when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - #header_ustar{ - header_v7=V7, - magic=binary_part(Bin, ?USTAR_MAGIC, ?USTAR_MAGIC_LEN), - version=binary_part(Bin, ?USTAR_VERSION, ?USTAR_VERSION_LEN), - uname=binary_part(Bin, ?USTAR_UNAME, ?USTAR_UNAME_LEN), - gname=binary_part(Bin, ?USTAR_GNAME, ?USTAR_GNAME_LEN), - devmajor=binary_part(Bin, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN), - devminor=binary_part(Bin, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN), - prefix=binary_part(Bin, 345, 155) - }. - -to_sparse_array(Bin) when is_binary(Bin) -> - MaxEntries = byte_size(Bin) div 24, - IsExtended = 1 =:= binary:at(Bin, 24*MaxEntries), - Entries = parse_sparse_entries(Bin, MaxEntries-1, []), - #sparse_array{ - entries=Entries, - max_entries=MaxEntries, - is_extended=IsExtended - }. - -parse_sparse_entries(<<>>, _, Acc) -> - Acc; -parse_sparse_entries(_, -1, Acc) -> - Acc; -parse_sparse_entries(Bin, N, Acc) -> - case to_sparse_entry(binary_part(Bin, N*24, 24)) of - nil -> - parse_sparse_entries(Bin, N-1, Acc); - Entry = #sparse_entry{} -> - parse_sparse_entries(Bin, N-1, [Entry|Acc]) - end. - --define(EMPTY_ENTRY, <<0,0,0,0,0,0,0,0,0,0,0,0>>). -to_sparse_entry(Bin) when is_binary(Bin), byte_size(Bin) =:= 24 -> - OffsetBin = binary_part(Bin, 0, 12), - NumBytesBin = binary_part(Bin, 12, 12), - case {OffsetBin, NumBytesBin} of - {?EMPTY_ENTRY, ?EMPTY_ENTRY} -> - nil; - _ -> - #sparse_entry{ - offset=parse_numeric(OffsetBin), - num_bytes=parse_numeric(NumBytesBin)} - end. - --spec get_format(binary()) -> {ok, pos_integer(), header_v7()} - | ?FORMAT_UNKNOWN - | {error, term()}. -get_format(Bin) when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - do_get_format(to_v7(Bin), Bin). - -do_get_format({error, _} = Err, _Bin) -> - Err; -do_get_format(#header_v7{}=V7, Bin) - when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - Checksum = parse_octal(V7#header_v7.checksum), - Chk1 = compute_checksum(Bin), - Chk2 = compute_signed_checksum(Bin), - if Checksum =/= Chk1 andalso Checksum =/= Chk2 -> - ?FORMAT_UNKNOWN; - true -> - %% guess magic - Ustar = to_ustar(V7, Bin), - Star = to_star(V7, Bin), - Magic = Ustar#header_ustar.magic, - Version = Ustar#header_ustar.version, - Trailer = Star#header_star.trailer, - Format = if - Magic =:= ?MAGIC_USTAR, Trailer =:= ?TRAILER_STAR -> - ?FORMAT_STAR; - Magic =:= ?MAGIC_USTAR -> - ?FORMAT_USTAR; - Magic =:= ?MAGIC_GNU, Version =:= ?VERSION_GNU -> - ?FORMAT_GNU; - true -> - ?FORMAT_V7 - end, - {ok, Format, V7} - end. - -unpack_format(Format, #header_v7{}=V7, Bin, Reader) - when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> - Mtime = parse_numeric(V7#header_v7.mtime), - Header0 = #tar_header{ - name=parse_string(V7#header_v7.name), - mode=parse_numeric(V7#header_v7.mode), - uid=parse_numeric(V7#header_v7.uid), - gid=parse_numeric(V7#header_v7.gid), - size=parse_numeric(V7#header_v7.size), - mtime=Mtime, - atime=Mtime, - ctime=Mtime, - typeflag=V7#header_v7.typeflag, - linkname=parse_string(V7#header_v7.linkname) - }, - Typeflag = Header0#tar_header.typeflag, - Header1 = if Format > ?FORMAT_V7 -> - unpack_modern(Format, V7, Bin, Header0); - true -> - Name = Header0#tar_header.name, - Header0#tar_header{name=safe_join_path("", Name)} - end, - HeaderOnly = is_header_only_type(Typeflag), - Header2 = if HeaderOnly -> - Header1#tar_header{size=0}; - true -> - Header1 - end, - if Typeflag =:= ?TYPE_GNU_SPARSE -> - Gnu = to_gnu(V7, Bin), - RealSize = parse_numeric(Gnu#header_gnu.real_size), - {Sparsemap, Reader2} = parse_sparse_map(Gnu, Reader), - Header3 = Header2#tar_header{size=RealSize}, - {Header3, new_sparse_file_reader(Reader2, Sparsemap, RealSize)}; - true -> - FileReader = #reg_file_reader{ - handle=Reader, - num_bytes=Header2#tar_header.size, - size=Header2#tar_header.size, - pos = 0 - }, - {Header2, FileReader} - end. - -unpack_modern(Format, #header_v7{}=V7, Bin, #tar_header{}=Header0) - when is_binary(Bin) -> - Typeflag = Header0#tar_header.typeflag, - Ustar = to_ustar(V7, Bin), - H0 = Header0#tar_header{ - uname=parse_string(Ustar#header_ustar.uname), - gname=parse_string(Ustar#header_ustar.gname)}, - H1 = if Typeflag =:= ?TYPE_CHAR - orelse Typeflag =:= ?TYPE_BLOCK -> - Ma = parse_numeric(Ustar#header_ustar.devmajor), - Mi = parse_numeric(Ustar#header_ustar.devminor), - H0#tar_header{ - devmajor=Ma, - devminor=Mi - }; - true -> - H0 - end, - {Prefix, H2} = case Format of - ?FORMAT_USTAR -> - {parse_string(Ustar#header_ustar.prefix), H1}; - ?FORMAT_STAR -> - Star = to_star(V7, Bin), - Prefix0 = parse_string(Star#header_star.prefix), - Atime0 = Star#header_star.atime, - Atime = parse_numeric(Atime0), - Ctime0 = Star#header_star.ctime, - Ctime = parse_numeric(Ctime0), - {Prefix0, H1#tar_header{ - atime=Atime, - ctime=Ctime - }}; - _ -> - {"", H1} - end, - Name = H2#tar_header.name, - H2#tar_header{name=safe_join_path(Prefix, Name)}. - - -safe_join_path([], Name) -> - filename:join([Name]); -safe_join_path(Prefix, []) -> - filename:join([Prefix]); -safe_join_path(Prefix, Name) -> - filename:join(Prefix, Name). - -new_sparse_file_reader(Reader, Sparsemap, RealSize) -> - true = validate_sparse_entries(Sparsemap, RealSize), - #sparse_file_reader{ - handle = Reader, - num_bytes = RealSize, - pos = 0, - size = RealSize, - sparse_map = Sparsemap}. - -validate_sparse_entries(Entries, RealSize) -> - validate_sparse_entries(Entries, RealSize, 0, 0). -validate_sparse_entries([], _RealSize, _I, _LastOffset) -> - true; -validate_sparse_entries([#sparse_entry{}=Entry|Rest], RealSize, I, LastOffset) -> - Offset = Entry#sparse_entry.offset, - NumBytes = Entry#sparse_entry.num_bytes, - if - Offset > ?MAX_INT64-NumBytes -> - throw({error, {invalid_sparse_map_entry, offset_too_large}}); - Offset+NumBytes > RealSize -> - throw({error, {invalid_sparse_map_entry, offset_too_large}}); - I > 0 andalso LastOffset > Offset -> - throw({error, {invalid_sparse_map_entry, overlapping_offsets}}); - true -> - ok - end, - validate_sparse_entries(Rest, RealSize, I+1, Offset+NumBytes). - - --spec parse_sparse_map(header_gnu(), reader_type()) -> - {[sparse_entry()], reader_type()}. -parse_sparse_map(#header_gnu{sparse=Sparse}, Reader) - when Sparse#sparse_array.is_extended -> - parse_sparse_map(Sparse, Reader, []); -parse_sparse_map(#header_gnu{sparse=Sparse}, Reader) -> - {Sparse#sparse_array.entries, Reader}. -parse_sparse_map(#sparse_array{is_extended=true,entries=Entries}, Reader, Acc) -> - case read_block(Reader) of - eof -> - throw({error, eof}); - {ok, Block, Reader2} -> - Sparse2 = to_sparse_array(Block), - parse_sparse_map(Sparse2, Reader2, Entries++Acc) - end; -parse_sparse_map(#sparse_array{entries=Entries}, Reader, Acc) -> - Sorted = lists:sort(fun (#sparse_entry{offset=A},#sparse_entry{offset=B}) -> - A =< B - end, Entries++Acc), - {Sorted, Reader}. - -%% Defined by taking the sum of the unsigned byte values of the -%% entire header record, treating the checksum bytes to as ASCII spaces -compute_checksum(<>) -> - C0 = checksum(H1) + (byte_size(H2) * $\s), - C1 = checksum(Rest), - C0 + C1. - -compute_signed_checksum(<>) -> - C0 = signed_checksum(H1) + (byte_size(H2) * $\s), - C1 = signed_checksum(Rest), - C0 + C1. - -%% Returns the checksum of a binary. -checksum(Bin) -> checksum(Bin, 0). -checksum(<
>, Sum) -> - checksum(Rest, Sum+A); -checksum(<<>>, Sum) -> Sum. - -signed_checksum(Bin) -> signed_checksum(Bin, 0). -signed_checksum(<>, Sum) -> - signed_checksum(Rest, Sum+A); -signed_checksum(<<>>, Sum) -> Sum. - --spec parse_numeric(binary()) -> non_neg_integer(). -parse_numeric(<<>>) -> - 0; -parse_numeric(<> = Bin) -> - %% check for base-256 format first - %% if the bit is set, then all following bits constitute a two's - %% complement encoded number in big-endian byte order - if - First band 16#80 =/= 0 -> - %% Handling negative numbers relies on the following identity: - %% -a-1 == ^a - %% If the number is negative, we use an inversion mask to invert - %% the data bytes and treat the value as an unsigned number - Inv = if First band 16#40 =/= 0 -> 16#00; true -> 16#FF end, - Bytes = binary:bin_to_list(Bin), - Reducer = fun (C, {I, X}) -> - C1 = C bxor Inv, - C2 = if I =:= 0 -> C1 band 16#7F; true -> C1 end, - if (X bsr 56) > 0 -> - throw({error,integer_overflow}); - true -> - {I+1, (X bsl 8) bor C2} - end - end, - {_, N} = lists:foldl(Reducer, {0,0}, Bytes), - if (N bsr 63) > 0 -> - throw({error, integer_overflow}); - true -> - if Inv =:= 16#FF -> - -1 bxor N; - true -> - N - end - end; - true -> - %% normal case is an octal number - parse_octal(Bin) - end. - -parse_octal(Bin) when is_binary(Bin) -> - %% skip leading/trailing zero bytes and spaces - do_parse_octal(Bin, <<>>). -do_parse_octal(<<>>, <<>>) -> - 0; -do_parse_octal(<<>>, Acc) -> - case io_lib:fread("~8u", binary:bin_to_list(Acc)) of - {error, _} -> throw({error, invalid_tar_checksum}); - {ok, [Octal], []} -> Octal; - {ok, _, _} -> throw({error, invalid_tar_checksum}) - end; -do_parse_octal(<<$\s,Rest/binary>>, Acc) -> - do_parse_octal(Rest, Acc); -do_parse_octal(<<0, Rest/binary>>, Acc) -> - do_parse_octal(Rest, Acc); -do_parse_octal(<>, Acc) -> - do_parse_octal(Rest, <>). - -parse_string(Bin) when is_binary(Bin) -> - do_parse_string(Bin, <<>>). -do_parse_string(<<>>, Acc) -> - case unicode:characters_to_list(Acc) of - Str when is_list(Str) -> - Str; - {incomplete, _Str, _Rest} -> - binary:bin_to_list(Acc); - {error, _Str, _Rest} -> - throw({error, {bad_header, invalid_string}}) - end; -do_parse_string(<<0, _/binary>>, Acc) -> - do_parse_string(<<>>, Acc); -do_parse_string(<>, Acc) -> - do_parse_string(Rest, <>). - -convert_header(Bin, #reader{pos=Pos}=Reader) - when byte_size(Bin) =:= ?BLOCK_SIZE, (Pos rem ?BLOCK_SIZE) =:= 0 -> - case get_format(Bin) of - ?FORMAT_UNKNOWN -> - throw({error, bad_header}); - {ok, Format, V7} -> - unpack_format(Format, V7, Bin, Reader); - {error, Reason} -> - throw({error, {bad_header, Reason}}) - end; -convert_header(Bin, #reader{pos=Pos}) when byte_size(Bin) =:= ?BLOCK_SIZE -> - throw({error, misaligned_read, Pos}); -convert_header(Bin, _Reader) when byte_size(Bin) =:= 0 -> - eof; -convert_header(_Bin, _Reader) -> - throw({error, eof}). - -%% Creates a partially-populated header record based -%% on the provided file_info record. If the file is -%% a symlink, then `link` is used as the link target. -%% If the file is a directory, a slash is appended to the name. -fileinfo_to_header(Name, #file_info{}=Fi, Link) when is_list(Name) -> - BaseHeader = #tar_header{name=Name, - mtime=0, - atime=0, - ctime=0, - mode=Fi#file_info.mode, - typeflag=?TYPE_REGULAR}, - do_fileinfo_to_header(BaseHeader, Fi, Link). - -do_fileinfo_to_header(Header, #file_info{size=Size,type=regular}, _Link) -> - Header#tar_header{size=Size,typeflag=?TYPE_REGULAR}; -do_fileinfo_to_header(#tar_header{name=Name}=Header, - #file_info{type=directory}, _Link) -> - Header#tar_header{name=Name++"/",typeflag=?TYPE_DIR}; -do_fileinfo_to_header(Header, #file_info{type=symlink}, Link) -> - Header#tar_header{typeflag=?TYPE_SYMLINK,linkname=Link}; -do_fileinfo_to_header(Header, #file_info{type=device,mode=Mode}=Fi, _Link) - when (Mode band ?S_IFMT) =:= ?S_IFCHR -> - Header#tar_header{typeflag=?TYPE_CHAR, - devmajor=Fi#file_info.major_device, - devminor=Fi#file_info.minor_device}; -do_fileinfo_to_header(Header, #file_info{type=device,mode=Mode}=Fi, _Link) - when (Mode band ?S_IFMT) =:= ?S_IFBLK -> - Header#tar_header{typeflag=?TYPE_BLOCK, - devmajor=Fi#file_info.major_device, - devminor=Fi#file_info.minor_device}; -do_fileinfo_to_header(Header, #file_info{type=other,mode=Mode}, _Link) - when (Mode band ?S_IFMT) =:= ?S_FIFO -> - Header#tar_header{typeflag=?TYPE_FIFO}; -do_fileinfo_to_header(Header, Fi, _Link) -> - {error, {invalid_file_type, Header#tar_header.name, Fi}}. - -is_ascii(Str) when is_list(Str) -> - not lists:any(fun (Char) -> Char >= 16#80 end, Str); -is_ascii(Bin) when is_binary(Bin) -> - is_ascii1(Bin). - -is_ascii1(<<>>) -> - true; -is_ascii1(<>) when C >= 16#80 -> - false; -is_ascii1(<<_, Rest/binary>>) -> - is_ascii1(Rest). - -to_ascii(Str) when is_list(Str) -> - case is_ascii(Str) of - true -> - unicode:characters_to_binary(Str); - false -> - Chars = lists:filter(fun (Char) -> Char < 16#80 end, Str), - unicode:characters_to_binary(Chars) - end; -to_ascii(Bin) when is_binary(Bin) -> - to_ascii(Bin, <<>>). -to_ascii(<<>>, Acc) -> - Acc; -to_ascii(<>, Acc) when C < 16#80 -> - to_ascii(Rest, <>); -to_ascii(<<_, Rest/binary>>, Acc) -> - to_ascii(Rest, Acc). - -is_header_only_type(?TYPE_SYMLINK) -> true; -is_header_only_type(?TYPE_LINK) -> true; -is_header_only_type(?TYPE_DIR) -> true; -is_header_only_type(_) -> false. - -foldl_read(#reader{access=read}=Reader, Fun, Accu, #read_opts{}=Opts) - when is_function(Fun,4) -> - case foldl_read0(Reader, Fun, Accu, Opts) of - {ok, Result, _Reader2} -> - Result; - {error, _} = Err -> - Err - end; -foldl_read(#reader{access=Access}, _Fun, _Accu, _Opts) -> - {error, {read_mode_expected, Access}}; -foldl_read(TarName, Fun, Accu, #read_opts{}=Opts) - when is_function(Fun,4) -> - try open(TarName, [read|Opts#read_opts.open_mode]) of - {ok, #reader{access=read}=Reader} -> - try - foldl_read(Reader, Fun, Accu, Opts) - after - _ = close(Reader) - end; - {error, _} = Err -> - Err - catch - throw:Err -> - Err - end. - -foldl_read0(Reader, Fun, Accu, Opts) -> - try foldl_read1(Fun, Accu, Reader, Opts, #{}) of - {ok,_,_} = Ok -> - Ok - catch - throw:{error, {Reason, Format, Args}} -> - read_verbose(Opts, Format, Args), - {error, Reason}; - throw:Err -> - Err - end. - -foldl_read1(Fun, Accu0, Reader0, Opts, ExtraHeaders) -> - {ok, Reader1} = skip_unread(Reader0), - case get_header(Reader1) of - eof -> - Fun(eof, Reader1, Opts, Accu0); - {Header, Reader2} -> - case Header#tar_header.typeflag of - ?TYPE_X_HEADER -> - {ExtraHeaders2, Reader3} = parse_pax(Reader2), - ExtraHeaders3 = maps:merge(ExtraHeaders, ExtraHeaders2), - foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders3); - ?TYPE_GNU_LONGNAME -> - {RealName, Reader3} = get_real_name(Reader2), - ExtraHeaders2 = maps:put(?PAX_PATH, - parse_string(RealName), ExtraHeaders), - foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders2); - ?TYPE_GNU_LONGLINK -> - {RealName, Reader3} = get_real_name(Reader2), - ExtraHeaders2 = maps:put(?PAX_LINKPATH, - parse_string(RealName), ExtraHeaders), - foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders2); - _ -> - Header1 = merge_pax(Header, ExtraHeaders), - {ok, NewAccu, Reader3} = Fun(Header1, Reader2, Opts, Accu0), - foldl_read1(Fun, NewAccu, Reader3, Opts, #{}) - end - end. - -%% Applies all known PAX attributes to the current tar header --spec merge_pax(tar_header(), #{binary() => binary()}) -> tar_header(). -merge_pax(Header, ExtraHeaders) when is_map(ExtraHeaders) -> - do_merge_pax(Header, maps:to_list(ExtraHeaders)). - -do_merge_pax(Header, []) -> - Header; -do_merge_pax(Header, [{?PAX_PATH, Path}|Rest]) -> - do_merge_pax(Header#tar_header{name=unicode:characters_to_list(Path)}, Rest); -do_merge_pax(Header, [{?PAX_LINKPATH, LinkPath}|Rest]) -> - do_merge_pax(Header#tar_header{linkname=unicode:characters_to_list(LinkPath)}, Rest); -do_merge_pax(Header, [{?PAX_GNAME, Gname}|Rest]) -> - do_merge_pax(Header#tar_header{gname=unicode:characters_to_list(Gname)}, Rest); -do_merge_pax(Header, [{?PAX_UNAME, Uname}|Rest]) -> - do_merge_pax(Header#tar_header{uname=unicode:characters_to_list(Uname)}, Rest); -do_merge_pax(Header, [{?PAX_UID, Uid}|Rest]) -> - Uid2 = binary_to_integer(Uid), - do_merge_pax(Header#tar_header{uid=Uid2}, Rest); -do_merge_pax(Header, [{?PAX_GID, Gid}|Rest]) -> - Gid2 = binary_to_integer(Gid), - do_merge_pax(Header#tar_header{gid=Gid2}, Rest); -do_merge_pax(Header, [{?PAX_ATIME, Atime}|Rest]) -> - Atime2 = parse_pax_time(Atime), - do_merge_pax(Header#tar_header{atime=Atime2}, Rest); -do_merge_pax(Header, [{?PAX_MTIME, Mtime}|Rest]) -> - Mtime2 = parse_pax_time(Mtime), - do_merge_pax(Header#tar_header{mtime=Mtime2}, Rest); -do_merge_pax(Header, [{?PAX_CTIME, Ctime}|Rest]) -> - Ctime2 = parse_pax_time(Ctime), - do_merge_pax(Header#tar_header{ctime=Ctime2}, Rest); -do_merge_pax(Header, [{?PAX_SIZE, Size}|Rest]) -> - Size2 = binary_to_integer(Size), - do_merge_pax(Header#tar_header{size=Size2}, Rest); -do_merge_pax(Header, [{<>, _Value}|Rest]) -> - do_merge_pax(Header, Rest); -do_merge_pax(Header, [_Ignore|Rest]) -> - do_merge_pax(Header, Rest). - -%% Returns the time since UNIX epoch as a datetime --spec parse_pax_time(binary()) -> tar_time(). -parse_pax_time(Bin) when is_binary(Bin) -> - TotalNano = case binary:split(Bin, [<<$.>>]) of - [SecondsStr, NanoStr0] -> - Seconds = binary_to_integer(SecondsStr), - if byte_size(NanoStr0) < ?MAX_NANO_INT_SIZE -> - %% right pad - PaddingN = ?MAX_NANO_INT_SIZE-byte_size(NanoStr0), - Padding = binary:copy(<<$0>>, PaddingN), - NanoStr1 = <>, - Nano = binary_to_integer(NanoStr1), - (Seconds*?BILLION)+Nano; - byte_size(NanoStr0) > ?MAX_NANO_INT_SIZE -> - %% right truncate - NanoStr1 = binary_part(NanoStr0, 0, ?MAX_NANO_INT_SIZE), - Nano = binary_to_integer(NanoStr1), - (Seconds*?BILLION)+Nano; - true -> - (Seconds*?BILLION)+binary_to_integer(NanoStr0) - end; - [SecondsStr] -> - binary_to_integer(SecondsStr)*?BILLION - end, - %% truncate to microseconds - Micro = TotalNano div 1000, - Mega = Micro div 1000000000000, - Secs = Micro div 1000000 - (Mega*1000000), - Secs. - -%% Given a regular file reader, reads the whole file and -%% parses all extended attributes it contains. -parse_pax(#reg_file_reader{handle=Handle,num_bytes=0}) -> - {#{}, Handle}; -parse_pax(#reg_file_reader{handle=Handle0,num_bytes=NumBytes}) -> - case do_read(Handle0, NumBytes) of - {ok, Bytes, Handle1} -> - do_parse_pax(Handle1, Bytes, #{}); - {error, _} = Err -> - throw(Err) - end. - -do_parse_pax(Reader, <<>>, Headers) -> - {Headers, Reader}; -do_parse_pax(Reader, Bin, Headers) -> - {Key, Value, Residual} = parse_pax_record(Bin), - NewHeaders = maps:put(Key, Value, Headers), - do_parse_pax(Reader, Residual, NewHeaders). - -%% Parse an extended attribute -parse_pax_record(Bin) when is_binary(Bin) -> - case binary:split(Bin, [<<$\n>>]) of - [Record, Residual] -> - case [X || X <- binary:split(Record, [<<$\s>>], [global]), X =/= <<>>] of - [_Len, Record1] -> - case [X || X <- binary:split(Record1, [<<$=>>], [global]), X =/= <<>>] of - [AttrName, AttrValue] -> - {AttrName, AttrValue, Residual}; - _Other -> - throw({error, malformed_pax_record}) - end; - _Other -> - throw({error, malformed_pax_record}) - end; - _Other -> - throw({error, malformed_pax_record}) - end. - -get_real_name(#reg_file_reader{handle=Handle,num_bytes=0}) -> - {"", Handle}; -get_real_name(#reg_file_reader{handle=Handle0,num_bytes=NumBytes}) -> - case do_read(Handle0, NumBytes) of - {ok, RealName, Handle1} -> - {RealName, Handle1}; - {error, _} = Err -> - throw(Err) - end; -get_real_name(#sparse_file_reader{num_bytes=NumBytes}=Reader0) -> - case do_read(Reader0, NumBytes) of - {ok, RealName, Reader1} -> - {RealName, Reader1}; - {error, _} = Err -> - throw(Err) - end. - -%% Skip the remaining bytes for the current file entry -skip_file(#reg_file_reader{handle=Handle0,pos=Pos,size=Size}=Reader) -> - Padding = skip_padding(Size), - AbsPos = Handle0#reader.pos + (Size-Pos) + Padding, - case do_position(Handle0, AbsPos) of - {ok, _, Handle1} -> - Reader#reg_file_reader{handle=Handle1,num_bytes=0,pos=Size}; - Err -> - throw(Err) - end; -skip_file(#sparse_file_reader{pos=Pos,size=Size}=Reader) -> - case do_read(Reader, Size-Pos) of - {ok, _, Reader2} -> - Reader2; - Err -> - throw(Err) - end. - -skip_padding(0) -> - 0; -skip_padding(Size) when (Size rem ?BLOCK_SIZE) =:= 0 -> - 0; -skip_padding(Size) when Size =< ?BLOCK_SIZE -> - ?BLOCK_SIZE - Size; -skip_padding(Size) -> - ?BLOCK_SIZE - (Size rem ?BLOCK_SIZE). - -skip_unread(#reader{pos=Pos}=Reader0) when (Pos rem ?BLOCK_SIZE) > 0 -> - Padding = skip_padding(Pos + ?BLOCK_SIZE), - AbsPos = Pos + Padding, - case do_position(Reader0, AbsPos) of - {ok, _, Reader1} -> - {ok, Reader1}; - Err -> - throw(Err) - end; -skip_unread(#reader{}=Reader) -> - {ok, Reader}; -skip_unread(#reg_file_reader{handle=Handle,num_bytes=0}) -> - skip_unread(Handle); -skip_unread(#reg_file_reader{}=Reader) -> - #reg_file_reader{handle=Handle} = skip_file(Reader), - {ok, Handle}; -skip_unread(#sparse_file_reader{handle=Handle,num_bytes=0}) -> - skip_unread(Handle); -skip_unread(#sparse_file_reader{}=Reader) -> - #sparse_file_reader{handle=Handle} = skip_file(Reader), - {ok, Handle}. - -write_extracted_element(#tar_header{name=Name,typeflag=Type}, - Bin, - #read_opts{output=memory}=Opts) -> - case typeflag(Type) of - regular -> - read_verbose(Opts, "x ~ts~n", [Name]), - {ok, {Name, Bin}}; - _ -> - ok - end; -write_extracted_element(#tar_header{name=Name0}=Header, Bin, Opts) -> - Name1 = make_safe_path(Name0, Opts), - Created = - case typeflag(Header#tar_header.typeflag) of - regular -> - create_regular(Name1, Name0, Bin, Opts); - directory -> - read_verbose(Opts, "x ~ts~n", [Name0]), - create_extracted_dir(Name1, Opts); - symlink -> - read_verbose(Opts, "x ~ts~n", [Name0]), - create_symlink(Name1, Header#tar_header.linkname, Opts); - Device when Device =:= char orelse Device =:= block -> - %% char/block devices will be created as empty files - %% and then have their major/minor device set later - create_regular(Name1, Name0, <<>>, Opts); - fifo -> - %% fifo devices will be created as empty files - create_regular(Name1, Name0, <<>>, Opts); - Other -> % Ignore. - read_verbose(Opts, "x ~ts - unsupported type ~p~n", - [Name0, Other]), - not_written - end, - case Created of - ok -> set_extracted_file_info(Name1, Header); - not_written -> ok - end. - -make_safe_path([$/|Path], Opts) -> - make_safe_path(Path, Opts); -make_safe_path(Path, #read_opts{cwd=Cwd}) -> - case safe_relative_path_links(Path, Cwd) of - unsafe -> - throw({error,{Path,unsafe_path}}); - SafePath -> - filename:absname(SafePath, Cwd) - end. - -safe_relative_path_links(Path, Cwd) -> - case filename:pathtype(Path) of - relative -> safe_relative_path_links(filename:split(Path), Cwd, [], ""); - _ -> unsafe - end. - -safe_relative_path_links([], _Cwd, _PrevLinks, Acc) -> - Acc; - -safe_relative_path_links([Segment | Segments], Cwd, PrevLinks, Acc) -> - AccSegment = join(Acc, Segment), - - case hex_filename:safe_relative_path(AccSegment) of - unsafe -> - unsafe; - - SafeAccSegment -> - case file:read_link(join(Cwd, SafeAccSegment)) of - {ok, LinkPath} -> - case lists:member(LinkPath, PrevLinks) of - true -> - unsafe; - false -> - case safe_relative_path_links(filename:split(LinkPath), Cwd, [LinkPath | PrevLinks], Acc) of - unsafe -> unsafe; - NewAcc -> safe_relative_path_links(Segments, Cwd, [], NewAcc) - end - end; - - {error, _} -> - safe_relative_path_links(Segments, Cwd, PrevLinks, SafeAccSegment) - end - end. - -join([], Path) -> Path; -join(Left, Right) -> filename:join(Left, Right). - -create_regular(Name, NameInArchive, Bin, Opts) -> - case write_extracted_file(Name, Bin, Opts) of - not_written -> - read_verbose(Opts, "x ~ts - exists, not created~n", [NameInArchive]), - not_written; - Ok -> - read_verbose(Opts, "x ~ts~n", [NameInArchive]), - Ok - end. - -create_extracted_dir(Name, _Opts) -> - case file:make_dir(Name) of - ok -> ok; - {error,enotsup} -> not_written; - {error,eexist} -> not_written; - {error,enoent} -> make_dirs(Name, dir); - {error,Reason} -> throw({error, Reason}) - end. - -create_symlink(Name, Linkname, Opts) -> - case file:make_symlink(Linkname, Name) of - ok -> ok; - {error,enoent} -> - ok = make_dirs(Name, file), - create_symlink(Name, Linkname, Opts); - {error,eexist} -> not_written; - {error,enotsup} -> - read_verbose(Opts, "x ~ts - symbolic links not supported~n", [Name]), - not_written; - {error,Reason} -> throw({error, Reason}) - end. - -write_extracted_file(Name, Bin, Opts) -> - Write = - case Opts#read_opts.keep_old_files of - true -> - case file:read_file_info(Name) of - {ok, _} -> false; - _ -> true - end; - false -> true - end, - case Write of - true -> write_file(Name, Bin); - false -> not_written - end. - -write_file(Name, Bin) -> - case file:write_file(Name, Bin) of - ok -> ok; - {error,enoent} -> - case make_dirs(Name, file) of - ok -> - write_file(Name, Bin); - {error,Reason} -> - throw({error, Reason}) - end; - {error,Reason} -> - throw({error, Reason}) - end. - -set_extracted_file_info(_, #tar_header{typeflag = ?TYPE_SYMLINK}) -> ok; -set_extracted_file_info(_, #tar_header{typeflag = ?TYPE_LINK}) -> ok; -set_extracted_file_info(Name, #tar_header{typeflag = ?TYPE_CHAR}=Header) -> - set_device_info(Name, Header); -set_extracted_file_info(Name, #tar_header{typeflag = ?TYPE_BLOCK}=Header) -> - set_device_info(Name, Header); -set_extracted_file_info(Name, #tar_header{mtime=Mtime,mode=Mode}) -> - Info = #file_info{mode=Mode, mtime=Mtime}, - file:write_file_info(Name, Info, [{time, posix}]). - -set_device_info(Name, #tar_header{}=Header) -> - Mtime = Header#tar_header.mtime, - Mode = Header#tar_header.mode, - Devmajor = Header#tar_header.devmajor, - Devminor = Header#tar_header.devminor, - Info = #file_info{ - mode=Mode, - mtime=Mtime, - major_device=Devmajor, - minor_device=Devminor - }, - file:write_file_info(Name, Info). - -%% Makes all directories leading up to the file. - -make_dirs(Name, file) -> - filelib:ensure_dir(Name); -make_dirs(Name, dir) -> - filelib:ensure_dir(filename:join(Name,"*")). - -%% Prints the message on if the verbose option is given (for reading). -read_verbose(#read_opts{verbose=true}, Format, Args) -> - io:format(Format, Args); -read_verbose(_, _, _) -> - ok. - -%% Prints the message on if the verbose option is given. -add_verbose(#add_opts{verbose=true}, Format, Args) -> - io:format(Format, Args); -add_verbose(_, _, _) -> - ok. - -%%%%%%%%%%%%%%%%%% -%% I/O primitives -%%%%%%%%%%%%%%%%%% - -do_write(#reader{handle=Handle,func=Fun}=Reader0, Data) - when is_function(Fun,2) -> - case Fun(write,{Handle,Data}) of - ok -> - {ok, Pos, Reader1} = do_position(Reader0, {cur,0}), - {ok, Reader1#reader{pos=Pos}}; - {error, _} = Err -> - Err - end. - -do_copy(#reader{func=Fun}=Reader, Source, #add_opts{chunk_size=0}=Opts) - when is_function(Fun, 2) -> - do_copy(Reader, Source, Opts#add_opts{chunk_size=65536}); -do_copy(#reader{func=Fun}=Reader, Source, #add_opts{chunk_size=ChunkSize}) - when is_function(Fun, 2) -> - case file:open(Source, [read, binary]) of - {ok, SourceFd} -> - case copy_chunked(Reader, SourceFd, ChunkSize, 0) of - {ok, _Copied, _Reader2} = Ok-> - _ = file:close(SourceFd), - Ok; - Err -> - _ = file:close(SourceFd), - throw(Err) - end; - Err -> - throw(Err) - end. - -copy_chunked(#reader{}=Reader, Source, ChunkSize, Copied) -> - case file:read(Source, ChunkSize) of - {ok, Bin} -> - {ok, Reader2} = do_write(Reader, Bin), - copy_chunked(Reader2, Source, ChunkSize, Copied+byte_size(Bin)); - eof -> - {ok, Copied, Reader}; - Other -> - Other - end. - - -do_position(#reader{handle=Handle,func=Fun}=Reader, Pos) - when is_function(Fun,2)-> - case Fun(position, {Handle,Pos}) of - {ok, NewPos} -> - %% since Pos may not always be an absolute seek, - %% make sure we update the reader with the new absolute position - {ok, AbsPos} = Fun(position, {Handle, {cur, 0}}), - {ok, NewPos, Reader#reader{pos=AbsPos}}; - Other -> - Other - end. - -do_read(#reg_file_reader{handle=Handle,pos=Pos,size=Size}=Reader, Len) -> - NumBytes = Size - Pos, - ActualLen = if NumBytes - Len < 0 -> NumBytes; true -> Len end, - case do_read(Handle, ActualLen) of - {ok, Bin, Handle2} -> - NewPos = Pos + ActualLen, - NumBytes2 = Size - NewPos, - Reader1 = Reader#reg_file_reader{ - handle=Handle2, - pos=NewPos, - num_bytes=NumBytes2}, - {ok, Bin, Reader1}; - Other -> - Other - end; -do_read(#sparse_file_reader{}=Reader, Len) -> - do_sparse_read(Reader, Len); -do_read(#reader{pos=Pos,handle=Handle,func=Fun}=Reader, Len) - when is_function(Fun,2)-> - %% Always convert to binary internally - case Fun(read2,{Handle,Len}) of - {ok, List} when is_list(List) -> - Bin = list_to_binary(List), - NewPos = Pos+byte_size(Bin), - {ok, Bin, Reader#reader{pos=NewPos}}; - {ok, Bin} when is_binary(Bin) -> - NewPos = Pos+byte_size(Bin), - {ok, Bin, Reader#reader{pos=NewPos}}; - Other -> - Other - end. - - -do_sparse_read(Reader, Len) -> - do_sparse_read(Reader, Len, <<>>). - -do_sparse_read(#sparse_file_reader{sparse_map=[#sparse_entry{num_bytes=0}|Entries] - }=Reader0, Len, Acc) -> - %% skip all empty fragments - Reader1 = Reader0#sparse_file_reader{sparse_map=Entries}, - do_sparse_read(Reader1, Len, Acc); -do_sparse_read(#sparse_file_reader{sparse_map=[], - pos=Pos,size=Size}=Reader0, Len, Acc) - when Pos < Size -> - %% if there are no more fragments, it is possible that there is one last sparse hole - %% this behaviour matches the BSD tar utility - %% however, GNU tar stops returning data even if we haven't reached the end - {ok, Bin, Reader1} = read_sparse_hole(Reader0, Size, Len), - do_sparse_read(Reader1, Len-byte_size(Bin), <>); -do_sparse_read(#sparse_file_reader{sparse_map=[]}=Reader, _Len, Acc) -> - {ok, Acc, Reader}; -do_sparse_read(#sparse_file_reader{}=Reader, 0, Acc) -> - {ok, Acc, Reader}; -do_sparse_read(#sparse_file_reader{sparse_map=[#sparse_entry{offset=Offset}|_], - pos=Pos}=Reader0, Len, Acc) - when Pos < Offset -> - {ok, Bin, Reader1} = read_sparse_hole(Reader0, Offset, Offset-Pos), - do_sparse_read(Reader1, Len-byte_size(Bin), <>); -do_sparse_read(#sparse_file_reader{sparse_map=[Entry|Entries], - pos=Pos}=Reader0, Len, Acc) -> - %% we're in a data fragment, so read from it - %% end offset of fragment - EndPos = Entry#sparse_entry.offset + Entry#sparse_entry.num_bytes, - %% bytes left in fragment - NumBytes = EndPos - Pos, - ActualLen = if Len > NumBytes -> NumBytes; true -> Len end, - case do_read(Reader0#sparse_file_reader.handle, ActualLen) of - {ok, Bin, Handle} -> - BytesRead = byte_size(Bin), - ActualEndPos = Pos+BytesRead, - Reader1 = if ActualEndPos =:= EndPos -> - Reader0#sparse_file_reader{sparse_map=Entries}; - true -> - Reader0 - end, - Size = Reader1#sparse_file_reader.size, - NumBytes2 = Size - ActualEndPos, - Reader2 = Reader1#sparse_file_reader{ - handle=Handle, - pos=ActualEndPos, - num_bytes=NumBytes2}, - do_sparse_read(Reader2, Len-byte_size(Bin), <>); - Other -> - Other - end. - -%% Reads a sparse hole ending at Offset -read_sparse_hole(#sparse_file_reader{pos=Pos}=Reader, Offset, Len) -> - N = Offset - Pos, - N2 = if N > Len -> - Len; - true -> - N - end, - Bin = <<0:N2/unit:8>>, - NumBytes = Reader#sparse_file_reader.size - (Pos+N2), - {ok, Bin, Reader#sparse_file_reader{ - num_bytes=NumBytes, - pos=Pos+N2}}. - --spec do_close(reader()) -> ok | {error, term()}. -do_close(#reader{handle=Handle,func=Fun}) when is_function(Fun,2) -> - Fun(close,Handle). - -%%%%%%%%%%%%%%%%%% -%% Option parsing -%%%%%%%%%%%%%%%%%% - -extract_opts(List) -> - extract_opts(List, default_options()). - -table_opts(List) -> - read_opts(List, default_options()). - -default_options() -> - {ok, Cwd} = file:get_cwd(), - #read_opts{cwd=Cwd}. - -extract_opts([keep_old_files|Rest], Opts) -> - extract_opts(Rest, Opts#read_opts{keep_old_files=true}); -extract_opts([{cwd, Cwd}|Rest], Opts) -> - extract_opts(Rest, Opts#read_opts{cwd=Cwd}); -extract_opts([{files, Files}|Rest], Opts) -> - Set = ordsets:from_list(Files), - extract_opts(Rest, Opts#read_opts{files=Set}); -extract_opts([memory|Rest], Opts) -> - extract_opts(Rest, Opts#read_opts{output=memory}); -extract_opts([compressed|Rest], Opts=#read_opts{open_mode=OpenMode}) -> - extract_opts(Rest, Opts#read_opts{open_mode=[compressed|OpenMode]}); -extract_opts([cooked|Rest], Opts=#read_opts{open_mode=OpenMode}) -> - extract_opts(Rest, Opts#read_opts{open_mode=[cooked|OpenMode]}); -extract_opts([verbose|Rest], Opts) -> - extract_opts(Rest, Opts#read_opts{verbose=true}); -extract_opts([Other|Rest], Opts) -> - extract_opts(Rest, read_opts([Other], Opts)); -extract_opts([], Opts) -> - Opts. - -read_opts([compressed|Rest], Opts=#read_opts{open_mode=OpenMode}) -> - read_opts(Rest, Opts#read_opts{open_mode=[compressed|OpenMode]}); -read_opts([cooked|Rest], Opts=#read_opts{open_mode=OpenMode}) -> - read_opts(Rest, Opts#read_opts{open_mode=[cooked|OpenMode]}); -read_opts([verbose|Rest], Opts) -> - read_opts(Rest, Opts#read_opts{verbose=true}); -read_opts([_|Rest], Opts) -> - read_opts(Rest, Opts); -read_opts([], Opts) -> - Opts. diff --git a/_build/default/plugins/hex_core/src/hex_erl_tar.hrl b/_build/default/plugins/hex_core/src/hex_erl_tar.hrl deleted file mode 100644 index ce7bafa1d6..0000000000 --- a/_build/default/plugins/hex_core/src/hex_erl_tar.hrl +++ /dev/null @@ -1,409 +0,0 @@ -% Copied from https://hub.fastgit.org/erlang/otp/blob/OTP-20.0.1/lib/stdlib/src/erl_tar.hrl - -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2017. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%% -%% %CopyrightEnd% - -%% Options used when adding files to a tar archive. --record(add_opts, { - read_info, %% Fun to use for read file/link info. - chunk_size = 0 :: integer(), %% For file reading when sending to sftp. 0=do not chunk - verbose = false :: boolean(), %% Verbose on/off. - atime = undefined :: undefined | integer(), - mtime = undefined :: undefined | integer(), - ctime = undefined :: undefined | integer(), - uid = 0 :: integer(), - gid = 0 :: integer()}). --type add_opts() :: #add_opts{}. - -%% Options used when reading a tar archive. --record(read_opts, { - cwd :: string(), %% Current working directory. - keep_old_files = false :: boolean(), %% Owerwrite or not. - files = all, %% Set of files to extract (or all) - output = file :: 'file' | 'memory', - open_mode = [], %% Open mode options. - verbose = false :: boolean()}). %% Verbose on/off. --type read_opts() :: #read_opts{}. - --type add_opt() :: dereference - | verbose - | {chunks, pos_integer()} - | {atime, integer()} - | {mtime, integer()} - | {ctime, integer()} - | {uid, integer()} - | {gid, integer()}. - - --type extract_opt() :: {cwd, string()} | - {files, [string()]} | - compressed | - cooked | - memory | - keep_old_files | - verbose. - --type create_opt() :: compressed | - cooked | - dereference | - verbose. - --type filelist() :: [file:filename() | - {string(), binary()} | - {string(), file:filename()}]. - --type tar_time() :: non_neg_integer(). - -%% The tar header, once fully parsed. --record(tar_header, { - name = "" :: string(), %% name of header file entry - mode = 8#100644 :: non_neg_integer(), %% permission and mode bits - uid = 0 :: non_neg_integer(), %% user id of owner - gid = 0 :: non_neg_integer(), %% group id of owner - size = 0 :: non_neg_integer(), %% length in bytes - mtime :: tar_time(), %% modified time - typeflag :: char(), %% type of header entry - linkname = "" :: string(), %% target name of link - uname = "" :: string(), %% user name of owner - gname = "" :: string(), %% group name of owner - devmajor = 0 :: non_neg_integer(), %% major number of character or block device - devminor = 0 :: non_neg_integer(), %% minor number of character or block device - atime :: tar_time(), %% access time - ctime :: tar_time() %% status change time - }). --type tar_header() :: #tar_header{}. - -%% Metadata for a sparse file fragment --record(sparse_entry, { - offset = 0 :: non_neg_integer(), - num_bytes = 0 :: non_neg_integer()}). --type sparse_entry() :: #sparse_entry{}. -%% Contains metadata about fragments of a sparse file --record(sparse_array, { - entries = [] :: [sparse_entry()], - is_extended = false :: boolean(), - max_entries = 0 :: non_neg_integer()}). --type sparse_array() :: #sparse_array{}. -%% A subset of tar header fields common to all tar implementations --record(header_v7, { - name :: binary(), - mode :: binary(), %% octal - uid :: binary(), %% integer - gid :: binary(), %% integer - size :: binary(), %% integer - mtime :: binary(), %% integer - checksum :: binary(), %% integer - typeflag :: byte(), %% char - linkname :: binary()}). --type header_v7() :: #header_v7{}. -%% The set of fields specific to GNU tar formatted archives --record(header_gnu, { - header_v7 :: header_v7(), - magic :: binary(), - version :: binary(), - uname :: binary(), - gname :: binary(), - devmajor :: binary(), %% integer - devminor :: binary(), %% integer - atime :: binary(), %% integer - ctime :: binary(), %% integer - sparse :: sparse_array(), - real_size :: binary()}). %% integer --type header_gnu() :: #header_gnu{}. -%% The set of fields specific to STAR-formatted archives --record(header_star, { - header_v7 :: header_v7(), - magic :: binary(), - version :: binary(), - uname :: binary(), - gname :: binary(), - devmajor :: binary(), %% integer - devminor :: binary(), %% integer - prefix :: binary(), - atime :: binary(), %% integer - ctime :: binary(), %% integer - trailer :: binary()}). --type header_star() :: #header_star{}. -%% The set of fields specific to USTAR-formatted archives --record(header_ustar, { - header_v7 :: header_v7(), - magic :: binary(), - version :: binary(), - uname :: binary(), - gname :: binary(), - devmajor :: binary(), %% integer - devminor :: binary(), %% integer - prefix :: binary()}). --type header_ustar() :: #header_ustar{}. - --type header_fields() :: header_v7() | - header_gnu() | - header_star() | - header_ustar(). - -%% The overall tar reader, it holds the low-level file handle, -%% its access, position, and the I/O primitives wrapper. --record(reader, { - handle :: file:io_device() | term(), - access :: read | write | ram, - pos = 0 :: non_neg_integer(), - func :: file_op() - }). --type reader() :: #reader{}. -%% A reader for a regular file within the tar archive, -%% It tracks its current state relative to that file. --record(reg_file_reader, { - handle :: reader(), - num_bytes = 0, - pos = 0, - size = 0 - }). --type reg_file_reader() :: #reg_file_reader{}. -%% A reader for a sparse file within the tar archive, -%% It tracks its current state relative to that file. --record(sparse_file_reader, { - handle :: reader(), - num_bytes = 0, %% bytes remaining - pos = 0, %% pos - size = 0, %% total size of file - sparse_map = #sparse_array{} - }). --type sparse_file_reader() :: #sparse_file_reader{}. - -%% Types for the readers --type reader_type() :: reader() | reg_file_reader() | sparse_file_reader(). --type handle() :: file:io_device() | term(). - -%% Type for the I/O primitive wrapper function --type file_op() :: fun((write | close | read2 | position, - {handle(), iodata()} | handle() | {handle(), non_neg_integer()} - | {handle(), non_neg_integer()}) -> - ok | eof | {ok, string() | binary()} | {ok, non_neg_integer()} - | {error, term()}). - -%% These constants (except S_IFMT) are -%% used to determine what type of device -%% a file is. Namely, `S_IFMT band file_info.mode` -%% will equal one of these contants, and tells us -%% which type it is. The stdlib file_info record -%% does not differentiate between device types, and -%% will not allow us to differentiate between sockets -%% and named pipes. These constants are pulled from libc. --define(S_IFMT, 61440). --define(S_IFSOCK, 49152). %% socket --define(S_FIFO, 4096). %% fifo/named pipe --define(S_IFBLK, 24576). %% block device --define(S_IFCHR, 8192). %% character device - -%% Typeflag constants for the tar header --define(TYPE_REGULAR, $0). %% regular file --define(TYPE_REGULAR_A, 0). %% regular file --define(TYPE_LINK, $1). %% hard link --define(TYPE_SYMLINK, $2). %% symbolic link --define(TYPE_CHAR, $3). %% character device node --define(TYPE_BLOCK, $4). %% block device node --define(TYPE_DIR, $5). %% directory --define(TYPE_FIFO, $6). %% fifo node --define(TYPE_CONT, $7). %% reserved --define(TYPE_X_HEADER, $x). %% extended header --define(TYPE_X_GLOBAL_HEADER, $g). %% global extended header --define(TYPE_GNU_LONGNAME, $L). %% next file has a long name --define(TYPE_GNU_LONGLINK, $K). %% next file symlinks to a file with a long name --define(TYPE_GNU_SPARSE, $S). %% sparse file - -%% Mode constants from tar spec --define(MODE_ISUID, 4000). %% set uid --define(MODE_ISGID, 2000). %% set gid --define(MODE_ISVTX, 1000). %% save text (sticky bit) --define(MODE_ISDIR, 40000). %% directory --define(MODE_ISFIFO, 10000). %% fifo --define(MODE_ISREG, 100000). %% regular file --define(MODE_ISLNK, 120000). %% symbolic link --define(MODE_ISBLK, 60000). %% block special file --define(MODE_ISCHR, 20000). %% character special file --define(MODE_ISSOCK, 140000). %% socket - -%% Keywords for PAX extended header --define(PAX_ATIME, <<"atime">>). --define(PAX_CHARSET, <<"charset">>). --define(PAX_COMMENT, <<"comment">>). --define(PAX_CTIME, <<"ctime">>). %% ctime is not a valid pax header --define(PAX_GID, <<"gid">>). --define(PAX_GNAME, <<"gname">>). --define(PAX_LINKPATH, <<"linkpath">>). --define(PAX_MTIME, <<"mtime">>). --define(PAX_PATH, <<"path">>). --define(PAX_SIZE, <<"size">>). --define(PAX_UID, <<"uid">>). --define(PAX_UNAME, <<"uname">>). --define(PAX_XATTR, <<"SCHILY.xattr.">>). --define(PAX_XATTR_STR, "SCHILY.xattr."). --define(PAX_NONE, <<"">>). - -%% Tar format constants -%% Unknown format --define(FORMAT_UNKNOWN, 0). -%% The format of the original Unix V7 tar tool prior to standardization --define(FORMAT_V7, 1). -%% The old and new GNU formats, incompatible with USTAR. -%% This covers the old GNU sparse extension, but it does -%% not cover the GNU sparse extensions using PAX headers, -%% versions 0.0, 0.1, and 1.0; these fall under the PAX format. --define(FORMAT_GNU, 2). -%% Schily's tar format, which is incompatible with USTAR. -%% This does not cover STAR extensions to the PAX format; these -%% fall under the PAX format. --define(FORMAT_STAR, 3). -%% USTAR is the former standardization of tar defined in POSIX.1-1988, -%% it is incompatible with the GNU and STAR formats. --define(FORMAT_USTAR, 4). -%% PAX is the latest standardization of tar defined in POSIX.1-2001. -%% This is an extension of USTAR and is "backwards compatible" with it. -%% -%% Some newer formats add their own extensions to PAX, such as GNU sparse -%% files and SCHILY extended attributes. Since they are backwards compatible -%% with PAX, they will be labelled as "PAX". --define(FORMAT_PAX, 5). - -%% Magic constants --define(MAGIC_GNU, <<"ustar ">>). --define(VERSION_GNU, <<" \x00">>). --define(MAGIC_USTAR, <<"ustar\x00">>). --define(VERSION_USTAR, <<"00">>). --define(TRAILER_STAR, <<"tar\x00">>). - -%% Size constants --define(BLOCK_SIZE, 512). %% size of each block in a tar stream --define(NAME_SIZE, 100). %% max length of the name field in USTAR format --define(PREFIX_SIZE, 155). %% max length of the prefix field in USTAR format - -%% Maximum size of a nanosecond value as an integer --define(MAX_NANO_INT_SIZE, 9). -%% Maximum size of a 64-bit signed integer --define(MAX_INT64, (1 bsl 63 - 1)). - --define(PAX_GNU_SPARSE_NUMBLOCKS, <<"GNU.sparse.numblocks">>). --define(PAX_GNU_SPARSE_OFFSET, <<"GNU.sparse.offset">>). --define(PAX_GNU_SPARSE_NUMBYTES, <<"GNU.sparse.numbytes">>). --define(PAX_GNU_SPARSE_MAP, <<"GNU.sparse.map">>). --define(PAX_GNU_SPARSE_NAME, <<"GNU.sparse.name">>). --define(PAX_GNU_SPARSE_MAJOR, <<"GNU.sparse.major">>). --define(PAX_GNU_SPARSE_MINOR, <<"GNU.sparse.minor">>). --define(PAX_GNU_SPARSE_SIZE, <<"GNU.sparse.size">>). --define(PAX_GNU_SPARSE_REALSIZE, <<"GNU.sparse.realsize">>). - --define(V7_NAME, 0). --define(V7_NAME_LEN, 100). --define(V7_MODE, 100). --define(V7_MODE_LEN, 8). --define(V7_UID, 108). --define(V7_UID_LEN, 8). --define(V7_GID, 116). --define(V7_GID_LEN, 8). --define(V7_SIZE, 124). --define(V7_SIZE_LEN, 12). --define(V7_MTIME, 136). --define(V7_MTIME_LEN, 12). --define(V7_CHKSUM, 148). --define(V7_CHKSUM_LEN, 8). --define(V7_TYPE, 156). --define(V7_TYPE_LEN, 1). --define(V7_LINKNAME, 157). --define(V7_LINKNAME_LEN, 100). - --define(STAR_TRAILER, 508). --define(STAR_TRAILER_LEN, 4). - --define(USTAR_MAGIC, 257). --define(USTAR_MAGIC_LEN, 6). --define(USTAR_VERSION, 263). --define(USTAR_VERSION_LEN, 2). --define(USTAR_UNAME, 265). --define(USTAR_UNAME_LEN, 32). --define(USTAR_GNAME, 297). --define(USTAR_GNAME_LEN, 32). --define(USTAR_DEVMAJ, 329). --define(USTAR_DEVMAJ_LEN, 8). --define(USTAR_DEVMIN, 337). --define(USTAR_DEVMIN_LEN, 8). --define(USTAR_PREFIX, 345). --define(USTAR_PREFIX_LEN, 155). - --define(GNU_MAGIC, 257). --define(GNU_MAGIC_LEN, 6). --define(GNU_VERSION, 263). --define(GNU_VERSION_LEN, 2). - -%% ?BLOCK_SIZE of zero-bytes. -%% Two of these in a row mark the end of an archive. --define(ZERO_BLOCK, <<0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0>>). - --define(BILLION, 1000000000). - --define(EPOCH, {{1970,1,1}, {0,0,0}}). diff --git a/_build/default/plugins/hex_core/src/hex_filename.erl b/_build/default/plugins/hex_core/src/hex_filename.erl deleted file mode 100644 index 58af55758b..0000000000 --- a/_build/default/plugins/hex_core/src/hex_filename.erl +++ /dev/null @@ -1,58 +0,0 @@ -% @private -% Excerpt from https://hub.fastgit.org/erlang/otp/blob/OTP-20.0.1/lib/stdlib/src/filename.erl#L761-L788 -% with modifications for changing local function calls to remote function calls -% to the `filename` module, for the functions `pathtype/1`, `split/1`, and `join/1` -% -% safe_relative_path/1 was not present in earlier OTP releases. - -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 1997-2017. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%% -%% %CopyrightEnd% -%% - --module(hex_filename). --export([safe_relative_path/1]). - -safe_relative_path(Path) -> - case filename:pathtype(Path) of - relative -> - Cs0 = filename:split(Path), - safe_relative_path_1(Cs0, []); - _ -> - unsafe - end. - -safe_relative_path_1(["."|T], Acc) -> - safe_relative_path_1(T, Acc); -safe_relative_path_1([<<".">>|T], Acc) -> - safe_relative_path_1(T, Acc); -safe_relative_path_1([".."|T], Acc) -> - climb(T, Acc); -safe_relative_path_1([<<"..">>|T], Acc) -> - climb(T, Acc); -safe_relative_path_1([H|T], Acc) -> - safe_relative_path_1(T, [H|Acc]); -safe_relative_path_1([], []) -> - []; -safe_relative_path_1([], Acc) -> - filename:join(lists:reverse(Acc)). - -climb(_, []) -> - unsafe; -climb(T, [_|Acc]) -> - safe_relative_path_1(T, Acc). diff --git a/_build/default/plugins/hex_core/src/hex_http.erl b/_build/default/plugins/hex_core/src/hex_http.erl deleted file mode 100644 index bed9e9dfb2..0000000000 --- a/_build/default/plugins/hex_core/src/hex_http.erl +++ /dev/null @@ -1,51 +0,0 @@ --module(hex_http). --export([request/5]). --ifdef(TEST). --export([user_agent/1]). --endif. --include_lib("hex_core.hrl"). - --type method() :: get | post | put | patch | delete. --type status() :: non_neg_integer(). --export_type([status/0]). --type headers() :: #{binary() => binary()}. --export_type([headers/0]). --type body() :: {ContentType :: binary(), Body :: binary()} | undefined. --type adapter_config() :: map(). - --callback request(method(), URI :: binary(), headers(), body(), adapter_config()) -> - {ok, status(), headers(), binary()} | - {error, term()}. - --spec request(hex_core:config(), method(), URI :: binary(), headers(), body()) -> - {ok, {status(), headers(), binary()}} | {error, term()}. -request(Config, Method, URI, Headers, Body) when is_binary(URI) and is_map(Headers) -> - {Adapter, AdapterConfig} = case maps:get(http_adapter, Config, {hex_http_httpc, #{}}) of - {Adapter0, AdapterConfig0} -> - {Adapter0, AdapterConfig0}; - %% TODO: remove in v0.9 - Adapter0 when is_atom(Adapter0) -> - AdapterConfig0 = maps:get(http_adapter_config, Config, #{}), - io:format("[hex_http] setting #{http_adapter => Module, http_adapter_config => Map} " - "is deprecated in favour of #{http_adapter => {Module, Map}}~n"), - {Adapter0, AdapterConfig0} - end, - UserAgentFragment = maps:get(http_user_agent_fragment, Config), - Headers2 = put_new(<<"user-agent">>, user_agent(UserAgentFragment), Headers), - Adapter:request(Method, URI, Headers2, Body, AdapterConfig). - -user_agent(UserAgentFragment) -> - OTPRelease = erlang:system_info(otp_release), - ERTSVersion = erlang:system_info(version), - OTPString = " (OTP/" ++ OTPRelease ++ ") (erts/" ++ ERTSVersion ++ ")", - iolist_to_binary(["hex_core/", ?HEX_CORE_VERSION, " ", UserAgentFragment, OTPString]). - -%%==================================================================== -%% Internal functions -%%==================================================================== - -put_new(Key, Value, Map) -> - case maps:find(Key, Map) of - {ok, _} -> Map; - error -> maps:put(Key, Value, Map) - end. diff --git a/_build/default/plugins/hex_core/src/hex_http_httpc.erl b/_build/default/plugins/hex_core/src/hex_http_httpc.erl deleted file mode 100644 index 9a56a99dfe..0000000000 --- a/_build/default/plugins/hex_core/src/hex_http_httpc.erl +++ /dev/null @@ -1,39 +0,0 @@ -%% @hidden - --module(hex_http_httpc). --behaviour(hex_http). --export([request/5]). - -%%==================================================================== -%% API functions -%%==================================================================== - -request(Method, URI, ReqHeaders, Body, AdapterConfig) -> - Profile = maps:get(profile, AdapterConfig, default), - Request = build_request(URI, ReqHeaders, Body), - case httpc:request(Method, Request, [], [{body_format, binary}], Profile) of - {ok, {{_, StatusCode, _}, RespHeaders, RespBody}} -> - RespHeaders2 = load_headers(RespHeaders), - {ok, {StatusCode, RespHeaders2, RespBody}}; - {error, Reason} -> {error, Reason} - end. - -%%==================================================================== -%% Internal functions -%%==================================================================== - -build_request(URI, ReqHeaders, Body) -> - build_request2(binary_to_list(URI), dump_headers(ReqHeaders), Body). - -build_request2(URI, ReqHeaders, undefined) -> - {URI, ReqHeaders}; -build_request2(URI, ReqHeaders, {ContentType, Body}) -> - {URI, ReqHeaders, ContentType, Body}. - -dump_headers(Map) -> - maps:fold(fun(K, V, Acc) -> - [{binary_to_list(K), binary_to_list(V)} | Acc] end, [], Map). - -load_headers(List) -> - lists:foldl(fun({K, V}, Acc) -> - maps:put(list_to_binary(K), list_to_binary(V), Acc) end, #{}, List). diff --git a/_build/default/plugins/hex_core/src/hex_pb_names.erl b/_build/default/plugins/hex_core/src/hex_pb_names.erl deleted file mode 100644 index de51f0bc35..0000000000 --- a/_build/default/plugins/hex_core/src/hex_pb_names.erl +++ /dev/null @@ -1,733 +0,0 @@ -%% -*- coding: utf-8 -*- -%% Automatically generated, do not edit -%% Generated by gpb_compile version 4.3.1 --module(hex_pb_names). - --export([encode_msg/2, encode_msg/3]). --export([decode_msg/2, decode_msg/3]). --export([merge_msgs/3, merge_msgs/4]). --export([verify_msg/2, verify_msg/3]). --export([get_msg_defs/0]). --export([get_msg_names/0]). --export([get_group_names/0]). --export([get_msg_or_group_names/0]). --export([get_enum_names/0]). --export([find_msg_def/1, fetch_msg_def/1]). --export([find_enum_def/1, fetch_enum_def/1]). --export([enum_symbol_by_value/2, enum_value_by_symbol/2]). --export([get_service_names/0]). --export([get_service_def/1]). --export([get_rpc_names/1]). --export([find_rpc_def/2, fetch_rpc_def/2]). --export([get_package_name/0]). --export([gpb_version_as_string/0, gpb_version_as_list/0]). - - -%% enumerated types - --export_type([]). - -%% message types --type 'Names'() :: - #{packages => ['Package'()], % = 1 - repository => iodata() % = 2 - }. - --type 'Package'() :: - #{name => iodata() % = 1 - }. - --export_type(['Names'/0, 'Package'/0]). - --spec encode_msg('Names'() | 'Package'(), atom()) -> binary(). -encode_msg(Msg, MsgName) when is_atom(MsgName) -> - encode_msg(Msg, MsgName, []). - --spec encode_msg('Names'() | 'Package'(), atom(), list()) -> binary(). -encode_msg(Msg, MsgName, Opts) -> - verify_msg(Msg, MsgName, Opts), - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Names' -> e_msg_Names(id(Msg, TrUserData), TrUserData); - 'Package' -> - e_msg_Package(id(Msg, TrUserData), TrUserData) - end. - - -e_msg_Names(Msg, TrUserData) -> - e_msg_Names(Msg, <<>>, TrUserData). - - -e_msg_Names(#{repository := F2} = M, Bin, TrUserData) -> - B1 = case M of - #{packages := F1} -> - TrF1 = id(F1, TrUserData), - if TrF1 == [] -> Bin; - true -> e_field_Names_packages(TrF1, Bin, TrUserData) - end; - _ -> Bin - end, - begin - TrF2 = id(F2, TrUserData), - e_type_string(TrF2, <>, TrUserData) - end. - -e_msg_Package(Msg, TrUserData) -> - e_msg_Package(Msg, <<>>, TrUserData). - - -e_msg_Package(#{name := F1}, Bin, TrUserData) -> - begin - TrF1 = id(F1, TrUserData), - e_type_string(TrF1, <>, TrUserData) - end. - -e_mfield_Names_packages(Msg, Bin, TrUserData) -> - SubBin = e_msg_Package(Msg, <<>>, TrUserData), - Bin2 = e_varint(byte_size(SubBin), Bin), - <>. - -e_field_Names_packages([Elem | Rest], Bin, - TrUserData) -> - Bin2 = <>, - Bin3 = e_mfield_Names_packages(id(Elem, TrUserData), - Bin2, TrUserData), - e_field_Names_packages(Rest, Bin3, TrUserData); -e_field_Names_packages([], Bin, _TrUserData) -> Bin. - --compile({nowarn_unused_function,e_type_sint/3}). -e_type_sint(Value, Bin, _TrUserData) when Value >= 0 -> - e_varint(Value * 2, Bin); -e_type_sint(Value, Bin, _TrUserData) -> - e_varint(Value * -2 - 1, Bin). - --compile({nowarn_unused_function,e_type_int32/3}). -e_type_int32(Value, Bin, _TrUserData) - when 0 =< Value, Value =< 127 -> - <>; -e_type_int32(Value, Bin, _TrUserData) -> - <> = <>, - e_varint(N, Bin). - --compile({nowarn_unused_function,e_type_int64/3}). -e_type_int64(Value, Bin, _TrUserData) - when 0 =< Value, Value =< 127 -> - <>; -e_type_int64(Value, Bin, _TrUserData) -> - <> = <>, - e_varint(N, Bin). - --compile({nowarn_unused_function,e_type_bool/3}). -e_type_bool(true, Bin, _TrUserData) -> - <>; -e_type_bool(false, Bin, _TrUserData) -> - <>; -e_type_bool(1, Bin, _TrUserData) -> <>; -e_type_bool(0, Bin, _TrUserData) -> <>. - --compile({nowarn_unused_function,e_type_string/3}). -e_type_string(S, Bin, _TrUserData) -> - Utf8 = unicode:characters_to_binary(S), - Bin2 = e_varint(byte_size(Utf8), Bin), - <>. - --compile({nowarn_unused_function,e_type_bytes/3}). -e_type_bytes(Bytes, Bin, _TrUserData) - when is_binary(Bytes) -> - Bin2 = e_varint(byte_size(Bytes), Bin), - <>; -e_type_bytes(Bytes, Bin, _TrUserData) - when is_list(Bytes) -> - BytesBin = iolist_to_binary(Bytes), - Bin2 = e_varint(byte_size(BytesBin), Bin), - <>. - --compile({nowarn_unused_function,e_type_fixed32/3}). -e_type_fixed32(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_sfixed32/3}). -e_type_sfixed32(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_fixed64/3}). -e_type_fixed64(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_sfixed64/3}). -e_type_sfixed64(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_float/3}). -e_type_float(V, Bin, _) when is_number(V) -> - <>; -e_type_float(infinity, Bin, _) -> - <>; -e_type_float('-infinity', Bin, _) -> - <>; -e_type_float(nan, Bin, _) -> - <>. - --compile({nowarn_unused_function,e_type_double/3}). -e_type_double(V, Bin, _) when is_number(V) -> - <>; -e_type_double(infinity, Bin, _) -> - <>; -e_type_double('-infinity', Bin, _) -> - <>; -e_type_double(nan, Bin, _) -> - <>. - --compile({nowarn_unused_function,e_varint/3}). -e_varint(N, Bin, _TrUserData) -> e_varint(N, Bin). - --compile({nowarn_unused_function,e_varint/2}). -e_varint(N, Bin) when N =< 127 -> <>; -e_varint(N, Bin) -> - Bin2 = <>, - e_varint(N bsr 7, Bin2). - - -decode_msg(Bin, MsgName) when is_binary(Bin) -> - decode_msg(Bin, MsgName, []). - -decode_msg(Bin, MsgName, Opts) when is_binary(Bin) -> - TrUserData = proplists:get_value(user_data, Opts), - decode_msg_1_catch(Bin, MsgName, TrUserData). - --ifdef('OTP_RELEASE'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. --ifdef('GPB_PATTERN_STACK'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --endif. - --endif. - -decode_msg_2_doit('Names', Bin, TrUserData) -> - id(d_msg_Names(Bin, TrUserData), TrUserData); -decode_msg_2_doit('Package', Bin, TrUserData) -> - id(d_msg_Package(Bin, TrUserData), TrUserData). - - - -d_msg_Names(Bin, TrUserData) -> - dfp_read_field_def_Names(Bin, 0, 0, id([], TrUserData), - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_Names(<<10, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - d_field_Names_packages(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -dfp_read_field_def_Names(<<18, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - d_field_Names_repository(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -dfp_read_field_def_Names(<<>>, 0, 0, R1, F@_2, - TrUserData) -> - S1 = #{repository => F@_2}, - if R1 == '$undef' -> S1; - true -> S1#{packages => lists_reverse(R1, TrUserData)} - end; -dfp_read_field_def_Names(Other, Z1, Z2, F@_1, F@_2, - TrUserData) -> - dg_read_field_def_Names(Other, Z1, Z2, F@_1, F@_2, - TrUserData). - -dg_read_field_def_Names(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Names(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -dg_read_field_def_Names(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Names_packages(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 18 -> - d_field_Names_repository(Rest, 0, 0, F@_1, F@_2, - TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Names(Rest, 0, 0, F@_1, F@_2, TrUserData); - 1 -> skip_64_Names(Rest, 0, 0, F@_1, F@_2, TrUserData); - 2 -> - skip_length_delimited_Names(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 3 -> - skip_group_Names(Rest, Key bsr 3, 0, F@_1, F@_2, - TrUserData); - 5 -> skip_32_Names(Rest, 0, 0, F@_1, F@_2, TrUserData) - end - end; -dg_read_field_def_Names(<<>>, 0, 0, R1, F@_2, - TrUserData) -> - S1 = #{repository => F@_2}, - if R1 == '$undef' -> S1; - true -> S1#{packages => lists_reverse(R1, TrUserData)} - end. - -d_field_Names_packages(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_Names_packages(Rest, N + 7, X bsl N + Acc, F@_1, - F@_2, TrUserData); -d_field_Names_packages(<<0:1, X:7, Rest/binary>>, N, - Acc, Prev, F@_2, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(d_msg_Package(Bs, TrUserData), TrUserData), - Rest2} - end, - dfp_read_field_def_Names(RestF, 0, 0, - cons(NewFValue, Prev, TrUserData), F@_2, - TrUserData). - -d_field_Names_repository(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_Names_repository(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -d_field_Names_repository(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Names(RestF, 0, 0, F@_1, NewFValue, - TrUserData). - -skip_varint_Names(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - skip_varint_Names(Rest, Z1, Z2, F@_1, F@_2, TrUserData); -skip_varint_Names(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - dfp_read_field_def_Names(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -skip_length_delimited_Names(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - skip_length_delimited_Names(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -skip_length_delimited_Names(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Names(Rest2, 0, 0, F@_1, F@_2, - TrUserData). - -skip_group_Names(Bin, FNum, Z2, F@_1, F@_2, - TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Names(Rest, 0, Z2, F@_1, F@_2, - TrUserData). - -skip_32_Names(<<_:32, Rest/binary>>, Z1, Z2, F@_1, F@_2, - TrUserData) -> - dfp_read_field_def_Names(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -skip_64_Names(<<_:64, Rest/binary>>, Z1, Z2, F@_1, F@_2, - TrUserData) -> - dfp_read_field_def_Names(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -d_msg_Package(Bin, TrUserData) -> - dfp_read_field_def_Package(Bin, 0, 0, - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_Package(<<10, Rest/binary>>, Z1, Z2, - F@_1, TrUserData) -> - d_field_Package_name(Rest, Z1, Z2, F@_1, TrUserData); -dfp_read_field_def_Package(<<>>, 0, 0, F@_1, _) -> - #{name => F@_1}; -dfp_read_field_def_Package(Other, Z1, Z2, F@_1, - TrUserData) -> - dg_read_field_def_Package(Other, Z1, Z2, F@_1, - TrUserData). - -dg_read_field_def_Package(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Package(Rest, N + 7, X bsl N + Acc, - F@_1, TrUserData); -dg_read_field_def_Package(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Package_name(Rest, 0, 0, F@_1, TrUserData); - _ -> - case Key band 7 of - 0 -> skip_varint_Package(Rest, 0, 0, F@_1, TrUserData); - 1 -> skip_64_Package(Rest, 0, 0, F@_1, TrUserData); - 2 -> - skip_length_delimited_Package(Rest, 0, 0, F@_1, - TrUserData); - 3 -> - skip_group_Package(Rest, Key bsr 3, 0, F@_1, - TrUserData); - 5 -> skip_32_Package(Rest, 0, 0, F@_1, TrUserData) - end - end; -dg_read_field_def_Package(<<>>, 0, 0, F@_1, _) -> - #{name => F@_1}. - -d_field_Package_name(<<1:1, X:7, Rest/binary>>, N, Acc, - F@_1, TrUserData) - when N < 57 -> - d_field_Package_name(Rest, N + 7, X bsl N + Acc, F@_1, - TrUserData); -d_field_Package_name(<<0:1, X:7, Rest/binary>>, N, Acc, - _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Package(RestF, 0, 0, NewFValue, - TrUserData). - -skip_varint_Package(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, TrUserData) -> - skip_varint_Package(Rest, Z1, Z2, F@_1, TrUserData); -skip_varint_Package(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, - TrUserData). - -skip_length_delimited_Package(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, TrUserData) - when N < 57 -> - skip_length_delimited_Package(Rest, N + 7, - X bsl N + Acc, F@_1, TrUserData); -skip_length_delimited_Package(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Package(Rest2, 0, 0, F@_1, - TrUserData). - -skip_group_Package(Bin, FNum, Z2, F@_1, TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Package(Rest, 0, Z2, F@_1, - TrUserData). - -skip_32_Package(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, - TrUserData). - -skip_64_Package(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, - TrUserData). - -read_group(Bin, FieldNum) -> - {NumBytes, EndTagLen} = read_gr_b(Bin, 0, 0, 0, 0, FieldNum), - <> = Bin, - {Group, Rest}. - -%% Like skipping over fields, but record the total length, -%% Each field is <(FieldNum bsl 3) bor FieldType> ++ -%% Record the length because varints may be non-optimally encoded. -%% -%% Groups can be nested, but assume the same FieldNum cannot be nested -%% because group field numbers are shared with the rest of the fields -%% numbers. Thus we can search just for an group-end with the same -%% field number. -%% -%% (The only time the same group field number could occur would -%% be in a nested sub message, but then it would be inside a -%% length-delimited entry, which we skip-read by length.) -read_gr_b(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, FieldNum) - when N < (32-7) -> - read_gr_b(Tl, N+7, X bsl N + Acc, NumBytes, TagLen+1, FieldNum); -read_gr_b(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, - FieldNum) -> - Key = X bsl N + Acc, - TagLen1 = TagLen + 1, - case {Key bsr 3, Key band 7} of - {FieldNum, 4} -> % 4 = group_end - {NumBytes, TagLen1}; - {_, 0} -> % 0 = varint - read_gr_vi(Tl, 0, NumBytes + TagLen1, FieldNum); - {_, 1} -> % 1 = bits64 - <<_:64, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 8, 0, FieldNum); - {_, 2} -> % 2 = length_delimited - read_gr_ld(Tl, 0, 0, NumBytes + TagLen1, FieldNum); - {_, 3} -> % 3 = group_start - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 4} -> % 4 = group_end - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 5} -> % 5 = bits32 - <<_:32, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 4, 0, FieldNum) - end. - -read_gr_vi(<<1:1, _:7, Tl/binary>>, N, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_vi(Tl, N+7, NumBytes+1, FieldNum); -read_gr_vi(<<0:1, _:7, Tl/binary>>, _, NumBytes, FieldNum) -> - read_gr_b(Tl, 0, 0, NumBytes+1, 0, FieldNum). - -read_gr_ld(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_ld(Tl, N+7, X bsl N + Acc, NumBytes+1, FieldNum); -read_gr_ld(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) -> - Len = X bsl N + Acc, - NumBytes1 = NumBytes + 1, - <<_:Len/binary, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes1 + Len, 0, FieldNum). - -merge_msgs(Prev, New, MsgName) when is_atom(MsgName) -> - merge_msgs(Prev, New, MsgName, []). - -merge_msgs(Prev, New, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Names' -> merge_msg_Names(Prev, New, TrUserData); - 'Package' -> merge_msg_Package(Prev, New, TrUserData) - end. - --compile({nowarn_unused_function,merge_msg_Names/3}). -merge_msg_Names(#{} = PMsg, - #{repository := NFrepository} = NMsg, TrUserData) -> - S1 = #{repository => NFrepository}, - case {PMsg, NMsg} of - {#{packages := PFpackages}, - #{packages := NFpackages}} -> - S1#{packages => - 'erlang_++'(PFpackages, NFpackages, TrUserData)}; - {_, #{packages := NFpackages}} -> - S1#{packages => NFpackages}; - {#{packages := PFpackages}, _} -> - S1#{packages => PFpackages}; - {_, _} -> S1 - end. - --compile({nowarn_unused_function,merge_msg_Package/3}). -merge_msg_Package(#{}, #{name := NFname}, _) -> - #{name => NFname}. - - -verify_msg(Msg, MsgName) when is_atom(MsgName) -> - verify_msg(Msg, MsgName, []). - -verify_msg(Msg, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Names' -> v_msg_Names(Msg, [MsgName], TrUserData); - 'Package' -> v_msg_Package(Msg, [MsgName], TrUserData); - _ -> mk_type_error(not_a_known_message, Msg, []) - end. - - --compile({nowarn_unused_function,v_msg_Names/3}). -v_msg_Names(#{repository := F2} = M, Path, - TrUserData) -> - case M of - #{packages := F1} -> - if is_list(F1) -> - _ = [v_msg_Package(Elem, [packages | Path], TrUserData) - || Elem <- F1], - ok; - true -> - mk_type_error({invalid_list_of, {msg, 'Package'}}, F1, - [packages | Path]) - end; - _ -> ok - end, - v_type_string(F2, [repository | Path], TrUserData), - lists:foreach(fun (packages) -> ok; - (repository) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Names(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, - [repository] -- maps:keys(M), 'Names'}, - M, Path); -v_msg_Names(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Names'}, X, Path). - --compile({nowarn_unused_function,v_msg_Package/3}). -v_msg_Package(#{name := F1} = M, Path, TrUserData) -> - v_type_string(F1, [name | Path], TrUserData), - lists:foreach(fun (name) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Package(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, [name] -- maps:keys(M), - 'Package'}, - M, Path); -v_msg_Package(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Package'}, X, Path). - --compile({nowarn_unused_function,v_type_string/3}). -v_type_string(S, Path, _TrUserData) - when is_list(S); is_binary(S) -> - try unicode:characters_to_binary(S) of - B when is_binary(B) -> ok; - {error, _, _} -> - mk_type_error(bad_unicode_string, S, Path) - catch - error:badarg -> - mk_type_error(bad_unicode_string, S, Path) - end; -v_type_string(X, Path, _TrUserData) -> - mk_type_error(bad_unicode_string, X, Path). - --compile({nowarn_unused_function,mk_type_error/3}). --spec mk_type_error(_, _, list()) -> no_return(). -mk_type_error(Error, ValueSeen, Path) -> - Path2 = prettify_path(Path), - erlang:error({gpb_type_error, - {Error, [{value, ValueSeen}, {path, Path2}]}}). - - --compile({nowarn_unused_function,prettify_path/1}). -prettify_path([]) -> top_level; -prettify_path(PathR) -> - list_to_atom(string:join(lists:map(fun atom_to_list/1, - lists:reverse(PathR)), - ".")). - - --compile({nowarn_unused_function,id/2}). --compile({inline,id/2}). -id(X, _TrUserData) -> X. - --compile({nowarn_unused_function,v_ok/3}). --compile({inline,v_ok/3}). -v_ok(_Value, _Path, _TrUserData) -> ok. - --compile({nowarn_unused_function,m_overwrite/3}). --compile({inline,m_overwrite/3}). -m_overwrite(_Prev, New, _TrUserData) -> New. - --compile({nowarn_unused_function,cons/3}). --compile({inline,cons/3}). -cons(Elem, Acc, _TrUserData) -> [Elem | Acc]. - --compile({nowarn_unused_function,lists_reverse/2}). --compile({inline,lists_reverse/2}). -'lists_reverse'(L, _TrUserData) -> lists:reverse(L). --compile({nowarn_unused_function,'erlang_++'/3}). --compile({inline,'erlang_++'/3}). -'erlang_++'(A, B, _TrUserData) -> A ++ B. - -get_msg_defs() -> - [{{msg, 'Names'}, - [#{name => packages, fnum => 1, rnum => 2, - type => {msg, 'Package'}, occurrence => repeated, - opts => []}, - #{name => repository, fnum => 2, rnum => 3, - type => string, occurrence => required, opts => []}]}, - {{msg, 'Package'}, - [#{name => name, fnum => 1, rnum => 2, type => string, - occurrence => required, opts => []}]}]. - - -get_msg_names() -> ['Names', 'Package']. - - -get_group_names() -> []. - - -get_msg_or_group_names() -> ['Names', 'Package']. - - -get_enum_names() -> []. - - -fetch_msg_def(MsgName) -> - case find_msg_def(MsgName) of - Fs when is_list(Fs) -> Fs; - error -> erlang:error({no_such_msg, MsgName}) - end. - - --spec fetch_enum_def(_) -> no_return(). -fetch_enum_def(EnumName) -> - erlang:error({no_such_enum, EnumName}). - - -find_msg_def('Names') -> - [#{name => packages, fnum => 1, rnum => 2, - type => {msg, 'Package'}, occurrence => repeated, - opts => []}, - #{name => repository, fnum => 2, rnum => 3, - type => string, occurrence => required, opts => []}]; -find_msg_def('Package') -> - [#{name => name, fnum => 1, rnum => 2, type => string, - occurrence => required, opts => []}]; -find_msg_def(_) -> error. - - -find_enum_def(_) -> error. - - --spec enum_symbol_by_value(_, _) -> no_return(). -enum_symbol_by_value(E, V) -> - erlang:error({no_enum_defs, E, V}). - - --spec enum_value_by_symbol(_, _) -> no_return(). -enum_value_by_symbol(E, V) -> - erlang:error({no_enum_defs, E, V}). - - - -get_service_names() -> []. - - -get_service_def(_) -> error. - - -get_rpc_names(_) -> error. - - -find_rpc_def(_, _) -> error. - - - --spec fetch_rpc_def(_, _) -> no_return(). -fetch_rpc_def(ServiceName, RpcName) -> - erlang:error({no_such_rpc, ServiceName, RpcName}). - - -get_package_name() -> undefined. - - - -gpb_version_as_string() -> - "4.3.1". - -gpb_version_as_list() -> - [4,3,1]. diff --git a/_build/default/plugins/hex_core/src/hex_pb_package.erl b/_build/default/plugins/hex_core/src/hex_pb_package.erl deleted file mode 100644 index e055e7305d..0000000000 --- a/_build/default/plugins/hex_core/src/hex_pb_package.erl +++ /dev/null @@ -1,1629 +0,0 @@ -%% -*- coding: utf-8 -*- -%% Automatically generated, do not edit -%% Generated by gpb_compile version 4.2.1 --module(hex_pb_package). - --export([encode_msg/2, encode_msg/3]). --export([decode_msg/2, decode_msg/3]). --export([merge_msgs/3, merge_msgs/4]). --export([verify_msg/2, verify_msg/3]). --export([get_msg_defs/0]). --export([get_msg_names/0]). --export([get_group_names/0]). --export([get_msg_or_group_names/0]). --export([get_enum_names/0]). --export([find_msg_def/1, fetch_msg_def/1]). --export([find_enum_def/1, fetch_enum_def/1]). --export([enum_symbol_by_value/2, enum_value_by_symbol/2]). --export([enum_symbol_by_value_RetirementReason/1, enum_value_by_symbol_RetirementReason/1]). --export([get_service_names/0]). --export([get_service_def/1]). --export([get_rpc_names/1]). --export([find_rpc_def/2, fetch_rpc_def/2]). --export([get_package_name/0]). --export([gpb_version_as_string/0, gpb_version_as_list/0]). - - -%% enumerated types --type 'RetirementReason'() :: 'RETIRED_OTHER' | 'RETIRED_INVALID' | 'RETIRED_SECURITY' | 'RETIRED_DEPRECATED' | 'RETIRED_RENAMED'. --export_type(['RetirementReason'/0]). - -%% message types --type 'Package'() :: - #{releases => ['Release'()], % = 1 - name => iodata(), % = 2 - repository => iodata() % = 3 - }. --type 'Release'() :: - #{version => iodata(), % = 1 - inner_checksum => iodata(), % = 2 - dependencies => ['Dependency'()] % = 3 - %% retired => 'RetirementStatus'() % = 4 - %% outer_checksum => iodata() % = 5 - }. --type 'RetirementStatus'() :: - #{reason => 'RETIRED_OTHER' | 'RETIRED_INVALID' | 'RETIRED_SECURITY' | 'RETIRED_DEPRECATED' | 'RETIRED_RENAMED' | integer() % = 1, enum RetirementReason - %% message => iodata() % = 2 - }. --type 'Dependency'() :: - #{package => iodata(), % = 1 - requirement => iodata() % = 2 - %% optional => boolean() | 0 | 1 % = 3 - %% app => iodata() % = 4 - %% repository => iodata() % = 5 - }. --export_type(['Package'/0, 'Release'/0, 'RetirementStatus'/0, 'Dependency'/0]). - --spec encode_msg('Package'() | 'Release'() | 'RetirementStatus'() | 'Dependency'(),'Package' | 'Release' | 'RetirementStatus' | 'Dependency') -> binary(). -encode_msg(Msg, MsgName) -> - encode_msg(Msg, MsgName, []). - - --spec encode_msg('Package'() | 'Release'() | 'RetirementStatus'() | 'Dependency'(),'Package' | 'Release' | 'RetirementStatus' | 'Dependency', list()) -> binary(). -encode_msg(Msg, MsgName, Opts) -> - verify_msg(Msg, MsgName, Opts), - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Package' -> e_msg_Package(Msg, TrUserData); - 'Release' -> e_msg_Release(Msg, TrUserData); - 'RetirementStatus' -> - e_msg_RetirementStatus(Msg, TrUserData); - 'Dependency' -> e_msg_Dependency(Msg, TrUserData) - end. - - - -e_msg_Package(Msg, TrUserData) -> - e_msg_Package(Msg, <<>>, TrUserData). - - -e_msg_Package(#{name := F2, repository := F3} = M, Bin, - TrUserData) -> - B1 = case M of - #{releases := F1} -> - TrF1 = id(F1, TrUserData), - if TrF1 == [] -> Bin; - true -> e_field_Package_releases(TrF1, Bin, TrUserData) - end; - _ -> Bin - end, - B2 = begin - TrF2 = id(F2, TrUserData), - e_type_string(TrF2, <>) - end, - begin - TrF3 = id(F3, TrUserData), - e_type_string(TrF3, <>) - end. - -e_msg_Release(Msg, TrUserData) -> - e_msg_Release(Msg, <<>>, TrUserData). - - -e_msg_Release(#{version := F1, inner_checksum := F2} = - M, - Bin, TrUserData) -> - B1 = begin - TrF1 = id(F1, TrUserData), - e_type_string(TrF1, <>) - end, - B2 = begin - TrF2 = id(F2, TrUserData), - e_type_bytes(TrF2, <>) - end, - B3 = case M of - #{dependencies := F3} -> - TrF3 = id(F3, TrUserData), - if TrF3 == [] -> B2; - true -> - e_field_Release_dependencies(TrF3, B2, TrUserData) - end; - _ -> B2 - end, - B4 = case M of - #{retired := F4} -> - begin - TrF4 = id(F4, TrUserData), - e_mfield_Release_retired(TrF4, <>, - TrUserData) - end; - _ -> B3 - end, - case M of - #{outer_checksum := F5} -> - begin - TrF5 = id(F5, TrUserData), - e_type_bytes(TrF5, <>) - end; - _ -> B4 - end. - -e_msg_RetirementStatus(Msg, TrUserData) -> - e_msg_RetirementStatus(Msg, <<>>, TrUserData). - - -e_msg_RetirementStatus(#{reason := F1} = M, Bin, - TrUserData) -> - B1 = begin - TrF1 = id(F1, TrUserData), - e_enum_RetirementReason(TrF1, <>) - end, - case M of - #{message := F2} -> - begin - TrF2 = id(F2, TrUserData), - e_type_string(TrF2, <>) - end; - _ -> B1 - end. - -e_msg_Dependency(Msg, TrUserData) -> - e_msg_Dependency(Msg, <<>>, TrUserData). - - -e_msg_Dependency(#{package := F1, requirement := F2} = - M, - Bin, TrUserData) -> - B1 = begin - TrF1 = id(F1, TrUserData), - e_type_string(TrF1, <>) - end, - B2 = begin - TrF2 = id(F2, TrUserData), - e_type_string(TrF2, <>) - end, - B3 = case M of - #{optional := F3} -> - begin - TrF3 = id(F3, TrUserData), - e_type_bool(TrF3, <>) - end; - _ -> B2 - end, - B4 = case M of - #{app := F4} -> - begin - TrF4 = id(F4, TrUserData), - e_type_string(TrF4, <>) - end; - _ -> B3 - end, - case M of - #{repository := F5} -> - begin - TrF5 = id(F5, TrUserData), - e_type_string(TrF5, <>) - end; - _ -> B4 - end. - -e_mfield_Package_releases(Msg, Bin, TrUserData) -> - SubBin = e_msg_Release(Msg, <<>>, TrUserData), - Bin2 = e_varint(byte_size(SubBin), Bin), - <>. - -e_field_Package_releases([Elem | Rest], Bin, - TrUserData) -> - Bin2 = <>, - Bin3 = e_mfield_Package_releases(id(Elem, TrUserData), - Bin2, TrUserData), - e_field_Package_releases(Rest, Bin3, TrUserData); -e_field_Package_releases([], Bin, _TrUserData) -> Bin. - -e_mfield_Release_dependencies(Msg, Bin, TrUserData) -> - SubBin = e_msg_Dependency(Msg, <<>>, TrUserData), - Bin2 = e_varint(byte_size(SubBin), Bin), - <>. - -e_field_Release_dependencies([Elem | Rest], Bin, - TrUserData) -> - Bin2 = <>, - Bin3 = e_mfield_Release_dependencies(id(Elem, - TrUserData), - Bin2, TrUserData), - e_field_Release_dependencies(Rest, Bin3, TrUserData); -e_field_Release_dependencies([], Bin, _TrUserData) -> - Bin. - -e_mfield_Release_retired(Msg, Bin, TrUserData) -> - SubBin = e_msg_RetirementStatus(Msg, <<>>, TrUserData), - Bin2 = e_varint(byte_size(SubBin), Bin), - <>. - -e_enum_RetirementReason('RETIRED_OTHER', Bin) -> - <>; -e_enum_RetirementReason('RETIRED_INVALID', Bin) -> - <>; -e_enum_RetirementReason('RETIRED_SECURITY', Bin) -> - <>; -e_enum_RetirementReason('RETIRED_DEPRECATED', Bin) -> - <>; -e_enum_RetirementReason('RETIRED_RENAMED', Bin) -> - <>; -e_enum_RetirementReason(V, Bin) -> e_varint(V, Bin). - -e_type_bool(true, Bin) -> <>; -e_type_bool(false, Bin) -> <>; -e_type_bool(1, Bin) -> <>; -e_type_bool(0, Bin) -> <>. - -e_type_string(S, Bin) -> - Utf8 = unicode:characters_to_binary(S), - Bin2 = e_varint(byte_size(Utf8), Bin), - <>. - -e_type_bytes(Bytes, Bin) when is_binary(Bytes) -> - Bin2 = e_varint(byte_size(Bytes), Bin), - <>; -e_type_bytes(Bytes, Bin) when is_list(Bytes) -> - BytesBin = iolist_to_binary(Bytes), - Bin2 = e_varint(byte_size(BytesBin), Bin), - <>. - -e_varint(N, Bin) when N =< 127 -> <>; -e_varint(N, Bin) -> - Bin2 = <>, - e_varint(N bsr 7, Bin2). - - -decode_msg(Bin, MsgName) when is_binary(Bin) -> - decode_msg(Bin, MsgName, []). - -decode_msg(Bin, MsgName, Opts) when is_binary(Bin) -> - TrUserData = proplists:get_value(user_data, Opts), - decode_msg_1_catch(Bin, MsgName, TrUserData). - --ifdef('OTP_RELEASE'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. --ifdef('GPB_PATTERN_STACK'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --endif. - --endif. - -decode_msg_2_doit('Package', Bin, TrUserData) -> - d_msg_Package(Bin, TrUserData); -decode_msg_2_doit('Release', Bin, TrUserData) -> - d_msg_Release(Bin, TrUserData); -decode_msg_2_doit('RetirementStatus', Bin, - TrUserData) -> - d_msg_RetirementStatus(Bin, TrUserData); -decode_msg_2_doit('Dependency', Bin, TrUserData) -> - d_msg_Dependency(Bin, TrUserData). - - - -d_msg_Package(Bin, TrUserData) -> - dfp_read_field_def_Package(Bin, 0, 0, - id([], TrUserData), id('$undef', TrUserData), - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_Package(<<10, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_field_Package_releases(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -dfp_read_field_def_Package(<<18, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_field_Package_name(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -dfp_read_field_def_Package(<<26, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_field_Package_repository(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData); -dfp_read_field_def_Package(<<>>, 0, 0, R1, F@_2, F@_3, - TrUserData) -> - #{releases => lists_reverse(R1, TrUserData), - name => F@_2, repository => F@_3}; -dfp_read_field_def_Package(Other, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData) -> - dg_read_field_def_Package(Other, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -dg_read_field_def_Package(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Package(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -dg_read_field_def_Package(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Package_releases(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 18 -> - d_field_Package_name(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 26 -> - d_field_Package_repository(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Package(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 1 -> - skip_64_Package(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 2 -> - skip_length_delimited_Package(Rest, 0, 0, F@_1, F@_2, - F@_3, TrUserData); - 3 -> - skip_group_Package(Rest, Key bsr 3, 0, F@_1, F@_2, F@_3, - TrUserData); - 5 -> - skip_32_Package(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData) - end - end; -dg_read_field_def_Package(<<>>, 0, 0, R1, F@_2, F@_3, - TrUserData) -> - #{releases => lists_reverse(R1, TrUserData), - name => F@_2, repository => F@_3}. - -d_field_Package_releases(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_field_Package_releases(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -d_field_Package_releases(<<0:1, X:7, Rest/binary>>, N, - Acc, Prev, F@_2, F@_3, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(d_msg_Release(Bs, TrUserData), TrUserData), - Rest2} - end, - dfp_read_field_def_Package(RestF, 0, 0, - cons(NewFValue, Prev, TrUserData), F@_2, F@_3, - TrUserData). - -d_field_Package_name(<<1:1, X:7, Rest/binary>>, N, Acc, - F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_field_Package_name(Rest, N + 7, X bsl N + Acc, F@_1, - F@_2, F@_3, TrUserData); -d_field_Package_name(<<0:1, X:7, Rest/binary>>, N, Acc, - F@_1, _, F@_3, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Package(RestF, 0, 0, F@_1, NewFValue, - F@_3, TrUserData). - -d_field_Package_repository(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_field_Package_repository(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -d_field_Package_repository(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Package(RestF, 0, 0, F@_1, F@_2, - NewFValue, TrUserData). - -skip_varint_Package(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - skip_varint_Package(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -skip_varint_Package(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -skip_length_delimited_Package(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - skip_length_delimited_Package(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, TrUserData); -skip_length_delimited_Package(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Package(Rest2, 0, 0, F@_1, F@_2, - F@_3, TrUserData). - -skip_group_Package(Bin, FNum, Z2, F@_1, F@_2, F@_3, - TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Package(Rest, 0, Z2, F@_1, F@_2, - F@_3, TrUserData). - -skip_32_Package(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -skip_64_Package(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -d_msg_Release(Bin, TrUserData) -> - dfp_read_field_def_Release(Bin, 0, 0, - id('$undef', TrUserData), - id('$undef', TrUserData), id([], TrUserData), - id('$undef', TrUserData), - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_Release(<<10, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Release_version(Rest, Z1, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); -dfp_read_field_def_Release(<<18, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Release_inner_checksum(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Release(<<26, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Release_dependencies(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Release(<<34, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Release_retired(Rest, Z1, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); -dfp_read_field_def_Release(<<42, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Release_outer_checksum(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Release(<<>>, 0, 0, F@_1, F@_2, R1, - F@_4, F@_5, TrUserData) -> - S1 = #{version => F@_1, inner_checksum => F@_2, - dependencies => lists_reverse(R1, TrUserData)}, - S2 = if F@_4 == '$undef' -> S1; - true -> S1#{retired => F@_4} - end, - if F@_5 == '$undef' -> S2; - true -> S2#{outer_checksum => F@_5} - end; -dfp_read_field_def_Release(Other, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData) -> - dg_read_field_def_Release(Other, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -dg_read_field_def_Release(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Release(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -dg_read_field_def_Release(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Release_version(Rest, 0, 0, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); - 18 -> - d_field_Release_inner_checksum(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 26 -> - d_field_Release_dependencies(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 34 -> - d_field_Release_retired(Rest, 0, 0, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); - 42 -> - d_field_Release_outer_checksum(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Release(Rest, 0, 0, F@_1, F@_2, F@_3, F@_4, - F@_5, TrUserData); - 1 -> - skip_64_Release(Rest, 0, 0, F@_1, F@_2, F@_3, F@_4, - F@_5, TrUserData); - 2 -> - skip_length_delimited_Release(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 3 -> - skip_group_Release(Rest, Key bsr 3, 0, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); - 5 -> - skip_32_Release(Rest, 0, 0, F@_1, F@_2, F@_3, F@_4, - F@_5, TrUserData) - end - end; -dg_read_field_def_Release(<<>>, 0, 0, F@_1, F@_2, R1, - F@_4, F@_5, TrUserData) -> - S1 = #{version => F@_1, inner_checksum => F@_2, - dependencies => lists_reverse(R1, TrUserData)}, - S2 = if F@_4 == '$undef' -> S1; - true -> S1#{retired => F@_4} - end, - if F@_5 == '$undef' -> S2; - true -> S2#{outer_checksum => F@_5} - end. - -d_field_Release_version(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Release_version(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -d_field_Release_version(<<0:1, X:7, Rest/binary>>, N, - Acc, _, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Release(RestF, 0, 0, NewFValue, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -d_field_Release_inner_checksum(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Release_inner_checksum(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData); -d_field_Release_inner_checksum(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, _, F@_3, F@_4, F@_5, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Release(RestF, 0, 0, F@_1, NewFValue, - F@_3, F@_4, F@_5, TrUserData). - -d_field_Release_dependencies(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Release_dependencies(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -d_field_Release_dependencies(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, Prev, F@_4, F@_5, - TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(d_msg_Dependency(Bs, TrUserData), TrUserData), - Rest2} - end, - dfp_read_field_def_Release(RestF, 0, 0, F@_1, F@_2, - cons(NewFValue, Prev, TrUserData), F@_4, F@_5, - TrUserData). - -d_field_Release_retired(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Release_retired(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -d_field_Release_retired(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, Prev, F@_5, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(d_msg_RetirementStatus(Bs, TrUserData), - TrUserData), - Rest2} - end, - dfp_read_field_def_Release(RestF, 0, 0, F@_1, F@_2, - F@_3, - if Prev == '$undef' -> NewFValue; - true -> - merge_msg_RetirementStatus(Prev, - NewFValue, - TrUserData) - end, - F@_5, TrUserData). - -d_field_Release_outer_checksum(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Release_outer_checksum(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData); -d_field_Release_outer_checksum(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Release(RestF, 0, 0, F@_1, F@_2, - F@_3, F@_4, NewFValue, TrUserData). - -skip_varint_Release(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - skip_varint_Release(Rest, Z1, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); -skip_varint_Release(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - dfp_read_field_def_Release(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_length_delimited_Release(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - skip_length_delimited_Release(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData); -skip_length_delimited_Release(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Release(Rest2, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_group_Release(Bin, FNum, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Release(Rest, 0, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_32_Release(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, F@_4, F@_5, TrUserData) -> - dfp_read_field_def_Release(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_64_Release(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, F@_4, F@_5, TrUserData) -> - dfp_read_field_def_Release(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -d_msg_RetirementStatus(Bin, TrUserData) -> - dfp_read_field_def_RetirementStatus(Bin, 0, 0, - id('$undef', TrUserData), - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_RetirementStatus(<<8, Rest/binary>>, - Z1, Z2, F@_1, F@_2, TrUserData) -> - d_field_RetirementStatus_reason(Rest, Z1, Z2, F@_1, - F@_2, TrUserData); -dfp_read_field_def_RetirementStatus(<<18, Rest/binary>>, - Z1, Z2, F@_1, F@_2, TrUserData) -> - d_field_RetirementStatus_message(Rest, Z1, Z2, F@_1, - F@_2, TrUserData); -dfp_read_field_def_RetirementStatus(<<>>, 0, 0, F@_1, - F@_2, _) -> - S1 = #{reason => F@_1}, - if F@_2 == '$undef' -> S1; - true -> S1#{message => F@_2} - end; -dfp_read_field_def_RetirementStatus(Other, Z1, Z2, F@_1, - F@_2, TrUserData) -> - dg_read_field_def_RetirementStatus(Other, Z1, Z2, F@_1, - F@_2, TrUserData). - -dg_read_field_def_RetirementStatus(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_RetirementStatus(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, TrUserData); -dg_read_field_def_RetirementStatus(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 8 -> - d_field_RetirementStatus_reason(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 18 -> - d_field_RetirementStatus_message(Rest, 0, 0, F@_1, F@_2, - TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_RetirementStatus(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 1 -> - skip_64_RetirementStatus(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 2 -> - skip_length_delimited_RetirementStatus(Rest, 0, 0, F@_1, - F@_2, TrUserData); - 3 -> - skip_group_RetirementStatus(Rest, Key bsr 3, 0, F@_1, - F@_2, TrUserData); - 5 -> - skip_32_RetirementStatus(Rest, 0, 0, F@_1, F@_2, - TrUserData) - end - end; -dg_read_field_def_RetirementStatus(<<>>, 0, 0, F@_1, - F@_2, _) -> - S1 = #{reason => F@_1}, - if F@_2 == '$undef' -> S1; - true -> S1#{message => F@_2} - end. - -d_field_RetirementStatus_reason(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_RetirementStatus_reason(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, TrUserData); -d_field_RetirementStatus_reason(<<0:1, X:7, - Rest/binary>>, - N, Acc, _, F@_2, TrUserData) -> - {NewFValue, RestF} = {d_enum_RetirementReason(begin - <> = - <<(X bsl N + - Acc):32/unsigned-native>>, - Res - end), - Rest}, - dfp_read_field_def_RetirementStatus(RestF, 0, 0, - NewFValue, F@_2, TrUserData). - -d_field_RetirementStatus_message(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_RetirementStatus_message(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, TrUserData); -d_field_RetirementStatus_message(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_RetirementStatus(RestF, 0, 0, F@_1, - NewFValue, TrUserData). - -skip_varint_RetirementStatus(<<1:1, _:7, Rest/binary>>, - Z1, Z2, F@_1, F@_2, TrUserData) -> - skip_varint_RetirementStatus(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -skip_varint_RetirementStatus(<<0:1, _:7, Rest/binary>>, - Z1, Z2, F@_1, F@_2, TrUserData) -> - dfp_read_field_def_RetirementStatus(Rest, Z1, Z2, F@_1, - F@_2, TrUserData). - -skip_length_delimited_RetirementStatus(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - skip_length_delimited_RetirementStatus(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, - TrUserData); -skip_length_delimited_RetirementStatus(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_RetirementStatus(Rest2, 0, 0, F@_1, - F@_2, TrUserData). - -skip_group_RetirementStatus(Bin, FNum, Z2, F@_1, F@_2, - TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_RetirementStatus(Rest, 0, Z2, F@_1, - F@_2, TrUserData). - -skip_32_RetirementStatus(<<_:32, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - dfp_read_field_def_RetirementStatus(Rest, Z1, Z2, F@_1, - F@_2, TrUserData). - -skip_64_RetirementStatus(<<_:64, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - dfp_read_field_def_RetirementStatus(Rest, Z1, Z2, F@_1, - F@_2, TrUserData). - -d_msg_Dependency(Bin, TrUserData) -> - dfp_read_field_def_Dependency(Bin, 0, 0, - id('$undef', TrUserData), - id('$undef', TrUserData), - id('$undef', TrUserData), - id('$undef', TrUserData), - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_Dependency(<<10, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Dependency_package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Dependency(<<18, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Dependency_requirement(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Dependency(<<24, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Dependency_optional(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Dependency(<<34, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Dependency_app(Rest, Z1, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); -dfp_read_field_def_Dependency(<<42, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - d_field_Dependency_repository(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); -dfp_read_field_def_Dependency(<<>>, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, _) -> - S1 = #{package => F@_1, requirement => F@_2}, - S2 = if F@_3 == '$undef' -> S1; - true -> S1#{optional => F@_3} - end, - S3 = if F@_4 == '$undef' -> S2; - true -> S2#{app => F@_4} - end, - if F@_5 == '$undef' -> S3; - true -> S3#{repository => F@_5} - end; -dfp_read_field_def_Dependency(Other, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData) -> - dg_read_field_def_Dependency(Other, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -dg_read_field_def_Dependency(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Dependency(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -dg_read_field_def_Dependency(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Dependency_package(Rest, 0, 0, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); - 18 -> - d_field_Dependency_requirement(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 24 -> - d_field_Dependency_optional(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 34 -> - d_field_Dependency_app(Rest, 0, 0, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); - 42 -> - d_field_Dependency_repository(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Dependency(Rest, 0, 0, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); - 1 -> - skip_64_Dependency(Rest, 0, 0, F@_1, F@_2, F@_3, F@_4, - F@_5, TrUserData); - 2 -> - skip_length_delimited_Dependency(Rest, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 3 -> - skip_group_Dependency(Rest, Key bsr 3, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData); - 5 -> - skip_32_Dependency(Rest, 0, 0, F@_1, F@_2, F@_3, F@_4, - F@_5, TrUserData) - end - end; -dg_read_field_def_Dependency(<<>>, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, _) -> - S1 = #{package => F@_1, requirement => F@_2}, - S2 = if F@_3 == '$undef' -> S1; - true -> S1#{optional => F@_3} - end, - S3 = if F@_4 == '$undef' -> S2; - true -> S2#{app => F@_4} - end, - if F@_5 == '$undef' -> S3; - true -> S3#{repository => F@_5} - end. - -d_field_Dependency_package(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Dependency_package(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -d_field_Dependency_package(<<0:1, X:7, Rest/binary>>, N, - Acc, _, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Dependency(RestF, 0, 0, NewFValue, - F@_2, F@_3, F@_4, F@_5, TrUserData). - -d_field_Dependency_requirement(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Dependency_requirement(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData); -d_field_Dependency_requirement(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, _, F@_3, F@_4, F@_5, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Dependency(RestF, 0, 0, F@_1, - NewFValue, F@_3, F@_4, F@_5, TrUserData). - -d_field_Dependency_optional(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Dependency_optional(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData); -d_field_Dependency_optional(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, _, F@_4, F@_5, TrUserData) -> - {NewFValue, RestF} = {X bsl N + Acc =/= 0, Rest}, - dfp_read_field_def_Dependency(RestF, 0, 0, F@_1, F@_2, - NewFValue, F@_4, F@_5, TrUserData). - -d_field_Dependency_app(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Dependency_app(Rest, N + 7, X bsl N + Acc, F@_1, - F@_2, F@_3, F@_4, F@_5, TrUserData); -d_field_Dependency_app(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, _, F@_5, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Dependency(RestF, 0, 0, F@_1, F@_2, - F@_3, NewFValue, F@_5, TrUserData). - -d_field_Dependency_repository(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) - when N < 57 -> - d_field_Dependency_repository(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData); -d_field_Dependency_repository(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {binary:copy(Bytes), Rest2} - end, - dfp_read_field_def_Dependency(RestF, 0, 0, F@_1, F@_2, - F@_3, F@_4, NewFValue, TrUserData). - -skip_varint_Dependency(<<1:1, _:7, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - skip_varint_Dependency(Rest, Z1, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData); -skip_varint_Dependency(<<0:1, _:7, Rest/binary>>, Z1, - Z2, F@_1, F@_2, F@_3, F@_4, F@_5, TrUserData) -> - dfp_read_field_def_Dependency(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_length_delimited_Dependency(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData) - when N < 57 -> - skip_length_delimited_Dependency(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, F@_4, - F@_5, TrUserData); -skip_length_delimited_Dependency(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, F@_4, F@_5, - TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Dependency(Rest2, 0, 0, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_group_Dependency(Bin, FNum, Z2, F@_1, F@_2, F@_3, - F@_4, F@_5, TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Dependency(Rest, 0, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_32_Dependency(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, F@_4, F@_5, TrUserData) -> - dfp_read_field_def_Dependency(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -skip_64_Dependency(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, F@_4, F@_5, TrUserData) -> - dfp_read_field_def_Dependency(Rest, Z1, Z2, F@_1, F@_2, - F@_3, F@_4, F@_5, TrUserData). - -d_enum_RetirementReason(0) -> 'RETIRED_OTHER'; -d_enum_RetirementReason(1) -> 'RETIRED_INVALID'; -d_enum_RetirementReason(2) -> 'RETIRED_SECURITY'; -d_enum_RetirementReason(3) -> 'RETIRED_DEPRECATED'; -d_enum_RetirementReason(4) -> 'RETIRED_RENAMED'; -d_enum_RetirementReason(V) -> V. - -read_group(Bin, FieldNum) -> - {NumBytes, EndTagLen} = read_gr_b(Bin, 0, 0, 0, 0, FieldNum), - <> = Bin, - {Group, Rest}. - -%% Like skipping over fields, but record the total length, -%% Each field is <(FieldNum bsl 3) bor FieldType> ++ -%% Record the length because varints may be non-optimally encoded. -%% -%% Groups can be nested, but assume the same FieldNum cannot be nested -%% because group field numbers are shared with the rest of the fields -%% numbers. Thus we can search just for an group-end with the same -%% field number. -%% -%% (The only time the same group field number could occur would -%% be in a nested sub message, but then it would be inside a -%% length-delimited entry, which we skip-read by length.) -read_gr_b(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, FieldNum) - when N < (32-7) -> - read_gr_b(Tl, N+7, X bsl N + Acc, NumBytes, TagLen+1, FieldNum); -read_gr_b(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, - FieldNum) -> - Key = X bsl N + Acc, - TagLen1 = TagLen + 1, - case {Key bsr 3, Key band 7} of - {FieldNum, 4} -> % 4 = group_end - {NumBytes, TagLen1}; - {_, 0} -> % 0 = varint - read_gr_vi(Tl, 0, NumBytes + TagLen1, FieldNum); - {_, 1} -> % 1 = bits64 - <<_:64, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 8, 0, FieldNum); - {_, 2} -> % 2 = length_delimited - read_gr_ld(Tl, 0, 0, NumBytes + TagLen1, FieldNum); - {_, 3} -> % 3 = group_start - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 4} -> % 4 = group_end - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 5} -> % 5 = bits32 - <<_:32, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 4, 0, FieldNum) - end. - -read_gr_vi(<<1:1, _:7, Tl/binary>>, N, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_vi(Tl, N+7, NumBytes+1, FieldNum); -read_gr_vi(<<0:1, _:7, Tl/binary>>, _, NumBytes, FieldNum) -> - read_gr_b(Tl, 0, 0, NumBytes+1, 0, FieldNum). - -read_gr_ld(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_ld(Tl, N+7, X bsl N + Acc, NumBytes+1, FieldNum); -read_gr_ld(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) -> - Len = X bsl N + Acc, - NumBytes1 = NumBytes + 1, - <<_:Len/binary, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes1 + Len, 0, FieldNum). - -merge_msgs(Prev, New, MsgName) -> - merge_msgs(Prev, New, MsgName, []). - -merge_msgs(Prev, New, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Package' -> merge_msg_Package(Prev, New, TrUserData); - 'Release' -> merge_msg_Release(Prev, New, TrUserData); - 'RetirementStatus' -> - merge_msg_RetirementStatus(Prev, New, TrUserData); - 'Dependency' -> - merge_msg_Dependency(Prev, New, TrUserData) - end. - -merge_msg_Package(#{} = PMsg, - #{name := NFname, repository := NFrepository} = NMsg, - TrUserData) -> - S1 = #{name => NFname, repository => NFrepository}, - case {PMsg, NMsg} of - {#{releases := PFreleases}, - #{releases := NFreleases}} -> - S1#{releases => - 'erlang_++'(PFreleases, NFreleases, TrUserData)}; - {_, #{releases := NFreleases}} -> - S1#{releases => NFreleases}; - {#{releases := PFreleases}, _} -> - S1#{releases => PFreleases}; - {_, _} -> S1 - end. - -merge_msg_Release(#{} = PMsg, - #{version := NFversion, - inner_checksum := NFinner_checksum} = - NMsg, - TrUserData) -> - S1 = #{version => NFversion, - inner_checksum => NFinner_checksum}, - S2 = case {PMsg, NMsg} of - {#{dependencies := PFdependencies}, - #{dependencies := NFdependencies}} -> - S1#{dependencies => - 'erlang_++'(PFdependencies, NFdependencies, - TrUserData)}; - {_, #{dependencies := NFdependencies}} -> - S1#{dependencies => NFdependencies}; - {#{dependencies := PFdependencies}, _} -> - S1#{dependencies => PFdependencies}; - {_, _} -> S1 - end, - S3 = case {PMsg, NMsg} of - {#{retired := PFretired}, #{retired := NFretired}} -> - S2#{retired => - merge_msg_RetirementStatus(PFretired, NFretired, - TrUserData)}; - {_, #{retired := NFretired}} -> - S2#{retired => NFretired}; - {#{retired := PFretired}, _} -> - S2#{retired => PFretired}; - {_, _} -> S2 - end, - case {PMsg, NMsg} of - {_, #{outer_checksum := NFouter_checksum}} -> - S3#{outer_checksum => NFouter_checksum}; - {#{outer_checksum := PFouter_checksum}, _} -> - S3#{outer_checksum => PFouter_checksum}; - _ -> S3 - end. - -merge_msg_RetirementStatus(#{} = PMsg, - #{reason := NFreason} = NMsg, _) -> - S1 = #{reason => NFreason}, - case {PMsg, NMsg} of - {_, #{message := NFmessage}} -> - S1#{message => NFmessage}; - {#{message := PFmessage}, _} -> - S1#{message => PFmessage}; - _ -> S1 - end. - -merge_msg_Dependency(#{} = PMsg, - #{package := NFpackage, requirement := NFrequirement} = - NMsg, - _) -> - S1 = #{package => NFpackage, - requirement => NFrequirement}, - S2 = case {PMsg, NMsg} of - {_, #{optional := NFoptional}} -> - S1#{optional => NFoptional}; - {#{optional := PFoptional}, _} -> - S1#{optional => PFoptional}; - _ -> S1 - end, - S3 = case {PMsg, NMsg} of - {_, #{app := NFapp}} -> S2#{app => NFapp}; - {#{app := PFapp}, _} -> S2#{app => PFapp}; - _ -> S2 - end, - case {PMsg, NMsg} of - {_, #{repository := NFrepository}} -> - S3#{repository => NFrepository}; - {#{repository := PFrepository}, _} -> - S3#{repository => PFrepository}; - _ -> S3 - end. - - -verify_msg(Msg, MsgName) -> - verify_msg(Msg, MsgName, []). - -verify_msg(Msg, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Package' -> - v_msg_Package(Msg, ['Package'], TrUserData); - 'Release' -> - v_msg_Release(Msg, ['Release'], TrUserData); - 'RetirementStatus' -> - v_msg_RetirementStatus(Msg, ['RetirementStatus'], - TrUserData); - 'Dependency' -> - v_msg_Dependency(Msg, ['Dependency'], TrUserData); - _ -> mk_type_error(not_a_known_message, Msg, []) - end. - - -v_msg_Package(#{name := F2, repository := F3} = M, Path, - TrUserData) -> - case M of - #{releases := F1} -> - if is_list(F1) -> - _ = [v_msg_Release(Elem, [releases | Path], TrUserData) - || Elem <- F1], - ok; - true -> - mk_type_error({invalid_list_of, {msg, 'Release'}}, F1, - [releases | Path]) - end; - _ -> ok - end, - v_type_string(F2, [name | Path]), - v_type_string(F3, [repository | Path]), - lists:foreach(fun (releases) -> ok; - (name) -> ok; - (repository) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Package(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, - [name, repository] -- maps:keys(M), 'Package'}, - M, Path); -v_msg_Package(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Package'}, X, Path). - -v_msg_Release(#{version := F1, inner_checksum := F2} = - M, - Path, TrUserData) -> - v_type_string(F1, [version | Path]), - v_type_bytes(F2, [inner_checksum | Path]), - case M of - #{dependencies := F3} -> - if is_list(F3) -> - _ = [v_msg_Dependency(Elem, [dependencies | Path], - TrUserData) - || Elem <- F3], - ok; - true -> - mk_type_error({invalid_list_of, {msg, 'Dependency'}}, - F3, [dependencies | Path]) - end; - _ -> ok - end, - case M of - #{retired := F4} -> - v_msg_RetirementStatus(F4, [retired | Path], - TrUserData); - _ -> ok - end, - case M of - #{outer_checksum := F5} -> - v_type_bytes(F5, [outer_checksum | Path]); - _ -> ok - end, - lists:foreach(fun (version) -> ok; - (inner_checksum) -> ok; - (dependencies) -> ok; - (retired) -> ok; - (outer_checksum) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Release(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, - [version, inner_checksum] -- maps:keys(M), 'Release'}, - M, Path); -v_msg_Release(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Release'}, X, Path). - -v_msg_RetirementStatus(#{reason := F1} = M, Path, _) -> - v_enum_RetirementReason(F1, [reason | Path]), - case M of - #{message := F2} -> v_type_string(F2, [message | Path]); - _ -> ok - end, - lists:foreach(fun (reason) -> ok; - (message) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_RetirementStatus(M, Path, _TrUserData) - when is_map(M) -> - mk_type_error({missing_fields, [reason] -- maps:keys(M), - 'RetirementStatus'}, - M, Path); -v_msg_RetirementStatus(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'RetirementStatus'}, X, - Path). - -v_msg_Dependency(#{package := F1, requirement := F2} = - M, - Path, _) -> - v_type_string(F1, [package | Path]), - v_type_string(F2, [requirement | Path]), - case M of - #{optional := F3} -> v_type_bool(F3, [optional | Path]); - _ -> ok - end, - case M of - #{app := F4} -> v_type_string(F4, [app | Path]); - _ -> ok - end, - case M of - #{repository := F5} -> - v_type_string(F5, [repository | Path]); - _ -> ok - end, - lists:foreach(fun (package) -> ok; - (requirement) -> ok; - (optional) -> ok; - (app) -> ok; - (repository) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Dependency(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, - [package, requirement] -- maps:keys(M), 'Dependency'}, - M, Path); -v_msg_Dependency(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Dependency'}, X, Path). - -v_enum_RetirementReason('RETIRED_OTHER', _Path) -> ok; -v_enum_RetirementReason('RETIRED_INVALID', _Path) -> ok; -v_enum_RetirementReason('RETIRED_SECURITY', _Path) -> - ok; -v_enum_RetirementReason('RETIRED_DEPRECATED', _Path) -> - ok; -v_enum_RetirementReason('RETIRED_RENAMED', _Path) -> ok; -v_enum_RetirementReason(V, Path) when is_integer(V) -> - v_type_sint32(V, Path); -v_enum_RetirementReason(X, Path) -> - mk_type_error({invalid_enum, 'RetirementReason'}, X, - Path). - -v_type_sint32(N, _Path) - when -2147483648 =< N, N =< 2147483647 -> - ok; -v_type_sint32(N, Path) when is_integer(N) -> - mk_type_error({value_out_of_range, sint32, signed, 32}, - N, Path); -v_type_sint32(X, Path) -> - mk_type_error({bad_integer, sint32, signed, 32}, X, - Path). - -v_type_bool(false, _Path) -> ok; -v_type_bool(true, _Path) -> ok; -v_type_bool(0, _Path) -> ok; -v_type_bool(1, _Path) -> ok; -v_type_bool(X, Path) -> - mk_type_error(bad_boolean_value, X, Path). - -v_type_string(S, Path) when is_list(S); is_binary(S) -> - try unicode:characters_to_binary(S) of - B when is_binary(B) -> ok; - {error, _, _} -> - mk_type_error(bad_unicode_string, S, Path) - catch - error:badarg -> - mk_type_error(bad_unicode_string, S, Path) - end; -v_type_string(X, Path) -> - mk_type_error(bad_unicode_string, X, Path). - -v_type_bytes(B, _Path) when is_binary(B) -> ok; -v_type_bytes(B, _Path) when is_list(B) -> ok; -v_type_bytes(X, Path) -> - mk_type_error(bad_binary_value, X, Path). - --spec mk_type_error(_, _, list()) -> no_return(). -mk_type_error(Error, ValueSeen, Path) -> - Path2 = prettify_path(Path), - erlang:error({gpb_type_error, - {Error, [{value, ValueSeen}, {path, Path2}]}}). - - -prettify_path([]) -> top_level; -prettify_path(PathR) -> - list_to_atom(string:join(lists:map(fun atom_to_list/1, - lists:reverse(PathR)), - ".")). - - --compile({inline,id/2}). -id(X, _TrUserData) -> X. - --compile({inline,cons/3}). -cons(Elem, Acc, _TrUserData) -> [Elem | Acc]. - --compile({inline,lists_reverse/2}). -'lists_reverse'(L, _TrUserData) -> lists:reverse(L). --compile({inline,'erlang_++'/3}). -'erlang_++'(A, B, _TrUserData) -> A ++ B. - -get_msg_defs() -> - [{{enum, 'RetirementReason'}, - [{'RETIRED_OTHER', 0}, {'RETIRED_INVALID', 1}, - {'RETIRED_SECURITY', 2}, {'RETIRED_DEPRECATED', 3}, - {'RETIRED_RENAMED', 4}]}, - {{msg, 'Package'}, - [#{name => releases, fnum => 1, rnum => 2, - type => {msg, 'Release'}, occurrence => repeated, - opts => []}, - #{name => name, fnum => 2, rnum => 3, type => string, - occurrence => required, opts => []}, - #{name => repository, fnum => 3, rnum => 4, - type => string, occurrence => required, opts => []}]}, - {{msg, 'Release'}, - [#{name => version, fnum => 1, rnum => 2, - type => string, occurrence => required, opts => []}, - #{name => inner_checksum, fnum => 2, rnum => 3, - type => bytes, occurrence => required, opts => []}, - #{name => dependencies, fnum => 3, rnum => 4, - type => {msg, 'Dependency'}, occurrence => repeated, - opts => []}, - #{name => retired, fnum => 4, rnum => 5, - type => {msg, 'RetirementStatus'}, - occurrence => optional, opts => []}, - #{name => outer_checksum, fnum => 5, rnum => 6, - type => bytes, occurrence => optional, opts => []}]}, - {{msg, 'RetirementStatus'}, - [#{name => reason, fnum => 1, rnum => 2, - type => {enum, 'RetirementReason'}, - occurrence => required, opts => []}, - #{name => message, fnum => 2, rnum => 3, type => string, - occurrence => optional, opts => []}]}, - {{msg, 'Dependency'}, - [#{name => package, fnum => 1, rnum => 2, - type => string, occurrence => required, opts => []}, - #{name => requirement, fnum => 2, rnum => 3, - type => string, occurrence => required, opts => []}, - #{name => optional, fnum => 3, rnum => 4, type => bool, - occurrence => optional, opts => []}, - #{name => app, fnum => 4, rnum => 5, type => string, - occurrence => optional, opts => []}, - #{name => repository, fnum => 5, rnum => 6, - type => string, occurrence => optional, opts => []}]}]. - - -get_msg_names() -> - ['Package', 'Release', 'RetirementStatus', - 'Dependency']. - - -get_group_names() -> []. - - -get_msg_or_group_names() -> - ['Package', 'Release', 'RetirementStatus', - 'Dependency']. - - -get_enum_names() -> ['RetirementReason']. - - -fetch_msg_def(MsgName) -> - case find_msg_def(MsgName) of - Fs when is_list(Fs) -> Fs; - error -> erlang:error({no_such_msg, MsgName}) - end. - - -fetch_enum_def(EnumName) -> - case find_enum_def(EnumName) of - Es when is_list(Es) -> Es; - error -> erlang:error({no_such_enum, EnumName}) - end. - - -find_msg_def('Package') -> - [#{name => releases, fnum => 1, rnum => 2, - type => {msg, 'Release'}, occurrence => repeated, - opts => []}, - #{name => name, fnum => 2, rnum => 3, type => string, - occurrence => required, opts => []}, - #{name => repository, fnum => 3, rnum => 4, - type => string, occurrence => required, opts => []}]; -find_msg_def('Release') -> - [#{name => version, fnum => 1, rnum => 2, - type => string, occurrence => required, opts => []}, - #{name => inner_checksum, fnum => 2, rnum => 3, - type => bytes, occurrence => required, opts => []}, - #{name => dependencies, fnum => 3, rnum => 4, - type => {msg, 'Dependency'}, occurrence => repeated, - opts => []}, - #{name => retired, fnum => 4, rnum => 5, - type => {msg, 'RetirementStatus'}, - occurrence => optional, opts => []}, - #{name => outer_checksum, fnum => 5, rnum => 6, - type => bytes, occurrence => optional, opts => []}]; -find_msg_def('RetirementStatus') -> - [#{name => reason, fnum => 1, rnum => 2, - type => {enum, 'RetirementReason'}, - occurrence => required, opts => []}, - #{name => message, fnum => 2, rnum => 3, type => string, - occurrence => optional, opts => []}]; -find_msg_def('Dependency') -> - [#{name => package, fnum => 1, rnum => 2, - type => string, occurrence => required, opts => []}, - #{name => requirement, fnum => 2, rnum => 3, - type => string, occurrence => required, opts => []}, - #{name => optional, fnum => 3, rnum => 4, type => bool, - occurrence => optional, opts => []}, - #{name => app, fnum => 4, rnum => 5, type => string, - occurrence => optional, opts => []}, - #{name => repository, fnum => 5, rnum => 6, - type => string, occurrence => optional, opts => []}]; -find_msg_def(_) -> error. - - -find_enum_def('RetirementReason') -> - [{'RETIRED_OTHER', 0}, {'RETIRED_INVALID', 1}, - {'RETIRED_SECURITY', 2}, {'RETIRED_DEPRECATED', 3}, - {'RETIRED_RENAMED', 4}]; -find_enum_def(_) -> error. - - -enum_symbol_by_value('RetirementReason', Value) -> - enum_symbol_by_value_RetirementReason(Value). - - -enum_value_by_symbol('RetirementReason', Sym) -> - enum_value_by_symbol_RetirementReason(Sym). - - -enum_symbol_by_value_RetirementReason(0) -> - 'RETIRED_OTHER'; -enum_symbol_by_value_RetirementReason(1) -> - 'RETIRED_INVALID'; -enum_symbol_by_value_RetirementReason(2) -> - 'RETIRED_SECURITY'; -enum_symbol_by_value_RetirementReason(3) -> - 'RETIRED_DEPRECATED'; -enum_symbol_by_value_RetirementReason(4) -> - 'RETIRED_RENAMED'. - - -enum_value_by_symbol_RetirementReason('RETIRED_OTHER') -> - 0; -enum_value_by_symbol_RetirementReason('RETIRED_INVALID') -> - 1; -enum_value_by_symbol_RetirementReason('RETIRED_SECURITY') -> - 2; -enum_value_by_symbol_RetirementReason('RETIRED_DEPRECATED') -> - 3; -enum_value_by_symbol_RetirementReason('RETIRED_RENAMED') -> - 4. - - -get_service_names() -> []. - - -get_service_def(_) -> error. - - -get_rpc_names(_) -> error. - - -find_rpc_def(_, _) -> error. - - - --spec fetch_rpc_def(_, _) -> no_return(). -fetch_rpc_def(ServiceName, RpcName) -> - erlang:error({no_such_rpc, ServiceName, RpcName}). - - -get_package_name() -> undefined. - - - -gpb_version_as_string() -> - "4.2.1". - -gpb_version_as_list() -> - [4,2,1]. diff --git a/_build/default/plugins/hex_core/src/hex_pb_signed.erl b/_build/default/plugins/hex_core/src/hex_pb_signed.erl deleted file mode 100644 index 035dc85035..0000000000 --- a/_build/default/plugins/hex_core/src/hex_pb_signed.erl +++ /dev/null @@ -1,562 +0,0 @@ -%% -*- coding: utf-8 -*- -%% Automatically generated, do not edit -%% Generated by gpb_compile version 4.3.1 --module(hex_pb_signed). - --export([encode_msg/2, encode_msg/3]). --export([decode_msg/2, decode_msg/3]). --export([merge_msgs/3, merge_msgs/4]). --export([verify_msg/2, verify_msg/3]). --export([get_msg_defs/0]). --export([get_msg_names/0]). --export([get_group_names/0]). --export([get_msg_or_group_names/0]). --export([get_enum_names/0]). --export([find_msg_def/1, fetch_msg_def/1]). --export([find_enum_def/1, fetch_enum_def/1]). --export([enum_symbol_by_value/2, enum_value_by_symbol/2]). --export([get_service_names/0]). --export([get_service_def/1]). --export([get_rpc_names/1]). --export([find_rpc_def/2, fetch_rpc_def/2]). --export([get_package_name/0]). --export([gpb_version_as_string/0, gpb_version_as_list/0]). - - -%% enumerated types - --export_type([]). - -%% message types --type 'Signed'() :: - #{payload => iodata() % = 1 - %% signature => iodata() % = 2 - }. - --export_type(['Signed'/0]). - --spec encode_msg('Signed'(), atom()) -> binary(). -encode_msg(Msg, MsgName) when is_atom(MsgName) -> - encode_msg(Msg, MsgName, []). - --spec encode_msg('Signed'(), atom(), list()) -> binary(). -encode_msg(Msg, MsgName, Opts) -> - verify_msg(Msg, MsgName, Opts), - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Signed' -> - e_msg_Signed(id(Msg, TrUserData), TrUserData) - end. - - -e_msg_Signed(Msg, TrUserData) -> - e_msg_Signed(Msg, <<>>, TrUserData). - - -e_msg_Signed(#{payload := F1} = M, Bin, TrUserData) -> - B1 = begin - TrF1 = id(F1, TrUserData), - e_type_bytes(TrF1, <>, TrUserData) - end, - case M of - #{signature := F2} -> - begin - TrF2 = id(F2, TrUserData), - e_type_bytes(TrF2, <>, TrUserData) - end; - _ -> B1 - end. - --compile({nowarn_unused_function,e_type_sint/3}). -e_type_sint(Value, Bin, _TrUserData) when Value >= 0 -> - e_varint(Value * 2, Bin); -e_type_sint(Value, Bin, _TrUserData) -> - e_varint(Value * -2 - 1, Bin). - --compile({nowarn_unused_function,e_type_int32/3}). -e_type_int32(Value, Bin, _TrUserData) - when 0 =< Value, Value =< 127 -> - <>; -e_type_int32(Value, Bin, _TrUserData) -> - <> = <>, - e_varint(N, Bin). - --compile({nowarn_unused_function,e_type_int64/3}). -e_type_int64(Value, Bin, _TrUserData) - when 0 =< Value, Value =< 127 -> - <>; -e_type_int64(Value, Bin, _TrUserData) -> - <> = <>, - e_varint(N, Bin). - --compile({nowarn_unused_function,e_type_bool/3}). -e_type_bool(true, Bin, _TrUserData) -> - <>; -e_type_bool(false, Bin, _TrUserData) -> - <>; -e_type_bool(1, Bin, _TrUserData) -> <>; -e_type_bool(0, Bin, _TrUserData) -> <>. - --compile({nowarn_unused_function,e_type_string/3}). -e_type_string(S, Bin, _TrUserData) -> - Utf8 = unicode:characters_to_binary(S), - Bin2 = e_varint(byte_size(Utf8), Bin), - <>. - --compile({nowarn_unused_function,e_type_bytes/3}). -e_type_bytes(Bytes, Bin, _TrUserData) - when is_binary(Bytes) -> - Bin2 = e_varint(byte_size(Bytes), Bin), - <>; -e_type_bytes(Bytes, Bin, _TrUserData) - when is_list(Bytes) -> - BytesBin = iolist_to_binary(Bytes), - Bin2 = e_varint(byte_size(BytesBin), Bin), - <>. - --compile({nowarn_unused_function,e_type_fixed32/3}). -e_type_fixed32(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_sfixed32/3}). -e_type_sfixed32(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_fixed64/3}). -e_type_fixed64(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_sfixed64/3}). -e_type_sfixed64(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_float/3}). -e_type_float(V, Bin, _) when is_number(V) -> - <>; -e_type_float(infinity, Bin, _) -> - <>; -e_type_float('-infinity', Bin, _) -> - <>; -e_type_float(nan, Bin, _) -> - <>. - --compile({nowarn_unused_function,e_type_double/3}). -e_type_double(V, Bin, _) when is_number(V) -> - <>; -e_type_double(infinity, Bin, _) -> - <>; -e_type_double('-infinity', Bin, _) -> - <>; -e_type_double(nan, Bin, _) -> - <>. - --compile({nowarn_unused_function,e_varint/3}). -e_varint(N, Bin, _TrUserData) -> e_varint(N, Bin). - --compile({nowarn_unused_function,e_varint/2}). -e_varint(N, Bin) when N =< 127 -> <>; -e_varint(N, Bin) -> - Bin2 = <>, - e_varint(N bsr 7, Bin2). - - -decode_msg(Bin, MsgName) when is_binary(Bin) -> - decode_msg(Bin, MsgName, []). - -decode_msg(Bin, MsgName, Opts) when is_binary(Bin) -> - TrUserData = proplists:get_value(user_data, Opts), - decode_msg_1_catch(Bin, MsgName, TrUserData). - --ifdef('OTP_RELEASE'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. --ifdef('GPB_PATTERN_STACK'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --endif. - --endif. - -decode_msg_2_doit('Signed', Bin, TrUserData) -> - id(d_msg_Signed(Bin, TrUserData), TrUserData). - - - -d_msg_Signed(Bin, TrUserData) -> - dfp_read_field_def_Signed(Bin, 0, 0, - id('$undef', TrUserData), - id('$undef', TrUserData), TrUserData). - -dfp_read_field_def_Signed(<<10, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - d_field_Signed_payload(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -dfp_read_field_def_Signed(<<18, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - d_field_Signed_signature(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -dfp_read_field_def_Signed(<<>>, 0, 0, F@_1, F@_2, _) -> - S1 = #{payload => F@_1}, - if F@_2 == '$undef' -> S1; - true -> S1#{signature => F@_2} - end; -dfp_read_field_def_Signed(Other, Z1, Z2, F@_1, F@_2, - TrUserData) -> - dg_read_field_def_Signed(Other, Z1, Z2, F@_1, F@_2, - TrUserData). - -dg_read_field_def_Signed(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Signed(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -dg_read_field_def_Signed(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Signed_payload(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 18 -> - d_field_Signed_signature(Rest, 0, 0, F@_1, F@_2, - TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Signed(Rest, 0, 0, F@_1, F@_2, TrUserData); - 1 -> skip_64_Signed(Rest, 0, 0, F@_1, F@_2, TrUserData); - 2 -> - skip_length_delimited_Signed(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 3 -> - skip_group_Signed(Rest, Key bsr 3, 0, F@_1, F@_2, - TrUserData); - 5 -> skip_32_Signed(Rest, 0, 0, F@_1, F@_2, TrUserData) - end - end; -dg_read_field_def_Signed(<<>>, 0, 0, F@_1, F@_2, _) -> - S1 = #{payload => F@_1}, - if F@_2 == '$undef' -> S1; - true -> S1#{signature => F@_2} - end. - -d_field_Signed_payload(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_Signed_payload(Rest, N + 7, X bsl N + Acc, F@_1, - F@_2, TrUserData); -d_field_Signed_payload(<<0:1, X:7, Rest/binary>>, N, - Acc, _, F@_2, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Signed(RestF, 0, 0, NewFValue, F@_2, - TrUserData). - -d_field_Signed_signature(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_Signed_signature(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -d_field_Signed_signature(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Signed(RestF, 0, 0, F@_1, NewFValue, - TrUserData). - -skip_varint_Signed(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - skip_varint_Signed(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -skip_varint_Signed(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - dfp_read_field_def_Signed(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -skip_length_delimited_Signed(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - skip_length_delimited_Signed(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -skip_length_delimited_Signed(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Signed(Rest2, 0, 0, F@_1, F@_2, - TrUserData). - -skip_group_Signed(Bin, FNum, Z2, F@_1, F@_2, - TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Signed(Rest, 0, Z2, F@_1, F@_2, - TrUserData). - -skip_32_Signed(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - F@_2, TrUserData) -> - dfp_read_field_def_Signed(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -skip_64_Signed(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - F@_2, TrUserData) -> - dfp_read_field_def_Signed(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -read_group(Bin, FieldNum) -> - {NumBytes, EndTagLen} = read_gr_b(Bin, 0, 0, 0, 0, FieldNum), - <> = Bin, - {Group, Rest}. - -%% Like skipping over fields, but record the total length, -%% Each field is <(FieldNum bsl 3) bor FieldType> ++ -%% Record the length because varints may be non-optimally encoded. -%% -%% Groups can be nested, but assume the same FieldNum cannot be nested -%% because group field numbers are shared with the rest of the fields -%% numbers. Thus we can search just for an group-end with the same -%% field number. -%% -%% (The only time the same group field number could occur would -%% be in a nested sub message, but then it would be inside a -%% length-delimited entry, which we skip-read by length.) -read_gr_b(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, FieldNum) - when N < (32-7) -> - read_gr_b(Tl, N+7, X bsl N + Acc, NumBytes, TagLen+1, FieldNum); -read_gr_b(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, - FieldNum) -> - Key = X bsl N + Acc, - TagLen1 = TagLen + 1, - case {Key bsr 3, Key band 7} of - {FieldNum, 4} -> % 4 = group_end - {NumBytes, TagLen1}; - {_, 0} -> % 0 = varint - read_gr_vi(Tl, 0, NumBytes + TagLen1, FieldNum); - {_, 1} -> % 1 = bits64 - <<_:64, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 8, 0, FieldNum); - {_, 2} -> % 2 = length_delimited - read_gr_ld(Tl, 0, 0, NumBytes + TagLen1, FieldNum); - {_, 3} -> % 3 = group_start - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 4} -> % 4 = group_end - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 5} -> % 5 = bits32 - <<_:32, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 4, 0, FieldNum) - end. - -read_gr_vi(<<1:1, _:7, Tl/binary>>, N, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_vi(Tl, N+7, NumBytes+1, FieldNum); -read_gr_vi(<<0:1, _:7, Tl/binary>>, _, NumBytes, FieldNum) -> - read_gr_b(Tl, 0, 0, NumBytes+1, 0, FieldNum). - -read_gr_ld(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_ld(Tl, N+7, X bsl N + Acc, NumBytes+1, FieldNum); -read_gr_ld(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) -> - Len = X bsl N + Acc, - NumBytes1 = NumBytes + 1, - <<_:Len/binary, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes1 + Len, 0, FieldNum). - -merge_msgs(Prev, New, MsgName) when is_atom(MsgName) -> - merge_msgs(Prev, New, MsgName, []). - -merge_msgs(Prev, New, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Signed' -> merge_msg_Signed(Prev, New, TrUserData) - end. - --compile({nowarn_unused_function,merge_msg_Signed/3}). -merge_msg_Signed(#{} = PMsg, - #{payload := NFpayload} = NMsg, _) -> - S1 = #{payload => NFpayload}, - case {PMsg, NMsg} of - {_, #{signature := NFsignature}} -> - S1#{signature => NFsignature}; - {#{signature := PFsignature}, _} -> - S1#{signature => PFsignature}; - _ -> S1 - end. - - -verify_msg(Msg, MsgName) when is_atom(MsgName) -> - verify_msg(Msg, MsgName, []). - -verify_msg(Msg, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Signed' -> v_msg_Signed(Msg, [MsgName], TrUserData); - _ -> mk_type_error(not_a_known_message, Msg, []) - end. - - --compile({nowarn_unused_function,v_msg_Signed/3}). -v_msg_Signed(#{payload := F1} = M, Path, TrUserData) -> - v_type_bytes(F1, [payload | Path], TrUserData), - case M of - #{signature := F2} -> - v_type_bytes(F2, [signature | Path], TrUserData); - _ -> ok - end, - lists:foreach(fun (payload) -> ok; - (signature) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Signed(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, - [payload] -- maps:keys(M), 'Signed'}, - M, Path); -v_msg_Signed(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Signed'}, X, Path). - --compile({nowarn_unused_function,v_type_bytes/3}). -v_type_bytes(B, _Path, _TrUserData) when is_binary(B) -> - ok; -v_type_bytes(B, _Path, _TrUserData) when is_list(B) -> - ok; -v_type_bytes(X, Path, _TrUserData) -> - mk_type_error(bad_binary_value, X, Path). - --compile({nowarn_unused_function,mk_type_error/3}). --spec mk_type_error(_, _, list()) -> no_return(). -mk_type_error(Error, ValueSeen, Path) -> - Path2 = prettify_path(Path), - erlang:error({gpb_type_error, - {Error, [{value, ValueSeen}, {path, Path2}]}}). - - --compile({nowarn_unused_function,prettify_path/1}). -prettify_path([]) -> top_level; -prettify_path(PathR) -> - list_to_atom(string:join(lists:map(fun atom_to_list/1, - lists:reverse(PathR)), - ".")). - - --compile({nowarn_unused_function,id/2}). --compile({inline,id/2}). -id(X, _TrUserData) -> X. - --compile({nowarn_unused_function,v_ok/3}). --compile({inline,v_ok/3}). -v_ok(_Value, _Path, _TrUserData) -> ok. - --compile({nowarn_unused_function,m_overwrite/3}). --compile({inline,m_overwrite/3}). -m_overwrite(_Prev, New, _TrUserData) -> New. - --compile({nowarn_unused_function,cons/3}). --compile({inline,cons/3}). -cons(Elem, Acc, _TrUserData) -> [Elem | Acc]. - --compile({nowarn_unused_function,lists_reverse/2}). --compile({inline,lists_reverse/2}). -'lists_reverse'(L, _TrUserData) -> lists:reverse(L). --compile({nowarn_unused_function,'erlang_++'/3}). --compile({inline,'erlang_++'/3}). -'erlang_++'(A, B, _TrUserData) -> A ++ B. - -get_msg_defs() -> - [{{msg, 'Signed'}, - [#{name => payload, fnum => 1, rnum => 2, type => bytes, - occurrence => required, opts => []}, - #{name => signature, fnum => 2, rnum => 3, - type => bytes, occurrence => optional, opts => []}]}]. - - -get_msg_names() -> ['Signed']. - - -get_group_names() -> []. - - -get_msg_or_group_names() -> ['Signed']. - - -get_enum_names() -> []. - - -fetch_msg_def(MsgName) -> - case find_msg_def(MsgName) of - Fs when is_list(Fs) -> Fs; - error -> erlang:error({no_such_msg, MsgName}) - end. - - --spec fetch_enum_def(_) -> no_return(). -fetch_enum_def(EnumName) -> - erlang:error({no_such_enum, EnumName}). - - -find_msg_def('Signed') -> - [#{name => payload, fnum => 1, rnum => 2, type => bytes, - occurrence => required, opts => []}, - #{name => signature, fnum => 2, rnum => 3, - type => bytes, occurrence => optional, opts => []}]; -find_msg_def(_) -> error. - - -find_enum_def(_) -> error. - - --spec enum_symbol_by_value(_, _) -> no_return(). -enum_symbol_by_value(E, V) -> - erlang:error({no_enum_defs, E, V}). - - --spec enum_value_by_symbol(_, _) -> no_return(). -enum_value_by_symbol(E, V) -> - erlang:error({no_enum_defs, E, V}). - - - -get_service_names() -> []. - - -get_service_def(_) -> error. - - -get_rpc_names(_) -> error. - - -find_rpc_def(_, _) -> error. - - - --spec fetch_rpc_def(_, _) -> no_return(). -fetch_rpc_def(ServiceName, RpcName) -> - erlang:error({no_such_rpc, ServiceName, RpcName}). - - -get_package_name() -> undefined. - - - -gpb_version_as_string() -> - "4.3.1". - -gpb_version_as_list() -> - [4,3,1]. diff --git a/_build/default/plugins/hex_core/src/hex_pb_versions.erl b/_build/default/plugins/hex_core/src/hex_pb_versions.erl deleted file mode 100644 index 8e611e6eb5..0000000000 --- a/_build/default/plugins/hex_core/src/hex_pb_versions.erl +++ /dev/null @@ -1,956 +0,0 @@ -%% -*- coding: utf-8 -*- -%% Automatically generated, do not edit -%% Generated by gpb_compile version 4.3.1 --module(hex_pb_versions). - --export([encode_msg/2, encode_msg/3]). --export([decode_msg/2, decode_msg/3]). --export([merge_msgs/3, merge_msgs/4]). --export([verify_msg/2, verify_msg/3]). --export([get_msg_defs/0]). --export([get_msg_names/0]). --export([get_group_names/0]). --export([get_msg_or_group_names/0]). --export([get_enum_names/0]). --export([find_msg_def/1, fetch_msg_def/1]). --export([find_enum_def/1, fetch_enum_def/1]). --export([enum_symbol_by_value/2, enum_value_by_symbol/2]). --export([get_service_names/0]). --export([get_service_def/1]). --export([get_rpc_names/1]). --export([find_rpc_def/2, fetch_rpc_def/2]). --export([get_package_name/0]). --export([gpb_version_as_string/0, gpb_version_as_list/0]). - - -%% enumerated types - --export_type([]). - -%% message types --type 'Versions'() :: - #{packages => ['Package'()], % = 1 - repository => iodata() % = 2 - }. - --type 'Package'() :: - #{name => iodata(), % = 1 - versions => [iodata()], % = 2 - retired => [integer()] % = 3, 32 bits - }. - --export_type(['Versions'/0, 'Package'/0]). - --spec encode_msg('Versions'() | 'Package'(), atom()) -> binary(). -encode_msg(Msg, MsgName) when is_atom(MsgName) -> - encode_msg(Msg, MsgName, []). - --spec encode_msg('Versions'() | 'Package'(), atom(), list()) -> binary(). -encode_msg(Msg, MsgName, Opts) -> - verify_msg(Msg, MsgName, Opts), - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Versions' -> - e_msg_Versions(id(Msg, TrUserData), TrUserData); - 'Package' -> - e_msg_Package(id(Msg, TrUserData), TrUserData) - end. - - -e_msg_Versions(Msg, TrUserData) -> - e_msg_Versions(Msg, <<>>, TrUserData). - - -e_msg_Versions(#{repository := F2} = M, Bin, - TrUserData) -> - B1 = case M of - #{packages := F1} -> - TrF1 = id(F1, TrUserData), - if TrF1 == [] -> Bin; - true -> e_field_Versions_packages(TrF1, Bin, TrUserData) - end; - _ -> Bin - end, - begin - TrF2 = id(F2, TrUserData), - e_type_string(TrF2, <>, TrUserData) - end. - -e_msg_Package(Msg, TrUserData) -> - e_msg_Package(Msg, <<>>, TrUserData). - - -e_msg_Package(#{name := F1} = M, Bin, TrUserData) -> - B1 = begin - TrF1 = id(F1, TrUserData), - e_type_string(TrF1, <>, TrUserData) - end, - B2 = case M of - #{versions := F2} -> - TrF2 = id(F2, TrUserData), - if TrF2 == [] -> B1; - true -> e_field_Package_versions(TrF2, B1, TrUserData) - end; - _ -> B1 - end, - case M of - #{retired := F3} -> - TrF3 = id(F3, TrUserData), - if TrF3 == [] -> B2; - true -> e_field_Package_retired(TrF3, B2, TrUserData) - end; - _ -> B2 - end. - -e_mfield_Versions_packages(Msg, Bin, TrUserData) -> - SubBin = e_msg_Package(Msg, <<>>, TrUserData), - Bin2 = e_varint(byte_size(SubBin), Bin), - <>. - -e_field_Versions_packages([Elem | Rest], Bin, - TrUserData) -> - Bin2 = <>, - Bin3 = e_mfield_Versions_packages(id(Elem, TrUserData), - Bin2, TrUserData), - e_field_Versions_packages(Rest, Bin3, TrUserData); -e_field_Versions_packages([], Bin, _TrUserData) -> Bin. - -e_field_Package_versions([Elem | Rest], Bin, - TrUserData) -> - Bin2 = <>, - Bin3 = e_type_string(id(Elem, TrUserData), Bin2, - TrUserData), - e_field_Package_versions(Rest, Bin3, TrUserData); -e_field_Package_versions([], Bin, _TrUserData) -> Bin. - -e_field_Package_retired(Elems, Bin, TrUserData) - when Elems =/= [] -> - SubBin = e_pfield_Package_retired(Elems, <<>>, - TrUserData), - Bin2 = <>, - Bin3 = e_varint(byte_size(SubBin), Bin2), - <>; -e_field_Package_retired([], Bin, _TrUserData) -> Bin. - -e_pfield_Package_retired([Value | Rest], Bin, - TrUserData) -> - Bin2 = e_type_int32(id(Value, TrUserData), Bin, - TrUserData), - e_pfield_Package_retired(Rest, Bin2, TrUserData); -e_pfield_Package_retired([], Bin, _TrUserData) -> Bin. - --compile({nowarn_unused_function,e_type_sint/3}). -e_type_sint(Value, Bin, _TrUserData) when Value >= 0 -> - e_varint(Value * 2, Bin); -e_type_sint(Value, Bin, _TrUserData) -> - e_varint(Value * -2 - 1, Bin). - --compile({nowarn_unused_function,e_type_int32/3}). -e_type_int32(Value, Bin, _TrUserData) - when 0 =< Value, Value =< 127 -> - <>; -e_type_int32(Value, Bin, _TrUserData) -> - <> = <>, - e_varint(N, Bin). - --compile({nowarn_unused_function,e_type_int64/3}). -e_type_int64(Value, Bin, _TrUserData) - when 0 =< Value, Value =< 127 -> - <>; -e_type_int64(Value, Bin, _TrUserData) -> - <> = <>, - e_varint(N, Bin). - --compile({nowarn_unused_function,e_type_bool/3}). -e_type_bool(true, Bin, _TrUserData) -> - <>; -e_type_bool(false, Bin, _TrUserData) -> - <>; -e_type_bool(1, Bin, _TrUserData) -> <>; -e_type_bool(0, Bin, _TrUserData) -> <>. - --compile({nowarn_unused_function,e_type_string/3}). -e_type_string(S, Bin, _TrUserData) -> - Utf8 = unicode:characters_to_binary(S), - Bin2 = e_varint(byte_size(Utf8), Bin), - <>. - --compile({nowarn_unused_function,e_type_bytes/3}). -e_type_bytes(Bytes, Bin, _TrUserData) - when is_binary(Bytes) -> - Bin2 = e_varint(byte_size(Bytes), Bin), - <>; -e_type_bytes(Bytes, Bin, _TrUserData) - when is_list(Bytes) -> - BytesBin = iolist_to_binary(Bytes), - Bin2 = e_varint(byte_size(BytesBin), Bin), - <>. - --compile({nowarn_unused_function,e_type_fixed32/3}). -e_type_fixed32(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_sfixed32/3}). -e_type_sfixed32(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_fixed64/3}). -e_type_fixed64(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_sfixed64/3}). -e_type_sfixed64(Value, Bin, _TrUserData) -> - <>. - --compile({nowarn_unused_function,e_type_float/3}). -e_type_float(V, Bin, _) when is_number(V) -> - <>; -e_type_float(infinity, Bin, _) -> - <>; -e_type_float('-infinity', Bin, _) -> - <>; -e_type_float(nan, Bin, _) -> - <>. - --compile({nowarn_unused_function,e_type_double/3}). -e_type_double(V, Bin, _) when is_number(V) -> - <>; -e_type_double(infinity, Bin, _) -> - <>; -e_type_double('-infinity', Bin, _) -> - <>; -e_type_double(nan, Bin, _) -> - <>. - --compile({nowarn_unused_function,e_varint/3}). -e_varint(N, Bin, _TrUserData) -> e_varint(N, Bin). - --compile({nowarn_unused_function,e_varint/2}). -e_varint(N, Bin) when N =< 127 -> <>; -e_varint(N, Bin) -> - Bin2 = <>, - e_varint(N bsr 7, Bin2). - - -decode_msg(Bin, MsgName) when is_binary(Bin) -> - decode_msg(Bin, MsgName, []). - -decode_msg(Bin, MsgName, Opts) when is_binary(Bin) -> - TrUserData = proplists:get_value(user_data, Opts), - decode_msg_1_catch(Bin, MsgName, TrUserData). - --ifdef('OTP_RELEASE'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. --ifdef('GPB_PATTERN_STACK'). -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --else. -decode_msg_1_catch(Bin, MsgName, TrUserData) -> - try decode_msg_2_doit(MsgName, Bin, TrUserData) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) - end. --endif. - --endif. - -decode_msg_2_doit('Versions', Bin, TrUserData) -> - id(d_msg_Versions(Bin, TrUserData), TrUserData); -decode_msg_2_doit('Package', Bin, TrUserData) -> - id(d_msg_Package(Bin, TrUserData), TrUserData). - - - -d_msg_Versions(Bin, TrUserData) -> - dfp_read_field_def_Versions(Bin, 0, 0, - id([], TrUserData), id('$undef', TrUserData), - TrUserData). - -dfp_read_field_def_Versions(<<10, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - d_field_Versions_packages(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -dfp_read_field_def_Versions(<<18, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - d_field_Versions_repository(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -dfp_read_field_def_Versions(<<>>, 0, 0, R1, F@_2, - TrUserData) -> - S1 = #{repository => F@_2}, - if R1 == '$undef' -> S1; - true -> S1#{packages => lists_reverse(R1, TrUserData)} - end; -dfp_read_field_def_Versions(Other, Z1, Z2, F@_1, F@_2, - TrUserData) -> - dg_read_field_def_Versions(Other, Z1, Z2, F@_1, F@_2, - TrUserData). - -dg_read_field_def_Versions(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Versions(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -dg_read_field_def_Versions(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Versions_packages(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 18 -> - d_field_Versions_repository(Rest, 0, 0, F@_1, F@_2, - TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Versions(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 1 -> - skip_64_Versions(Rest, 0, 0, F@_1, F@_2, TrUserData); - 2 -> - skip_length_delimited_Versions(Rest, 0, 0, F@_1, F@_2, - TrUserData); - 3 -> - skip_group_Versions(Rest, Key bsr 3, 0, F@_1, F@_2, - TrUserData); - 5 -> - skip_32_Versions(Rest, 0, 0, F@_1, F@_2, TrUserData) - end - end; -dg_read_field_def_Versions(<<>>, 0, 0, R1, F@_2, - TrUserData) -> - S1 = #{repository => F@_2}, - if R1 == '$undef' -> S1; - true -> S1#{packages => lists_reverse(R1, TrUserData)} - end. - -d_field_Versions_packages(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_Versions_packages(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -d_field_Versions_packages(<<0:1, X:7, Rest/binary>>, N, - Acc, Prev, F@_2, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(d_msg_Package(Bs, TrUserData), TrUserData), - Rest2} - end, - dfp_read_field_def_Versions(RestF, 0, 0, - cons(NewFValue, Prev, TrUserData), F@_2, - TrUserData). - -d_field_Versions_repository(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - d_field_Versions_repository(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, TrUserData); -d_field_Versions_repository(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, _, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Versions(RestF, 0, 0, F@_1, - NewFValue, TrUserData). - -skip_varint_Versions(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - skip_varint_Versions(Rest, Z1, Z2, F@_1, F@_2, - TrUserData); -skip_varint_Versions(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, TrUserData) -> - dfp_read_field_def_Versions(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -skip_length_delimited_Versions(<<1:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) - when N < 57 -> - skip_length_delimited_Versions(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, TrUserData); -skip_length_delimited_Versions(<<0:1, X:7, - Rest/binary>>, - N, Acc, F@_1, F@_2, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Versions(Rest2, 0, 0, F@_1, F@_2, - TrUserData). - -skip_group_Versions(Bin, FNum, Z2, F@_1, F@_2, - TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Versions(Rest, 0, Z2, F@_1, F@_2, - TrUserData). - -skip_32_Versions(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - F@_2, TrUserData) -> - dfp_read_field_def_Versions(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -skip_64_Versions(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - F@_2, TrUserData) -> - dfp_read_field_def_Versions(Rest, Z1, Z2, F@_1, F@_2, - TrUserData). - -d_msg_Package(Bin, TrUserData) -> - dfp_read_field_def_Package(Bin, 0, 0, - id('$undef', TrUserData), id([], TrUserData), - id([], TrUserData), TrUserData). - -dfp_read_field_def_Package(<<10, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_field_Package_name(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -dfp_read_field_def_Package(<<18, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_field_Package_versions(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -dfp_read_field_def_Package(<<26, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_pfield_Package_retired(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -dfp_read_field_def_Package(<<24, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - d_field_Package_retired(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -dfp_read_field_def_Package(<<>>, 0, 0, F@_1, R1, R2, - TrUserData) -> - #{name => F@_1, - versions => lists_reverse(R1, TrUserData), - retired => lists_reverse(R2, TrUserData)}; -dfp_read_field_def_Package(Other, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData) -> - dg_read_field_def_Package(Other, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -dg_read_field_def_Package(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 32 - 7 -> - dg_read_field_def_Package(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -dg_read_field_def_Package(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) -> - Key = X bsl N + Acc, - case Key of - 10 -> - d_field_Package_name(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 18 -> - d_field_Package_versions(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 26 -> - d_pfield_Package_retired(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 24 -> - d_field_Package_retired(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - _ -> - case Key band 7 of - 0 -> - skip_varint_Package(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 1 -> - skip_64_Package(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData); - 2 -> - skip_length_delimited_Package(Rest, 0, 0, F@_1, F@_2, - F@_3, TrUserData); - 3 -> - skip_group_Package(Rest, Key bsr 3, 0, F@_1, F@_2, F@_3, - TrUserData); - 5 -> - skip_32_Package(Rest, 0, 0, F@_1, F@_2, F@_3, - TrUserData) - end - end; -dg_read_field_def_Package(<<>>, 0, 0, F@_1, R1, R2, - TrUserData) -> - #{name => F@_1, - versions => lists_reverse(R1, TrUserData), - retired => lists_reverse(R2, TrUserData)}. - -d_field_Package_name(<<1:1, X:7, Rest/binary>>, N, Acc, - F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_field_Package_name(Rest, N + 7, X bsl N + Acc, F@_1, - F@_2, F@_3, TrUserData); -d_field_Package_name(<<0:1, X:7, Rest/binary>>, N, Acc, - _, F@_2, F@_3, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Package(RestF, 0, 0, NewFValue, F@_2, - F@_3, TrUserData). - -d_field_Package_versions(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_field_Package_versions(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -d_field_Package_versions(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, Prev, F@_3, TrUserData) -> - {NewFValue, RestF} = begin - Len = X bsl N + Acc, - <> = Rest, - {id(binary:copy(Bytes), TrUserData), Rest2} - end, - dfp_read_field_def_Package(RestF, 0, 0, F@_1, - cons(NewFValue, Prev, TrUserData), F@_3, - TrUserData). - -d_field_Package_retired(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_field_Package_retired(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -d_field_Package_retired(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, Prev, TrUserData) -> - {NewFValue, RestF} = {begin - <> = <<(X bsl N + - Acc):32/unsigned-native>>, - id(Res, TrUserData) - end, - Rest}, - dfp_read_field_def_Package(RestF, 0, 0, F@_1, F@_2, - cons(NewFValue, Prev, TrUserData), TrUserData). - -d_pfield_Package_retired(<<1:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - d_pfield_Package_retired(Rest, N + 7, X bsl N + Acc, - F@_1, F@_2, F@_3, TrUserData); -d_pfield_Package_retired(<<0:1, X:7, Rest/binary>>, N, - Acc, F@_1, F@_2, E, TrUserData) -> - Len = X bsl N + Acc, - <> = Rest, - NewSeq = d_packed_field_Package_retired(PackedBytes, 0, - 0, E, TrUserData), - dfp_read_field_def_Package(Rest2, 0, 0, F@_1, F@_2, - NewSeq, TrUserData). - -d_packed_field_Package_retired(<<1:1, X:7, - Rest/binary>>, - N, Acc, AccSeq, TrUserData) - when N < 57 -> - d_packed_field_Package_retired(Rest, N + 7, - X bsl N + Acc, AccSeq, TrUserData); -d_packed_field_Package_retired(<<0:1, X:7, - Rest/binary>>, - N, Acc, AccSeq, TrUserData) -> - {NewFValue, RestF} = {begin - <> = <<(X bsl N + - Acc):32/unsigned-native>>, - id(Res, TrUserData) - end, - Rest}, - d_packed_field_Package_retired(RestF, 0, 0, - [NewFValue | AccSeq], TrUserData); -d_packed_field_Package_retired(<<>>, 0, 0, AccSeq, _) -> - AccSeq. - -skip_varint_Package(<<1:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - skip_varint_Package(Rest, Z1, Z2, F@_1, F@_2, F@_3, - TrUserData); -skip_varint_Package(<<0:1, _:7, Rest/binary>>, Z1, Z2, - F@_1, F@_2, F@_3, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -skip_length_delimited_Package(<<1:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, TrUserData) - when N < 57 -> - skip_length_delimited_Package(Rest, N + 7, - X bsl N + Acc, F@_1, F@_2, F@_3, TrUserData); -skip_length_delimited_Package(<<0:1, X:7, Rest/binary>>, - N, Acc, F@_1, F@_2, F@_3, TrUserData) -> - Length = X bsl N + Acc, - <<_:Length/binary, Rest2/binary>> = Rest, - dfp_read_field_def_Package(Rest2, 0, 0, F@_1, F@_2, - F@_3, TrUserData). - -skip_group_Package(Bin, FNum, Z2, F@_1, F@_2, F@_3, - TrUserData) -> - {_, Rest} = read_group(Bin, FNum), - dfp_read_field_def_Package(Rest, 0, Z2, F@_1, F@_2, - F@_3, TrUserData). - -skip_32_Package(<<_:32, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -skip_64_Package(<<_:64, Rest/binary>>, Z1, Z2, F@_1, - F@_2, F@_3, TrUserData) -> - dfp_read_field_def_Package(Rest, Z1, Z2, F@_1, F@_2, - F@_3, TrUserData). - -read_group(Bin, FieldNum) -> - {NumBytes, EndTagLen} = read_gr_b(Bin, 0, 0, 0, 0, FieldNum), - <> = Bin, - {Group, Rest}. - -%% Like skipping over fields, but record the total length, -%% Each field is <(FieldNum bsl 3) bor FieldType> ++ -%% Record the length because varints may be non-optimally encoded. -%% -%% Groups can be nested, but assume the same FieldNum cannot be nested -%% because group field numbers are shared with the rest of the fields -%% numbers. Thus we can search just for an group-end with the same -%% field number. -%% -%% (The only time the same group field number could occur would -%% be in a nested sub message, but then it would be inside a -%% length-delimited entry, which we skip-read by length.) -read_gr_b(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, FieldNum) - when N < (32-7) -> - read_gr_b(Tl, N+7, X bsl N + Acc, NumBytes, TagLen+1, FieldNum); -read_gr_b(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, - FieldNum) -> - Key = X bsl N + Acc, - TagLen1 = TagLen + 1, - case {Key bsr 3, Key band 7} of - {FieldNum, 4} -> % 4 = group_end - {NumBytes, TagLen1}; - {_, 0} -> % 0 = varint - read_gr_vi(Tl, 0, NumBytes + TagLen1, FieldNum); - {_, 1} -> % 1 = bits64 - <<_:64, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 8, 0, FieldNum); - {_, 2} -> % 2 = length_delimited - read_gr_ld(Tl, 0, 0, NumBytes + TagLen1, FieldNum); - {_, 3} -> % 3 = group_start - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 4} -> % 4 = group_end - read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); - {_, 5} -> % 5 = bits32 - <<_:32, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 4, 0, FieldNum) - end. - -read_gr_vi(<<1:1, _:7, Tl/binary>>, N, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_vi(Tl, N+7, NumBytes+1, FieldNum); -read_gr_vi(<<0:1, _:7, Tl/binary>>, _, NumBytes, FieldNum) -> - read_gr_b(Tl, 0, 0, NumBytes+1, 0, FieldNum). - -read_gr_ld(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) - when N < (64-7) -> - read_gr_ld(Tl, N+7, X bsl N + Acc, NumBytes+1, FieldNum); -read_gr_ld(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) -> - Len = X bsl N + Acc, - NumBytes1 = NumBytes + 1, - <<_:Len/binary, Tl2/binary>> = Tl, - read_gr_b(Tl2, 0, 0, NumBytes1 + Len, 0, FieldNum). - -merge_msgs(Prev, New, MsgName) when is_atom(MsgName) -> - merge_msgs(Prev, New, MsgName, []). - -merge_msgs(Prev, New, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Versions' -> merge_msg_Versions(Prev, New, TrUserData); - 'Package' -> merge_msg_Package(Prev, New, TrUserData) - end. - --compile({nowarn_unused_function,merge_msg_Versions/3}). -merge_msg_Versions(#{} = PMsg, - #{repository := NFrepository} = NMsg, TrUserData) -> - S1 = #{repository => NFrepository}, - case {PMsg, NMsg} of - {#{packages := PFpackages}, - #{packages := NFpackages}} -> - S1#{packages => - 'erlang_++'(PFpackages, NFpackages, TrUserData)}; - {_, #{packages := NFpackages}} -> - S1#{packages => NFpackages}; - {#{packages := PFpackages}, _} -> - S1#{packages => PFpackages}; - {_, _} -> S1 - end. - --compile({nowarn_unused_function,merge_msg_Package/3}). -merge_msg_Package(#{} = PMsg, #{name := NFname} = NMsg, - TrUserData) -> - S1 = #{name => NFname}, - S2 = case {PMsg, NMsg} of - {#{versions := PFversions}, - #{versions := NFversions}} -> - S1#{versions => - 'erlang_++'(PFversions, NFversions, TrUserData)}; - {_, #{versions := NFversions}} -> - S1#{versions => NFversions}; - {#{versions := PFversions}, _} -> - S1#{versions => PFversions}; - {_, _} -> S1 - end, - case {PMsg, NMsg} of - {#{retired := PFretired}, #{retired := NFretired}} -> - S2#{retired => - 'erlang_++'(PFretired, NFretired, TrUserData)}; - {_, #{retired := NFretired}} -> - S2#{retired => NFretired}; - {#{retired := PFretired}, _} -> - S2#{retired => PFretired}; - {_, _} -> S2 - end. - - -verify_msg(Msg, MsgName) when is_atom(MsgName) -> - verify_msg(Msg, MsgName, []). - -verify_msg(Msg, MsgName, Opts) -> - TrUserData = proplists:get_value(user_data, Opts), - case MsgName of - 'Versions' -> - v_msg_Versions(Msg, [MsgName], TrUserData); - 'Package' -> v_msg_Package(Msg, [MsgName], TrUserData); - _ -> mk_type_error(not_a_known_message, Msg, []) - end. - - --compile({nowarn_unused_function,v_msg_Versions/3}). -v_msg_Versions(#{repository := F2} = M, Path, - TrUserData) -> - case M of - #{packages := F1} -> - if is_list(F1) -> - _ = [v_msg_Package(Elem, [packages | Path], TrUserData) - || Elem <- F1], - ok; - true -> - mk_type_error({invalid_list_of, {msg, 'Package'}}, F1, - [packages | Path]) - end; - _ -> ok - end, - v_type_string(F2, [repository | Path], TrUserData), - lists:foreach(fun (packages) -> ok; - (repository) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Versions(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, - [repository] -- maps:keys(M), 'Versions'}, - M, Path); -v_msg_Versions(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Versions'}, X, Path). - --compile({nowarn_unused_function,v_msg_Package/3}). -v_msg_Package(#{name := F1} = M, Path, TrUserData) -> - v_type_string(F1, [name | Path], TrUserData), - case M of - #{versions := F2} -> - if is_list(F2) -> - _ = [v_type_string(Elem, [versions | Path], TrUserData) - || Elem <- F2], - ok; - true -> - mk_type_error({invalid_list_of, string}, F2, - [versions | Path]) - end; - _ -> ok - end, - case M of - #{retired := F3} -> - if is_list(F3) -> - _ = [v_type_int32(Elem, [retired | Path], TrUserData) - || Elem <- F3], - ok; - true -> - mk_type_error({invalid_list_of, int32}, F3, - [retired | Path]) - end; - _ -> ok - end, - lists:foreach(fun (name) -> ok; - (versions) -> ok; - (retired) -> ok; - (OtherKey) -> - mk_type_error({extraneous_key, OtherKey}, M, Path) - end, - maps:keys(M)), - ok; -v_msg_Package(M, Path, _TrUserData) when is_map(M) -> - mk_type_error({missing_fields, [name] -- maps:keys(M), - 'Package'}, - M, Path); -v_msg_Package(X, Path, _TrUserData) -> - mk_type_error({expected_msg, 'Package'}, X, Path). - --compile({nowarn_unused_function,v_type_int32/3}). -v_type_int32(N, _Path, _TrUserData) - when -2147483648 =< N, N =< 2147483647 -> - ok; -v_type_int32(N, Path, _TrUserData) when is_integer(N) -> - mk_type_error({value_out_of_range, int32, signed, 32}, - N, Path); -v_type_int32(X, Path, _TrUserData) -> - mk_type_error({bad_integer, int32, signed, 32}, X, - Path). - --compile({nowarn_unused_function,v_type_string/3}). -v_type_string(S, Path, _TrUserData) - when is_list(S); is_binary(S) -> - try unicode:characters_to_binary(S) of - B when is_binary(B) -> ok; - {error, _, _} -> - mk_type_error(bad_unicode_string, S, Path) - catch - error:badarg -> - mk_type_error(bad_unicode_string, S, Path) - end; -v_type_string(X, Path, _TrUserData) -> - mk_type_error(bad_unicode_string, X, Path). - --compile({nowarn_unused_function,mk_type_error/3}). --spec mk_type_error(_, _, list()) -> no_return(). -mk_type_error(Error, ValueSeen, Path) -> - Path2 = prettify_path(Path), - erlang:error({gpb_type_error, - {Error, [{value, ValueSeen}, {path, Path2}]}}). - - --compile({nowarn_unused_function,prettify_path/1}). -prettify_path([]) -> top_level; -prettify_path(PathR) -> - list_to_atom(string:join(lists:map(fun atom_to_list/1, - lists:reverse(PathR)), - ".")). - - --compile({nowarn_unused_function,id/2}). --compile({inline,id/2}). -id(X, _TrUserData) -> X. - --compile({nowarn_unused_function,v_ok/3}). --compile({inline,v_ok/3}). -v_ok(_Value, _Path, _TrUserData) -> ok. - --compile({nowarn_unused_function,m_overwrite/3}). --compile({inline,m_overwrite/3}). -m_overwrite(_Prev, New, _TrUserData) -> New. - --compile({nowarn_unused_function,cons/3}). --compile({inline,cons/3}). -cons(Elem, Acc, _TrUserData) -> [Elem | Acc]. - --compile({nowarn_unused_function,lists_reverse/2}). --compile({inline,lists_reverse/2}). -'lists_reverse'(L, _TrUserData) -> lists:reverse(L). --compile({nowarn_unused_function,'erlang_++'/3}). --compile({inline,'erlang_++'/3}). -'erlang_++'(A, B, _TrUserData) -> A ++ B. - -get_msg_defs() -> - [{{msg, 'Versions'}, - [#{name => packages, fnum => 1, rnum => 2, - type => {msg, 'Package'}, occurrence => repeated, - opts => []}, - #{name => repository, fnum => 2, rnum => 3, - type => string, occurrence => required, opts => []}]}, - {{msg, 'Package'}, - [#{name => name, fnum => 1, rnum => 2, type => string, - occurrence => required, opts => []}, - #{name => versions, fnum => 2, rnum => 3, - type => string, occurrence => repeated, opts => []}, - #{name => retired, fnum => 3, rnum => 4, type => int32, - occurrence => repeated, opts => [packed]}]}]. - - -get_msg_names() -> ['Versions', 'Package']. - - -get_group_names() -> []. - - -get_msg_or_group_names() -> ['Versions', 'Package']. - - -get_enum_names() -> []. - - -fetch_msg_def(MsgName) -> - case find_msg_def(MsgName) of - Fs when is_list(Fs) -> Fs; - error -> erlang:error({no_such_msg, MsgName}) - end. - - --spec fetch_enum_def(_) -> no_return(). -fetch_enum_def(EnumName) -> - erlang:error({no_such_enum, EnumName}). - - -find_msg_def('Versions') -> - [#{name => packages, fnum => 1, rnum => 2, - type => {msg, 'Package'}, occurrence => repeated, - opts => []}, - #{name => repository, fnum => 2, rnum => 3, - type => string, occurrence => required, opts => []}]; -find_msg_def('Package') -> - [#{name => name, fnum => 1, rnum => 2, type => string, - occurrence => required, opts => []}, - #{name => versions, fnum => 2, rnum => 3, - type => string, occurrence => repeated, opts => []}, - #{name => retired, fnum => 3, rnum => 4, type => int32, - occurrence => repeated, opts => [packed]}]; -find_msg_def(_) -> error. - - -find_enum_def(_) -> error. - - --spec enum_symbol_by_value(_, _) -> no_return(). -enum_symbol_by_value(E, V) -> - erlang:error({no_enum_defs, E, V}). - - --spec enum_value_by_symbol(_, _) -> no_return(). -enum_value_by_symbol(E, V) -> - erlang:error({no_enum_defs, E, V}). - - - -get_service_names() -> []. - - -get_service_def(_) -> error. - - -get_rpc_names(_) -> error. - - -find_rpc_def(_, _) -> error. - - - --spec fetch_rpc_def(_, _) -> no_return(). -fetch_rpc_def(ServiceName, RpcName) -> - erlang:error({no_such_rpc, ServiceName, RpcName}). - - -get_package_name() -> undefined. - - - -gpb_version_as_string() -> - "4.3.1". - -gpb_version_as_list() -> - [4,3,1]. diff --git a/_build/default/plugins/hex_core/src/hex_registry.erl b/_build/default/plugins/hex_core/src/hex_registry.erl deleted file mode 100644 index b9e89748f9..0000000000 --- a/_build/default/plugins/hex_core/src/hex_registry.erl +++ /dev/null @@ -1,131 +0,0 @@ --module(hex_registry). --export([ - encode_names/1, - decode_names/2, - encode_versions/1, - decode_versions/2, - encode_package/1, - decode_package/3, - sign_protobuf/2, - decode_signed/1, - decode_and_verify_signed/2, - sign/2, - verify/3 -]). --include_lib("public_key/include/public_key.hrl"). - --type private_key() :: #'RSAPrivateKey'{} | binary(). --type public_key() :: #'RSAPublicKey'{} | binary(). - -%%==================================================================== -%% API functions -%%==================================================================== - -%% @doc -%% Encode Names message. -encode_names(Names) -> - hex_pb_names:encode_msg(Names, 'Names'). - -%% @doc -%% Decode message created with encode_names/1. -decode_names(Payload, no_verify) -> - #{packages := Packages} = hex_pb_names:decode_msg(Payload, 'Names'), - {ok, Packages}; - -decode_names(Payload, Repository) -> - case hex_pb_names:decode_msg(Payload, 'Names') of - #{repository := Repository, packages := Packages} -> - {ok, Packages}; - _ -> - {error, unverified} - end. - -%% @doc -%% Encode Versions message. -encode_versions(Versions) -> - hex_pb_versions:encode_msg(Versions, 'Versions'). - -%% @doc -%% Decode message created with encode_versions/1. -decode_versions(Payload, no_verify) -> - #{packages := Packages} = hex_pb_versions:decode_msg(Payload, 'Versions'), - {ok, Packages}; - -decode_versions(Payload, Repository) -> - case hex_pb_versions:decode_msg(Payload, 'Versions') of - #{repository := Repository, packages := Packages} -> - {ok, Packages}; - _ -> - {error, unverified} - end. - -%% @doc -%% Encode Package message. -encode_package(Package) -> - hex_pb_package:encode_msg(Package, 'Package'). - -%% @doc -%% Decode message created with encode_package/1. -decode_package(Payload, no_verify, no_verify) -> - #{releases := Releases} = hex_pb_package:decode_msg(Payload, 'Package'), - {ok, Releases}; - -decode_package(Payload, Repository, Package) -> - case hex_pb_package:decode_msg(Payload, 'Package') of - #{repository := Repository, name := Package, releases := Releases} -> - {ok, Releases}; - _ -> - {error, unverified} - end. - -%% @doc -%% Encode Signed message. -sign_protobuf(Payload, PrivateKey) -> - Signature = sign(Payload, PrivateKey), - hex_pb_signed:encode_msg(#{payload => Payload, signature => Signature}, 'Signed'). - -%% @doc -%% Decode message created with sign_protobuf/2 without verification. -decode_signed(Signed) -> - hex_pb_signed:decode_msg(Signed, 'Signed'). - -%% @doc -%% Decode message created with sign_protobuf/2 and verify it against public key. --spec decode_and_verify_signed(binary(), public_key()) -> {ok, binary()} | {error, term()}. -decode_and_verify_signed(Signed, PublicKey) -> - #{payload := Payload, signature := Signature} = decode_signed(Signed), - case verify(Payload, Signature, PublicKey) of - true -> {ok, Payload}; - false -> {error, unverified}; - {error, Reason} -> {error, Reason} - end. - -%% @doc -%% Signs binary with given private key. --spec sign(binary(), private_key()) -> binary(). -sign(Binary, PrivateKey) -> - {ok, RSAPrivateKey} = key(PrivateKey), - public_key:sign(Binary, sha512, RSAPrivateKey). - -%% @doc -%% Verifies binary against signature and a public key. --spec verify(binary(), binary(), public_key()) -> boolean() | {error, term()}. -verify(Binary, Signature, PublicKey) -> - case key(PublicKey) of - {ok, RSAPublicKey} -> public_key:verify(Binary, sha512, Signature, RSAPublicKey); - {error, Reason} -> {error, Reason} - end. - -%%==================================================================== -%% Internal functions -%%==================================================================== - -key(#'RSAPublicKey'{} = Key) -> - {ok, Key}; -key(#'RSAPrivateKey'{} = Key) -> - {ok, Key}; -key(Binary) when is_binary(Binary) -> - case public_key:pem_decode(Binary) of - [Entry | _] -> {ok, public_key:pem_entry_decode(Entry)}; - _ -> {error, bad_key} - end. diff --git a/_build/default/plugins/hex_core/src/hex_repo.erl b/_build/default/plugins/hex_core/src/hex_repo.erl deleted file mode 100644 index 8bfd2733da..0000000000 --- a/_build/default/plugins/hex_core/src/hex_repo.erl +++ /dev/null @@ -1,174 +0,0 @@ --module(hex_repo). --export([ - get_names/1, - get_versions/1, - get_package/2, - get_tarball/3 -]). - -%%==================================================================== -%% API functions -%%==================================================================== - -%% @doc -%% Gets names resource from the repository. -%% -%% Examples: -%% -%% ``` -%% > hex_repo:get_names(hex_core:default_config()). -%% {ok, {200, ..., -%% [ -%% #{name => <<"package1">>}, -%% #{name => <<"package2">>}, -%% ]}} -%% ''' -%% @end -get_names(Config) when is_map(Config) -> - Verify = maps:get(repo_verify_origin, Config, true), - Decoder = fun(Data) -> - case Verify of - true -> hex_registry:decode_names(Data, repo_name(Config)); - false -> hex_registry:decode_names(Data, no_verify) - end - end, - get_protobuf(Config, <<"names">>, Decoder). - -%% @doc -%% Gets versions resource from the repository. -%% -%% Examples: -%% -%% ``` -%% > hex_repo:get_versions(Config). -%% {ok, {200, ..., -%% [ -%% #{name => <<"package1">>, retired => [], -%% versions => [<<"1.0.0">>]}, -%% #{name => <<"package2">>, retired => [<<"0.5.0>>"], -%% versions => [<<"0.5.0">>, <<"1.0.0">>]}, -%% ]}} -%% ''' -%% @end -get_versions(Config) when is_map(Config) -> - Verify = maps:get(repo_verify_origin, Config, true), - Decoder = fun(Data) -> - case Verify of - true -> hex_registry:decode_versions(Data, repo_name(Config)); - false -> hex_registry:decode_versions(Data, no_verify) - end - end, - get_protobuf(Config, <<"versions">>, Decoder). - -%% @doc -%% Gets package resource from the repository. -%% -%% Examples: -%% -%% ``` -%% > hex_repo:get_package(hex_core:default_config(), <<"package1">>). -%% {ok, {200, ..., -%% { -%% #{checksum => ..., version => <<"0.5.0">>, dependencies => []}, -%% #{checksum => ..., version => <<"1.0.0">>, dependencies => [ -%% #{package => <<"package2">>, optional => true, requirement => <<"~> 0.1">>} -%% ]}, -%% ]}} -%% ''' -%% @end -get_package(Config, Name) when is_binary(Name) and is_map(Config) -> - Verify = maps:get(repo_verify_origin, Config, true), - Decoder = fun(Data) -> - case Verify of - true -> hex_registry:decode_package(Data, repo_name(Config), Name); - false -> hex_registry:decode_package(Data, no_verify, no_verify) - end - end, - get_protobuf(Config, <<"packages/", Name/binary>>, Decoder). - -%% @doc -%% Gets tarball from the repository. -%% -%% Examples: -%% -%% ``` -%% > {ok, {200, _, Tarball}} = hex_repo:get_tarball(hex_core:default_config(), <<"package1">>, <<"1.0.0">>), -%% > {ok, #{metadata := Metadata}} = hex_tarball:unpack(Tarball, memory). -%% ''' -%% @end -get_tarball(Config, Name, Version) -> - ReqHeaders = make_headers(Config), - - case get(Config, tarball_url(Config, Name, Version), ReqHeaders) of - {ok, {200, RespHeaders, Tarball}} -> - {ok, {200, RespHeaders, Tarball}}; - - Other -> - Other - end. - -%%==================================================================== -%% Internal functions -%%==================================================================== - -get(Config, URI, Headers) -> - hex_http:request(Config, get, URI, Headers, undefined). - -get_protobuf(Config, Path, Decoder) -> - PublicKey = maps:get(repo_public_key, Config), - ReqHeaders = make_headers(Config), - - case get(Config, build_url(Config, Path), ReqHeaders) of - {ok, {200, RespHeaders, Compressed}} -> - Signed = zlib:gunzip(Compressed), - case decode(Signed, PublicKey, Decoder, Config) of - {ok, Decoded} -> - {ok, {200, RespHeaders, Decoded}}; - - {error, _} = Error -> - Error - end; - - Other -> - Other - end. - -decode(Signed, PublicKey, Decoder, Config) -> - Verify = maps:get(repo_verify, Config, true), - - case Verify of - true -> - case hex_registry:decode_and_verify_signed(Signed, PublicKey) of - {ok, Payload} -> - Decoder(Payload); - Other -> - Other - end; - false -> - #{payload := Payload} = hex_registry:decode_signed(Signed), - Decoder(Payload) - end. - -repo_name(#{repo_organization := Name}) when is_binary(Name) -> Name; -repo_name(#{repo_name := Name}) when is_binary(Name) -> Name. - -tarball_url(Config, Name, Version) -> - Filename = tarball_filename(Name, Version), - build_url(Config, <<"tarballs/", Filename/binary>>). - -build_url(#{repo_url := URI, repo_organization := Org}, Path) when is_binary(Org) -> - <>; -build_url(#{repo_url := URI, repo_organization := undefined}, Path) -> - <>; -build_url(Config, Path) -> - build_url(Config#{repo_organization => undefined}, Path). - -tarball_filename(Name, Version) -> - <>. - -make_headers(Config) -> - maps:fold(fun set_header/3, #{}, Config). - -set_header(http_etag, ETag, Headers) when is_binary(ETag) -> maps:put(<<"if-none-match">>, ETag, Headers); -set_header(repo_key, Token, Headers) when is_binary(Token) -> maps:put(<<"authorization">>, Token, Headers); -set_header(_, _, Headers) -> Headers. diff --git a/_build/default/plugins/hex_core/src/hex_tarball.erl b/_build/default/plugins/hex_core/src/hex_tarball.erl deleted file mode 100644 index 8c50b923d4..0000000000 --- a/_build/default/plugins/hex_core/src/hex_tarball.erl +++ /dev/null @@ -1,572 +0,0 @@ --module(hex_tarball). --export([create/2, create/3, create_docs/1, create_docs/2, unpack/2, unpack/3, - unpack_docs/2, unpack_docs/3, format_checksum/1, format_error/1]). --ifdef(TEST). --export([do_decode_metadata/1, gzip/1, normalize_requirements/1]). --endif. --define(VERSION, <<"3">>). --define(BUILD_TOOL_FILES, [ - {<<"mix.exs">>, <<"mix">>}, - {<<"rebar.config">>, <<"rebar3">>}, - {<<"rebar">>, <<"rebar3">>}, - {<<"Makefile">>, <<"make">>}, - {<<"Makefile.win">>, <<"make">>} -]). --include_lib("kernel/include/file.hrl"). - --type checksum() :: binary(). --type contents() :: #{filename() => binary()}. --type filename() :: string(). --type files() :: [{filename(), filename() | binary()}]. --type metadata() :: map(). --type tarball() :: binary(). - -%%==================================================================== -%% API functions -%%==================================================================== - -%% @doc -%% Creates a package tarball. -%% -%% Returns the binary of the tarball the "inner checksum" and "outer checksum". -%% The inner checksum is deprecated in favor of the inner checksum. -%% -%% Examples: -%% -%% ``` -%% > Metadata = #{<<"name">> => <<"foo">>, <<"version">> => <<"1.0.0">>}, -%% > Files = [{"src/foo.erl", <<"-module(foo).">>}], -%% > hex_tarball:create(Metadata, Files). -%% {ok, #{tarball => <<86,69,...>>, -%% outer_checksum => <<40,32,...>>, -%% inner_checksum => <<178,12,...>>}} -%% ''' -%% @end --spec create(metadata(), files(), hex_core:config()) -> {ok, #{tarball => tarball(), outer_checksum => checksum(), - inner_checksum => tarball()}} | {error, term()}. -create(Metadata, Files, Config) -> - MetadataBinary = encode_metadata(Metadata), - ContentsTarball = create_memory_tarball(Files), - ContentsTarballCompressed = gzip(ContentsTarball), - InnerChecksum = inner_checksum(?VERSION, MetadataBinary, ContentsTarballCompressed), - InnerChecksumBase16 = encode_base16(InnerChecksum), - TarballMaxSize = maps:get(tarball_max_size, Config), - TarballMaxUncompressedSize = maps:get(tarball_max_uncompressed_size, Config), - - OuterFiles = [ - {"VERSION", ?VERSION}, - {"CHECKSUM", InnerChecksumBase16}, - {"metadata.config", MetadataBinary}, - {"contents.tar.gz", ContentsTarballCompressed} - ], - - Tarball = create_memory_tarball(OuterFiles), - OuterChecksum = checksum(Tarball), - - UncompressedSize = byte_size(ContentsTarball), - - case {(byte_size(Tarball) > TarballMaxSize), (UncompressedSize > TarballMaxUncompressedSize)} of - {_, true} -> - {error, {tarball, {too_big_uncompressed, TarballMaxUncompressedSize}}}; - - {true, _} -> - {error, {tarball, {too_big_compressed, TarballMaxSize}}}; - - {false, false} -> - {ok, #{tarball => Tarball, outer_checksum => OuterChecksum, inner_checksum => InnerChecksum}} - end. - --spec create(metadata(), files()) -> {ok, #{tarball => tarball(), outer_checksum => checksum(), - inner_checksum => tarball()}} | {error, term()}. -create(Metadata, Files) -> - create(Metadata, Files, hex_core:default_config()). - -%% @doc -%% Creates a docs tarball. -%% -%% Examples: -%% -%% ``` -%% > Files = [{"doc/index.html", <<"Docs">>}], -%% > hex_tarball:create_docs(Files). -%% {ok, <<86,69,...>>} -%% ''' -%% @end --spec create_docs(files(), hex_core:config()) -> {ok, tarball()} | {error, term()}. -create_docs(Files, #{tarball_max_size := TarballMaxSize, tarball_max_uncompressed_size := TarballMaxUncompressedSize}) -> - UncompressedTarball = create_memory_tarball(Files), - UncompressedSize = byte_size(UncompressedTarball), - Tarball = gzip(UncompressedTarball), - Size = byte_size(Tarball), - - case(Size > TarballMaxSize) or (UncompressedSize > TarballMaxUncompressedSize) of - true -> - {error, {tarball, too_big}}; - - false -> - {ok, Tarball} - end. - --spec create_docs(files()) -> {ok, tarball()}. -create_docs(Files) -> - create_docs(Files, hex_core:default_config()). - -%% @doc -%% Unpacks a package tarball. -%% -%% Remember to verify the outer tarball checksum against the registry checksum -%% returned from `hex_repo:get_package(Config, Package)`. -%% -%% Examples: -%% -%% ``` -%% > hex_tarball:unpack(Tarball, memory). -%% {ok,#{outer_checksum => <<...>>, -%% contents => [{"src/foo.erl",<<"-module(foo).">>}], -%% metadata => #{<<"name">> => <<"foo">>, ...}}} -%% -%% > hex_tarball:unpack(Tarball, "path/to/unpack"). -%% {ok,#{outer_checksum => <<...>>, -%% metadata => #{<<"name">> => <<"foo">>, ...}}} -%% ''' --spec unpack(tarball(), memory, hex_core:config()) -> - {ok, #{outer_checksum => checksum(), inner_checksum => checksum(), - metadata => metadata(), contents => contents()}} | - {error, term()}; - (tarball(), filename(), hex_core:config()) -> - {ok, #{outer_checksum => checksum(), inner_checksum => checksum(), - metadata => metadata()}} | - {error, term()}. -unpack(Tarball, _, #{tarball_max_size := TarballMaxSize}) when byte_size(Tarball) > TarballMaxSize -> - {error, {tarball, too_big}}; - -unpack(Tarball, Output, _Config) -> - case hex_erl_tar:extract({binary, Tarball}, [memory]) of - {ok, []} -> - {error, {tarball, empty}}; - - {ok, FileList} -> - OuterChecksum = crypto:hash(sha256, Tarball), - do_unpack(maps:from_list(FileList), OuterChecksum, Output); - - {error, Reason} -> - {error, {tarball, Reason}} - end. - - --spec unpack(tarball(), memory) -> - {ok, #{outer_checksum => checksum(), inner_checksum => checksum(), - metadata => metadata(), contents => contents()}} | - {error, term()}; - (tarball(), filename()) -> - {ok, #{outer_checksum => checksum(), inner_checksum => checksum(), - metadata => metadata()}} | - {error, term()}. -unpack(Tarball, Output) -> - unpack(Tarball, Output, hex_core:default_config()). - -%% @doc -%% Unpacks a documentation tarball. -%% -%% Examples: -%% -%% ``` -%% > hex_tarball:unpack_docs(Tarball, memory). -%% {ok, [{"index.html", <<"">>}, ...]} -%% -%% > hex_tarball:unpack_docs(Tarball, "path/to/unpack"). -%% ok -%% ''' --spec unpack_docs(tarball(), memory, hex_core:config()) -> {ok, contents()} | {error, term()}; - (tarball(), filename(), hex_core:config()) -> ok | {error, term()}. -unpack_docs(Tarball, _, #{tarball_max_size := TarballMaxSize}) when byte_size(Tarball) > TarballMaxSize -> - {error, {tarball, too_big}}; - -unpack_docs(Tarball, Output, _Config) -> - unpack_tarball(Tarball, Output). - --spec unpack_docs(tarball(), memory) -> {ok, contents()} | {error, term()}; - (tarball(), filename()) -> ok | {error, term()}. -unpack_docs(Tarball, Output) -> - unpack_docs(Tarball, Output, hex_core:default_config()). - -%% @doc -%% Returns base16-encoded representation of checksum. --spec format_checksum(checksum()) -> binary(). -format_checksum(Checksum) -> - encode_base16(Checksum). - -%% @doc -%% Converts an error reason term to a human-readable error message string. --spec format_error(term()) -> string(). -format_error({tarball, empty}) -> "empty tarball"; -format_error({tarball, {too_big_uncompressed, Size}}) -> - io_lib:format("package exceeds max uncompressed size ~w ~s", [format_byte_size(Size), "MB"]); -format_error({tarball, {too_big_compressed, Size}}) -> - io_lib:format("package exceeds max compressed size ~w ~s", [format_byte_size(Size), "MB"]); - -format_error({tarball, {missing_files, Files}}) -> io_lib:format("missing files: ~p", [Files]); -format_error({tarball, {bad_version, Vsn}}) -> io_lib:format("unsupported version: ~p", [Vsn]); -format_error({tarball, invalid_checksum}) -> "invalid tarball checksum"; -format_error({tarball, Reason}) -> "tarball error, " ++ hex_erl_tar:format_error(Reason); -format_error({inner_tarball, Reason}) -> "inner tarball error, " ++ hex_erl_tar:format_error(Reason); -format_error({metadata, invalid_terms}) -> "error reading package metadata: invalid terms"; -format_error({metadata, not_key_value}) -> "error reading package metadata: not in key-value format"; -format_error({metadata, Reason}) -> "error reading package metadata" ++ safe_erl_term:format_error(Reason); - -format_error({checksum_mismatch, ExpectedChecksum, ActualChecksum}) -> - io_lib:format( - "tarball checksum mismatch~n~n" ++ - "Expected (base16-encoded): ~s~n" ++ - "Actual (base16-encoded): ~s", - [encode_base16(ExpectedChecksum), encode_base16(ActualChecksum)]). - -format_byte_size(Size) -> - Size / 1000000. - -%%==================================================================== -%% Internal functions -%%==================================================================== - -inner_checksum(Version, MetadataBinary, ContentsBinary) -> - Blob = <>, - crypto:hash(sha256, Blob). - -checksum(ContentsBinary) when is_binary(ContentsBinary) -> - crypto:hash(sha256, ContentsBinary). - -encode_metadata(Meta) -> - Data = lists:map( - fun(MetaPair) -> - String = io_lib_pretty:print(binarify(MetaPair), [{encoding, utf8}]), - unicode:characters_to_binary([String, ".\n"]) - end, maps:to_list(Meta)), - iolist_to_binary(Data). - -do_unpack(Files, OuterChecksum, Output) -> - State = #{ - inner_checksum => undefined, - outer_checksum => OuterChecksum, - contents => undefined, - files => Files, - metadata => undefined, - output => Output - }, - State1 = check_files(State), - State2 = check_version(State1), - State3 = check_inner_checksum(State2), - State4 = decode_metadata(State3), - finish_unpack(State4). - -finish_unpack({error, _} = Error) -> - Error; -finish_unpack(#{metadata := Metadata, files := Files, inner_checksum := InnerChecksum, outer_checksum := OuterChecksum, output := Output}) -> - _ = maps:get("VERSION", Files), - ContentsBinary = maps:get("contents.tar.gz", Files), - - case Output of - memory -> ok; - _ -> filelib:ensure_dir(filename:join(Output, "*")) - end, - - case unpack_tarball(ContentsBinary, Output) of - ok -> - copy_metadata_config(Output, maps:get("metadata.config", Files)), - {ok, #{inner_checksum => InnerChecksum, outer_checksum => OuterChecksum, metadata => Metadata}}; - - {ok, Contents} -> - {ok, #{inner_checksum => InnerChecksum, outer_checksum => OuterChecksum, metadata => Metadata, contents => Contents}}; - - {error, Reason} -> - {error, {inner_tarball, Reason}} - end. - -copy_metadata_config(Output, MetadataBinary) -> - ok = file:write_file(filename:join(Output, "hex_metadata.config"), MetadataBinary). - -check_files(#{files := Files} = State) -> - RequiredFiles = ["VERSION", "CHECKSUM", "metadata.config", "contents.tar.gz"], - case diff_keys(Files, RequiredFiles, []) of - ok -> - State; - - {error, {missing_keys, Keys}} -> - {error, {tarball, {missing_files, Keys}}} - end. - -check_version({error, _} = Error) -> - Error; -check_version(#{files := Files} = State) -> - case maps:get("VERSION", Files) of - <<"3">> -> - State; - - Version -> - {error, {tarball, {bad_version, Version}}} - end. - -% Note: This checksum is deprecated -check_inner_checksum({error, _} = Error) -> - Error; -check_inner_checksum(#{files := Files} = State) -> - ChecksumBase16 = maps:get("CHECKSUM", Files), - ExpectedChecksum = decode_base16(ChecksumBase16), - - Version = maps:get("VERSION", Files), - MetadataBinary = maps:get("metadata.config", Files), - ContentsBinary = maps:get("contents.tar.gz", Files), - ActualChecksum = inner_checksum(Version, MetadataBinary, ContentsBinary), - - if - byte_size(ExpectedChecksum) /= 32 -> - {error, {tarball, invalid_inner_checksum}}; - - ExpectedChecksum == ActualChecksum -> - maps:put(inner_checksum, ExpectedChecksum, State); - - true -> - {error, {tarball, {inner_checksum_mismatch, ExpectedChecksum, ActualChecksum}}} - end. - -decode_metadata({error, _} = Error) -> - Error; -decode_metadata(#{files := #{"metadata.config" := Binary}} = State) when is_binary(Binary) -> - case do_decode_metadata(Binary) of - #{} = Metadata -> maps:put(metadata, normalize_metadata(Metadata), State); - Other -> Other - end. - -do_decode_metadata(Binary) when is_binary(Binary) -> - {ok, String} = characters_to_list(Binary), - - case safe_erl_term:string(String) of - {ok, Tokens, _Line} -> - try - Terms = safe_erl_term:terms(Tokens), - maps:from_list(Terms) - catch - error:function_clause -> - {error, {metadata, invalid_terms}}; - - error:badarg -> - {error, {metadata, not_key_value}} - end; - - {error, {_Line, safe_erl_term, Reason}, _Line2} -> - {error, {metadata, Reason}} - end. - -characters_to_list(Binary) -> - case unicode:characters_to_list(Binary) of - List when is_list(List) -> - {ok, List}; - {error, _, _} -> - case unicode:characters_to_list(Binary, latin1) of - List when is_list(List) -> {ok, List}; - Other -> Other - end - end. - -normalize_metadata(Metadata1) -> - Metadata2 = maybe_update_with(<<"requirements">>, fun normalize_requirements/1, Metadata1), - Metadata3 = maybe_update_with(<<"links">>, fun try_into_map/1, Metadata2), - Metadata4 = maybe_update_with(<<"extra">>, fun try_into_map/1, Metadata3), - guess_build_tools(Metadata4). - -normalize_requirements(Requirements) -> - case is_list(Requirements) andalso (Requirements /= []) andalso is_list(hd(Requirements)) of - true -> - maps:from_list(lists:map(fun normalize_legacy_requirement/1, Requirements)); - - false -> - try_into_map(fun normalize_normal_requirement/1, Requirements) - end. - -normalize_normal_requirement({Name, Requirement}) -> - {Name, try_into_map(Requirement)}. - -normalize_legacy_requirement(Requirement) -> - Map = maps:from_list(Requirement), - Name = maps:get(<<"name">>, Map), - {Name, maps:without([<<"name">>], Map)}. - -guess_build_tools(#{<<"build_tools">> := BuildTools} = Metadata) when is_list(BuildTools) -> - Metadata; -guess_build_tools(#{<<"files">> := Filenames} = Metadata) -> - BaseFiles = [Filename || Filename <- Filenames, filename:dirname(binary_to_list(Filename)) == "."], - BuildTools = lists:usort([Tool || {Filename, Tool} <- ?BUILD_TOOL_FILES, lists:member(Filename, BaseFiles)]), - Metadata#{<<"build_tools">> => BuildTools}; -guess_build_tools(Metadata) -> - Metadata. - -%%==================================================================== -%% Tar Helpers -%%==================================================================== - -unpack_tarball(ContentsBinary, memory) -> - hex_erl_tar:extract({binary, ContentsBinary}, [memory, compressed]); -unpack_tarball(ContentsBinary, Output) -> - filelib:ensure_dir(filename:join(Output, "*")), - case hex_erl_tar:extract({binary, ContentsBinary}, [{cwd, Output}, compressed]) of - ok -> - [try_updating_mtime(filename:join(Output, Path)) || Path <- filelib:wildcard("**", Output)], - ok; - Other -> - Other - end. - -%% let it silently fail for bad symlinks -try_updating_mtime(Path) -> - Time = calendar:universal_time(), - _ = file:write_file_info(Path, #file_info{mtime=Time}, [{time, universal}]), - ok. - -create_memory_tarball(Files) -> - Path = tmp_path(), - {ok, Tar} = hex_erl_tar:open(Path, [write]), - - try - add_files(Tar, Files) - after - ok = hex_erl_tar:close(Tar) - end, - {ok, Tarball} = file:read_file(Path), - ok = file:delete(Path), - Tarball. - -tmp_path() -> - "tmp_" ++ binary_to_list(encode_base16(crypto:strong_rand_bytes(32))). - -add_files(Tar, Files) when is_list(Files) -> - lists:map(fun(File) -> add_file(Tar, File) end, Files). - -add_file(Tar, {Filename, Contents}) when is_list(Filename) and is_binary(Contents) -> - ok = hex_erl_tar:add(Tar, Contents, Filename, tar_opts()); -add_file(Tar, Filename) when is_list(Filename) -> - add_file(Tar, {Filename, Filename}); -add_file(Tar, {Filename, AbsFilename}) when is_list(Filename), is_list(AbsFilename) -> - {ok, FileInfo} = file:read_link_info(AbsFilename, []), - - case FileInfo#file_info.type of - symlink -> - ok = hex_erl_tar:add(Tar, {Filename, AbsFilename}, tar_opts()); - directory -> - case file:list_dir(AbsFilename) of - {ok, []} -> - hex_erl_tar:add(Tar, {Filename, AbsFilename}, tar_opts()); - - {ok, _} -> - ok - end; - _ -> - Mode = FileInfo#file_info.mode, - {ok, Contents} = file:read_file(AbsFilename), - ok = hex_erl_tar:add(Tar, Contents, Filename, Mode, tar_opts()) - end. - -tar_opts() -> - NixEpoch = calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}), - Y2kEpoch = calendar:datetime_to_gregorian_seconds({{2000, 1, 1}, {0, 0, 0}}), - Epoch = Y2kEpoch - NixEpoch, - [{atime, Epoch}, {mtime, Epoch}, {ctime, Epoch}, {uid, 0}, {gid, 0}]. - -%% Reproducible gzip by not setting mtime and OS -%% -%% From https://tools.ietf.org/html/rfc1952 -%% -%% +---+---+---+---+---+---+---+---+---+---+ -%% |ID1|ID2|CM |FLG| MTIME |XFL|OS | (more-->) -%% +---+---+---+---+---+---+---+---+---+---+ -%% -%% +=======================+ -%% |...compressed blocks...| (more-->) -%% +=======================+ -%% -%% +---+---+---+---+---+---+---+---+ -%% | CRC32 | ISIZE | -%% +---+---+---+---+---+---+---+---+ -gzip(Uncompressed) -> - Compressed = gzip_no_header(Uncompressed), - Header = <<31, 139, 8, 0, 0, 0, 0, 0, 0, 0>>, - Crc = erlang:crc32(Uncompressed), - Size = byte_size(Uncompressed), - Trailer = <>, - iolist_to_binary([Header, Compressed, Trailer]). - -gzip_no_header(Uncompressed) -> - Zstream = zlib:open(), - - try - zlib:deflateInit(Zstream, default, deflated, -15, 8, default), - Compressed = zlib:deflate(Zstream, Uncompressed, finish), - zlib:deflateEnd(Zstream), - iolist_to_binary(Compressed) - after - zlib:close(Zstream) - end. - -%%==================================================================== -%% Helpers -%%==================================================================== - -binarify(Binary) when is_binary(Binary) -> Binary; -binarify(Number) when is_number(Number) -> Number; -binarify(Atom) when Atom == undefined orelse is_boolean(Atom) -> Atom; -binarify(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); -binarify(List) when is_list(List) -> - [binarify(E) || E <- List]; -binarify({Key, Value}) -> - {binarify(Key), binarify(Value)}; -binarify(Map) when is_map(Map) -> - List = maps:to_list(Map), - lists:map(fun({K, V}) -> binarify({K, V}) end, List). - -diff_keys(Map, RequiredKeys, OptionalKeys) -> - Keys = maps:keys(Map), - MissingKeys = RequiredKeys -- Keys, - UnknownKeys = Keys -- (RequiredKeys ++ OptionalKeys), - - case {MissingKeys, UnknownKeys} of - {[], []} -> - ok; - - % Server should validate this but clients should not - % {_, [_ | _]} -> - % {error, {unknown_keys, UnknownKeys}}; - - _ -> - {error, {missing_keys, MissingKeys}} - end. - -maybe_update_with(Key, Fun, Map) -> - case maps:find(Key, Map) of - {ok, Value} -> maps:put(Key, Fun(Value), Map); - error -> Map - end. - -try_into_map(List) -> - try_into_map(fun(X) -> X end, List). - -try_into_map(Fun, Input) -> - case is_list(Input) andalso lists:all(fun(E) -> is_tuple(E) andalso (tuple_size(E) == 2) end, Input) of - true -> maps:from_list(lists:map(Fun, Input)); - false -> Input - end. - -encode_base16(Binary) -> - <> = Binary, - String = string:to_upper(lists:flatten(io_lib:format("~64.16.0b", [X]))), - list_to_binary(String). - -%% Based on https://hub.fastgit.org/goj/base16/blob/master/src/base16.erl -%% (C) 2012, Erlang Solutions Ltd. - -decode_base16(Base16) -> - << <<(unhex(H) bsl 4 + unhex(L))>> || <> <= Base16 >>. - -unhex(D) when $0 =< D andalso D =< $9 -> - D - $0; -unhex(D) when $a =< D andalso D =< $f -> - 10 + D - $a; -unhex(D) when $A =< D andalso D =< $F -> - 10 + D - $A. diff --git a/_build/default/plugins/hex_core/src/safe_erl_term.erl b/_build/default/plugins/hex_core/src/safe_erl_term.erl deleted file mode 100644 index e164febadc..0000000000 --- a/_build/default/plugins/hex_core/src/safe_erl_term.erl +++ /dev/null @@ -1,660 +0,0 @@ --file("d:/msys64/mingw32/erlang/erl10.3/lib/parsetools-2.1.8/include/leexinc.hrl", 0). -%% The source of this file is part of leex distribution, as such it -%% has the same Copyright as the other files in the leex -%% distribution. The Copyright is defined in the accompanying file -%% COPYRIGHT. However, the resultant scanner generated by leex is the -%% property of the creator of the scanner and is not covered by that -%% Copyright. - --module(safe_erl_term). - --export([string/1,string/2,token/2,token/3,tokens/2,tokens/3]). --export([format_error/1]). - -%% User code. This is placed here to allow extra attributes. --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 24). - --export([terms/1]). - -terms(Tokens) -> - terms(Tokens, []). - -terms([{dot, _} = H], Buffer) -> - [buffer_to_term([H|Buffer])]; -terms([{dot, _} = H|T], Buffer) -> - [buffer_to_term([H|Buffer])|terms(T, [])]; -terms([H|T], Buffer) -> - terms(T, [H|Buffer]). - -buffer_to_term(Buffer) -> - {ok, Term} = erl_parse:parse_term(lists:reverse(Buffer)), - Term. - -unquote(TokenChars, TokenLen) -> - lists:sublist(TokenChars, 2, TokenLen - 2). - -tokenize_atom(TokenChars, TokenLine) -> - try list_to_existing_atom(TokenChars) of - Atom -> {token, {atom, TokenLine, Atom}} - catch - error:badarg -> {error, "illegal atom " ++ TokenChars} - end. - -escape([$\\|Cs]) -> - do_escape(Cs); -escape([C|Cs]) -> - [C|escape(Cs)]; -escape([]) -> []. - -do_escape([O1,O2,O3|S]) when - O1 >= $0, O1 =< $7, O2 >= $0, O2 =< $7, O3 >= $0, O3 =< $7 -> - [(O1*8 + O2)*8 + O3 - 73*$0|escape(S)]; -do_escape([$^,C|Cs]) -> - [C band 31|escape(Cs)]; -do_escape([C|Cs]) when C >= $\000, C =< $\s -> - escape(Cs); -do_escape([C|Cs]) -> - [escape_char(C)|escape(Cs)]. - -escape_char($n) -> $\n; %\n = LF -escape_char($r) -> $\r; %\r = CR -escape_char($t) -> $\t; %\t = TAB -escape_char($v) -> $\v; %\v = VT -escape_char($b) -> $\b; %\b = BS -escape_char($f) -> $\f; %\f = FF -escape_char($e) -> $\e; %\e = ESC -escape_char($s) -> $\s; %\s = SPC -escape_char($d) -> $\d; %\d = DEL -escape_char(C) -> C. - --file("d:/msys64/mingw32/erlang/erl10.3/lib/parsetools-2.1.8/include/leexinc.hrl", 14). - -format_error({illegal,S}) -> ["illegal characters ",io_lib:write_string(S)]; -format_error({user,S}) -> S. - -string(String) -> string(String, 1). - -string(String, Line) -> string(String, Line, String, []). - -%% string(InChars, Line, TokenChars, Tokens) -> -%% {ok,Tokens,Line} | {error,ErrorInfo,Line}. -%% Note the line number going into yystate, L0, is line of token -%% start while line number returned is line of token end. We want line -%% of token start. - -string([], L, [], Ts) -> % No partial tokens! - {ok,yyrev(Ts),L}; -string(Ics0, L0, Tcs, Ts) -> - case yystate(yystate(), Ics0, L0, 0, reject, 0) of - {A,Alen,Ics1,L1} -> % Accepting end state - string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts); - {A,Alen,Ics1,L1,_S1} -> % Accepting transistion state - string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts); - {reject,_Alen,Tlen,_Ics1,L1,_S1} -> % After a non-accepting state - {error,{L0,?MODULE,{illegal,yypre(Tcs, Tlen+1)}},L1}; - {A,Alen,Tlen,_Ics1,L1,_S1} -> - Tcs1 = yysuf(Tcs, Alen), - L2 = adjust_line(Tlen, Alen, Tcs1, L1), - string_cont(Tcs1, L2, yyaction(A, Alen, Tcs, L0), Ts) - end. - -%% string_cont(RestChars, Line, Token, Tokens) -%% Test for and remove the end token wrapper. Push back characters -%% are prepended to RestChars. - --dialyzer({nowarn_function, string_cont/4}). - -string_cont(Rest, Line, {token,T}, Ts) -> - string(Rest, Line, Rest, [T|Ts]); -string_cont(Rest, Line, {token,T,Push}, Ts) -> - NewRest = Push ++ Rest, - string(NewRest, Line, NewRest, [T|Ts]); -string_cont(Rest, Line, {end_token,T}, Ts) -> - string(Rest, Line, Rest, [T|Ts]); -string_cont(Rest, Line, {end_token,T,Push}, Ts) -> - NewRest = Push ++ Rest, - string(NewRest, Line, NewRest, [T|Ts]); -string_cont(Rest, Line, skip_token, Ts) -> - string(Rest, Line, Rest, Ts); -string_cont(Rest, Line, {skip_token,Push}, Ts) -> - NewRest = Push ++ Rest, - string(NewRest, Line, NewRest, Ts); -string_cont(_Rest, Line, {error,S}, _Ts) -> - {error,{Line,?MODULE,{user,S}},Line}. - -%% token(Continuation, Chars) -> -%% token(Continuation, Chars, Line) -> -%% {more,Continuation} | {done,ReturnVal,RestChars}. -%% Must be careful when re-entering to append the latest characters to the -%% after characters in an accept. The continuation is: -%% {token,State,CurrLine,TokenChars,TokenLen,TokenLine,AccAction,AccLen} - -token(Cont, Chars) -> token(Cont, Chars, 1). - -token([], Chars, Line) -> - token(yystate(), Chars, Line, Chars, 0, Line, reject, 0); -token({token,State,Line,Tcs,Tlen,Tline,Action,Alen}, Chars, _) -> - token(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Action, Alen). - -%% token(State, InChars, Line, TokenChars, TokenLen, TokenLine, -%% AcceptAction, AcceptLen) -> -%% {more,Continuation} | {done,ReturnVal,RestChars}. -%% The argument order is chosen to be more efficient. - -token(S0, Ics0, L0, Tcs, Tlen0, Tline, A0, Alen0) -> - case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of - %% Accepting end state, we have a token. - {A1,Alen1,Ics1,L1} -> - token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline)); - %% Accepting transition state, can take more chars. - {A1,Alen1,[],L1,S1} -> % Need more chars to check - {more,{token,S1,L1,Tcs,Alen1,Tline,A1,Alen1}}; - {A1,Alen1,Ics1,L1,_S1} -> % Take what we got - token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline)); - %% After a non-accepting state, maybe reach accept state later. - {A1,Alen1,Tlen1,[],L1,S1} -> % Need more chars to check - {more,{token,S1,L1,Tcs,Tlen1,Tline,A1,Alen1}}; - {reject,_Alen1,Tlen1,eof,L1,_S1} -> % No token match - %% Check for partial token which is error. - Ret = if Tlen1 > 0 -> {error,{Tline,?MODULE, - %% Skip eof tail in Tcs. - {illegal,yypre(Tcs, Tlen1)}},L1}; - true -> {eof,L1} - end, - {done,Ret,eof}; - {reject,_Alen1,Tlen1,Ics1,L1,_S1} -> % No token match - Error = {Tline,?MODULE,{illegal,yypre(Tcs, Tlen1+1)}}, - {done,{error,Error,L1},Ics1}; - {A1,Alen1,Tlen1,_Ics1,L1,_S1} -> % Use last accept match - Tcs1 = yysuf(Tcs, Alen1), - L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), - token_cont(Tcs1, L2, yyaction(A1, Alen1, Tcs, Tline)) - end. - -%% token_cont(RestChars, Line, Token) -%% If we have a token or error then return done, else if we have a -%% skip_token then continue. - --dialyzer({nowarn_function, token_cont/3}). - -token_cont(Rest, Line, {token,T}) -> - {done,{ok,T,Line},Rest}; -token_cont(Rest, Line, {token,T,Push}) -> - NewRest = Push ++ Rest, - {done,{ok,T,Line},NewRest}; -token_cont(Rest, Line, {end_token,T}) -> - {done,{ok,T,Line},Rest}; -token_cont(Rest, Line, {end_token,T,Push}) -> - NewRest = Push ++ Rest, - {done,{ok,T,Line},NewRest}; -token_cont(Rest, Line, skip_token) -> - token(yystate(), Rest, Line, Rest, 0, Line, reject, 0); -token_cont(Rest, Line, {skip_token,Push}) -> - NewRest = Push ++ Rest, - token(yystate(), NewRest, Line, NewRest, 0, Line, reject, 0); -token_cont(Rest, Line, {error,S}) -> - {done,{error,{Line,?MODULE,{user,S}},Line},Rest}. - -%% tokens(Continuation, Chars, Line) -> -%% {more,Continuation} | {done,ReturnVal,RestChars}. -%% Must be careful when re-entering to append the latest characters to the -%% after characters in an accept. The continuation is: -%% {tokens,State,CurrLine,TokenChars,TokenLen,TokenLine,Tokens,AccAction,AccLen} -%% {skip_tokens,State,CurrLine,TokenChars,TokenLen,TokenLine,Error,AccAction,AccLen} - -tokens(Cont, Chars) -> tokens(Cont, Chars, 1). - -tokens([], Chars, Line) -> - tokens(yystate(), Chars, Line, Chars, 0, Line, [], reject, 0); -tokens({tokens,State,Line,Tcs,Tlen,Tline,Ts,Action,Alen}, Chars, _) -> - tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Ts, Action, Alen); -tokens({skip_tokens,State,Line,Tcs,Tlen,Tline,Error,Action,Alen}, Chars, _) -> - skip_tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Error, Action, Alen). - -%% tokens(State, InChars, Line, TokenChars, TokenLen, TokenLine, Tokens, -%% AcceptAction, AcceptLen) -> -%% {more,Continuation} | {done,ReturnVal,RestChars}. - -tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Ts, A0, Alen0) -> - case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of - %% Accepting end state, we have a token. - {A1,Alen1,Ics1,L1} -> - tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts); - %% Accepting transition state, can take more chars. - {A1,Alen1,[],L1,S1} -> % Need more chars to check - {more,{tokens,S1,L1,Tcs,Alen1,Tline,Ts,A1,Alen1}}; - {A1,Alen1,Ics1,L1,_S1} -> % Take what we got - tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts); - %% After a non-accepting state, maybe reach accept state later. - {A1,Alen1,Tlen1,[],L1,S1} -> % Need more chars to check - {more,{tokens,S1,L1,Tcs,Tlen1,Tline,Ts,A1,Alen1}}; - {reject,_Alen1,Tlen1,eof,L1,_S1} -> % No token match - %% Check for partial token which is error, no need to skip here. - Ret = if Tlen1 > 0 -> {error,{Tline,?MODULE, - %% Skip eof tail in Tcs. - {illegal,yypre(Tcs, Tlen1)}},L1}; - Ts == [] -> {eof,L1}; - true -> {ok,yyrev(Ts),L1} - end, - {done,Ret,eof}; - {reject,_Alen1,Tlen1,_Ics1,L1,_S1} -> - %% Skip rest of tokens. - Error = {L1,?MODULE,{illegal,yypre(Tcs, Tlen1+1)}}, - skip_tokens(yysuf(Tcs, Tlen1+1), L1, Error); - {A1,Alen1,Tlen1,_Ics1,L1,_S1} -> - Token = yyaction(A1, Alen1, Tcs, Tline), - Tcs1 = yysuf(Tcs, Alen1), - L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), - tokens_cont(Tcs1, L2, Token, Ts) - end. - -%% tokens_cont(RestChars, Line, Token, Tokens) -%% If we have an end_token or error then return done, else if we have -%% a token then save it and continue, else if we have a skip_token -%% just continue. - --dialyzer({nowarn_function, tokens_cont/4}). - -tokens_cont(Rest, Line, {token,T}, Ts) -> - tokens(yystate(), Rest, Line, Rest, 0, Line, [T|Ts], reject, 0); -tokens_cont(Rest, Line, {token,T,Push}, Ts) -> - NewRest = Push ++ Rest, - tokens(yystate(), NewRest, Line, NewRest, 0, Line, [T|Ts], reject, 0); -tokens_cont(Rest, Line, {end_token,T}, Ts) -> - {done,{ok,yyrev(Ts, [T]),Line},Rest}; -tokens_cont(Rest, Line, {end_token,T,Push}, Ts) -> - NewRest = Push ++ Rest, - {done,{ok,yyrev(Ts, [T]),Line},NewRest}; -tokens_cont(Rest, Line, skip_token, Ts) -> - tokens(yystate(), Rest, Line, Rest, 0, Line, Ts, reject, 0); -tokens_cont(Rest, Line, {skip_token,Push}, Ts) -> - NewRest = Push ++ Rest, - tokens(yystate(), NewRest, Line, NewRest, 0, Line, Ts, reject, 0); -tokens_cont(Rest, Line, {error,S}, _Ts) -> - skip_tokens(Rest, Line, {Line,?MODULE,{user,S}}). - -%%skip_tokens(InChars, Line, Error) -> {done,{error,Error,Line},Ics}. -%% Skip tokens until an end token, junk everything and return the error. - -skip_tokens(Ics, Line, Error) -> - skip_tokens(yystate(), Ics, Line, Ics, 0, Line, Error, reject, 0). - -%% skip_tokens(State, InChars, Line, TokenChars, TokenLen, TokenLine, Tokens, -%% AcceptAction, AcceptLen) -> -%% {more,Continuation} | {done,ReturnVal,RestChars}. - -skip_tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Error, A0, Alen0) -> - case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of - {A1,Alen1,Ics1,L1} -> % Accepting end state - skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error); - {A1,Alen1,[],L1,S1} -> % After an accepting state - {more,{skip_tokens,S1,L1,Tcs,Alen1,Tline,Error,A1,Alen1}}; - {A1,Alen1,Ics1,L1,_S1} -> - skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error); - {A1,Alen1,Tlen1,[],L1,S1} -> % After a non-accepting state - {more,{skip_tokens,S1,L1,Tcs,Tlen1,Tline,Error,A1,Alen1}}; - {reject,_Alen1,_Tlen1,eof,L1,_S1} -> - {done,{error,Error,L1},eof}; - {reject,_Alen1,Tlen1,_Ics1,L1,_S1} -> - skip_tokens(yysuf(Tcs, Tlen1+1), L1, Error); - {A1,Alen1,Tlen1,_Ics1,L1,_S1} -> - Token = yyaction(A1, Alen1, Tcs, Tline), - Tcs1 = yysuf(Tcs, Alen1), - L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), - skip_cont(Tcs1, L2, Token, Error) - end. - -%% skip_cont(RestChars, Line, Token, Error) -%% Skip tokens until we have an end_token or error then return done -%% with the original rror. - --dialyzer({nowarn_function, skip_cont/4}). - -skip_cont(Rest, Line, {token,_T}, Error) -> - skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0); -skip_cont(Rest, Line, {token,_T,Push}, Error) -> - NewRest = Push ++ Rest, - skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0); -skip_cont(Rest, Line, {end_token,_T}, Error) -> - {done,{error,Error,Line},Rest}; -skip_cont(Rest, Line, {end_token,_T,Push}, Error) -> - NewRest = Push ++ Rest, - {done,{error,Error,Line},NewRest}; -skip_cont(Rest, Line, skip_token, Error) -> - skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0); -skip_cont(Rest, Line, {skip_token,Push}, Error) -> - NewRest = Push ++ Rest, - skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0); -skip_cont(Rest, Line, {error,_S}, Error) -> - skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0). - --compile({nowarn_unused_function, [yyrev/1, yyrev/2, yypre/2, yysuf/2]}). - -yyrev(List) -> lists:reverse(List). -yyrev(List, Tail) -> lists:reverse(List, Tail). -yypre(List, N) -> lists:sublist(List, N). -yysuf(List, N) -> lists:nthtail(N, List). - -%% adjust_line(TokenLength, AcceptLength, Chars, Line) -> NewLine -%% Make sure that newlines in Chars are not counted twice. -%% Line has been updated with respect to newlines in the prefix of -%% Chars consisting of (TokenLength - AcceptLength) characters. - --compile({nowarn_unused_function, adjust_line/4}). - -adjust_line(N, N, _Cs, L) -> L; -adjust_line(T, A, [$\n|Cs], L) -> - adjust_line(T-1, A, Cs, L-1); -adjust_line(T, A, [_|Cs], L) -> - adjust_line(T-1, A, Cs, L). - -%% yystate() -> InitialState. -%% yystate(State, InChars, Line, CurrTokLen, AcceptAction, AcceptLen) -> -%% {Action, AcceptLen, RestChars, Line} | -%% {Action, AcceptLen, RestChars, Line, State} | -%% {reject, AcceptLen, CurrTokLen, RestChars, Line, State} | -%% {Action, AcceptLen, CurrTokLen, RestChars, Line, State}. -%% Generated state transition functions. The non-accepting end state -%% return signal either an unrecognised character or end of current -%% input. - --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.erl", 360). -yystate() -> 12. - -yystate(19, [92|Ics], Line, Tlen, Action, Alen) -> - yystate(15, Ics, Line, Tlen+1, Action, Alen); -yystate(19, [34|Ics], Line, Tlen, Action, Alen) -> - yystate(7, Ics, Line, Tlen+1, Action, Alen); -yystate(19, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(8, Ics, Line+1, Tlen+1, Action, Alen); -yystate(19, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(19, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(19, [C|Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(19, [C|Ics], Line, Tlen, Action, Alen) when C >= 93 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(19, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,19}; -yystate(18, [92|Ics], Line, Tlen, Action, Alen) -> - yystate(14, Ics, Line, Tlen+1, Action, Alen); -yystate(18, [39|Ics], Line, Tlen, Action, Alen) -> - yystate(10, Ics, Line, Tlen+1, Action, Alen); -yystate(18, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(5, Ics, Line+1, Tlen+1, Action, Alen); -yystate(18, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(18, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 38 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(18, [C|Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(18, [C|Ics], Line, Tlen, Action, Alen) when C >= 93 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(18, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,18}; -yystate(17, [60|Ics], Line, Tlen, Action, Alen) -> - yystate(11, Ics, Line, Tlen+1, Action, Alen); -yystate(17, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,17}; -yystate(16, [10|Ics], Line, Tlen, _, _) -> - yystate(16, Ics, Line+1, Tlen+1, 8, Tlen); -yystate(16, [C|Ics], Line, Tlen, _, _) when C >= 0, C =< 9 -> - yystate(16, Ics, Line, Tlen+1, 8, Tlen); -yystate(16, [C|Ics], Line, Tlen, _, _) when C >= 11, C =< 32 -> - yystate(16, Ics, Line, Tlen+1, 8, Tlen); -yystate(16, Ics, Line, Tlen, _, _) -> - {8,Tlen,Ics,Line,16}; -yystate(15, [94|Ics], Line, Tlen, Action, Alen) -> - yystate(19, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [93|Ics], Line, Tlen, Action, Alen) -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [92|Ics], Line, Tlen, Action, Alen) -> - yystate(15, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [34|Ics], Line, Tlen, Action, Alen) -> - yystate(7, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(8, Ics, Line+1, Tlen+1, Action, Alen); -yystate(15, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [C|Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(15, [C|Ics], Line, Tlen, Action, Alen) when C >= 95 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(15, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,15}; -yystate(14, [94|Ics], Line, Tlen, Action, Alen) -> - yystate(18, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [93|Ics], Line, Tlen, Action, Alen) -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [92|Ics], Line, Tlen, Action, Alen) -> - yystate(14, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [39|Ics], Line, Tlen, Action, Alen) -> - yystate(10, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(5, Ics, Line+1, Tlen+1, Action, Alen); -yystate(14, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 38 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [C|Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(14, [C|Ics], Line, Tlen, Action, Alen) when C >= 95 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(14, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,14}; -yystate(13, Ics, Line, Tlen, _, _) -> - {4,Tlen,Ics,Line}; -yystate(12, [125|Ics], Line, Tlen, Action, Alen) -> - yystate(13, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [123|Ics], Line, Tlen, Action, Alen) -> - yystate(13, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [93|Ics], Line, Tlen, Action, Alen) -> - yystate(13, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [91|Ics], Line, Tlen, Action, Alen) -> - yystate(13, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [62|Ics], Line, Tlen, Action, Alen) -> - yystate(3, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [61|Ics], Line, Tlen, Action, Alen) -> - yystate(3, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [60|Ics], Line, Tlen, Action, Alen) -> - yystate(17, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [47|Ics], Line, Tlen, Action, Alen) -> - yystate(1, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [46|Ics], Line, Tlen, Action, Alen) -> - yystate(6, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [39|Ics], Line, Tlen, Action, Alen) -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [35|Ics], Line, Tlen, Action, Alen) -> - yystate(13, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [34|Ics], Line, Tlen, Action, Alen) -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(16, Ics, Line+1, Tlen+1, Action, Alen); -yystate(12, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(16, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 32 -> - yystate(16, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [C|Ics], Line, Tlen, Action, Alen) when C >= 43, C =< 45 -> - yystate(13, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [C|Ics], Line, Tlen, Action, Alen) when C >= 48, C =< 57 -> - yystate(9, Ics, Line, Tlen+1, Action, Alen); -yystate(12, [C|Ics], Line, Tlen, Action, Alen) when C >= 97, C =< 122 -> - yystate(4, Ics, Line, Tlen+1, Action, Alen); -yystate(12, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,12}; -yystate(11, Ics, Line, Tlen, _, _) -> - {5,Tlen,Ics,Line}; -yystate(10, [92|Ics], Line, Tlen, _, _) -> - yystate(14, Ics, Line, Tlen+1, 1, Tlen); -yystate(10, [39|Ics], Line, Tlen, _, _) -> - yystate(2, Ics, Line, Tlen+1, 1, Tlen); -yystate(10, [10|Ics], Line, Tlen, _, _) -> - yystate(5, Ics, Line+1, Tlen+1, 1, Tlen); -yystate(10, [C|Ics], Line, Tlen, _, _) when C >= 0, C =< 9 -> - yystate(5, Ics, Line, Tlen+1, 1, Tlen); -yystate(10, [C|Ics], Line, Tlen, _, _) when C >= 11, C =< 38 -> - yystate(5, Ics, Line, Tlen+1, 1, Tlen); -yystate(10, [C|Ics], Line, Tlen, _, _) when C >= 40, C =< 91 -> - yystate(5, Ics, Line, Tlen+1, 1, Tlen); -yystate(10, [C|Ics], Line, Tlen, _, _) when C >= 93 -> - yystate(5, Ics, Line, Tlen+1, 1, Tlen); -yystate(10, Ics, Line, Tlen, _, _) -> - {1,Tlen,Ics,Line,10}; -yystate(9, [C|Ics], Line, Tlen, _, _) when C >= 48, C =< 57 -> - yystate(9, Ics, Line, Tlen+1, 3, Tlen); -yystate(9, Ics, Line, Tlen, _, _) -> - {3,Tlen,Ics,Line,9}; -yystate(8, [92|Ics], Line, Tlen, Action, Alen) -> - yystate(15, Ics, Line, Tlen+1, Action, Alen); -yystate(8, [34|Ics], Line, Tlen, Action, Alen) -> - yystate(0, Ics, Line, Tlen+1, Action, Alen); -yystate(8, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(8, Ics, Line+1, Tlen+1, Action, Alen); -yystate(8, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(8, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(8, [C|Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(8, [C|Ics], Line, Tlen, Action, Alen) when C >= 93 -> - yystate(8, Ics, Line, Tlen+1, Action, Alen); -yystate(8, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,8}; -yystate(7, [92|Ics], Line, Tlen, _, _) -> - yystate(15, Ics, Line, Tlen+1, 2, Tlen); -yystate(7, [34|Ics], Line, Tlen, _, _) -> - yystate(0, Ics, Line, Tlen+1, 2, Tlen); -yystate(7, [10|Ics], Line, Tlen, _, _) -> - yystate(8, Ics, Line+1, Tlen+1, 2, Tlen); -yystate(7, [C|Ics], Line, Tlen, _, _) when C >= 0, C =< 9 -> - yystate(8, Ics, Line, Tlen+1, 2, Tlen); -yystate(7, [C|Ics], Line, Tlen, _, _) when C >= 11, C =< 33 -> - yystate(8, Ics, Line, Tlen+1, 2, Tlen); -yystate(7, [C|Ics], Line, Tlen, _, _) when C >= 35, C =< 91 -> - yystate(8, Ics, Line, Tlen+1, 2, Tlen); -yystate(7, [C|Ics], Line, Tlen, _, _) when C >= 93 -> - yystate(8, Ics, Line, Tlen+1, 2, Tlen); -yystate(7, Ics, Line, Tlen, _, _) -> - {2,Tlen,Ics,Line,7}; -yystate(6, Ics, Line, Tlen, _, _) -> - {6,Tlen,Ics,Line}; -yystate(5, [92|Ics], Line, Tlen, Action, Alen) -> - yystate(14, Ics, Line, Tlen+1, Action, Alen); -yystate(5, [39|Ics], Line, Tlen, Action, Alen) -> - yystate(2, Ics, Line, Tlen+1, Action, Alen); -yystate(5, [10|Ics], Line, Tlen, Action, Alen) -> - yystate(5, Ics, Line+1, Tlen+1, Action, Alen); -yystate(5, [C|Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(5, [C|Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 38 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(5, [C|Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(5, [C|Ics], Line, Tlen, Action, Alen) when C >= 93 -> - yystate(5, Ics, Line, Tlen+1, Action, Alen); -yystate(5, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,5}; -yystate(4, [95|Ics], Line, Tlen, _, _) -> - yystate(4, Ics, Line, Tlen+1, 0, Tlen); -yystate(4, [64|Ics], Line, Tlen, _, _) -> - yystate(4, Ics, Line, Tlen+1, 0, Tlen); -yystate(4, [C|Ics], Line, Tlen, _, _) when C >= 48, C =< 57 -> - yystate(4, Ics, Line, Tlen+1, 0, Tlen); -yystate(4, [C|Ics], Line, Tlen, _, _) when C >= 65, C =< 90 -> - yystate(4, Ics, Line, Tlen+1, 0, Tlen); -yystate(4, [C|Ics], Line, Tlen, _, _) when C >= 97, C =< 122 -> - yystate(4, Ics, Line, Tlen+1, 0, Tlen); -yystate(4, Ics, Line, Tlen, _, _) -> - {0,Tlen,Ics,Line,4}; -yystate(3, [62|Ics], Line, Tlen, Action, Alen) -> - yystate(11, Ics, Line, Tlen+1, Action, Alen); -yystate(3, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,3}; -yystate(2, Ics, Line, Tlen, _, _) -> - {1,Tlen,Ics,Line}; -yystate(1, Ics, Line, Tlen, _, _) -> - {7,Tlen,Ics,Line}; -yystate(0, Ics, Line, Tlen, _, _) -> - {2,Tlen,Ics,Line}; -yystate(S, Ics, Line, Tlen, Action, Alen) -> - {Action,Alen,Tlen,Ics,Line,S}. - -%% yyaction(Action, TokenLength, TokenChars, TokenLine) -> -%% {token,Token} | {end_token, Token} | skip_token | {error,String}. -%% Generated action function. - -yyaction(0, TokenLen, YYtcs, TokenLine) -> - TokenChars = yypre(YYtcs, TokenLen), - yyaction_0(TokenChars, TokenLine); -yyaction(1, TokenLen, YYtcs, TokenLine) -> - TokenChars = yypre(YYtcs, TokenLen), - yyaction_1(TokenChars, TokenLen, TokenLine); -yyaction(2, TokenLen, YYtcs, TokenLine) -> - TokenChars = yypre(YYtcs, TokenLen), - yyaction_2(TokenChars, TokenLen, TokenLine); -yyaction(3, TokenLen, YYtcs, TokenLine) -> - TokenChars = yypre(YYtcs, TokenLen), - yyaction_3(TokenChars, TokenLine); -yyaction(4, TokenLen, YYtcs, TokenLine) -> - TokenChars = yypre(YYtcs, TokenLen), - yyaction_4(TokenChars, TokenLine); -yyaction(5, TokenLen, YYtcs, TokenLine) -> - TokenChars = yypre(YYtcs, TokenLen), - yyaction_5(TokenChars, TokenLine); -yyaction(6, _, _, TokenLine) -> - yyaction_6(TokenLine); -yyaction(7, _, _, TokenLine) -> - yyaction_7(TokenLine); -yyaction(8, _, _, _) -> - yyaction_8(); -yyaction(_, _, _, _) -> error. - --compile({inline,yyaction_0/2}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 12). -yyaction_0(TokenChars, TokenLine) -> - tokenize_atom (TokenChars, TokenLine) . - --compile({inline,yyaction_1/3}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 13). -yyaction_1(TokenChars, TokenLen, TokenLine) -> - tokenize_atom (escape (unquote (TokenChars, TokenLen)), TokenLine) . - --compile({inline,yyaction_2/3}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 14). -yyaction_2(TokenChars, TokenLen, TokenLine) -> - { token, { string, TokenLine, escape (unquote (TokenChars, TokenLen)) } } . - --compile({inline,yyaction_3/2}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 15). -yyaction_3(TokenChars, TokenLine) -> - { token, { integer, TokenLine, list_to_integer (TokenChars) } } . - --compile({inline,yyaction_4/2}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 16). -yyaction_4(TokenChars, TokenLine) -> - { token, { list_to_atom (TokenChars), TokenLine } } . - --compile({inline,yyaction_5/2}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 17). -yyaction_5(TokenChars, TokenLine) -> - { token, { list_to_atom (TokenChars), TokenLine } } . - --compile({inline,yyaction_6/1}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 18). -yyaction_6(TokenLine) -> - { token, { dot, TokenLine } } . - --compile({inline,yyaction_7/1}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 19). -yyaction_7(TokenLine) -> - { token, { '/', TokenLine } } . - --compile({inline,yyaction_8/0}). --file("d:/msys64/home/jonhl/dgiot/emqx-rel/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 20). -yyaction_8() -> - skip_token . - --file("d:/msys64/mingw32/erlang/erl10.3/lib/parsetools-2.1.8/include/leexinc.hrl", 313). diff --git a/_build/default/plugins/hex_core/src/safe_erl_term.xrl b/_build/default/plugins/hex_core/src/safe_erl_term.xrl deleted file mode 100644 index 8e58653d6e..0000000000 --- a/_build/default/plugins/hex_core/src/safe_erl_term.xrl +++ /dev/null @@ -1,77 +0,0 @@ -%%% Author : Robert Virding -%%% Purpose : Token definitions for Erlang. - -Definitions. - -D = [0-9] -U = [A-Z] -L = [a-z] -A = ({U}|{L}|{D}|_|@) -WS = ([\000-\s]) - -Rules. - -{L}{A}* : tokenize_atom(TokenChars, TokenLine). -'(\\\^.|\\.|[^'])*' : tokenize_atom(escape(unquote(TokenChars, TokenLen)), TokenLine). -"(\\\^.|\\.|[^"])*" : {token, {string, TokenLine, escape(unquote(TokenChars, TokenLen))}}. -{D}+ : {token, {integer, TokenLine, list_to_integer(TokenChars)}}. -[\#\[\]}{,+-] : {token, {list_to_atom(TokenChars), TokenLine}}. -(<<|>>|=>) : {token, {list_to_atom(TokenChars), TokenLine}}. -\. : {token, {dot, TokenLine}}. -/ : {token, {'/', TokenLine}}. -{WS}+ : skip_token. - -Erlang code. - --export([terms/1]). - -terms(Tokens) -> - terms(Tokens, []). - -terms([{dot, _} = H], Buffer) -> - [buffer_to_term([H|Buffer])]; -terms([{dot, _} = H|T], Buffer) -> - [buffer_to_term([H|Buffer])|terms(T, [])]; -terms([H|T], Buffer) -> - terms(T, [H|Buffer]). - -buffer_to_term(Buffer) -> - {ok, Term} = erl_parse:parse_term(lists:reverse(Buffer)), - Term. - -unquote(TokenChars, TokenLen) -> - lists:sublist(TokenChars, 2, TokenLen - 2). - -tokenize_atom(TokenChars, TokenLine) -> - try list_to_existing_atom(TokenChars) of - Atom -> {token, {atom, TokenLine, Atom}} - catch - error:badarg -> {error, "illegal atom " ++ TokenChars} - end. - -escape([$\\|Cs]) -> - do_escape(Cs); -escape([C|Cs]) -> - [C|escape(Cs)]; -escape([]) -> []. - -do_escape([O1,O2,O3|S]) when - O1 >= $0, O1 =< $7, O2 >= $0, O2 =< $7, O3 >= $0, O3 =< $7 -> - [(O1*8 + O2)*8 + O3 - 73*$0|escape(S)]; -do_escape([$^,C|Cs]) -> - [C band 31|escape(Cs)]; -do_escape([C|Cs]) when C >= $\000, C =< $\s -> - escape(Cs); -do_escape([C|Cs]) -> - [escape_char(C)|escape(Cs)]. - -escape_char($n) -> $\n; %\n = LF -escape_char($r) -> $\r; %\r = CR -escape_char($t) -> $\t; %\t = TAB -escape_char($v) -> $\v; %\v = VT -escape_char($b) -> $\b; %\b = BS -escape_char($f) -> $\f; %\f = FF -escape_char($e) -> $\e; %\e = ESC -escape_char($s) -> $\s; %\s = SPC -escape_char($d) -> $\d; %\d = DEL -escape_char(C) -> C. diff --git a/_build/default/plugins/jsx/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/jsx/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index 379d325a0f..0000000000 Binary files a/_build/default/plugins/jsx/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/jsx/CHANGES.md b/_build/default/plugins/jsx/CHANGES.md deleted file mode 100644 index 8f404be708..0000000000 --- a/_build/default/plugins/jsx/CHANGES.md +++ /dev/null @@ -1,214 +0,0 @@ -v2.8.2 - -* enable `debug_info` for rebar3 - -v2.8.1 - -* enable `debug_info` when used via mix -* accept `erlang:timestamp` as input to the parser - - -v2.8.0 - -* add `JSX_FORCE_MAPS` env var for forcing decoding to maps rather than - attempting to autodetect - -v2.7.2 - -* fix an issue where tuples were assumed to be jsx ast and not checked -* mask a `function_clause` error in encoder with a `badarg` error for api unity - -v2.7.1 - -* support for milliseconds in datetimes - -v2.7.0 - -* `return_tail` option -* fixes for edoc generation - -v2.6.2 - -* ensure maps are always enabled when compiling via mix - -v2.6.1 - -* hex.pm maintenance release - -v2.6.0 - -* equivalent to v2.5.3 but created for semver reasons - -v2.5.3 - -* add a `mix.exs` to be buildable by both mix and rebar -* minor README updates - -v2.5.2 - -* fix regression parsing <<"-0e...">> (thanks @c-bik) - -v2.5.1 - -* assume all datetimes are UTC time and add `Z` designator to indicate -* fix parsing issue with datetimes in arrays - -v2.5.0 - -* `consult/2` function for reading a file directly to a json term -* `maps_always` build flag for always returning maps on platforms - that support them -* dialyzer fixes - -v2.4.0 - -* enough performance improvements to justify a new version. 2-3x - speedup depending on mode of operation - -v2.3.1 - -* fixes an issue where astral plane json escape sequences were - inadvertently being converted to the unicode replacement - character - -v2.3 - -* switched to a faster implementation of string parsing in both - the decoder and encoder -* expand `uescape` option to the decoder -* allow control codes in json passed to decoder (contrary to the spec, - yes) - -v2.2 - -* `return_maps` option -* `uescape` option for 7-bit clean output -* add `Makefile` for slightly better `erlang.mk` compatibility -* add `maps_support/0` call to determine whether `jsx` was compiled - with support for maps or not - -v2.1.1 - -* faster generation of json via iolists -* `repeat_keys` option - -v2.1 - -* force the end of streams with `end_json` in addition to `end_stream` -* support for encoding erlang datetime tuples to iso8601 format -* allow a single trailing comma in objects and arrays - -v2.0.4 - -* more typespec adjustments - -v2.0.3 - -* update some typespecs to make them more comprehensive - -v2.0.2 - -* fixes travis-ci spec - -v2.0.1 - -* fix regression in output of empty objects/arrays - -v2.0 - -* jsx is much more pragmatic by default; common json errors are silently - ignored (and fixed). stricter parsing must be enabled with options -* add support for encoding otp 17.0's new maps data type -* removed `pre_encode` and `post_decode` options in favour of making jsx - functions easier to wrap and customize -* streaming behavior is now disabled by default and must be requested explicitly -* removed deprecated function names (`to_json`, `to_term`, `term_to_json`, etc) -* expanded test coverage - - -v1.4.5 - -* various fixes to typespecs uncovered by dialyzer -* allow integer keys during encoding -* convert atoms (other than `true`, `false` and `null`) to strings during encoding - -v1.4.4 - -* typespec for `json_term/0` fixed -* incorrect boolean shortcircuiting fixed in multibyte escape processing - -v1.4.3 - -* add empty rebar.config for mix build tool -* add `attempt_atom` option for decoding json objects -* fix a bug related to multibyte codepoints and streaming input -* add a missing error state in the encoder - -v1.4.2 - -* build apparatus cleaned up and streamlined -* new `{raw, <<"json goes here">>}` intermediate form to support direct generation of json -* bugfixes involving inappropriate exceptions from jsx functions - -v1.4.1 - -* fixes a bug with interaction between `dirty_strings` and even numbers of escape characters -* performance enhancements - -v1.4 - -* radically refactored decoder -* `dirty_strings` now behaves intuitively in decoding. bad codepoints, bad utf8, illegal characters and escapes (except `"` and `'` if `single_quoted_strings` is enabled) are ignored completely -* `incomplete_handler` & `error_handler` are now available for use, see documentation in README - -v1.3.3 - -* `pre_encode` now orders input in the order you'd expect - -v1.3.2 - -* `pre_encode` is now able to handle tuples *correctly* - -v1.3.1 - -* `pre_encode` is now able to handle tuples - -v1.3 - -* introduces `prettify/1` and `minify/1`, shortcuts for `format/2` -* introduce `encode/1,2` and `decode/1,2` as primary interface to built in tokenizers. `to_json/1,2` and `to_term/1,2` remain accessible but not advertised -* new `parser/3` function exposes syntactic analysis stage for use with user defined tokenizers -* improved documentation - -v1.2.1 - -* fixes incorrect handling of escaped forward slashes, thanks bob ippolito - -v1.2 - -* rewritten handling of string escaping to improve performance -* `pre_encode` and `post_decode` hooks, see README -* `relax` option - -v1.1.2 - -* add `dirty_strings` option -* more fixes for invalid unicode in strings - -v1.1.1 - -* fixes bug regarding handling of invalid unicode in R14Bxx - -v1.1 - -* improvements to string escaping and json generation performance - -v1.0.2 - -* fixes to function specs -* rewritten README -* `comments` option - -v1.0.1 - -* rebar fix diff --git a/_build/default/plugins/jsx/LICENSE b/_build/default/plugins/jsx/LICENSE deleted file mode 100644 index de1b470f38..0000000000 --- a/_build/default/plugins/jsx/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License - -Copyright (c) 2010-2013 alisdair sullivan - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/_build/default/plugins/jsx/hex_metadata.config b/_build/default/plugins/jsx/hex_metadata.config deleted file mode 100644 index e4aa92dabe..0000000000 --- a/_build/default/plugins/jsx/hex_metadata.config +++ /dev/null @@ -1,15 +0,0 @@ -{<<"app">>,<<"jsx">>}. -{<<"build_tools">>,[<<"rebar3">>]}. -{<<"description">>,<<"a streaming, evented json parsing toolkit">>}. -{<<"files">>, - [<<"src/jsx.app.src">>,<<"CHANGES.md">>,<<"LICENSE">>,<<"rebar.config">>, - <<"rebar.config.script">>,<<"src/jsx.erl">>,<<"src/jsx_config.erl">>, - <<"src/jsx_config.hrl">>,<<"src/jsx_consult.erl">>, - <<"src/jsx_decoder.erl">>,<<"src/jsx_encoder.erl">>, - <<"src/jsx_parser.erl">>,<<"src/jsx_to_json.erl">>, - <<"src/jsx_to_term.erl">>,<<"src/jsx_verify.erl">>]}. -{<<"licenses">>,[<<"MIT">>]}. -{<<"links">>,[]}. -{<<"name">>,<<"jsx">>}. -{<<"requirements">>,[]}. -{<<"version">>,<<"2.10.0">>}. diff --git a/_build/default/plugins/jsx/rebar.config b/_build/default/plugins/jsx/rebar.config deleted file mode 100644 index a6475089fd..0000000000 --- a/_build/default/plugins/jsx/rebar.config +++ /dev/null @@ -1,2 +0,0 @@ -{edoc_opts, [{preprocess, true}]}. -{erl_opts, [debug_info]}. diff --git a/_build/default/plugins/jsx/rebar.config.script b/_build/default/plugins/jsx/rebar.config.script deleted file mode 100644 index 5841b7d405..0000000000 --- a/_build/default/plugins/jsx/rebar.config.script +++ /dev/null @@ -1,15 +0,0 @@ -Def0 = case erlang:is_builtin(erlang, binary_to_integer, 1) andalso - erlang:is_builtin(erlang, binary_to_float, 1) of - true -> []; - false -> [{d, no_binary_to_whatever}] - end, -Def1 = case erlang:is_builtin(erlang, is_map, 1) of - true -> [{d, maps_support}|Def0]; - false -> Def0 - end, -Defs = case os:getenv("JSX_FORCE_MAPS") of - false -> Def1; - _ -> [{d, maps_always}|Def1] - end, -lists:keystore(erl_opts, 1, CONFIG, - {erl_opts, proplists:get_value(erl_opts, CONFIG, []) ++ Defs}). diff --git a/_build/default/plugins/jsx/src/jsx.app.src b/_build/default/plugins/jsx/src/jsx.app.src deleted file mode 100644 index b67880da9d..0000000000 --- a/_build/default/plugins/jsx/src/jsx.app.src +++ /dev/null @@ -1,11 +0,0 @@ -{application,jsx, - [{description,"a streaming, evented json parsing toolkit"}, - {vsn,"2.10.0"}, - {modules,[jsx,jsx_encoder,jsx_decoder,jsx_parser,jsx_to_json, - jsx_to_term,jsx_config,jsx_verify]}, - {registered,[]}, - {applications,[kernel,stdlib]}, - {env,[]}, - {files,["src","rebar.config","rebar.config.script", - "rebar.lockREADME.md","CHANGES.md","LICENSE"]}, - {licenses,["MIT"]}]}. diff --git a/_build/default/plugins/jsx/src/jsx.erl b/_build/default/plugins/jsx/src/jsx.erl deleted file mode 100644 index acdf420b4d..0000000000 --- a/_build/default/plugins/jsx/src/jsx.erl +++ /dev/null @@ -1,527 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 alisdair sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx). - --export([encode/1, encode/2, decode/1, decode/2]). --export([is_json/1, is_json/2, is_term/1, is_term/2]). --export([format/1, format/2, minify/1, prettify/1]). --export([consult/1, consult/2]). --export([encoder/3, decoder/3, parser/3]). --export([resume/3]). --export([maps_support/0]). - --export_type([json_term/0, json_text/0, token/0]). --export_type([encoder/0, decoder/0, parser/0, internal_state/0]). --export_type([config/0]). - - --ifdef(TEST). -%% data and helper functions for tests --export([test_cases/0, special_test_cases/0]). --export([init/1, handle_event/2]). --endif. - - --ifndef(maps_support). --type json_term() :: [{binary() | atom(), json_term()}] | [{},...] - | [json_term()] | [] - | true | false | null - | integer() | float() - | binary() | atom() - | calendar:datetime(). --endif. - --ifdef(maps_support). --type json_term() :: [{binary() | atom(), json_term()}] | [{},...] - | [json_term()] | [] - | map() - | true | false | null - | integer() | float() - | binary() | atom() - | calendar:datetime(). --endif. - --type json_text() :: binary(). - --type config() :: jsx_config:config(). - --spec encode(Source::json_term()) -> json_text(). - -encode(Source) -> encode(Source, []). - --spec encode(Source::json_term(), Config::jsx_to_json:config()) -> json_text() | {incomplete, encoder()}. - -encode(Source, Config) -> jsx_to_json:to_json(Source, Config). - - --spec decode(Source::json_text()) -> json_term(). - -decode(Source) -> decode(Source, []). - --spec decode(Source::json_text(), Config::jsx_to_term:config()) -> json_term() | {incomplete, decoder()}. - -decode(Source, Config) -> jsx_to_term:to_term(Source, Config). - - --spec format(Source::json_text()) -> json_text(). - -format(Source) -> format(Source, []). - --spec format(Source::json_text(), Config::jsx_to_json:config()) -> json_text() | {incomplete, decoder()}. - -format(Source, Config) -> jsx_to_json:format(Source, Config). - - --spec minify(Source::json_text()) -> json_text(). - -minify(Source) -> format(Source, []). - - --spec prettify(Source::json_text()) -> json_text(). - -prettify(Source) -> format(Source, [space, {indent, 2}]). - - --spec is_json(Source::any()) -> boolean(). - -is_json(Source) -> is_json(Source, []). - --spec is_json(Source::any(), Config::jsx_verify:config()) -> boolean() | {incomplete, decoder()}. - -is_json(Source, Config) -> jsx_verify:is_json(Source, Config). - - --spec is_term(Source::any()) -> boolean(). - -is_term(Source) -> is_term(Source, []). - --spec is_term(Source::any(), Config::jsx_verify:config()) -> boolean() | {incomplete, encoder()}. - -is_term(Source, Config) -> jsx_verify:is_term(Source, Config). - - --spec consult(File::file:name_all()) -> list(json_term()). - -consult(File) -> consult(File, []). - --spec consult(File::file:name_all(), Config::jsx_to_term:config()) -> list(json_term()). - -consult(File, Config) -> jsx_consult:consult(File, Config). - - --type decoder() :: fun((json_text() | end_stream | end_json) -> any()). - --spec decoder(Handler::module(), State::any(), Config::list()) -> decoder(). - -decoder(Handler, State, Config) -> jsx_decoder:decoder(Handler, State, Config). - - --type encoder() :: fun((json_term() | end_stream | end_json) -> any()). - --spec encoder(Handler::module(), State::any(), Config::list()) -> encoder(). - -encoder(Handler, State, Config) -> jsx_encoder:encoder(Handler, State, Config). - - --type token() :: [token()] - | start_object - | end_object - | start_array - | end_array - | {key, binary()} - | {string, binary()} - | binary() - | {number, integer() | float()} - | {integer, integer()} - | {float, float()} - | integer() - | float() - | {literal, true} - | {literal, false} - | {literal, null} - | true - | false - | null - | end_json. - - --type parser() :: fun((token() | end_stream) -> any()). - --spec parser(Handler::module(), State::any(), Config::list()) -> parser(). - -parser(Handler, State, Config) -> jsx_parser:parser(Handler, State, Config). - --opaque internal_state() :: tuple(). - --spec resume(Term::json_text() | token(), InternalState::internal_state(), Config::list()) -> any(). - -resume(Term, {decoder, State, Handler, Acc, Stack}, Config) -> - jsx_decoder:resume(Term, State, Handler, Acc, Stack, jsx_config:parse_config(Config)); -resume(Term, {parser, State, Handler, Stack}, Config) -> - jsx_parser:resume(Term, State, Handler, Stack, jsx_config:parse_config(Config)). - - --spec maps_support() -> boolean(). - --ifndef(maps_support). -maps_support() -> false. --endif. --ifdef(maps_support). -maps_support() -> true. --endif. - - --ifdef(TEST). - --include_lib("eunit/include/eunit.hrl"). - - -%% test handler -init([]) -> []. - -handle_event(end_json, State) -> lists:reverse([end_json] ++ State); -handle_event(Event, State) -> [Event] ++ State. - - -test_cases() -> - empty_array() - ++ nested_array() - ++ empty_object() - ++ nested_object() - ++ strings() - ++ literals() - ++ integers() - ++ floats() - ++ compound_object(). - -%% segregate these so we can skip them in `jsx_to_term` -special_test_cases() -> special_objects() ++ special_array(). - - -empty_array() -> [{"[]", <<"[]">>, [], [start_array, end_array]}]. - - -nested_array() -> - [{ - "[[[]]]", - <<"[[[]]]">>, - [[[]]], - [start_array, start_array, start_array, end_array, end_array, end_array] - }]. - - -empty_object() -> [{"{}", <<"{}">>, [{}], [start_object, end_object]}]. - - -nested_object() -> - [{ - "{\"key\":{\"key\":{}}}", - <<"{\"key\":{\"key\":{}}}">>, - [{<<"key">>, [{<<"key">>, [{}]}]}], - [ - start_object, - {key, <<"key">>}, - start_object, - {key, <<"key">>}, - start_object, - end_object, - end_object, - end_object - ] - }]. - - -naked_strings() -> - Raw = [ - "", - "hello world" - ], - [ - { - String, - <<"\"", (list_to_binary(String))/binary, "\"">>, - list_to_binary(String), - [{string, list_to_binary(String)}] - } - || String <- Raw - ]. - - -strings() -> - naked_strings() - ++ [ wrap_with_array(Test) || Test <- naked_strings() ] - ++ [ wrap_with_object(Test) || Test <- naked_strings() ]. - - -naked_integers() -> - Raw = [ - 1, 2, 3, - 127, 128, 129, - 255, 256, 257, - 65534, 65535, 65536, - 18446744073709551616, - 18446744073709551617 - ], - [ - { - integer_to_list(X), - list_to_binary(integer_to_list(X)), - X, - [{integer, X}] - } - || X <- Raw ++ [ -1 * Y || Y <- Raw ] ++ [0] - ]. - - -integers() -> - naked_integers() - ++ [ wrap_with_array(Test) || Test <- naked_integers() ] - ++ [ wrap_with_object(Test) || Test <- naked_integers() ]. - - -naked_floats() -> - Raw = [ - 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, - 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, - 1234567890.0987654321, - 0.0e0, - 1234567890.0987654321e16, - 0.1e0, 0.1e1, 0.1e2, 0.1e4, 0.1e8, 0.1e16, 0.1e308, - 1.0e0, 1.0e1, 1.0e2, 1.0e4, 1.0e8, 1.0e16, 1.0e308, - 2.2250738585072014e-308, %% min normalized float - 1.7976931348623157e308, %% max normalized float - 5.0e-324, %% min denormalized float - 2.225073858507201e-308 %% max denormalized float - ], - [ - { - sane_float_to_list(X), - list_to_binary(sane_float_to_list(X)), - X, - [{float, X}] - } - || X <- Raw ++ [ -1 * Y || Y <- Raw ] - ]. - - -floats() -> - naked_floats() - ++ [ wrap_with_array(Test) || Test <- naked_floats() ] - ++ [ wrap_with_object(Test) || Test <- naked_floats() ]. - - -naked_literals() -> - [ - { - atom_to_list(Literal), - atom_to_binary(Literal, unicode), - Literal, - [{literal, Literal}] - } - || Literal <- [true, false, null] - ]. - - -literals() -> - naked_literals() - ++ [ wrap_with_array(Test) || Test <- naked_literals() ] - ++ [ wrap_with_object(Test) || Test <- naked_literals() ]. - - -compound_object() -> - [{ - "[{\"alpha\":[1,2,3],\"beta\":{\"alpha\":[1.0,2.0,3.0],\"beta\":[true,false]}},[{}]]", - <<"[{\"alpha\":[1,2,3],\"beta\":{\"alpha\":[1.0,2.0,3.0],\"beta\":[true,false]}},[{}]]">>, - [[{<<"alpha">>, [1, 2, 3]}, {<<"beta">>, [{<<"alpha">>, [1.0, 2.0, 3.0]}, {<<"beta">>, [true, false]}]}], [[{}]]], - [ - start_array, - start_object, - {key, <<"alpha">>}, - start_array, - {integer, 1}, - {integer, 2}, - {integer, 3}, - end_array, - {key, <<"beta">>}, - start_object, - {key, <<"alpha">>}, - start_array, - {float, 1.0}, - {float, 2.0}, - {float, 3.0}, - end_array, - {key, <<"beta">>}, - start_array, - {literal, true}, - {literal, false}, - end_array, - end_object, - end_object, - start_array, - start_object, - end_object, - end_array, - end_array - ] - }]. - - -special_objects() -> - [ - { - "[{key, atom}]", - <<"{\"key\":\"atom\"}">>, - [{key, atom}], - [start_object, {key, <<"key">>}, {string, <<"atom">>}, end_object] - }, - { - "[{1, true}]", - <<"{\"1\":true}">>, - [{1, true}], - [start_object, {key, <<"1">>}, {literal, true}, end_object] - } - ]. - - -special_array() -> - [ - { - "[foo, bar]", - <<"[\"foo\",\"bar\"]">>, - [foo, bar], - [start_array, {string, <<"foo">>}, {string, <<"bar">>}, end_array] - } - ]. - - -wrap_with_array({Title, JSON, Term, Events}) -> - { - "[" ++ Title ++ "]", - <<"[", JSON/binary, "]">>, - [Term], - [start_array] ++ Events ++ [end_array] - }. - - -wrap_with_object({Title, JSON, Term, Events}) -> - { - "{\"key\":" ++ Title ++ "}", - <<"{\"key\":", JSON/binary, "}">>, - [{<<"key">>, Term}], - [start_object, {key, <<"key">>}] ++ Events ++ [end_object] - }. - - -sane_float_to_list(X) -> - [Output] = io_lib:format("~p", [X]), - Output. - - -incremental_decode(JSON) -> - Final = lists:foldl( - fun(Byte, Decoder) -> {incomplete, F} = Decoder(Byte), F end, - decoder(jsx, [], [stream]), - json_to_bytes(JSON) - ), - Final(end_stream). - - -incremental_parse(Events) -> - Final = lists:foldl( - fun(Event, Parser) -> {incomplete, F} = Parser(Event), F end, - parser(?MODULE, [], [stream]), - lists:map(fun(X) -> [X] end, Events) - ), - Final(end_stream). - - -%% used to convert a json text into a list of codepoints to be incrementally -%% parsed -json_to_bytes(JSON) -> json_to_bytes(JSON, []). - -json_to_bytes(<<>>, Acc) -> [<<>>] ++ lists:reverse(Acc); -json_to_bytes(<>, Acc) -> json_to_bytes(Rest, [<>] ++ Acc). - - -%% actual tests! -decode_test_() -> - Data = test_cases(), - [{Title, ?_assertEqual(Events ++ [end_json], (decoder(?MODULE, [], []))(JSON))} - || {Title, JSON, _, Events} <- Data - ] ++ - [{Title ++ " (incremental)", ?_assertEqual(Events ++ [end_json], incremental_decode(JSON))} - || {Title, JSON, _, Events} <- Data - ]. - - -parse_test_() -> - Data = test_cases(), - [{Title, ?_assertEqual(Events ++ [end_json], (parser(?MODULE, [], []))(Events ++ [end_json]))} - || {Title, _, _, Events} <- Data - ] ++ - [{Title ++ " (incremental)", ?_assertEqual(Events ++ [end_json], incremental_parse(Events))} - || {Title, _, _, Events} <- Data - ]. - - -encode_test_() -> - Data = test_cases(), - [ - { - Title, ?_assertEqual( - Events ++ [end_json], - (jsx:encoder(jsx, [], []))(Term) - ) - } || {Title, _, Term, Events} <- Data - ]. - -end_stream_test_() -> - Tokens = [start_object, end_object, end_json], - [ - {"encoder end_stream", ?_assertEqual( - Tokens, - begin - {incomplete, F} = (jsx:parser(jsx, [], [stream]))([start_object, end_object]), - F(end_stream) - end - )}, - {"encoder end_json", ?_assertEqual( - Tokens, - begin - {incomplete, F} = (jsx:parser(jsx, [], [stream]))([start_object, end_object]), - F(end_json) - end - )}, - {"decoder end_stream", ?_assertEqual( - Tokens, - begin {incomplete, F} = (jsx:decoder(jsx, [], [stream]))(<<"{}">>), F(end_stream) end - )}, - {"decoder end_json", ?_assertEqual( - Tokens, - begin {incomplete, F} = (jsx:decoder(jsx, [], [stream]))(<<"{}">>), F(end_json) end - )} - ]. - - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_config.erl b/_build/default/plugins/jsx/src/jsx_config.erl deleted file mode 100644 index 47cbcf72be..0000000000 --- a/_build/default/plugins/jsx/src/jsx_config.erl +++ /dev/null @@ -1,346 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 alisdair sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_config). - --export([parse_config/1]). --export([config_to_list/1]). --export([extract_config/1, valid_flags/0]). - --ifdef(TEST). --export([fake_error_handler/3]). --endif. - --include("jsx_config.hrl"). - --type handler_type(Handler) :: - fun((jsx:json_text() | end_stream | - jsx:json_term(), - {decoder, any(), module(), null | list(), list()} | - {parser, any(), module(), list()} | - {encoder, any(), module()}, - list({pre_encode, fun((any()) -> any())} | - {error_handler, Handler} | - {incomplete_handler, Handler} | - atom())) -> any()). --type handler() :: handler_type(handler()). --export_type([handler/0]). - --type config() :: #config{}. --export_type([config/0]). - -%% parsing of jsx config --spec parse_config(Config::proplists:proplist()) -> config(). - -parse_config(Config) -> parse_config(Config, #config{}). - -parse_config([], Config) -> Config; -parse_config([escaped_forward_slashes|Rest], Config) -> - parse_config(Rest, Config#config{escaped_forward_slashes=true}); -parse_config([escaped_strings|Rest], Config) -> - parse_config(Rest, Config#config{escaped_strings=true}); -parse_config([unescaped_jsonp|Rest], Config) -> - parse_config(Rest, Config#config{unescaped_jsonp=true}); -parse_config([dirty_strings|Rest], Config) -> - parse_config(Rest, Config#config{dirty_strings=true}); -parse_config([multi_term|Rest], Config) -> - parse_config(Rest, Config#config{multi_term=true}); -parse_config([return_tail|Rest], Config) -> - parse_config(Rest, Config#config{return_tail=true}); -%% retained for backwards compat, now does nothing however -parse_config([repeat_keys|Rest], Config) -> - parse_config(Rest, Config); -parse_config([uescape|Rest], Config) -> - parse_config(Rest, Config#config{uescape=true}); -parse_config([strict|Rest], Config) -> - parse_config(Rest, Config#config{ - strict_comments=true, - strict_commas=true, - strict_utf8=true, - strict_single_quotes=true, - strict_escapes=true, - strict_control_codes=true - }); -parse_config([{strict, Strict}|Rest], Config) -> - parse_strict(Strict, Rest, Config); -parse_config([stream|Rest], Config) -> - parse_config(Rest, Config#config{stream=true}); -parse_config([{error_handler, ErrorHandler}|Rest] = Options, Config) when is_function(ErrorHandler, 3) -> - case Config#config.error_handler of - false -> parse_config(Rest, Config#config{error_handler=ErrorHandler}) - ; _ -> erlang:error(badarg, [Options, Config]) - end; -parse_config([{incomplete_handler, IncompleteHandler}|Rest] = Options, Config) when is_function(IncompleteHandler, 3) -> - case Config#config.incomplete_handler of - false -> parse_config(Rest, Config#config{incomplete_handler=IncompleteHandler}) - ; _ -> erlang:error(badarg, [Options, Config]) - end; -parse_config(_Options, _Config) -> erlang:error(badarg). - - -parse_strict([], Rest, Config) -> parse_config(Rest, Config); -parse_strict([comments|Strict], Rest, Config) -> - parse_strict(Strict, Rest, Config#config{strict_comments=true}); -parse_strict([trailing_commas|Strict], Rest, Config) -> - parse_strict(Strict, Rest, Config#config{strict_commas=true}); -parse_strict([utf8|Strict], Rest, Config) -> - parse_strict(Strict, Rest, Config#config{strict_utf8=true}); -parse_strict([single_quotes|Strict], Rest, Config) -> - parse_strict(Strict, Rest, Config#config{strict_single_quotes=true}); -parse_strict([escapes|Strict], Rest, Config) -> - parse_strict(Strict, Rest, Config#config{strict_escapes=true}); -parse_strict([control_codes|Strict], Rest, Config) -> - parse_strict(Strict, Rest, Config#config{strict_control_codes=true}); -parse_strict(_Strict, _Rest, _Config) -> - erlang:error(badarg). - - - --spec config_to_list(Config::config()) -> proplists:proplist(). - -config_to_list(Config) -> - reduce_config(lists:map( - fun ({error_handler, F}) -> {error_handler, F}; - ({incomplete_handler, F}) -> {incomplete_handler, F}; - ({Key, true}) -> Key - end, - lists:filter( - fun({_, false}) -> false; (_) -> true end, - lists:zip(record_info(fields, config), tl(tuple_to_list(Config))) - ) - )). - - -reduce_config(Input) -> reduce_config(Input, [], []). - -reduce_config([], Output, Strict) -> - case length(Strict) of - 0 -> lists:reverse(Output); - 5 -> lists:reverse(Output) ++ [strict]; - _ -> lists:reverse(Output) ++ [{strict, lists:reverse(Strict)}] - end; -reduce_config([strict_comments|Input], Output, Strict) -> - reduce_config(Input, Output, [comments] ++ Strict); -reduce_config([strict_utf8|Input], Output, Strict) -> - reduce_config(Input, Output, [utf8] ++ Strict); -reduce_config([strict_single_quotes|Input], Output, Strict) -> - reduce_config(Input, Output, [single_quotes] ++ Strict); -reduce_config([strict_escapes|Input], Output, Strict) -> - reduce_config(Input, Output, [escapes] ++ Strict); -reduce_config([strict_control_codes|Input], Output, Strict) -> - reduce_config(Input, Output, [control_codes] ++ Strict); -reduce_config([Else|Input], Output, Strict) -> - reduce_config(Input, [Else] ++ Output, Strict). - - --spec valid_flags() -> [atom()]. - -valid_flags() -> - [ - escaped_forward_slashes, - escaped_strings, - unescaped_jsonp, - dirty_strings, - multi_term, - return_tail, - repeat_keys, - strict, - stream, - uescape, - error_handler, - incomplete_handler - ]. - - --spec extract_config(Config::proplists:proplist()) -> proplists:proplist(). - -extract_config(Config) -> - extract_parser_config(Config, []). - -extract_parser_config([], Acc) -> Acc; -extract_parser_config([{K,V}|Rest], Acc) -> - case lists:member(K, valid_flags()) of - true -> extract_parser_config(Rest, [{K,V}] ++ Acc) - ; false -> extract_parser_config(Rest, Acc) - end; -extract_parser_config([K|Rest], Acc) -> - case lists:member(K, valid_flags()) of - true -> extract_parser_config(Rest, [K] ++ Acc) - ; false -> extract_parser_config(Rest, Acc) - end. - - -%% eunit tests --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -config_test_() -> - [ - {"all flags", - ?_assertEqual( - #config{escaped_forward_slashes = true, - escaped_strings = true, - unescaped_jsonp = true, - dirty_strings = true, - multi_term = true, - return_tail = true, - strict_comments = true, - strict_commas = true, - strict_utf8 = true, - strict_single_quotes = true, - strict_escapes = true, - strict_control_codes = true, - stream = true, - uescape = true - }, - parse_config([dirty_strings, - escaped_forward_slashes, - escaped_strings, - unescaped_jsonp, - multi_term, - return_tail, - repeat_keys, - strict, - stream, - uescape - ]) - ) - }, - {"strict flag", - ?_assertEqual( - #config{strict_comments = true, - strict_commas = true, - strict_utf8 = true, - strict_single_quotes = true, - strict_escapes = true, - strict_control_codes = true - }, - parse_config([strict]) - ) - }, - {"strict selective", - ?_assertEqual( - #config{strict_comments = true}, - parse_config([{strict, [comments]}]) - ) - }, - {"strict expanded", - ?_assertEqual( - #config{strict_comments = true, - strict_utf8 = true, - strict_single_quotes = true, - strict_escapes = true - }, - parse_config([{strict, [comments, utf8, single_quotes, escapes]}]) - ) - }, - {"error_handler flag", ?_assertEqual( - #config{error_handler=fun ?MODULE:fake_error_handler/3}, - parse_config([{error_handler, fun ?MODULE:fake_error_handler/3}]) - )}, - {"two error_handlers defined", ?_assertError( - badarg, - parse_config([ - {error_handler, fun(_, _, _) -> true end}, - {error_handler, fun(_, _, _) -> false end} - ]) - )}, - {"incomplete_handler flag", ?_assertEqual( - #config{incomplete_handler=fun ?MODULE:fake_error_handler/3}, - parse_config([{incomplete_handler, fun ?MODULE:fake_error_handler/3}]) - )}, - {"two incomplete_handlers defined", ?_assertError( - badarg, - parse_config([ - {incomplete_handler, fun(_, _, _) -> true end}, - {incomplete_handler, fun(_, _, _) -> false end} - ]) - )}, - {"bad option flag", ?_assertError(badarg, parse_config([this_flag_does_not_exist]))} - ]. - - -config_to_list_test_() -> - [ - {"empty config", ?_assertEqual( - [], - config_to_list(#config{}) - )}, - {"all flags", ?_assertEqual( - [dirty_strings, - escaped_forward_slashes, - escaped_strings, - multi_term, - stream, - uescape, - unescaped_jsonp, - strict - ], - config_to_list( - #config{escaped_forward_slashes = true, - escaped_strings = true, - unescaped_jsonp = true, - dirty_strings = true, - multi_term = true, - strict_comments = true, - strict_utf8 = true, - strict_single_quotes = true, - strict_escapes = true, - strict_control_codes = true, - stream = true, - uescape = true - } - ) - )}, - {"single strict", ?_assertEqual( - [{strict, [comments]}], - config_to_list(#config{strict_comments = true}) - )}, - {"multiple strict", ?_assertEqual( - [{strict, [utf8, single_quotes, escapes]}], - config_to_list(#config{strict_utf8 = true, strict_single_quotes = true, strict_escapes = true}) - )}, - {"all strict", ?_assertEqual( - [strict], - config_to_list(#config{strict_comments = true, - strict_utf8 = true, - strict_single_quotes = true, - strict_escapes = true, - strict_control_codes = true}) - )}, - {"error handler", ?_assertEqual( - [{error_handler, fun ?MODULE:fake_error_handler/3}], - config_to_list(#config{error_handler=fun ?MODULE:fake_error_handler/3}) - )}, - {"incomplete handler", ?_assertEqual( - [{incomplete_handler, fun ?MODULE:fake_error_handler/3}], - config_to_list(#config{incomplete_handler=fun ?MODULE:fake_error_handler/3}) - )} - ]. - - -fake_error_handler(_, _, _) -> ok. - - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_config.hrl b/_build/default/plugins/jsx/src/jsx_config.hrl deleted file mode 100644 index c89963c502..0000000000 --- a/_build/default/plugins/jsx/src/jsx_config.hrl +++ /dev/null @@ -1,18 +0,0 @@ --record(config, { - dirty_strings = false :: boolean(), - escaped_forward_slashes = false :: boolean(), - escaped_strings = false :: boolean(), - multi_term = false :: boolean(), - strict_comments = false :: boolean(), - strict_commas = false :: boolean(), - strict_utf8 = false :: boolean(), - strict_single_quotes = false :: boolean(), - strict_escapes = false :: boolean(), - strict_control_codes = false :: boolean(), - stream = false :: boolean(), - return_tail = false :: boolean(), - uescape = false :: boolean(), - unescaped_jsonp = false :: boolean(), - error_handler = false :: false | jsx_config:handler(), - incomplete_handler = false :: false | jsx_config:handler() -}). diff --git a/_build/default/plugins/jsx/src/jsx_consult.erl b/_build/default/plugins/jsx/src/jsx_consult.erl deleted file mode 100644 index b1a44246e6..0000000000 --- a/_build/default/plugins/jsx/src/jsx_consult.erl +++ /dev/null @@ -1,99 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2015 Alisdair Sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_consult). - --export([consult/2]). --export([init/1, reset/1, handle_event/2]). - - --record(config, { - labels = binary, - return_maps = false -}). - --type config() :: list(). --export_type([config/0]). - --ifndef(maps_support). --type json_value() :: list(json_value()) - | list({binary() | atom(), json_value()}) - | true - | false - | null - | integer() - | float() - | binary(). --endif. - --ifdef(maps_support). --type json_value() :: list(json_value()) - | map() - | true - | false - | null - | integer() - | float() - | binary(). --endif. - - --ifdef(maps_always). -opts(Opts) -> [return_maps, multi_term] ++ Opts. --endif. --ifndef(maps_always). -opts(Opts) -> [multi_term] ++ Opts. --endif. - --spec consult(File::file:name_all(), Config::config()) -> [json_value()]. - -consult(File, Config) when is_list(Config) -> - case file:read_file(File) of - {ok, Bin} -> - {Final, _, _} = (jsx:decoder( - ?MODULE, - opts(Config), - jsx_config:extract_config(opts(Config)) - ))(Bin), - lists:reverse(Final); - {error, _} -> erlang:error(badarg) - end. - - --type state() :: {[], proplists:proplist(), {list(), #config{}}}. --spec init(Config::proplists:proplist()) -> state(). - -init(Config) -> {[], Config, jsx_to_term:start_term(Config)}. - - --spec reset(State::state()) -> state(). - -reset({Acc, Config, _}) -> {Acc, Config, jsx_to_term:start_term(Config)}. - - --spec handle_event(Event::any(), State::state()) -> state(). - -handle_event(end_json, {Acc, Config, State}) -> - {[jsx_to_term:get_value(State)] ++ Acc, Config, State}; -handle_event(Event, {Acc, Config, State}) -> - {Acc, Config, jsx_to_term:handle_event(Event, State)}. diff --git a/_build/default/plugins/jsx/src/jsx_decoder.erl b/_build/default/plugins/jsx/src/jsx_decoder.erl deleted file mode 100644 index 1a834d9181..0000000000 --- a/_build/default/plugins/jsx/src/jsx_decoder.erl +++ /dev/null @@ -1,1916 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 alisdair sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_decoder). - -%% inline handle_event, format_number and maybe_replace --compile({inline, [handle_event/3]}). --compile({inline, [format_number/1]}). --compile({inline, [maybe_replace/2]}). --compile({inline, [doublequote/5, singlequote/5]}). - --export([decoder/3, resume/6]). - - --spec decoder(Handler::module(), State::any(), Config::list()) -> jsx:decoder(). - -decoder(Handler, State, Config) -> - fun(JSON) -> start(JSON, {Handler, Handler:init(State)}, [], jsx_config:parse_config(Config)) end. - - -%% resume allows continuation from interrupted decoding without having to explicitly export -%% all states --spec resume( - Rest::binary(), - State::atom(), - Handler::{atom(), any()}, - Acc::any(), - Stack::list(atom()), - Config::jsx:config() - ) -> jsx:decoder() | {incomplete, jsx:decoder()}. - -resume(Rest, State, Handler, Acc, Stack, Config) -> - case State of - start -> start(Rest, Handler, Stack, Config); - value -> value(Rest, Handler, Stack, Config); - object -> object(Rest, Handler, Stack, Config); - array -> array(Rest, Handler, Stack, Config); - colon -> colon(Rest, Handler, Stack, Config); - key -> key(Rest, Handler, Stack, Config); - string -> string(Rest, Handler, Acc, Stack, Config); - number -> number(Rest, Handler, Acc, Stack, Config); - true -> true(Rest, Handler, Stack, Config); - false -> false(Rest, Handler, Stack, Config); - null -> null(Rest, Handler, Stack, Config); - comment -> comment(Rest, Handler, Acc, Stack, Config); - maybe_done -> maybe_done(Rest, Handler, Stack, Config); - done -> done(Rest, Handler, Stack, Config) - end. - - --include("jsx_config.hrl"). - - -%% whitespace --define(space, 16#20). --define(tab, 16#09). --define(cr, 16#0D). --define(newline, 16#0A). - -%% object delimiters --define(start_object, 16#7B). --define(end_object, 16#7D). - -%% array delimiters --define(start_array, 16#5B). --define(end_array, 16#5D). - -%% kv seperator --define(comma, 16#2C). --define(doublequote, 16#22). --define(singlequote, 16#27). --define(colon, 16#3A). - -%% string escape sequences --define(rsolidus, 16#5C). --define(solidus, 16#2F). - -%% math --define(zero, 16#30). --define(decimalpoint, 16#2E). --define(negative, 16#2D). --define(positive, 16#2B). - -%% comments --define(star, 16#2A). - - -%% some useful guards --define(is_hex(Symbol), - (Symbol >= $a andalso Symbol =< $f) orelse - (Symbol >= $A andalso Symbol =< $F) orelse - (Symbol >= $0 andalso Symbol =< $9) -). - --define(is_nonzero(Symbol), - Symbol >= $1 andalso Symbol =< $9 -). - - -%% error is a macro so the stack trace shows the error site when possible --ifndef(error). --define(error(State, Bin, Handler, Acc, Stack, Config), - case Config#config.error_handler of - false -> erlang:error(badarg); - F -> F(Bin, {decoder, State, Handler, Acc, Stack}, jsx_config:config_to_list(Config)) - end -). --define(error(State, Bin, Handler, Stack, Config), - ?error(State, Bin, Handler, null, Stack, Config) -). --endif. - - -incomplete(State, Rest, Handler, Stack, Config = #config{stream=false}) -> - ?error(State, Rest, Handler, Stack, Config); -incomplete(State, Rest, Handler, Stack, Config) -> - incomplete(State, Rest, Handler, unused, Stack, Config). - - -incomplete(State, Rest, Handler, Acc, Stack, Config = #config{stream=false}) -> - ?error(State, Rest, Handler, Acc, Stack, Config); -incomplete(State, Rest, Handler, Acc, Stack, Config = #config{incomplete_handler=false}) -> - {incomplete, fun(Stream) when is_binary(Stream) -> - resume(<>, State, Handler, Acc, Stack, Config); - (End) when End == end_stream; End == end_json -> - case resume(<>, State, Handler, Acc, Stack, Config#config{stream=false}) of - {incomplete, _} -> ?error(State, Rest, Handler, Acc, Stack, Config); - Else -> Else - end - end - }; -incomplete(State, Rest, Handler, Acc, Stack, Config = #config{incomplete_handler=F}) -> - F(Rest, {decoder, State, Handler, Acc, Stack}, jsx_config:config_to_list(Config)). - - -handle_event(Event, {Handler, State}, _Config) -> {Handler, Handler:handle_event(Event, State)}. - - -start(<<16#ef, 16#bb, 16#bf, Rest/binary>>, Handler, Stack, Config) -> - value(Rest, Handler, Stack, Config); -start(<<16#ef, 16#bb>>, Handler, Stack, Config) -> - incomplete(start, <<16#ef, 16#bb>>, Handler, Stack, Config); -start(<<16#ef>>, Handler, Stack, Config) -> - incomplete(start, <<16#ef>>, Handler, Stack, Config); -start(<<>>, Handler, Stack, Config) -> - incomplete(start, <<>>, Handler, Stack, Config); -start(Bin, Handler, Stack, Config) -> - value(Bin, Handler, Stack, Config). - - -value(<>, Handler, Stack, Config) -> - string(Rest, Handler, Stack, Config); -value(<>, Handler, Stack, Config) -> - value(Rest, Handler, Stack, Config); -value(<>, Handler, Stack, Config) -> - object(Rest, handle_event(start_object, Handler, Config), [key|Stack], Config); -value(<>, Handler, Stack, Config) -> - array(Rest, handle_event(start_array, Handler, Config), [array|Stack], Config); -value(<<$t, $r, $u, $e, Rest/binary>>, Handler, Stack, Config) -> - maybe_done(Rest, handle_event({literal, true}, Handler, Config), Stack, Config); -value(<<$f, $a, $l, $s, $e, Rest/binary>>, Handler, Stack, Config) -> - maybe_done(Rest, handle_event({literal, false}, Handler, Config), Stack, Config); -value(<<$n, $u, $l, $l, Rest/binary>>, Handler, Stack, Config) -> - maybe_done(Rest, handle_event({literal, null}, Handler, Config), Stack, Config); -value(<>, Handler, Stack, Config) -> - number(Rest, Handler, [?zero], [zero|Stack], Config); -value(<<$1, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$1], [integer|Stack], Config); -value(<<$2, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$2], [integer|Stack], Config); -value(<<$3, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$3], [integer|Stack], Config); -value(<<$4, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$4], [integer|Stack], Config); -value(<<$5, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$5], [integer|Stack], Config); -value(<<$6, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$6], [integer|Stack], Config); -value(<<$7, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$7], [integer|Stack], Config); -value(<<$8, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$8], [integer|Stack], Config); -value(<<$9, Rest/binary>>, Handler, Stack, Config) -> - number(Rest, Handler, [$9], [integer|Stack], Config); -value(<>, Handler, Stack, Config) -> - number(Rest, Handler, [$-], [negative|Stack], Config); -value(<>, Handler, Stack, Config) -> - value(Rest, Handler, Stack, Config); -value(<<$t, Rest/binary>>, Handler, Stack, Config) -> - true(Rest, Handler, Stack, Config); -value(<<$f, Rest/binary>>, Handler, Stack, Config) -> - false(Rest, Handler, Stack, Config); -value(<<$n, Rest/binary>>, Handler, Stack, Config) -> - null(Rest, Handler, Stack, Config); -value(<>, Handler, Stack, Config) -> - value(Rest, Handler, Stack, Config); -value(<>, Handler, Stack, Config) -> - value(Rest, Handler, Stack, Config); -value(<>, Handler, Stack, Config=#config{strict_single_quotes=false}) -> - string(Rest, Handler, [singlequote|Stack], Config); -value(<> = Rest, Handler, Stack, Config=#config{strict_commas=false}) -> - maybe_done(Rest, Handler, Stack, Config); -value(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - ?error(value, <>, Handler, Stack, Config); -value(<>, Handler, Stack, Config) -> - comment(Rest, Handler, value, [comment|Stack], Config); -value(<>, Handler, Stack, Config) -> - comment(Rest, Handler, value, [multicomment|Stack], Config); -value(<>, Handler, Stack, Config) -> - incomplete(value, <>, Handler, Stack, Config); -value(<<>>, Handler, Stack, Config) -> - incomplete(value, <<>>, Handler, Stack, Config); -value(Bin, Handler, Stack, Config) -> - ?error(value, Bin, Handler, Stack, Config). - - -object(<>, Handler, Stack, Config) -> - string(Rest, Handler, Stack, Config); -object(<>, Handler, Stack, Config) -> - object(Rest, Handler, Stack, Config); -object(<>, Handler, [key|Stack], Config) -> - maybe_done(Rest, handle_event(end_object, Handler, Config), Stack, Config); -object(<>, Handler, Stack, Config) -> - object(Rest, Handler, Stack, Config); -object(<>, Handler, Stack, Config) -> - object(Rest, Handler, Stack, Config); -object(<>, Handler, Stack, Config) -> - object(Rest, Handler, Stack, Config); -object(<>, Handler, Stack, Config=#config{strict_single_quotes=false}) -> - string(Rest, Handler, [singlequote|Stack], Config); -object(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - ?error(object, <>, Handler, Stack, Config); -object(<>, Handler, Stack, Config) -> - comment(Rest, Handler, object, [comment|Stack], Config); -object(<>, Handler, Stack, Config) -> - comment(Rest, Handler, object, [multicomment|Stack], Config); -object(<>, Handler, Stack, Config) -> - incomplete(object, <>, Handler, Stack, Config); -object(<<>>, Handler, Stack, Config) -> - incomplete(object, <<>>, Handler, Stack, Config); -object(Bin, Handler, Stack, Config) -> - ?error(object, Bin, Handler, Stack, Config). - - -array(<>, Handler, [array|Stack], Config) -> - maybe_done(Rest, handle_event(end_array, Handler, Config), Stack, Config); -array(<>, Handler, Stack, Config) -> - array(Rest, Handler, Stack, Config); -array(<>, Handler, Stack, Config) -> - array(Rest, Handler, Stack, Config); -array(<>, Handler, Stack, Config) -> - array(Rest, Handler, Stack, Config); -array(<>, Handler, Stack, Config) -> - array(Rest, Handler, Stack, Config); -array(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - value(<>, Handler, Stack, Config); -array(<>, Handler, Stack, Config) -> - comment(Rest, Handler, array, [comment|Stack], Config); -array(<>, Handler, Stack, Config) -> - comment(Rest, Handler, array, [multicomment|Stack], Config); -array(<>, Handler, Stack, Config) -> - incomplete(array, <>, Handler, Stack, Config); -array(<<>>, Handler, Stack, Config) -> - incomplete(array, <<>>, Handler, Stack, Config); -array(Bin, Handler, Stack, Config) -> - value(Bin, Handler, Stack, Config). - - -colon(<>, Handler, [key|Stack], Config) -> - value(Rest, Handler, [object|Stack], Config); -colon(<>, Handler, Stack, Config) -> - colon(Rest, Handler, Stack, Config); -colon(<>, Handler, Stack, Config) -> - colon(Rest, Handler, Stack, Config); -colon(<>, Handler, Stack, Config) -> - colon(Rest, Handler, Stack, Config); -colon(<>, Handler, Stack, Config) -> - colon(Rest, Handler, Stack, Config); -colon(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - ?error(colon, <>, Handler, Stack, Config); -colon(<>, Handler, Stack, Config) -> - comment(Rest, Handler, colon, [comment|Stack], Config); -colon(<>, Handler, Stack, Config) -> - comment(Rest, Handler, colon, [multicomment|Stack], Config); -colon(<>, Handler, Stack, Config) -> - incomplete(colon, <>, Handler, Stack, Config); -colon(<<>>, Handler, Stack, Config) -> - incomplete(colon, <<>>, Handler, Stack, Config); -colon(Bin, Handler, Stack, Config) -> - ?error(colon, Bin, Handler, Stack, Config). - - -key(<>, Handler, Stack, Config) -> - string(Rest, Handler, Stack, Config); -key(<>, Handler, Stack, Config) -> - key(Rest, Handler, Stack, Config); -key(<>, Handler, [key|Stack], Config=#config{strict_commas=false}) -> - maybe_done(<>, Handler, [object|Stack], Config); -key(<>, Handler, Stack, Config) -> - key(Rest, Handler, Stack, Config); -key(<>, Handler, Stack, Config) -> - key(Rest, Handler, Stack, Config); -key(<>, Handler, Stack, Config) -> - key(Rest, Handler, Stack, Config); -key(<>, Handler, Stack, Config=#config{strict_single_quotes=false}) -> - string(Rest, Handler, [singlequote|Stack], Config); -key(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - ?error(key, <>, Handler, Stack, Config); -key(<>, Handler, Stack, Config) -> - comment(Rest, Handler, key, [comment|Stack], Config); -key(<>, Handler, Stack, Config) -> - comment(Rest, Handler, key, [multicomment|Stack], Config); -key(<>, Handler, Stack, Config) -> - incomplete(key, <>, Handler, Stack, Config); -key(<<>>, Handler, Stack, Config) -> - incomplete(key, <<>>, Handler, Stack, Config); -key(Bin, Handler, Stack, Config) -> - ?error(key, Bin, Handler, Stack, Config). - - -%% note that if you encounter an error from string and you can't find the clause that -%% caused it here, it might be in unescape below -string(Bin, Handler, Stack, Config) -> - string(Bin, Handler, [], Stack, Config). - - -string(<>, Handler, Acc, Stack, Config) -> - doublequote(Rest, Handler, Acc, Stack, Config); -string(<>, Handler, Acc, Stack, Config) -> - singlequote(Rest, Handler, Acc, Stack, Config); -string(<>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace(?solidus, Config)], Stack, Config); -string(<>, Handler, Acc, Stack, Config) -> - unescape(Rest, Handler, Acc, Stack, Config); -%% TODO this is pretty gross and i don't like it -string(<> = Bin, Handler, Acc, Stack, Config=#config{uescape=true}) -> - case X of - X when X < 16#80 -> count(Bin, Handler, Acc, Stack, Config); - X -> string(Rest, Handler, [Acc, json_escape_sequence(X)], Stack, Config) - end; -%% u+2028 -string(<<226, 128, 168, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace(16#2028, Config)], Stack, Config); -%% u+2029 -string(<<226, 128, 169, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace(16#2029, Config)], Stack, Config); -string(<> = Bin, Handler, Acc, Stack, Config=#config{strict_control_codes=true}) when X > 16#1f -> - count(Bin, Handler, Acc, Stack, Config); -string(<<_/utf8, _/binary>> = Bin, Handler, Acc, Stack, Config=#config{strict_control_codes=false}) -> - count(Bin, Handler, Acc, Stack, Config); -%% necessary for bytes that are badly formed utf8 that won't match in `count` -string(<>, Handler, Acc, Stack, Config=#config{dirty_strings=true}) -> - string(Rest, Handler, [Acc, X], Stack, Config); -%% u+fffe and u+ffff for R14BXX (subsequent runtimes will happily match with /utf8 -string(<<239, 191, 190, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, <<16#fffe/utf8>>], Stack, Config); -string(<<239, 191, 191, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, <<16#ffff/utf8>>], Stack, Config); -string(<<>>, Handler, Acc, Stack, Config) -> - incomplete(string, <<>>, Handler, Acc, Stack, Config); -string(<>, Handler, Acc, Stack, Config) when X >= 2#11000000 -> - incomplete(string, <>, Handler, Acc, Stack, Config); -string(<>, Handler, Acc, Stack, Config) when X >= 2#11100000, Y >= 2#10000000 -> - incomplete(string, <>, Handler, Acc, Stack, Config); -string(<>, Handler, Acc, Stack, Config) - when X >= 2#11100000, Y >= 2#10000000, Z >= 2#10000000 -> - incomplete(string, <>, Handler, Acc, Stack, Config); -%% surrogates -string(<<237, X, _, Rest/binary>>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) - when X >= 160 -> - string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config); -%% overlong encodings and missing continuations of a 2 byte sequence -string(<>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) - when X >= 192, X =< 223 -> - strip_continuations(Rest, Handler, Acc, Stack, Config, 1); -%% overlong encodings and missing continuations of a 3 byte sequence -string(<>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) - when X >= 224, X =< 239 -> - strip_continuations(Rest, Handler, Acc, Stack, Config, 2); -%% overlong encodings and missing continuations of a 4 byte sequence -string(<>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) - when X >= 240, X =< 247 -> - strip_continuations(Rest, Handler, Acc, Stack, Config, 3); -%% incompletes and unexpected bytes, including orphan continuations -string(<<_, Rest/binary>>, Handler, Acc, Stack, Config=#config{strict_utf8=false}) -> - string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config); -string(Bin, Handler, Acc, Stack, Config) -> ?error(string, Bin, Handler, Acc, Stack, Config). - - -count(Bin, Handler, Acc, Stack, Config) -> - Size = count(Bin, 0, Config), - <> = Bin, - string(Rest, Handler, [Acc, Clean], Stack, Config). - - -%% explicitly whitelist ascii set for faster parsing. really? really. someone should -%% submit a patch that unrolls simple guards -count(<<32, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<33, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<>, N, _) -> N; -count(<<35, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<36, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<37, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<38, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<>, N, _) -> N; -count(<<40, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<41, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<42, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<43, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<44, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<45, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<46, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<>, N, _) -> N; -count(<<48, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<49, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<50, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<51, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<52, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<53, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<54, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<55, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<56, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<57, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<58, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<59, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<60, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<61, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<62, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<63, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<64, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<65, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<66, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<67, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<68, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<69, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<70, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<71, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<72, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<73, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<74, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<75, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<76, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<77, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<78, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<79, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<80, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<81, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<82, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<83, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<84, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<85, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<86, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<87, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<88, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<89, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<90, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<91, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<>, N, _) -> N; -count(<<93, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<94, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<95, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<96, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<97, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<98, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<99, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<100, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<101, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<102, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<103, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<104, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<105, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<106, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<107, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<108, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<109, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<110, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<111, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<112, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<113, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<114, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<115, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<116, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<117, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<118, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<119, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<120, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<121, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<122, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<123, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<124, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<125, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<126, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<127, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<_, Rest/binary>>, N, Config=#config{dirty_strings=true}) -> - count(Rest, N + 1, Config); -count(<<_/utf8, _/binary>>, N, #config{uescape=true}) -> N; -count(<>, N, Config=#config{strict_control_codes=false}) when X < 32 -> - count(Rest, N + 1, Config); -count(<>, N, #config{strict_control_codes=true}) when X < 32 -> N; -count(<>, N, Config) -> - case X of - X when X < 16#800 -> count(Rest, N + 2, Config); - %% jsonp escaping - 16#2028 -> N; - 16#2029 -> N; - X when X < 16#10000 -> count(Rest, N + 3, Config); - _ -> count(Rest, N + 4, Config) - end; -count(_, N, _) -> N. - - -doublequote(Rest, Handler, Acc, [key|_] = Stack, Config) -> - colon(Rest, handle_event({key, iolist_to_binary(Acc)}, Handler, Config), Stack, Config); -doublequote(Rest, Handler, Acc, [singlequote|_] = Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace(?doublequote, Config)], Stack, Config); -doublequote(<<>>, Handler, Acc, [singlequote|_] = Stack, Config) -> - incomplete(string, <>, Handler, Acc, Stack, Config); -doublequote(Rest, Handler, Acc, Stack, Config) -> - maybe_done(Rest, handle_event({string, iolist_to_binary(Acc)}, Handler, Config), Stack, Config). - - -singlequote(Rest, Handler, Acc, [singlequote, key|Stack], Config) -> - colon(Rest, handle_event({key, iolist_to_binary(Acc)}, Handler, Config), [key|Stack], Config); -singlequote(Rest, Handler, Acc, [singlequote|Stack], Config) -> - maybe_done(Rest, handle_event({string, iolist_to_binary(Acc)}, Handler, Config), Stack, Config); -singlequote(Rest, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, ?singlequote], Stack, Config). - - -%% strips continuation bytes after bad utf bytes, guards against both too short -%% and overlong sequences. N is the maximum number of bytes to strip -strip_continuations(<>, Handler, Acc, Stack, Config, 0) -> - string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config); -strip_continuations(<>, Handler, Acc, Stack, Config, N) when X >= 128, X =< 191 -> - strip_continuations(Rest, Handler, Acc, Stack, Config, N - 1); -%% if end of input is reached before stripping the max number of continuations -%% possible magic numbers are reinserted into the stream that get us back to -%% the same state without complicated machinery -strip_continuations(<<>>, Handler, Acc, Stack, Config, N) -> - case N of - 1 -> incomplete(string, <<192>>, Handler, Acc, Stack, Config); - 2 -> incomplete(string, <<224>>, Handler, Acc, Stack, Config); - 3 -> incomplete(string, <<240>>, Handler, Acc, Stack, Config) - end; -%% not a continuation byte, insert a replacement character for sequence thus -%% far and dispatch back to string -strip_continuations(<>, Handler, Acc, Stack, Config, _) -> - string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config). - - -%% this all gets really gross and should probably eventually be folded into -%% but for now it fakes being part of string on incompletes and errors -unescape(<>, Handler, Acc, Stack, Config=#config{dirty_strings=true}) -> - string(<>, Handler, [Acc, <>], Stack, Config); -unescape(<>, Handler, Acc, Stack, Config=#config{dirty_strings=true}) -> - string(Rest, Handler, [Acc, <>], Stack, Config); -unescape(<<$b, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\b, Config)], Stack, Config); -unescape(<<$f, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\f, Config)], Stack, Config); -unescape(<<$n, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\n, Config)], Stack, Config); -unescape(<<$r, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\r, Config)], Stack, Config); -unescape(<<$t, Rest/binary>>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\t, Config)], Stack, Config); -unescape(<>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\", Config)], Stack, Config); -unescape(<>, Handler, Acc, Stack, Config=#config{strict_single_quotes=false}) -> - string(Rest, Handler, [Acc, <>], Stack, Config); -unescape(<>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($\\, Config)], Stack, Config); -unescape(<>, Handler, Acc, Stack, Config) -> - string(Rest, Handler, [Acc, maybe_replace($/, Config)], Stack, Config); -unescape(<<$u, F, A, B, C, ?rsolidus, $u, G, X, Y, Z, Rest/binary>>, Handler, Acc, Stack, Config) - when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), - (X == $c orelse X == $d orelse X == $e orelse X == $f orelse X == $C orelse X == $D orelse X == $E orelse X == $F), - (F == $d orelse F == $D), - (G == $d orelse G == $D), - ?is_hex(B), ?is_hex(C), ?is_hex(Y), ?is_hex(Z) - -> - High = erlang:list_to_integer([$d, A, B, C], 16), - Low = erlang:list_to_integer([$d, X, Y, Z], 16), - Codepoint = (High - 16#d800) * 16#400 + (Low - 16#dc00) + 16#10000, - string(Rest, Handler, [Acc, <>], Stack, Config); -unescape(<<$u, F, A, B, C, ?rsolidus, $u, W, X, Y, Z, Rest/binary>>, Handler, Acc, Stack, Config) - when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), - (F == $d orelse F == $D), - ?is_hex(B), ?is_hex(C), ?is_hex(W), ?is_hex(X), ?is_hex(Y), ?is_hex(Z) - -> - case Config#config.strict_utf8 of - true -> ?error(<<$u, $d, A, B, C, ?rsolidus, $u, W, X, Y, Z, Rest/binary>>, Handler, Acc, Stack, Config); - false -> string(Rest, Handler, [Acc, <<16#fffd/utf8>>, <<16#fffd/utf8>>], Stack, Config) - end; -unescape(<<$u, F, A, B, C, ?rsolidus, Rest/binary>>, Handler, Acc, Stack, Config) - when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), - (F == $d orelse F == $D), - ?is_hex(B), ?is_hex(C) - -> - incomplete(string, <>, Handler, Acc, Stack, Config); -unescape(<<$u, F, A, B, C>>, Handler, Acc, Stack, Config) - when (A == $8 orelse A == $9 orelse A == $a orelse A == $b orelse A == $A orelse A == $B), - (F == $d orelse F == $D), - ?is_hex(B), ?is_hex(C) - -> - incomplete(string, <>, Handler, Acc, Stack, Config); -unescape(<<$u, A, B, C, D, Rest/binary>>, Handler, Acc, Stack, Config) - when ?is_hex(A), ?is_hex(B), ?is_hex(C), ?is_hex(D) -> - case erlang:list_to_integer([A, B, C, D], 16) of - Codepoint when Codepoint < 16#d800; Codepoint > 16#dfff -> - string(Rest, Handler, [Acc, maybe_replace(Codepoint, Config)], Stack, Config); - _ when Config#config.strict_utf8 -> - ?error(string, <>, Handler, Acc, Stack, Config); - _ -> string(Rest, Handler, [Acc, <<16#fffd/utf8>>], Stack, Config) - end; -unescape(Bin, Handler, Acc, Stack, Config) -> - case is_partial_escape(Bin) of - true -> incomplete(string, <>, Handler, Acc, Stack, Config); - false -> case Config#config.strict_escapes of - true -> ?error(string, <>, Handler, Acc, Stack, Config); - false -> string(Bin, Handler, [Acc, <>], Stack, Config) - end - end. - - -is_partial_escape(<<$u, A, B, C>>) when ?is_hex(A), ?is_hex(B), ?is_hex(C) -> true; -is_partial_escape(<<$u, A, B>>) when ?is_hex(A), ?is_hex(B) -> true; -is_partial_escape(<<$u, A>>) when ?is_hex(A) -> true; -is_partial_escape(<<$u>>) -> true; -is_partial_escape(<<>>) -> true; -is_partial_escape(_) -> false. - - -maybe_replace(C, #config{dirty_strings=true}) -> <>; -maybe_replace($\b, #config{escaped_strings=true}) -> <<$\\, $b>>; -maybe_replace($\t, #config{escaped_strings=true}) -> <<$\\, $t>>; -maybe_replace($\n, #config{escaped_strings=true}) -> <<$\\, $n>>; -maybe_replace($\f, #config{escaped_strings=true}) -> <<$\\, $f>>; -maybe_replace($\r, #config{escaped_strings=true}) -> <<$\\, $r>>; -maybe_replace($\", #config{escaped_strings=true}) -> <<$\\, $\">>; -maybe_replace($/, Config=#config{escaped_strings=true}) -> - case Config#config.escaped_forward_slashes of - true -> <<$\\, $/>> - ; false -> <<$/>> - end; -maybe_replace($\\, #config{escaped_strings=true}) -> <<$\\, $\\>>; -maybe_replace(X, Config=#config{escaped_strings=true}) when X == 16#2028; X == 16#2029 -> - case Config#config.unescaped_jsonp of - true -> <> - ; false -> json_escape_sequence(X) - end; -maybe_replace(X, #config{escaped_strings=true}) when X < 32 -> - json_escape_sequence(X); -maybe_replace(X, _Config) -> <>. - - -%% convert a codepoint to it's \uXXXX equiv. -json_escape_sequence(X) when X < 65536 -> - <> = <>, - <<$\\, $u, (to_hex(A)), (to_hex(B)), (to_hex(C)), (to_hex(D))>>; -json_escape_sequence(X) -> - Adjusted = X - 16#10000, - <> = <>, - [json_escape_sequence(A + 16#d800), json_escape_sequence(B + 16#dc00)]. - - -%% ascii "1" is [49], "2" is [50], etc... -to_hex(10) -> $a; -to_hex(11) -> $b; -to_hex(12) -> $c; -to_hex(13) -> $d; -to_hex(14) -> $e; -to_hex(15) -> $f; -to_hex(X) -> X + 48. - - -number(<<$e, Rest/binary>>, Handler, Acc, [integer|Stack], Config) -> - number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); -number(<<$E, Rest/binary>>, Handler, Acc, [integer|Stack], Config) -> - number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); -number(<<$e, Rest/binary>>, Handler, Acc, [zero|Stack], Config) -> - number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); -number(<<$E, Rest/binary>>, Handler, Acc, [zero|Stack], Config) -> - number(Rest, Handler, [Acc, $., $0, $e], [e|Stack], Config); -number(<<>>, Handler, Acc, [State|Stack], Config=#config{stream=false}) -> - NumType = case State of - zero -> integer; - integer -> integer; - decimal -> float; - exp -> float - end, - finish_number(<<>>, Handler, {NumType, iolist_to_binary(Acc)}, Stack, Config); -number(<<>>, Handler, Acc, Stack, Config) -> - incomplete(number, <<>>, Handler, Acc, Stack, Config); -number(Bin, Handler, Acc, [State|Stack], Config) -> - Counted = case State of - zero -> zero(Bin, 0); - integer -> integer(Bin, 0); - negative -> negative(Bin, 0); - initialdecimal -> initialdecimal(Bin, 0); - decimal -> decimal(Bin, 0); - e -> e(Bin, 0); - ex -> ex(Bin, 0); - exp -> exp(Bin, 0) - end, - case Counted of - {finish_integer, Size} -> - <> = Bin, - finish_number(Rest, Handler, {integer, iolist_to_binary([Acc, Clean])}, Stack, Config); - {finish_float, Size} -> - <> = Bin, - finish_number(Rest, Handler, {float, iolist_to_binary([Acc, Clean])}, Stack, Config); - {error, Size} -> - <> = Bin, - ?error(number, Rest, Handler, [Acc, Clean], Stack, Config); - {NewState, Size} -> - <> = Bin, - number(Rest, Handler, [Acc, Clean], [NewState|Stack], Config) - end. - - -zero(<>, N) -> initialdecimal(Rest, N + 1); -zero(<<$e, _/binary>>, N) -> {integer, N}; -zero(<<$E, _/binary>>, N) -> {integer, N}; -zero(<<>>, N) -> {zero, N}; -zero(_, N) -> {finish_integer, N}. - - -integer(<<$0, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$1, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$2, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$3, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$4, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$5, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$6, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$7, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$8, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<<$9, Rest/binary>>, N) -> integer(Rest, N + 1); -integer(<>, N) -> initialdecimal(Rest, N + 1); -integer(<<$e, _/binary>>, N) -> {integer, N}; -integer(<<$E, _/binary>>, N) -> {integer, N}; -integer(<<>>, N) -> {integer, N}; -integer(_, N) -> {finish_integer, N}. - - -negative(<<$0, Rest/binary>>, N) -> zero(Rest, N + 1); -negative(<<$1, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$2, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$3, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$4, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$5, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$6, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$7, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$8, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<$9, Rest/binary>>, N) -> integer(Rest, N + 1); -negative(<<>>, N) -> {negative, N}; -negative(_, N) -> {error, N}. - - -initialdecimal(<<$0, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$1, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$2, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$3, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$4, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$5, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$6, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$7, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$8, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<$9, Rest/binary>>, N) -> decimal(Rest, N + 1); -initialdecimal(<<>>, N) -> {initialdecimal, N}; -initialdecimal(_, N) -> {error, N}. - - -decimal(<<$0, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$1, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$2, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$3, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$4, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$5, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$6, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$7, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$8, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$9, Rest/binary>>, N) -> decimal(Rest, N + 1); -decimal(<<$e, Rest/binary>>, N) -> e(Rest, N + 1); -decimal(<<$E, Rest/binary>>, N) -> e(Rest, N + 1); -decimal(<<>>, N) -> {decimal, N}; -decimal(_, N) -> {finish_float, N}. - - -e(<<$0, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$1, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$2, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$3, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$4, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$5, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$6, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$7, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$8, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<<$9, Rest/binary>>, N) -> exp(Rest, N + 1); -e(<>, N) -> ex(Rest, N + 1); -e(<>, N) -> ex(Rest, N + 1); -e(<<>>, N) -> {e, N}; -e(_, N) -> {error, N}. - - -ex(<<$0, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$1, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$2, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$3, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$4, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$5, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$6, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$7, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$8, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<$9, Rest/binary>>, N) -> exp(Rest, N + 1); -ex(<<>>, N) -> {ex, N}; -ex(_, N) -> {error, N}. - - -exp(<<$0, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$1, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$2, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$3, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$4, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$5, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$6, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$7, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$8, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<$9, Rest/binary>>, N) -> exp(Rest, N + 1); -exp(<<>>, N) -> {exp, N}; -exp(_, N) -> {finish_float, N}. - - -finish_number(Rest, Handler, Acc, Stack, Config) -> - maybe_done(Rest, handle_event(format_number(Acc), Handler, Config), Stack, Config). - - --ifndef(no_binary_to_whatever). -format_number({integer, Acc}) -> {integer, binary_to_integer(Acc)}; -format_number({float, Acc}) -> {float, binary_to_float(Acc)}. --else. -format_number({integer, Acc}) -> {integer, list_to_integer(unicode:characters_to_list(Acc))}; -format_number({float, Acc}) -> {float, list_to_float(unicode:characters_to_list(Acc))}. --endif. - - -true(<<$r, $u, $e, Rest/binary>>, Handler, Stack, Config) -> - maybe_done(Rest, handle_event({literal, true}, Handler, Config), Stack, Config); -true(<<$r, $u>>, Handler, Stack, Config) -> - incomplete(true, <<$r, $u>>, Handler, Stack, Config); -true(<<$r>>, Handler, Stack, Config) -> - incomplete(true, <<$r>>, Handler, Stack, Config); -true(<<>>, Handler, Stack, Config) -> - incomplete(true, <<>>, Handler, Stack, Config); -true(Bin, Handler, Stack, Config) -> - ?error(true, Bin, Handler, Stack, Config). - - -false(<<$a, $l, $s, $e, Rest/binary>>, Handler, Stack, Config) -> - maybe_done(Rest, handle_event({literal, false}, Handler, Config), Stack, Config); -false(<<$a, $l, $s>>, Handler, Stack, Config) -> - incomplete(false, <<$a, $l, $s>>, Handler, Stack, Config); -false(<<$a, $l>>, Handler, Stack, Config) -> - incomplete(false, <<$a, $l>>, Handler, Stack, Config); -false(<<$a>>, Handler, Stack, Config) -> - incomplete(false, <<$a>>, Handler, Stack, Config); -false(<<>>, Handler, Stack, Config) -> - incomplete(false, <<>>, Handler, Stack, Config); -false(Bin, Handler, Stack, Config) -> - ?error(false, Bin, Handler, Stack, Config). - - -null(<<$u, $l, $l, Rest/binary>>, Handler, Stack, Config) -> - maybe_done(Rest, handle_event({literal, null}, Handler, Config), Stack, Config); -null(<<$u, $l>>, Handler, Stack, Config) -> - incomplete(null, <<$u, $l>>, Handler, Stack, Config); -null(<<$u>>, Handler, Stack, Config) -> - incomplete(null, <<$u>>, Handler, Stack, Config); -null(<<>>, Handler, Stack, Config) -> - incomplete(null, <<>>, Handler, Stack, Config); -null(Bin, Handler, Stack, Config) -> - ?error(null, Bin, Handler, Stack, Config). - - -comment(<>, Handler, Resume, [comment|Stack], Config) -> - resume(Rest, Resume, Handler, unused, Stack, Config); -comment(<>, Handler, Resume, Stack, Config) -> - comment(Rest, Handler, Resume, [multicomment|Stack], Config); -comment(<>, Handler, Resume, [multicomment|_] = Stack, Config) -> - incomplete(comment, <>, Handler, Resume, Stack, Config); -comment(<>, Handler, Resume, [multicomment|Stack], Config) -> - case Stack of - [multicomment|_] -> comment(Rest, Handler, Resume, Stack, Config); - _ -> resume(Rest, Resume, Handler, unused, Stack, Config) - end; -comment(<>, Handler, Resume, [multicomment|_] = Stack, Config) -> - incomplete(comment, <>, Handler, Resume, Stack, Config); -comment(<<_/utf8, Rest/binary>>, Handler, Resume, Stack, Config) -> - comment(Rest, Handler, Resume, Stack, Config); -comment(<<_, Rest/binary>>, Handler, Resume, Stack, Config=#config{strict_utf8=false}) -> - comment(Rest, Handler, Resume, Stack, Config); -comment(<<>>, Handler, done, [Comment], Config=#config{stream=false}) - when Comment == comment; Comment == multicomment -> - resume(<<>>, done, Handler, unused, [], Config); -comment(<<>>, Handler, Resume, Stack, Config) -> - incomplete(comment, <<>>, Handler, Resume, Stack, Config); -comment(Bin, Handler, Resume, Stack, Config) -> - ?error(comment, Bin, Handler, Resume, Stack, Config). - - -maybe_done(<>, Handler, [], Config) -> - done(Rest, handle_event(end_json, Handler, Config), [], Config); -maybe_done(<>, Handler, Stack, Config) -> - maybe_done(Rest, Handler, Stack, Config); -maybe_done(<>, Handler, [object|Stack], Config) -> - maybe_done(Rest, handle_event(end_object, Handler, Config), Stack, Config); -maybe_done(<>, Handler, [array|Stack], Config) -> - maybe_done(Rest, handle_event(end_array, Handler, Config), Stack, Config); -maybe_done(<>, Handler, [object|Stack], Config) -> - key(Rest, Handler, [key|Stack], Config); -maybe_done(<>, Handler, [array|_] = Stack, Config) -> - value(Rest, Handler, Stack, Config); -maybe_done(<>, Handler, Stack, Config) -> - maybe_done(Rest, Handler, Stack, Config); -maybe_done(<>, Handler, Stack, Config) -> - maybe_done(Rest, Handler, Stack, Config); -maybe_done(<>, Handler, Stack, Config) -> - maybe_done(Rest, Handler, Stack, Config); -maybe_done(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - ?error(maybe_done, <>, Handler, Stack, Config); -maybe_done(<>, Handler, Stack, Config) -> - comment(Rest, Handler, maybe_done, [comment|Stack], Config); -maybe_done(<>, Handler, Stack, Config) -> - comment(Rest, Handler, maybe_done, [multicomment|Stack], Config); -maybe_done(<>, Handler, Stack, Config) -> - incomplete(maybe_done, <>, Handler, Stack, Config); -maybe_done(<<>>, Handler, Stack, Config) when length(Stack) > 0 -> - incomplete(maybe_done, <<>>, Handler, Stack, Config); -maybe_done(Bin, Handler, Stack, Config) -> - ?error(maybe_done, Bin, Handler, Stack, Config). - - -done(<>, Handler, [], Config) -> - done(Rest, Handler, [], Config); -done(<>, Handler, [], Config) -> - done(Rest, Handler, [], Config); -done(<>, Handler, [], Config) -> - done(Rest, Handler, [], Config); -done(<>, Handler, [], Config) -> - done(Rest, Handler, [], Config); -done(<>, Handler, Stack, Config=#config{strict_comments=true}) -> - ?error(done, <>, Handler, Stack, Config); -done(<>, Handler, Stack, Config) -> - comment(Rest, Handler, done, [comment|Stack], Config); -done(<>, Handler, Stack, Config) -> - comment(Rest, Handler, done, [multicomment|Stack], Config); -done(<>, Handler, Stack, Config) -> - incomplete(done, <>, Handler, Stack, Config); -done(Bin, {_Handler, State}, _Stack, #config{return_tail=true}) -> - {with_tail,State, Bin}; -done(<<>>, {Handler, State}, [], Config=#config{stream=true}) -> - incomplete(done, <<>>, {Handler, State}, [], Config); -done(<<>>, {_Handler, State}, [], _Config) -> State; -done(Bin, {Handler, State}, _Stack, Config=#config{multi_term=true}) -> - value(Bin, {Handler, Handler:reset(State)}, [], Config); -done(Bin, Handler, Stack, Config) -> ?error(done, Bin, Handler, Stack, Config). - - - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -json_to_bytes(JSON) -> json_to_bytes(JSON, []). - -json_to_bytes(<<>>, Acc) -> [<<>>] ++ lists:reverse(Acc); -json_to_bytes(<>, Acc) -> json_to_bytes(Rest, [<>] ++ Acc). - - -decode(JSON) -> decode(JSON, []). -decode(JSON, Config) -> (decoder(jsx, [], Config))(JSON). - - -incremental_decode(JSON) -> incremental_decode(JSON, []). -incremental_decode(JSON, Config) -> - Final = lists:foldl( - fun(Byte, Decoder) -> {incomplete, F} = Decoder(Byte), F end, - decoder(jsx, [], [stream] ++ Config), - json_to_bytes(JSON) - ), - Final(end_stream). - - -%% all these numbers have different representation in erlang than in javascript and -%% do not roundtrip like most integers/floats -special_number_test_() -> - Cases = [ - % {title, test form, json, opt flags} - {"-0", [{integer, 0}, end_json], <<"-0">>}, - {"-0.0", [{float, 0.0}, end_json], <<"-0.0">>}, - {"0e0", [{float, 0.0}, end_json], <<"0e0">>}, - {"0e4", [{float, 0.0}, end_json], <<"0e4">>}, - {"1e0", [{float, 1.0}, end_json], <<"1e0">>}, - {"-1e0", [{float, -1.0}, end_json], <<"-1e0">>}, - {"-0e0", [{float, -0.0}, end_json], <<"-0e0">>}, - {"1e4", [{float, 1.0e4}, end_json], <<"1e4">>}, - {"number terminated by whitespace", - [start_array, {integer, 1}, end_array, end_json], - <<"[ 1 ]">> - }, - {"number terminated by comma", - [start_array, {integer, 1}, {integer, 1}, end_array, end_json], - <<"[ 1, 1 ]">> - }, - {"number terminated by comma in object", - [start_object, {key, <<"x">>}, {integer, 1}, {key, <<"y">>}, {integer, 1}, end_object, end_json], - <<"{\"x\": 1, \"y\": 1}">> - } - ], - [{Title, ?_assertEqual(Events, decode(JSON))} - || {Title, Events, JSON} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertEqual(Events, incremental_decode(JSON))} - || {Title, Events, JSON} <- Cases - ]. - - -comments_test_() -> - Cases = [ - % {title, test form, json, opt flags} - {"preceeding // comment", - [start_array, end_array, end_json], - <<"// comment ", ?newline, "[]">> - }, - {"preceeding /**/ comment", - [start_array, end_array, end_json], - <<"/* comment */[]">> - }, - {"trailing // comment", - [start_array, end_array, end_json], - <<"[]// comment", ?newline>> - }, - {"trailing // comment (no newline)", - [start_array, end_array, end_json], - <<"[]// comment">> - }, - {"trailing /**/ comment", - [start_array, end_array, end_json], - <<"[] /* comment */">> - }, - {"// comment inside array", - [start_array, end_array, end_json], - <<"[ // comment", ?newline, "]">> - }, - {"/**/ comment inside array", - [start_array, end_array, end_json], - <<"[ /* comment */ ]">> - }, - {"// comment at beginning of array", - [start_array, {literal, true}, end_array, end_json], - <<"[ // comment", ?newline, "true", ?newline, "]">> - }, - {"/**/ comment at beginning of array", - [start_array, {literal, true}, end_array, end_json], - <<"[ /* comment */ true ]">> - }, - {"// comment at end of array", - [start_array, {literal, true}, end_array, end_json], - <<"[ true // comment", ?newline, "]">> - }, - {"/**/ comment at end of array", - [start_array, {literal, true}, end_array, end_json], - <<"[ true /* comment */ ]">> - }, - {"// comment midarray (post comma)", - [start_array, {literal, true}, {literal, false}, end_array, end_json], - <<"[ true, // comment", ?newline, "false ]">> - }, - {"/**/ comment midarray (post comma)", - [start_array, {literal, true}, {literal, false}, end_array, end_json], - <<"[ true, /* comment */ false ]">> - }, - {"// comment midarray (pre comma)", - [start_array, {literal, true}, {literal, false}, end_array, end_json], - <<"[ true// comment", ?newline, ", false ]">> - }, - {"/**/ comment midarray (pre comma)", - [start_array, {literal, true}, {literal, false}, end_array, end_json], - <<"[ true/* comment */, false ]">> - }, - {"// comment inside object", - [start_object, end_object, end_json], - <<"{ // comment", ?newline, "}">> - }, - {"/**/ comment inside object", - [start_object, end_object, end_json], - <<"{ /* comment */ }">> - }, - {"// comment at beginning of object", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ // comment", ?newline, " \"key\": true", ?newline, "}">> - }, - {"/**/ comment at beginning of object", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ /* comment */ \"key\": true }">> - }, - {"// comment at end of object", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ \"key\": true // comment", ?newline, "}">> - }, - {"/**/ comment at end of object", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ \"key\": true /* comment */ }">> - }, - {"// comment midobject (post comma)", - [ - start_object, - {key, <<"x">>}, - {literal, true}, - {key, <<"y">>}, - {literal, false}, - end_object, - end_json - ], - <<"{ \"x\": true, // comment", ?newline, "\"y\": false }">> - }, - {"/**/ comment midobject (post comma)", - [ - start_object, - {key, <<"x">>}, - {literal, true}, - {key, <<"y">>}, - {literal, false}, - end_object, - end_json - ], - <<"{ \"x\": true, /* comment */", ?newline, "\"y\": false }">> - }, - {"// comment midobject (pre comma)", - [ - start_object, - {key, <<"x">>}, - {literal, true}, - {key, <<"y">>}, - {literal, false}, - end_object, - end_json - ], - <<"{ \"x\": true// comment", ?newline, ", \"y\": false }">> - }, - {"/**/ comment midobject (pre comma)", - [ - start_object, - {key, <<"x">>}, - {literal, true}, - {key, <<"y">>}, - {literal, false}, - end_object, - end_json - ], - <<"{ \"x\": true/* comment */", ?newline, ", \"y\": false }">> - }, - {"// comment precolon", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ \"key\" // comment", ?newline, ": true }">> - }, - {"/**/ comment precolon", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ \"key\"/* comment */: true }">> - }, - {"// comment postcolon", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ \"key\": // comment", ?newline, " true }">> - }, - {"/**/ comment postcolon", - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - <<"{ \"key\":/* comment */ true }">> - }, - {"// comment terminating zero", - [start_array, {integer, 0}, end_array, end_json], - <<"[ 0// comment", ?newline, "]">> - }, - {"// comment terminating integer", - [start_array, {integer, 1}, end_array, end_json], - <<"[ 1// comment", ?newline, "]">> - }, - {"// comment terminating float", - [start_array, {float, 1.0}, end_array, end_json], - <<"[ 1.0// comment", ?newline, "]">> - }, - {"// comment terminating exp", - [start_array, {float, 1.0e1}, end_array, end_json], - <<"[ 1e1// comment", ?newline, "]">> - }, - {"/**/ comment terminating zero", - [start_array, {integer, 0}, end_array, end_json], - <<"[ 0/* comment */ ]">> - }, - {"/**/ comment terminating integer", - [start_array, {integer, 1}, end_array, end_json], - <<"[ 1/* comment */ ]">> - }, - {"/**/ comment terminating float", - [start_array, {float, 1.0}, end_array, end_json], - <<"[ 1.0/* comment */ ]">> - }, - {"/**/ comment terminating exp", - [start_array, {float, 1.0e1}, end_array, end_json], - <<"[ 1e1/* comment */ ]">> - }, - {"/**/ comment following /**/ comment", - [start_array, {literal, true}, end_array, end_json], - <<"[/* comment *//* comment */true]">> - }, - {"/**/ comment following // comment", - [start_array, {literal, true}, end_array, end_json], - <<"[// comment", ?newline, "/* comment */true]">> - }, - {"// comment following /**/ comment", - [start_array, {literal, true}, end_array, end_json], - <<"[/* comment */// comment", ?newline, "true]">> - }, - {"// comment following // comment", - [start_array, {literal, true}, end_array, end_json], - <<"[// comment", ?newline, "// comment", ?newline, "true]">> - }, - {"/**/ comment inside /**/ comment", - [start_array, {literal, true}, end_array, end_json], - <<"[ /* /* comment */ */ true ]">> - }, - {"/**/ comment with /", - [start_array, {literal, true}, end_array, end_json], - <<"[ /* / */ true ]">> - }, - {"/**/ comment with *", - [start_array, {literal, true}, end_array, end_json], - <<"[ /* * */ true ]">> - }, - {"// comment with badutf", - [start_array, {literal, true}, end_array, end_json], - <<"[ // comment ", 16#00c0, " ", ?newline, "true]">> - }, - {"/**/ comment with badutf", - [start_array, {literal, true}, end_array, end_json], - <<"[ /* comment ", 16#00c0, " */ true]">> - }, - {"/**/ comment with badutf preceeded by /", - [start_array, {literal, true}, end_array, end_json], - <<"[ /* comment /", 16#00c0, " */ true]">> - } - ], - [{Title, ?_assertEqual(Events, decode(JSON))} - || {Title, Events, JSON} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertEqual(Events, incremental_decode(JSON))} - || {Title, Events, JSON} <- Cases - ] ++ - % error when `{strict, [comments]}` is present - [{Title, ?_assertError(badarg, decode(JSON, [{strict, [comments]}]))} - || {Title, _Events, JSON} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertError( - badarg, - incremental_decode(JSON, [{strict, [comments]}]) - )} || {Title, _Events, JSON} <- Cases - ]. - - -no_comments_test_() -> - Cases = [ - {"// comment with badutf", - badarg, - <<"[ // comment ", 16#00c0, " ", ?newline, "true]">>, - [{strict, [utf8]}] - }, - {"/**/ comment with badutf", - badarg, - <<"[ /* comment ", 16#00c0, " */ true]">>, - [{strict, [utf8]}] - }, - {"/**/ comment with badutf preceeded by /", - badarg, - <<"[ /* comment /", 16#00c0, " */ true]">>, - [{strict, [utf8]}] - } - ], - [{Title, ?_assertError(Error, decode(JSON, Config))} - || {Title, Error, JSON, Config} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertError(Error, incremental_decode(JSON, Config))} - || {Title, Error, JSON, Config} <- Cases - ]. - - -% doing the full unicode range takes foreverrrrrrr so just do boundaries -% excludes characters that may need escaping -codepoints() -> - lists:seq(0, 32) ++ - [32, 33] ++ - lists:seq(35, 46) ++ - lists:seq(48, 91) ++ - lists:seq(93, 127) ++ - [16#2027, 16#202a, 16#d7ff, 16#e000] ++ - lists:seq(16#fdd0, 16#ffff) ++ - [16#10000, 16#20000, 16#30000, 16#40000, 16#50000] ++ - [16#60000, 16#70000, 16#80000, 16#90000, 16#a0000, 16#b0000] ++ - [16#c0000, 16#d0000, 16#e0000, 16#f0000, 16#100000]. - - -surrogates() -> lists:seq(16#d800, 16#dfff). - - -%% erlang refuses to decode certain codepoints, so fake them all -to_fake_utf8(N) when N < 16#0080 -> <<34/utf8, N:8, 34/utf8>>; -to_fake_utf8(N) when N < 16#0800 -> - <<0:5, Y:5, X:6>> = <>, - <<34/utf8, 2#110:3, Y:5, 2#10:2, X:6, 34/utf8>>; -to_fake_utf8(N) when N < 16#10000 -> - <> = <>, - <<34/utf8, 2#1110:4, Z:4, 2#10:2, Y:6, 2#10:2, X:6, 34/utf8>>; -to_fake_utf8(N) -> - <<0:3, W:3, Z:6, Y:6, X:6>> = <>, - <<34/utf8, 2#11110:5, W:3, 2#10:2, Z:6, 2#10:2, Y:6, 2#10:2, X:6, 34/utf8>>. - - -clean_string_test_() -> - Clean = codepoints(), - Dirty = surrogates(), - % clean codepoints - [{"clean u+" ++ integer_to_list(Codepoint, 16), ?_assertEqual( - [{string, <>}, end_json], - decode(<<34/utf8, Codepoint/utf8, 34/utf8>>) - )} || Codepoint <- Clean - ] ++ - % bad codepoints replaced by u+FFFD - [{"clean u+" ++ integer_to_list(Codepoint, 16), ?_assertEqual( - [{string, <<16#fffd/utf8>>}, end_json], - decode(to_fake_utf8(Codepoint)) - )} || Codepoint <- Dirty - ] ++ - % bad codepoints that cause errors - [{"dirty u+" ++ integer_to_list(Codepoint, 16), ?_assertError( - badarg, - decode(to_fake_utf8(Codepoint), [{strict, [utf8]}]) - )} || Codepoint <- Dirty - ]. - - -dirty_string_test_() -> - Cases = [ - {"dirty \\n", - [start_array, {string, <<"\\n">>}, end_array, end_json], - <<"[\"\\n\"]">>, - [dirty_strings] - }, - {"dirty \\uwxyz", - [start_array, {string, <<"\\uwxyz">>}, end_array, end_json], - <<"[\"\\uwxyz\"]">>, - [dirty_strings] - }, - {"dirty \\x23", - [start_array, {string, <<"\\x23">>}, end_array, end_json], - <<"[\"\\x23\"]">>, - [dirty_strings] - }, - {"dirty 0", - [start_array, {string, <<0>>}, end_array, end_json], - <<"[\"", 0, "\"]">>, - [dirty_strings] - }, - {"dirty 0\\\"0", - [start_array, {string, <<0, ?rsolidus, ?doublequote, 0>>}, end_array, end_json], - <<"[\"", 0, ?rsolidus, ?doublequote, 0, "\"]">>, - [dirty_strings] - }, - {"dirty 0\\\\\"0", - [start_array, {string, <<0, ?rsolidus, ?rsolidus, ?doublequote, 0>>}, end_array, end_json], - <<"[\"", 0, ?rsolidus, ?rsolidus, ?doublequote, 0, "\"]">>, - [dirty_strings] - }, - {"dirty 16#d800", - [start_array, {string, <<237, 160, 128>>}, end_array, end_json], - <<"[\"", 237, 160, 128, "\"]">>, - [dirty_strings] - }, - {"dirty /", - [start_array, {string, <<$/>>}, end_array, end_json], - <<"[\"", $/, "\"]">>, - [dirty_strings, escaped_forward_slashes] - }, - {"dirty <<194, 129>>", - [start_array, {string, <<194, 129>>}, end_array, end_json], - <<"[\"", 194, 129, "\"]">>, - [dirty_strings] - } - ], - [{Title, ?_assertEqual(Events, decode(JSON, Config))} - || {Title, Events, JSON, Config} <- Cases - ] ++ - % ensure `dirty_strings` and `strict` interact properly - [{Title, ?_assertEqual(Events, decode(JSON, Config ++ [strict]))} - || {Title, Events, JSON, Config} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertEqual(Events, incremental_decode(JSON, Config))} - || {Title, Events, JSON, Config} <- Cases - ]. - - -bad_utf8_test_() -> - Cases = [ - {"orphan continuation byte u+0080", <<16#fffd/utf8>>, <<16#0080>>}, - {"orphan continuation byte u+00bf", <<16#fffd/utf8>>, <<16#00bf>>}, - {"2 continuation bytes", - binary:copy(<<16#fffd/utf8>>, 2), - <<(binary:copy(<<16#0080>>, 2))/binary>> - }, - {"3 continuation bytes", - binary:copy(<<16#fffd/utf8>>, 3), - <<(binary:copy(<<16#0080>>, 3))/binary>> - }, - {"4 continuation bytes", - binary:copy(<<16#fffd/utf8>>, 4), - <<(binary:copy(<<16#0080>>, 4))/binary>> - }, - {"5 continuation bytes", - binary:copy(<<16#fffd/utf8>>, 5), - <<(binary:copy(<<16#0080>>, 5))/binary>> - }, - {"6 continuation bytes", - binary:copy(<<16#fffd/utf8>>, 6), - <<(binary:copy(<<16#0080>>, 6))/binary>> - }, - {"all continuation bytes", - binary:copy(<<16#fffd/utf8>>, length(lists:seq(16#0080, 16#00bf))), - <<(list_to_binary(lists:seq(16#0080, 16#00bf)))/binary>> - }, - {"lonely start byte", <<16#fffd/utf8>>, <<16#00c0>>}, - {"lonely start bytes (2 byte)", - <<16#fffd/utf8, 32, 16#fffd/utf8>>, - <<16#00c0, 32, 16#00df>> - }, - {"lonely start bytes (3 byte)", - <<16#fffd/utf8, 32, 16#fffd/utf8>>, - <<16#00e0, 32, 16#00ef>> - }, - {"lonely start bytes (4 byte)", - <<16#fffd/utf8, 32, 16#fffd/utf8>>, - <<16#00f0, 32, 16#00f7>> - }, - {"missing continuation byte (3 byte)", <<16#fffd/utf8, 32>>, <<224, 160, 32>>}, - {"missing continuation byte (4 byte missing one)", - <<16#fffd/utf8, 32>>, - <<240, 144, 128, 32>> - }, - {"missing continuation byte (4 byte missing two)", - <<16#fffd/utf8, 32>>, - <<240, 144, 32>> - }, - {"overlong encoding of u+002f (2 byte)", - <<16#fffd/utf8, 32>>, - <<16#c0, 16#af, 32>> - }, - {"overlong encoding of u+002f (3 byte)", - <<16#fffd/utf8, 32>>, - <<16#e0, 16#80, 16#af, 32>> - }, - {"overlong encoding of u+002f (4 byte)", - <<16#fffd/utf8, 32>>, - <<16#f0, 16#80, 16#80, 16#af, 32>> - }, - {"highest overlong 2 byte sequence", - <<16#fffd/utf8, 32>>, - <<16#c1, 16#bf, 32>> - }, - {"highest overlong 3 byte sequence", - <<16#fffd/utf8, 32>>, - <<16#e0, 16#9f, 16#bf, 32>> - }, - {"highest overlong 4 byte sequence", - <<16#fffd/utf8, 32>>, - <<16#f0, 16#8f, 16#bf, 16#bf, 32>> - } - ], - [{Title, ?_assertError( - badarg, - decode(<<34, JSON/binary, 34>>, [{strict, [utf8]}]) - )} || {Title, _, JSON} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertError( - badarg, - incremental_decode(<<34, JSON/binary, 34>>, [{strict, [utf8]}]) - )} || {Title, _, JSON} <- Cases - ] ++ - [{Title ++ " replaced", ?_assertEqual( - [{string, Replacement}, end_json], - decode(<<34, JSON/binary, 34>>) - )} || {Title, Replacement, JSON} <- Cases - ] ++ - [{Title ++ " replaced (incremental)", ?_assertEqual( - [{string, Replacement}, end_json], - incremental_decode(<<34, JSON/binary, 34>>) - )} || {Title, Replacement, JSON} <- Cases - ]. - - -unescape_test_() -> - Cases = [ - {"unescape backspace", <<"\b">>, <<"\\b"/utf8>>}, - {"unescape tab", <<"\t">>, <<"\\t"/utf8>>}, - {"unescape newline", <<"\n">>, <<"\\n"/utf8>>}, - {"unescape formfeed", <<"\f">>, <<"\\f"/utf8>>}, - {"unescape carriage return", <<"\r">>, <<"\\r"/utf8>>}, - {"unescape quote", <<"\"">>, <<"\\\""/utf8>>}, - {"unescape solidus", <<"/">>, <<"\\/"/utf8>>}, - {"unescape reverse solidus", <<"\\">>, <<"\\\\"/utf8>>}, - {"unescape control", <<0>>, <<"\\u0000"/utf8>>}, - {"unescape surrogate pair", <<16#10000/utf8>>, <<"\\ud800\\udc00"/utf8>>}, - {"unescape surrogate pair", <<16#10000/utf8>>, <<"\\uD800\\uDC00"/utf8>>}, - {"replace bad high surrogate", <<16#fffd/utf8>>, <<"\\udc00"/utf8>>}, - {"replace bad high surrogate", <<16#fffd/utf8>>, <<"\\uDC00"/utf8>>}, - {"replace naked high surrogate", - <<16#fffd/utf8, "hello world">>, - <<"\\ud800hello world"/utf8>> - }, - {"replace naked high surrogate", - <<16#fffd/utf8, "hello world">>, - <<"\\uD800hello world"/utf8>> - }, - {"replace naked low surrogate", - <<16#fffd/utf8, "hello world">>, - <<"\\udc00hello world"/utf8>> - }, - {"replace naked low surrogate", - <<16#fffd/utf8, "hello world">>, - <<"\\uDC00hello world"/utf8>> - }, - {"replace bad surrogate pair", <<16#fffd/utf8, 16#fffd/utf8>>, <<"\\ud800\\u0000">>}, - {"replace bad surrogate pair", <<16#fffd/utf8, 16#fffd/utf8>>, <<"\\uD800\\u0000">>} - ], - [{Title, ?_assertEqual([{string, Escaped}, end_json], decode(<<34, JSON/binary, 34>>))} - || {Title, Escaped, JSON} <- Cases - ] ++ - [{Title ++ " (incremental)", ?_assertEqual( - [{string, Escaped}, end_json], - incremental_decode(<<34, JSON/binary, 34>>) - )} || {Title, Escaped, JSON} <- Cases - ]. - - -bad_escaped_surrogate_test_() -> - Cases = [ - {"do not unescape bad high surrogate", <<"\\udc00">>}, - {"do not unescape naked high surrogate", <<"\\ud800hello world">>}, - {"do not unescape naked low surrogate", <<"\\udc00hello world">>}, - {"do not unescape bad surrogate pair", <<"\\ud800\\u0000">>} - ], - [{Title, ?_assertError(badarg, decode(<<34, JSON/binary, 34>>, [{strict, [utf8]}]))} - || {Title, JSON} <- Cases - ]. - - -escape_test_() -> - Cases = [ - {"backspace", <<"\b">>, <<"\\b">>}, - {"tab", <<"\t">>, <<"\\t">>}, - {"newline", <<"\n">>, <<"\\n">>}, - {"formfeed", <<"\f">>, <<"\\f">>}, - {"carriage return", <<"\r">>, <<"\\r">>}, - {"quote", <<"\"">>, <<"\\\"">>}, - {"backslash", <<"\\">>, <<"\\\\">>}, - {"control", <<0>>, <<"\\u0000">>} - ], - [{"escape " ++ Title, ?_assertEqual( - [{string, Escaped}, end_json], - decode(<<34, Escaped/binary, 34>>, [escaped_strings]) - )} || {Title, _Unescaped, Escaped} <- Cases - ] ++ - [{"do not escape " ++ Title, ?_assertEqual( - [{string, Unescaped}, end_json], - decode(<<34, Escaped/binary, 34>>) - )} || {Title, Unescaped, Escaped} <- Cases - ]. - - -special_escape_test_() -> - Cases = [ - {"escape forward slash", <<"\\/">>, <<"/"/utf8>>, [escaped_forward_slashes]}, - {"do not escape forward slash", <<"/">>, <<"/"/utf8>>, []}, - {"escape jsonp", <<"\\u2028">>, <<16#2028/utf8>>, []}, - {"do not escape jsonp", <<16#2028/utf8>>, <<16#2028/utf8>>, [unescaped_jsonp]} - ], - [{Title, ?_assertEqual( - [{string, Expect}, end_json], - decode(<<34, Raw/binary, 34>>, [escaped_strings] ++ Config) - )} || {Title, Expect, Raw, Config} <- Cases - ]. - - -uescape_test_() -> - [ - {"\"\\u0080\"", ?_assertEqual( - [{string, <<"\\u0080">>}, end_json], - decode(<<34, 128/utf8, 34>>, [uescape]) - )}, - {"\"\\u8ca8\\u5481\\u3002\\u0091\\u0091\"", ?_assertEqual( - [{string, <<"\\u8ca8\\u5481\\u3002\\u0091\\u0091">>}, end_json], - decode( - <<34,232,178,168,229,146,129,227,128,130,194,145,194,145,34>>, - [uescape] - ) - )}, - {"\"\\ud834\\udd1e\"", ?_assertEqual( - [{string, <<"\\ud834\\udd1e">>}, end_json], - decode(<<34, 240, 157, 132, 158, 34>>, [uescape]) - )}, - {"\"\\ud83d\\ude0a\"", ?_assertEqual( - [{string, <<"\\ud83d\\ude0a">>}, end_json], - decode(<<34, 240, 159, 152, 138, 34>>, [uescape]) - )} - ]. - - -single_quoted_string_test_() -> - Cases = [ - {"single quoted string", [{string, <<"hello world">>}, end_json], <<39, "hello world", 39>>}, - {"single quoted string with embedded double quotes", - [{string, <<"quoth the raven, \"nevermore\"">>}, end_json], - <<39, "quoth the raven, \"nevermore\"", 39>> - }, - {"escaped single quote", - [{string, <<"quoth the raven, 'nevermore'">>}, end_json], - <<39, "quoth the raven, \\'nevermore\\'", 39>> - }, - {"single quoted key", - [start_object, - {key, <<"key">>}, {string, <<"value">>}, - {key, <<"another key">>}, {string, <<"another value">>}, - end_object, end_json], - <<"{'key':'value','another key':'another value'}">> - } - ], - [{Title, ?_assertEqual(Expect, decode(Raw, []))} || {Title, Expect, Raw} <- Cases] ++ - [{Title, ?_assertError( - badarg, - decode(Raw, [{strict, [single_quotes]}]) - )} || {Title, _Expect, Raw} <- Cases - ]. - - -embedded_single_quoted_string_test_() -> - [ - {"string with embedded single quotes", ?_assertEqual( - [{string, <<"quoth the raven, 'nevermore'">>}, end_json], - decode(<<34, "quoth the raven, 'nevermore'", 34>>, []) - )}, - {"string with embedded single quotes", ?_assertEqual( - [{string, <<"quoth the raven, 'nevermore'">>}, end_json], - decode(<<34, "quoth the raven, 'nevermore'", 34>>, [{strict, [single_quotes]}]) - )} - ]. - - -ignored_bad_escapes_test_() -> - [ - {"ignore unrecognized escape sequence", ?_assertEqual( - [{string, <<"\\x25">>}, end_json], - decode(<<"\"\\x25\"">>, []) - )} - ]. - - -bom_test_() -> - [ - {"bom", ?_assertEqual( - [start_array, end_array, end_json], - decode(<<16#ef, 16#bb, 16#bf, "[]"/utf8>>, []) - )} - ]. - - -trailing_comma_test_() -> - [ - {"trailing comma in object", ?_assertEqual( - [start_object, {key, <<"key">>}, {literal, true}, end_object, end_json], - decode(<<"{\"key\": true,}">>, []) - )}, - {"strict trailing comma in object", ?_assertError( - badarg, - decode(<<"{\"key\": true,}">>, [{strict, [trailing_commas]}]) - )}, - {"two trailing commas in object", ?_assertError( - badarg, - decode(<<"{\"key\": true,,}">>, []) - )}, - {"comma in empty object", ?_assertError( - badarg, - decode(<<"{,}">>, []) - )}, - {"trailing comma in list", ?_assertEqual( - [start_array, {literal, true}, end_array, end_json], - decode(<<"[true,]">>, []) - )}, - {"strict trailing comma in list", ?_assertError( - badarg, - decode(<<"[true,]">>, [{strict, [trailing_commas]}]) - )}, - {"two trailing commas in list", ?_assertError( - badarg, - decode(<<"[true,,]">>, []) - )}, - {"comma in empty list", ?_assertError( - badarg, - decode(<<"[,]">>, []) - )} - ]. - - -incomplete_test_() -> - [ - {"stream false", ?_assertError( - badarg, - decode(<<"{">>) - )}, - {"stream true", ?_assertMatch( - {incomplete, _}, - decode(<<"{">>, [stream]) - )}, - {"complete input", ?_assertMatch( - {incomplete, _}, - decode(<<"{}">>, [stream]) - )} - ]. - - -error_test_() -> - Cases = [ - {"maybe_bom error", <<16#ef, 0>>}, - {"definitely_bom error", <<16#ef, 16#bb, 0>>}, - {"object error", <<"{"/utf8, 0>>}, - {"colon error", <<"{\"\""/utf8, 0>>}, - {"key error", <<"{\"\":1,"/utf8, 0>>}, - {"value error", <<0>>}, - {"negative error", <<"-"/utf8, 0>>}, - {"zero error", <<"0"/utf8, 0>>}, - {"integer error", <<"1"/utf8, 0>>}, - {"decimal error", <<"1.0"/utf8, 0>>}, - {"e error", <<"1e"/utf8, 0>>}, - {"ex error", <<"1e+"/utf8, 0>>}, - {"exp error", <<"1e1"/utf8, 0>>}, - {"exp error", <<"1.0e1"/utf8, 0>>}, - {"exp error", <<"1.e"/utf8>>}, - {"true error", <<"tru"/utf8, 0>>}, - {"false error", <<"fals"/utf8, 0>>}, - {"null error", <<"nul"/utf8, 0>>}, - {"maybe_done error", <<"[[]"/utf8, 0>>}, - {"done error", <<"[]"/utf8, 0>>} - ], - [{Title, ?_assertError(badarg, decode(State))} || {Title, State} <- Cases]. - - -custom_incomplete_handler_test_() -> - [ - {"custom incomplete handler", ?_assertError( - incomplete, - decode(<<>>, [{incomplete_handler, fun(_, _, _) -> erlang:error(incomplete) end}, stream]) - )} - ]. - - -return_tail_test_() -> - [ - {"return_tail with tail", ?_assertEqual( - {with_tail,[{}],<<"3">>}, - jsx:decode(<<"{} 3">>, [return_tail]) - )}, - {"return_tail without tail", ?_assertEqual( - {with_tail,[{}],<<"">>}, - jsx:decode(<<"{}">>, [return_tail]) - )}, - {"return_tail with trimmed whitespace", ?_assertEqual( - {with_tail,[{}],<<"">>}, - jsx:decode(<<"{} ">>, [return_tail]) - )}, - {"return_tail and streaming", ?_assertEqual( - {with_tail,[{}],<<"3">>}, - begin - {incomplete, F} = jsx:decode(<<"{">>, [return_tail, stream]), - F(<<"} 3">>) - end - )}, - {"return_tail and streaming", ?_assertEqual( - {with_tail,[{}],<<"">>}, - begin - %% In case of infinite stream of objects a user does not know - %% when to call F(end_stream). - %% So, return_tail overwrites conservative stream end. - %% This means that we don't need to call end_stream explicitly. - {incomplete, F} = jsx:decode(<<"{">>, [return_tail, stream]), - F(<<"}">>) - end - )} - ]. - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_encoder.erl b/_build/default/plugins/jsx/src/jsx_encoder.erl deleted file mode 100644 index 39140d872d..0000000000 --- a/_build/default/plugins/jsx/src/jsx_encoder.erl +++ /dev/null @@ -1,127 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 Alisdair Sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_encoder). - --export([encoder/3, encode/1, encode/2]). - --spec encoder(Handler::module(), State::any(), Config::list()) -> jsx:encoder(). - -encoder(Handler, State, Config) -> - Parser = jsx:parser(Handler, State, Config), - fun(Term) -> Parser(encode(Term) ++ [end_json]) end. - - --spec encode(Term::any()) -> any(). - -encode(Term) -> encode(Term, ?MODULE). - - --spec encode(Term::any(), EntryPoint::module()) -> any(). - --ifndef(maps_support). -encode(Term, EntryPoint) -> encode_(Term, EntryPoint). --endif. - --ifdef(maps_support). -encode(Map, _EntryPoint) when is_map(Map), map_size(Map) < 1 -> - [start_object, end_object]; -encode(Term, EntryPoint) when is_map(Term) -> - [start_object] ++ unpack(Term, EntryPoint); -encode(Term, EntryPoint) -> encode_(Term, EntryPoint). --endif. - -encode_([], _EntryPoint) -> [start_array, end_array]; -encode_([{}], _EntryPoint) -> [start_object, end_object]; - -%% datetime special case -encode_([{{_,_,_},{_,_,_}} = DateTime|Rest], EntryPoint) -> - [start_array] ++ [DateTime] ++ unhitch(Rest, EntryPoint); -encode_([{_, _}|_] = Term, EntryPoint) -> - [start_object] ++ unzip(Term, EntryPoint); -encode_(Term, EntryPoint) when is_list(Term) -> - [start_array] ++ unhitch(Term, EntryPoint); - -encode_(Else, _EntryPoint) -> [Else]. - - -unzip([{K, V}|Rest], EntryPoint) when is_integer(K); is_binary(K); is_atom(K) -> - [K] ++ EntryPoint:encode(V, EntryPoint) ++ unzip(Rest, EntryPoint); -unzip([], _) -> [end_object]; -unzip(_, _) -> erlang:error(badarg). - - -unhitch([V|Rest], EntryPoint) -> - EntryPoint:encode(V, EntryPoint) ++ unhitch(Rest, EntryPoint); -unhitch([], _) -> [end_array]. - - --ifdef(maps_support). -unpack(Map, EntryPoint) -> unpack(Map, maps:keys(Map), EntryPoint). - -unpack(Map, [K|Rest], EntryPoint) when is_integer(K); is_binary(K); is_atom(K) -> - [K] ++ EntryPoint:encode(maps:get(K, Map), EntryPoint) ++ unpack(Map, Rest, EntryPoint); -unpack(_, [], _) -> [end_object]. --endif. - - - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -parser(Term, Opts) -> (jsx:parser(jsx, [], Opts))(Term). - - -error_test_() -> - [ - {"value error", ?_assertError(badarg, parser(self(), []))}, - {"string error", ?_assertError(badarg, parser(<<239, 191, 191>>, [strict]))} - ]. - -custom_error_handler_test_() -> - Error = fun(Term, {_, State, _, _}, _) -> {State, Term} end, - [ - {"value error", ?_assertEqual( - {value, [self()]}, - parser(self(), [{error_handler, Error}]) - )}, - {"string error", ?_assertEqual( - {value, [{string, <<237, 160, 128>>}]}, - parser(<<237, 160, 128>>, [{error_handler, Error}, strict]) - )} - ]. - -improper_lists_test_() -> - [ - {"improper proplist", ?_assertError( - badarg, - encode([{<<"key">>, <<"value">>}, false]) - )}, - {"improper list", ?_assertError( - badarg, - encode([{literal, true}, false, null]) - )} - ]. - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_parser.erl b/_build/default/plugins/jsx/src/jsx_parser.erl deleted file mode 100644 index ca341c0e04..0000000000 --- a/_build/default/plugins/jsx/src/jsx_parser.erl +++ /dev/null @@ -1,1214 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 Alisdair Sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_parser). - --export([parser/3, resume/5]). --export([init/1, handle_event/2]). - - --spec parser(Handler::module(), State::any(), Config::list()) -> jsx:parser(). - -parser(Handler, State, Config) -> - fun(Tokens) -> value(Tokens, {Handler, Handler:init(State)}, [], jsx_config:parse_config(Config)) end. - - -%% resume allows continuation from interrupted decoding without having to explicitly export -%% all states --spec resume( - Rest::jsx:token(), - State::atom(), - Handler::{atom(), any()}, - Stack::list(atom()), - Config::jsx:config() - ) -> jsx:parser() | {incomplete, jsx:parser()}. - -resume(Rest, State, Handler, Stack, Config) -> - case State of - value -> value(Rest, Handler, Stack, Config); - object -> object(Rest, Handler, Stack, Config); - array -> array(Rest, Handler, Stack, Config); - maybe_done -> maybe_done(Rest, Handler, Stack, Config); - done -> done(Rest, Handler, Stack, Config) - end. - - --include("jsx_config.hrl"). - - -%% error, incomplete and event macros --ifndef(error). --define(error(State, Terms, Handler, Stack, Config), - case Config#config.error_handler of - false -> erlang:error(badarg); - F -> F(Terms, {parser, State, Handler, Stack}, jsx_config:config_to_list(Config)) - end - -). --endif. - - -incomplete(State, Handler, Stack, Config=#config{stream=false}) -> - ?error(State, [], Handler, Stack, Config); -incomplete(State, Handler, Stack, Config=#config{incomplete_handler=false}) -> - {incomplete, fun(End) when End == end_stream; End == end_json -> - case resume([end_json], State, Handler, Stack, Config) of - {incomplete, _} -> ?error(State, [], Handler, Stack, Config); - Else -> Else - end; - (Tokens) -> - resume(Tokens, State, Handler, Stack, Config) - end - }; -incomplete(State, Handler, Stack, Config=#config{incomplete_handler=F}) -> - F([], {parser, State, Handler, Stack}, jsx_config:config_to_list(Config)). - - -handle_event(Event, {Handler, State}, _Config) -> {Handler, Handler:handle_event(Event, State)}. - - -value([String|Tokens], Handler, Stack, Config) when is_binary(String) -> - try clean_string(String, Config) of Clean -> - maybe_done(Tokens, handle_event({string, Clean}, Handler, Config), Stack, Config) - catch error:badarg -> - ?error(value, [{string, String}|Tokens], Handler, Stack, Config) - end; -value([true|Tokens], Handler, Stack, Config) -> - maybe_done(Tokens, handle_event({literal, true}, Handler, Config), Stack, Config); -value([false|Tokens], Handler, Stack, Config) -> - maybe_done(Tokens, handle_event({literal, false}, Handler, Config), Stack, Config); -value([null|Tokens], Handler, Stack, Config) -> - maybe_done(Tokens, handle_event({literal, null}, Handler, Config), Stack, Config); -value([start_object|Tokens], Handler, Stack, Config) -> - object(Tokens, handle_event(start_object, Handler, Config), [object|Stack], Config); -value([start_array|Tokens], Handler, Stack, Config) -> - array(Tokens, handle_event(start_array, Handler, Config), [array|Stack], Config); -value([Number|Tokens], Handler, Stack, Config) when is_integer(Number) -> - maybe_done(Tokens, handle_event({integer, Number}, Handler, Config), Stack, Config); -value([Number|Tokens], Handler, Stack, Config) when is_float(Number) -> - maybe_done(Tokens, handle_event({float, Number}, Handler, Config), Stack, Config); -value([{raw, Raw}|Tokens], Handler, Stack, Config) when is_binary(Raw) -> - value((jsx:decoder(?MODULE, [], []))(Raw) ++ Tokens, Handler, Stack, Config); -value([{_,_,_}=Timestamp|Tokens], Handler, Stack, Config) -> - {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:now_to_datetime( - Timestamp), - value([{string, unicode:characters_to_binary(io_lib:format( - "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", - [Year, Month, Day, Hour, Min, Sec] - ))}|Tokens], - Handler, - Stack, - Config - ); -value([{{Year, Month, Day}, {Hour, Min, Sec}}|Tokens], Handler, Stack, Config) -when is_integer(Year), is_integer(Month), is_integer(Day), is_integer(Hour), is_integer(Min), is_integer(Sec) -> - value([{string, unicode:characters_to_binary(io_lib:format( - "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", - [Year, Month, Day, Hour, Min, Sec] - ))}|Tokens], - Handler, - Stack, - Config - ); -value([{{Year, Month, Day}, {Hour, Min, Sec}}|Tokens], Handler, Stack, Config) -when is_integer(Year), is_integer(Month), is_integer(Day), is_integer(Hour), is_integer(Min), is_float(Sec) -> - value([{string, unicode:characters_to_binary(io_lib:format( - "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~9.6.0fZ", - [Year, Month, Day, Hour, Min, Sec] - ))}|Tokens], - Handler, - Stack, - Config - ); -value([{literal, Value}|Tokens], Handler, Stack, Config) -when Value == true; Value == false; Value == null -> - value([Value] ++ Tokens, Handler, Stack, Config); -value([{integer, Value}|Tokens], Handler, Stack, Config) -when is_integer(Value) -> - value([Value] ++ Tokens, Handler, Stack, Config); -value([{float, Value}|Tokens], Handler, Stack, Config) -when is_float(Value) -> - value([Value] ++ Tokens, Handler, Stack, Config); -value([{string, Value}|Tokens], Handler, Stack, Config) -when is_binary(Value); is_atom(Value) -> - value([Value] ++ Tokens, Handler, Stack, Config); -value([{number, Value}|Tokens], Handler, Stack, Config) -when is_float(Value); is_integer(Value) -> - value([Value] ++ Tokens, Handler, Stack, Config); -value([String|Tokens], Handler, Stack, Config) when is_atom(String) -> - value([{string, atom_to_binary(String, utf8)}] ++ Tokens, Handler, Stack, Config); -value([], Handler, Stack, Config) -> - incomplete(value, Handler, Stack, Config); -value(BadTokens, Handler, Stack, Config) when is_list(BadTokens) -> - ?error(value, BadTokens, Handler, Stack, Config); -value(Token, Handler, Stack, Config) -> - value([Token], Handler, Stack, Config). - - -object([end_object|Tokens], Handler, [object|Stack], Config) -> - maybe_done(Tokens, handle_event(end_object, Handler, Config), Stack, Config); -object([{key, Key}|Tokens], Handler, Stack, Config) -when is_atom(Key); is_binary(Key); is_integer(Key) -> - object([Key|Tokens], Handler, Stack, Config); -object([Key|Tokens], Handler, [object|Stack], Config) -when is_atom(Key); is_binary(Key); is_integer(Key) -> - try clean_string(fix_key(Key), Config) - of K -> - value( - Tokens, - handle_event({key, K}, Handler, Config), - [object|Stack], - Config - ) - catch error:badarg -> - ?error(object, [{string, Key}|Tokens], Handler, Stack, Config) - end; -object([], Handler, Stack, Config) -> - incomplete(object, Handler, Stack, Config); -object(Token, Handler, Stack, Config) -> - object([Token], Handler, Stack, Config). - - -array([end_array|Tokens], Handler, [array|Stack], Config) -> - maybe_done(Tokens, handle_event(end_array, Handler, Config), Stack, Config); -array([], Handler, Stack, Config) -> - incomplete(array, Handler, Stack, Config); -array(Tokens, Handler, Stack, Config) when is_list(Tokens) -> - value(Tokens, Handler, Stack, Config); -array(Token, Handler, Stack, Config) -> - array([Token], Handler, Stack, Config). - - -maybe_done([end_json], Handler, [], Config) -> - done([end_json], Handler, [], Config); -maybe_done(Tokens, Handler, [object|_] = Stack, Config) when is_list(Tokens) -> - object(Tokens, Handler, Stack, Config); -maybe_done(Tokens, Handler, [array|_] = Stack, Config) when is_list(Tokens) -> - array(Tokens, Handler, Stack, Config); -maybe_done([], Handler, Stack, Config) -> - incomplete(maybe_done, Handler, Stack, Config); -maybe_done(BadTokens, Handler, Stack, Config) when is_list(BadTokens) -> - ?error(maybe_done, BadTokens, Handler, Stack, Config); -maybe_done(Token, Handler, Stack, Config) -> - maybe_done([Token], Handler, Stack, Config). - - -done([], Handler, [], Config=#config{stream=true}) -> - incomplete(done, Handler, [], Config); -done(Tokens, Handler, [], Config) when Tokens == [end_json]; Tokens == [] -> - {_, State} = handle_event(end_json, Handler, Config), - State; -done(BadTokens, Handler, Stack, Config) when is_list(BadTokens) -> - ?error(done, BadTokens, Handler, Stack, Config); -done(Token, Handler, Stack, Config) -> - done([Token], Handler, Stack, Config). - - -fix_key(Key) when is_atom(Key) -> atom_to_binary(Key, utf8); -fix_key(Key) when is_integer(Key) -> list_to_binary(integer_to_list(Key)); -fix_key(Key) when is_binary(Key) -> Key. - - -clean_string(Bin, #config{dirty_strings=true}) -> Bin; -clean_string(Bin, Config) -> clean(Bin, [], Config). - - -%% unroll the control characters -clean(<<0, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(0, Config)], Config); -clean(<<1, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(1, Config)], Config); -clean(<<2, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(2, Config)], Config); -clean(<<3, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(3, Config)], Config); -clean(<<4, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(4, Config)], Config); -clean(<<5, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(5, Config)], Config); -clean(<<6, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(6, Config)], Config); -clean(<<7, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(7, Config)], Config); -clean(<<8, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(8, Config)], Config); -clean(<<9, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(9, Config)], Config); -clean(<<10, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(10, Config)], Config); -clean(<<11, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(11, Config)], Config); -clean(<<12, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(12, Config)], Config); -clean(<<13, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(13, Config)], Config); -clean(<<14, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(14, Config)], Config); -clean(<<15, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(15, Config)], Config); -clean(<<16, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(16, Config)], Config); -clean(<<17, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(17, Config)], Config); -clean(<<18, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(18, Config)], Config); -clean(<<19, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(19, Config)], Config); -clean(<<20, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(20, Config)], Config); -clean(<<21, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(21, Config)], Config); -clean(<<22, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(22, Config)], Config); -clean(<<23, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(23, Config)], Config); -clean(<<24, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(24, Config)], Config); -clean(<<25, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(25, Config)], Config); -clean(<<26, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(26, Config)], Config); -clean(<<27, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(27, Config)], Config); -clean(<<28, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(28, Config)], Config); -clean(<<29, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(29, Config)], Config); -clean(<<30, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(30, Config)], Config); -clean(<<31, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(31, Config)], Config); -clean(<<34, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(34, Config)], Config); -clean(<<47, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(47, Config)], Config); -clean(<<92, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(92, Config)], Config); -clean(<> = Bin, Acc, Config=#config{uescape=true}) -> - case X of - X when X < 16#80 -> start_count(Bin, Acc, Config); - _ -> clean(Rest, [Acc, json_escape_sequence(X)], Config) - end; -%% u+2028 -clean(<<226, 128, 168, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(16#2028, Config)], Config); -%% u+2029 -clean(<<226, 128, 169, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(16#2029, Config)], Config); -clean(<<_/utf8, _/binary>> = Bin, Acc, Config) -> start_count(Bin, Acc, Config); -%% surrogates -clean(<<237, X, _, Rest/binary>>, Acc, Config) when X >= 160 -> - clean(Rest, [Acc, maybe_replace(surrogate, Config)], Config); -%% overlong encodings and missing continuations of a 2 byte sequence -clean(<>, Acc, Config) when X >= 192, X =< 223 -> - clean(strip_continuations(Rest, 1), [Acc, maybe_replace(badutf, Config)], Config); -%% overlong encodings and missing continuations of a 3 byte sequence -clean(<>, Acc, Config) when X >= 224, X =< 239 -> - clean(strip_continuations(Rest, 2), [Acc, maybe_replace(badutf, Config)], Config); -%% overlong encodings and missing continuations of a 4 byte sequence -clean(<>, Acc, Config) when X >= 240, X =< 247 -> - clean(strip_continuations(Rest, 3), [Acc, maybe_replace(badutf, Config)], Config); -clean(<<_, Rest/binary>>, Acc, Config) -> - clean(Rest, [Acc, maybe_replace(badutf, Config)], Config); -clean(<<>>, Acc, _) -> iolist_to_binary(Acc). - - -start_count(Bin, Acc, Config) -> - Size = count(Bin, 0, Config), - <> = Bin, - clean(Rest, [Acc, Clean], Config). - - -%% again, unrolling ascii makes a huge difference. sadly -count(<<0, _/binary>>, N, _) -> N; -count(<<1, _/binary>>, N, _) -> N; -count(<<2, _/binary>>, N, _) -> N; -count(<<3, _/binary>>, N, _) -> N; -count(<<4, _/binary>>, N, _) -> N; -count(<<5, _/binary>>, N, _) -> N; -count(<<6, _/binary>>, N, _) -> N; -count(<<7, _/binary>>, N, _) -> N; -count(<<8, _/binary>>, N, _) -> N; -count(<<9, _/binary>>, N, _) -> N; -count(<<10, _/binary>>, N, _) -> N; -count(<<11, _/binary>>, N, _) -> N; -count(<<12, _/binary>>, N, _) -> N; -count(<<13, _/binary>>, N, _) -> N; -count(<<14, _/binary>>, N, _) -> N; -count(<<15, _/binary>>, N, _) -> N; -count(<<16, _/binary>>, N, _) -> N; -count(<<17, _/binary>>, N, _) -> N; -count(<<18, _/binary>>, N, _) -> N; -count(<<19, _/binary>>, N, _) -> N; -count(<<20, _/binary>>, N, _) -> N; -count(<<21, _/binary>>, N, _) -> N; -count(<<22, _/binary>>, N, _) -> N; -count(<<23, _/binary>>, N, _) -> N; -count(<<24, _/binary>>, N, _) -> N; -count(<<25, _/binary>>, N, _) -> N; -count(<<26, _/binary>>, N, _) -> N; -count(<<27, _/binary>>, N, _) -> N; -count(<<28, _/binary>>, N, _) -> N; -count(<<29, _/binary>>, N, _) -> N; -count(<<30, _/binary>>, N, _) -> N; -count(<<31, _/binary>>, N, _) -> N; -count(<<32, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<33, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<34, _/binary>>, N, _) -> N; -count(<<35, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<36, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<37, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<38, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<39, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<40, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<41, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<42, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<43, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<44, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<45, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<46, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<47, _/binary>>, N, _) -> N; -count(<<48, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<49, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<50, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<51, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<52, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<53, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<54, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<55, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<56, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<57, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<58, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<59, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<60, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<61, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<62, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<63, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<64, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<65, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<66, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<67, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<68, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<69, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<70, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<71, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<72, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<73, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<74, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<75, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<76, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<77, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<78, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<79, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<80, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<81, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<82, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<83, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<84, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<85, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<86, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<87, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<88, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<89, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<90, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<91, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<92, _/binary>>, N, _) -> N; -count(<<93, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<94, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<95, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<96, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<97, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<98, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<99, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<100, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<101, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<102, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<103, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<104, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<105, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<106, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<107, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<108, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<109, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<110, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<111, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<112, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<113, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<114, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<115, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<116, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<117, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<118, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<119, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<120, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<121, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<122, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<123, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<124, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<125, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<126, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<127, Rest/binary>>, N, Config) -> - count(Rest, N + 1, Config); -count(<<_/utf8, _/binary>>, N, #config{uescape=true}) -> N; -count(<>, N, Config) -> - case X of - X when X < 16#800 -> count(Rest, N + 2, Config); - 16#2028 -> N; - 16#2029 -> N; - X when X < 16#10000 -> count(Rest, N + 3, Config); - _ -> count(Rest, N + 4, Config) - end; -count(<<_, _/binary>>, N, _) -> N; -count(<<>>, N, _) -> N. - - -strip_continuations(Bin, 0) -> Bin; -strip_continuations(<>, N) when X >= 128, X =< 191 -> - strip_continuations(Rest, N - 1); -%% not a continuation byte -strip_continuations(Bin, _) -> Bin. - - -maybe_replace($\b, #config{escaped_strings=true}) -> <<$\\, $b>>; -maybe_replace($\t, #config{escaped_strings=true}) -> <<$\\, $t>>; -maybe_replace($\n, #config{escaped_strings=true}) -> <<$\\, $n>>; -maybe_replace($\f, #config{escaped_strings=true}) -> <<$\\, $f>>; -maybe_replace($\r, #config{escaped_strings=true}) -> <<$\\, $r>>; -maybe_replace($\", #config{escaped_strings=true}) -> <<$\\, $\">>; -maybe_replace($/, Config=#config{escaped_strings=true}) -> - case Config#config.escaped_forward_slashes of - true -> <<$\\, $/>>; - false -> <<$/>> - end; -maybe_replace($\\, #config{escaped_strings=true}) -> <<$\\, $\\>>; -maybe_replace(X, #config{escaped_strings=true}) when X < 32 -> - json_escape_sequence(X); -maybe_replace(X, Config=#config{escaped_strings=true}) when X == 16#2028; X == 16#2029 -> - case Config#config.unescaped_jsonp of - true -> <>; - false -> json_escape_sequence(X) - end; -maybe_replace(Atom, #config{strict_utf8=true}) when is_atom(Atom) -> - erlang:error(badarg); -maybe_replace(surrogate, _Config) -> - <<16#fffd/utf8>>; -maybe_replace(badutf, _Config) -> - <<16#fffd/utf8>>; -maybe_replace(X, _Config) -> - <>. - - -%% convert a codepoint to it's \uXXXX equiv. -json_escape_sequence(X) when X < 65536 -> - <> = <>, - <<$\\, $u, (to_hex(A)), (to_hex(B)), (to_hex(C)), (to_hex(D))>>; -json_escape_sequence(X) -> - Adjusted = X - 16#10000, - <> = <>, - [json_escape_sequence(A + 16#d800), json_escape_sequence(B + 16#dc00)]. - - -to_hex(10) -> $a; -to_hex(11) -> $b; -to_hex(12) -> $c; -to_hex(13) -> $d; -to_hex(14) -> $e; -to_hex(15) -> $f; -to_hex(X) -> X + 48. %% ascii "1" is [49], "2" is [50], etc... - - -%% for raw input --spec init(proplists:proplist()) -> list(). - -init([]) -> []. - - --spec handle_event(Event::any(), Acc::list()) -> list(). - -handle_event(end_json, State) -> lists:reverse(State); -handle_event(Event, State) -> [Event] ++ State. - - - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -parse(Events, Config) -> value(Events, {jsx, []}, [], jsx_config:parse_config(Config)). - - -error_test_() -> - [ - {"value error", ?_assertError(badarg, parse([self()], []))}, - {"maybe_done error", ?_assertError(badarg, parse([start_array, end_array, start_array, end_json], []))}, - {"done error", ?_assertError(badarg, parse([{string, <<"">>}, {literal, true}, end_json], []))}, - {"string error", ?_assertError(badarg, parse([{string, <<237, 160, 128>>}, end_json], [strict]))} - ]. - - -custom_error_handler_test_() -> - Error = fun(Rest, {_, State, _, _}, _) -> {State, Rest} end, - [ - {"value error", ?_assertEqual( - {value, [self()]}, - parse([self()], [{error_handler, Error}]) - )}, - {"maybe_done error", ?_assertEqual( - {maybe_done, [start_array, end_json]}, - parse([start_array, end_array, start_array, end_json], [{error_handler, Error}]) - )}, - {"done error", ?_assertEqual( - {maybe_done, [{literal, true}, end_json]}, - parse([{string, <<"">>}, {literal, true}, end_json], [{error_handler, Error}]) - )}, - {"string error", ?_assertEqual( - {value, [{string, <<237, 160, 128>>}, end_json]}, - parse([{string, <<237, 160, 128>>}, end_json], [{error_handler, Error}, strict]) - )} - ]. - - -incomplete_test_() -> - Cases = [ - {"incomplete value", []}, - {"incomplete object", [start_object]}, - {"incomplete array", [start_array]}, - {"incomplete maybe_done", [start_array, end_array]} - ], - [{Title, ?_assertError(badarg, parse(Events, []))} - || {Title, Events} <- Cases - ]. - - -custom_incomplete_handler_test_() -> - [ - {"custom incomplete handler", ?_assertError( - badarg, - parse([], [{incomplete_handler, fun(_, _, _) -> erlang:error(badarg) end}]) - )} - ]. - - -raw_test_() -> - Parse = fun(Events, Config) -> (parser(?MODULE, [], Config))(Events ++ [end_json]) end, - [ - {"raw empty list", ?_assertEqual( - [start_array, end_array], - Parse([{raw, <<"[]">>}], []) - )}, - {"raw empty object", ?_assertEqual( - [start_object, end_object], - Parse([{raw, <<"{}">>}], []) - )}, - {"raw chunk inside stream", ?_assertEqual( - [start_object, {key, <<"key">>}, start_array, {literal, true}, end_array, end_object], - Parse([start_object, {key, <<"key">>}, {raw, <<"[true]">>}, end_object], []) - )} - ]. - - -%% erlang refuses to encode certain codepoints, so fake them -to_fake_utf8(N) when N < 16#0080 -> <>; -to_fake_utf8(N) when N < 16#0800 -> - <<0:5, Y:5, X:6>> = <>, - <<2#110:3, Y:5, 2#10:2, X:6>>; -to_fake_utf8(N) when N < 16#10000 -> - <> = <>, - <<2#1110:4, Z:4, 2#10:2, Y:6, 2#10:2, X:6>>; -to_fake_utf8(N) -> - <<0:3, W:3, Z:6, Y:6, X:6>> = <>, - <<2#11110:5, W:3, 2#10:2, Z:6, 2#10:2, Y:6, 2#10:2, X:6>>. - - -codepoints() -> - unicode:characters_to_binary( - [32, 33] - ++ lists:seq(35, 46) - ++ lists:seq(48, 91) - ++ lists:seq(93, 16#2027) - ++ lists:seq(16#202a, 16#d7ff) - ++ lists:seq(16#e000, 16#ffff) - ). - - -extended_codepoints() -> - unicode:characters_to_binary( - lists:seq(16#10000, 16#1ffff) ++ [ - 16#20000, 16#30000, 16#40000, 16#50000, 16#60000, - 16#70000, 16#80000, 16#90000, 16#a0000, 16#b0000, - 16#c0000, 16#d0000, 16#e0000, 16#f0000, 16#100000 - ] - ). - - -surrogates() -> [ to_fake_utf8(N) || N <- lists:seq(16#d800, 16#dfff) ]. - - -clean_string_helper(String) -> - try clean_string(String, #config{strict_utf8=true}) of Clean -> Clean - catch error:badarg -> {error, badarg} - end. - - -clean_string_test_() -> - [ - {"clean codepoints", ?_assertEqual( - codepoints(), - clean_string(codepoints(), #config{}) - )}, - {"clean extended codepoints", ?_assertEqual( - extended_codepoints(), - clean_string(extended_codepoints(), #config{}) - )}, - {"escape path codepoints", ?_assertEqual( - codepoints(), - clean_string(codepoints(), #config{escaped_strings=true}) - )}, - {"escape path extended codepoints", ?_assertEqual( - extended_codepoints(), - clean_string(extended_codepoints(), #config{escaped_strings=true}) - )}, - {"error surrogates", ?_assertEqual( - lists:duplicate(length(surrogates()), {error, badarg}), - lists:map(fun(Codepoint) -> clean_string_helper(Codepoint) end, surrogates()) - )}, - {"clean surrogates", ?_assertEqual( - lists:duplicate(length(surrogates()), <<16#fffd/utf8>>), - lists:map(fun(Codepoint) -> clean_string(Codepoint, #config{}) end, surrogates()) - )} - ]. - - -escape_test_() -> - [ - {"maybe_escape backspace", ?_assertEqual( - <<"\\b">>, - clean_string(<<16#0008/utf8>>, #config{escaped_strings=true}) - )}, - {"don't escape backspace", ?_assertEqual( - <<"\b">>, - clean_string(<<16#0008/utf8>>, #config{}) - )}, - {"maybe_escape tab", ?_assertEqual( - <<"\\t">>, - clean_string(<<16#0009/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape newline", ?_assertEqual( - <<"\\n">>, - clean_string(<<16#000a/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape formfeed", ?_assertEqual( - <<"\\f">>, - clean_string(<<16#000c/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape carriage return", ?_assertEqual( - <<"\\r">>, - clean_string(<<16#000d/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape quote", ?_assertEqual( - <<"\\\"">>, - clean_string(<<16#0022/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape forward slash", ?_assertEqual( - <<"\\/">>, - clean_string(<<16#002f/utf8>>, #config{escaped_strings=true, escaped_forward_slashes=true}) - )}, - {"do not maybe_escape forward slash", ?_assertEqual( - <<"/">>, - clean_string(<<16#002f/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape backslash", ?_assertEqual( - <<"\\\\">>, - clean_string(<<16#005c/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape jsonp (u2028)", ?_assertEqual( - <<"\\u2028">>, - clean_string(<<16#2028/utf8>>, #config{escaped_strings=true}) - )}, - {"do not maybe_escape jsonp (u2028)", ?_assertEqual( - <<16#2028/utf8>>, - clean_string(<<16#2028/utf8>>, #config{escaped_strings=true, unescaped_jsonp=true}) - )}, - {"maybe_escape jsonp (u2029)", ?_assertEqual( - <<"\\u2029">>, - clean_string(<<16#2029/utf8>>, #config{escaped_strings=true}) - )}, - {"do not maybe_escape jsonp (u2029)", ?_assertEqual( - <<16#2029/utf8>>, - clean_string(<<16#2029/utf8>>, #config{escaped_strings=true, unescaped_jsonp=true}) - )}, - {"maybe_escape u0000", ?_assertEqual( - <<"\\u0000">>, - clean_string(<<16#0000/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0001", ?_assertEqual( - <<"\\u0001">>, - clean_string(<<16#0001/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0002", ?_assertEqual( - <<"\\u0002">>, - clean_string(<<16#0002/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0003", ?_assertEqual( - <<"\\u0003">>, - clean_string(<<16#0003/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0004", ?_assertEqual( - <<"\\u0004">>, - clean_string(<<16#0004/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0005", ?_assertEqual( - <<"\\u0005">>, - clean_string(<<16#0005/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0006", ?_assertEqual( - <<"\\u0006">>, - clean_string(<<16#0006/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0007", ?_assertEqual( - <<"\\u0007">>, - clean_string(<<16#0007/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u000b", ?_assertEqual( - <<"\\u000b">>, - clean_string(<<16#000b/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u000e", ?_assertEqual( - <<"\\u000e">>, - clean_string(<<16#000e/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u000f", ?_assertEqual( - <<"\\u000f">>, - clean_string(<<16#000f/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0010", ?_assertEqual( - <<"\\u0010">>, - clean_string(<<16#0010/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0011", ?_assertEqual( - <<"\\u0011">>, - clean_string(<<16#0011/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0012", ?_assertEqual( - <<"\\u0012">>, - clean_string(<<16#0012/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0013", ?_assertEqual( - <<"\\u0013">>, - clean_string(<<16#0013/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0014", ?_assertEqual( - <<"\\u0014">>, - clean_string(<<16#0014/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0015", ?_assertEqual( - <<"\\u0015">>, - clean_string(<<16#0015/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0016", ?_assertEqual( - <<"\\u0016">>, - clean_string(<<16#0016/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0017", ?_assertEqual( - <<"\\u0017">>, - clean_string(<<16#0017/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0018", ?_assertEqual( - <<"\\u0018">>, - clean_string(<<16#0018/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u0019", ?_assertEqual( - <<"\\u0019">>, - clean_string(<<16#0019/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u001a", ?_assertEqual( - <<"\\u001a">>, - clean_string(<<16#001a/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u001b", ?_assertEqual( - <<"\\u001b">>, - clean_string(<<16#001b/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u001c", ?_assertEqual( - <<"\\u001c">>, - clean_string(<<16#001c/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u001d", ?_assertEqual( - <<"\\u001d">>, - clean_string(<<16#001d/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u001e", ?_assertEqual( - <<"\\u001e">>, - clean_string(<<16#001e/utf8>>, #config{escaped_strings=true}) - )}, - {"maybe_escape u001f", ?_assertEqual( - <<"\\u001f">>, - clean_string(<<16#001f/utf8>>, #config{escaped_strings=true}) - )} - ]. - - -bad_utf8_test_() -> - [ - {"orphan continuation byte u+0080", ?_assertError( - badarg, - clean_string(<<16#0080>>, #config{strict_utf8=true}) - )}, - {"orphan continuation byte u+0080 replaced", ?_assertEqual( - <<16#fffd/utf8>>, - clean_string(<<16#0080>>, #config{}) - )}, - {"orphan continuation byte u+00bf", ?_assertError( - badarg, - clean_string(<<16#00bf>>, #config{strict_utf8=true}) - )}, - {"orphan continuation byte u+00bf replaced", ?_assertEqual( - <<16#fffd/utf8>>, - clean_string(<<16#00bf>>, #config{}) - )}, - {"2 continuation bytes", ?_assertError( - badarg, - clean_string(<<(binary:copy(<<16#0080>>, 2))/binary>>, #config{strict_utf8=true}) - )}, - {"2 continuation bytes replaced", ?_assertEqual( - binary:copy(<<16#fffd/utf8>>, 2), - clean_string(<<(binary:copy(<<16#0080>>, 2))/binary>>, #config{}) - )}, - {"3 continuation bytes", ?_assertError( - badarg, - clean_string(<<(binary:copy(<<16#0080>>, 3))/binary>>, #config{strict_utf8=true}) - )}, - {"3 continuation bytes replaced", ?_assertEqual( - binary:copy(<<16#fffd/utf8>>, 3), - clean_string(<<(binary:copy(<<16#0080>>, 3))/binary>>, #config{}) - )}, - {"4 continuation bytes", ?_assertError( - badarg, - clean_string(<<(binary:copy(<<16#0080>>, 4))/binary>>, #config{strict_utf8=true}) - )}, - {"4 continuation bytes replaced", ?_assertEqual( - binary:copy(<<16#fffd/utf8>>, 4), - clean_string(<<(binary:copy(<<16#0080>>, 4))/binary>>, #config{}) - )}, - {"5 continuation bytes", ?_assertError( - badarg, - clean_string(<<(binary:copy(<<16#0080>>, 5))/binary>>, #config{strict_utf8=true}) - )}, - {"5 continuation bytes replaced", ?_assertEqual( - binary:copy(<<16#fffd/utf8>>, 5), - clean_string(<<(binary:copy(<<16#0080>>, 5))/binary>>, #config{}) - )}, - {"6 continuation bytes", ?_assertError( - badarg, - clean_string(<<(binary:copy(<<16#0080>>, 6))/binary>>, #config{strict_utf8=true}) - )}, - {"6 continuation bytes replaced", ?_assertEqual( - binary:copy(<<16#fffd/utf8>>, 6), - clean_string(<<(binary:copy(<<16#0080>>, 6))/binary>>, #config{}) - )}, - {"all continuation bytes", ?_assertError( - badarg, - clean_string(<<(list_to_binary(lists:seq(16#0080, 16#00bf)))/binary>>, #config{strict_utf8=true}) - )}, - {"all continuation bytes replaced", ?_assertEqual( - binary:copy(<<16#fffd/utf8>>, length(lists:seq(16#0080, 16#00bf))), - clean_string( - <<(list_to_binary(lists:seq(16#0080, 16#00bf)))/binary>>, - #config{} - ) - )}, - {"lonely start byte", ?_assertError( - badarg, - clean_string(<<16#00c0>>, #config{strict_utf8=true}) - )}, - {"lonely start byte replaced", ?_assertEqual( - <<16#fffd/utf8>>, - clean_string(<<16#00c0>>, #config{}) - )}, - {"lonely start bytes (2 byte)", ?_assertError( - badarg, - clean_string(<<16#00c0, 32, 16#00df>>, #config{strict_utf8=true}) - )}, - {"lonely start bytes (2 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32, 16#fffd/utf8>>, - clean_string(<<16#00c0, 32, 16#00df>>, #config{}) - )}, - {"lonely start bytes (3 byte)", ?_assertError( - badarg, - clean_string(<<16#00e0, 32, 16#00ef>>, #config{strict_utf8=true}) - )}, - {"lonely start bytes (3 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32, 16#fffd/utf8>>, - clean_string(<<16#00e0, 32, 16#00ef>>, #config{}) - )}, - {"lonely start bytes (4 byte)", ?_assertError( - badarg, - clean_string(<<16#00f0, 32, 16#00f7>>, #config{strict_utf8=true}) - )}, - {"lonely start bytes (4 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32, 16#fffd/utf8>>, - clean_string(<<16#00f0, 32, 16#00f7>>, #config{}) - )}, - {"missing continuation byte (3 byte)", ?_assertError( - badarg, - clean_string(<<224, 160, 32>>, #config{strict_utf8=true}) - )}, - {"missing continuation byte (3 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<224, 160, 32>>, #config{}) - )}, - {"missing continuation byte (4 byte missing one)", ?_assertError( - badarg, - clean_string(<<240, 144, 128, 32>>, #config{strict_utf8=true}) - )}, - {"missing continuation byte (4 byte missing one) replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<240, 144, 128, 32>>, #config{}) - )}, - {"missing continuation byte (4 byte missing two)", ?_assertError( - badarg, - clean_string(<<240, 144, 32>>, #config{strict_utf8=true}) - )}, - {"missing continuation byte (4 byte missing two) replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<240, 144, 32>>, #config{}) - )}, - {"overlong encoding of u+002f (2 byte)", ?_assertError( - badarg, - clean_string(<<16#c0, 16#af, 32>>, #config{strict_utf8=true}) - )}, - {"overlong encoding of u+002f (2 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<16#c0, 16#af, 32>>, #config{}) - )}, - {"overlong encoding of u+002f (3 byte)", ?_assertError( - badarg, - clean_string(<<16#e0, 16#80, 16#af, 32>>, #config{strict_utf8=true}) - )}, - {"overlong encoding of u+002f (3 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<16#e0, 16#80, 16#af, 32>>, #config{}) - )}, - {"overlong encoding of u+002f (4 byte)", ?_assertError( - badarg, - clean_string(<<16#f0, 16#80, 16#80, 16#af, 32>>, #config{strict_utf8=true}) - )}, - {"overlong encoding of u+002f (4 byte) replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<16#f0, 16#80, 16#80, 16#af, 32>>, #config{}) - )}, - {"highest overlong 2 byte sequence", ?_assertError( - badarg, - clean_string(<<16#c1, 16#bf, 32>>, #config{strict_utf8=true}) - )}, - {"highest overlong 2 byte sequence replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<16#c1, 16#bf, 32>>, #config{}) - )}, - {"highest overlong 3 byte sequence", ?_assertError( - badarg, - clean_string(<<16#e0, 16#9f, 16#bf, 32>>, #config{strict_utf8=true}) - )}, - {"highest overlong 3 byte sequence replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<16#e0, 16#9f, 16#bf, 32>>, #config{}) - )}, - {"highest overlong 4 byte sequence", ?_assertError( - badarg, - clean_string(<<16#f0, 16#8f, 16#bf, 16#bf, 32>>, #config{strict_utf8=true}) - )}, - {"highest overlong 4 byte sequence replaced", ?_assertEqual( - <<16#fffd/utf8, 32>>, - clean_string(<<16#f0, 16#8f, 16#bf, 16#bf, 32>>, #config{}) - )} - ]. - - -json_escape_sequence_test_() -> - [ - {"json escape sequence test - 16#0000", ?_assertEqual(<<"\\u0000"/utf8>>, json_escape_sequence(16#0000))}, - {"json escape sequence test - 16#abc", ?_assertEqual(<<"\\u0abc"/utf8>>, json_escape_sequence(16#abc))}, - {"json escape sequence test - 16#def", ?_assertEqual(<<"\\u0def"/utf8>>, json_escape_sequence(16#def))} - ]. - - -uescape_test_() -> - [ - {"\"\\u0080\"", ?_assertEqual( - <<"\\u0080">>, - clean_string(<<128/utf8>>, #config{uescape=true}) - )}, - {"\"\\u8ca8\\u5481\\u3002\\u0091\\u0091\"", ?_assertEqual( - <<"\\u8ca8\\u5481\\u3002\\u0091\\u0091">>, - clean_string( - <<232,178,168,229,146,129,227,128,130,194,145,194,145>>, - #config{uescape=true} - ) - )}, - {"\"\\ud834\\udd1e\"", ?_assertEqual( - <<"\\ud834\\udd1e">>, - clean_string(<<240, 157, 132, 158>>, #config{uescape=true}) - )}, - {"\"\\ud83d\\ude0a\"", ?_assertEqual( - <<"\\ud83d\\ude0a">>, - clean_string(<<240, 159, 152, 138>>, #config{uescape=true}) - )} - ]. - - -fix_key_test_() -> - [ - {"binary key", ?_assertEqual(fix_key(<<"foo">>), <<"foo">>)}, - {"atom key", ?_assertEqual(fix_key(foo), <<"foo">>)}, - {"integer key", ?_assertEqual(fix_key(123), <<"123">>)} - ]. - - -datetime_test_() -> - [ - {"datetime", ?_assertEqual( - [start_array, {string, <<"2014-08-13T23:12:34Z">>}, end_array, end_json], - parse([start_array, {{2014,08,13},{23,12,34}}, end_array, end_json], []) - )}, - {"datetime", ?_assertEqual( - [start_array, {string, <<"2014-08-13T23:12:34.363369Z">>}, end_array, end_json], - parse([start_array, {{2014,08,13},{23,12,34.363369}}, end_array, end_json], []) - )} - ]. - - -timestamp_test_() -> - [ - {"timestamp", ?_assertEqual( - [start_array, {string, <<"2016-01-15T18:19:28Z">>}, end_array, end_json], - parse([start_array, {1452,881968,111772}, end_array, end_json], []) - )} - ]. - - -rogue_tuple_test_() -> - [ - {"kv in value position of object", ?_assertError( - badarg, - parse([start_object, <<"key">>, {<<"key">>, <<"value">>}, end_object, end_json], []) - )}, - {"kv in value position of list", ?_assertError( - badarg, - parse([start_array, {<<"key">>, <<"value">>}, end_array, end_json], []) - )} - ]. - - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_to_json.erl b/_build/default/plugins/jsx/src/jsx_to_json.erl deleted file mode 100644 index fb14df3d80..0000000000 --- a/_build/default/plugins/jsx/src/jsx_to_json.erl +++ /dev/null @@ -1,409 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 alisdair sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_to_json). - --export([to_json/2, format/2]). --export([init/1, handle_event/2]). --export([start_json/0, start_json/1]). --export([start_object/1, start_array/1, finish/1, insert/2, get_key/1, get_value/1]). - - --record(config, { - space = 0, - indent = 0, - depth = 0, - newline = <<$\n>> -}). - --type config() :: list(). --export_type([config/0]). - - --spec to_json(Source::any(), Config::config()) -> binary(). - -to_json(Source, Config) when is_list(Config) -> - (jsx:encoder(?MODULE, Config, jsx_config:extract_config(Config ++ [escaped_strings])))(Source). - - --spec format(Source::binary(), Config::config()) -> binary(). - -format(Source, Config) when is_binary(Source) andalso is_list(Config) -> - (jsx:decoder(?MODULE, Config, jsx_config:extract_config(Config ++ [escaped_strings])))(Source); -format(_, _) -> erlang:error(badarg). - - -parse_config(Config) -> parse_config(Config, #config{}). - -parse_config([{space, Val}|Rest], Config) when is_integer(Val), Val > 0 -> - parse_config(Rest, Config#config{space = Val}); -parse_config([space|Rest], Config) -> - parse_config(Rest, Config#config{space = 1}); -parse_config([{indent, Val}|Rest], Config) when is_integer(Val), Val > 0 -> - parse_config(Rest, Config#config{indent = Val}); -parse_config([indent|Rest], Config) -> - parse_config(Rest, Config#config{indent = 1}); -parse_config([{newline, Val}|Rest], Config) when is_binary(Val) -> - parse_config(Rest, Config#config{newline = Val}); -parse_config([{K, _}|Rest] = Options, Config) -> - case lists:member(K, jsx_config:valid_flags()) of - true -> parse_config(Rest, Config) - ; false -> erlang:error(badarg, [Options, Config]) - end; -parse_config([K|Rest] = Options, Config) -> - case lists:member(K, jsx_config:valid_flags()) of - true -> parse_config(Rest, Config) - ; false -> erlang:error(badarg, [Options, Config]) - end; -parse_config([], Config) -> - Config. - - --define(start_object, <<"{">>). --define(start_array, <<"[">>). --define(end_object, <<"}">>). --define(end_array, <<"]">>). --define(colon, <<":">>). --define(comma, <<",">>). --define(quote, <<"\"">>). --define(space, <<" ">>). --define(newline, <<"\n">>). - - --type state() :: {unicode:charlist(), #config{}}. --spec init(Config::proplists:proplist()) -> state(). - -init(Config) -> {[], parse_config(Config)}. - - --spec handle_event(Event::any(), State::state()) -> state(). - -handle_event(end_json, State) -> get_value(State); - -handle_event(start_object, State) -> start_object(State); -handle_event(end_object, State) -> finish(State); - -handle_event(start_array, State) -> start_array(State); -handle_event(end_array, State) -> finish(State); - -handle_event({Type, Event}, {_, Config} = State) -> insert(encode(Type, Event, Config), State). - - -encode(string, String, _Config) -> - [?quote, String, ?quote]; -encode(key, Key, _Config) -> - [?quote, Key, ?quote]; -encode(literal, Literal, _Config) -> - erlang:atom_to_list(Literal); -encode(integer, Integer, _Config) -> - erlang:integer_to_list(Integer); -encode(float, Float, _Config) -> - io_lib:format("~p", [Float]). - - -space(Config) -> - case Config#config.space of - 0 -> <<>> - ; X when X > 0 -> binary:copy(?space, X) - end. - - -indent(Config) -> - case Config#config.indent of - 0 -> <<>> - ; X when X > 0 -> <<(Config#config.newline)/binary, (binary:copy(?space, X * Config#config.depth))/binary>> - end. - - -indent_or_space(Config) -> - case Config#config.indent > 0 of - true -> indent(Config) - ; false -> space(Config) - end. - - -%% internal state is a stack and a config object -%% `{Stack, Config}` -%% the stack is a list of in progress objects/arrays -%% `[Current, Parent, Grandparent,...OriginalAncestor]` -%% an object has the representation on the stack of -%% `{object, Object}` -%% of if there's a key with a yet to be matched value -%% `{object, Key, Object}` -%% an array looks like -%% `{array, Array}` -%% `Object` and `Array` are utf8 encoded binaries - -start_json() -> {[], #config{}}. - -start_json(Config) when is_list(Config) -> {[], parse_config(Config)}. - -%% allocate a new object on top of the stack -start_object({Stack, Config = #config{depth = Depth}}) -> - {[{object, ?start_object}] ++ Stack, Config#config{depth = Depth + 1}}. - -%% allocate a new array on top of the stack -start_array({Stack, Config = #config{depth = Depth}}) -> - {[{array, ?start_array}] ++ Stack, Config#config{depth = Depth + 1}}. - -%% finish an object or array and insert it into the parent object if it exists -finish({Stack, Config = #config{depth = Depth}}) -> - NewConfig = Config#config{depth = Depth - 1}, - finish_({Stack, NewConfig}). - -finish_({[{object, <<"{">>}], Config}) -> {<<"{}">>, Config}; -finish_({[{array, <<"[">>}], Config}) -> {<<"[]">>, Config}; -finish_({[{object, <<"{">>}|Rest], Config}) -> insert(<<"{}">>, {Rest, Config}); -finish_({[{array, <<"[">>}|Rest], Config}) -> insert(<<"[]">>, {Rest, Config}); -finish_({[{object, Object}], Config}) -> - {[Object, indent(Config), ?end_object], Config}; -finish_({[{object, Object}|Rest], Config}) -> - insert([Object, indent(Config), ?end_object], {Rest, Config}); -finish_({[{array, Array}], Config}) -> - {[Array, indent(Config), ?end_array], Config}; -finish_({[{array, Array}|Rest], Config}) -> - insert([Array, indent(Config), ?end_array], {Rest, Config}); -finish_(_) -> erlang:error(badarg). - -%% insert a value when there's no parent object or array -insert(Value, {[], Config}) -> - {Value, Config}; -%% insert a key or value into an object or array, autodetects the 'right' thing -insert(Key, {[{object, Object}|Rest], Config}) -> - {[{object, Key, Object}] ++ Rest, Config}; -insert(Value, {[{object, Key, ?start_object}|Rest], Config}) -> - { - [{object, [ - ?start_object, - indent(Config), - Key, - ?colon, - space(Config), - Value - ]}] ++ Rest, - Config - }; -insert(Value, {[{object, Key, Object}|Rest], Config}) -> - { - [{object, [ - Object, - ?comma, - indent_or_space(Config), - Key, - ?colon, - space(Config), - Value - ]}] ++ Rest, - Config - }; -insert(Value, {[{array, ?start_array}|Rest], Config}) -> - {[{array, [?start_array, indent(Config), Value]}] ++ Rest, Config}; -insert(Value, {[{array, Array}|Rest], Config}) -> - { - [{array, [Array, - ?comma, - indent_or_space(Config), - Value - ]}] ++ Rest, - Config - }; -insert(_, _) -> erlang:error(badarg). - - -get_key({[{object, Key, _}|_], _}) -> Key; -get_key(_) -> erlang:error(badarg). - - -get_value({Value, _Config}) -> - try unicode:characters_to_binary(Value) - catch error:_ -> erlang:error(badarg) - end; -get_value(_) -> erlang:error(badarg). - - - -%% eunit tests - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -config_test_() -> - [ - {"empty config", ?_assertEqual(#config{}, parse_config([]))}, - {"unspecified indent/space", ?_assertEqual( - #config{space=1, indent=1}, - parse_config([space, indent]) - )}, - {"specific indent", ?_assertEqual( - #config{indent=4}, - parse_config([{indent, 4}]) - )}, - {"specific space", ?_assertEqual( - #config{space=2}, - parse_config([{space, 2}]) - )}, - {"specific space and indent", ?_assertEqual( - #config{space=2, indent=2}, - parse_config([{space, 2}, {indent, 2}]) - )}, - {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, - {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} - ]. - - -space_test_() -> - [ - {"no space", ?_assertEqual(<<>>, space(#config{space=0}))}, - {"one space", ?_assertEqual(<<" ">>, space(#config{space=1}))}, - {"four spaces", ?_assertEqual(<<" ">>, space(#config{space=4}))} - ]. - - -indent_test_() -> - [ - {"no indent", ?_assertEqual(<<>>, indent(#config{indent=0, depth=1}))}, - {"indent 1 depth 1", ?_assertEqual( - <>/binary>>, - indent(#config{indent=1, depth=1}) - )}, - {"indent 1 depth 2", ?_assertEqual( - <>/binary>>, - indent(#config{indent=1, depth=2}) - )}, - {"indent 4 depth 1", ?_assertEqual( - <>/binary>>, - indent(#config{indent=4, depth=1}) - )}, - {"indent 4 depth 2", ?_assertEqual( - <>/binary, <<" ">>/binary>>, - indent(#config{indent=4, depth=2}) - )} - ]. - - -indent_or_space_test_() -> - [ - {"no indent so space", ?_assertEqual( - <<" ">>, - indent_or_space(#config{space=1, indent=0, depth=1}) - )}, - {"indent so no space", ?_assertEqual( - <>/binary>>, - indent_or_space(#config{space=1, indent=1, depth=1}) - )} - ]. - - -encode_test_() -> - [ - {"0.0", ?_assert(encode(float, 0.0, #config{}) =:= ["0.0"])}, - {"1.0", ?_assert(encode(float, 1.0, #config{}) =:= ["1.0"])}, - {"-1.0", ?_assert(encode(float, -1.0, #config{}) =:= ["-1.0"])}, - {"3.1234567890987654321", - ?_assert( - encode(float, 3.1234567890987654321, #config{}) =:= ["3.1234567890987655"]) - }, - {"1.0e23", ?_assert(encode(float, 1.0e23, #config{}) =:= ["1.0e23"])}, - {"0.3", ?_assert(encode(float, 3.0/10.0, #config{}) =:= ["0.3"])}, - {"0.0001", ?_assert(encode(float, 0.0001, #config{}) =:= ["0.0001"])}, - {"0.00001", ?_assert(encode(float, 0.00001, #config{}) =:= ["1.0e-5"])}, - {"0.00000001", ?_assert(encode(float, 0.00000001, #config{}) =:= ["1.0e-8"])}, - {"1.0e-323", ?_assert(encode(float, 1.0e-323, #config{}) =:= ["1.0e-323"])}, - {"1.0e308", ?_assert(encode(float, 1.0e308, #config{}) =:= ["1.0e308"])}, - {"min normalized float", - ?_assert( - encode(float, math:pow(2, -1022), #config{}) =:= ["2.2250738585072014e-308"] - ) - }, - {"max normalized float", - ?_assert( - encode(float, (2 - math:pow(2, -52)) * math:pow(2, 1023), #config{}) - =:= ["1.7976931348623157e308"] - ) - }, - {"min denormalized float", - ?_assert(encode(float, math:pow(2, -1074), #config{}) =:= ["5.0e-324"]) - }, - {"max denormalized float", - ?_assert( - encode(float, (1 - math:pow(2, -52)) * math:pow(2, -1022), #config{}) - =:= ["2.225073858507201e-308"] - ) - }, - {"hello world", ?_assert(encode(string, <<"hello world">>, #config{}) - =:= [<<"\"">>, <<"hello world">>, <<"\"">>] - )}, - {"key", ?_assert(encode(key, <<"key">>, #config{}) =:= [<<"\"">>, <<"key">>, <<"\"">>])}, - {"1", ?_assert(encode(integer, 1, #config{}) =:= "1")}, - {"-1", ?_assert(encode(integer, -1, #config{}) =:= "-1")}, - {"true", ?_assert(encode(literal, true, #config{}) =:= "true")}, - {"false", ?_assert(encode(literal, false, #config{}) =:= "false")}, - {"null", ?_assert(encode(literal, null, #config{}) =:= "null")} - ]. - - -format_test_() -> - % {minified version, pretty version} - Cases = [ - {"empty object", <<"{}">>, <<"{}">>}, - {"empty array", <<"[]">>, <<"[]">>}, - {"single key object", <<"{\"k\":\"v\"}">>, <<"{\n \"k\": \"v\"\n}">>}, - {"single member array", <<"[true]">>, <<"[\n true\n]">>}, - {"multiple key object", - <<"{\"k\":\"v\",\"x\":\"y\"}">>, - <<"{\n \"k\": \"v\",\n \"x\": \"y\"\n}">> - }, - {"multiple member array", - <<"[1.0,2.0,3.0]">>, - <<"[\n 1.0,\n 2.0,\n 3.0\n]">> - }, - {"nested structure", - <<"[[{},[],true],{\"k\":\"v\",\"x\":\"y\"}]">>, - <<"[\n [\n {},\n [],\n true\n ],\n {\n \"k\": \"v\",\n \"x\": \"y\"\n }\n]">> - } - ], - [{Title, ?_assertEqual(Min, jsx:minify(Pretty))} || {Title, Min, Pretty} <- Cases] ++ - [{Title, ?_assertEqual(Pretty, jsx:prettify(Min))} || {Title, Min, Pretty} <- Cases]. - -custom_newline_test_() -> - [ - {"single key object", ?_assert( - jsx:format(<<"{\"k\":\"v\"}">>, [space, {indent, 2}, {newline, <<$\r>>}]) - =:= <<"{\r \"k\": \"v\"\r}">>) - } - ]. - -handle_event_test_() -> - Data = jsx:test_cases() ++ jsx:special_test_cases(), - [ - { - Title, ?_assertEqual( - JSON, - lists:foldl(fun handle_event/2, init([]), Events ++ [end_json]) - ) - } || {Title, JSON, _, Events} <- Data - ]. - - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_to_term.erl b/_build/default/plugins/jsx/src/jsx_to_term.erl deleted file mode 100644 index e4e5f5e495..0000000000 --- a/_build/default/plugins/jsx/src/jsx_to_term.erl +++ /dev/null @@ -1,459 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 Alisdair Sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_to_term). - --export([to_term/2]). --export([init/1, handle_event/2]). --export([ - start_term/1, - start_object/1, - start_array/1, - finish/1, - insert/2, - get_key/1, - get_value/1 -]). - - --record(config, { - labels = binary, - return_maps = false -}). - --type config() :: list(). --export_type([config/0]). - --ifndef(maps_support). --type json_value() :: list(json_value()) - | list({binary() | atom(), json_value()}) | [{},...] - | true - | false - | null - | integer() - | float() - | binary(). --endif. - --ifdef(maps_support). --type json_value() :: list(json_value()) - | list({binary() | atom(), json_value()}) | [{},...] - | map() - | true - | false - | null - | integer() - | float() - | binary(). --endif. - - --spec to_term(Source::binary(), Config::config()) -> json_value(). - --ifdef(maps_always). -to_term(Source, Config) when is_list(Config) -> - (jsx:decoder(?MODULE, [return_maps] ++ Config, jsx_config:extract_config(Config)))(Source). --endif. --ifndef(maps_always). -to_term(Source, Config) when is_list(Config) -> - (jsx:decoder(?MODULE, Config, jsx_config:extract_config(Config)))(Source). --endif. - -parse_config(Config) -> parse_config(Config, #config{}). - -parse_config([{labels, Val}|Rest], Config) - when Val == binary; Val == atom; Val == existing_atom; Val == attempt_atom -> - parse_config(Rest, Config#config{labels = Val}); -parse_config([labels|Rest], Config) -> - parse_config(Rest, Config#config{labels = binary}); -parse_config([{return_maps, Val}|Rest], Config) - when Val == true; Val == false -> - parse_config(Rest, Config#config{return_maps = Val}); -parse_config([return_maps|Rest], Config) -> - parse_config(Rest, Config#config{return_maps = true}); -parse_config([{K, _}|Rest] = Options, Config) -> - case lists:member(K, jsx_config:valid_flags()) of - true -> parse_config(Rest, Config) - ; false -> erlang:error(badarg, [Options, Config]) - end; -parse_config([K|Rest] = Options, Config) -> - case lists:member(K, jsx_config:valid_flags()) of - true -> parse_config(Rest, Config) - ; false -> erlang:error(badarg, [Options, Config]) - end; -parse_config([], Config) -> - Config. - - --type state() :: {list(), #config{}}. --spec init(Config::proplists:proplist()) -> state(). - -init(Config) -> start_term(Config). - --spec handle_event(Event::any(), State::state()) -> state(). - -handle_event(end_json, State) -> get_value(State); - -handle_event(start_object, State) -> start_object(State); -handle_event(end_object, State) -> finish(State); - -handle_event(start_array, State) -> start_array(State); -handle_event(end_array, State) -> finish(State); - -handle_event({key, Key}, {_, Config} = State) -> insert(format_key(Key, Config), State); - -handle_event({_, Event}, State) -> insert(Event, State). - - -format_key(Key, Config) -> - case Config#config.labels of - binary -> Key - ; atom -> binary_to_atom(Key, utf8) - ; existing_atom -> binary_to_existing_atom(Key, utf8) - ; attempt_atom -> - try binary_to_existing_atom(Key, utf8) of - Result -> Result - catch - error:badarg -> Key - end - end. - - -%% internal state is a stack and a config object -%% `{Stack, Config}` -%% the stack is a list of in progress objects/arrays -%% `[Current, Parent, Grandparent,...OriginalAncestor]` -%% an object has the representation on the stack of -%% `{object, [ -%% {NthKey, NthValue}, -%% {NMinus1Key, NthMinus1Value}, -%% ..., -%% {FirstKey, FirstValue} -%% ]}` -%% or if returning maps -%% `{object, #{ -%% FirstKey => FirstValue, -%% SecondKey => SecondValue, -%% ..., -%% NthKey => NthValue -%% }}` -%% or if there's a key with a yet to be matched value -%% `{object, Key, ...}` -%% an array looks like -%% `{array, [NthValue, NthMinus1Value,...FirstValue]}` - -start_term(Config) when is_list(Config) -> {[], parse_config(Config)}. - - --ifndef(maps_support). -%% allocate a new object on top of the stack -start_object({Stack, Config}) -> {[{object, []}] ++ Stack, Config}. - - -%% allocate a new array on top of the stack -start_array({Stack, Config}) -> {[{array, []}] ++ Stack, Config}. - - -%% finish an object or array and insert it into the parent object if it exists or -%% return it if it is the root object -finish({[{object, []}], Config}) -> {[{}], Config}; -finish({[{object, []}|Rest], Config}) -> insert([{}], {Rest, Config}); -finish({[{object, Pairs}], Config}) -> {lists:reverse(Pairs), Config}; -finish({[{object, Pairs}|Rest], Config}) -> insert(lists:reverse(Pairs), {Rest, Config}); -finish({[{array, Values}], Config}) -> {lists:reverse(Values), Config}; -finish({[{array, Values}|Rest], Config}) -> insert(lists:reverse(Values), {Rest, Config}); -finish(_) -> erlang:error(badarg). - - -%% insert a value when there's no parent object or array -insert(Value, {[], Config}) -> {Value, Config}; -%% insert a key or value into an object or array, autodetects the 'right' thing -insert(Key, {[{object, Pairs}|Rest], Config}) -> - {[{object, Key, Pairs}] ++ Rest, Config}; -insert(Value, {[{object, Key, Pairs}|Rest], Config}) -> - {[{object, [{Key, Value}] ++ Pairs}] ++ Rest, Config}; -insert(Value, {[{array, Values}|Rest], Config}) -> - {[{array, [Value] ++ Values}] ++ Rest, Config}; -insert(_, _) -> erlang:error(badarg). --endif. - - --ifdef(maps_support). -%% allocate a new object on top of the stack -start_object({Stack, Config=#config{return_maps=true}}) -> - {[{object, #{}}] ++ Stack, Config}; -start_object({Stack, Config}) -> - {[{object, []}] ++ Stack, Config}. - - -%% allocate a new array on top of the stack -start_array({Stack, Config}) -> {[{array, []}] ++ Stack, Config}. - - -%% finish an object or array and insert it into the parent object if it exists or -%% return it if it is the root object -finish({[{object, Map}], Config=#config{return_maps=true}}) -> {Map, Config}; -finish({[{object, Map}|Rest], Config=#config{return_maps=true}}) -> insert(Map, {Rest, Config}); -finish({[{object, []}], Config}) -> {[{}], Config}; -finish({[{object, []}|Rest], Config}) -> insert([{}], {Rest, Config}); -finish({[{object, Pairs}], Config}) -> {lists:reverse(Pairs), Config}; -finish({[{object, Pairs}|Rest], Config}) -> insert(lists:reverse(Pairs), {Rest, Config}); -finish({[{array, Values}], Config}) -> {lists:reverse(Values), Config}; -finish({[{array, Values}|Rest], Config}) -> insert(lists:reverse(Values), {Rest, Config}); -finish(_) -> erlang:error(badarg). - - -%% insert a value when there's no parent object or array -insert(Value, {[], Config}) -> {Value, Config}; -%% insert a key or value into an object or array, autodetects the 'right' thing -insert(Key, {[{object, Map}|Rest], Config=#config{return_maps=true}}) -> - {[{object, Key, Map}] ++ Rest, Config}; -insert(Key, {[{object, Pairs}|Rest], Config}) -> - {[{object, Key, Pairs}] ++ Rest, Config}; -insert(Value, {[{object, Key, Map}|Rest], Config=#config{return_maps=true}}) -> - {[{object, maps:put(Key, Value, Map)}] ++ Rest, Config}; -insert(Value, {[{object, Key, Pairs}|Rest], Config}) -> - {[{object, [{Key, Value}] ++ Pairs}] ++ Rest, Config}; -insert(Value, {[{array, Values}|Rest], Config}) -> - {[{array, [Value] ++ Values}] ++ Rest, Config}; -insert(_, _) -> erlang:error(badarg). --endif. - - -get_key({[{object, Key, _}|_], _}) -> Key; -get_key(_) -> erlang:error(badarg). - - -get_value({Value, _Config}) -> Value; -get_value(_) -> erlang:error(badarg). - - - -%% eunit tests - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -config_test_() -> - [ - {"empty config", ?_assertEqual(#config{}, parse_config([]))}, - {"implicit binary labels", ?_assertEqual(#config{}, parse_config([labels]))}, - {"binary labels", ?_assertEqual(#config{}, parse_config([{labels, binary}]))}, - {"atom labels", ?_assertEqual(#config{labels=atom}, parse_config([{labels, atom}]))}, - {"existing atom labels", ?_assertEqual( - #config{labels=existing_atom}, - parse_config([{labels, existing_atom}]) - )}, - {"return_maps true", ?_assertEqual( - #config{return_maps=true}, - parse_config([return_maps]) - )}, - {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, - {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} - ]. - - -format_key_test_() -> - [ - {"binary key", ?_assertEqual(<<"key">>, format_key(<<"key">>, #config{labels=binary}))}, - {"atom key", ?_assertEqual(key, format_key(<<"key">>, #config{labels=atom}))}, - {"existing atom key", ?_assertEqual( - key, - format_key(<<"key">>, #config{labels=existing_atom}) - )}, - {"nonexisting atom key", ?_assertError( - badarg, - format_key(<<"nonexistentatom">>, #config{labels=existing_atom}) - )}, - {"sloppy existing atom key", ?_assertEqual( - key, - format_key(<<"key">>, #config{labels=attempt_atom}) - )}, - {"nonexisting atom key", ?_assertEqual( - <<"nonexistentatom">>, - format_key(<<"nonexistentatom">>, #config{labels=attempt_atom}) - )} - ]. - - -rep_manipulation_test_() -> - [ - {"allocate a new context with option", ?_assertEqual( - {[], #config{labels=atom}}, - start_term([{labels, atom}]) - )}, - {"allocate a new object on an empty stack", ?_assertEqual( - {[{object, []}], #config{}}, - start_object({[], #config{}}) - )}, - {"allocate a new object on a stack", ?_assertEqual( - {[{object, []}, {object, []}], #config{}}, - start_object({[{object, []}], #config{}}) - )}, - {"allocate a new array on an empty stack", ?_assertEqual( - {[{array, []}], #config{}}, - start_array({[], #config{}}) - )}, - {"allocate a new array on a stack", ?_assertEqual( - {[{array, []}, {object, []}], #config{}}, - start_array({[{object, []}], #config{}}) - )}, - {"insert a key into an object", ?_assertEqual( - {[{object, key, []}, junk], #config{}}, - insert(key, {[{object, []}, junk], #config{}}) - )}, - {"get current key", ?_assertEqual( - key, - get_key({[{object, key, []}], #config{}}) - )}, - {"try to get non-key from object", ?_assertError( - badarg, - get_key({[{object, []}], #config{}}) - )}, - {"try to get key from array", ?_assertError( - badarg, - get_key({[{array, []}], #config{}}) - )}, - {"insert a value into an object", ?_assertEqual( - {[{object, [{key, value}]}, junk], #config{}}, - insert(value, {[{object, key, []}, junk], #config{}}) - )}, - {"insert a value into an array", ?_assertEqual( - {[{array, [value]}, junk], #config{}}, - insert(value, {[{array, []}, junk], #config{}}) - )}, - {"finish an object with no ancestor", ?_assertEqual( - {[{a, b}, {x, y}], #config{}}, - finish({[{object, [{x, y}, {a, b}]}], #config{}}) - )}, - {"finish an empty object", ?_assertEqual( - {[{}], #config{}}, - finish({[{object, []}], #config{}}) - )}, - {"finish an object with an ancestor", ?_assertEqual( - {[{object, [{key, [{a, b}, {x, y}]}, {foo, bar}]}], #config{}}, - finish({[{object, [{x, y}, {a, b}]}, {object, key, [{foo, bar}]}], #config{}}) - )}, - {"finish an array with no ancestor", ?_assertEqual( - {[a, b, c], #config{}}, - finish({[{array, [c, b, a]}], #config{}}) - )}, - {"finish an array with an ancestor", ?_assertEqual( - {[{array, [[a, b, c], d, e, f]}], #config{}}, - finish({[{array, [c, b, a]}, {array, [d, e, f]}], #config{}}) - )} - ]. - - --ifdef(maps_support). -rep_manipulation_with_maps_test_() -> - [ - {"allocate a new object on an empty stack", ?_assertEqual( - {[{object, #{}}], #config{return_maps=true}}, - start_object({[], #config{return_maps=true}}) - )}, - {"allocate a new object on a stack", ?_assertEqual( - {[{object, #{}}, {object, #{}}], #config{return_maps=true}}, - start_object({[{object, #{}}], #config{return_maps=true}}) - )}, - {"insert a key into an object", ?_assertEqual( - {[{object, key, #{}}, junk], #config{return_maps=true}}, - insert(key, {[{object, #{}}, junk], #config{return_maps=true}}) - )}, - {"get current key", ?_assertEqual( - key, - get_key({[{object, key, #{}}], #config{return_maps=true}}) - )}, - {"try to get non-key from object", ?_assertError( - badarg, - get_key({[{object, #{}}], #config{return_maps=true}}) - )}, - {"insert a value into an object", ?_assertEqual( - {[{object, #{key => value}}, junk], #config{return_maps=true}}, - insert(value, {[{object, key, #{}}, junk], #config{return_maps=true}}) - )}, - {"finish an object with no ancestor", ?_assertEqual( - {#{a => b, x => y}, #config{return_maps=true}}, - finish({[{object, #{x => y, a => b}}], #config{return_maps=true}}) - )}, - {"finish an empty object", ?_assertEqual( - {#{}, #config{return_maps=true}}, - finish({[{object, #{}}], #config{return_maps=true}}) - )}, - {"finish an object with an ancestor", ?_assertEqual( - { - [{object, #{key => #{a => b, x => y}, foo => bar}}], - #config{return_maps=true} - }, - finish({ - [{object, #{x => y, a => b}}, {object, key, #{foo => bar}}], - #config{return_maps=true} - }) - )} - ]. - - -return_maps_test_() -> - [ - {"an empty map", ?_assertEqual( - #{}, - jsx:decode(<<"{}">>, [return_maps]) - )}, - {"an empty map", ?_assertEqual( - [{}], - jsx:decode(<<"{}">>, []) - )}, - {"an empty map", ?_assertEqual( - [{}], - jsx:decode(<<"{}">>, [{return_maps, false}]) - )}, - {"a small map", ?_assertEqual( - #{<<"awesome">> => true, <<"library">> => <<"jsx">>}, - jsx:decode(<<"{\"library\": \"jsx\", \"awesome\": true}">>, [return_maps]) - )}, - {"a recursive map", ?_assertEqual( - #{<<"key">> => #{<<"key">> => true}}, - jsx:decode(<<"{\"key\": {\"key\": true}}">>, [return_maps]) - )}, - {"a map inside a list", ?_assertEqual( - [#{}], - jsx:decode(<<"[{}]">>, [return_maps]) - )} - ]. --endif. - - -handle_event_test_() -> - Data = jsx:test_cases(), - [ - { - Title, ?_assertEqual( - Term, - lists:foldl(fun handle_event/2, init([]), Events ++ [end_json]) - ) - } || {Title, _, Term, Events} <- Data - ]. - - --endif. diff --git a/_build/default/plugins/jsx/src/jsx_verify.erl b/_build/default/plugins/jsx/src/jsx_verify.erl deleted file mode 100644 index 5f4a3d89e6..0000000000 --- a/_build/default/plugins/jsx/src/jsx_verify.erl +++ /dev/null @@ -1,119 +0,0 @@ -%% The MIT License - -%% Copyright (c) 2010-2013 alisdair sullivan - -%% Permission is hereby granted, free of charge, to any person obtaining a copy -%% of this software and associated documentation files (the "Software"), to deal -%% in the Software without restriction, including without limitation the rights -%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the Software is -%% furnished to do so, subject to the following conditions: - -%% The above copyright notice and this permission notice shall be included in -%% all copies or substantial portions of the Software. - -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -%% THE SOFTWARE. - - --module(jsx_verify). - --export([is_json/2, is_term/2]). --export([init/1, handle_event/2]). - - --spec is_json(Source::binary(), Config::proplists:proplist()) -> true | false | {incomplete, jsx:decoder()}. - -is_json(Source, Config) when is_list(Config) -> - try (jsx:decoder(?MODULE, Config, jsx_config:extract_config(Config)))(Source) - catch error:badarg -> false - end. - - --spec is_term(Source::any(), Config::proplists:proplist()) -> true | false | {incomplete, jsx:encoder()}. - -is_term(Source, Config) when is_list(Config) -> - try (jsx:encoder(?MODULE, Config, jsx_config:extract_config(Config)))(Source) - catch error:badarg -> false - end. - - -parse_config(Config) -> parse_config(Config, []). - -%% ignore deprecated flags -parse_config([no_repeated_keys|Rest], Config) -> - parse_config(Rest, Config); -parse_config([{repeated_keys, Val}|Rest], Config) when Val == true; Val == false -> - parse_config(Rest, Config); -parse_config([repeated_keys|Rest], Config) -> - parse_config(Rest, Config); -parse_config([{K, _}|Rest] = Options, Config) -> - case lists:member(K, jsx_config:valid_flags()) of - true -> parse_config(Rest, Config); - false -> erlang:error(badarg, [Options, Config]) - end; -parse_config([K|Rest] = Options, Config) -> - case lists:member(K, jsx_config:valid_flags()) of - true -> parse_config(Rest, Config); - false -> erlang:error(badarg, [Options, Config]) - end; -parse_config([], Config) -> - Config. - - -%% we don't actually need any state for this --type state() :: []. --spec init(Config::proplists:proplist()) -> state(). - -init(Config) -> parse_config(Config). - - --spec handle_event(Event::any(), State::state()) -> state(). - -handle_event(end_json, _) -> true; - -handle_event(_, State) -> State. - - - -%% eunit tests --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). - - -config_test_() -> - [ - {"empty config", ?_assertEqual([], parse_config([]))}, - {"no repeat keys", ?_assertEqual([], parse_config([no_repeated_keys]))}, - {"bare repeated keys", ?_assertEqual([], parse_config([repeated_keys]))}, - {"repeated keys true", ?_assertEqual( - [], - parse_config([{repeated_keys, true}]) - )}, - {"repeated keys false", ?_assertEqual( - [], - parse_config([{repeated_keys, false}]) - )}, - {"invalid opt flag", ?_assertError(badarg, parse_config([error]))}, - {"invalid opt tuple", ?_assertError(badarg, parse_config([{error, true}]))} - ]. - - -handle_event_test_() -> - Data = jsx:test_cases() ++ jsx:special_test_cases(), - [ - { - Title, ?_assertEqual( - true, - lists:foldl(fun handle_event/2, [], Events ++ [end_json]) - ) - } || {Title, _, _, Events} <- Data - ]. - - --endif. diff --git a/_build/default/plugins/neotoma/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/neotoma/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index cad649fa85..0000000000 Binary files a/_build/default/plugins/neotoma/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/neotoma/LICENSE b/_build/default/plugins/neotoma/LICENSE deleted file mode 100644 index 8d76190b14..0000000000 --- a/_build/default/plugins/neotoma/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2009 Sean Cribbs - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/_build/default/plugins/neotoma/README.textile b/_build/default/plugins/neotoma/README.textile deleted file mode 100644 index a659595542..0000000000 --- a/_build/default/plugins/neotoma/README.textile +++ /dev/null @@ -1,40 +0,0 @@ -h1. Neotoma - -!https://travis-ci.org/seancribbs/neotoma.svg?branch=master!:https://travis-ci.org/seancribbs/neotoma - -h2. About - -Neotoma is a packrat parser-generator for Erlang for Parsing Expression Grammars (PEGs). -It consists of a parsing-combinator library with memoization routines, a parser for PEGs, -and a utility to generate parsers from PEGs. It is inspired by treetop, a Ruby library with -similar aims, and parsec, the parser-combinator library for Haskell. - -Neotoma is licensed under the MIT License (see LICENSE). - -h2. Features - -# Simple, declarative parsers generated from even simpler grammars. -# Fully integrated, single-pass lexical and syntactic analysis (a feature of PEGs). -# Packrat-style memoization, boasting parse-time bound linearly to the input size (at the expense of memory usage). -# In-place semantic analysis/transformation, supporting single-pass end-to-end in some applications. -# Erlang code-generation for the lexical/syntactic analysis piece, with the option of semantic analysis/transformation inline, or in a separate module. -# Line/column number tracking for easy resolution of parsing errors. - -h2. Installation - -# Clone the repository from github:
$ git clone git://github.com/seancribbs/neotoma.git
-# Symlink or copy the cloned repository to somewhere in your Erlang code path. $ERLANG_HOME/lib is best. -# Build the source:
$ make
- -h2. Usage - -# After making sure the library is in your code path, fire up an Erlang shell. -# To generate a parser from a PEG, use @neotoma:file/1,2@ (more detailed documentation pending). For PEG examples, see the @extra/@ directory in the repository. - -
1> neotoma:file("extra/arithmetic.peg").
- - This will place @arithmetic.erl@ in the same directory as the @.peg@ file by default. - -h2. Contributing - -Please send pull-requests to 'seancribbs' on github. When submitting a patch, eunit tests are strongly encouraged. diff --git a/_build/default/plugins/neotoma/hex_metadata.config b/_build/default/plugins/neotoma/hex_metadata.config deleted file mode 100644 index b674bdab05..0000000000 --- a/_build/default/plugins/neotoma/hex_metadata.config +++ /dev/null @@ -1,14 +0,0 @@ -{<<"name">>,<<"neotoma">>}. -{<<"version">>,<<"1.7.3">>}. -{<<"app">>,<<"neotoma">>}. -{<<"contributors">>,[<<"Sean Cribbs">>]}. -{<<"precompiled">>,false}. -{<<"description">>,<<"PEG/Packrat toolkit and parser-generator.">>}. -{<<"files">>, - [<<"src/neotoma.app.src">>,<<"src/neotoma.erl">>,<<"src/neotoma_parse.erl">>, - <<"src/neotoma_parse.erl.safe">>,<<"priv/neotoma_parse.peg">>, - <<"priv/peg_includes.hrl">>,<<"rebar.config">>,<<"rebar.lock">>, - <<"README.textile">>,<<"LICENSE">>]}. -{<<"licenses">>,[<<"MIT">>]}. -{<<"links">>,[{<<"Github">>,<<"https://hub.fastgit.org/seancribbs/neotoma">>}]}. -{<<"build_tools">>,[<<"rebar">>]}. diff --git a/_build/default/plugins/neotoma/priv/neotoma_parse.peg b/_build/default/plugins/neotoma/priv/neotoma_parse.peg deleted file mode 100644 index 49d9fda006..0000000000 --- a/_build/default/plugins/neotoma/priv/neotoma_parse.peg +++ /dev/null @@ -1,303 +0,0 @@ -%% Grammar and transformations - -rules <- space? declaration_sequence space? code_block? space? -` - RootRule = verify_rules(), - Rules = unicode:characters_to_binary(lists:map(fun(R) -> [R, "\n\n"] end, lists:nth(2, Node))), - Code = case lists:nth(4, Node) of - {code, Block} -> Block; - _ -> [] - end, - [{rules, Rules}, - {code, Code}, - {root, RootRule}, - {transform, ets:lookup(memo_table_name(),gen_transform)}, - {combinators, ets:lookup_element(memo_table_name(), combinators, 2)}] - -`; - -declaration_sequence <- head:declaration tail:(space declaration)* -` - FirstRule = proplists:get_value(head, Node), - OtherRules = [I || [_,I] <- proplists:get_value(tail, Node, [])], - [FirstRule|OtherRules] -`; - -declaration <- nonterminal space* '<-' space* parsing_expression space? code_block? space? ';' -` - [{nonterminal,Symbol}|Tail] = Node, - add_lhs(Symbol, Index), - Transform = case lists:nth(6,Tail) of - {code, CodeBlock} -> CodeBlock; - _ -> - ets:insert_new(memo_table_name(),{gen_transform, true}), - ["transform('",Symbol,"', Node, Idx)"] - end, - TransformArgs = case used_transform_variables(Transform) of - [] -> "_Node, _Idx"; - ['Idx'] -> "_Node, Idx"; - ['Node'] -> "Node, _Idx"; - ['Idx', 'Node'] -> "Node, Idx" - end, - ["-spec '", Symbol, "'(input(), index()) -> parse_result().\n", - "'",Symbol,"'","(Input, Index) ->\n ", - "p(Input, Index, '",Symbol,"', fun(I,D) -> (", - lists:nth(4, Tail), - ")(I,D) end, fun(", TransformArgs, ") ->",Transform," end)."] -`; - -parsing_expression <- choice / sequence / primary ~; - -choice <- head:alternative tail:(space '/' space alternative)+ -` - Tail = [lists:last(S) || S <- proplists:get_value(tail, Node)], - Head = proplists:get_value(head, Node), - Statements = [[", ", TS] || TS <- Tail], - used_combinator(p_choose), - ["p_choose([", Head, Statements, "])"] -`; - -alternative <- sequence / labeled_primary ~; - -primary <- prefix atomic / atomic suffix / atomic -` -case Node of - [Atomic, one_or_more] -> - used_combinator(p_one_or_more), - used_combinator(p_scan), - ["p_one_or_more(", Atomic, ")"]; - [Atomic, zero_or_more] -> - used_combinator(p_zero_or_more), - used_combinator(p_scan), - ["p_zero_or_more(", Atomic, ")"]; - [Atomic, optional] -> - used_combinator(p_optional), - ["p_optional(", Atomic, ")"]; - [assert, Atomic] -> - used_combinator(p_assert), - ["p_assert(", Atomic, ")"]; - [not_, Atomic] -> - used_combinator(p_not), - ["p_not(", Atomic, ")"]; - _ -> Node -end -`; - -sequence <- head:labeled_primary tail:(space labeled_primary)+ -` - Tail = [lists:nth(2, S) || S <- proplists:get_value(tail, Node)], - Head = proplists:get_value(head, Node), - Statements = [[", ", TS] || TS <- Tail], - used_combinator(p_seq), - ["p_seq([", Head, Statements, "])"] -`; - -labeled_primary <- label? primary -` - case hd(Node) of - [] -> lists:nth(2, Node); - Label -> - used_combinator(p_label), - ["p_label('", Label, "', ", lists:nth(2, Node), ")"] - end -`; - -label <- alpha_char alphanumeric_char* ':' -` - lists:sublist(Node, length(Node)-1) -`; - -suffix <- repetition_suffix / optional_suffix -` - case Node of - <<"*">> -> zero_or_more; - <<"+">> -> one_or_more; - <<"?">> -> optional - end -`; - -optional_suffix <- '?' ~; - -repetition_suffix <- '+' / '*' ~; - -prefix <- '&' / '!' -` - case Node of - <<"&">> -> assert; - <<"!">> -> not_ - end -`; - -atomic <- terminal / nonterminal / parenthesized_expression -` -case Node of - {nonterminal, Symbol} -> - [<<"fun '">>, Symbol, <<"'/2">>]; - _ -> Node -end -`; - -parenthesized_expression <- '(' space? parsing_expression space? ')' `lists:nth(3, Node)`; - -nonterminal <- alpha_char alphanumeric_char* -` - Symbol = unicode:characters_to_binary(Node), - add_nt(Symbol, Idx), - {nonterminal, Symbol} -`; - -terminal <- regexp_string / quoted_string / character_class / anything_symbol ~; - -regexp_string <- '#' string:(!'#' ('\\#' / .))+ '#' -` - used_combinator(p_regexp), - ["p_regexp(<<\"", - % Escape \ and " as they are used in erlang string. Other sumbol stay as is. - % \ -> \\ - % " -> \" - re:replace(proplists:get_value(string, Node), "\"|\\\\", "\\\\&", [{return, binary}, global]), - "\">>)"] -`; - -quoted_string <- single_quoted_string / double_quoted_string -` - used_combinator(p_string), - lists:flatten(["p_string(<<\"", - escape_string(unicode:characters_to_list(proplists:get_value(string, Node))), - "\">>)"]) -`; - -double_quoted_string <- '"' string:(!'"' ("\\\\" / '\\"' / .))* '"' ~; - -single_quoted_string <- "'" string:(!"'" ("\\\\" / "\\'" / .))* "'" ~; - -character_class <- '[' characters:(!']' ('\\\\' . / !'\\\\' .))+ ']' -` - used_combinator(p_charclass), - ["p_charclass(<<\"[", - escape_string(unicode:characters_to_list(proplists:get_value(characters, Node))), - "]\">>)"] -`; - -anything_symbol <- '.' ` used_combinator(p_anything), <<"p_anything()">> `; - -alpha_char <- [A-Za-z_] ~; - -alphanumeric_char <- alpha_char / [0-9] ~; - -space <- (white / comment_to_eol)+ ~; - -comment_to_eol <- !'%{' '%' (!"\n" .)* ~; - -white <- [ \t\n\r] ~; - -code_block <- ( '%{' code:('\\%' / '$%' / !'%}' .)+ '%}' ) / - ('`' code:('\\`' / '$`' / !'`' .)+ '`') / - '~' -` - case Node of - <<"~">> -> {code, <<"Node">>}; - _ -> {code, proplists:get_value('code', Node)} - end -`; - -%% Extra functions -` -% insert escapes into a string --spec escape_string(string()) -> string(). -escape_string(String) -> escape_string(String, []). - --spec escape_string(string(), string()) -> string(). -escape_string([], Output) -> - lists:reverse(Output); -escape_string([H|T], Output) -> - escape_string(T, - case H of - $/ -> [$/,$\\|Output]; - $\" -> [$\",$\\|Output]; % " comment inserted to help some editors with highlighting the generated parser - $\' -> [$\',$\\|Output]; % ' comment inserted to help some editors with highlighting the generated parser - $\b -> [$b,$\\|Output]; - $\d -> [$d,$\\|Output]; - $\e -> [$e,$\\|Output]; - $\f -> [$f,$\\|Output]; - $\n -> [$n,$\\|Output]; - $\r -> [$r,$\\|Output]; - $\s -> [$s,$\\|Output]; - $\t -> [$t,$\\|Output]; - $\v -> [$v,$\\|Output]; - _ -> [H|Output] - end). - --spec add_lhs(binary(), index()) -> true. -add_lhs(Symbol, Index) -> - case ets:lookup(memo_table_name(), lhs) of - [] -> - ets:insert(memo_table_name(), {lhs, [{Symbol,Index}]}); - [{lhs, L}] when is_list(L) -> - ets:insert(memo_table_name(), {lhs, [{Symbol,Index}|L]}) - end. - --spec add_nt(binary(), index()) -> true | ok. -add_nt(Symbol, Index) -> - case ets:lookup(memo_table_name(), nts) of - [] -> - ets:insert(memo_table_name(), {nts, [{Symbol,Index}]}); - [{nts, L}] when is_list(L) -> - case proplists:is_defined(Symbol, L) of - true -> - ok; - _ -> - ets:insert(memo_table_name(), {nts, [{Symbol,Index}|L]}) - end - end. - --spec verify_rules() -> ok | no_return(). -verify_rules() -> - [{lhs, LHS}] = ets:lookup(memo_table_name(), lhs), - [{nts, NTs}] = ets:lookup(memo_table_name(), nts), - [Root|NonRoots] = lists:reverse(LHS), - lists:foreach(fun({Sym,Idx}) -> - case proplists:is_defined(Sym, NTs) of - true -> - ok; - _ -> - io:format("neotoma warning: rule '~s' is unused. ~p~n", [Sym,Idx]) - end - end, NonRoots), - lists:foreach(fun({S,I}) -> - case proplists:is_defined(S, LHS) of - true -> - ok; - _ -> - io:format("neotoma error: nonterminal '~s' has no reduction. (found at ~p) No parser will be generated!~n", [S,I]), - exit({neotoma, {no_reduction, list_to_atom(binary_to_list(S))}}) - end - end, NTs), - Root. - --spec used_combinator(atom()) -> true. -used_combinator(C) -> - case ets:lookup(memo_table_name(), combinators) of - [] -> - ets:insert(memo_table_name(), {combinators, ordsets:from_list([C])}); - [{combinators, Cs}] -> - ets:insert(memo_table_name(), {combinators, ordsets:add_element(C, Cs)}) - end. - --spec used_transform_variables(binary()) -> [ 'Node' | 'Idx' ]. -used_transform_variables(Transform) -> - Code = unicode:characters_to_list(Transform), - {ok, Tokens, _} = erl_scan:string(Code), - used_transform_variables(Tokens, []). - -used_transform_variables([{var, _, Name}|Tokens], Acc) -> - used_transform_variables(Tokens, case Name of - 'Node' -> [Name | Acc]; - 'Idx' -> [Name | Acc]; - _ -> Acc - end); -used_transform_variables([_|Tokens], Acc) -> - used_transform_variables(Tokens, Acc); -used_transform_variables([], Acc) -> - lists:usort(Acc). -` diff --git a/_build/default/plugins/neotoma/priv/peg_includes.hrl b/_build/default/plugins/neotoma/priv/peg_includes.hrl deleted file mode 100644 index 183b98c5a9..0000000000 --- a/_build/default/plugins/neotoma/priv/peg_includes.hrl +++ /dev/null @@ -1,253 +0,0 @@ --file("peg_includes.hrl", 1). --type index() :: {{line, pos_integer()}, {column, pos_integer()}}. --type input() :: binary(). --type parse_failure() :: {fail, term()}. --type parse_success() :: {term(), input(), index()}. --type parse_result() :: parse_failure() | parse_success(). --type parse_fun() :: fun((input(), index()) -> parse_result()). --type xform_fun() :: fun((input(), index()) -> term()). - --spec p(input(), index(), atom(), parse_fun(), xform_fun()) -> parse_result(). -p(Inp, StartIndex, Name, ParseFun, TransformFun) -> - case get_memo(StartIndex, Name) of % See if the current reduction is memoized - {ok, Memo} -> %Memo; % If it is, return the stored result - Memo; - _ -> % If not, attempt to parse - Result = case ParseFun(Inp, StartIndex) of - {fail,_} = Failure -> % If it fails, memoize the failure - Failure; - {Match, InpRem, NewIndex} -> % If it passes, transform and memoize the result. - Transformed = TransformFun(Match, StartIndex), - {Transformed, InpRem, NewIndex} - end, - memoize(StartIndex, Name, Result), - Result - end. - --spec setup_memo() -> ets:tid(). -setup_memo() -> - put({parse_memo_table, ?MODULE}, ets:new(?MODULE, [set])). - --spec release_memo() -> true. -release_memo() -> - ets:delete(memo_table_name()). - --spec memoize(index(), atom(), parse_result()) -> true. -memoize(Index, Name, Result) -> - Memo = case ets:lookup(memo_table_name(), Index) of - [] -> []; - [{Index, Plist}] -> Plist - end, - ets:insert(memo_table_name(), {Index, [{Name, Result}|Memo]}). - --spec get_memo(index(), atom()) -> {ok, term()} | {error, not_found}. -get_memo(Index, Name) -> - case ets:lookup(memo_table_name(), Index) of - [] -> {error, not_found}; - [{Index, Plist}] -> - case proplists:lookup(Name, Plist) of - {Name, Result} -> {ok, Result}; - _ -> {error, not_found} - end - end. - --spec memo_table_name() -> ets:tid(). -memo_table_name() -> - get({parse_memo_table, ?MODULE}). - --ifdef(p_eof). --spec p_eof() -> parse_fun(). -p_eof() -> - fun(<<>>, Index) -> {eof, [], Index}; - (_, Index) -> {fail, {expected, eof, Index}} end. --endif. - --ifdef(p_optional). --spec p_optional(parse_fun()) -> parse_fun(). -p_optional(P) -> - fun(Input, Index) -> - case P(Input, Index) of - {fail,_} -> {[], Input, Index}; - {_, _, _} = Success -> Success - end - end. --endif. - --ifdef(p_not). --spec p_not(parse_fun()) -> parse_fun(). -p_not(P) -> - fun(Input, Index)-> - case P(Input,Index) of - {fail,_} -> - {[], Input, Index}; - {Result, _, _} -> {fail, {expected, {no_match, Result},Index}} - end - end. --endif. - --ifdef(p_assert). --spec p_assert(parse_fun()) -> parse_fun(). -p_assert(P) -> - fun(Input,Index) -> - case P(Input,Index) of - {fail,_} = Failure-> Failure; - _ -> {[], Input, Index} - end - end. --endif. - --ifdef(p_seq). --spec p_seq([parse_fun()]) -> parse_fun(). -p_seq(P) -> - fun(Input, Index) -> - p_all(P, Input, Index, []) - end. - --spec p_all([parse_fun()], input(), index(), [term()]) -> parse_result(). -p_all([], Inp, Index, Accum ) -> {lists:reverse( Accum ), Inp, Index}; -p_all([P|Parsers], Inp, Index, Accum) -> - case P(Inp, Index) of - {fail, _} = Failure -> Failure; - {Result, InpRem, NewIndex} -> p_all(Parsers, InpRem, NewIndex, [Result|Accum]) - end. --endif. - --ifdef(p_choose). --spec p_choose([parse_fun()]) -> parse_fun(). -p_choose(Parsers) -> - fun(Input, Index) -> - p_attempt(Parsers, Input, Index, none) - end. - --spec p_attempt([parse_fun()], input(), index(), none | parse_failure()) -> parse_result(). -p_attempt([], _Input, _Index, Failure) -> Failure; -p_attempt([P|Parsers], Input, Index, FirstFailure)-> - case P(Input, Index) of - {fail, _} = Failure -> - case FirstFailure of - none -> p_attempt(Parsers, Input, Index, Failure); - _ -> p_attempt(Parsers, Input, Index, FirstFailure) - end; - Result -> Result - end. --endif. - --ifdef(p_zero_or_more). --spec p_zero_or_more(parse_fun()) -> parse_fun(). -p_zero_or_more(P) -> - fun(Input, Index) -> - p_scan(P, Input, Index, []) - end. --endif. - --ifdef(p_one_or_more). --spec p_one_or_more(parse_fun()) -> parse_fun(). -p_one_or_more(P) -> - fun(Input, Index)-> - Result = p_scan(P, Input, Index, []), - case Result of - {[_|_], _, _} -> - Result; - _ -> - {fail, {expected, Failure, _}} = P(Input,Index), - {fail, {expected, {at_least_one, Failure}, Index}} - end - end. --endif. - --ifdef(p_label). --spec p_label(atom(), parse_fun()) -> parse_fun(). -p_label(Tag, P) -> - fun(Input, Index) -> - case P(Input, Index) of - {fail,_} = Failure -> - Failure; - {Result, InpRem, NewIndex} -> - {{Tag, Result}, InpRem, NewIndex} - end - end. --endif. - --ifdef(p_scan). --spec p_scan(parse_fun(), input(), index(), [term()]) -> {[term()], input(), index()}. -p_scan(_, <<>>, Index, Accum) -> {lists:reverse(Accum), <<>>, Index}; -p_scan(P, Inp, Index, Accum) -> - case P(Inp, Index) of - {fail,_} -> {lists:reverse(Accum), Inp, Index}; - {Result, InpRem, NewIndex} -> p_scan(P, InpRem, NewIndex, [Result | Accum]) - end. --endif. - --ifdef(p_string). --spec p_string(binary()) -> parse_fun(). -p_string(S) -> - Length = erlang:byte_size(S), - fun(Input, Index) -> - try - <> = Input, - {S, Rest, p_advance_index(S, Index)} - catch - error:{badmatch,_} -> {fail, {expected, {string, S}, Index}} - end - end. --endif. - --ifdef(p_anything). --spec p_anything() -> parse_fun(). -p_anything() -> - fun(<<>>, Index) -> {fail, {expected, any_character, Index}}; - (Input, Index) when is_binary(Input) -> - <> = Input, - {<>, Rest, p_advance_index(<>, Index)} - end. --endif. - --ifdef(p_charclass). --spec p_charclass(string() | binary()) -> parse_fun(). -p_charclass(Class) -> - {ok, RE} = re:compile(Class, [unicode, dotall]), - fun(Inp, Index) -> - case re:run(Inp, RE, [anchored]) of - {match, [{0, Length}|_]} -> - {Head, Tail} = erlang:split_binary(Inp, Length), - {Head, Tail, p_advance_index(Head, Index)}; - _ -> {fail, {expected, {character_class, binary_to_list(Class)}, Index}} - end - end. --endif. - --ifdef(p_regexp). --spec p_regexp(binary()) -> parse_fun(). -p_regexp(Regexp) -> - {ok, RE} = re:compile(Regexp, [unicode, dotall, anchored]), - fun(Inp, Index) -> - case re:run(Inp, RE) of - {match, [{0, Length}|_]} -> - {Head, Tail} = erlang:split_binary(Inp, Length), - {Head, Tail, p_advance_index(Head, Index)}; - _ -> {fail, {expected, {regexp, binary_to_list(Regexp)}, Index}} - end - end. --endif. - --ifdef(line). --spec line(index() | term()) -> pos_integer() | undefined. -line({{line,L},_}) -> L; -line(_) -> undefined. --endif. - --ifdef(column). --spec column(index() | term()) -> pos_integer() | undefined. -column({_,{column,C}}) -> C; -column(_) -> undefined. --endif. - --spec p_advance_index(input() | unicode:charlist() | pos_integer(), index()) -> index(). -p_advance_index(MatchedInput, Index) when is_list(MatchedInput) orelse is_binary(MatchedInput)-> % strings - lists:foldl(fun p_advance_index/2, Index, unicode:characters_to_list(MatchedInput)); -p_advance_index(MatchedInput, Index) when is_integer(MatchedInput) -> % single characters - {{line, Line}, {column, Col}} = Index, - case MatchedInput of - $\n -> {{line, Line+1}, {column, 1}}; - _ -> {{line, Line}, {column, Col+1}} - end. diff --git a/_build/default/plugins/neotoma/rebar.config b/_build/default/plugins/neotoma/rebar.config deleted file mode 100644 index 7c46044f4a..0000000000 --- a/_build/default/plugins/neotoma/rebar.config +++ /dev/null @@ -1,5 +0,0 @@ -{erl_opts, [debug_info, warn_export_vars]}. -{xref_checks, [undefined_function_calls]}. -{eunit_opts, [verbose]}. - -{plugins, [rebar3_hex]}. diff --git a/_build/default/plugins/neotoma/src/neotoma.app.src b/_build/default/plugins/neotoma/src/neotoma.app.src deleted file mode 100644 index 77de90b51a..0000000000 --- a/_build/default/plugins/neotoma/src/neotoma.app.src +++ /dev/null @@ -1,10 +0,0 @@ -{application, neotoma, - [ - {description, "PEG/Packrat toolkit and parser-generator."}, - {vsn, "1.7.3"}, - {applications, [kernel, stdlib]}, - {contributors, ["Sean Cribbs"]}, - {licenses, ["MIT"]}, - {links, [{"Github", "https://hub.fastgit.org/seancribbs/neotoma"}]} - ] -}. diff --git a/_build/default/plugins/neotoma/src/neotoma.erl b/_build/default/plugins/neotoma/src/neotoma.erl deleted file mode 100644 index f4102f605d..0000000000 --- a/_build/default/plugins/neotoma/src/neotoma.erl +++ /dev/null @@ -1,145 +0,0 @@ --module(neotoma). --author("Sean Cribbs "). --export([file/1, file/2, bootstrap/0]). --export([main/1]). - --define(ALL_COMBINATORS, [p_eof, p_optional, p_not, p_assert, p_seq, - p_choose, p_zero_or_more, p_one_or_more, p_label, p_scan, - p_string, p_anything, p_charclass, p_regexp, line, column]). - --type option() :: {module, atom()} | {output, file:filename()} | {transform_module, atom()} | - {neotoma_priv_dir, file:filename()}. - -%% @doc Handler function for escript. --spec main(list()) -> ok | no_return(). -main([]) -> - io:format("Usage: neotoma filename [-module output_module] [-output output_dir] [-transform_module transform_module]\n"); -main([Filename | Args]) -> - %% code:priv_dir is unreliable when called in escript context, but - %% escript:script_name does what we want. - PrivDir = filename:join([filename:dirname(escript:script_name()), "priv"]), - file(Filename, [{neotoma_priv_dir, PrivDir} | parse_options(Args)]). - -%% @doc Generates a parser from the specified file. -%% @equiv file(Filename, []) --spec file(file:filename()) -> ok | {error, atom()}. -file(InputGrammar) -> - file(InputGrammar, []). - -%% @doc Generates a parser from the specified file with the given options. --spec file(file:filename(), [option()]) -> ok | {error, atom()}. -file(InputGrammar, Options) -> - Basename = filename:basename(InputGrammar, ".peg"), - InputDir = filename:dirname(InputGrammar), - ModuleName = proplists:get_value(module, Options, list_to_atom(Basename)), - OutputDir = proplists:get_value(output, Options, InputDir), - OutputFilename = filename:join(OutputDir, atom_to_list(ModuleName) ++ ".erl"), - TransformModule = proplists:get_value(transform_module, Options, false), - validate_params(filename:absname(InputGrammar), - ModuleName, - TransformModule, - filename:absname(OutputFilename)), - Parsed = parse_grammar(InputGrammar), - Rules = proplists:get_value(rules, Parsed), - Root = proplists:get_value(root, Parsed), - Code = proplists:get_value(code, Parsed), - GenTransform = proplists:get_value(transform, Parsed), - Combinators = proplists:get_value(combinators, Parsed, ?ALL_COMBINATORS), - ModuleAttrs = generate_module_attrs(ModuleName, Combinators), - EntryFuns = generate_entry_functions(Root), - TransformFun = create_transform(TransformModule, OutputDir, GenTransform), - PrivDir = proplists:get_value(neotoma_priv_dir, Options, code:priv_dir(neotoma)), - {ok, PegIncludes} = file:read_file(filename:join([PrivDir, "peg_includes.hrl"])), - file:write_file(OutputFilename, [ModuleAttrs, "\n", Code, "\n", EntryFuns, "\n", Rules, "\n", TransformFun, "\n", PegIncludes]). - --spec validate_params(file:filename(),atom(),atom(),file:filename()) -> 'ok'. -validate_params(InputGrammar, _, _, OutputFile) when InputGrammar =:= OutputFile -> - throw({badarg, "Input and output file are the same!"}); -validate_params(_,_, false, _) -> ok; -validate_params(_,_, TransformModule, _) when not is_atom(TransformModule) -> - throw({badarg, "transform_module option must be an atom"}); -validate_params(_,Basename, TransformModule, _) when Basename =:= TransformModule -> - throw({badarg, "Transform module named same as parser module!"}); -validate_params(_,_, TransformModule, OutputFile) -> - OutMod = list_to_atom(filename:basename(OutputFile, ".erl")), - case OutMod of - TransformModule -> throw({badarg, "Transform module file same as parser output file!"}); - _ -> ok - end. - --spec generate_module_attrs(atom(), [atom()]) -> iolist(). -generate_module_attrs(ModName, Combinators) -> - ["-module(", atom_to_list(ModName) ,").\n", - "-export([parse/1,file/1]).\n", - [ generate_combinator_macro(C) || Combinators /= undefined, C <- Combinators ], - "\n" - ]. - -generate_combinator_macro(C) -> - ["-define(", atom_to_list(C), ",true).\n"]. - --spec generate_entry_functions({iodata(),_}) -> iolist(). -generate_entry_functions(Root) -> - {RootRule,_} = Root, - ["-spec file(file:name()) -> any().\n", - "file(Filename) -> case file:read_file(Filename) of {ok,Bin} -> parse(Bin); Err -> Err end.\n\n", - "-spec parse(binary() | list()) -> any().\n", - "parse(List) when is_list(List) -> parse(unicode:characters_to_binary(List));\n", - "parse(Input) when is_binary(Input) ->\n", - " _ = setup_memo(),\n", - " Result = case '",RootRule,"'(Input,{{line,1},{column,1}}) of\n", - " {AST, <<>>, _Index} -> AST;\n", - " Any -> Any\n" - " end,\n", - " release_memo(), Result.\n"]. - --spec parse_grammar(file:filename()) -> any(). -parse_grammar(InputFile) -> - case neotoma_parse:file(InputFile) of - {fail, Index} -> - throw({grammar_error, {fail, Index}}); - {Parsed, Remainder, Index} -> - io:format("WARNING: Grammar parse ended unexpectedly at ~p, generated parser may be incorrect.~nRemainder:~n~p", - [Index, Remainder]), - Parsed; - L when is_list(L) -> L; - _ -> throw({error, {unknown, grammar, InputFile}}) - end. - --spec create_transform(atom() | boolean(),file:filename(),_) -> iolist(). -create_transform(_,_,[]) -> []; -create_transform(false,_,_) -> - "transform(_,Node,_Index) -> Node."; -create_transform(ModName,Dir,_) when is_atom(ModName) -> - XfFile = filename:join(Dir, atom_to_list(ModName) ++ ".erl"), - case filelib:is_regular(XfFile) of - true -> io:format("'~s' already exists, skipping generation.~n", [XfFile]); - false -> generate_transform_stub(XfFile, ModName) - end, - ["transform(Symbol,Node,Index) -> ",atom_to_list(ModName),":transform(Symbol, Node, Index)."]. - --spec generate_transform_stub(file:filename(), atom()) -> 'ok' | {'error',atom()}. -generate_transform_stub(XfFile,ModName) -> - Data = ["-module(",atom_to_list(ModName),").\n", - "-export([transform/3]).\n\n", - "%% Add clauses to this function to transform syntax nodes\n", - "%% from the parser into semantic output.\n", - "transform(Symbol, Node, _Index) when is_atom(Symbol) ->\n Node."], - file:write_file(XfFile, Data). - -%% @doc Bootstraps the neotoma metagrammar. Intended only for internal development! -%% @equiv file("src/neotoma_parse.peg") --spec bootstrap() -> 'ok'. -bootstrap() -> - file("priv/neotoma_parse.peg", [{output, "src/"}, {neotoma_priv_dir, "priv"}]). - -%% @doc Parses arguments passed to escript --spec parse_options(list()) -> list(). -parse_options(["-module", ModName | Rest]) -> - [{module, list_to_atom(ModName)} | parse_options(Rest)]; -parse_options(["-output", Dir | Rest]) -> - [{output, Dir} | parse_options(Rest)]; -parse_options(["-transform_module", ModName | Rest]) -> - [{transform_module, list_to_atom(ModName)} | parse_options(Rest)]; -parse_options([]) -> - []. diff --git a/_build/default/plugins/neotoma/src/neotoma_parse.erl b/_build/default/plugins/neotoma/src/neotoma_parse.erl deleted file mode 100644 index 1bffaf8723..0000000000 --- a/_build/default/plugins/neotoma/src/neotoma_parse.erl +++ /dev/null @@ -1,625 +0,0 @@ --module(neotoma_parse). --export([parse/1,file/1]). --define(p_anything,true). --define(p_charclass,true). --define(p_choose,true). --define(p_label,true). --define(p_not,true). --define(p_one_or_more,true). --define(p_optional,true). --define(p_scan,true). --define(p_seq,true). --define(p_string,true). --define(p_zero_or_more,true). - - - -% insert escapes into a string --spec escape_string(string()) -> string(). -escape_string(String) -> escape_string(String, []). - --spec escape_string(string(), string()) -> string(). -escape_string([], Output) -> - lists:reverse(Output); -escape_string([H|T], Output) -> - escape_string(T, - case H of - $/ -> [$/,$\\|Output]; - $\" -> [$\",$\\|Output]; % " comment inserted to help some editors with highlighting the generated parser - $\' -> [$\',$\\|Output]; % ' comment inserted to help some editors with highlighting the generated parser - $\b -> [$b,$\\|Output]; - $\d -> [$d,$\\|Output]; - $\e -> [$e,$\\|Output]; - $\f -> [$f,$\\|Output]; - $\n -> [$n,$\\|Output]; - $\r -> [$r,$\\|Output]; - $\s -> [$s,$\\|Output]; - $\t -> [$t,$\\|Output]; - $\v -> [$v,$\\|Output]; - _ -> [H|Output] - end). - --spec add_lhs(binary(), index()) -> true. -add_lhs(Symbol, Index) -> - case ets:lookup(memo_table_name(), lhs) of - [] -> - ets:insert(memo_table_name(), {lhs, [{Symbol,Index}]}); - [{lhs, L}] when is_list(L) -> - ets:insert(memo_table_name(), {lhs, [{Symbol,Index}|L]}) - end. - --spec add_nt(binary(), index()) -> true | ok. -add_nt(Symbol, Index) -> - case ets:lookup(memo_table_name(), nts) of - [] -> - ets:insert(memo_table_name(), {nts, [{Symbol,Index}]}); - [{nts, L}] when is_list(L) -> - case proplists:is_defined(Symbol, L) of - true -> - ok; - _ -> - ets:insert(memo_table_name(), {nts, [{Symbol,Index}|L]}) - end - end. - --spec verify_rules() -> ok | no_return(). -verify_rules() -> - [{lhs, LHS}] = ets:lookup(memo_table_name(), lhs), - [{nts, NTs}] = ets:lookup(memo_table_name(), nts), - [Root|NonRoots] = lists:reverse(LHS), - lists:foreach(fun({Sym,Idx}) -> - case proplists:is_defined(Sym, NTs) of - true -> - ok; - _ -> - io:format("neotoma warning: rule '~s' is unused. ~p~n", [Sym,Idx]) - end - end, NonRoots), - lists:foreach(fun({S,I}) -> - case proplists:is_defined(S, LHS) of - true -> - ok; - _ -> - io:format("neotoma error: nonterminal '~s' has no reduction. (found at ~p) No parser will be generated!~n", [S,I]), - exit({neotoma, {no_reduction, list_to_atom(binary_to_list(S))}}) - end - end, NTs), - Root. - --spec used_combinator(atom()) -> true. -used_combinator(C) -> - case ets:lookup(memo_table_name(), combinators) of - [] -> - ets:insert(memo_table_name(), {combinators, ordsets:from_list([C])}); - [{combinators, Cs}] -> - ets:insert(memo_table_name(), {combinators, ordsets:add_element(C, Cs)}) - end. - --spec used_transform_variables(binary()) -> [ 'Node' | 'Idx' ]. -used_transform_variables(Transform) -> - Code = unicode:characters_to_list(Transform), - {ok, Tokens, _} = erl_scan:string(Code), - used_transform_variables(Tokens, []). - -used_transform_variables([{var, _, Name}|Tokens], Acc) -> - used_transform_variables(Tokens, case Name of - 'Node' -> [Name | Acc]; - 'Idx' -> [Name | Acc]; - _ -> Acc - end); -used_transform_variables([_|Tokens], Acc) -> - used_transform_variables(Tokens, Acc); -used_transform_variables([], Acc) -> - lists:usort(Acc). - --spec file(file:name()) -> any(). -file(Filename) -> case file:read_file(Filename) of {ok,Bin} -> parse(Bin); Err -> Err end. - --spec parse(binary() | list()) -> any(). -parse(List) when is_list(List) -> parse(unicode:characters_to_binary(List)); -parse(Input) when is_binary(Input) -> - _ = setup_memo(), - Result = case 'rules'(Input,{{line,1},{column,1}}) of - {AST, <<>>, _Index} -> AST; - Any -> Any - end, - release_memo(), Result. - --spec 'rules'(input(), index()) -> parse_result(). -'rules'(Input, Index) -> - p(Input, Index, 'rules', fun(I,D) -> (p_seq([p_optional(fun 'space'/2), fun 'declaration_sequence'/2, p_optional(fun 'space'/2), p_optional(fun 'code_block'/2), p_optional(fun 'space'/2)]))(I,D) end, fun(Node, _Idx) -> - RootRule = verify_rules(), - Rules = unicode:characters_to_binary(lists:map(fun(R) -> [R, "\n\n"] end, lists:nth(2, Node))), - Code = case lists:nth(4, Node) of - {code, Block} -> Block; - _ -> [] - end, - [{rules, Rules}, - {code, Code}, - {root, RootRule}, - {transform, ets:lookup(memo_table_name(),gen_transform)}, - {combinators, ets:lookup_element(memo_table_name(), combinators, 2)}] - - end). - --spec 'declaration_sequence'(input(), index()) -> parse_result(). -'declaration_sequence'(Input, Index) -> - p(Input, Index, 'declaration_sequence', fun(I,D) -> (p_seq([p_label('head', fun 'declaration'/2), p_label('tail', p_zero_or_more(p_seq([fun 'space'/2, fun 'declaration'/2])))]))(I,D) end, fun(Node, _Idx) -> - FirstRule = proplists:get_value(head, Node), - OtherRules = [I || [_,I] <- proplists:get_value(tail, Node, [])], - [FirstRule|OtherRules] - end). - --spec 'declaration'(input(), index()) -> parse_result(). -'declaration'(Input, Index) -> - p(Input, Index, 'declaration', fun(I,D) -> (p_seq([fun 'nonterminal'/2, p_zero_or_more(fun 'space'/2), p_string(<<"<-">>), p_zero_or_more(fun 'space'/2), fun 'parsing_expression'/2, p_optional(fun 'space'/2), p_optional(fun 'code_block'/2), p_optional(fun 'space'/2), p_string(<<";">>)]))(I,D) end, fun(Node, _Idx) -> - [{nonterminal,Symbol}|Tail] = Node, - add_lhs(Symbol, Index), - Transform = case lists:nth(6,Tail) of - {code, CodeBlock} -> CodeBlock; - _ -> - ets:insert_new(memo_table_name(),{gen_transform, true}), - ["transform('",Symbol,"', Node, Idx)"] - end, - TransformArgs = case used_transform_variables(Transform) of - [] -> "_Node, _Idx"; - ['Idx'] -> "_Node, Idx"; - ['Node'] -> "Node, _Idx"; - ['Idx', 'Node'] -> "Node, Idx" - end, - ["-spec '", Symbol, "'(input(), index()) -> parse_result().\n", - "'",Symbol,"'","(Input, Index) ->\n ", - "p(Input, Index, '",Symbol,"', fun(I,D) -> (", - lists:nth(4, Tail), - ")(I,D) end, fun(", TransformArgs, ") ->",Transform," end)."] - end). - --spec 'parsing_expression'(input(), index()) -> parse_result(). -'parsing_expression'(Input, Index) -> - p(Input, Index, 'parsing_expression', fun(I,D) -> (p_choose([fun 'choice'/2, fun 'sequence'/2, fun 'primary'/2]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'choice'(input(), index()) -> parse_result(). -'choice'(Input, Index) -> - p(Input, Index, 'choice', fun(I,D) -> (p_seq([p_label('head', fun 'alternative'/2), p_label('tail', p_one_or_more(p_seq([fun 'space'/2, p_string(<<"\/">>), fun 'space'/2, fun 'alternative'/2])))]))(I,D) end, fun(Node, _Idx) -> - Tail = [lists:last(S) || S <- proplists:get_value(tail, Node)], - Head = proplists:get_value(head, Node), - Statements = [[", ", TS] || TS <- Tail], - used_combinator(p_choose), - ["p_choose([", Head, Statements, "])"] - end). - --spec 'alternative'(input(), index()) -> parse_result(). -'alternative'(Input, Index) -> - p(Input, Index, 'alternative', fun(I,D) -> (p_choose([fun 'sequence'/2, fun 'labeled_primary'/2]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'primary'(input(), index()) -> parse_result(). -'primary'(Input, Index) -> - p(Input, Index, 'primary', fun(I,D) -> (p_choose([p_seq([fun 'prefix'/2, fun 'atomic'/2]), p_seq([fun 'atomic'/2, fun 'suffix'/2]), fun 'atomic'/2]))(I,D) end, fun(Node, _Idx) -> -case Node of - [Atomic, one_or_more] -> - used_combinator(p_one_or_more), - used_combinator(p_scan), - ["p_one_or_more(", Atomic, ")"]; - [Atomic, zero_or_more] -> - used_combinator(p_zero_or_more), - used_combinator(p_scan), - ["p_zero_or_more(", Atomic, ")"]; - [Atomic, optional] -> - used_combinator(p_optional), - ["p_optional(", Atomic, ")"]; - [assert, Atomic] -> - used_combinator(p_assert), - ["p_assert(", Atomic, ")"]; - [not_, Atomic] -> - used_combinator(p_not), - ["p_not(", Atomic, ")"]; - _ -> Node -end - end). - --spec 'sequence'(input(), index()) -> parse_result(). -'sequence'(Input, Index) -> - p(Input, Index, 'sequence', fun(I,D) -> (p_seq([p_label('head', fun 'labeled_primary'/2), p_label('tail', p_one_or_more(p_seq([fun 'space'/2, fun 'labeled_primary'/2])))]))(I,D) end, fun(Node, _Idx) -> - Tail = [lists:nth(2, S) || S <- proplists:get_value(tail, Node)], - Head = proplists:get_value(head, Node), - Statements = [[", ", TS] || TS <- Tail], - used_combinator(p_seq), - ["p_seq([", Head, Statements, "])"] - end). - --spec 'labeled_primary'(input(), index()) -> parse_result(). -'labeled_primary'(Input, Index) -> - p(Input, Index, 'labeled_primary', fun(I,D) -> (p_seq([p_optional(fun 'label'/2), fun 'primary'/2]))(I,D) end, fun(Node, _Idx) -> - case hd(Node) of - [] -> lists:nth(2, Node); - Label -> - used_combinator(p_label), - ["p_label('", Label, "', ", lists:nth(2, Node), ")"] - end - end). - --spec 'label'(input(), index()) -> parse_result(). -'label'(Input, Index) -> - p(Input, Index, 'label', fun(I,D) -> (p_seq([fun 'alpha_char'/2, p_zero_or_more(fun 'alphanumeric_char'/2), p_string(<<":">>)]))(I,D) end, fun(Node, _Idx) -> - lists:sublist(Node, length(Node)-1) - end). - --spec 'suffix'(input(), index()) -> parse_result(). -'suffix'(Input, Index) -> - p(Input, Index, 'suffix', fun(I,D) -> (p_choose([fun 'repetition_suffix'/2, fun 'optional_suffix'/2]))(I,D) end, fun(Node, _Idx) -> - case Node of - <<"*">> -> zero_or_more; - <<"+">> -> one_or_more; - <<"?">> -> optional - end - end). - --spec 'optional_suffix'(input(), index()) -> parse_result(). -'optional_suffix'(Input, Index) -> - p(Input, Index, 'optional_suffix', fun(I,D) -> (p_string(<<"?">>))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'repetition_suffix'(input(), index()) -> parse_result(). -'repetition_suffix'(Input, Index) -> - p(Input, Index, 'repetition_suffix', fun(I,D) -> (p_choose([p_string(<<"+">>), p_string(<<"*">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'prefix'(input(), index()) -> parse_result(). -'prefix'(Input, Index) -> - p(Input, Index, 'prefix', fun(I,D) -> (p_choose([p_string(<<"&">>), p_string(<<"!">>)]))(I,D) end, fun(Node, _Idx) -> - case Node of - <<"&">> -> assert; - <<"!">> -> not_ - end - end). - --spec 'atomic'(input(), index()) -> parse_result(). -'atomic'(Input, Index) -> - p(Input, Index, 'atomic', fun(I,D) -> (p_choose([fun 'terminal'/2, fun 'nonterminal'/2, fun 'parenthesized_expression'/2]))(I,D) end, fun(Node, _Idx) -> -case Node of - {nonterminal, Symbol} -> - [<<"fun '">>, Symbol, <<"'/2">>]; - _ -> Node -end - end). - --spec 'parenthesized_expression'(input(), index()) -> parse_result(). -'parenthesized_expression'(Input, Index) -> - p(Input, Index, 'parenthesized_expression', fun(I,D) -> (p_seq([p_string(<<"(">>), p_optional(fun 'space'/2), fun 'parsing_expression'/2, p_optional(fun 'space'/2), p_string(<<")">>)]))(I,D) end, fun(Node, _Idx) ->lists:nth(3, Node) end). - --spec 'nonterminal'(input(), index()) -> parse_result(). -'nonterminal'(Input, Index) -> - p(Input, Index, 'nonterminal', fun(I,D) -> (p_seq([fun 'alpha_char'/2, p_zero_or_more(fun 'alphanumeric_char'/2)]))(I,D) end, fun(Node, Idx) -> - Symbol = unicode:characters_to_binary(Node), - add_nt(Symbol, Idx), - {nonterminal, Symbol} - end). - --spec 'terminal'(input(), index()) -> parse_result(). -'terminal'(Input, Index) -> - p(Input, Index, 'terminal', fun(I,D) -> (p_choose([fun 'regexp_string'/2, fun 'quoted_string'/2, fun 'character_class'/2, fun 'anything_symbol'/2]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'regexp_string'(input(), index()) -> parse_result(). -'regexp_string'(Input, Index) -> - p(Input, Index, 'regexp_string', fun(I,D) -> (p_seq([p_string(<<"#">>), p_label('string', p_one_or_more(p_seq([p_not(p_string(<<"#">>)), p_choose([p_string(<<"\\#">>), p_anything()])]))), p_string(<<"#">>)]))(I,D) end, fun(Node, _Idx) -> - used_combinator(p_regexp), - ["p_regexp(<<\"", - % Escape \ and " as they are used in erlang string. Other sumbol stay as is. - % \ -> \\ - % " -> \" - re:replace(proplists:get_value(string, Node), "\"|\\\\", "\\\\&", [{return, binary}, global]), - "\">>)"] - end). - --spec 'quoted_string'(input(), index()) -> parse_result(). -'quoted_string'(Input, Index) -> - p(Input, Index, 'quoted_string', fun(I,D) -> (p_choose([fun 'single_quoted_string'/2, fun 'double_quoted_string'/2]))(I,D) end, fun(Node, _Idx) -> - used_combinator(p_string), - lists:flatten(["p_string(<<\"", - escape_string(unicode:characters_to_list(proplists:get_value(string, Node))), - "\">>)"]) - end). - --spec 'double_quoted_string'(input(), index()) -> parse_result(). -'double_quoted_string'(Input, Index) -> - p(Input, Index, 'double_quoted_string', fun(I,D) -> (p_seq([p_string(<<"\"">>), p_label('string', p_zero_or_more(p_seq([p_not(p_string(<<"\"">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\"">>), p_anything()])]))), p_string(<<"\"">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'single_quoted_string'(input(), index()) -> parse_result(). -'single_quoted_string'(Input, Index) -> - p(Input, Index, 'single_quoted_string', fun(I,D) -> (p_seq([p_string(<<"\'">>), p_label('string', p_zero_or_more(p_seq([p_not(p_string(<<"\'">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\'">>), p_anything()])]))), p_string(<<"\'">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'character_class'(input(), index()) -> parse_result(). -'character_class'(Input, Index) -> - p(Input, Index, 'character_class', fun(I,D) -> (p_seq([p_string(<<"[">>), p_label('characters', p_one_or_more(p_seq([p_not(p_string(<<"]">>)), p_choose([p_seq([p_string(<<"\\\\">>), p_anything()]), p_seq([p_not(p_string(<<"\\\\">>)), p_anything()])])]))), p_string(<<"]">>)]))(I,D) end, fun(Node, _Idx) -> - used_combinator(p_charclass), - ["p_charclass(<<\"[", - escape_string(unicode:characters_to_list(proplists:get_value(characters, Node))), - "]\">>)"] - end). - --spec 'anything_symbol'(input(), index()) -> parse_result(). -'anything_symbol'(Input, Index) -> - p(Input, Index, 'anything_symbol', fun(I,D) -> (p_string(<<".">>))(I,D) end, fun(_Node, _Idx) -> used_combinator(p_anything), <<"p_anything()">> end). - --spec 'alpha_char'(input(), index()) -> parse_result(). -'alpha_char'(Input, Index) -> - p(Input, Index, 'alpha_char', fun(I,D) -> (p_charclass(<<"[A-Za-z_]">>))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'alphanumeric_char'(input(), index()) -> parse_result(). -'alphanumeric_char'(Input, Index) -> - p(Input, Index, 'alphanumeric_char', fun(I,D) -> (p_choose([fun 'alpha_char'/2, p_charclass(<<"[0-9]">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'space'(input(), index()) -> parse_result(). -'space'(Input, Index) -> - p(Input, Index, 'space', fun(I,D) -> (p_one_or_more(p_choose([fun 'white'/2, fun 'comment_to_eol'/2])))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'comment_to_eol'(input(), index()) -> parse_result(). -'comment_to_eol'(Input, Index) -> - p(Input, Index, 'comment_to_eol', fun(I,D) -> (p_seq([p_not(p_string(<<"%{">>)), p_string(<<"%">>), p_zero_or_more(p_seq([p_not(p_string(<<"\n">>)), p_anything()]))]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'white'(input(), index()) -> parse_result(). -'white'(Input, Index) -> - p(Input, Index, 'white', fun(I,D) -> (p_charclass(<<"[\s\t\n\r]">>))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'code_block'(input(), index()) -> parse_result(). -'code_block'(Input, Index) -> - p(Input, Index, 'code_block', fun(I,D) -> (p_choose([p_seq([p_string(<<"%{">>), p_label('code', p_one_or_more(p_choose([p_string(<<"\\%">>), p_string(<<"$%">>), p_seq([p_not(p_string(<<"%}">>)), p_anything()])]))), p_string(<<"%}">>)]), p_seq([p_string(<<"`">>), p_label('code', p_one_or_more(p_choose([p_string(<<"\\`">>), p_string(<<"$`">>), p_seq([p_not(p_string(<<"`">>)), p_anything()])]))), p_string(<<"`">>)]), p_string(<<"~">>)]))(I,D) end, fun(Node, _Idx) -> - case Node of - <<"~">> -> {code, <<"Node">>}; - _ -> {code, proplists:get_value('code', Node)} - end - end). - - - --file("peg_includes.hrl", 1). --type index() :: {{line, pos_integer()}, {column, pos_integer()}}. --type input() :: binary(). --type parse_failure() :: {fail, term()}. --type parse_success() :: {term(), input(), index()}. --type parse_result() :: parse_failure() | parse_success(). --type parse_fun() :: fun((input(), index()) -> parse_result()). --type xform_fun() :: fun((input(), index()) -> term()). - --spec p(input(), index(), atom(), parse_fun(), xform_fun()) -> parse_result(). -p(Inp, StartIndex, Name, ParseFun, TransformFun) -> - case get_memo(StartIndex, Name) of % See if the current reduction is memoized - {ok, Memo} -> %Memo; % If it is, return the stored result - Memo; - _ -> % If not, attempt to parse - Result = case ParseFun(Inp, StartIndex) of - {fail,_} = Failure -> % If it fails, memoize the failure - Failure; - {Match, InpRem, NewIndex} -> % If it passes, transform and memoize the result. - Transformed = TransformFun(Match, StartIndex), - {Transformed, InpRem, NewIndex} - end, - memoize(StartIndex, Name, Result), - Result - end. - --spec setup_memo() -> ets:tid(). -setup_memo() -> - put({parse_memo_table, ?MODULE}, ets:new(?MODULE, [set])). - --spec release_memo() -> true. -release_memo() -> - ets:delete(memo_table_name()). - --spec memoize(index(), atom(), parse_result()) -> true. -memoize(Index, Name, Result) -> - Memo = case ets:lookup(memo_table_name(), Index) of - [] -> []; - [{Index, Plist}] -> Plist - end, - ets:insert(memo_table_name(), {Index, [{Name, Result}|Memo]}). - --spec get_memo(index(), atom()) -> {ok, term()} | {error, not_found}. -get_memo(Index, Name) -> - case ets:lookup(memo_table_name(), Index) of - [] -> {error, not_found}; - [{Index, Plist}] -> - case proplists:lookup(Name, Plist) of - {Name, Result} -> {ok, Result}; - _ -> {error, not_found} - end - end. - --spec memo_table_name() -> ets:tid(). -memo_table_name() -> - get({parse_memo_table, ?MODULE}). - --ifdef(p_eof). --spec p_eof() -> parse_fun(). -p_eof() -> - fun(<<>>, Index) -> {eof, [], Index}; - (_, Index) -> {fail, {expected, eof, Index}} end. --endif. - --ifdef(p_optional). --spec p_optional(parse_fun()) -> parse_fun(). -p_optional(P) -> - fun(Input, Index) -> - case P(Input, Index) of - {fail,_} -> {[], Input, Index}; - {_, _, _} = Success -> Success - end - end. --endif. - --ifdef(p_not). --spec p_not(parse_fun()) -> parse_fun(). -p_not(P) -> - fun(Input, Index)-> - case P(Input,Index) of - {fail,_} -> - {[], Input, Index}; - {Result, _, _} -> {fail, {expected, {no_match, Result},Index}} - end - end. --endif. - --ifdef(p_assert). --spec p_assert(parse_fun()) -> parse_fun(). -p_assert(P) -> - fun(Input,Index) -> - case P(Input,Index) of - {fail,_} = Failure-> Failure; - _ -> {[], Input, Index} - end - end. --endif. - --ifdef(p_seq). --spec p_seq([parse_fun()]) -> parse_fun(). -p_seq(P) -> - fun(Input, Index) -> - p_all(P, Input, Index, []) - end. - --spec p_all([parse_fun()], input(), index(), [term()]) -> parse_result(). -p_all([], Inp, Index, Accum ) -> {lists:reverse( Accum ), Inp, Index}; -p_all([P|Parsers], Inp, Index, Accum) -> - case P(Inp, Index) of - {fail, _} = Failure -> Failure; - {Result, InpRem, NewIndex} -> p_all(Parsers, InpRem, NewIndex, [Result|Accum]) - end. --endif. - --ifdef(p_choose). --spec p_choose([parse_fun()]) -> parse_fun(). -p_choose(Parsers) -> - fun(Input, Index) -> - p_attempt(Parsers, Input, Index, none) - end. - --spec p_attempt([parse_fun()], input(), index(), none | parse_failure()) -> parse_result(). -p_attempt([], _Input, _Index, Failure) -> Failure; -p_attempt([P|Parsers], Input, Index, FirstFailure)-> - case P(Input, Index) of - {fail, _} = Failure -> - case FirstFailure of - none -> p_attempt(Parsers, Input, Index, Failure); - _ -> p_attempt(Parsers, Input, Index, FirstFailure) - end; - Result -> Result - end. --endif. - --ifdef(p_zero_or_more). --spec p_zero_or_more(parse_fun()) -> parse_fun(). -p_zero_or_more(P) -> - fun(Input, Index) -> - p_scan(P, Input, Index, []) - end. --endif. - --ifdef(p_one_or_more). --spec p_one_or_more(parse_fun()) -> parse_fun(). -p_one_or_more(P) -> - fun(Input, Index)-> - Result = p_scan(P, Input, Index, []), - case Result of - {[_|_], _, _} -> - Result; - _ -> - {fail, {expected, Failure, _}} = P(Input,Index), - {fail, {expected, {at_least_one, Failure}, Index}} - end - end. --endif. - --ifdef(p_label). --spec p_label(atom(), parse_fun()) -> parse_fun(). -p_label(Tag, P) -> - fun(Input, Index) -> - case P(Input, Index) of - {fail,_} = Failure -> - Failure; - {Result, InpRem, NewIndex} -> - {{Tag, Result}, InpRem, NewIndex} - end - end. --endif. - --ifdef(p_scan). --spec p_scan(parse_fun(), input(), index(), [term()]) -> {[term()], input(), index()}. -p_scan(_, <<>>, Index, Accum) -> {lists:reverse(Accum), <<>>, Index}; -p_scan(P, Inp, Index, Accum) -> - case P(Inp, Index) of - {fail,_} -> {lists:reverse(Accum), Inp, Index}; - {Result, InpRem, NewIndex} -> p_scan(P, InpRem, NewIndex, [Result | Accum]) - end. --endif. - --ifdef(p_string). --spec p_string(binary()) -> parse_fun(). -p_string(S) -> - Length = erlang:byte_size(S), - fun(Input, Index) -> - try - <> = Input, - {S, Rest, p_advance_index(S, Index)} - catch - error:{badmatch,_} -> {fail, {expected, {string, S}, Index}} - end - end. --endif. - --ifdef(p_anything). --spec p_anything() -> parse_fun(). -p_anything() -> - fun(<<>>, Index) -> {fail, {expected, any_character, Index}}; - (Input, Index) when is_binary(Input) -> - <> = Input, - {<>, Rest, p_advance_index(<>, Index)} - end. --endif. - --ifdef(p_charclass). --spec p_charclass(string() | binary()) -> parse_fun(). -p_charclass(Class) -> - {ok, RE} = re:compile(Class, [unicode, dotall]), - fun(Inp, Index) -> - case re:run(Inp, RE, [anchored]) of - {match, [{0, Length}|_]} -> - {Head, Tail} = erlang:split_binary(Inp, Length), - {Head, Tail, p_advance_index(Head, Index)}; - _ -> {fail, {expected, {character_class, binary_to_list(Class)}, Index}} - end - end. --endif. - --ifdef(p_regexp). --spec p_regexp(binary()) -> parse_fun(). -p_regexp(Regexp) -> - {ok, RE} = re:compile(Regexp, [unicode, dotall, anchored]), - fun(Inp, Index) -> - case re:run(Inp, RE) of - {match, [{0, Length}|_]} -> - {Head, Tail} = erlang:split_binary(Inp, Length), - {Head, Tail, p_advance_index(Head, Index)}; - _ -> {fail, {expected, {regexp, binary_to_list(Regexp)}, Index}} - end - end. --endif. - --ifdef(line). --spec line(index() | term()) -> pos_integer() | undefined. -line({{line,L},_}) -> L; -line(_) -> undefined. --endif. - --ifdef(column). --spec column(index() | term()) -> pos_integer() | undefined. -column({_,{column,C}}) -> C; -column(_) -> undefined. --endif. - --spec p_advance_index(input() | unicode:charlist() | pos_integer(), index()) -> index(). -p_advance_index(MatchedInput, Index) when is_list(MatchedInput) orelse is_binary(MatchedInput)-> % strings - lists:foldl(fun p_advance_index/2, Index, unicode:characters_to_list(MatchedInput)); -p_advance_index(MatchedInput, Index) when is_integer(MatchedInput) -> % single characters - {{line, Line}, {column, Col}} = Index, - case MatchedInput of - $\n -> {{line, Line+1}, {column, 1}}; - _ -> {{line, Line}, {column, Col+1}} - end. diff --git a/_build/default/plugins/neotoma/src/neotoma_parse.erl.safe b/_build/default/plugins/neotoma/src/neotoma_parse.erl.safe deleted file mode 100644 index c6486b5743..0000000000 --- a/_build/default/plugins/neotoma/src/neotoma_parse.erl.safe +++ /dev/null @@ -1,625 +0,0 @@ --module(neotoma_parse). --export([parse/1,file/1]). --define(p_anything,true). --define(p_charclass,true). --define(p_choose,true). --define(p_label,true). --define(p_not,true). --define(p_one_or_more,true). --define(p_optional,true). --define(p_scan,true). --define(p_seq,true). --define(p_string,true). --define(p_zero_or_more,true). - - - -% insert escapes into a string --spec escape_string(string()) -> string(). -escape_string(String) -> escape_string(String, []). - --spec escape_string(string(), string()) -> string(). -escape_string([], Output) -> - lists:reverse(Output); -escape_string([H|T], Output) -> - escape_string(T, - case H of - $/ -> [$/,$\\|Output]; - $\" -> [$\",$\\|Output]; % " comment inserted to help some editors with highlighting the generated parser - $\' -> [$\',$\\|Output]; % ' comment inserted to help some editors with highlighting the generated parser - $\b -> [$b,$\\|Output]; - $\d -> [$d,$\\|Output]; - $\e -> [$e,$\\|Output]; - $\f -> [$f,$\\|Output]; - $\n -> [$n,$\\|Output]; - $\r -> [$r,$\\|Output]; - $\s -> [$s,$\\|Output]; - $\t -> [$t,$\\|Output]; - $\v -> [$v,$\\|Output]; - _ -> [H|Output] - end). - --spec add_lhs(binary(), index()) -> true. -add_lhs(Symbol, Index) -> - case ets:lookup(memo_table_name(), lhs) of - [] -> - ets:insert(memo_table_name(), {lhs, [{Symbol,Index}]}); - [{lhs, L}] when is_list(L) -> - ets:insert(memo_table_name(), {lhs, [{Symbol,Index}|L]}) - end. - --spec add_nt(binary(), index()) -> true | ok. -add_nt(Symbol, Index) -> - case ets:lookup(memo_table_name(), nts) of - [] -> - ets:insert(memo_table_name(), {nts, [{Symbol,Index}]}); - [{nts, L}] when is_list(L) -> - case proplists:is_defined(Symbol, L) of - true -> - ok; - _ -> - ets:insert(memo_table_name(), {nts, [{Symbol,Index}|L]}) - end - end. - --spec verify_rules() -> ok | no_return(). -verify_rules() -> - [{lhs, LHS}] = ets:lookup(memo_table_name(), lhs), - [{nts, NTs}] = ets:lookup(memo_table_name(), nts), - [Root|NonRoots] = lists:reverse(LHS), - lists:foreach(fun({Sym,Idx}) -> - case proplists:is_defined(Sym, NTs) of - true -> - ok; - _ -> - io:format("neotoma warning: rule '~s' is unused. ~p~n", [Sym,Idx]) - end - end, NonRoots), - lists:foreach(fun({S,I}) -> - case proplists:is_defined(S, LHS) of - true -> - ok; - _ -> - io:format("neotoma error: nonterminal '~s' has no reduction. (found at ~p) No parser will be generated!~n", [S,I]), - exit({neotoma, {no_reduction, list_to_atom(binary_to_list(S))}}) - end - end, NTs), - Root. - --spec used_combinator(atom()) -> true. -used_combinator(C) -> - case ets:lookup(memo_table_name(), combinators) of - [] -> - ets:insert(memo_table_name(), {combinators, ordsets:from_list([C])}); - [{combinators, Cs}] -> - ets:insert(memo_table_name(), {combinators, ordsets:add_element(C, Cs)}) - end. - --spec used_transform_variables(binary()) -> [ 'Node' | 'Idx' ]. -used_transform_variables(Transform) -> - Code = unicode:characters_to_list(Transform), - {ok, Tokens, _} = erl_scan:string(Code), - used_transform_variables(Tokens, []). - -used_transform_variables([{var, _, Name}|Tokens], Acc) -> - used_transform_variables(Tokens, case Name of - 'Node' -> [Name | Acc]; - 'Idx' -> [Name | Acc]; - _ -> Acc - end); -used_transform_variables([_|Tokens], Acc) -> - used_transform_variables(Tokens, Acc); -used_transform_variables([], Acc) -> - lists:usort(Acc). - --spec file(file:name()) -> any(). -file(Filename) -> case file:read_file(Filename) of {ok,Bin} -> parse(Bin); Err -> Err end. - --spec parse(binary() | list()) -> any(). -parse(List) when is_list(List) -> parse(unicode:characters_to_binary(List)); -parse(Input) when is_binary(Input) -> - setup_memo(), - Result = case 'rules'(Input,{{line,1},{column,1}}) of - {AST, <<>>, _Index} -> AST; - Any -> Any - end, - release_memo(), Result. - --spec 'rules'(input(), index()) -> parse_result(). -'rules'(Input, Index) -> - p(Input, Index, 'rules', fun(I,D) -> (p_seq([p_optional(fun 'space'/2), fun 'declaration_sequence'/2, p_optional(fun 'space'/2), p_optional(fun 'code_block'/2), p_optional(fun 'space'/2)]))(I,D) end, fun(Node, _Idx) -> - RootRule = verify_rules(), - Rules = iolist_to_binary(lists:map(fun(R) -> [R, "\n\n"] end, lists:nth(2, Node))), - Code = case lists:nth(4, Node) of - {code, Block} -> Block; - _ -> [] - end, - [{rules, Rules}, - {code, Code}, - {root, RootRule}, - {transform, ets:lookup(memo_table_name(),gen_transform)}, - {combinators, ets:lookup_element(memo_table_name(), combinators, 2)}] - - end). - --spec 'declaration_sequence'(input(), index()) -> parse_result(). -'declaration_sequence'(Input, Index) -> - p(Input, Index, 'declaration_sequence', fun(I,D) -> (p_seq([p_label('head', fun 'declaration'/2), p_label('tail', p_zero_or_more(p_seq([fun 'space'/2, fun 'declaration'/2])))]))(I,D) end, fun(Node, _Idx) -> - FirstRule = proplists:get_value(head, Node), - OtherRules = [I || [_,I] <- proplists:get_value(tail, Node, [])], - [FirstRule|OtherRules] - end). - --spec 'declaration'(input(), index()) -> parse_result(). -'declaration'(Input, Index) -> - p(Input, Index, 'declaration', fun(I,D) -> (p_seq([fun 'nonterminal'/2, p_zero_or_more(fun 'space'/2), p_string(<<"<-">>), p_zero_or_more(fun 'space'/2), fun 'parsing_expression'/2, p_optional(fun 'space'/2), p_optional(fun 'code_block'/2), p_optional(fun 'space'/2), p_string(<<";">>)]))(I,D) end, fun(Node, _Idx) -> - [{nonterminal,Symbol}|Tail] = Node, - add_lhs(Symbol, Index), - Transform = case lists:nth(6,Tail) of - {code, CodeBlock} -> CodeBlock; - _ -> - ets:insert_new(memo_table_name(),{gen_transform, true}), - ["transform('",Symbol,"', Node, Idx)"] - end, - TransformArgs = case used_transform_variables(Transform) of - [] -> "_Node, _Idx"; - ['Idx'] -> "_Node, Idx"; - ['Node'] -> "Node, _Idx"; - ['Idx', 'Node'] -> "Node, Idx" - end, - ["-spec '", Symbol, "'(input(), index()) -> parse_result().\n", - "'",Symbol,"'","(Input, Index) ->\n ", - "p(Input, Index, '",Symbol,"', fun(I,D) -> (", - lists:nth(4, Tail), - ")(I,D) end, fun(", TransformArgs, ") ->",Transform," end)."] - end). - --spec 'parsing_expression'(input(), index()) -> parse_result(). -'parsing_expression'(Input, Index) -> - p(Input, Index, 'parsing_expression', fun(I,D) -> (p_choose([fun 'choice'/2, fun 'sequence'/2, fun 'primary'/2]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'choice'(input(), index()) -> parse_result(). -'choice'(Input, Index) -> - p(Input, Index, 'choice', fun(I,D) -> (p_seq([p_label('head', fun 'alternative'/2), p_label('tail', p_one_or_more(p_seq([fun 'space'/2, p_string(<<"\/">>), fun 'space'/2, fun 'alternative'/2])))]))(I,D) end, fun(Node, _Idx) -> - Tail = [lists:last(S) || S <- proplists:get_value(tail, Node)], - Head = proplists:get_value(head, Node), - Statements = [[", ", TS] || TS <- Tail], - used_combinator(p_choose), - ["p_choose([", Head, Statements, "])"] - end). - --spec 'alternative'(input(), index()) -> parse_result(). -'alternative'(Input, Index) -> - p(Input, Index, 'alternative', fun(I,D) -> (p_choose([fun 'sequence'/2, fun 'labeled_primary'/2]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'primary'(input(), index()) -> parse_result(). -'primary'(Input, Index) -> - p(Input, Index, 'primary', fun(I,D) -> (p_choose([p_seq([fun 'prefix'/2, fun 'atomic'/2]), p_seq([fun 'atomic'/2, fun 'suffix'/2]), fun 'atomic'/2]))(I,D) end, fun(Node, _Idx) -> -case Node of - [Atomic, one_or_more] -> - used_combinator(p_one_or_more), - used_combinator(p_scan), - ["p_one_or_more(", Atomic, ")"]; - [Atomic, zero_or_more] -> - used_combinator(p_zero_or_more), - used_combinator(p_scan), - ["p_zero_or_more(", Atomic, ")"]; - [Atomic, optional] -> - used_combinator(p_optional), - ["p_optional(", Atomic, ")"]; - [assert, Atomic] -> - used_combinator(p_assert), - ["p_assert(", Atomic, ")"]; - [not_, Atomic] -> - used_combinator(p_not), - ["p_not(", Atomic, ")"]; - _ -> Node -end - end). - --spec 'sequence'(input(), index()) -> parse_result(). -'sequence'(Input, Index) -> - p(Input, Index, 'sequence', fun(I,D) -> (p_seq([p_label('head', fun 'labeled_primary'/2), p_label('tail', p_one_or_more(p_seq([fun 'space'/2, fun 'labeled_primary'/2])))]))(I,D) end, fun(Node, _Idx) -> - Tail = [lists:nth(2, S) || S <- proplists:get_value(tail, Node)], - Head = proplists:get_value(head, Node), - Statements = [[", ", TS] || TS <- Tail], - used_combinator(p_seq), - ["p_seq([", Head, Statements, "])"] - end). - --spec 'labeled_primary'(input(), index()) -> parse_result(). -'labeled_primary'(Input, Index) -> - p(Input, Index, 'labeled_primary', fun(I,D) -> (p_seq([p_optional(fun 'label'/2), fun 'primary'/2]))(I,D) end, fun(Node, _Idx) -> - case hd(Node) of - [] -> lists:nth(2, Node); - Label -> - used_combinator(p_label), - ["p_label('", Label, "', ", lists:nth(2, Node), ")"] - end - end). - --spec 'label'(input(), index()) -> parse_result(). -'label'(Input, Index) -> - p(Input, Index, 'label', fun(I,D) -> (p_seq([fun 'alpha_char'/2, p_zero_or_more(fun 'alphanumeric_char'/2), p_string(<<":">>)]))(I,D) end, fun(Node, _Idx) -> - lists:sublist(Node, length(Node)-1) - end). - --spec 'suffix'(input(), index()) -> parse_result(). -'suffix'(Input, Index) -> - p(Input, Index, 'suffix', fun(I,D) -> (p_choose([fun 'repetition_suffix'/2, fun 'optional_suffix'/2]))(I,D) end, fun(Node, _Idx) -> - case Node of - <<"*">> -> zero_or_more; - <<"+">> -> one_or_more; - <<"?">> -> optional - end - end). - --spec 'optional_suffix'(input(), index()) -> parse_result(). -'optional_suffix'(Input, Index) -> - p(Input, Index, 'optional_suffix', fun(I,D) -> (p_string(<<"?">>))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'repetition_suffix'(input(), index()) -> parse_result(). -'repetition_suffix'(Input, Index) -> - p(Input, Index, 'repetition_suffix', fun(I,D) -> (p_choose([p_string(<<"+">>), p_string(<<"*">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'prefix'(input(), index()) -> parse_result(). -'prefix'(Input, Index) -> - p(Input, Index, 'prefix', fun(I,D) -> (p_choose([p_string(<<"&">>), p_string(<<"!">>)]))(I,D) end, fun(Node, _Idx) -> - case Node of - <<"&">> -> assert; - <<"!">> -> not_ - end - end). - --spec 'atomic'(input(), index()) -> parse_result(). -'atomic'(Input, Index) -> - p(Input, Index, 'atomic', fun(I,D) -> (p_choose([fun 'terminal'/2, fun 'nonterminal'/2, fun 'parenthesized_expression'/2]))(I,D) end, fun(Node, _Idx) -> -case Node of - {nonterminal, Symbol} -> - [<<"fun '">>, Symbol, <<"'/2">>]; - _ -> Node -end - end). - --spec 'parenthesized_expression'(input(), index()) -> parse_result(). -'parenthesized_expression'(Input, Index) -> - p(Input, Index, 'parenthesized_expression', fun(I,D) -> (p_seq([p_string(<<"(">>), p_optional(fun 'space'/2), fun 'parsing_expression'/2, p_optional(fun 'space'/2), p_string(<<")">>)]))(I,D) end, fun(Node, _Idx) ->lists:nth(3, Node) end). - --spec 'nonterminal'(input(), index()) -> parse_result(). -'nonterminal'(Input, Index) -> - p(Input, Index, 'nonterminal', fun(I,D) -> (p_seq([fun 'alpha_char'/2, p_zero_or_more(fun 'alphanumeric_char'/2)]))(I,D) end, fun(Node, Idx) -> - Symbol = iolist_to_binary(Node), - add_nt(Symbol, Idx), - {nonterminal, Symbol} - end). - --spec 'terminal'(input(), index()) -> parse_result(). -'terminal'(Input, Index) -> - p(Input, Index, 'terminal', fun(I,D) -> (p_choose([fun 'regexp_string'/2, fun 'quoted_string'/2, fun 'character_class'/2, fun 'anything_symbol'/2]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'regexp_string'(input(), index()) -> parse_result(). -'regexp_string'(Input, Index) -> - p(Input, Index, 'regexp_string', fun(I,D) -> (p_seq([p_string(<<"#">>), p_label('string', p_one_or_more(p_seq([p_not(p_string(<<"#">>)), p_choose([p_string(<<"\\#">>), p_anything()])]))), p_string(<<"#">>)]))(I,D) end, fun(Node, _Idx) -> - used_combinator(p_regexp), - ["p_regexp(<<\"", - % Escape \ and " as they are used in erlang string. Other sumbol stay as is. - % \ -> \\ - % " -> \" - re:replace(proplists:get_value(string, Node), "\"|\\\\", "\\\\&", [{return, binary}, global]), - "\">>)"] - end). - --spec 'quoted_string'(input(), index()) -> parse_result(). -'quoted_string'(Input, Index) -> - p(Input, Index, 'quoted_string', fun(I,D) -> (p_choose([fun 'single_quoted_string'/2, fun 'double_quoted_string'/2]))(I,D) end, fun(Node, _Idx) -> - used_combinator(p_string), - lists:flatten(["p_string(<<\"", - escape_string(binary_to_list(iolist_to_binary(proplists:get_value(string, Node)))), - "\">>)"]) - end). - --spec 'double_quoted_string'(input(), index()) -> parse_result(). -'double_quoted_string'(Input, Index) -> - p(Input, Index, 'double_quoted_string', fun(I,D) -> (p_seq([p_string(<<"\"">>), p_label('string', p_zero_or_more(p_seq([p_not(p_string(<<"\"">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\"">>), p_anything()])]))), p_string(<<"\"">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'single_quoted_string'(input(), index()) -> parse_result(). -'single_quoted_string'(Input, Index) -> - p(Input, Index, 'single_quoted_string', fun(I,D) -> (p_seq([p_string(<<"\'">>), p_label('string', p_zero_or_more(p_seq([p_not(p_string(<<"\'">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\'">>), p_anything()])]))), p_string(<<"\'">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'character_class'(input(), index()) -> parse_result(). -'character_class'(Input, Index) -> - p(Input, Index, 'character_class', fun(I,D) -> (p_seq([p_string(<<"[">>), p_label('characters', p_one_or_more(p_seq([p_not(p_string(<<"]">>)), p_choose([p_seq([p_string(<<"\\\\">>), p_anything()]), p_seq([p_not(p_string(<<"\\\\">>)), p_anything()])])]))), p_string(<<"]">>)]))(I,D) end, fun(Node, _Idx) -> - used_combinator(p_charclass), - ["p_charclass(<<\"[", - escape_string(binary_to_list(iolist_to_binary(proplists:get_value(characters, Node)))), - "]\">>)"] - end). - --spec 'anything_symbol'(input(), index()) -> parse_result(). -'anything_symbol'(Input, Index) -> - p(Input, Index, 'anything_symbol', fun(I,D) -> (p_string(<<".">>))(I,D) end, fun(_Node, _Idx) -> used_combinator(p_anything), <<"p_anything()">> end). - --spec 'alpha_char'(input(), index()) -> parse_result(). -'alpha_char'(Input, Index) -> - p(Input, Index, 'alpha_char', fun(I,D) -> (p_charclass(<<"[A-Za-z_]">>))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'alphanumeric_char'(input(), index()) -> parse_result(). -'alphanumeric_char'(Input, Index) -> - p(Input, Index, 'alphanumeric_char', fun(I,D) -> (p_choose([fun 'alpha_char'/2, p_charclass(<<"[0-9]">>)]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'space'(input(), index()) -> parse_result(). -'space'(Input, Index) -> - p(Input, Index, 'space', fun(I,D) -> (p_one_or_more(p_choose([fun 'white'/2, fun 'comment_to_eol'/2])))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'comment_to_eol'(input(), index()) -> parse_result(). -'comment_to_eol'(Input, Index) -> - p(Input, Index, 'comment_to_eol', fun(I,D) -> (p_seq([p_not(p_string(<<"%{">>)), p_string(<<"%">>), p_zero_or_more(p_seq([p_not(p_string(<<"\n">>)), p_anything()]))]))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'white'(input(), index()) -> parse_result(). -'white'(Input, Index) -> - p(Input, Index, 'white', fun(I,D) -> (p_charclass(<<"[\s\t\n\r]">>))(I,D) end, fun(Node, _Idx) ->Node end). - --spec 'code_block'(input(), index()) -> parse_result(). -'code_block'(Input, Index) -> - p(Input, Index, 'code_block', fun(I,D) -> (p_choose([p_seq([p_string(<<"%{">>), p_label('code', p_one_or_more(p_choose([p_string(<<"\\%">>), p_string(<<"$%">>), p_seq([p_not(p_string(<<"%}">>)), p_anything()])]))), p_string(<<"%}">>)]), p_seq([p_string(<<"`">>), p_label('code', p_one_or_more(p_choose([p_string(<<"\\`">>), p_string(<<"$`">>), p_seq([p_not(p_string(<<"`">>)), p_anything()])]))), p_string(<<"`">>)]), p_string(<<"~">>)]))(I,D) end, fun(Node, _Idx) -> - case Node of - <<"~">> -> {code, <<"Node">>}; - _ -> {code, proplists:get_value('code', Node)} - end - end). - - - --file("peg_includes.hrl", 1). --type index() :: {{line, pos_integer()}, {column, pos_integer()}}. --type input() :: binary(). --type parse_failure() :: {fail, term()}. --type parse_success() :: {term(), input(), index()}. --type parse_result() :: parse_failure() | parse_success(). --type parse_fun() :: fun((input(), index()) -> parse_result()). --type xform_fun() :: fun((input(), index()) -> term()). - --spec p(input(), index(), atom(), parse_fun(), xform_fun()) -> parse_result(). -p(Inp, StartIndex, Name, ParseFun, TransformFun) -> - case get_memo(StartIndex, Name) of % See if the current reduction is memoized - {ok, Memo} -> %Memo; % If it is, return the stored result - Memo; - _ -> % If not, attempt to parse - Result = case ParseFun(Inp, StartIndex) of - {fail,_} = Failure -> % If it fails, memoize the failure - Failure; - {Match, InpRem, NewIndex} -> % If it passes, transform and memoize the result. - Transformed = TransformFun(Match, StartIndex), - {Transformed, InpRem, NewIndex} - end, - memoize(StartIndex, Name, Result), - Result - end. - --spec setup_memo() -> ets:tid(). -setup_memo() -> - put({parse_memo_table, ?MODULE}, ets:new(?MODULE, [set])). - --spec release_memo() -> true. -release_memo() -> - ets:delete(memo_table_name()). - --spec memoize(index(), atom(), parse_result()) -> true. -memoize(Index, Name, Result) -> - Memo = case ets:lookup(memo_table_name(), Index) of - [] -> []; - [{Index, Plist}] -> Plist - end, - ets:insert(memo_table_name(), {Index, [{Name, Result}|Memo]}). - --spec get_memo(index(), atom()) -> {ok, term()} | {error, not_found}. -get_memo(Index, Name) -> - case ets:lookup(memo_table_name(), Index) of - [] -> {error, not_found}; - [{Index, Plist}] -> - case proplists:lookup(Name, Plist) of - {Name, Result} -> {ok, Result}; - _ -> {error, not_found} - end - end. - --spec memo_table_name() -> ets:tid(). -memo_table_name() -> - get({parse_memo_table, ?MODULE}). - --ifdef(p_eof). --spec p_eof() -> parse_fun(). -p_eof() -> - fun(<<>>, Index) -> {eof, [], Index}; - (_, Index) -> {fail, {expected, eof, Index}} end. --endif. - --ifdef(p_optional). --spec p_optional(parse_fun()) -> parse_fun(). -p_optional(P) -> - fun(Input, Index) -> - case P(Input, Index) of - {fail,_} -> {[], Input, Index}; - {_, _, _} = Success -> Success - end - end. --endif. - --ifdef(p_not). --spec p_not(parse_fun()) -> parse_fun(). -p_not(P) -> - fun(Input, Index)-> - case P(Input,Index) of - {fail,_} -> - {[], Input, Index}; - {Result, _, _} -> {fail, {expected, {no_match, Result},Index}} - end - end. --endif. - --ifdef(p_assert). --spec p_assert(parse_fun()) -> parse_fun(). -p_assert(P) -> - fun(Input,Index) -> - case P(Input,Index) of - {fail,_} = Failure-> Failure; - _ -> {[], Input, Index} - end - end. --endif. - --ifdef(p_seq). --spec p_seq([parse_fun()]) -> parse_fun(). -p_seq(P) -> - fun(Input, Index) -> - p_all(P, Input, Index, []) - end. - --spec p_all([parse_fun()], input(), index(), [term()]) -> parse_result(). -p_all([], Inp, Index, Accum ) -> {lists:reverse( Accum ), Inp, Index}; -p_all([P|Parsers], Inp, Index, Accum) -> - case P(Inp, Index) of - {fail, _} = Failure -> Failure; - {Result, InpRem, NewIndex} -> p_all(Parsers, InpRem, NewIndex, [Result|Accum]) - end. --endif. - --ifdef(p_choose). --spec p_choose([parse_fun()]) -> parse_fun(). -p_choose(Parsers) -> - fun(Input, Index) -> - p_attempt(Parsers, Input, Index, none) - end. - --spec p_attempt([parse_fun()], input(), index(), none | parse_failure()) -> parse_result(). -p_attempt([], _Input, _Index, Failure) -> Failure; -p_attempt([P|Parsers], Input, Index, FirstFailure)-> - case P(Input, Index) of - {fail, _} = Failure -> - case FirstFailure of - none -> p_attempt(Parsers, Input, Index, Failure); - _ -> p_attempt(Parsers, Input, Index, FirstFailure) - end; - Result -> Result - end. --endif. - --ifdef(p_zero_or_more). --spec p_zero_or_more(parse_fun()) -> parse_fun(). -p_zero_or_more(P) -> - fun(Input, Index) -> - p_scan(P, Input, Index, []) - end. --endif. - --ifdef(p_one_or_more). --spec p_one_or_more(parse_fun()) -> parse_fun(). -p_one_or_more(P) -> - fun(Input, Index)-> - Result = p_scan(P, Input, Index, []), - case Result of - {[_|_], _, _} -> - Result; - _ -> - {fail, {expected, Failure, _}} = P(Input,Index), - {fail, {expected, {at_least_one, Failure}, Index}} - end - end. --endif. - --ifdef(p_label). --spec p_label(atom(), parse_fun()) -> parse_fun(). -p_label(Tag, P) -> - fun(Input, Index) -> - case P(Input, Index) of - {fail,_} = Failure -> - Failure; - {Result, InpRem, NewIndex} -> - {{Tag, Result}, InpRem, NewIndex} - end - end. --endif. - --ifdef(p_scan). --spec p_scan(parse_fun(), input(), index(), [term()]) -> {[term()], input(), index()}. -p_scan(_, <<>>, Index, Accum) -> {lists:reverse(Accum), <<>>, Index}; -p_scan(P, Inp, Index, Accum) -> - case P(Inp, Index) of - {fail,_} -> {lists:reverse(Accum), Inp, Index}; - {Result, InpRem, NewIndex} -> p_scan(P, InpRem, NewIndex, [Result | Accum]) - end. --endif. - --ifdef(p_string). --spec p_string(binary()) -> parse_fun(). -p_string(S) -> - Length = erlang:byte_size(S), - fun(Input, Index) -> - try - <> = Input, - {S, Rest, p_advance_index(S, Index)} - catch - error:{badmatch,_} -> {fail, {expected, {string, S}, Index}} - end - end. --endif. - --ifdef(p_anything). --spec p_anything() -> parse_fun(). -p_anything() -> - fun(<<>>, Index) -> {fail, {expected, any_character, Index}}; - (Input, Index) when is_binary(Input) -> - <> = Input, - {<>, Rest, p_advance_index(<>, Index)} - end. --endif. - --ifdef(p_charclass). --spec p_charclass(string() | binary()) -> parse_fun(). -p_charclass(Class) -> - {ok, RE} = re:compile(Class, [unicode, dotall]), - fun(Inp, Index) -> - case re:run(Inp, RE, [anchored]) of - {match, [{0, Length}|_]} -> - {Head, Tail} = erlang:split_binary(Inp, Length), - {Head, Tail, p_advance_index(Head, Index)}; - _ -> {fail, {expected, {character_class, binary_to_list(Class)}, Index}} - end - end. --endif. - --ifdef(p_regexp). --spec p_regexp(binary()) -> parse_fun(). -p_regexp(Regexp) -> - {ok, RE} = re:compile(Regexp, [unicode, dotall, anchored]), - fun(Inp, Index) -> - case re:run(Inp, RE) of - {match, [{0, Length}|_]} -> - {Head, Tail} = erlang:split_binary(Inp, Length), - {Head, Tail, p_advance_index(Head, Index)}; - _ -> {fail, {expected, {regexp, binary_to_list(Regexp)}, Index}} - end - end. --endif. - --ifdef(line). --spec line(index() | term()) -> pos_integer() | undefined. -line({{line,L},_}) -> L; -line(_) -> undefined. --endif. - --ifdef(column). --spec column(index() | term()) -> pos_integer() | undefined. -column({_,{column,C}}) -> C; -column(_) -> undefined. --endif. - --spec p_advance_index(input() | unicode:charlist() | pos_integer(), index()) -> index(). -p_advance_index(MatchedInput, Index) when is_list(MatchedInput) orelse is_binary(MatchedInput)-> % strings - lists:foldl(fun p_advance_index/2, Index, unicode:characters_to_list(MatchedInput)); -p_advance_index(MatchedInput, Index) when is_integer(MatchedInput) -> % single characters - {{line, Line}, {column, Col}} = Index, - case MatchedInput of - $\n -> {{line, Line+1}, {column, 1}}; - _ -> {{line, Line}, {column, Col+1}} - end. diff --git a/_build/default/plugins/pc b/_build/default/plugins/pc deleted file mode 160000 index a94c4afc25..0000000000 --- a/_build/default/plugins/pc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a94c4afc253ada8ffe3d8eebdaaffde5d8a0f390 diff --git a/_build/default/plugins/rebar3_hex/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/rebar3_hex/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index ad4790dbdd..0000000000 Binary files a/_build/default/plugins/rebar3_hex/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/rebar3_hex/LICENSE b/_build/default/plugins/rebar3_hex/LICENSE deleted file mode 100644 index f5927955cf..0000000000 --- a/_build/default/plugins/rebar3_hex/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2015, Tristan Sloughter . -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. - -* The names of its contributors may not 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 -OWNER 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. diff --git a/_build/default/plugins/rebar3_hex/README.md b/_build/default/plugins/rebar3_hex/README.md deleted file mode 100644 index cd01a6b3ff..0000000000 --- a/_build/default/plugins/rebar3_hex/README.md +++ /dev/null @@ -1,92 +0,0 @@ -rebar3 Hex Providers [![GitHub Actions CI][ci-img]][ci] [![Coverage][cov-img]][cov] -========================= - -[ci]: https://hub.fastgit.org/tsloughter/rebar3_hex -[ci-img]: https://hub.fastgit.org/tsloughter/rebar3_hex/workflows/build/badge.svg -[cov]: https://codecov.io/gh/tsloughter/rebar3_hex -[cov-img]: https://codecov.io/gh/tsloughter/rebar3_hex/branch/master/graph/badge.svg - -Providers for interacting with the Erlang package manager [hex.pm](https://hex.pm/). - - -Usage ------- - -Add to your global rebar3 config in `~/.config/rebar3/rebar.config`: - -```erlang -{plugins, [rebar3_hex]}. -``` - -Usage --------- - -## Authenticating User - -If you already have a user for [hex.pm](https://hex.pm) run: - - -```shell -$ rebar3 hex user auth -``` - -Note that this will ask for your hex.pm username and password, as well as a password for encrypting your api token that has write permissions to the repository. When publishing a package you will have to give this password to decrypt the token in order to publish. - -## Private Organizations - -[Private organizations]() are treated as repositories that have a parent. The parent is found as the first part of a repository's name, separated from the organization by a `:`. So for an organization `rebar3` on the main repository `hexpm` the name must be `hexpm:rebar3`. - -`~/.config/rebar3/rebar.config` - -```erlang -{hex, [{repos, [ - #{name => <<"hexpm:rebar3">>} - ]}]}. -``` - -## Read-Only Repo Key for CI - -If you have a private organization or other private repository it is recommended that you use a repo specific auth token for reading from the repository in CI. To generate a token: - -```shell -$ rebar3 hex repo auth generate -Generated key: abc123 -``` - -Then in CI use whatever method is available for setting an environment variable to the token and add this call at the beginning of your CI runs to add the token to your rebar3 hex tokens: - -```shell -$ rebar3 hex repo auth --key $REPO_KEY -``` - -## Publishing Packages - -Two functions are available for publishing applications to hex as packages. The first, `hex publish`, simply packages up what you have as is: - -``` shell -$ rebar3 hex publish -``` - -Note that it will display the details of what it is publishing (what files, the version, dependencies) and ask if it should continue, so be sure to read the output carefully and make sure it is publishing what you expected. - -Another task, `hex cut` is available to provide some additional functionality around versioning and git tags: - -``` shell -$ rebar3 hex cut -``` - -This command will ask how to increment (major, minor, patch) the version number based on the last version and can create a git tag and push that tag upstream. - -## Publishing Docs - -``` shell -$ rebar3 hex docs -``` - -## Adding and Removing Owners of Packages - -Owners can be added and removed for packages you are an owner of with the `hex owner` command: - -``` shell -$ rebar3 hex owner [add | remove] -``` diff --git a/_build/default/plugins/rebar3_hex/hex_metadata.config b/_build/default/plugins/rebar3_hex/hex_metadata.config deleted file mode 100644 index c652c69028..0000000000 --- a/_build/default/plugins/rebar3_hex/hex_metadata.config +++ /dev/null @@ -1,28 +0,0 @@ -{<<"app">>,<<"rebar3_hex">>}. -{<<"build_tools">>,[<<"rebar3">>]}. -{<<"description">>,<<"Hex.pm plugin for rebar3">>}. -{<<"files">>, - [<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>,<<"rebar.lock">>, - <<"src/rebar3_hex.app.src">>,<<"src/rebar3_hex.erl">>, - <<"src/rebar3_hex.hrl">>,<<"src/rebar3_hex_client.erl">>, - <<"src/rebar3_hex_config.erl">>,<<"src/rebar3_hex_cut.erl">>, - <<"src/rebar3_hex_docs.erl">>,<<"src/rebar3_hex_error.erl">>, - <<"src/rebar3_hex_file.erl">>,<<"src/rebar3_hex_io.erl">>, - <<"src/rebar3_hex_key.erl">>,<<"src/rebar3_hex_owner.erl">>, - <<"src/rebar3_hex_publish.erl">>,<<"src/rebar3_hex_repo.erl">>, - <<"src/rebar3_hex_results.erl">>,<<"src/rebar3_hex_retire.erl">>, - <<"src/rebar3_hex_revert.erl">>,<<"src/rebar3_hex_search.erl">>, - <<"src/rebar3_hex_user.erl">>]}. -{<<"licenses">>,[<<"MIT">>]}. -{<<"links">>,[{<<"Github">>,<<"https://hub.fastgit.org/tsloughter/rebar3_hex">>}]}. -{<<"name">>,<<"rebar3_hex">>}. -{<<"requirements">>, - [{<<"hex_core">>, - [{<<"app">>,<<"hex_core">>}, - {<<"optional">>,false}, - {<<"requirement">>,<<"0.7.1">>}]}, - {<<"verl">>, - [{<<"app">>,<<"verl">>}, - {<<"optional">>,false}, - {<<"requirement">>,<<"1.0.2">>}]}]}. -{<<"version">>,<<"6.11.3">>}. diff --git a/_build/default/plugins/rebar3_hex/rebar.config b/_build/default/plugins/rebar3_hex/rebar.config deleted file mode 100644 index cb1c1bf888..0000000000 --- a/_build/default/plugins/rebar3_hex/rebar.config +++ /dev/null @@ -1,33 +0,0 @@ -{minimum_otp_vsn, "18"}. - -{erl_opts, [ - debug_info, - {platform_define, "^2[3-9]", 'POST_OTP_22'}, - {platform_define, "^20", 'POST_OTP_19'}, - {platform_define, "^19", 'POST_OTP_18'}, - {platform_define, "^[2-9]", 'POST_OTP_18'} -]}. - -{project_plugins, [covertool, {rebar3_hank, "~> 0.3.0"}]}. - -{deps, [{hex_core, "0.7.1"}, {verl, "1.0.2"}]}. - -{profiles, [ - {test, [ - {extra_src_dirs, ["test/support"]}, - {overrides, [{override, rebar3,[{deps, [{erlware_commons, "1.3.1"}]}]}]}, - {deps, [{hex_core, "0.7.1"}, - {erlware_commons, "1.3.1"}, {elli, "3.3.0"}, - {jsone, "1.5.3"}, {meck, "0.9.0"}]}, - {erl_opts, [nowarn_export_all]} - ]} -]}. - -{hank, - [{ignore, - [{"test/**/*.erl", unnecessary_function_arguments}]}]}. - -{xref_checks,[undefined_function_calls,undefined_functions,locals_not_used, - deprecated_function_calls,deprecated_functions]}. - -{alias, [{test, [{ct, "--cover"}, {cover, "-v"}]}]}. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex.app.src b/_build/default/plugins/rebar3_hex/src/rebar3_hex.app.src deleted file mode 100644 index 314d82b1c6..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex.app.src +++ /dev/null @@ -1,8 +0,0 @@ -{application,rebar3_hex, - [{description,"Hex.pm plugin for rebar3"}, - {vsn,"6.11.3"}, - {applications,[kernel,stdlib]}, - {maintainers,["Tristan Sloughter"]}, - {licenses,["MIT"]}, - {links,[{"Github", - "https://hub.fastgit.org/tsloughter/rebar3_hex"}]}]}. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex.erl deleted file mode 100644 index eef1c2d547..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex.erl +++ /dev/null @@ -1,58 +0,0 @@ --module(rebar3_hex). - --export([ init/1 - , gather_opts/2 - , get_required/2 - , task_args/1 - , repo_opt/0 - , help_opt/0 - ]). - -init(State) -> - lists:foldl(fun provider_init/2, {ok, State}, [rebar3_hex_user, - rebar3_hex_cut, - rebar3_hex_key, - rebar3_hex_owner, - rebar3_hex_repo, - rebar3_hex_docs, - rebar3_hex_search, - rebar3_hex_revert, - rebar3_hex_retire, - rebar3_hex_publish]). - -provider_init(Module, {ok, State}) -> - Module:init(State). - -gather_opts(Targets, State) -> - {Args, _} = rebar_state:command_parsed_args(State), - lists:foldl(fun(T, Acc) -> - case proplists:get_value(T, Args, undefined) of - undefined -> - Acc; - V -> - maps:put(T, V, Acc) - end - end, #{}, Targets). - -get_required(Key, Args) -> - case proplists:get_value(Key, Args) of - undefined -> - {error, {required, Key}}; - Value -> - Value - end. - -task_args(State) -> - {Opts, _Args} = rebar_state:command_parsed_args(State), - case proplists:get_value(task, Opts, undefined) of - undefined -> - {undefined, Opts}; - Task -> - {Task, proplists:delete(task, Opts)} - end. - -repo_opt() -> - {repo, $r, "repo", string, "Repository to use for this command."}. - -help_opt() -> - {help, $h, "help", undefined, "Help"}. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex.hrl b/_build/default/plugins/rebar3_hex/src/rebar3_hex.hrl deleted file mode 100644 index 513d640155..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex.hrl +++ /dev/null @@ -1,3 +0,0 @@ --define(PRV_ERROR(Reason), - {error, {?MODULE, Reason}}). --define(DEFAULT_HEX_REPO, <<"hexpm">>). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_client.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_client.erl deleted file mode 100644 index 5aaf0c68c6..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_client.erl +++ /dev/null @@ -1,128 +0,0 @@ --module(rebar3_hex_client). - --export([ is_success/1 - , key_add/3 - , key_get/2 - , key_delete/2 - , key_delete_all/1 - , key_list/1 - , publish/3 - , publish_docs/4 - , delete_docs/3 - , test_key/2 - , member_of/1 - , pretty_print_status/1 - , pretty_print_errors/1 - ]). - --include("rebar3_hex.hrl"). - --define(is_success(N), N >= 200 andalso N =< 299). - -key_add(HexConfig, <>, Perms) -> - Res = hex_api_key:add(HexConfig, KeyName, Perms), - response(Res); -key_add(HexConfig, KeyName, Perms) -> - key_add(HexConfig, to_binary(KeyName), Perms). - -key_get(HexConfig, <>) -> - Res = hex_api_key:get(HexConfig, KeyName), - response(Res); -key_get(HexConfig, KeyName) -> - key_get(HexConfig, to_binary(KeyName)). - -member_of(HexConfig) -> - Res = hex_api_organization:list(HexConfig), - response(Res). - -key_list(HexConfig) -> - Res = hex_api_key:list(HexConfig), - response(Res). - -key_delete(HexConfig, <>) -> - Res = hex_api_key:delete(HexConfig, KeyName), - response(Res); -key_delete(HexConfig, KeyName) -> - key_delete(HexConfig, to_binary(KeyName)). - -key_delete_all(HexConfig) -> - Res = hex_api_key:delete_all(HexConfig), - response(Res). - -test_key(HexConfig, Perms) -> - Res = hex_api_auth:test(HexConfig, Perms), - response(Res). - -publish(HexConfig, Tarball, Opts) -> - Res = hex_api_release:publish(HexConfig, Tarball, Opts), - response(Res). - -publish_docs(Repo, Name, Version, Tarball) -> - {ok, Config} = rebar3_hex_config:hex_config_write(Repo), - - TarballContentType = "application/octet-stream", - - Headers = maps:get(http_headers, Config, #{}), - Headers1 = maps:put(<<"content-length">>, integer_to_binary(byte_size(Tarball)), Headers), - Config2 = maps:put(http_headers, Headers1, Config), - - Body = {TarballContentType, Tarball}, - Res = hex_api:post(Config2, ["packages", Name, "releases", Version, "docs"], Body), - response(Res). - -delete_docs(Config, Name, Version) -> - Res = hex_api:delete(Config, ["packages", Name, "releases", Version, "docs"]), - response(Res). - -response({ok, {201, _Headers, Res}}) -> - {ok, Res}; -response({ok, {204, _Headers, Res}}) -> - {ok, Res}; -response({ok, {N, _Headers, Res}}) when ?is_success(N) -> - {ok, Res}; -response({ok, {401, _Headers, Res}}) -> - {error, Res}; -response({ok, {403, _Headers, Res}}) -> - {error, Res}; -response({ok, {404, _Headers, Res}}) -> - {error, Res}; -response({ok, {422, _Headers, #{<<"message">> := <<"Validation error(s)">>} = Res}}) -> - {error, Res}; -response({ok, {422, _Headers, Res}}) -> - {error, Res}; -response({_, _} = Unknown) -> - Unknown. - -is_success(N) when ?is_success(N) -> true; -is_success(_N) -> false. - -pretty_print_status(401) -> "Authentication failed (401)"; -pretty_print_status(403) -> "Forbidden (403)"; -pretty_print_status(404) -> "Entity not found (404)"; -pretty_print_status(422) -> "Validation failed (422)"; -pretty_print_status(Code) -> io_lib:format("HTTP status code: ~p", [Code]). - -pretty_print_errors(Errors) -> - L = maps:fold(fun(K,V,Acc) -> - case is_map(V) of - true -> - Acc ++ [pretty_print_errors(V)]; - false -> - Acc ++ [<>] - end - end, - [], - Errors), - binary:list_to_bin(join_lists(", ", L)). - --ifdef(POST_OTP_18). -join_lists(Sep, List) -> lists:join(Sep, List). --else. -join_lists(_Sep, []) -> []; -join_lists(Sep, List) -> - [Last | AllButLast] = lists:reverse(List), - lists:foldl(fun (Elem,Acc) -> [Elem,Sep|Acc] end, [Last], AllButLast). --endif. - -to_binary(Subject) -> - rebar_utils:to_binary(Subject). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_config.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_config.erl deleted file mode 100644 index f7a591a483..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_config.erl +++ /dev/null @@ -1,176 +0,0 @@ --module(rebar3_hex_config). - --export([ api_key_name/1 - , api_key_name/2 - , repos_key_name/0 - , org_key_name/2 - , parent_repos/1 - , hex_config/2 - , hex_config_write/1 - , hex_config_read/1 - , repo/1 - , update_auth_config/2 - ]). - --include("rebar3_hex.hrl"). - --spec api_key_name(binary()) -> binary(). -api_key_name(Key) -> - Prefix = key_name_prefix(Key), - key_name(Prefix, <<"-api">>). - --spec api_key_name(binary(), binary()) -> binary(). -api_key_name(Key, Suffix) -> - Prefix = key_name_prefix(Key), - key_name(Prefix, <<"-api-">>, Suffix). - --spec repos_key_name() -> binary(). -repos_key_name() -> - key_name(hostname(), <<"-repositories">>). - --spec org_key_name(binary(), binary()) -> binary(). -org_key_name(Key, Org) -> - Prefix = key_name_prefix(Key), - key_name(Prefix, <<"-repository-">>, Org). - --spec hostname() -> binary(). -hostname() -> - {ok, Name} = inet:gethostname(), - list_to_binary(Name). - -key_name(Prefix, Suffix) -> - <>. - -key_name(Prefix, Interfix, Suffix) -> - <>. - -key_name_prefix(undefined) -> hostname(); -key_name_prefix(Key) -> Key. - -update_auth_config(Config, State) -> - rebar_hex_repos:update_auth_config(Config, State). - -repo(State) -> - {Args, _} = rebar_state:command_parsed_args(State), - Resources = rebar_state:resources(State), - #{repos := Repos} = rebar_resource_v2:find_resource_state(pkg, Resources), - case proplists:get_value(repo, Args, undefined) of - undefined -> - Res = [R || R <- Repos, maps:get(name, R) =/= ?DEFAULT_HEX_REPO], - case Res of - [] -> - case rebar_hex_repos:get_repo_config(?DEFAULT_HEX_REPO, Repos) of - {ok, Repo} -> - {ok, set_http_adapter(Repo)}; - _ -> - {error, no_repo_in_state} - end; - [_Repo|_Rest] -> - {error, {required, repo}} - end; - RepoName -> - repo(State, RepoName) - end. - -repo(State, RepoName) -> - Resources = rebar_state:resources(State), - #{repos := Repos} = rebar_resource_v2:find_resource_state(pkg, Resources), - BinName = rebar_utils:to_binary(RepoName), - MaybeFound1 = get_repo(BinName, Repos), - MaybeParentRepo = <<"hexpm:">>, - MaybeFound2 = get_repo(<>, Repos), - case {MaybeFound1, MaybeFound2} of - {{ok, Repo1}, undefined} -> - {ok, set_http_adapter(merge_with_env(Repo1))}; - {undefined, {ok, Repo2}} -> - {ok, set_http_adapter(merge_with_env(Repo2))}; - {undefined, undefined} -> - {error, {not_valid_repo, RepoName}} - end. - - --define( ENV_VARS - , [ {"HEX_API_KEY", {api_key, {string, undefined}}} - , {"HEX_API_URL", {api_url, {string, undefined}}} - , {"HEX_UNSAFE_REGISTRY", {repo_verify, {boolean, false}}} - , {"HEX_NO_VERIFY_REPO_ORIGIN", {repo_verify_origin, {boolean, true}}} - ] - ). - -merge_with_env(Repo) -> - lists:foldl(fun({EnvName, {Key, _} = Default}, Acc) -> - Val = maybe_env_val(EnvName, Default), - maybe_put_key(Key, Val, Acc) - end, Repo, ?ENV_VARS). - -maybe_put_key(_Key, undefined, Repo) -> - Repo; -maybe_put_key(Key, Val, Repo) -> - case maps:get(Key, Repo, undefined) of - Val -> - Repo; - _ -> - Repo#{Key => Val} - end. - -maybe_env_val(K, {_, {Type, Default}}) -> - case {os:getenv(K), {Type, Default}} of - {false, {_, Default}} -> - Default; - {"", {_, Default}} -> - Default; - {Val, {boolean, _}} -> - to_bool(string:to_lower(Val)); - {Val, {string, _}} -> - rebar_utils:to_binary(Val) - end. - -set_http_adapter(Repo) -> - Repo#{http_adapter => {hex_http_httpc, #{profile => rebar}}}. - -to_bool("0") -> false; -to_bool("false") -> false; -to_bool(_) -> true. - -parent_repos(State) -> - Resources = rebar_state:resources(State), - #{repos := Repos} = rebar_resource_v2:find_resource_state(pkg, Resources), - Fun = fun(#{name := Name} = Repo, Acc) -> - [Parent|_] = rebar3_hex_io:str_split(Name, <<":">>), - case maps:is_key(Parent, Acc) of - true -> - Acc; - false -> - maps:put(name, Repo, Acc) - end - end, - Map = lists:foldl(Fun, #{}, Repos), - {ok, maps:values(Map)}. - -get_repo(BinaryName, Repos) -> - try rebar_hex_repos:get_repo_config(BinaryName, Repos) of - Name -> - Name - catch - {error,{rebar_hex_repos,{repo_not_found,BinaryName}}} -> undefined - end. - -hex_config(Repo, read) -> - hex_config_read(Repo); -hex_config(Repo, write) -> - hex_config_write(Repo). - -hex_config_write(#{api_key := Key} = HexConfig) when is_binary(Key) -> - {ok, set_http_adapter(HexConfig)}; -hex_config_write(#{write_key := undefined}) -> - {error, no_write_key}; -hex_config_write(#{api_key := undefined, write_key := WriteKey, username := Username} = HexConfig) -> - DecryptedWriteKey = rebar3_hex_user:decrypt_write_key(Username, WriteKey), - {ok, set_http_adapter(HexConfig#{api_key => DecryptedWriteKey})}; -hex_config_write(_) -> - {error, no_write_key}. - -hex_config_read(#{read_key := ReadKey} = HexConfig) -> - {ok, set_http_adapter(HexConfig#{api_key => ReadKey})}; -hex_config_read(_Config) -> - {error, no_read_key}. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_cut.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_cut.erl deleted file mode 100644 index 9b64c9f89c..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_cut.erl +++ /dev/null @@ -1,188 +0,0 @@ --module(rebar3_hex_cut). - --export([init/1, - do/1, - format_error/1]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, cut). --define(DEPS, [{default, lock}]). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex cut"}, - {short_desc, "Increment version number and publish package"}, - {desc, ""}, - {opts, [{increment, $i, "increment", string, - "Type of semver increment: major, minor or patch"}, - rebar3_hex:repo_opt()]} - ]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - case rebar3_hex_config:repo(State) of - {ok, Repo} -> - handle_command(State, Repo); - {error, Reason} -> - ?PRV_ERROR(Reason) - end. - -handle_command(State, Repo) -> - {Args, _} = rebar_state:command_parsed_args(State), - case proplists:get_value(increment, Args, undefined) of - undefined -> - Apps = rebar3_hex_io:select_apps(rebar_state:project_apps(State)), - lists:foldl(fun(App, {ok, StateAcc}) -> - do_(App, Repo, StateAcc) - end, {ok, State}, Apps); - Type -> - case string_to_bump(Type) of - error -> - {error, {?MODULE, {bad_increment, Type}}}; - Bump -> - Apps = rebar3_hex_io:select_apps(rebar_state:project_apps(State)), - lists:foldl(fun(App, {ok, StateAcc}) -> - do_(Bump, App, Repo, StateAcc) - end, {ok, State}, Apps) - end - end. - --spec format_error(any()) -> iolist(). -format_error({no_write_key, RepoName}) -> - io_lib:format("No api key with permissions to write to the repository ~ts was found.", [RepoName]); -format_error({bad_increment, Type}) -> - io_lib:format("Increment must be major, minor or patch. ~s is not valid.", [Type]); -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -%% =================================================================== -%% Public API -%% =================================================================== - -do_(App, HexConfig, State) -> - Version = rebar_app_info:original_vsn(App), - ResolvedVersion = rebar_utils:vcs_vsn(Version, - rebar_app_info:dir(App), - rebar_state:resources(State)), - Type = get_increment(ResolvedVersion), - do_(Type, App, HexConfig, State). - -do_(Type, App, HexConfig, State) -> - Version = rebar_app_info:original_vsn(App), - ResolvedVersion = rebar_utils:vcs_vsn(Version, - rebar_app_info:dir(App), - rebar_state:resources(State)), - {ok, Ver} = verl:parse(rebar_utils:to_binary(ResolvedVersion)), - NewVersion = increment(Type, Ver), - AppSrcFile = rebar_app_info:app_file_src(App), - - case Version of - _Git when Version =:= git orelse Version =:= "git" -> - rebar_api:info("Creating new tag v~s...", [NewVersion]), - rebar_utils:sh(io_lib:format("git tag v~s", [NewVersion]), []), - - {application, _, AppDetails} = rebar3_hex_file:update_app_src(App, NewVersion), - - case rebar3_hex_publish:validate_app_details(AppDetails) of - ok -> - Name = rebar_app_info:name(App), - Deps = rebar_state:get(State, {locks, default}, []), - {TopLevel, Excluded} = rebar3_hex_publish:gather_deps(Deps), - case rebar3_hex_publish:publish(App, Name, NewVersion, TopLevel, - Excluded, AppDetails, HexConfig, State) of - {ok, _State} -> - case rebar3_hex_io:ask("Push new tag to origin?", boolean, "Y") of - true -> - rebar_api:info("Pushing new tag v~s...", [NewVersion]), - rebar_utils:sh(io_lib:format("git push origin v~s", [NewVersion]), []), - {ok, State}; - false -> - {ok, State} - end; - {error, _} = Error -> - rebar_api:info("Deleting new tag v~s...", [NewVersion]), - rebar_utils:sh(io_lib:format("git tag -d v~s", [NewVersion]), []), - Error - end; - Error -> - Error - end; - _ -> - Spec = rebar3_hex_file:update_app_src(App, NewVersion), - NewAppSrcFile = io_lib:format("~tp.\n", [Spec]), - ok = rebar_file_utils:write_file_if_contents_differ(AppSrcFile, NewAppSrcFile), - ask_commit_and_push(NewVersion), - case rebar3_hex_publish:publish(rebar_app_info:original_vsn(App, NewVersion), HexConfig, State) of - {ok, _State} -> - {ok, State}; - {error, _} = Error -> - Error - end - end. - -get_increment(Version) -> - rebar3_hex_io:say("Select semver increment or other (Current ~s):", [Version]), - rebar3_hex_io:say("1) patch", []), - rebar3_hex_io:say("2) minor", []), - rebar3_hex_io:say("3) major", []), - rebar3_hex_io:say("4) other", []), - case rebar3_hex_io:ask("[1-4] ", number) of - 4 -> - rebar3_hex_io:ask("New Version ", string); - Type -> - int_to_bump(Type) - end. - -increment(patch, #{major := Maj, minor := Min, patch := Patch}) -> - ver_format(#{major => Maj, minor => Min, patch => Patch + 1}); -increment(minor, #{major := Maj, minor := Min}) -> - ver_format(#{major => Maj, minor => Min + 1, patch => 0}); -increment(major, #{major := Maj}) -> - ver_format(#{major => Maj + 1, minor => 0, patch => 0}); -increment(Version, _) when is_list(Version) -> - rebar_utils:to_binary(Version). - -%% TODO: Support pre and build -ver_format(#{major := Maj, minor := Min, patch := Patch}) -> - MajBin = integer_to_binary(Maj), - MinBin = integer_to_binary(Min), - PatchBin = integer_to_binary(Patch), - DotBin = <<".">>, - <>. - -int_to_bump(1) -> patch; -int_to_bump(2) -> minor; -int_to_bump(3) -> major; -int_to_bump(_) -> error. - -string_to_bump("patch") -> patch; -string_to_bump("minor") -> minor; -string_to_bump("major") -> major; -string_to_bump(_) -> error. - -ask_commit_and_push(NewVersion) -> - case rebar3_hex_io:ask(io_lib:format("Create 'v~s' commit?", [NewVersion]), boolean, "Y") of - true -> - rebar_utils:sh(io_lib:format("git commit -a -m 'v~s'", [NewVersion]), []), - case rebar3_hex_io:ask("Push master to origin master?", boolean, "N") of - true -> - rebar_utils:sh("git push origin master:master", []); - false -> - ok - end; - false -> - ok - end. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_docs.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_docs.erl deleted file mode 100644 index b1103b884a..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_docs.erl +++ /dev/null @@ -1,257 +0,0 @@ --module(rebar3_hex_docs). - --export([init/1, - do/1, - publish/3, - format_error/1]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, docs). --define(DEPS, [{default, lock}]). - --define(DEFAULT_DOC_DIR, "doc"). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex docs"}, - {short_desc, "Publish documentation for the current project and version"}, - {desc, ""}, - {opts, [{revert, undefined, "revert", string, "Revert given version."}, - {dry_run, undefined, "dry-run", {boolean, false}, help(dry_run)}, - rebar3_hex:repo_opt()]}, - {profiles, [docs]}]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - Apps = rebar3_hex_io:select_apps(rebar_state:project_apps(State)), - try publish_apps(Apps, State) of - {ok, State} -> - {ok, State} - catch - throw:{error,{rebar3_hex_docs, _}} = Err -> - Err; - error:{badmatch, {error, Reason}} -> - ?PRV_ERROR(Reason) - end. - -%% @doc Publish documentation directory to repository -%% -%% This following function is exported for publishing docs via the -%% main the publish command. --spec publish(rebar_app_info:t(), rebar_state:t(), map()) -> - {ok, rebar_state:t()}. -publish(App, State, Repo) -> - handle_command(App, State, Repo). - --spec format_error(any()) -> iolist(). -format_error(bad_command) -> - "Invalid command and/or options provided"; -format_error({publish, {unauthorized, _Res}}) -> - "Error publishing : Not authorized"; -format_error({publish, {not_found, _Res}}) -> - "Error publishing : Package or Package Version not found"; -format_error({revert, {unauthorized, _Res}}) -> - "Error reverting docs : Not authorized"; -format_error({revert, {not_found, _Res}}) -> - "Error reverting docs : Package or Package Version not found"; -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -%% =================================================================== -%% Internal Functions -%% =================================================================== - -help(dry_run) -> - "Generates docs (if configured) but does not publish the docs. Useful for inspecting docs before publishing.". - -publish_apps(Apps, State) -> - lists:foldl(fun(App, {ok, StateAcc}) -> - case handle_command(App, StateAcc) of - {ok, _StateAcc} -> - {ok, StateAcc}; - Err -> - throw(Err) - end - end, {ok, State}, Apps). - -handle_command(App, State) -> - {ok, Repo} = rebar3_hex_config:repo(State), - handle_command(App, State, Repo). - -handle_command(App, State, Repo) -> - {Args, _} = rebar_state:command_parsed_args(State), - case proplists:get_value(revert, Args, undefined) of - undefined -> - do_publish(App, State, Repo); - Vsn -> - do_revert(App,State,Repo, Vsn) - end. - -do_publish(App, State, Repo) -> - maybe_gen_docs(State, Repo), - AppDir = rebar_app_info:dir(App), - DocDir = resolve_doc_dir(App), - assert_doc_dir(filename:join(AppDir, DocDir)), - Files = rebar3_hex_file:expand_paths([DocDir], AppDir), - AppDetails = rebar_app_info:app_details(App), - Name = binary_to_list(rebar_app_info:name(App)), - PkgName = rebar_utils:to_list(proplists:get_value(pkg_name, AppDetails, Name)), - OriginalVsn = rebar_app_info:original_vsn(App), - Vsn = rebar_utils:vcs_vsn(App, OriginalVsn, State), - - Tarball = PkgName ++ "-" ++ vsn_string(Vsn) ++ "-docs.tar.gz", - ok = erl_tar:create(Tarball, file_list(Files, DocDir), [compressed]), - {ok, Tar} = file:read_file(Tarball), - file:delete(Tarball), - - {ok, Config} = rebar3_hex_config:hex_config_write(Repo), - - {Args, _} = rebar_state:command_parsed_args(State), - case proplists:get_bool(dry_run, Args) of - true -> - rebar_api:info("--dry-run enabled : will not publish docs.", []), - {ok, State}; - false -> - case rebar3_hex_client:publish_docs(Config, rebar_utils:to_binary(PkgName), rebar_utils:to_binary(Vsn), Tar) of - {ok, _} -> - rebar_api:info("Published docs for ~ts ~ts", [PkgName, Vsn]), - {ok, State}; - Reason -> - ?PRV_ERROR({publish, Reason}) - end - end. - -vsn_string(<>) -> - binary_to_list(Vsn); -vsn_string(Vsn) -> - Vsn. - -do_revert(App, State, Repo, Vsn) -> - {ok, Config} = rebar3_hex_config:hex_config_write(Repo), - - AppDetails = rebar_app_info:app_details(App), - Name = binary_to_list(rebar_app_info:name(App)), - PkgName = ec_cnv:to_list(proplists:get_value(pkg_name, AppDetails, Name)), - case rebar3_hex_client:delete_docs(Config, rebar_utils:to_binary(PkgName), rebar_utils:to_binary(Vsn)) of - {modified, _Body} -> - rebar_api:info("Successfully deleted docs for ~ts ~ts", [Name, Vsn]), - {ok, State}; - Reason -> - ?PRV_ERROR({revert, Reason}) - end. - -%% @doc Returns the directory were docs are to be found -%% -%% The priority for resolution is the following: -%% 1. `doc' entry in the application's `*.app.src'. -%% 2. `dir' entry specified in `edoc_opts'. -%% 3. `"doc"' fallback default value. --spec resolve_doc_dir(rebar_app_info:t()) -> string(). -resolve_doc_dir(AppInfo) -> - AppOpts = rebar_app_info:opts(AppInfo), - EdocOpts = rebar_opts:get(AppOpts, edoc_opts, []), - AppDetails = rebar_app_info:app_details(AppInfo), - Dir = proplists:get_value(dir, EdocOpts, ?DEFAULT_DOC_DIR), - proplists:get_value(doc, AppDetails, Dir). - -%% @doc Generates docs based on configuration -%% -%% This function will generate docs according to the following configuration: -%% -%% - `{doc, Options}' as part of your global hex config, where `Options' is a map. -%% - `#{doc => Options}' as part of a specific repo configuration, where `Options' is a map -%% -%% Repo specific config will always override global hex config if the repo in question is -%% the context in which rebar3_hex is operating in. -%% -%% Supported options: -%% -%% - `provider' - This value of this option should be the name of a valid doc -%% provider, such as `edoc'. Note that only `edoc' is supported out of -%% the box with rebar3. Refer to `src/rebar_prv_edoc.erl' as an example -%% of a docs provider in `rebar3', as well as -%% https://rebar3.org/docs/tutorials/building_plugins/ for documentation on -%% creating plugins. -%% -%% Example global config within rebar.config : -%% -%% `{hex, {doc, #{provider => edoc}}}.' -%% -%% Example repo specific config: -%% ``` -%% {hex, [ -%% {repos, [ -%% #{name => <<"my_private_hex">>, -%% repo_url => <<"https://my_private_hex.foo">>, -%% doc => #{provider => edoc} -%% } -%% ] -%% } -%% ] -%% }. -%% ''' -maybe_gen_docs(State, Repo) -> - case doc_opts(State, Repo) of - {ok, #{provider := PrvName}} -> - case providers:get_provider(PrvName, rebar_state:providers(State)) of - not_found -> - rebar_api:error("No provider found for ~ts", [PrvName]); - Prv -> - gen_docs(State, Prv) - end; - _ -> - Msg = "No valid hex docs configuration found. Docs will will not be generated", - rebar_api:error(Msg, []) - end. - -doc_opts(State, Repo) -> - case Repo of - #{doc := DocOpts} when is_map(DocOpts) -> - {ok, DocOpts}; - _ -> - Opts = rebar_state:opts(State), - case proplists:get_value(doc, rebar_opts:get(Opts, hex, []), undefined) of - DocOpts when is_map(DocOpts) -> {ok, DocOpts}; - _ -> undefined - end - end. - -gen_docs(State, Prv) -> - case providers:do(Prv, State) of - {ok, State} -> - {ok, State}; - Err -> - ?PRV_ERROR({publish, Err}) - end. - --spec assert_doc_dir(string()) -> true. -assert_doc_dir(DocDir) -> - filelib:is_file(DocDir ++ "/index.html") orelse missing_doc_abort(DocDir). - -missing_doc_abort(DocDir) -> - rebar_api:abort( "Docs were not published since they " - "couldn't be found in '~s'. " - "Please build the docs and then run " - "`rebar3 hex docs` to publish them." - , [DocDir] - ). - - -file_list(Files, DocDir) -> - [{drop_path(ShortName, [DocDir]), FullName} || {ShortName, FullName} <- Files]. - -drop_path(File, Path) -> - filename:join(filename:split(File) -- Path). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_error.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_error.erl deleted file mode 100644 index 3d259bc2af..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_error.erl +++ /dev/null @@ -1,25 +0,0 @@ --module(rebar3_hex_error). - --export([format_error/1]). - -format_error({required, repo}) -> - "A repository argument is required for this command."; - -format_error({error, no_read_key}) -> - "No read key found for user. Be sure to authenticate first with:" - " rebar3 hex user auth"; - -format_error({error, no_write_key}) -> - "No write key found for user. Be sure to authenticate first with:" - " rebar3 hex user auth"; - -format_error({Cmd, unsupported_params}) -> - io_lib:format("Either some or all of the parameters supplied for the ~ts command are ", [Cmd]) - ++ " invalid or form an invalid combination of parameters."; - -format_error({Cmd, missing_required_params}) -> - io_lib:format("Required parameters for the ~ts command have not been supplied.", [Cmd]); - -format_error(Reason) -> - rebar_api:debug("Unknown error : ~ts", [Reason]), - "An unknown error was encountered. Run with DEBUG=1 for more details.". diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_file.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_file.erl deleted file mode 100644 index 25cf516f5f..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_file.erl +++ /dev/null @@ -1,34 +0,0 @@ --module(rebar3_hex_file). - --export([ expand_paths/2 - , update_app_src/2 - ]). - -expand_paths(Paths, Dir) -> - AbsDir = filename:absname(Dir), - Files = lists:flatmap(fun dir_files1/1, [filename:join(Dir, P) || P <- Paths]), - [{relative_path(F1, AbsDir), F1} || F1 <- filter_regular(Files)]. - -dir_files1(Dir) -> - lists:flatmap(fun(Y) -> dir_files(Y) end, filelib:wildcard(Dir)). - -filter_regular(Files) -> - lists:filter(fun filelib:is_regular/1, [filename:absname(F) || F <- Files]). - -dir_files(Path) -> - case filelib:is_dir(Path) of - true -> - filelib:wildcard(filename:join(Path, "**")); - false -> - [Path] - end. - -relative_path(AbsFile, AbsDir) -> - rebar_dir:make_relative_path(AbsFile, AbsDir). - -update_app_src(App, Version) -> - AppSrcFile = rebar_app_info:app_file_src(App), - AppSrc = rebar_file_utils:try_consult(AppSrcFile), - [{application, Name, Details}] = AppSrc, - NewDetails = lists:keyreplace(vsn, 1, Details, {vsn, rebar_utils:to_list(Version)}), - {application, Name, NewDetails}. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_io.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_io.erl deleted file mode 100644 index 97e5058eb4..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_io.erl +++ /dev/null @@ -1,167 +0,0 @@ --module(rebar3_hex_io). - --export([ - get_password/1, - say/1, - say/2, - ask/2, - ask/3, - select_apps/1, - str_split/2 - ]). - - - --ifdef(POST_OTP_19). -str_split(Str, Pattern) -> - string:split(Str, Pattern). --else. -str_split(Str, Pattern) -> - Bin = unicode:characters_to_binary(Str), - Bpat = unicode:characters_to_binary(Pattern), - Blist = binary:split(Bin, Bpat), - lists:map(fun(B) -> unicode:characters_to_list(B) end, Blist). --endif. --include("rebar3_hex.hrl"). - -select_apps([App]) -> - [App]; -select_apps(Apps) -> - io:format("Select application(s):", []), - lists:foldl(fun(App, Idx) -> - io:format("~p) ~s", [Idx, rebar_app_info:name(App)]), - Idx+1 - end, 1, Apps), - io:format("------------", []), - io:format("A) All", []), - case ask(io_lib:format("[1-~p] or (A)ll ", [length(Apps)]), string, "A") of - "A" -> - Apps; - Index -> - [lists:nth(list_to_integer(Index), Apps)] - end. - -get_password(Prompt) -> - ok = io:setopts([binary]), - Overwriter = fun() -> - prompt_password(Prompt), - receive - {done, _Pid, _Ref} -> - ok - end - end, - Pid = spawn_link(Overwriter), - PwLine = try - io:get_line(Prompt) - after - Ref = make_ref(), - Pid ! {done, self(), Ref}, - receive - {done, Pid, Ref} -> - ok - after - timer:seconds(5) -> - throw(?PRV_ERROR(win32_prompt_timeout)) - end - end, - [Pw | _] = binary:split(PwLine, <<"\n">>), - Pw. - -prompt_password(Prompt) -> - % This is spawned to continually overwrite the prompt the user is - % entering data on, in order to hide characters typed. - ClearLine = "\e[2K", - receive - {done, Parent, Ref} -> - Parent ! {done, self(), Ref}, - Spaces = lists:duplicate(byte_size(Prompt) + 24, $ ), - io:fwrite(standard_error, "~ts\r~ts\r", [ClearLine, Spaces]) - after - 1 -> - Spaces = lists:duplicate(24, $ ), - io:fwrite(standard_error, "~ts\r~ts~ts\r~ts", [ClearLine, Prompt, Spaces, Prompt]), - prompt_password(Prompt) - end. - -ask(Prompt, Type) -> - ask_convert(Prompt, fun get/2, Type, none). - -ask(Prompt, Type, Default) -> - ask_convert(Prompt, fun get/2, Type, Default). - -ask_convert(Prompt, TransFun, Type, Default) -> - DefaultPrompt = erlang:iolist_to_binary([Prompt, default(Default), "> "]), - NewPrompt = erlang:binary_to_list(DefaultPrompt), - Data = trim(trim(io:get_line(NewPrompt)), both, [$\n]), - case TransFun(Type, Data) of - no_data -> - maybe_continue(Prompt, TransFun, Type, Default); - no_clue -> - continue(Prompt, TransFun, Type, Default); - Ret -> - Ret - end. - -maybe_continue(Prompt, TransFun, Type, Default) -> - case Default of - none -> - continue(Prompt, TransFun, Type, Default); - Default -> - TransFun(Type, Default) - end. - -continue(Prompt, TransFun, Type, Default) -> - say("I didn't understand that. A ~p is expected.~n", [Type]), - ask_convert(Prompt, TransFun, Type, Default). - -default(none) -> - []; -default(Default) -> - [" (", io_lib:format("~p", [Default]) , ")"]. - -get(boolean, []) -> - no_data; -get(boolean, [In | _]) when In =:= $Y orelse In =:= $y -> - true; -get(boolean, [In | _]) when In =:= $N orelse In =:= $n -> - false; -get(boolean, _) -> - no_clue; -get(integer, []) -> - no_data; -get(number, String) -> - get(integer, String); -get(integer, String) -> - case (catch list_to_integer(String)) of - {'Exit', _} -> - no_clue; - Integer -> - Integer - end; -get(string, []) -> - no_data; -get(string, String) -> - case is_list(String) of - true -> - String; - false -> - no_clue - end. - --ifdef(unicode_str). -trim(Str, right, Chars) -> string:trim(Str, trailing, Chars); -trim(Str, left, Chars) -> string:trim(Str, leading, Chars); -trim(Str, both, Chars) -> string:trim(Str, both, Chars). --else. -trim(Str) -> string:strip(rebar_utils:to_list(Str)). -trim(Str, Dir, [Chars|_]) -> string:strip(rebar_utils:to_list(Str), Dir, Chars). --endif. - -say(Say) -> - io:format(lists:flatten([Say, "~n"])). - --spec say(string(), [term()] | term()) -> ok. -say(Say, Args) when is_list(Args) -> - io:format(lists:flatten([Say, "~n"]), Args); -say(Say, Args) -> - io:format(lists:flatten([Say, "~n"]), [Args]). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_key.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_key.erl deleted file mode 100644 index f713c0e0bd..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_key.erl +++ /dev/null @@ -1,191 +0,0 @@ --module(rebar3_hex_key). - --export([init/1, do/1, format_error/1]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, key). --define(DEPS, []). - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([{name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, - "rebar3 hex key [generate -k | list | revoke -k " - "| revoke --all]"}, - {short_desc, - "Remove or list API keys associated with your account"}, - {desc, ""}, - {opts, - [{all, $a, "all", boolean, "all."}, - {keyname, $k, "key-name", string, "key-name"}, - {permission, $p, "permission", list, "perms."}, - rebar3_hex:repo_opt()]}]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, term()}. -do(State) -> - case rebar3_hex_config:repo(State) of - {ok, Repo} -> - TaskArgs = rebar3_hex:task_args(State), - handle_command(TaskArgs, State, Repo); - {error, Reason} -> - ?PRV_ERROR(Reason) - end. - -handle_command({"generate", Params}, State, Repo) -> - Fun = fun (State1, Config, Params1) -> - generate(State1, Config, Params1) - end, - perform(State, Repo, write, Fun, Params); -handle_command({"fetch", []}, _State, _Repo) -> - ?PRV_ERROR({fetch, missing_required_params}); -handle_command({"fetch", [{keyname, KeyName}]}, State, Repo) -> - Fun = fun (State1, Config, [KeyName1]) -> - fetch(State1, Config, KeyName1) - end, - perform(State, Repo, read, Fun, [KeyName]); -handle_command({"list", _Params}, State, Repo) -> - Fun = fun (State1, Config, []) -> - list(State1, Config) - end, - perform(State, Repo, read, Fun, []); -handle_command({"revoke", [{keyname, KeyName}]}, State, Repo) -> - Fun = fun (State1, Config, [KeyName1]) -> - revoke(State1, Config, KeyName1) - end, - perform(State, Repo, write, Fun, [KeyName]); -handle_command({"revoke", [{all, true}]}, State, Repo) -> - Fun = fun (State1, Config, []) -> - revoke_all(State1, Config) - end, - perform(State, Repo, write, Fun, []); -handle_command({"revoke", _Params}, _State, _Repo) -> - ?PRV_ERROR({revoke, unsupported_params}); -handle_command(_, _, _) -> - ?PRV_ERROR(bad_command). - -perform(State, Repo, RepoContext, Fun, Params) -> - case rebar3_hex_config:hex_config(Repo, RepoContext) of - {ok, Config} -> - Fun(State, Config, Params); - Err -> - ?PRV_ERROR(Err) - end. - -generate(State, HexConfig, Params) -> - Perms = gather_permissions(proplists:get_all_values(permission, Params)), - KeyName = proplists:get_value(keyname, Params, undefined), - case rebar3_hex_client:key_add(HexConfig, KeyName, Perms) of - {ok, _Res} -> - rebar3_hex_io:say("Key successfully created", []), - {ok, State}; - Error -> - ?PRV_ERROR({generate, Error}) - end. - -fetch(State, HexConfig, KeyName) -> - case rebar3_hex_client:key_get(HexConfig, KeyName) of - {ok, Res} -> - ok = print_key_details(Res), - {ok, State}; - Error -> - ?PRV_ERROR({fetch, Error}) - end. - -revoke(State, HexConfig, KeyName) -> - case rebar3_hex_client:key_delete(HexConfig, KeyName) of - {ok, _Res} -> - rebar3_hex_io:say("Key successfully revoked", []), - {ok, State}; - Error -> - ?PRV_ERROR({revoke, Error}) - end. - -revoke_all(State, HexConfig) -> - case rebar3_hex_client:key_delete_all(HexConfig) of - {ok, _Res} -> - rebar3_hex_io:say("All keys successfully revoked", []), - {ok, State}; - Error -> - ?PRV_ERROR({revoke_all, Error}) - end. - -list(State, HexConfig) -> - case rebar3_hex_client:key_list(HexConfig) of - {ok, Res} -> - ok = print_results(Res), - {ok, State}; - Error -> - ?PRV_ERROR({list, Error}) - end. - -gather_permissions([]) -> - []; -gather_permissions(Perms) -> - lists:foldl(fun (Name, Acc) -> - [Domain, Resource] = binary:split(rebar_utils:to_binary(Name), <<":">>), - [#{<<"domain">> => Domain, <<"resource">> => Resource}] ++ Acc - end, - [], - Perms). - -print_results(Res) -> - Header = ["Name", "Created"], - Rows = lists:map(fun (#{<<"name">> := Name, <<"inserted_at">> := Created}) -> - [binary_to_list(Name), binary_to_list(Created)] - end, - Res), - ok = rebar3_hex_results:print_table([Header] ++ Rows), - ok. - - - -print_key_details(#{<<"name">> := Name, - <<"inserted_at">> := Created, - <<"updated_at">> := Updated, - <<"last_use">> := - #{<<"ip">> := Addr, <<"used_at">> := Used, <<"user_agent">> := _Agent}}) -> - Header = ["Name", "Created", "Updated", "LastUsed", "LastUsedBy"], - Row = [binary_to_list(Name), - binary_to_list(Created), - binary_to_list(Updated), - binary_to_list(Used), - binary_to_list(Addr)], - ok = rebar3_hex_results:print_table([Header] ++ [Row]), - ok; - -print_key_details(#{<<"name">> := Name, - <<"inserted_at">> := Created, - <<"updated_at">> := Updated}) -> - Header = ["Name", "Created", "Updated", "LastUsed", "LastUsedBy"], - Row = [binary_to_list(Name), - binary_to_list(Created), - binary_to_list(Updated), - "never", - "n/a"], - ok = rebar3_hex_results:print_table([Header] ++ [Row]), - ok. - --spec format_error(any()) -> iolist(). -format_error({list, {unauthorized, _Res}}) -> - "Error while attempting to perform list : Not authorized"; -format_error({list, {error, #{<<"message">> := Msg}}}) -> - "Error while attempting to perform list : " ++ Msg; -format_error({revoke, {not_found, _Res}}) -> - "Error while revoking key : key not found"; -format_error({generate, - {validation_errors, #{<<"errors">> := Errors, <<"message">> := Message}}}) -> - ErrorString = rebar3_hex_results:errors_to_string(Errors), - io_lib:format("~ts~n\t~ts", [Message, ErrorString]); -format_error(bad_command) -> - "Unknown command. Command must be fetch, generate, list, or " - "revoke"; -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_owner.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_owner.erl deleted file mode 100644 index f1f43a694c..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_owner.erl +++ /dev/null @@ -1,214 +0,0 @@ --module(rebar3_hex_owner). - --export([init/1, - do/1, - format_error/1]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, owner). --define(DEPS, []). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([{name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex owner"}, - {short_desc, "Add, remove, transfer or list package owners"}, - {desc, support()}, - {opts, [rebar3_hex:repo_opt(), - {level, $l, "level", {string, "full"}, "Ownership level."}, - {transfer, $t, "transfer", {boolean, false}, "Transfer Package"} - ]}]), - - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - case rebar3_hex_config:repo(State) of - {ok, Repo} -> - handle_command(State, Repo); - {error, Reason} -> - ?PRV_ERROR(Reason) - end. - -handle_command(State, Repo) -> - case command_args(State) of - {"add", Package, UsernameOrEmail, Level, Transfer} -> - case valid_level(Level) of - true -> - case rebar3_hex_config:hex_config_write(Repo) of - {ok, Config} -> - {ok, State} = add(Config, Package, UsernameOrEmail, Level, Transfer, State), - ok = rebar3_hex_io:say("Added ~ts to ~ts", [UsernameOrEmail, Package]), - {ok, State}; - Err -> - ?PRV_ERROR(Err) - end; - false -> - {error, "level must be one of full or maintainer"} - end; - {"remove", Package, UsernameOrEmail} -> - case rebar3_hex_config:hex_config_write(Repo) of - {ok, Config} -> - {ok, State} = remove(Config, Package, UsernameOrEmail, State), - ok = rebar3_hex_io:say("Removed ~ts to ~ts", [UsernameOrEmail, Package]), - {ok, State}; - Err -> - ?PRV_ERROR(Err) - end; - {"transfer", Package, UsernameOrEmail} -> - case rebar3_hex_config:hex_config_write(Repo) of - {ok, Config} -> - {ok, State} = add(Config, Package, UsernameOrEmail, <<"full">>, true, State), - ok = rebar3_hex_io:say("Transfered ~ts to ~ts", [Package, UsernameOrEmail]), - {ok, State}; - Err -> - ?PRV_ERROR(Err) - end; - {"list", Package} -> - case rebar3_hex_config:hex_config_read(Repo) of - {ok, Config} -> - list(Config, Package, State); - Err -> - ?PRV_ERROR(Err) - end; - _Command -> - ?PRV_ERROR(bad_command) - end. - -command_args(State) -> - case get_args(rebar_state:command_args(State)) of - {"list", Package} -> - {"list", rebar_utils:to_binary(Package)}; - - {"add", Package, UserOrEmail} -> - {AllArgs, _} = rebar_state:command_parsed_args(State), - Level = proplists:get_value(level, AllArgs, "full"), - Transfer = proplists:get_value(transfer, AllArgs, false), - {"add", rebar_utils:to_binary(Package), rebar_utils:to_binary(UserOrEmail), rebar_utils:to_binary(Level), Transfer}; - - {Command, Package, UserOrEmail} -> - {Command, rebar_utils:to_binary(Package), rebar_utils:to_binary(UserOrEmail)}; - - BadCommand -> - BadCommand - end. - -get_args(["list", Package]) -> - {"list", Package}; -get_args(["list", Package| _Rest]) -> - {"list", Package}; -get_args([Task, Package, Username]) when Task =:= "transfer" -> - {Task, Package, Username}; -get_args([Task, Package, UserName | _Rest]) when Task =:= "add" orelse Task =:= "remove" -> - {Task, Package, UserName}; -get_args([Task, Package, UserName, "-r", _]) -> - {Task, Package, UserName}; -get_args(BadCommand) -> - BadCommand. - -support() -> - "Adds, removes or lists package owners.~n~n" - "Package owners have full permissions to the package. They can " - "publish and revert releases and even remove other package owners.~n~n" - "Supported commmand combinations: ~n~n" - " rebar3 hex owner add ~n~n" - " rebar3 hex owner add ~n~n" - " rebar3 hex owner add ~n~n" - " rebar3 hex owner list ~n~n" - " rebar3 hex owner remove ~n~n" - " rebar3 hex owner transfer ~n~n" - "Argument descriptions: ~n ~n" - " - a valid hex username or email address for a hex user~n~n" - " - a valid hex package name~n~n" - " - one of full or maintainer~n~n" - " - boolean value indicating whether to transfer a specified package or not~n~n". - --spec format_error(any()) -> iolist(). -format_error(bad_command) -> - S = "Invalid command ~n~n", - support(), - io_lib:format(S, []); -format_error({validation_errors, Cmd, Package, User, Errors, Message}) -> - ErrorString = rebar3_hex_results:errors_to_string(Errors), - Action = verb_to_gerund(Cmd), - io_lib:format("Error ~ts ~ts as owner of package ~ts : ~ts~n\t~ts", [Action, User, Package, Message, ErrorString]); -format_error({error, Package, Reason}) -> - io_lib:format("Error listing owners of package ~ts: ~p", [Package, Reason]); -format_error({status, Status, Package}) -> - io_lib:format("Error listing owners of package ~ts: ~ts", - [Package, rebar3_hex_client:pretty_print_status(Status)]); -format_error({error, Package, UsernameOrEmail, Reason}) -> - io_lib:format("Error adding ~ts as owner of package ~ts: ~p", [UsernameOrEmail, Package, Reason]); -format_error({status, Status, Package, UsernameOrEmail}) -> - io_lib:format("Error adding ~ts as owner of package ~ts: ~ts", - [UsernameOrEmail, Package, rebar3_hex_client:pretty_print_status(Status)]); -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -valid_level(<<"full">>) -> true; -valid_level(<<"maintainer">>) -> true; -valid_level(_) -> false. - -add(HexConfig, Package, UsernameOrEmail, Level, Transfer, State) -> - case hex_api_package_owner:add(HexConfig, Package, UsernameOrEmail, Level, Transfer) of - {ok, {Code, _Headers, _Body}} when Code =:= 204 orelse Code =:= 201-> - {ok, State}; - {ok, {422, _Headers, #{<<"errors">> := Errors, <<"message">> := Message}}} -> - erlang:error(?PRV_ERROR({validation_errors, add, Package, UsernameOrEmail, Errors, Message})); - {ok, {Status, _Headers, _Body}} -> - erlang:error(?PRV_ERROR({status, Status, Package, UsernameOrEmail})); - {error, Reason} -> - erlang:error(?PRV_ERROR({error, Package, UsernameOrEmail, Reason})) - end. - -remove(HexConfig, Package, UsernameOrEmail, State) -> - case hex_api_package_owner:delete(HexConfig, Package, UsernameOrEmail) of - {ok, {204, _Headers, _Body}} -> - {ok, State}; - {ok, {Status, _Headers, _Body}} -> - ?PRV_ERROR({status, Status, Package, UsernameOrEmail}); - {error, Reason} -> - ?PRV_ERROR({error, Package, UsernameOrEmail, Reason}) - end. - -list(HexConfig, Package, State) -> - case hex_api_package_owner:list(HexConfig, Package) of - {ok, {200, _Headers, List}} -> - Owners = [owner(Owner) || Owner <- List], - OwnersString = rebar_string:join(Owners, "\n"), - rebar3_hex_io:say("~s", [OwnersString]), - {ok, State}; - {ok, {Status, _Headers, _Body}} -> - ?PRV_ERROR({status, Status, Package}); - {error, Reason} -> - ?PRV_ERROR({error, Package, Reason}) - end. - -owner(Owner) -> - Name0 = maps:get(<<"username">>, Owner, nil), - Email0 = maps:get(<<"email">>, Owner, nil), - {Name, Email} = case {Name0, Email0} of - _ when is_binary(Name0), is_binary(Email0) -> - {Name0, Email0}; - _ when is_binary(Name0) -> - {Name0, <<"unspecified">>}; - _ when is_binary(Email0) -> - {<<"unspecified">>, Email0}; - _ -> - {<<"unspecified">>, <<"unspecified">>} - end, - binary_to_list(Name) ++ " (" ++ binary_to_list(Email) ++ ")". - -verb_to_gerund(add) -> "adding"; -verb_to_gerund(remove) -> "removing"; -verb_to_gerund(list) -> "listing". diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_publish.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_publish.erl deleted file mode 100644 index 18dbf2c484..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_publish.erl +++ /dev/null @@ -1,564 +0,0 @@ -%% @doc The publish provider is responsible for creating a tarball of -%% an application and uploading to the repository. -%% @end --module(rebar3_hex_publish). - --export([ init/1 - , do/1 - , format_error/1 - ]). - --export([ publish/3 - , publish/8 - , validate_app_details/1 - , gather_deps/1 - ]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, publish). --define(DEPS, [{default, lock}]). - --define(DEFAULT_FILES, ["src", "c_src", "include", "rebar.config.script" - ,"priv", "rebar.config", "rebar.lock" - ,"CHANGELOG*", "changelog*" - ,"README*", "readme*" - ,"LICENSE*", "license*" - ,"NOTICE"]). - --define(VALIDATIONS, [ has_semver - , has_contributors - , has_maintainers - , has_description - , has_licenses - , has_unstable_deps - ]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --endif. - -%% =================================================================== -%% Public API -%% =================================================================== - - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([{name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex publish"}, - {short_desc, "Publish a new version of your package and update the package"}, - {desc, support()}, - {opts, [rebar3_hex:repo_opt(), - {yes, $y, "yes", {boolean, false}, help(yes)}, - {replace, undefined, "replace", {boolean, false}, help(replace)}, - {package, $p, "package", string, help(package)}, - {revert, undefined, "revert", string, help(revert)}, - {without_docs, undefined, "without-docs", {boolean, false}, help(without_docs)}]}]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - case rebar3_hex_config:repo(State) of - {ok, Repo} -> - OptMap = rebar3_hex:gather_opts([revert, package], State), - handle_command(OptMap, State, Repo); - {error, Reason} -> - ?PRV_ERROR(Reason) - end. - -handle_command(#{revert := Vsn, package := Pkg}, State, Repo) -> - ok = rebar3_hex_revert:revert(binarify(Pkg), binarify(Vsn), Repo, State), - {ok, State}; - -handle_command(#{revert := _Vsn}, _State, _Repo) -> - {error, "--revert requires a package name"}; - -handle_command(_Args, State, Repo) -> - case maps:get(write_key, Repo, maps:get(api_key, Repo, undefined)) of - undefined -> - ?PRV_ERROR(no_write_key); - _ -> - Apps = rebar3_hex_io:select_apps(rebar_state:project_apps(State)), - lists:foldl(fun(App, {ok, StateAcc}) -> - publish(App, Repo, StateAcc) - end, {ok, State}, Apps) - end. - --spec format_error(any()) -> iolist(). -format_error(ErrList) when is_list(ErrList) -> - F = fun(Err, Acc) -> - ErrStr = format_error(Err), - Acc ++ " " ++ ErrStr ++ "\n" - end, - More = "\n Please see https://hex.pm/docs/rebar3_publish for more info.\n", - lists:foldl(F, "Validator Errors:\n", ErrList) ++ More; -format_error(bad_command) -> - "bad command"; -format_error({required, repo}) -> - "publish requires a repo name argument to identify the repo to publish to"; -format_error({not_valid_repo, RepoName}) -> - io_lib:format("No configuration for repository ~ts found.", [RepoName]); -format_error({invalid_semver, AppName, Version}) -> - Err = "~ts.app.src : non-semantic version number \"~ts\" found", - io_lib:format(Err, [AppName, Version]); -format_error({no_description, AppName}) -> - Err = "~ts.app.src : missing or empty description property", - io_lib:format(Err, [AppName]); -format_error({no_license, AppName}) -> - Err = "~ts.app.src : missing or empty licenses property", - io_lib:format(Err, [AppName]); -format_error({has_maintainers, AppName}) -> - Err = "~ts.app.src : deprecated field maintainers found", - io_lib:format(Err, [AppName]); -format_error({has_contributors, AppName}) -> - Err = "~ts.app.src : deprecated field contributors found", - io_lib:format(Err, [AppName]); -format_error({has_unstable_deps, Deps}) -> - MainMsg = "The following pre-release dependencies were found : ", - DepList = [io_lib:format("~s - ~s ", [Pkg, Ver]) || {Pkg, Ver} <- Deps], - Msg = ["In the future packages with pre-release dependencies will be considered unstable ", - "and will be prevented from being published. ", - "We recommend you upgrade your these dependencies as soon as possible"], - io_lib:format("~s~n~n~s~n~n~s~n", [MainMsg, DepList, Msg]); -format_error(no_write_key) -> - "No write key found for user. Be sure to authenticate first with:" - ++ " rebar3 hex user auth"; - -format_error({publish, {error, {tarball, _} = Err}}) -> - hex_tarball:format_error(Err); -format_error({publish, {error, #{<<"errors">> := Errors, <<"message">> := Message}}}) -> - ErrorString = errors_to_string(Errors), - io_lib:format("Failed to publish package: ~ts~n\t~ts", [Message, ErrorString]); -format_error({publish, {error, #{<<"message">> := Message}}}) -> - io_lib:format("Failed to publish package: ~ts", [Message]); -format_error({non_hex_deps, Excluded}) -> - Err = "Can not publish package because the following deps are not available" - ++ " in hex: ~s", - io_lib:format(Err, [string:join(Excluded, ", ")]); -format_error(undefined_server_error) -> - "Unknown server error"; -format_error({status, Status}) -> - rebar3_hex_client:pretty_print_status(Status); -format_error({status, Status, undefined_server_error}) -> - "Unknown server error: " ++ rebar3_hex_client:pretty_print_status(Status); -format_error({status, Status, Error}) -> - Message = maps:get(<<"message">>, Error, ""), - Errors = maps:get(<<"errors">>, Error, ""), - ErrorString = errors_to_string(Errors), - Data = [rebar3_hex_client:pretty_print_status(Status), Message, ErrorString], - io_lib:format("Status Code: ~s~nHex Error: ~s~n\t~s", Data); -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -%% =================================================================== -%% Public API -%% =================================================================== - -publish(App, HexConfig, State) -> - Name = rebar_app_info:name(App), - - Version = rebar_app_info:original_vsn(App), - ResolvedVersion = rebar_utils:vcs_vsn(App, Version, State), - {application, _, AppDetails} = rebar3_hex_file:update_app_src(App, ResolvedVersion), - - - Deps = rebar_state:get(State, {locks, default}, []), - {TopLevel, Excluded} = gather_deps(Deps), - - case is_valid_app({App, Name, ResolvedVersion, AppDetails, Deps}) of - ok -> - publish(App, Name, ResolvedVersion, TopLevel, - Excluded, AppDetails, HexConfig, State); - {error, Errors} -> - ?PRV_ERROR(Errors) - end. - -publish(App, Name, Version, Deps, [], AppDetails, HexConfig, State) -> - AppDir = rebar_app_info:dir(App), - Config = rebar_config:consult(AppDir), - ConfigDeps = proplists:get_value(deps, Config, []), - Deps1 = update_versions(ConfigDeps, Deps), - - Description = proplists:get_value(description, AppDetails, ""), - - PackageFiles = include_files(Name, AppDir, AppDetails), - - Licenses = proplists:get_value(licenses, AppDetails, []), - Links = proplists:get_value(links, AppDetails, []), - BuildTools = proplists:get_value(build_tools, AppDetails, [<<"rebar3">>]), - - %% We check the app file for the 'pkg' key which allows us to select - %% a package name other then the app name, if it is not set we default - %% back to the app name. - PkgName = rebar_utils:to_binary(proplists:get_value(pkg_name, AppDetails, Name)), - - Optional = [{<<"app">>, Name}, - {<<"parameters">>, []}, - {<<"description">>, rebar_utils:to_binary(Description)}, - {<<"files">>, [binarify(File) || {File, _} <- PackageFiles]}, - {<<"licenses">>, binarify(Licenses)}, - {<<"links">>, to_map(binarify(Links))}, - {<<"build_tools">>, binarify(BuildTools)}], - OptionalFiltered = [{Key, Value} || {Key, Value} <- Optional, Value =/= []], - Metadata = maps:from_list([{<<"name">>, PkgName}, {<<"version">>, binarify(Version)}, - {<<"requirements">>, maps:from_list(Deps1)} | OptionalFiltered]), - - rebar3_hex_io:say("Publishing ~ts ~ts to ~ts", [PkgName, Version, maps:get(name, HexConfig)]), - rebar3_hex_io:say(" Description: ~ts", [Description]), - rebar3_hex_io:say(" Dependencies:~n ~ts", [format_deps(Deps1)]), - rebar3_hex_io:say(" Included files:~n ~ts", [string:join([F || {F, _} <- PackageFiles], "\n ")]), - rebar3_hex_io:say(" Licenses: ~ts", [format_licenses(Licenses)]), - rebar3_hex_io:say(" Links:~n ~ts", [format_links(Links)]), - rebar3_hex_io:say(" Build tools: ~ts", [format_build_tools(BuildTools)]), - maybe_say_coc(HexConfig), - {Args, _} = rebar_state:command_parsed_args(State), - case proplists:get_bool(yes, Args) of - true -> - publish_package_and_docs(Name, Version, Metadata, PackageFiles, HexConfig, App, State); - false -> - case rebar3_hex_io:ask("Proceed?", boolean, "Y") of - true -> - publish_package_and_docs(Name, Version, Metadata, PackageFiles, HexConfig, App, State); - _ -> - rebar3_hex_io:say("Goodbye..."), - {ok, State} - end - end; - -publish(_AppDir, _Name, _Version, _Deps, Excluded, _AppDetails, _, _) -> - ?PRV_ERROR({non_hex_deps, Excluded}). - -hex_opts(Opts) -> - lists:filter(fun({K, _}) -> is_hex_opt(K) end, Opts). - -is_hex_opt(replace) -> true; -is_hex_opt(_) -> false. - -gather_deps(Deps) -> - Top = locks_to_deps(Deps), - Excluded = [binary_to_list(N) || {N,{T,_,_,_},0} <- Deps, T =/= pkg], - Excluded1 = [binary_to_list(N) || {N,{T,_,_},0} <- Deps, T =/= pkg], - {Top, Excluded++Excluded1}. - -locks_to_deps(Deps) -> - lists:foldl(fun(D,Acc) -> lock_to_dep(D, Acc) end, [], Deps). - -lock_to_dep({A,{pkg,N,V,_, _},0}, Acc) -> - [{N, [{<<"app">>, A}, {<<"optional">>, false}, {<<"requirement">>, V}]} | Acc]; -lock_to_dep({A, {pkg,N,V,_},0}, Acc) -> - [{N, [{<<"app">>, A}, {<<"optional">>, false}, {<<"requirement">>, V}]} | Acc]; -lock_to_dep(_, Acc) -> - Acc. - -publish_package_and_docs(Name, Version, Metadata, PackageFiles, HexConfig, App, State) -> - {Args, _} = rebar_state:command_parsed_args(State), - HexOpts = hex_opts(Args), - case rebar3_hex_config:hex_config_write(HexConfig) of - {ok, HexConfig1} -> - case create_and_publish(HexOpts, Metadata, PackageFiles, HexConfig1) of - ok -> - rebar_api:info("Published ~s ~s", [Name, Version]), - case proplists:get_bool(without_docs, Args) of - true -> - rebar_api:info("--without-docs is enabled : will not publish docs", []), - {ok, State}; - false -> - rebar3_hex_docs:publish(App, State, HexConfig1), - {ok, State} - end; - Error={error, _} -> - Error - end; - Error={error, _} -> - Error - end. - -%% Internal functions - -%% if publishing to the public repo or to a private organization link to the code of conduct -maybe_say_coc(#{parent := <<"hexpm">>}) -> - rebar3_hex_io:say("Before publishing, please read Hex CoC: https://hex.pm/policies/codeofconduct", []); -maybe_say_coc(#{name := <<"hexpm">>}) -> - rebar3_hex_io:say("Be aware, you are publishing to the public Hexpm repository.", []), - rebar3_hex_io:say("Before publishing, please read Hex CoC: https://hex.pm/policies/codeofconduct", []); -maybe_say_coc(_) -> - ok. - -create_and_publish(Opts, Metadata, PackageFiles, HexConfig) -> - case hex_tarball:create(Metadata, PackageFiles) of - {ok, #{tarball := Tarball, inner_checksum := _Checksum}} -> - case rebar3_hex_client:publish(HexConfig, Tarball, Opts) of - {ok, _Res} -> - ok; - Error -> - ?PRV_ERROR({publish, Error}) - end; - Error -> - ?PRV_ERROR({publish, Error}) - end. - -known_exclude_file(Path, ExcludeRe) -> - KnownExcludes = [ - "~$", %% emacs temp files - "\\.o$", %% c object files - "\\.so$", %% compiled nif libraries - "\\.swp$" %% vim swap files - ], - lists:foldl(fun(_, true) -> true; - (RE, false) -> - re:run(Path, RE) =/= nomatch - end, false, KnownExcludes ++ ExcludeRe). - -exclude_file(Path, ExcludeFiles, ExcludeRe) -> - lists:keymember(Path, 2, ExcludeFiles) orelse - known_exclude_file(Path, ExcludeRe). - -%% allows us to support lists of tuples or maps for metadata the user writes in .app.src -to_map(Map) when is_map(Map) -> - Map; -to_map(List) when is_list(List) -> - maps:from_list(List). - -include_files(Name, AppDir, AppDetails) -> - AppSrc = {application, to_atom(Name), AppDetails}, - FilePaths = proplists:get_value(files, AppDetails, ?DEFAULT_FILES), - IncludeFilePaths = proplists:get_value(include_files, AppDetails, []), - ExcludeFilePaths = proplists:get_value(exclude_files, AppDetails, []), - ExcludeRes = proplists:get_value(exclude_regexps, AppDetails, []), - - AllFiles = lists:ukeysort(2, rebar3_hex_file:expand_paths(FilePaths, AppDir)), - IncludeFiles = lists:ukeysort(2, rebar3_hex_file:expand_paths(IncludeFilePaths, AppDir)), - ExcludeFiles = lists:ukeysort(2, rebar3_hex_file:expand_paths(ExcludeFilePaths, AppDir)), - - %% We filter first and then include, that way glob excludes can be - %% overwritten be explict includes - FilterExcluded = lists:filter(fun ({_, Path}) -> - not exclude_file(Path, ExcludeFiles, ExcludeRes) - end, AllFiles), - WithIncludes = lists:ukeymerge(2, FilterExcluded, IncludeFiles), - - AppFileSrc = filename:join("src", to_list(Name)++".app.src"), - AppSrcBinary = rebar_utils:to_binary(lists:flatten(io_lib:format("~tp.\n", [AppSrc]))), - lists:keystore(AppFileSrc, 1, WithIncludes, {AppFileSrc, AppSrcBinary}). - - -is_valid_app({_App, _Name, _Version, _AppDetails, _Deps} = A) -> - F = fun(K, Acc) -> - case validate_app(K, A) of - ok -> - Acc; - {error, Error} -> - Acc ++ [Error] - end - end, - case lists:foldl(F, [], ?VALIDATIONS) of - [] -> - ok; - Errors -> - {error, Errors} - end. - -validate_app(has_unstable_deps, {_, _, _, _, Deps}) -> - case lists:foldl(fun(Dep, Acc) -> is_unstable_dep(Dep, Acc) end, [], Deps) of - [] -> - ok; - PreDeps -> - rebar_log:log(warn, format_error({has_unstable_deps, PreDeps}), []), - ok - end; -validate_app(has_semver, {_, Name, Ver, _, _}) -> - case verl:parse(rebar_utils:to_binary(Ver)) of - {error, invalid_version} -> - {error, {invalid_semver, Name, Ver}}; - _ -> - ok - end; -validate_app(has_contributors, {_, Name, _, AppDetails, _}) -> - case proplists:is_defined(contributors, AppDetails) of - true -> - rebar_log:log(warn, format_error({has_contributors, Name}), []), - ok; - false -> - ok - end; -validate_app(has_maintainers, {_, Name, _, AppDetails, _}) -> - case proplists:is_defined(maintainers, AppDetails) of - true -> - rebar_log:log(warn, format_error({has_maintainers, Name}), []), - ok; - false -> - ok - end; -validate_app(has_description, {_, Name, _, AppDetails, _}) -> - case is_empty_prop(description, AppDetails) of - true -> - {error, {no_description, Name}}; - false -> - ok - end; -validate_app(has_licenses, {_, Name, _, AppDetails, _}) -> - case is_empty_prop(licenses, AppDetails) of - true -> - {error, {no_license, Name}}; - _ -> - ok - end. - -is_empty_prop(K, PropList) -> - Prop = proplists:get_value(K, PropList), - case Prop of - Empty when Empty =:= [] orelse Empty =:= undefined -> - true; - _ -> - false - end. - -is_unstable_dep({_, {pkg, Pkg, Ver, _, _}, _}, Acc) -> - case verl:parse(Ver) of - {ok, #{pre := Pre}} when Pre =/= [] -> - [{Pkg, Ver}|Acc]; - _ -> - Acc - end; - -%% TODO: Resolve in an issue whether git deps should be classified as unstable. -%% For now and in the interest of keeping things working, we do not classify as unstable. -is_unstable_dep(_, Acc) -> - Acc. - -%% TODO: Modify hex cut so we can deprecate this? -validate_app_details(AppDetails) -> - case proplists:is_defined(contributors, AppDetails) of - true -> - {error, {rebar3_hex_publish, has_contributors}}; - false -> - ok - end. - -format_deps(Deps) -> - string:join([binary_to_list(<>) || {N, #{<<"requirement">> := V}} <- Deps], "\n "). - -format_licenses(Licenses) -> - string:join(Licenses, ", "). - -format_links(Links) -> - string:join([lists:flatten([Name, ": ", Url]) || {Name, Url} <- Links], "\n "). - -format_build_tools(BuildTools) -> - string:join([io_lib:format("~s", [Tool]) || Tool <- BuildTools], ", "). - -update_versions(ConfigDeps, Deps) -> - [begin - case lists:keyfind(binary_to_atom(N, utf8), 1, ConfigDeps) of - {_, V} when is_binary(V) -> - {N, maps:from_list(lists:keyreplace(<<"requirement">>, 1, M, {<<"requirement">>, V}))}; - {_, V} when is_list(V) -> - {N, maps:from_list(lists:keyreplace(<<"requirement">>, 1, M, {<<"requirement">>, list_to_binary(V)}))}; - _ -> - %% using version from lock. prepend ~> to make it looser - {_, Version} = lists:keyfind(<<"requirement">>, 1, M), - {N, maps:from_list(lists:keyreplace(<<"requirement">>, 1, M, {<<"requirement">>, <<"~>", Version/binary>>}))} - end - end || {N, M} <- Deps]. - - -errors_to_string(Value) when is_binary(Value) -> - Value; -errors_to_string(Map) when is_map(Map) -> - errors_to_string(maps:to_list(Map)); -errors_to_string({<<"inserted_at">>, E}) -> - lists:flatten(io_lib:format("Inserted At: ~s~n", [E])); -errors_to_string({<<"requirements">>, Rs}) -> - lists:flatten(["Requirements could not be computed\n", - [io_lib:format("~s\n~20.20c\n~s\n",[P,$-, R]) || {P, R} <- maps:to_list(Rs)]]); -errors_to_string({Key, Value}) -> - io_lib:format("~s: ~s", [Key, errors_to_string(Value)]); -errors_to_string(Errors) when is_list(Errors) -> - lists:flatten([io_lib:format("~s", [errors_to_string(Values)]) || Values <- Errors]). - - -binarify(Term) when is_boolean(Term) -> - Term; -binarify(Term) when is_atom(Term) -> - atom_to_binary(Term, utf8); -binarify([]) -> - []; -binarify(Map) when is_map(Map) -> - maps:from_list(binarify(maps:to_list(Map))); -binarify(Term) when is_list(Term) -> - case io_lib:printable_unicode_list(Term) of - true -> - rebar_utils:to_binary(Term); - false -> - [binarify(X) || X <- Term] - end; -binarify({Key, Value}) -> - {binarify(Key), binarify(Value)}; -binarify(Term) -> - Term. - -%% via ec_cnv --spec to_atom(atom() | list() | binary() | integer() | float()) -> - atom(). -to_atom(X) - when erlang:is_atom(X) -> - X; -to_atom(X) - when erlang:is_list(X) -> - erlang:list_to_existing_atom(X); -to_atom(X) -> - to_atom(to_list(X)). - - --spec to_list(atom() | list() | binary() | integer() | float()) -> - list(). -to_list(X) - when erlang:is_float(X) -> - erlang:float_to_list(X); -to_list(X) - when erlang:is_integer(X) -> - erlang:integer_to_list(X); -to_list(X) - when erlang:is_binary(X) -> - erlang:binary_to_list(X); -to_list(X) - when erlang:is_atom(X) -> - erlang:atom_to_list(X); -to_list(X) - when erlang:is_list(X) -> - X. - -help(package) -> - "Specifies the package to use with the publish command, currently only utilized in a revert operation"; -help(revert) -> - "Revert given version, if the last version is reverted the package is removed"; -help(replace) -> - "Allows overwriting an existing package version if it exists. Private " - "packages can always be overwritten, publicpackages can only be " - "overwritten within one hour after they were initially published."; -help(yes) -> - "Publishes the package without any confirmation prompts"; -help(without_docs) -> - "Publishing a package without publishing documentation that may be automatically generated". - -support() -> - "Publishes a new version of a package with options to revert and replace existing packages~n~n" - "Supported commmand combinations:~n~n" - " rebar3 hex publish~n~n" - " rebar3 hex publish --yes~n~n" - " rebar3 hex publish --repo ~n~n" - " rebar3 hex publish --repo --yes~n~n" - " rebar3 hex publish --revert --package ~n~n" - " rebar3 hex publish --revert --package --yes~n~n" - " rebar3 hex publish --replace~n~n" - " rebar3 hex publish --replace --yes~n~n" - "Argument descriptions:~n~n" - " - a valid repository, only required when multiple repositories are configured~n~n" - " - a valid version string, currently only utilized with --revert switch~n~n" - " - a valid package name, currently only utilized with --revert switch~n~n". diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_repo.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_repo.erl deleted file mode 100644 index e9f3322d56..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_repo.erl +++ /dev/null @@ -1,133 +0,0 @@ --module(rebar3_hex_repo). - --export([init/1, - do/1, - format_error/1]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, repo). --define(DEPS, []). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex repo auth myrepo --key 1234"}, - {short_desc, "Add, remove or list configured repositories and their auth keys"}, - {desc, ""}, - {opts, [{subcmd, undefined, undefined, string, "Repo task to run"}, - {repo, undefined, undefined, string, "Name of a repository"}, - {key, $k, "key", string, "Authentication key for repository"}]} - ]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - {Args, _} = rebar_state:command_parsed_args(State), - case proplists:get_value(subcmd, Args, undefined) of - "generate" -> - case proplists:get_value(repo, Args, undefined) of - undefined -> - ?PRV_ERROR(no_repo); - Repo -> - generate(list_to_binary(Repo), State) - end; - "auth" -> - case proplists:get_value(repo, Args, undefined) of - undefined -> - ?PRV_ERROR(no_repo); - Repo -> - case proplists:get_value(key, Args, undefined) of - undefined -> - ?PRV_ERROR(auth_no_key); - Key -> - auth(list_to_binary(Repo), list_to_binary(Key), State), - {ok, State} - end - end; - "list" -> - list_repos(State); - Command -> - ?PRV_ERROR({bad_command, Command}) - end. - --spec format_error(any()) -> iolist(). -format_error(no_repo) -> - "Authenticate and generate commands require repository name as argument"; -format_error(auth_no_key) -> - "Repo authenticate command requires key"; -format_error({bad_command, Command}) -> - io_lib:format("Unknown repo command ~ts", [Command]); -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -auth(Repo, Key, State) -> - Config = rebar_hex_repos:auth_config(State), - RepoConfig = maps:get(Repo, Config, #{}), - RepoConfig1 = RepoConfig#{auth_key => Key}, - rebar_hex_repos:update_auth_config(#{Repo => RepoConfig1}, State). - -generate(RepoName, State) -> - {ok, RepoConfig} = rebar_hex_repos:get_repo_config(RepoName, State), - - RepoName1 = case binary:split(RepoName, <<":">>) of - [_Parent, Org] -> - Org; - Public -> - Public - end, - - Permissions = [#{<<"domain">> => <<"repository">>, - <<"resource">> => RepoName}], - Name = <>, - - {ok, HexConfig} = rebar3_hex_config:hex_config_write(RepoConfig), - case hex_api_key:add(HexConfig, Name, Permissions) of - {ok, {201, _Headers, #{<<"secret">> := Secret}}} -> - rebar3_hex_io:say("Generated key: ~ts", [Secret]), - {ok, State}; - {ok, {Status, _Headers, #{<<"message">> := Message}}} -> - ?PRV_ERROR({error, Status, Message}); - {error, Reason} -> - ?PRV_ERROR({error, Reason}) - end. - -list_repos(State) -> - Resources = rebar_state:resources(State), - #{repos := Repos} = rebar_resource_v2:find_resource_state(pkg, Resources), - Headers = ["Name", "URL", "Public Key", "Auth Key"], - Rows = lists:map(fun(Repo) -> - #{name := Name, - api_organization := Org, - repo_url := Url, - read_key := ReadKey, - repo_public_key := PubKey} = Repo, - - AuthKey = maps:get(auth_key, Repo, ReadKey), - [binary_to_list(Name), - maybe_org_url(Org, Url), - printable_public_key(PubKey), - binary_to_list(AuthKey)] - end, Repos), - rebar3_hex_results:print_table([Headers] ++ Rows), - {ok, State}. - -printable_public_key(PubKey) -> - [Pem] = public_key:pem_decode(PubKey), - Public = public_key:pem_entry_decode(Pem), - Hash = crypto:hash(sha256, public_key:ssh_encode(Public, ssh2_pubkey)), - Encoded = string:substr(base64:encode_to_string(Hash), 1, 43), - "SHA256:" ++ Encoded. - -maybe_org_url(undefined, Url) -> binary_to_list(Url); -maybe_org_url(Org, Url) -> binary_to_list(Url) ++ "/repos/" ++ binary_to_list(Org). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_results.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_results.erl deleted file mode 100644 index e084716d6e..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_results.erl +++ /dev/null @@ -1,66 +0,0 @@ --module(rebar3_hex_results). - --export([errors_to_string/1, print_table/1]). - --include("rebar3_hex.hrl"). - -errors_to_string(Value) when is_binary(Value) -> - Value; -errors_to_string(Map) when is_map(Map) -> - errors_to_string(maps:to_list(Map)); -errors_to_string({<<"inserted_at">>, E}) -> - lists:flatten(io_lib:format("Inserted At: ~s~n", [E])); -errors_to_string({<<"requirements">>, Rs}) -> - lists:flatten(["Requirements could not be computed\n", - [io_lib:format("~s\n~20.20c\n~s\n",[P,$-, R]) || {P, R} <- maps:to_list(Rs)]]); -errors_to_string({Key, Value}) -> - io_lib:format("~s: ~s", [Key, errors_to_string(Value)]); -errors_to_string(Errors) when is_list(Errors) -> - lists:flatten([io_lib:format("~s", [errors_to_string(Values)]) || Values <- Errors]). - -print_table(Rows) -> - Table = table(Rows), - io:fwrite(Table), - ok. - -underline_emphasis(Item) -> - io_lib:format("\e[1m\e[00m\e[4m~ts\e[24m", [Item]). - -% Returns a str, expects first row to be a header -table(Rows) -> - [Header | Body] = align_rows(Rows), - Table = [pretty_header(Header), ""] ++ Body, - lists:foldl(fun(Row, Acc) -> - Acc ++ [io_lib:fwrite("~s~n", [lists:flatten(Row)])] - end, - [], - Table). - -pretty_header(Header) -> - lists:map(fun(W) -> - [Value, Space] = rebar3_hex_io:str_split(W, " "), - underline_emphasis(Value) ++ " " ++ Space end, - Header). - -align_rows(Rows) -> - WidestCells = widest_cells(Rows), - [align_cells(R, WidestCells) || R <- Rows]. - -align_cells(Row, WidestCells) -> - Padded = rpad_row(Row, length(WidestCells), ""), - [ string:left(Cell, Length + 2, $\s) - || {Cell, Length} <- lists:zip(Padded, WidestCells)]. - -widest_cells(Rows) -> - lists:foldl( fun(Row, Acc) -> - CellLengths = [length(C) || C <- Row ], - Widest = lists:max([length(Acc), length(CellLengths)]), - Padded = rpad_row(CellLengths, Widest, 0), - WidestPadded = rpad_row(Acc, Widest, 0), - [ lists:max([A, B]) || {A, B} <- lists:zip(Padded, WidestPadded)] - end, - [], - Rows). - -rpad_row(L, Length, Elem) -> - L ++ lists:duplicate(Length - length(L), Elem). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_retire.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_retire.erl deleted file mode 100644 index 154bee668e..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_retire.erl +++ /dev/null @@ -1,109 +0,0 @@ -%% @doc This provider allows the user to delete a package within one -%% hour of its publication. -%% @end --module(rebar3_hex_retire). - --export([init/1, - do/1, - format_error/1]). - --export([retire/6]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, retire). --define(DEPS, []). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([{name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex retire some_pkg 0.3.0"}, - {short_desc, "Mark a package as deprecated."}, - {desc, ""}, - {opts, [{pkg, undefined, undefined, string, "Name of the package to retire."}, - {vsn, undefined, undefined, string, "Version of the package to retire."}, - {reason, undefined, undefined, string, "Reason to retire package."}, - {message, undefined, undefined, string, "Clarifying message for retirement"}, - rebar3_hex:repo_opt()]}]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - case rebar3_hex_config:repo(State) of - {ok, Repo} -> - handle_command(State, Repo); - {error, Reason} -> - ?PRV_ERROR(Reason) - end. - -handle_command(State, Repo) -> - {Args, _} = rebar_state:command_parsed_args(State), - Name = rebar3_hex:get_required(pkg, Args), - PkgName = rebar_utils:to_binary(Name), - Version = rebar3_hex:get_required(vsn, Args), - Reason = rebar3_hex:get_required(reason, Args), - Message = rebar3_hex:get_required(message, Args), - retire(PkgName, rebar_utils:to_binary(Version), Repo, - rebar_utils:to_binary(Reason), - rebar_utils:to_binary(Message), - State). - -errors_to_string(Value) when is_binary(Value) -> - Value; -errors_to_string(Map) when is_map(Map) -> - errors_to_string(maps:to_list(Map)); -errors_to_string({<<"reason">> = Key, <<"is invalid">> = Value}) -> - ValidVals = "must be one of other, invalid, security, deprecated or renamed", - io_lib:format("~s: ~s - ~s", [Key, errors_to_string(Value), ValidVals]); -errors_to_string({Key, Value}) -> - io_lib:format("~s: ~s", [Key, errors_to_string(Value)]); -errors_to_string(Errors) when is_list(Errors) -> - lists:flatten([io_lib:format("~s", [errors_to_string(Values)]) || Values <- Errors]). - -format_error({validation_errors, Errors, Message}) -> - ErrorString = errors_to_string(Errors), - io_lib:format("Failed to retire package: ~ts~n\t~ts", [Message, ErrorString]); -format_error({api_error, PkgName, Version, Reason}) -> - io_lib:format("Unable to delete package ~ts ~ts: ~ts", [PkgName, Version, Reason]); -format_error({required, pkg}) -> - "retire requires a package name argument to identify the package to delete"; -format_error({required, vsn}) -> - "retire requires a version number argument to identify the package to delete"; -format_error({required, reason}) -> - "retire requires a reason with value of either other, invalid, security, deprecated or renamed"; -format_error({required, message}) -> - "retire requires a message to clarify the reason for the retirement of the package"; -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -retire(PkgName, Version, Repo, RetireReason, RetireMessage, State) -> - case rebar3_hex_config:hex_config_write(Repo) of - {error, no_write_key} -> - ?PRV_ERROR({no_write_key, maps:get(name, Repo)}); - - {ok, HexConfig} -> - - Msg = #{<<"reason">> => RetireReason, - <<"message">> => RetireMessage}, - - case hex_api_release:retire(HexConfig, PkgName, Version, Msg) of - {ok, {204, _Headers, _Body}} -> - rebar_api:info("Successfully retired package ~ts ~ts", [PkgName, Version]), - {ok, State}; - {ok, {422, _Headers, #{<<"errors">> := Errors, <<"message">> := Message}}} -> - ?PRV_ERROR({validation_errors, Errors, Message}); - {ok, {Code, _Headers, _Body}} -> - ?PRV_ERROR({api_error, PkgName, Version, rebar3_hex_client:pretty_print_status(Code)}); - {error, Reason} -> - ?PRV_ERROR({api_error, PkgName, Version, io_lib:format("~p", [Reason])}) - end - end. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_revert.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_revert.erl deleted file mode 100644 index 6f7bb03f75..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_revert.erl +++ /dev/null @@ -1,106 +0,0 @@ -%% @doc This provider allows the user to delete a package within one -%% hour of its publication. -%% @end --module(rebar3_hex_revert). - --export([init/1, - do/1, - format_error/1]). - --export([revert/4]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, revert). --define(DEPS, []). - --hank([{unnecessary_function_arguments, - [{revert, 4, 4}]}]). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([{name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex revert some_pkg 0.3.0"}, - {short_desc, "Delete a package from the repository"}, - {desc, ""}, - {opts, [{pkg, undefined, undefined, string, "Name of the package to delete."}, - {vsn, undefined, undefined, string, "Version of the package to delete."}, - rebar3_hex:repo_opt()]}]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - case rebar3_hex_config:repo(State) of - {ok, Repo} -> - handle_command(State, Repo); - {error, Reason} -> - ?PRV_ERROR(Reason) - end. - -handle_command(State, Repo) -> - {Args, _} = rebar_state:command_parsed_args(State), - case proplists:get_value(pkg, Args, undefined) of - undefined -> - ?PRV_ERROR(package_name_required); - Name -> - PkgName = rebar_utils:to_binary(Name), - case proplists:get_value(vsn, Args, undefined) of - undefined -> - ?PRV_ERROR(version_required); - Version -> - case verl:parse(rebar_utils:to_binary(Version)) of - {ok, _} -> - case revert(PkgName, rebar_utils:to_binary(Version), Repo, State) of - ok -> - {ok, State}; - Error -> - Error - end; - _ -> - Msg = "The version argument provided \"~s\" is not a valid semantic version.", - rebar_api:abort(Msg, [Version]) - end - end - end. - -format_error({api_error, PkgName, Version, Reason}) -> - io_lib:format("Unable to delete package ~ts ~ts: ~ts", [PkgName, Version, Reason]); -format_error(package_name_required) -> - "revert requires a package name argument to identify the package to delete"; -format_error(version_required) -> - "revert requires a version number argument to identify the package to delete"; -format_error(Arg) -> - rebar3_hex_error:format_error(Arg). - -%% - -revert(PkgName, Version, Repo, _State) -> - case rebar3_hex_config:hex_config_write(Repo) of - {error, no_write_key} -> - ?PRV_ERROR({no_write_key, maps:get(name, Repo)}); - {ok, HexConfig} -> - case hex_api_release:delete(HexConfig, PkgName, Version) of - {ok, {Code, _Headers, _Body}} when Code =:= 200 ; - Code =:= 204 -> - rebar_api:info("Successfully deleted package ~ts ~ts", [PkgName, Version]), - case rebar3_hex_io:ask(io_lib:format("Also delete tag v~s?", [Version]), boolean, "N") of - true -> - rebar_utils:sh(io_lib:format("git tag -d v~s", [Version]), []); - _ -> - ok - end; - {ok, {Code, _Headers, _Body}} -> - ?PRV_ERROR({api_error, PkgName, Version, rebar3_hex_client:pretty_print_status(Code)}); - {error, Reason} -> - ?PRV_ERROR({api_error, PkgName, Version, io_lib:format("~p", [Reason])}) - end - end. diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_search.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_search.erl deleted file mode 100644 index 68569bfbb7..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_search.erl +++ /dev/null @@ -1,126 +0,0 @@ --module(rebar3_hex_search). - --export([init/1, - do/1, - format_error/1]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, search). --define(DEPS, []). - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex search "}, - {short_desc, "Display packages matching the given search query"}, - {desc, ""}, - {opts, [{term, undefined, undefined, string, "Search term."}, - rebar3_hex:repo_opt()]} - ]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - {Args, _} = rebar_state:command_parsed_args(State), - Term = proplists:get_value(term, Args, ""), - {ok, Parents} = rebar3_hex_config:parent_repos(State), - lists:foreach(fun(Repo) -> search(State, Repo, Term) end, Parents), - {ok, State}. - -search(State, Repo, Term) -> - {ok, HexConfig} = rebar3_hex_config:hex_config_read(Repo), - case hex_api_package:search(HexConfig, rebar_utils:to_binary(Term), []) of - {ok, {200, _Headers, []}} -> - io:format("No Results~n"), - {ok, State}; - {ok, {200, _Headers, Packages}} -> - Header = ["Name", "Version", "Description", "URL"], - Rows = lists:map(fun(Package) -> - #{<<"name">> := Name, - <<"meta">> := #{<<"description">> := Description}, - <<"releases">> := Releases, - <<"html_url">> := Url - } = Package, - - Descrip = truncate_description(Description), - [binary_to_list(Name), - latest_stable(Releases), Descrip, unicode:characters_to_list(Url)] - - end, sort_by_downloads(Packages)), - ok = rebar3_hex_results:print_table([Header] ++ Rows), - {ok, State}; - {ok, {Status, _Headers, _Body}} -> - throw(?PRV_ERROR({status, Status})); - {error, Reason} -> - throw(?PRV_ERROR({error, Reason})) - end. - - -truncate_description(Description) -> - Descrip = string:sub_string( - string:strip( - string:strip( - unicode:characters_to_list(Description), both, $\n) - ), 1, 50), - Blist = binary:split(unicode:characters_to_binary(Descrip), <<"\n">>, [global]), - Slist = lists:map(fun(B) -> unicode:characters_to_list(B) end, Blist), - Dstr = string:join(Slist, ""), - case size(Description) of - N when N >= 50 -> - Dstr ++ "..."; - _ -> - Dstr - end. - -sort_by_downloads(Packages) -> - {Unused, Popular} = lists:partition(fun(P) -> maps:get(<<"downloads">>, P) == #{} end, Packages), - lists:sort(fun(#{<<"downloads">> := #{<<"all">> := A}}, - #{<<"downloads">> := #{<<"all">> := B}}) -> - A > B - end, - Popular) ++ Unused. - -latest_stable(Releases) -> - case gather_stable_releases(Releases) of - [] -> - ""; - [Latest | _Rest] -> - binary_to_list(maps:get(<<"version">>, Latest)) - end. - -gather_stable_releases(Releases) -> - version_sort(lists:filter(fun(#{<<"version">> := Ver}) -> - {ok, V} = verl:parse(Ver), - case V of - #{pre := []} -> - true; - _ -> - false - end - end, - Releases - )). - -version_sort(Releases) -> - lists:sort(fun(#{<<"version">> := A}, #{<<"version">> := B}) -> - At = list_to_tuple(binary:split(A, <<".">>, [global])), - Bt = list_to_tuple(binary:split(B, <<".">>, [global])), - At >= Bt - end, - Releases). - --spec format_error(any()) -> iolist(). -format_error({status, Status}) -> - io_lib:format("Error searching for packages: ~ts", - [rebar3_hex_client:pretty_print_status(Status)]); -format_error({error, Reason}) -> - io_lib:format("Error searching for packages: ~p", [Reason]); -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). diff --git a/_build/default/plugins/rebar3_hex/src/rebar3_hex_user.erl b/_build/default/plugins/rebar3_hex/src/rebar3_hex_user.erl deleted file mode 100644 index a658b8c074..0000000000 --- a/_build/default/plugins/rebar3_hex/src/rebar3_hex_user.erl +++ /dev/null @@ -1,310 +0,0 @@ --module(rebar3_hex_user). - --export([init/1, - do/1, - format_error/1]). - --export([hex_register/2, - whoami/2, - auth/2, - deauth/2, - reset_password/2, - encrypt_write_key/3, - decrypt_write_key/2, - decrypt_write_key/3]). - --include("rebar3_hex.hrl"). - --define(PROVIDER, user). --define(DEPS, []). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([{name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, hex}, - {bare, true}, - {deps, ?DEPS}, - {example, "rebar3 hex user "}, - {short_desc, "Hex user tasks"}, - {desc, ""}, - {opts, [rebar3_hex:repo_opt()]}]), - State1 = rebar_state:add_provider(State, Provider), - {ok, State1}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - case rebar_state:command_args(State) of - ["register" | _] -> - {ok, Repo} = rebar3_hex_config:repo(State), - hex_register(Repo, State); - ["whoami" | _] -> - try handle(whoami, State) of - _ -> {ok, State} - catch - {error, _} = Err -> - Err - end; - ["auth" | _] -> - {ok, Repo} = rebar3_hex_config:repo(State), - auth(Repo, State); - ["deauth" | _] -> - {ok, Repo} = rebar3_hex_config:repo(State), - deauth(Repo, State); - ["reset_password" | _] -> - {ok, Repo} = rebar3_hex_config:repo(State), - reset_password(Repo, State); - _ -> - throw(?PRV_ERROR(bad_command)) - end. - - - -handle(whoami, State) -> - {ok, Parents} = rebar3_hex_config:parent_repos(State), - lists:foreach(fun(R) -> case whoami(R, State) of - {ok, _Res} -> ok; - {error, _} = Err -> - throw(Err) - end - end, - Parents). - - --spec format_error(any()) -> iolist(). -format_error({whoami_failure, Reason}) -> - io_lib:format("Fetching currently authenticated user failed: ~ts", [Reason]); -format_error(bad_local_password) -> - "Failure to decrypt write key: bad local password"; -format_error({registration_failure, Reason}) -> - io_lib:format("Registration of user failed: ~ts", [Reason]); -format_error({generate_key, Reason}) -> - io_lib:format("Failure generating authentication tokens: ~ts", [Reason]); -format_error(no_match_local_password) -> - "Password confirmation failed. The passwords must match."; -format_error(bad_command) -> - "Command must be one of register, whoami, auth, deauth or reset_password"; -format_error(Reason) -> - rebar3_hex_error:format_error(Reason). - -hex_register(Repo, State) -> - rebar3_hex_io:say("By registering an account on Hex.pm you accept all our " - "policies and terms of service found at https://hex.pm/policies\n"), - Username = list_to_binary(rebar3_hex_io:ask("Username:", string, "")), - Email = list_to_binary(rebar3_hex_io:ask("Email:", string, "")), - case get_account_password() of - <<"">> -> - error; - Password -> - PasswordConfirm = get_account_password(confirm), - case Password =:= PasswordConfirm of - true -> - rebar3_hex_io:say("Registering..."), - create_user(Username, Email, Password, Repo, State); - false -> - ?PRV_ERROR({error, "passwords do not match"}) - end - end. - -whoami(#{name := Name} = Repo, State) -> - case maps:get(read_key, Repo, undefined) of - undefined -> - {error, "Not authenticated as any user currently for this repository"}; - ReadKey -> - case hex_api_user:me(Repo#{api_key => ReadKey}) of - {ok, {200, _Headers, #{<<"username">> := Username, - <<"email">> := Email}}} -> - rebar3_hex_io:say("~ts : ~ts (~ts)", [Name, Username, Email]), - {ok, State}; - {ok, {_Status, _Headers, #{<<"message">> := Message}}} -> - ?PRV_ERROR({whoami_failure, Message}); - {error, Reason} -> - ?PRV_ERROR({whoami_failure, io_lib:format("~p", [Reason])}) - end - end. - -auth(Repo, State) -> - Username = list_to_binary(rebar3_hex_io:ask("Username:", string, "")), - Password = get_account_password(), - - rebar3_hex_io:say("You have authenticated on Hex using your account password. However, " - "Hex requires you to have a local password that applies only to this machine for security " - "purposes. Please enter it."), - - LocalPassword = rebar3_hex_io:get_password(<<"Local Password: ">>), - ConfirmLocalPassword = rebar3_hex_io:get_password(<<"Local Password (confirm): ">>), - - case LocalPassword =:= ConfirmLocalPassword of - true -> - generate_all_keys(Username, Password, LocalPassword, Repo, State); - false -> - throw(?PRV_ERROR(no_match_local_password)) - end. - -deauth(#{username := Username, name := RepoName}, State) -> - rebar3_hex_config:update_auth_config(#{RepoName => #{}}, State), - rebar3_hex_io:say("User `~s` removed from the local machine. " - "To authenticate again, run `rebar3 hex user auth` " - "or create a new user with `rebar3 hex user register`", [Username]), - {ok, State}; -deauth(_Repo, State) -> - rebar3_hex_io:say("Not authenticated as any user currently for this repository"), - {ok, State}. - -reset_password(Repo, State) -> - User = rebar3_hex_io:ask("Username or Email:", string, ""), - case hex_api_user:reset_password(Repo, list_to_binary(User)) of - {ok, {204, _Headers, _Content}} -> - rebar3_hex_io:say("Email with reset link sent", []), - {ok, State}; - {ok, {_Status, _Headers, #{<<"message">> := Message}}} -> - ?PRV_ERROR({reset_failure, Message}); - {error, Reason} -> - ?PRV_ERROR({reset_failure, io_lib:format("~p", [Reason])}) - end. - -%% Internal functions - -get_account_password() -> - rebar3_hex_io:get_password(<<"Account Password: ">>). - -get_account_password(confirm) -> - rebar3_hex_io:get_password(<<"Account Password (confirm): ">>). - -create_user(Username, Email, Password, Repo, State) -> - case hex_api_user:create(Repo, Username, Password, Email) of - {ok, {201, _Headers, _Body}} -> - rebar3_hex_io:say("You are required to confirm your email to access your account, " - "a confirmation email has been sent to ~s", [Email]), - rebar3_hex_io:say("Then run `rebar3 hex auth -r ~ts` to create and configure api tokens locally.", - [maps:get(name, Repo)]), - {ok, State}; - {ok, {_Status, _Headers, #{<<"errors">> := Errors}}} -> - ?PRV_ERROR({registration_failure, - rebar3_hex_client:pretty_print_errors(Errors)}); - {error, Reason} -> - ?PRV_ERROR({registration_failure, io_lib:format("~p", [Reason])}) - end. - -pad(Binary) -> - case byte_size(Binary) of - Size when Size =< 16 -> - <>; - Size when Size =< 24 -> - <>; - Size when Size =< 32 -> - <> - end. - -generate_all_keys(Username, Password, LocalPassword, Repo, State) -> - rebar3_hex_io:say("Generating all keys..."), - - Auth = base64:encode_to_string(<>), - RepoConfig0 = Repo#{api_key => list_to_binary("Basic " ++ Auth)}, - - %% write key - WriteKeyName = api_key_name(), - WritePermissions = [#{<<"domain">> => <<"api">>}], - case generate_key(RepoConfig0, WriteKeyName, WritePermissions) of - {ok, WriteKey} -> - - WriteKeyEncrypted = encrypt_write_key(Username, LocalPassword, WriteKey), - - %% read key - RepoConfig1 = Repo#{api_key => WriteKey}, - ReadKeyName = api_key_name("read"), - ReadPermissions = [#{<<"domain">> => <<"api">>, <<"resource">> => <<"read">>}], - {ok, ReadKey} = generate_key(RepoConfig1, ReadKeyName, ReadPermissions), - - %% repo key - ReposKeyName = repos_key_name(), - ReposPermissions = [#{<<"domain">> => <<"repositories">>}], - {ok, ReposKey} = generate_key(RepoConfig1, ReposKeyName, ReposPermissions), - - % By default a repositories key is created which gives user access to all repositories - % that they are granted access to server side. For the time being we default - % to hexpm for user auth entries as there is currently no other use case. - rebar3_hex_config:update_auth_config(#{?DEFAULT_HEX_REPO => #{ - username => Username, - write_key => WriteKeyEncrypted, - read_key => ReadKey, - repo_key => ReposKey}}, State), - {ok, State}; - {error, {rebar3_hex_user, _Msg}} = Error -> - Error - end. - --ifdef(POST_OTP_22). --spec encrypt_write_key(binary(), binary(), binary()) -> {binary(), {binary(), binary()}}. -encrypt_write_key(Username, LocalPassword, WriteKey) -> - AAD = Username, - IV = crypto:strong_rand_bytes(16), - Key = pad(LocalPassword), - {IV, crypto:crypto_one_time_aead(cipher(Key), Key, IV, WriteKey, AAD, true)}. --else. --spec encrypt_write_key(binary(), binary(), binary()) -> {binary(), {binary(), binary()}}. -encrypt_write_key(Username, LocalPassword, WriteKey) -> - AAD = Username, - IV = crypto:strong_rand_bytes(16), - {IV, crypto:block_encrypt(aes_gcm, pad(LocalPassword), IV, {AAD, WriteKey})}. --endif. - --spec decrypt_write_key(binary(), {binary(), {binary(), binary()}} | undefined) -> binary(). -decrypt_write_key(_Username, undefined) -> - {error, no_write_key}; -decrypt_write_key(Username, {IV, {CipherText, CipherTag}}) -> - LocalPassword = rebar3_hex_io:get_password(<<"Local Password: ">>), - decrypt_write_key(Username, LocalPassword, {IV, {CipherText, CipherTag}}). - --ifdef(POST_OTP_22). -decrypt_write_key(Username, LocalPassword, {IV, {CipherText, CipherTag}}) -> - Key = pad(LocalPassword), - case crypto:crypto_one_time_aead(cipher(Key), Key, IV, CipherText, Username, CipherTag, false) of - error -> - throw(?PRV_ERROR(bad_local_password)); - Result -> - Result - end. --else. -decrypt_write_key(Username, LocalPassword, {IV, {CipherText, CipherTag}}) -> - case crypto:block_decrypt(aes_gcm, pad(LocalPassword), IV, {Username, CipherText, CipherTag}) of - error -> - throw(?PRV_ERROR(bad_local_password)); - Result -> - Result - end. --endif. - --ifdef(POST_OTP_22). -cipher(Key) when byte_size(Key) == 16 -> aes_128_gcm; -cipher(Key) when byte_size(Key) == 24 -> aes_192_gcm; -cipher(Key) when byte_size(Key) == 32 -> aes_256_gcm. --endif. - -generate_key(RepoConfig, KeyName, Permissions) -> - case hex_api_key:add(RepoConfig, KeyName, Permissions) of - {ok, {201, _Headers, #{<<"secret">> := Secret}}} -> - {ok, Secret}; - {ok, {_Status, _Headers, #{<<"message">> := Message}}} -> - ?PRV_ERROR({generate_key, Message}); - {error, Reason} -> - ?PRV_ERROR({generate_key, io_lib:format("~p", [Reason])}) - end. - -hostname() -> - {ok, Name} = inet:gethostname(), - Name. - -api_key_name() -> - list_to_binary(hostname()). - -api_key_name(Postfix) -> - list_to_binary([hostname(), "-api-", Postfix]). - -repos_key_name() -> - list_to_binary([hostname(), "-repositories"]). - diff --git a/_build/default/plugins/rebar3_neotoma_plugin/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/rebar3_neotoma_plugin/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index f4db8e583d..0000000000 Binary files a/_build/default/plugins/rebar3_neotoma_plugin/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/rebar3_neotoma_plugin/LICENSE b/_build/default/plugins/rebar3_neotoma_plugin/LICENSE deleted file mode 100644 index 8f71f43fee..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/_build/default/plugins/rebar3_neotoma_plugin/README.md b/_build/default/plugins/rebar3_neotoma_plugin/README.md deleted file mode 100644 index b80ac67567..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# rebar3_neotoma_plugin -Rebar3 neotoma (Parser Expression Grammar) compiler plugin. - -Build ------ - - $ rebar3 compile - -Use ---- - -Add the plugin to your rebar config: - - {plugins, [rebar3_neotoma_plugin]}. - -Then just call your plugin directly in an existing application: - - - $ rebar3 neotoma compile - ===> Fetching rebar3_neotoma_plugin - ===> Compiling rebar3_neotoma_plugin - -To have it invoked automatically when running `rebar3 compile` add it as a `provider_hooks`: - -``` -{provider_hooks, [ - {pre, [{compile, {neotoma, compile}}]} - ]}. -``` diff --git a/_build/default/plugins/rebar3_neotoma_plugin/hex_metadata.config b/_build/default/plugins/rebar3_neotoma_plugin/hex_metadata.config deleted file mode 100644 index 5145ad59c1..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/hex_metadata.config +++ /dev/null @@ -1,17 +0,0 @@ -{<<"name">>,<<"rebar3_neotoma_plugin">>}. -{<<"version">>,<<"0.2.0">>}. -{<<"app">>,<<"rebar3_neotoma_plugin">>}. -{<<"requirements">>,[{<<"neotoma">>,<<"1.7.3">>}]}. -{<<"maintainers">>,[<<"Oleg Tsarev">>,<<"Tristan Sloughter">>]}. -{<<"precompiled">>,false}. -{<<"description">>,<<"Neotoma rebar plugin">>}. -{<<"files">>, - [{<<"src/rebar3_neotoma_plugin.app.src">>, - <<"{application,rebar3_neotoma_plugin,\n [{description,\"Neotoma rebar plugin\"},\n {vsn,\"0.2.0\"},\n {registered,[]},\n {applications,[kernel,stdlib,neotoma]},\n {env,[]},\n {modules,[rebar3_neotoma_plugin]},\n {maintainers,[\"Oleg Tsarev\",\"Tristan Sloughter\"]},\n {licenses,[\"Apache\"]},\n {links,[{\"Github\",\n \"https://hub.fastgit.org/zamotivator/rebar3_neotoma_plugin\"}]}]}.\n">>}, - <<"src/rebar3_neotoma_plugin.erl">>,<<"src/rebar3_prv_neotoma_clean.erl">>, - <<"src/rebar3_prv_neotoma_compile.erl">>,<<"rebar.config">>, - <<"rebar.lock">>,<<"README.md">>,<<"LICENSE">>]}. -{<<"licenses">>,[<<"Apache">>]}. -{<<"links">>, - [{<<"Github">>,<<"https://hub.fastgit.org/zamotivator/rebar3_neotoma_plugin">>}]}. -{<<"build_tools">>,[<<"rebar3">>]}. diff --git a/_build/default/plugins/rebar3_neotoma_plugin/rebar.config b/_build/default/plugins/rebar3_neotoma_plugin/rebar.config deleted file mode 100644 index 2c45a562d7..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/rebar.config +++ /dev/null @@ -1,2 +0,0 @@ -{erl_opts, [debug_info]}. -{deps, [neotoma]}. diff --git a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_neotoma_plugin.app.src b/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_neotoma_plugin.app.src deleted file mode 100644 index 48f3f448cf..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_neotoma_plugin.app.src +++ /dev/null @@ -1,11 +0,0 @@ -{application,rebar3_neotoma_plugin, - [{description,"Neotoma rebar plugin"}, - {vsn,"0.2.0"}, - {registered,[]}, - {applications,[kernel,stdlib,neotoma]}, - {env,[]}, - {modules,[rebar3_neotoma_plugin]}, - {maintainers,["Oleg Tsarev","Tristan Sloughter"]}, - {licenses,["Apache"]}, - {links,[{"Github", - "https://hub.fastgit.org/zamotivator/rebar3_neotoma_plugin"}]}]}. diff --git a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_neotoma_plugin.erl b/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_neotoma_plugin.erl deleted file mode 100644 index 89dd810263..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_neotoma_plugin.erl +++ /dev/null @@ -1,13 +0,0 @@ --module(rebar3_neotoma_plugin). - --export([init/1]). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - {ok, State1} = rebar3_prv_neotoma_compile:init(State), - {ok, State2} = rebar3_prv_neotoma_clean:init(State1), - {ok, State2}. diff --git a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_prv_neotoma_clean.erl b/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_prv_neotoma_clean.erl deleted file mode 100644 index 95b1fafb45..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_prv_neotoma_clean.erl +++ /dev/null @@ -1,33 +0,0 @@ --module(rebar3_prv_neotoma_clean). - --export([init/1, do/1, format_error/1]). - --define(PROVIDER, clean). --define(DEPS, [{default, app_discovery}]). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, neotoma}, - {bare, false}, - {deps, ?DEPS}, - {example, "rebar3 neotoma clean"}, - {short_desc, "Clean source generated from peg files."}, - {desc, ""}, - {opts, []} - ]), - {ok, rebar_state:add_provider(State, Provider)}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - rebar_api:info("Cleaning neotoma generated files not yet implemented", []), - {ok, State}. - -format_error(Error) -> - io_lib:format("~p", [Error]). diff --git a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_prv_neotoma_compile.erl b/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_prv_neotoma_compile.erl deleted file mode 100644 index 4bc75f9c31..0000000000 --- a/_build/default/plugins/rebar3_neotoma_plugin/src/rebar3_prv_neotoma_compile.erl +++ /dev/null @@ -1,52 +0,0 @@ --module(rebar3_prv_neotoma_compile). - --export([init/1, - do/1, - format_error/1]). - --define(PROVIDER, compile). --define(DEPS, [{default, app_discovery}]). - -%% =================================================================== -%% Public API -%% =================================================================== - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, - {module, ?MODULE}, - {namespace, neotoma}, - {bare, false}, - {deps, ?DEPS}, - {example, "rebar3 neotoma compile"}, - {short_desc, "compile peg files."}, - {desc, "compile peg files."}, - {opts, []} - ]), - {ok, rebar_state:add_provider(State, Provider)}. - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - rebar_api:info("Running neotoma...", []), - Apps = case rebar_state:current_app(State) of - undefined -> - rebar_state:project_apps(State); - AppInfo -> - [AppInfo] - end, - [begin - Opts = rebar_app_info:opts(AppInfo), - SourceDir = filename:join(rebar_app_info:dir(AppInfo), "src"), - CompileFun = fun(Source, Target, _Config) -> - OutDir = filename:dirname(Target), - neotoma:file(Source, [{output, OutDir}]) - end, - - rebar_base_compiler:run(Opts, [], SourceDir, ".peg", SourceDir, ".erl", CompileFun, [{check_last_mod, true}]) - end || AppInfo <- Apps], - - {ok, State}. - -format_error(Error) -> - io_lib:format("~p", [Error]). diff --git a/_build/default/plugins/rebar3_proper/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/rebar3_proper/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index 0488a61163..0000000000 Binary files a/_build/default/plugins/rebar3_proper/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/rebar3_proper/LICENSE b/_build/default/plugins/rebar3_proper/LICENSE deleted file mode 100644 index 949fc1b891..0000000000 --- a/_build/default/plugins/rebar3_proper/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2015, Fred Hebert, All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. 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. - -3. Neither the name of the copyright holder 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. diff --git a/_build/default/plugins/rebar3_proper/README.md b/_build/default/plugins/rebar3_proper/README.md deleted file mode 100644 index 54018ca771..0000000000 --- a/_build/default/plugins/rebar3_proper/README.md +++ /dev/null @@ -1,160 +0,0 @@ -Rebar3 Proper Plugin -===== - -Run PropEr test suites. - -By default, will look for all modules starting in `prop_` in the `test/` -directories of a rebar3 project, and running all properties (functions of arity -0 with a `prop_` prefix) in them. - -Todo/Gotchas ----- - -- No automated tests yet since this repo runs tests for a living - -Use ---- - -Add the plugin to your rebar config: - - %% the plugin itself - {project_plugins, [rebar3_proper]}. - %% The PropEr dependency is required to compile the test cases - %% and will be used to run the tests as well. - {profiles, - [{test, [ - {deps, [ - %% hex - {proper, "1.3.0"} - %% newest from master - {proper, {git, "https://hub.fastgit.org/proper-testing/proper.git", - {branch, "master"}}} - ]} - ]} - ]}. - -Then just call your plugin directly in an existing application: - - Usage: rebar3 proper [-d
] [-m ] [-p ] - [-n ] [-v ] [-c []] - [--retry []] [--regressions []] - [--store []] [--long_result ] - [--start_size ] [--max_size ] - [--max_shrinks ] - [--noshrink ] - [--constraint_tries ] - [--spec_timeout ] - [--any_to_integer ] - - -d, --dir directory where the property tests are located - (defaults to "test"). The directory also needs to be - declared in extra_src_dirs. - -m, --module name of one or more modules to test (comma-separated) - -p, --prop name of properties to test within a specified module - (comma-separated) - -n, --numtests number of tests to run when testing a given property - -s, --search_steps number of searches to run when testing a given - targeted property - -v, --verbose each propertie tested shows its output or not - (defaults to true) - -c, --cover generate cover data [default: false] - --retry If failing test case counterexamples have been - stored, they are retried [default: false] - --regressions replays the test cases stored in the regression - file. [default: false] - --store stores the last counterexample into the regression - file. [default: false] - --long_result enables long-result mode, displaying - counter-examples on failure rather than just false - --start_size specifies the initial value of the size parameter - --max_size specifies the maximum value of the size parameter - --max_shrinks specifies the maximum number of times a failing test - case should be shrunk before returning - --noshrink instructs PropEr to not attempt to shrink any - failing test cases - --constraint_tries specifies the maximum number of tries before the - generator subsystem gives up on producing an - instance that satisfies a ?SUCHTHAT constraint - --spec_timeout duration, in milliseconds, after which PropEr - considers an input to be failing - --any_to_integer converts instances of the any() type to integers in - order to speed up execution - -All of [PropEr's standard configurations](http://proper.softlab.ntua.gr/doc/proper.html#Options) -that can be put in a consult file can be put in `{proper_opts, [Options]}.` in your rebar.config file. - -Workflow ---- - -A workflow to handle errors and do development is being experimented with: - -1. Run any properties with `rebar3 proper` -2. On a test failure, replay the last failing cases with `rebar3 proper --retry` -3. Call `rebar3 proper --store` if the cases are interesting and you want to keep them for the future. The entries will be appended in a `proper-regressions.consult` file in your configured test directory. Check in that file or edit it as you wish. -4. Use `rebar3 proper --regressions` to prevent regressions from happening by testing your code against all stored counterexamples - -Per-Properties Meta functions ---- - -This plugin allows you to export additional meta functions to add per-property options and documentation. For example, in the following code: - -```erlang --module(prop_demo). --include_lib("proper/include/proper.hrl"). --export([prop_demo/1]). % NOT auto-exported by PropEr, we must do it ourselves - -prop_demo(doc) -> - %% Docs are shown when the test property fails - "only properties that return `true' are seen as passing"; -prop_demo(opts) -> - %% Override CLI and rebar.config option for `numtests' only - [{numtests, 500}]. - -prop_demo() -> % auto-exported by Proper - ?FORALL(_N, integer(), false). % always fail - -prop_works() -> - ?FORALL(_N, integer(), true). - -prop_fails() -> - ?FORALL(_N, integer(), false). % fails also -``` - -When run, the `prop_demo/0` property will _always_ run 500 times (if it does not fail), and on failure, properties with a doc value have it displayed: - -``` -... -1/3 properties passed, 2 failed -===> Failed test cases: -prop_demo:prop_demo() -> false (only properties that return `true' are seen as passing) -prop_demo:prop_fails() -> false -``` - -The meta function may be omitted entirely. - - -Changelog ----- - -- 0.12.1: fix debug message to match newer rebar3 standards, fixes unintuitive handling of non-compiled directories. -- 0.12.0: drop compile phase since newer rebar3 versions handle all of that for us out of the box. Eliminates old deprecation warning. -- 0.11.1: fix unicode support in meta-functions output -- 0.11.0: add option to set search steps for targeted properties -- 0.10.4: add PropEr FSM template -- 0.10.3: fix the template change, which was apparently rushed. -- 0.10.2: create the regression file path if it doesn't exist; simplify prop_statem template -- 0.10.1: support per-app `erl_opts` values rather than only root config -- 0.10.0: support hooks for app and umbrella level; add per-property opts and docs via meta-functions; remove runtime dependency on PropEr and use the one specified by the app instead -- 0.9.0: support for umbrella projects -- 0.8.0: storage and replay of counterexamples -- 0.7.2: rely on a non-beta PropEr version -- 0.7.1: fix bug regarding lib and priv directories in code path -- 0.7.0: fix bug with include paths of hrl files from parent apps, support counterexamples with --retry -- 0.6.3: fix bug with cover-compiling in rebar 3.2.0 and above again -- 0.6.2: fix bug with cover-compiling in rebar 3.2.0 and above -- 0.6.1: fix bug on option parsing in config files -- 0.5.0: switches to package dependencies -- 0.4.0: switches license to BSD with templates -- 0.3.0: code coverage supported -- 0.2.0: basic functionality -- 0.1.0: first commits diff --git a/_build/default/plugins/rebar3_proper/hex_metadata.config b/_build/default/plugins/rebar3_proper/hex_metadata.config deleted file mode 100644 index ba13325229..0000000000 --- a/_build/default/plugins/rebar3_proper/hex_metadata.config +++ /dev/null @@ -1,19 +0,0 @@ -{<<"app">>,<<"rebar3_proper">>}. -{<<"build_tools">>,[<<"rebar3">>]}. -{<<"description">>,<<"Run PropEr test suites">>}. -{<<"files">>, - [<<"LICENSE">>,<<"README.md">>,<<"priv/templates/prop.erl.tpl">>, - <<"priv/templates/prop_fsm.erl.tpl">>, - <<"priv/templates/prop_statem.erl.tpl">>, - <<"priv/templates/proper.template">>, - <<"priv/templates/proper_fsm.template">>, - <<"priv/templates/proper_statem.template">>,<<"rebar.config">>, - <<"rebar.lock">>,<<"src/rebar3_proper.app.src">>, - <<"src/rebar3_proper.erl">>,<<"src/rebar3_proper_prv.erl">>]}. -{<<"licenses">>,[<<"BSD">>]}. -{<<"links">>, - [{<<"Github">>,<<"https://hub.fastgit.org/ferd/rebar3_proper">>}, - {<<"PropEr">>,<<"http://proper.softlab.ntua.gr/">>}]}. -{<<"name">>,<<"rebar3_proper">>}. -{<<"requirements">>,[]}. -{<<"version">>,<<"0.12.1">>}. diff --git a/_build/default/plugins/rebar3_proper/priv/templates/prop.erl.tpl b/_build/default/plugins/rebar3_proper/priv/templates/prop.erl.tpl deleted file mode 100644 index 795ca15e06..0000000000 --- a/_build/default/plugins/rebar3_proper/priv/templates/prop.erl.tpl +++ /dev/null @@ -1,21 +0,0 @@ --module(prop_{{name}}). --include_lib("proper/include/proper.hrl"). - -%%%%%%%%%%%%%%%%%% -%%% Properties %%% -%%%%%%%%%%%%%%%%%% -prop_test() -> - ?FORALL(Type, mytype(), - begin - boolean(Type) - end). - -%%%%%%%%%%%%%%% -%%% Helpers %%% -%%%%%%%%%%%%%%% -boolean(_) -> true. - -%%%%%%%%%%%%%%%%%% -%%% Generators %%% -%%%%%%%%%%%%%%%%%% -mytype() -> term(). diff --git a/_build/default/plugins/rebar3_proper/priv/templates/prop_fsm.erl.tpl b/_build/default/plugins/rebar3_proper/priv/templates/prop_fsm.erl.tpl deleted file mode 100644 index dcdf00df27..0000000000 --- a/_build/default/plugins/rebar3_proper/priv/templates/prop_fsm.erl.tpl +++ /dev/null @@ -1,54 +0,0 @@ --module(prop_{{name}}). --include_lib("proper/include/proper.hrl"). - --export([initial_state/0, initial_state_data/0, - on/1, off/1, service/3, % State generators - weight/3, precondition/4, postcondition/5, next_state_data/5]). - -prop_test() -> - ?FORALL(Cmds, proper_fsm:commands(?MODULE), - begin - actual_system:start_link(), - {History,State,Result} = proper_fsm:run_commands(?MODULE, Cmds), - actual_system:stop(), - ?WHENFAIL(io:format("History: ~p\nState: ~p\nResult: ~p\n", - [History,State,Result]), - aggregate(zip(proper_fsm:state_names(History), - command_names(Cmds)), - Result =:= ok)) - end). - --record(data, {}). - -%% Initial state for the state machine -initial_state() -> on. -%% Initial model data at the start. Should be deterministic. -initial_state_data() -> #data{}. - -%% State commands generation -on(_Data) -> [{off, {call, actual_system, some_call, [term(), term()]}}]. - -off(_Data) -> - [{off, {call, actual_system, some_call, [term(), term()]}}, - {history, {call, actual_system, some_call, [term(), term()]}}, - { {service,sub,state}, {call, actual_system, some_call, [term()]}}]. - -service(_Sub, _State, _Data) -> - [{on, {call, actual_system, some_call, [term(), term()]}}]. - -%% Optional callback, weight modification of transitions -weight(_FromState, _ToState, _Call) -> 1. - -%% Picks whether a command should be valid. -precondition(_From, _To, #data{}, {call, _Mod, _Fun, _Args}) -> true. - -%% Given the state states and data *prior* to the call -%% `{call, Mod, Fun, Args}', determine if the result `Res' (coming -%% from the actual system) makes sense. -postcondition(_From, _To, _Data, {call, _Mod, _Fun, _Args}, _Res) -> true. - -%% Assuming the postcondition for a call was true, update the model -%% accordingly for the test to proceed. -next_state_data(_From, _To, Data, _Res, {call, _Mod, _Fun, _Args}) -> - NewData = Data, - NewData. diff --git a/_build/default/plugins/rebar3_proper/priv/templates/prop_statem.erl.tpl b/_build/default/plugins/rebar3_proper/priv/templates/prop_statem.erl.tpl deleted file mode 100644 index b284f937cb..0000000000 --- a/_build/default/plugins/rebar3_proper/priv/templates/prop_statem.erl.tpl +++ /dev/null @@ -1,50 +0,0 @@ --module(prop_{{name}}). --include_lib("proper/include/proper.hrl"). - -%% Model Callbacks --export([command/1, initial_state/0, next_state/3, - precondition/2, postcondition/3]). - -%%%%%%%%%%%%%%%%%% -%%% PROPERTIES %%% -%%%%%%%%%%%%%%%%%% -prop_test() -> - ?FORALL(Cmds, commands(?MODULE), - begin - actual_system:start_link(), - {History, State, Result} = run_commands(?MODULE, Cmds), - actual_system:stop(), - ?WHENFAIL(io:format("History: ~p\nState: ~p\nResult: ~p\n", - [History,State,Result]), - aggregate(command_names(Cmds), Result =:= ok)) - end). - -%%%%%%%%%%%%% -%%% MODEL %%% -%%%%%%%%%%%%% -%% @doc Initial model value at system start. Should be deterministic. -initial_state() -> - #{}. - -%% @doc List of possible commands to run against the system -command(_State) -> - oneof([ - {call, actual_system, some_call, [term(), term()]} - ]). - -%% @doc Determines whether a command should be valid under the -%% current state. -precondition(_State, {call, _Mod, _Fun, _Args}) -> - true. - -%% @doc Given the state `State' *prior* to the call -%% `{call, Mod, Fun, Args}', determine whether the result -%% `Res' (coming from the actual system) makes sense. -postcondition(_State, {call, _Mod, _Fun, _Args}, _Res) -> - true. - -%% @doc Assuming the postcondition for a call was true, update the model -%% accordingly for the test to proceed. -next_state(State, _Res, {call, _Mod, _Fun, _Args}) -> - NewState = State, - NewState. diff --git a/_build/default/plugins/rebar3_proper/priv/templates/proper.template b/_build/default/plugins/rebar3_proper/priv/templates/proper.template deleted file mode 100644 index 4f2befa1e6..0000000000 --- a/_build/default/plugins/rebar3_proper/priv/templates/proper.template +++ /dev/null @@ -1,6 +0,0 @@ -{description, "Template for a regular PropEr suite"}. -{variables, [ - {name, "Name of the suite (prop_)"}, - {test_dir, "test", "The directory where the test suite goes"} -]}. -{template, "prop.erl.tpl", "{{test_dir}}/prop_{{name}}.erl"}. diff --git a/_build/default/plugins/rebar3_proper/priv/templates/proper_fsm.template b/_build/default/plugins/rebar3_proper/priv/templates/proper_fsm.template deleted file mode 100644 index 7da7524b9d..0000000000 --- a/_build/default/plugins/rebar3_proper/priv/templates/proper_fsm.template +++ /dev/null @@ -1,8 +0,0 @@ -{description, "Template for a state machine PropEr suite"}. -{variables, [ - {name, "fsm", "Name of the suite (prop_)"}, - {test_dir, "test", "The directory where the test suite goes"} -]}. -{template, "prop_fsm.erl.tpl", "{{test_dir}}/prop_{{name}}.erl"}. - - diff --git a/_build/default/plugins/rebar3_proper/priv/templates/proper_statem.template b/_build/default/plugins/rebar3_proper/priv/templates/proper_statem.template deleted file mode 100644 index 8d4ffe5907..0000000000 --- a/_build/default/plugins/rebar3_proper/priv/templates/proper_statem.template +++ /dev/null @@ -1,7 +0,0 @@ -{description, "Template for a statem PropEr suite"}. -{variables, [ - {name, "stateful", "Name of the suite (prop_)"}, - {test_dir, "test", "The directory where the test suite goes"} -]}. -{template, "prop_statem.erl.tpl", "{{test_dir}}/prop_{{name}}.erl"}. - diff --git a/_build/default/plugins/rebar3_proper/rebar.config b/_build/default/plugins/rebar3_proper/rebar.config deleted file mode 100644 index 5846c05661..0000000000 --- a/_build/default/plugins/rebar3_proper/rebar.config +++ /dev/null @@ -1,5 +0,0 @@ -%% PropEr not actually needed as a dep as long as the -%% parent app has it as a dependency. -% {deps, [ -% {proper, "1.2.0"} -% ]}. diff --git a/_build/default/plugins/rebar3_proper/src/rebar3_proper.app.src b/_build/default/plugins/rebar3_proper/src/rebar3_proper.app.src deleted file mode 100644 index 8b3cb4ce57..0000000000 --- a/_build/default/plugins/rebar3_proper/src/rebar3_proper.app.src +++ /dev/null @@ -1,10 +0,0 @@ -{application,rebar3_proper, - [{description,"Run PropEr test suites"}, - {vsn,"0.12.1"}, - {registered,[]}, - {applications,[kernel,stdlib,proper]}, - {env,[]}, - {modules,[]}, - {licenses,["BSD"]}, - {links,[{"Github","https://hub.fastgit.org/ferd/rebar3_proper"}, - {"PropEr","http://proper.softlab.ntua.gr/"}]}]}. diff --git a/_build/default/plugins/rebar3_proper/src/rebar3_proper.erl b/_build/default/plugins/rebar3_proper/src/rebar3_proper.erl deleted file mode 100644 index 8c19ff74a5..0000000000 --- a/_build/default/plugins/rebar3_proper/src/rebar3_proper.erl +++ /dev/null @@ -1,8 +0,0 @@ --module(rebar3_proper). - --export([init/1]). - --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - {ok, State1} = rebar3_proper_prv:init(State), - {ok, State1}. diff --git a/_build/default/plugins/rebar3_proper/src/rebar3_proper_prv.erl b/_build/default/plugins/rebar3_proper/src/rebar3_proper_prv.erl deleted file mode 100644 index bfa082d76f..0000000000 --- a/_build/default/plugins/rebar3_proper/src/rebar3_proper_prv.erl +++ /dev/null @@ -1,542 +0,0 @@ --module(rebar3_proper_prv). - --export([init/1, do/1, format_error/1]). - --define(PROVIDER, proper). --define(DEPS, [compile]). --define(PRV_ERROR(Reason), {error, {?MODULE, Reason}}). --define(COUNTEREXAMPLE_FILE, "rebar3_proper-counterexamples.consult"). --define(REGRESSION_FILE, "proper-regressions.consult"). - -%% =================================================================== -%% Public API -%% =================================================================== --spec init(rebar_state:t()) -> {ok, rebar_state:t()}. -init(State) -> - Provider = providers:create([ - {name, ?PROVIDER}, % The 'user friendly' name of the task - {module, ?MODULE}, % The module implementation of the task - {profiles, [test]}, - {bare, true}, % The task can be run by the user, always true - {deps, ?DEPS}, % The list of dependencies - {example, "rebar3 proper"}, % How to use the plugin - {opts, proper_opts()}, % list of options understood by the plugin - {short_desc, "Run PropEr test suites"}, - {desc, "Run PropEr test suites"} - ]), - {ok, rebar_state:add_provider(State, Provider)}. - - --spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}. -do(State) -> - run_pre_hooks(State), - {Opts, ProperOpts} = handle_opts(State), - rebar_api:debug("{proper_opts,\n\t% general options:~n\t~p~n\t++~n" - "\t% proper-specific options:~n\t~p}", - [Opts, ProperOpts]), - rebar_utils:update_code(rebar_state:code_paths(State, all_deps), [soft_purge]), - maybe_cover_compile(State), - %% needed in 3.2.0 and after -- this reloads the code paths required to - %% compile everything *after* cover-compiling has cleaned up after itself - %% (which incidentally clears up *our* environment too), but skips reloading - %% the top level apps' own code paths since those would overwrite the cover- - %% compiled code sitting in memory. The top app's path is readded to the - %% code path but not pre-loaded in memory, though. - TopAppsPaths = app_paths(State), - rebar_utils:update_code(rebar_state:code_paths(State, all_deps)--TopAppsPaths, [soft_purge]), - FlatPaths = TopAppsPaths ++ (code:get_path() -- TopAppsPaths), - true = code:set_path(FlatPaths), - - ensure_proper(), - SysConfigs = sys_config_list(ProperOpts, Opts), - Configs = lists:flatmap(fun(Filename) -> - rebar_file_utils:consult_config(State, Filename) - end, SysConfigs), - [application:load(Application) || Config <- SysConfigs, {Application, _} <- Config], - rebar_utils:reread_config(Configs), - - - Res = case run_type(Opts) of - quickcheck -> do_quickcheck(State, Opts, ProperOpts); - retry -> do_retry(State, Opts, ProperOpts); - regressions -> do_regressions(State, Opts, ProperOpts); - store -> do_store(State, Opts, ProperOpts) - end, - run_post_hooks(State, Res), - Res. - -run_type(Opts) -> - case {proplists:get_value(retry, Opts, false), - proplists:get_value(regressions, Opts, false), - proplists:get_value(store, Opts, false)} of - {true, _, _} -> retry; - {_, true, _} -> regressions; - {_, _, true} -> store; - _ -> quickcheck - end. - -do_quickcheck(State, Opts, ProperOpts) -> - try find_properties(State, Opts) of - Props -> - rebar_api:debug("properties: ~p", [Props]), - Failed = [{Mod, Fun, Res, proper:counterexample()} - || {Mod, Fun} <- Props, - Res <- [catch check(Mod, Fun, ProperOpts)], - Res =/= true], - rebar_api:debug("Failing Results: ~p", [Failed]), - maybe_write_coverdata(State), - rebar_utils:cleanup_code_path(rebar_state:code_paths(State, default)), - case Failed of - [] -> - Tot = length(Props), - rebar_api:info("~n~p/~p properties passed", [Tot, Tot]), - {ok, State}; - [_|_] -> - Tot = length(Props), - FailedCount = length(Failed), - Passed = Tot - FailedCount, - rebar_api:error("~n~p/~p properties passed, ~p failed", [Passed, Tot, FailedCount]), - store_counterexamples(State, Failed), - ?PRV_ERROR({failed, Failed}) - end - catch - throw:{module_not_found,_Mod,_Props}=Error -> ?PRV_ERROR(Error); - throw:{property_not_found,_Prop,_Mods}=Error -> ?PRV_ERROR(Error) - end. - -do_retry(State, Opts, ProperOpts) -> - Base = rebar_dir:base_dir(State), - FilePath = filename:join([Base, ?COUNTEREXAMPLE_FILE]), - case file:consult(FilePath) of - {ok, Data} -> - run_retries(State, Opts, ProperOpts, Data); - {error, _} -> - rebar_api:info("no counterexamples to run.", []), - {ok, State} - end. - -do_regressions(State, Opts, ProperOpts) -> - Dir = proplists:get_value(dir, Opts, "test"), - FilePath = filename:join([Dir, ?REGRESSION_FILE]), - case file:consult(FilePath) of - {ok, Data} -> - run_retries(State, Opts, ProperOpts, Data); - {error, _} -> - rebar_api:info("no regression tests to run.", []), - {ok, State} - end. - -do_store(State, Opts, _ProperOpts) -> - Base = rebar_dir:base_dir(State), - FilePath = filename:join([Base, ?COUNTEREXAMPLE_FILE]), - case file:consult(FilePath) of - {ok, Data} -> - Dir = proplists:get_value(dir, Opts, "test"), - RegressionPath = filename:join([Dir, ?REGRESSION_FILE]), - filelib:ensure_dir(RegressionPath), - {ok, Io} = file:open(RegressionPath, [append, {encoding, utf8}]), - rebar_api:debug("Storing counterexamples to ~s", [RegressionPath]), - {ok, Prior} = file:consult(RegressionPath), - [io:format(Io, "~n~p.~n", [{Mod,Fun,CounterEx}]) - || {Mod,Fun,CounterEx} <- Data, - CounterEx =/= undefined, - not lists:member({Mod,Fun,CounterEx}, Prior)], % dedupe - file:close(Io), - {ok, State}; - {error, ConsultErr} -> - rebar_api:debug("counterexample file consult result: ~p", [ConsultErr]), - rebar_api:info("no counterexamples to store.", []), - {ok, State} - end. - - -run_retries(State, Opts, ProperOpts, CounterExamples) -> - Dir = proplists:get_value(dir, Opts, "test"), - {Mods, Props} = lists:unzip([{atom_to_list(M), atom_to_list(F)} - || {M, F, _Args} <- CounterExamples]), - try find_properties(State, Dir, Mods, Props) of - Found -> - ExpectedLen = length(CounterExamples), - FoundLen = length(Found), - rebar_api:info("Running ~p counterexamples out of ~p properties", - [ExpectedLen, FoundLen]), - Failed = [{M, F, Result, Args} - || {M,F,Args} <- CounterExamples, - lists:member({M,F}, Found), - Result <- [catch retry(M, F, Args, ProperOpts)], - Result =/= true], - FailedCount = length(Failed), - Passed = ExpectedLen - FailedCount, - case Failed of - [] -> - rebar_api:info("~n~p/~p counterexamples passed", [Passed, ExpectedLen]), - {ok, State}; - [_|_] -> - rebar_api:error("~n~p/~p counterexamples passed, ~p failed", - [Passed, ExpectedLen, FailedCount]), - ?PRV_ERROR({failed, Failed}) - end - catch - throw:{module_not_found,_Mod,_Props}=Error -> ?PRV_ERROR(Error); - throw:{property_not_found,_Prop,_Mods}=Error -> ?PRV_ERROR(Error) - end. - - - --spec format_error(any()) -> iolist(). -format_error({failed, Failed}) -> - ["Failed test cases:", - [io_lib:format("~n~p:~p() -> ~p~ts", - [M,F,Res,format_doc(M,F)]) || {M,F,Res,_} <- Failed]]; -format_error({module_not_found, Mod, any}) -> - io_lib:format("Module ~p does not exist or exports no properties", [Mod]); -format_error({module_not_found, Mod, _}) -> - io_lib:format("Module ~p does not exist", [Mod]); -format_error({property_not_found, Prop, []}) -> - io_lib:format("Property ~p does not belong to any module", [Prop]); -format_error({property_not_found, Prop, Mods}) -> - io_lib:format("Property ~p does not belong to any module in ~p", [Prop, Mods]); -format_error(Reason) -> - io_lib:format("~p", [Reason]). - -%% =================================================================== -%% Private -%% =================================================================== -maybe_cover_compile(State) -> - {RawOpts, _} = rebar_state:command_parsed_args(State), - State1 = case proplists:get_value(cover, RawOpts, false) of - true -> rebar_state:set(State, cover_enabled, true); - false -> State - end, - rebar_prv_cover:maybe_cover_compile(State1). - -maybe_write_coverdata(State) -> - {RawOpts, _} = rebar_state:command_parsed_args(State), - State1 = case proplists:get_value(cover, RawOpts, false) of - true -> rebar_state:set(State, cover_enabled, true); - false -> State - end, - rebar_prv_cover:maybe_write_coverdata(State1, ?PROVIDER). - -ensure_proper() -> - try proper:module_info() of - _ -> ok - catch - error:undef -> - rebar_api:abort("PropEr not found. Add it as a dependency of " - "the application you are testing.", []) - end. - -check(Mod, Fun, Opts) -> - rebar_api:info("Testing ~p:~p()", [Mod, Fun]), - NewOpts = fetch_opts(Mod, Fun, Opts), - proper:quickcheck(Mod:Fun(), NewOpts). - -retry(Mod, Fun, Args, Opts) -> - rebar_api:info("Retrying ~p:~p()", [Mod, Fun]), - NewOpts = fetch_opts(Mod, Fun, Opts), - proper:check(Mod:Fun(), Args, NewOpts). - -fetch_opts(Mod, Fun, Opts) -> - try Mod:Fun(opts) of - TestOpts -> - rebar_api:debug("Custom test options found for ~p:~p():~n\t~p", - [Mod, Fun, TestOpts]), - TestOpts ++ Opts - catch - error:E when E == undef; E == function_clause -> - rebar_api:debug("~p:~p(opts) not found; using predefined options", - [Mod, Fun]), - Opts - end. - -store_counterexamples(State, Failed) -> - Base = rebar_dir:base_dir(State), - FilePath = filename:join([Base, ?COUNTEREXAMPLE_FILE]), - {ok, Io} = file:open(FilePath, [write, {encoding, utf8}]), - rebar_api:debug("Writing counterexamples to ~s", [FilePath]), - %% Then run as proper:check(Mod:Fun(), CounterEx) - [io:format(Io, "~p.~n", [{Mod,Fun,CounterEx}]) || {Mod,Fun,_,CounterEx} <- Failed, - CounterEx =/= undefined], - file:close(Io), - ok. - -find_properties(State, Opts) -> - Dir = proplists:get_value(dir, Opts, "test"), - Mods = proplists:get_value(module, Opts, any), - Props = proplists:get_value(properties, Opts, any), - Found = find_properties(State, Dir, Mods, Props), - rebar_api:debug("Found: ~p", [Found]), - {ModsFound0, PropsFound0} = lists:unzip(Found), - ModsFound = [atom_to_list(Mod) || Mod <- ModsFound0], - PropsFound = [atom_to_list(Prop) || Prop <- PropsFound0], - Props =/= any andalso - [throw({property_not_found, Prop, Mods}) - || Prop <- Props, not lists:member(Prop, PropsFound)], - Mods =/= any andalso - [throw({module_not_found, Mod, Props}) - || Mod <- Mods, not lists:member(Mod, ModsFound)], - Found. - -find_properties(State, Dir, Mods, Props) -> - %% Fetch directories and app configs - RawDirs = [{{rebar_app_info:name(App), - filename:join([rebar_app_info:out_dir(App), Dir])}, - filename:join(rebar_app_info:dir(App), Dir)} - || App <- rebar_state:project_apps(State), - not rebar_app_info:is_checkout(App)], - %% Pick a root test directory for umbrella apps - UmbrellaDir = - [{{<<"root">>, - filename:join(rebar_dir:base_dir(State), "prop_"++Dir)}, - P} || P <- [make_absolute_path(filename:join([".", Dir]))], - not lists:member(P, [D || {_,D} <- RawDirs])], - TestDirs = RawDirs ++ UmbrellaDir, - rebar_api:debug("SearchDirs: ~p", [TestDirs]), - %% Keep directories with properties in them - Dirs = [{App, TestDir} - || {App, TestDir} <- TestDirs, - {ok, Files} <- [file:list_dir(TestDir)], - lists:any(fun(File) -> prop_suite(Mods, File) end, Files)], - [Prop || {_, TestDir} <- Dirs, - {ok, Files} <- [file:list_dir(TestDir)], - File <- Files, - prop_suite(Mods, File), - mod_compiled(module(File), TestDir), - Prop <- properties(Props, module(File))]. - -prop_suite(Mods, File) -> - Mod = filename:basename(File, ".erl"), - filename:extension(File) =:= ".erl" - andalso - ((Mods =:= any andalso lists:prefix("prop_", Mod)) - orelse - (Mods =/= any andalso lists:member(Mod, Mods))). - -module(File) -> - list_to_atom(filename:basename(File, ".erl")). - -mod_compiled(Mod, TestDir) -> - try Mod:module_info() of - _ -> true - catch - error:undef when TestDir =:= "test" -> - rebar_api:debug("Skipping module ~p since it was not compiled.", - [Mod]), - false; - error:undef -> - rebar_api:debug("Skipping module ~p since it was not compiled. " - "Verify presence in extra_src_dirs", [Mod]), - false - end. - -properties(any, Mod) -> - [{Mod, Prop} || {Prop,0} <- Mod:module_info(exports), - prop_prefix(Prop)]; -properties(Props, Mod) -> - [{Mod, Prop} || {Prop,0} <- Mod:module_info(exports), - lists:member(atom_to_list(Prop), Props)]. - -prop_prefix(Atom) -> - lists:prefix("prop_", atom_to_list(Atom)). - -proper_opts() -> - [{dir, $d, "dir", string, - "directory where the property tests are located (defaults to \"test\"). " - "The directory also needs to be declared in extra_src_dirs."}, - {module, $m, "module", string, - "name of one or more modules to test (comma-separated)"}, - {properties, $p, "prop", string, - "name of properties to test within a specified module (comma-separated)"}, - {numtests, $n, "numtests", integer, - "number of tests to run when testing a given property"}, - {search_steps, $s, "search_steps", integer, - "number of searches to run when testing a given targeted property"}, - {verbose, $v, "verbose", boolean, - "each property tested shows its output or not (defaults to true)"}, - {cover, $c, "cover", {boolean, false}, - "generate cover data"}, - %% no short format for these buddies - {retry, undefined, "retry", {boolean, false}, - "If failing test case counterexamples have been stored, " - "they are retried"}, - {regressions, undefined, "regressions", {boolean, false}, - "replays the test cases stored in the regression file."}, - {store, undefined, "store", {boolean, false}, - "stores the last counterexample into the regression file."}, - {long_result, undefined, "long_result", boolean, - "enables long-result mode, displaying counter-examples on failure " - "rather than just false"}, - {start_size, undefined, "start_size", integer, - "specifies the initial value of the size parameter"}, - {max_size, undefined, "max_size", integer, - "specifies the maximum value of the size parameter"}, - {max_shrinks, undefined, "max_shrinks", integer, - "specifies the maximum number of times a failing test case should be " - "shrunk before returning"}, - {noshrink, undefined, "noshrink", boolean, - "instructs PropEr to not attempt to shrink any failing test cases"}, - {constraint_tries, undefined, "constraint_tries", integer, - "specifies the maximum number of tries before the generator subsystem " - "gives up on producing an instance that satisfies a ?SUCHTHAT " - "constraint"}, - {spec_timeout, undefined, "spec_timeout", integer, - "duration, in milliseconds, after which PropEr considers an input " - "to be failing"}, - {any_to_integer, undefined, "any_to_integer", boolean, - "converts instances of the any() type to integers in order to speed " - "up execution"}, - {on_output, undefined, "on_output", string, - "specifies a binary function '{Mod,Fun}', similar to io:format/2, " - "to be used for all output printing"}, - {sys_config, undefined, "sys_config", string, - "config file to load before starting tests"} - ]. - -handle_opts(State) -> - {CliOpts, _} = rebar_state:command_parsed_args(State), - ConfigOpts = rebar_state:get(State, proper_opts, []), - {fill_defaults(rebar3_opts(merge_opts(ConfigOpts, CliOpts))), - proper_opts(merge_opts(ConfigOpts, proper_opts(CliOpts)))}. - -fill_defaults(Opts) -> - [{dir, "test"} || proplists:get_value(dir, Opts) =:= undefined] ++ - [{mods, any} || proplists:get_value(mods, Opts) =:= undefined] ++ - [{properties, any} || proplists:get_value(properties, Opts) =:= undefined] - ++ Opts. - -rebar3_opts([]) -> - []; -rebar3_opts([{dir, Dir} | T]) -> - [{dir, Dir} | rebar3_opts(T)]; -rebar3_opts([{module, Mods} | T]) -> - [{module, maybe_parse_csv(Mods)} | rebar3_opts(T)]; -rebar3_opts([{properties, Props} | T]) -> - [{properties, maybe_parse_csv(Props)} | rebar3_opts(T)]; -rebar3_opts([{retry, Retry} | T]) -> - [{retry, Retry} | rebar3_opts(T)]; -rebar3_opts([{regressions, Retry} | T]) -> - [{regressions, Retry} | rebar3_opts(T)]; -rebar3_opts([{sys_config, Config} | T]) -> - [{sys_config, Config} | rebar3_opts(T)]; -rebar3_opts([{store, Retry} | T]) -> - [{store, Retry} | rebar3_opts(T)]; -rebar3_opts([_ | T]) -> - rebar3_opts(T). - -proper_opts([]) -> []; -proper_opts([{verbose, true} | T]) -> [verbose | proper_opts(T)]; -proper_opts([{verbose, false} | T]) -> [quiet | proper_opts(T)]; -proper_opts([{long_result, true} | T]) -> [long_result | proper_opts(T)]; -proper_opts([{long_result, false} | T]) -> proper_opts(T); -proper_opts([{noshrink, true} | T]) -> [noshrink | proper_opts(T)]; -proper_opts([{noshrink, false} | T]) -> proper_opts(T); -proper_opts([{any_to_integer, true} | T]) -> [any_to_integer | proper_opts(T)]; -proper_opts([{any_to_integer, false} | T]) -> proper_opts(T); -proper_opts([{on_output, {Mod, Fun}} | T]) -> - [{on_output, fun Mod:Fun/2} | proper_opts(T)]; -proper_opts([{on_output, MFStr} | T]) when is_list(MFStr) -> - case on_output(MFStr) of - undefined -> proper_opts(T); - Fun -> [{on_output, Fun} | proper_opts(T)] - end; -%% those are rebar3-only options -proper_opts([{dir,_} | T]) -> proper_opts(T); -proper_opts([{module,_} | T]) -> proper_opts(T); -proper_opts([{properties,_} | T]) -> proper_opts(T); -proper_opts([{cover,_} | T]) -> proper_opts(T); -proper_opts([{retry,_} | T]) -> proper_opts(T); -proper_opts([{regressions,_} | T]) -> proper_opts(T); -proper_opts([{sys_config,_} | T]) -> proper_opts(T); -proper_opts([{store,_} | T]) -> proper_opts(T); -%% fall-through -proper_opts([H|T]) -> [H | proper_opts(T)]. - -merge_opts(Old, New) -> - rebar_utils:tup_umerge(New, Old). - -maybe_parse_csv(Data) -> - case is_atom_list(Data) of - true -> [atom_to_list(D) || D <- Data]; - false -> parse_csv(Data) - end. - -is_atom_list([]) -> true; -is_atom_list([H|T]) when is_atom(H) -> is_atom_list(T); -is_atom_list(_) -> false. - -parse_csv(IoData) -> - re:split(IoData, ", *", [{return, list}]). - --spec on_output(MFStr :: string()) -> 'undefined' | Fun when - Fun :: fun((Format :: io:format(), Data :: [term()]) -> ok). -on_output(MFStr) -> - case erl_scan:string(MFStr ++ ".") of - {ok, Tokens, _EndLocation} -> - case erl_parse:parse_term(Tokens) of - {ok, {Mod, Fun}} -> fun Mod:Fun/2; - _ -> undefined - end; - _ -> undefined - end. - -app_paths(State) -> - Apps = rebar_state:project_apps(State), - [rebar_app_info:ebin_dir(App) || App <- Apps, - not rebar_app_info:is_checkout(App)]. - -sys_config_list(CmdOpts, CfgOpts) -> - CmdSysConfigs = split_string(proplists:get_value(sys_config, CmdOpts, "")), - case proplists:get_value(sys_config, CfgOpts, []) of - [H | _]=Configs when is_list(H) -> - Configs ++ CmdSysConfigs; - [] -> - CmdSysConfigs; - Configs -> - [Configs | CmdSysConfigs] - end. - -split_string(String) -> - string:tokens(String, [$,]). - -make_absolute_path(Path) -> - case filename:pathtype(Path) of - absolute -> - Path; - relative -> - {ok, Dir} = file:get_cwd(), - filename:join([Dir, Path]); - volumerelative -> - Volume = hd(filename:split(Path)), - {ok, Dir} = file:get_cwd(Volume), - filename:join([Dir, Path]) - end. - -run_pre_hooks(State) -> - Providers = rebar_state:providers(State), - Cwd = rebar_dir:get_cwd(), - rebar_hooks:run_project_and_app_hooks(Cwd, pre, ?PROVIDER, Providers, State). - -run_post_hooks(_, {ok, State}) -> run_post_hooks_(State); -run_post_hooks(State, _) -> run_post_hooks_(State). - -run_post_hooks_(State) -> - Providers = rebar_state:providers(State), - Cwd = rebar_dir:get_cwd(), - rebar_hooks:run_project_and_app_hooks(Cwd, post, ?PROVIDER, Providers, State), - %% reset code paths for the plugin if we want to handle our own errors - %% since the rebar3 hooks drop them by default - PluginDepsPaths = lists:usort(rebar_state:code_paths(State, all_plugin_deps)), - code:add_pathsa(PluginDepsPaths), - ok. - -format_doc(Mod, Fun) -> - try Mod:Fun(doc) of - IoData -> [" (", IoData, $)] - catch - error:E when E == undef; E == function_clause -> - rebar_api:debug("~p:~p(doc) not found; omitting docstring", - [Mod,Fun]), - [] - end. - diff --git a/_build/default/plugins/verl/.rebar3/rebar_compiler_erl/source.dag b/_build/default/plugins/verl/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index cc6e98d9ef..0000000000 Binary files a/_build/default/plugins/verl/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/default/plugins/verl/LICENSE b/_build/default/plugins/verl/LICENSE deleted file mode 100644 index 50e0a132cd..0000000000 --- a/_build/default/plugins/verl/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2019, Bryan Paxton . - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/_build/default/plugins/verl/README.md b/_build/default/plugins/verl/README.md deleted file mode 100644 index 754ec7218b..0000000000 --- a/_build/default/plugins/verl/README.md +++ /dev/null @@ -1,101 +0,0 @@ -verl [![Hex Version](https://img.shields.io/hexpm/v/verl.svg)](https://hex.pm/packages/verl) [![CircleCI](https://circleci.com/gh/jelly-beam/verl.svg?style=svg)](https://circleci.com/gh/jelly-beam/verl) [![codecov](https://codecov.io/gh/jelly-beam/verl/branch/master/graph/badge.svg)](https://codecov.io/gh/jelly-beam/verl) -===== - -SemVer 2.0 version and requirements parsing, matching, and comparisons. - -All parsing of versions and requirements adhere to the [SemVer 2.0 schema](http://semver.org/) - - -Build ------ - - $ rebar3 compile - -Usage ------- - -### Comparisons - 1> verl:compare(<<"1.0.0">>, <<"1.0.1">>). - lt - 2> verl:compare(<<"1.0.0">>, <<"1.0.0">>). - eq - 3> verl:compare(<<"2.0.0">>, <<"1.0.0">>). - gt - 4> verl:compare(<<"1.0.0-pre">>, <<"1.0.0">>). - lt - 5> verl:compare(<<"1.0.0">>, <<"1.0.0-pre">>). - gt - -### Version, Requirements, and matching - -#### matching - 1> verl:is_match(<<"1.0.0">>, <<"~> 1.0.0">>). - true - 2> verl:is_match(<<"1.0.0">>, <<"~> 2.0.0">>). - false - 3> verl:is_match(<<"3.2.0">>, <<"~> 3.0.0">>). - false - 4> verl:is_match(<<"3.2.0">>, <<"~> 3.0">>). - true - -#### Compiled requirements for ludicious speed matching - 1> {ok, Req} = verl:parse_requirement(<<"~> 3.0">>). - {ok,#{compiled => false, - string => <<"~> 3.0">>, - matchspec => [{{'$1','$2','$3','$4','$5'}...}], - string => <<"~> 3.0">>}} - 2> verl:is_match(<<"3.0.0-dev">>, Req). - false - 3> verl:is_match(<<"1.2.3">>, Req). - false - 4> verl:is_match(<<"3.1.0">>, Req). - true - -#### Version parsing - - 1> verl:parse(<<"1.2.3">>). - #{build => undefined,major => 1,minor => 2,patch => 3, - pre => []} - 2> verl:parse(<<"1.2.3+build">>). - #{build => <<"build">>,major => 1,minor => 2,patch => 3, - pre => []} - 3> verl:parse(<<"1.2.3-pre+build">>). - #{build => <<"build">>,major => 1,minor => 2,patch => 3, - pre => [<<"pre">>]} - 4> verl:parse(<<"1">>). - {error, invalid_version} - 5> verl:parse(<<"2">>). - {error, invalid_version} - -Don't want a map? Use the verl_parser module... - - 1> verl_parser:parse_version(<<"1.2.3">>). - {ok,{1,2,3,[],[]}} - 2> verl_parser:parse_version(<<"1.2.3+build">>). - {ok,{1,2,3,[],[<<"build">>]}} - 3> verl_parser:parse_version(<<"1.2.3-pre+build">>). - {ok,{1,2,3,[<<"pre">>],[<<"build">>]}} - 4> verl_parser:parse_version(<<"1">>). - {error, invalid_version} - -##### Requirements parsing - - 1> verl:parse_requirement(<<"~> 2.1.0-dev">>). - {ok,#{compiled => false, - string => <<"~> 2.1.0-dev">>, - matchspec => - [{{'$1','$2','$3','$4','$5'}...] }} - 2> verl:parse_requirement(<<"~> 2.1.0-">>). - {error,invalid_requirement} - -Don't want a map? User the verl_parser_module... - - 1> verl_parser:parse_requirement(<<"~> 2.1.0-dev">>). - {ok, [{{'$1','$2','$3','$4','$5'}...]} - 2> verl:parse_requirement(<<"~> 2.1.0-">>). - {error,invalid_requirement} - -Credits -------- - - All credit goes to the Elixir team and contributors to Version and Version.Parser in the Elixir standard lib for the - algorithm and original implementation. diff --git a/_build/default/plugins/verl/hex_metadata.config b/_build/default/plugins/verl/hex_metadata.config deleted file mode 100644 index 4515bdafd1..0000000000 --- a/_build/default/plugins/verl/hex_metadata.config +++ /dev/null @@ -1,13 +0,0 @@ -{<<"app">>,<<"verl">>}. -{<<"build_tools">>,[<<"rebar3">>]}. -{<<"description">>, - <<"SemVer2 version and requirements parsing, matching, and comparison">>}. -{<<"files">>, - [<<"src/verl.app.src">>,<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>, - <<"rebar.lock">>,<<"src/verl.erl">>,<<"src/verl.hrl">>, - <<"src/verl_parser.erl">>]}. -{<<"licenses">>,[<<"Apache 2.0">>]}. -{<<"links">>,[{<<"Github">>,<<"https://hub.fastgit.org/jelly-beam/verl">>}]}. -{<<"name">>,<<"verl">>}. -{<<"requirements">>,[]}. -{<<"version">>,<<"1.0.2">>}. diff --git a/_build/default/plugins/verl/rebar.config b/_build/default/plugins/verl/rebar.config deleted file mode 100644 index f69ffc0709..0000000000 --- a/_build/default/plugins/verl/rebar.config +++ /dev/null @@ -1,17 +0,0 @@ -{erl_opts, [debug_info]}. -{deps, []}. -{project_plugins, [rebar3_proper, rebar3_hex, covertool]}. -{profiles, [{test, [{deps, [{proper, "1.2.0"}]}]}]}. - -{xref_ignores, [verl, {verl_parser, parse_version, 2}]}. - -{alias, [{quick_test, [{proper, "--cover --numtests=3"}, - {eunit, "--cover"}, - {cover, "-v"}]}, - {test, [{ct, "-c"}, {proper, "--cover"}, {eunit, "--cover"}, {cover, "-v"}]}, - {check, [{proper, "--cover --numtests=3"}, - {eunit, "--cover"}, - xref, dialyzer, cover]}]}. - -{xref_checks,[undefined_function_calls,undefined_functions,locals_not_used, - deprecated_function_calls,deprecated_functions]}. diff --git a/_build/default/plugins/verl/src/verl.app.src b/_build/default/plugins/verl/src/verl.app.src deleted file mode 100644 index bc0a82d0cc..0000000000 --- a/_build/default/plugins/verl/src/verl.app.src +++ /dev/null @@ -1,11 +0,0 @@ -{application,verl, - [{description,"SemVer2 version and requirements parsing, matching, and comparison"}, - {vsn,"1.0.2"}, - {organization,"jellybeam"}, - {registered,[]}, - {applications,[kernel,stdlib]}, - {env,[]}, - {modules,[]}, - {extra,{maintainers,["Bryan Paxton"]}}, - {licenses,["Apache 2.0"]}, - {links,[{"Github","https://hub.fastgit.org/jelly-beam/verl"}]}]}. diff --git a/_build/default/plugins/verl/src/verl.erl b/_build/default/plugins/verl/src/verl.erl deleted file mode 100644 index f8b1491afb..0000000000 --- a/_build/default/plugins/verl/src/verl.erl +++ /dev/null @@ -1,203 +0,0 @@ --module(verl). - --export([ - compare/2 - , is_match/2 - , is_match/3 - , parse/1 - , parse_requirement/1 - , compile_requirement/1]). - --type version() :: binary(). --type requirement() :: binary(). --opaque major() :: non_neg_integer(). --opaque minor() :: non_neg_integer(). --opaque patch() :: non_neg_integer(). --opaque pre() :: [binary() | non_neg_integer()]. --opaque build() :: binary() | undefined. --opaque version_t() :: #{ - major => major() - , minor => minor() - , patch => patch() - , pre => pre() - , build => [build()]}. --opaque requirement_t() :: #{ - string => requirement(), - matchspec => list(), - compiled => boolean() - }. - --opaque compiled_requirement() :: #{ - compiled => true, - matchspec => ets:comp_match_spec(), - string => requirement()}. - --export_type([version/0, requirement/0, major/0, minor/0, patch/0, pre/0, - build/0, version_t/0, requirement_t/0, compiled_requirement/0]). - -%%% @doc -%%% Compare two version returing whether first argument is greater, equal, or -%%% less than than second argument. -%%% @end --spec compare(version(), version()) -> gt | eq | lt | {error, invalid_version}. -compare(Version1, Version2) -> - ver_cmp(to_matchable(Version1,true), to_matchable(Version2, true)). - -%%% @doc -%%% Parses a semantic version returing a version_t() or {error, invalid_version} -%%% @end --spec parse(version()) -> version_t() | {error, invalid_version}. -parse(Str) -> - build_version(Str). - -%%% @doc -%%% Parses a semantic version requirement, returns a requirement_t() -%%% @end --spec parse_requirement(requirement()) -> - {ok, requirement_t()} | {error, invalid_requirement}. -parse_requirement(Str) -> - case verl_parser:parse_requirement(Str) of - {ok, Spec} -> - {ok, #{string => Str, matchspec => Spec, compiled => false}}; - {error, invalid_requirement} -> - {error, invalid_requirement} - end. - -%%% @doc -%%% Compiles a version requirement as returned by parse_requirement for faster -%%% matches. -%%% @end --spec compile_requirement(requirement_t()) -> compiled_requirement(). -compile_requirement(Req) when is_map(Req) -> - Ms = ets:match_spec_compile(maps:get(matchspec, Req)), - maps:put(compiled, true, maps:put(matchspec, Ms, Req)). - -%%% @doc -%%% Returns true if the dependency is in range of the requirement, otherwise -%%% false. -%%% @end --spec is_match(version() | version_t(), requirement() | requirement_t()) -> boolean() | {error, badarg | invalid_requirement | invalid_version}. -is_match(Version, Requirement) -> - is_match(Version, Requirement, []). - -%%% @doc -%%% Exactly like is_match/2 but takes an options argument. -%%% @end -is_match(Version, Requirement, Opts) when is_binary(Version) andalso is_binary(Requirement) -> - case build_version(Version) of - {ok, Ver} -> - case build_requirement(Requirement) of - {ok, Req} -> - is_match(Ver, Req, Opts); - {error, invalid_requirement} -> - {error, invalid_requirement} - end; - {error, invalid_version} -> - {error, invalid_version} - end; -is_match(Version, Requirement, Opts) when is_binary(Version) andalso is_map(Requirement) -> - case build_version(Version) of - {ok, Ver} -> - is_match(Ver, Requirement, Opts); - {error, invalid_version} -> - {error, invalid_version} - end; -is_match(Version, Requirement, Opts) when is_map(Version) andalso is_binary(Requirement) -> - case build_requirement(Requirement) of - {ok, Req} -> - is_match(Version, Req, Opts); - {error, invalid_requirement} -> - {error, invalid_requirement} - end; -is_match(Version, #{matchspec := Spec, compiled := false} = R, Opts) when is_map(R) -> - AllowPre = proplists:get_value(allow_pre, Opts, true), - {ok, Result} = ets:test_ms(to_matchable(Version, AllowPre), Spec), - Result /= false; -is_match(Version, #{matchspec := Spec, compiled := true} = R, Opts) when - is_map(Version) andalso is_map(R) -> - AllowPre = proplists:get_value(allow_pre, Opts, true), - ets:match_spec_run([to_matchable(Version, AllowPre)], Spec) /= []. - -to_matchable(#{major := Major, minor := Minor, patch := Patch, pre := Pre}, AllowPre) -> - {Major, Minor, Patch, Pre, AllowPre}; -to_matchable(String, AllowPre) when is_binary(String) -> - case verl_parser:parse_version(String) of - {ok, {Major, Minor, Patch, Pre, _Build}} -> - {Major, Minor, Patch, Pre, AllowPre}; - {error, invalid_version} -> - {error, invalid_version} - end. - -%% private -%% -build_version(Version) -> - case verl_parser:parse_version(Version) of - {ok, {Major, Minor, Patch, Pre, Build}} -> - {ok, #{major => Major, - minor => Minor, - patch => Patch, - pre => Pre, - build => build_string(Build)}}; - {error, invalid_version} -> - {error, invalid_version} - end. - -build_requirement(Str) -> - case verl_parser:parse_requirement(Str) of - {ok, Spec} -> - {ok, #{string => Str, matchspec => Spec, compiled => false}}; - {error, invalid_requirement} -> - {error, invalid_requirement} - end. - -build_string(Build) -> - case Build of - [] -> undefined; - _ -> binary:list_to_bin(Build) - end. - -ver_cmp({Maj1, Min1, Patch1, Pre1, _}, {Maj2, Min2, Patch2, Pre2, _}) -> - case {Maj1, Min1, Patch1} > {Maj2, Min2, Patch2} of - true -> - gt; - false -> - case {Maj1, Min1, Patch1} < {Maj2, Min2, Patch2} of - true -> - lt; - false -> - test_pre(Pre1, Pre2) - end - end; -ver_cmp(_, _) -> {error, invalid_version}. - -test_pre(Pre1, Pre2) -> - case pre_is_eq(Pre1, Pre2) of - true -> - gt; - false -> - case pre_is_eq(Pre2, Pre1) of - true -> - lt; - false -> - pre_cmp(Pre1, Pre2) - end - end. - -pre_cmp(Pre1, Pre2) -> - case Pre1 > Pre2 of - true -> - gt; - false -> - case Pre1 < Pre2 of - true -> - lt; - false -> - eq - end - end. - -pre_is_eq(Pre1, Pre2) -> - case Pre1 == [] of - false -> false; - true -> Pre2 /= [] - end. diff --git a/_build/default/plugins/verl/src/verl.hrl b/_build/default/plugins/verl/src/verl.hrl deleted file mode 100644 index 63df2a3ac0..0000000000 --- a/_build/default/plugins/verl/src/verl.hrl +++ /dev/null @@ -1 +0,0 @@ --define(VERL_VERSION, "1.0.2"). diff --git a/_build/default/plugins/verl/src/verl_parser.erl b/_build/default/plugins/verl/src/verl_parser.erl deleted file mode 100644 index 8134cc3be2..0000000000 --- a/_build/default/plugins/verl/src/verl_parser.erl +++ /dev/null @@ -1,408 +0,0 @@ --module(verl_parser). - --export([parse_requirement/1, parse_version/1, parse_version/2]). - --type operator() :: '!=' | '&&' | '<' | '<=' | '==' | '>' | '>=' | '||' | '~>' | bitstring(). - --spec parse_version(verl:version()) -> - {ok, {verl:major(), verl:minor(), verl:patch(), [verl:pre()], [verl:build()]}} | {error, invalid_version}. -parse_version(Str) -> parse_version(Str, false). - --spec parse_version(verl:version(), boolean()) -> - {ok,{verl:major(),verl:minor(), verl:patch(), [verl:pre()],[verl:build()]}} | {error, invalid_version}. -parse_version(Str, Approximate) when is_binary(Str) -> - try parse_and_convert(Str, Approximate) of - {ok, {_, _, undefined, _, _}} -> - - {error, invalid_version}; - {ok, _} = V -> - V; - {error, invalid_version} -> - {error, invalid_version} - catch - error:{badmatch, {error, T}} when T =:= invalid_version - orelse T =:= nan - orelse T =:= bad_part - orelse T =:= leading_zero -> - {error, invalid_version} - end. - --spec parse_requirement(verl:requirement()) -> {ok, ets:match_spec()} | {error, invalid_requirement}. -parse_requirement(Source) -> - Lexed = lexer(Source, []), - to_matchspec(Lexed). - --spec lexer(binary(), [operator()]) -> [operator()]. -lexer(<<">=", Rest/binary>>, Acc) -> - lexer(Rest, ['>=' | Acc]); -lexer(<<"<=", Rest/binary>>, Acc) -> - lexer(Rest, ['<=' | Acc]); -lexer(<<"~>", Rest/binary>>, Acc) -> - lexer(Rest, ['~>' | Acc]); -lexer(<<">", Rest/binary>>, Acc) -> - lexer(Rest, ['>' | Acc]); -lexer(<<"<", Rest/binary>>, Acc) -> - lexer(Rest, ['<' | Acc]); -lexer(<<"==", Rest/binary>>, Acc) -> - lexer(Rest, ['==' | Acc]); -lexer(<<"!=", Rest/binary>>, Acc) -> - lexer(Rest, ['!=' | Acc]); -lexer(<<"!", Rest/binary>>, Acc) -> - lexer(Rest, ['!=' | Acc]); -lexer(<<" or ", Rest/binary>>, Acc) -> - lexer(Rest, ['||' | Acc]); -lexer(<<" and ", Rest/binary>>, Acc) -> - lexer(Rest, ['&&' | Acc]); -lexer(<<" ", Rest/binary>>, Acc) -> - lexer(Rest, Acc); -lexer(<>, []) -> - lexer(Rest, [<>, '==']); -lexer(<>, [Head | Acc]) -> - Acc1 = case Head of - Head when is_binary(Head) -> - [<> | Acc]; - Head when Head =:= '&&' orelse Head =:= '||' -> - [<>, '==', Head | Acc]; - _Other -> - [<>, Head | Acc] - end, - lexer(Body, Acc1); -lexer(<<>>, Acc) -> - lists:reverse(Acc). - --spec parse_condition(verl:version()) -> {integer(),integer(),'undefined' | integer(),[binary() | integer()]}. -parse_condition(Version) -> parse_condition(Version, false). - --spec parse_condition(verl:version(), boolean()) -> {integer(),integer(),'undefined' | integer(),[binary() | integer()]}. -parse_condition(Version, Approximate) -> - try case parse_and_convert(Version, Approximate) of - {ok, {Major, Minor, Patch, Pre, _Bld}} -> - {Major, Minor, Patch, Pre}; - _ -> - throw(invalid_matchspec) - end - catch - error:{badmatch, {error, T}} when T =:= invalid_version - orelse T =:= nan - orelse T =:= bad_part - orelse T =:= leading_zero -> - throw(invalid_matchspec) - end. - --spec approximate_upper({integer(),integer(),'undefined' | integer(),[binary() | integer()]}) -> - {integer(),integer(),0,[0,...]}. -approximate_upper(Version) -> - case Version of - {Major, _Minor, undefined, _} -> - {Major + 1, 0, 0, [0]}; - {Major, Minor, _Patch, _Pre} -> - {Major, Minor + 1, 0, [0]} - end. - --spec matchable_to_string({integer(),integer(),'undefined' | integer(),[binary() | integer()]}) -> binary(). -matchable_to_string({Major, Minor, Patch, Pre}) -> - Patch1 = case Patch of - P when P =:= undefined orelse P =:= false -> - <<"0">>; - _ -> - maybe_to_string(Patch) - end, - Pre1 = case Pre == [] of - true -> - <<>>; - false -> - case Pre of - [0] -> - <<"-0">>; - _ -> - Pre0 = maybe_to_string(Pre), - << <<"-">>/binary, Pre0/binary >> - end - end, - Major1 = maybe_to_string(Major), - Minor1 = maybe_to_string(Minor), - Patch2 = maybe_to_string(Patch1), - Joined = join_bins([Major1, Minor1, Patch2], <<".">>), - << Joined/binary, Pre1/binary >>. - --spec pre_condition('<' | '>',[binary() | integer()]) -> tuple(). -pre_condition('>', Pre) -> - PreLength = length(Pre), - {'orelse', - {'andalso', {'==', {length, '$4'}, 0}, - {const, PreLength /= 0}}, - {'andalso', {const, PreLength /= 0}, - {'orelse', {'>', {length, '$4'}, PreLength}, - {'andalso', {'==', {length, '$4'}, PreLength}, - {'>', '$4', {const, Pre}}}}}}; -pre_condition('<', Pre) -> - PreLength = length(Pre), - {'orelse', - {'andalso', {'/=', {length, '$4'}, 0}, - {const, PreLength == 0}}, - {'andalso', {'/=', {length, '$4'}, 0}, - {'orelse', {'<', {length, '$4'}, PreLength}, - {'andalso', {'==', {length, '$4'}, PreLength}, - {'<', '$4', {const, Pre}}}}}}. - --spec no_pre_condition([binary() | integer()]) -> tuple(). -no_pre_condition([]) -> - {'orelse', '$5', {'==', {length, '$4'}, 0}}; -no_pre_condition(_) -> - {const, true}. - --spec to_matchspec([operator(), ...]) -> - {error, invalid_requirement} | {ok, ets:match_spec()}. -to_matchspec(Lexed) -> - try case is_valid_requirement(Lexed) of - true -> - First = to_condition(Lexed), - Rest = lists:nthtail(2, Lexed), - {ok, [{{'$1', '$2', '$3', '$4', '$5'}, [to_condition(First, Rest)], ['$_']}]}; - false -> - {error, invalid_requirement} - end - catch - invalid_matchspec -> {error, invalid_requirement} - end. - --spec to_condition([iodata(), ...]) -> tuple(). -to_condition(['==', Version | _]) -> - Matchable = parse_condition(Version), - main_condition('==', Matchable); -to_condition(['!=', Version | _]) -> - Matchable = parse_condition(Version), - main_condition('/=', Matchable); -to_condition(['~>', Version | _]) -> - From = parse_condition(Version, true), - To = approximate_upper(From), - {'andalso', - to_condition(['>=', matchable_to_string(From)]), - to_condition(['<', matchable_to_string(To)])}; -to_condition(['>', Version | _]) -> - {Major, Minor, Patch, Pre} = - parse_condition(Version), - {'andalso', - {'orelse', - main_condition('>', {Major, Minor, Patch}), - {'andalso', - main_condition('==', {Major, Minor, Patch}), - pre_condition('>', Pre)}}, - no_pre_condition(Pre)}; -to_condition(['>=', Version | _]) -> - Matchable = parse_condition(Version), - {'orelse', main_condition('==', Matchable), - to_condition(['>', Version])}; -to_condition(['<', Version | _]) -> - {Major, Minor, Patch, Pre} = - parse_condition(Version), - {'orelse', - main_condition('<', {Major, Minor, Patch}), - {'andalso', - main_condition('==', {Major, Minor, Patch}), - pre_condition('<', Pre)}}; -to_condition(['<=', Version | _]) -> - Matchable = parse_condition(Version), - {'orelse', main_condition('==', Matchable), - to_condition(['<', Version])}. - - --spec to_condition(tuple(), list()) -> tuple(). -to_condition(Current, []) -> Current; -to_condition(Current, - ['&&', Operator, Version | Rest]) -> - to_condition({'andalso', Current, - to_condition([Operator, Version])}, - Rest); -to_condition(Current, - ['||', Operator, Version | Rest]) -> - to_condition({'orelse', Current, - to_condition([Operator, Version])}, - Rest). - --spec main_condition(any(), tuple()) -> tuple(). -main_condition(Op, Version) - when tuple_size(Version) == 3 -> - {Op, {{'$1', '$2', '$3'}}, {const, Version}}; -main_condition(Op, Version) - when tuple_size(Version) == 4 -> - {Op, {{'$1', '$2', '$3', '$4'}}, - {const, Version}}. - - --spec bisect(binary(),binary(), list()) -> [binary() | undefined, ...]. - -bisect(Str, Delim, Opts) -> - [First | Rest ] = binary:split(Str, [Delim], Opts), - Rest1 = case Rest of - [] -> - undefined; - _ -> - join_bins(Rest, Delim) - end, - [First, Rest1]. - --spec has_leading_zero(error | undefined | binary() | [binary()]) -> boolean(). -has_leading_zero(<<48/integer, _/integer, _/binary>>) -> - true; -has_leading_zero(_) -> - false. - --spec is_valid_identifier(any()) -> boolean(). -is_valid_identifier(<>) - when is_integer(Char) andalso - Char >= 48 andalso Char =< 57; - is_integer(Char) andalso - Char >= 97 andalso Char=< 122; - is_integer(Char) andalso - Char >= 65 andalso Char =< 90; - Char == 45 -> - is_valid_identifier(Rest); -is_valid_identifier(<<>>) -> - true; -is_valid_identifier(_) -> - false. - --spec join_bins([binary(), ...], binary()) -> binary(). -join_bins(List, Delim) -> - lists:foldl(fun(Bin, Acc) -> - case bit_size(Acc) of - N when N > 0 -> - <>; - _ -> - Bin - end - end, <<>>, List). - --spec maybe_patch(undefined | binary() | integer(), boolean()) -> - {ok, undefined | integer()}. -maybe_patch(undefined, true) -> - {ok, undefined}; -maybe_patch(Patch, _) -> - to_digits(Patch). - --spec parse_and_convert(verl:version(), boolean()) -> - {error,invalid_version} | {ok,{integer(),integer(),'undefined' | - integer(),[binary() | - integer()],[binary()]}}. -parse_and_convert(Str, Approx) -> - [VerPre, Build] = bisect(Str, <<"+">>, [global]), - [Ver, Pre] = bisect(VerPre, <<"-">>, []), - [Maj1, Min1, Patch1, Other] = split_ver(Ver), - case Other of - undefined -> - {ok, Maj2} = to_digits(Maj1), - {ok, Min2} = to_digits(Min1), - {ok, Patch2} = maybe_patch(Patch1, Approx), - {ok, PreParts} = opt_dot_separated(Pre), - {ok, PreParts1} = parts_to_integers(PreParts, []), - {ok, Build2} = opt_dot_separated(Build), - {ok, {Maj2, Min2, Patch2, PreParts1, Build2}}; - _ -> - {error, invalid_version} - end. - --spec parse_digits('error' | 'undefined' | binary() | [binary()],bitstring()) -> {'error','nan'} | {'ok',integer()}. -parse_digits(<>, Acc) - when is_integer(Char) andalso Char >= 48 andalso Char =< 57 -> - parse_digits(Rest, <>); -parse_digits(<<>>, Acc) when byte_size(Acc) > 0 -> - {ok, binary_to_integer(Acc)}; -parse_digits(_, _) -> {error, nan}. - --spec parts_to_integers([binary()],[binary() | integer()]) -> {'error','nan'} | {'ok',[binary() | integer()]}. -parts_to_integers([Part | Rest], Acc) -> - case parse_digits(Part, <<>>) of - {ok, Int} -> - case has_leading_zero(Part) of - P when P =:= undefined orelse P =:= false -> - parts_to_integers(Rest, [Int | Acc]); - _ -> {error, nan} - end; - {error, nan} -> - parts_to_integers(Rest, [Part | Acc]) - end; -parts_to_integers([], Acc) -> - {ok, lists:reverse(Acc)}. - --spec opt_dot_separated('undefined' | binary()) -> {'error','bad_part'} | {'ok',[binary()]}. -opt_dot_separated(undefined) -> {ok, []}; -opt_dot_separated(Str) -> - Parts = binary:split(Str, <<".">>, [global]), - Fun = fun(P) -> - case P /= <<>> of - false -> false; - true -> is_valid_identifier(P) - end - end, - case lists:all(Fun, Parts) of - P when P =:= undefined orelse P =:= false -> - {error, bad_part}; - _ -> - {ok, Parts} - end. - --spec split_ver(binary()) -> ['error' | 'undefined' | binary() | [binary()],...]. -split_ver(Str) -> - case binary:split(Str, [<<".">>], [global]) of - [Maj0, Min0] -> - [Maj0, Min0, undefined, undefined]; - [Maj, Min, P] -> - [Maj, Min, P, undefined]; - [Major, Minor, Patch | Rest] -> - [Major, Minor, Patch, Rest]; - _ -> - [error, error, error, error] - end. - - --spec to_digits('error' | 'undefined' | binary() | [binary()]) -> - {'error','leading_zero' | 'nan'} | {'ok',integer()}. -to_digits(Str) -> - case has_leading_zero(Str) of - S when S =:= undefined orelse S =:= false -> - parse_digits(Str, <<>>); - true -> - {error, leading_zero} - end. - --spec maybe_to_string(binary() | [binary() | byte()] | integer()) -> binary(). -maybe_to_string(Part) -> - case Part of - Rewrite when is_binary(Rewrite) -> - Rewrite; - Int when is_integer(Int) -> - integer_to_binary(Int); - Rewrite when is_list(Rewrite)-> - list_to_binary(Rewrite) - end. - --spec is_valid_requirement([operator(), ...]) -> boolean(). -is_valid_requirement([]) -> false; -is_valid_requirement([A | Next]) -> - is_valid_requirement(A, Next). - --spec is_valid_requirement(operator(), [operator()]) -> boolean(). -is_valid_requirement(A, []) - when is_binary(A) -> - true; -is_valid_requirement(A, [B | Next]) - when (is_atom(A) andalso - is_atom(B)) - andalso (A =:= '&&' orelse A =:= '||') -> - is_valid_requirement(B, Next); -is_valid_requirement(A, [B | Next]) - when (is_binary(A) andalso - is_atom(B)) - andalso (B =:= '&&' orelse B =:= '||') -> - is_valid_requirement(B, Next); -is_valid_requirement(A, [B | Next]) - when (is_atom(A) andalso - is_binary(B)) - andalso (A =:= '&&' orelse A =:= '||') -> - is_valid_requirement(B, Next); -is_valid_requirement(A, [B | Next]) - when is_atom(A) andalso - is_binary(B) -> - is_valid_requirement(B, Next); -is_valid_requirement(_, _) -> false. diff --git a/_build/emqx/conf/acl.conf b/_build/emqx/conf/acl.conf deleted file mode 100644 index af2fb0dd11..0000000000 --- a/_build/emqx/conf/acl.conf +++ /dev/null @@ -1,26 +0,0 @@ -%%-------------------------------------------------------------------- -%% [ACL](https://docs.emqx.io/broker/v3/en/config.html) -%% -%% -type(who() :: all | binary() | -%% {ipaddr, esockd_access:cidr()} | -%% {client, binary()} | -%% {user, binary()}). -%% -%% -type(access() :: subscribe | publish | pubsub). -%% -%% -type(topic() :: binary()). -%% -%% -type(rule() :: {allow, all} | -%% {allow, who(), access(), list(topic())} | -%% {deny, all} | -%% {deny, who(), access(), list(topic())}). -%%-------------------------------------------------------------------- - -{allow, {user, "dashboard"}, subscribe, ["$SYS/#"]}. - -{allow, {ipaddr, "127.0.0.1"}, pubsub, ["$SYS/#", "#"]}. - -{deny, all, subscribe, ["$SYS/#", {eq, "#"}]}. - -{allow, all}. - diff --git a/_build/emqx/conf/emqx.conf b/_build/emqx/conf/emqx.conf deleted file mode 100644 index ce07623927..0000000000 --- a/_build/emqx/conf/emqx.conf +++ /dev/null @@ -1,2177 +0,0 @@ -##==================================================================== -## EMQ X Configuration R4.0 -##==================================================================== - -##-------------------------------------------------------------------- -## Cluster -##-------------------------------------------------------------------- - -## Cluster name. -## -## Value: String -cluster.name = emqxcl - -## Specify the erlang distributed protocol. -## -## Value: Enum -## - inet_tcp: the default; handles TCP streams with IPv4 addressing. -## - inet6_tcp: handles TCP with IPv6 addressing. -## - inet_tls: using TLS for Erlang Distribution. -## -## vm.args: -proto_dist inet_tcp -cluster.proto_dist = inet_tcp - -## Cluster auto-discovery strategy. -## -## Value: Enum -## - manual: Manual join command -## - static: Static node list -## - mcast: IP Multicast -## - dns: DNS A Record -## - etcd: etcd -## - k8s: Kubernetes -## -## Default: manual -cluster.discovery = manual - -## Enable cluster autoheal from network partition. -## -## Value: on | off -## -## Default: on -cluster.autoheal = on - -## Autoclean down node. A down node will be removed from the cluster -## if this value > 0. -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 5m -cluster.autoclean = 5m - -##-------------------------------------------------------------------- -## Cluster using static node list - -## Node list of the cluster. -## -## Value: String -## cluster.static.seeds = emqx1@127.0.0.1,emqx2@127.0.0.1 - -##-------------------------------------------------------------------- -## Cluster using IP Multicast. - -## IP Multicast Address. -## -## Value: IP Address -## cluster.mcast.addr = 239.192.0.1 - -## Multicast Ports. -## -## Value: Port List -## cluster.mcast.ports = 4369,4370 - -## Multicast Iface. -## -## Value: Iface Address -## -## Default: 0.0.0.0 -## cluster.mcast.iface = 0.0.0.0 - -## Multicast Ttl. -## -## Value: 0-255 -## cluster.mcast.ttl = 255 - -## Multicast loop. -## -## Value: on | off -## cluster.mcast.loop = on - -##-------------------------------------------------------------------- -## Cluster using DNS A records. - -## DNS name. -## -## Value: String -## cluster.dns.name = localhost - -## The App name is used to build 'node.name' with IP address. -## -## Value: String -## cluster.dns.app = emqx - -##-------------------------------------------------------------------- -## Cluster using etcd - -## Etcd server list, seperated by ','. -## -## Value: String -## cluster.etcd.server = http://127.0.0.1:2379 - -## The prefix helps build nodes path in etcd. Each node in the cluster -## will create a path in etcd: v2/keys/// -## -## Value: String -## cluster.etcd.prefix = emqxcl - -## The TTL for node's path in etcd. -## -## Value: Duration -## -## Default: 1m, 1 minute -## cluster.etcd.node_ttl = 1m - -## Path to a file containing the client's private PEM-encoded key. -## -## Value: File -## cluster.etcd.ssl.keyfile = {{ platform_etc_dir }}/certs/client-key.pem - -## The path to a file containing the client's certificate. -## -## Value: File -## cluster.etcd.ssl.certfile = {{ platform_etc_dir }}/certs/client.pem - -## Path to the file containing PEM-encoded CA certificates. The CA certificates -## are used during server authentication and when building the client certificate chain. -## -## Value: File -## cluster.etcd.ssl.cacertfile = {{ platform_etc_dir }}/certs/ca.pem - -##-------------------------------------------------------------------- -## Cluster using Kubernetes - -## Kubernetes API server list, seperated by ','. -## -## Value: String -## cluster.k8s.apiserver = http://10.110.111.204:8080 - -## The service name helps lookup EMQ nodes in the cluster. -## -## Value: String -## cluster.k8s.service_name = emqx - -## The address type is used to extract host from k8s service. -## -## Value: ip | dns | hostname -## cluster.k8s.address_type = ip - -## The app name helps build 'node.name'. -## -## Value: String -## cluster.k8s.app_name = emqx - -## The suffix added to dns and hostname get from k8s service -## -## Value: String -## cluster.k8s.suffix = pod.cluster.local - -## Kubernetes Namespace -## -## Value: String -## cluster.k8s.namespace = default - -##-------------------------------------------------------------------- -## Node -##-------------------------------------------------------------------- - -## Node name. -## -## See: http://erlang.org/doc/reference_manual/distributed.html -## -## Value: @ -## -## Default: emqx@127.0.0.1 -node.name = emqx@127.0.0.1 - -## Cookie for distributed node communication. -## -## Value: String -node.cookie = emqxsecretcookie - -## Data dir for the node -## -## Value: Folder -node.data_dir = {{ platform_data_dir }} - -## Heartbeat monitoring of an Erlang runtime system. Comment the line to disable -## heartbeat, or set the value as 'on' -## -## Value: on -## -## vm.args: -heart -## node.heartbeat = on - -## Sets the number of threads in async thread pool. Valid range is 0-1024. -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: 0-1024 -## -## vm.args: +A Number -## node.async_threads = 4 - -## Sets the maximum number of simultaneously existing processes for this -## system if a Number is passed as value. -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: Number [1024-134217727] -## -## vm.args: +P Number -## node.process_limit = 2097152 - -## Sets the maximum number of simultaneously existing ports for this system. -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: Number [1024-134217727] -## -## vm.args: +Q Number -## node.max_ports = 1048576 - -## Sets the distribution buffer busy limit (dist_buf_busy_limit). -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: Number [1KB-2GB] -## -## vm.args: +zdbbl size -## node.dist_buffer_size = 8MB - -## Sets the maximum number of ETS tables. Note that mnesia and SSL will -## create temporary ETS tables. -## -## Value: Number -## -## vm.args: +e Number -## node.max_ets_tables = 262144 - -## Global GC Interval. -## -## Value: Duration -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 20s: 20 seconds -## -## Defaut: 15 minutes -node.global_gc_interval = 15m - -## Tweak GC to run more often. -## -## Value: Number [0-65535] -## -## vm.args: -env ERL_FULLSWEEP_AFTER Number -## node.fullsweep_after = 1000 - -## Crash dump log file. -## -## Value: Log file -node.crash_dump = {{ platform_log_dir }}/crash.dump - -## Specify SSL Options in the file if using SSL for Erlang Distribution. -## -## Value: File -## -## vm.args: -ssl_dist_optfile -## node.ssl_dist_optfile = {{ platform_etc_dir }}/ssl_dist.conf - -## Sets the net_kernel tick time. TickTime is specified in seconds. -## Notice that all communicating nodes are to have the same TickTime -## value specified. -## -## See: http://www.erlang.org/doc/man/kernel_app.html#net_ticktime -## -## Value: Number -## -## vm.args: -kernel net_ticktime Number -## node.dist_net_ticktime = 120 - -## Sets the port range for the listener socket of a distributed Erlang node. -## Note that if there are firewalls between clustered nodes, this port segment -## for nodes’ communication should be allowed. -## -## See: http://www.erlang.org/doc/man/kernel_app.html -## -## Value: Port [1024-65535] -node.dist_listen_min = 6369 -node.dist_listen_max = 6369 - -##-------------------------------------------------------------------- -## RPC -##-------------------------------------------------------------------- -## RPC Mode. -## -## Value: sync | async -rpc.mode = async - -## Max batch size of async RPC requests. -## -## Value: Integer -## Zero or negative value disables rpc batching. -## -## NOTE: RPC batch won't work when rpc.mode = sync -rpc.async_batch_size = 256 - -## TCP server port for RPC. -## -## Value: Port [1024-65535] -rpc.tcp_server_port = 5369 - -## TCP port for outgoing RPC connections. -## -## Value: Port [1024-65535] -rpc.tcp_client_port = 5369 - -## Number of outgoing RPC connections. -## -## Value: Interger [1-256] -## Defaults to NumberOfCPUSchedulers / 2 -#rpc.tcp_client_num = 1 - -## RCP Client connect timeout. -## -## Value: Seconds -rpc.connect_timeout = 5s - -## TCP send timeout of RPC client and server. -## -## Value: Seconds -rpc.send_timeout = 5s - -## Authentication timeout -## -## Value: Seconds -rpc.authentication_timeout = 5s - -## Default receive timeout for call() functions -## -## Value: Seconds -rpc.call_receive_timeout = 15s - -## Socket idle keepalive. -## -## Value: Seconds -rpc.socket_keepalive_idle = 900s - -## TCP Keepalive probes interval. -## -## Value: Seconds -rpc.socket_keepalive_interval = 75s - -## Probes lost to close the connection -## -## Value: Integer -rpc.socket_keepalive_count = 9 - -## Size of TCP send buffer. -## -## Value: Bytes -rpc.socket_sndbuf = 1MB - -## Size of TCP receive buffer. -## -## Value: Seconds -rpc.socket_recbuf = 1MB - -## Size of user-level software socket buffer. -## -## Value: Seconds -rpc.socket_buffer = 1MB - -##-------------------------------------------------------------------- -## Log -##-------------------------------------------------------------------- - -## Where to emit the logs. -## Enable the console (standard output) logs. -## -## Value: off | file | console | both -## - off: disable logs entirely -## - file: write logs only to file -## - console: write logs only to standard I/O -## - both: write logs both to file and standard I/O -log.to = both - -## The log severity level. -## -## Value: debug | info | notice | warning | error | critical | alert | emergency -## -## Note: Only the messages with severity level higher than or equal to -## this level will be logged. -## -## Default: warning -log.level = warning - -## The dir for log files. -## -## Value: Folder -log.dir = {{ platform_log_dir }} - -## The log filename for logs of level specified in "log.level". -## -## If `log.rotation` is enabled, this is the base name of the -## files. Each file in a rotated log is named .N, where N is an integer. -## -## Value: String -## Default: emqx.log -log.file = emqx.log - -## Limits the total number of characters printed for each log event. -## -## Value: Integer -## Default: No Limit -#log.chars_limit = 8192 - -## Enables the log rotation. -## With this enabled, new log files will be created when the current -## log file is full, max to `log.rotation.size` files will be created. -## -## Value: on | off -## Default: on -log.rotation = on - -## Maximum size of each log file. -## -## Value: Number -## Default: 10M -## Supported Unit: KB | MB | GB -log.rotation.size = 10MB - -## Maximum rotation count of log files. -## -## Value: Number -## Default: 5 -log.rotation.count = 5 - -## To create additional log files for specific log levels. -## -## Value: File Name -## Format: log.$level.file = $filename, -## where "$level" can be one of: debug, info, notice, warning, -## error, critical, alert, emergency -## Note: Log files for a specific log level will only contain all the logs -## that higher than or equal to that level -## -#log.info.file = info.log -#log.error.file = error.log - -## The max allowed queue length before switching to sync mode. -## -## Log overload protection parameter. If the message queue grows -## larger than this value the handler switches from anync to sync mode. -## -## Default: 100 -## -#log.sync_mode_qlen = 100 - -## The max allowed queue length before switching to drop mode. -## -## Log overload protection parameter. When the message queue grows -## larger than this threshold, the handler switches to a mode in which -## it drops all new events that senders want to log. -## -## Default: 3000 -## -#log.drop_mode_qlen = 3000 - -## The max allowed queue length before switching to flush mode. -## -## Log overload protection parameter. If the length of the message queue -## grows larger than this threshold, a flush (delete) operation takes place. -## To flush events, the handler discards the messages in the message queue -## by receiving them in a loop without logging. -## -## Default: 8000 -## -#log.flush_qlen = 8000 - -## Kill the log handler when it gets overloaded. -## -## Log overload protection parameter. It is possible that a handler, -## even if it can successfully manage peaks of high load without crashing, -## can build up a large message queue, or use a large amount of memory. -## We could kill the log handler in these cases and restart it after a -## few seconds. -## -## Default: on -## -#log.overload_kill = on - -## The max allowed queue length before killing the log hanlder. -## -## Log overload protection parameter. This is the maximum allowed queue -## length. If the message queue grows larger than this, the handler -## process is terminated. -## -## Default: 20000 -## -#log.overload_kill_qlen = 20000 - -## The max allowed memory size before killing the log hanlder. -## -## Log overload protection parameter. This is the maximum memory size -## that the handler process is allowed to use. If the handler grows -## larger than this, the process is terminated. -## -## Default: 30MB -## -#log.overload_kill_mem_size = 30MB - -## Restart the log hanlder after some seconds. -## -## Log overload protection parameter. If the handler is terminated, -## it restarts automatically after a delay specified in seconds. -## The value "infinity" prevents restarts. -## -## Default: 5s -## -#log.overload_kill_restart_after = 5s - -## Max burst count and time window for burst control. -## -## Log overload protection parameter. Large bursts of log events - many -## events received by the handler under a short period of time - can -## potentially cause problems. By specifying the maximum number of events -## to be handled within a certain time frame, the handler can avoid -## choking the log with massive amounts of printouts. -## -## This config controls the maximum number of events to handle within -## a time frame. After the limit is reached, successive events are -## dropped until the end of the time frame. -## -## Note that there would be no warning if any messages were -## dropped because of burst control. -## -## Comment this config out to disable the burst control feature. -## -## Value: MaxBurstCount,TimeWindow -## Default: disabled -## -#log.burst_limit = 20000, 1s - -##-------------------------------------------------------------------- -## Authentication/Access Control -##-------------------------------------------------------------------- - -## Allow anonymous authentication by default if no auth plugins loaded. -## Notice: Disable the option in production deployment! -## -## Value: true | false -allow_anonymous = true - -## Allow or deny if no ACL rules matched. -## -## Value: allow | deny -acl_nomatch = allow - -## Default ACL File. -## -## Value: File Name -acl_file = {{ platform_etc_dir }}/acl.conf - -## Whether to enable ACL cache. -## -## If enabled, ACLs roles for each client will be cached in the memory -## -## Value: on | off -enable_acl_cache = on - -## The maximum count of ACL entries can be cached for a client. -## -## Value: Integer greater than 0 -## Default: 32 -acl_cache_max_size = 32 - -## The time after which an ACL cache entry will be deleted -## -## Value: Duration -## Default: 1 minute -acl_cache_ttl = 1m - -## The action when acl check reject current operation -## -## Value: ignore | disconnect -## Default: ignore -acl_deny_action = ignore - -## Specify the global flapping detect policy. -## The value is a string composed of flapping threshold, duration and banned interval. -## 1. threshold: an integer to specfify the disconnected times of a MQTT Client; -## 2. duration: the time window for flapping detect; -## 3. banned interval: the banned interval if a flapping is detected. -## -## Value: Integer,Duration,Duration -flapping_detect_policy = 30, 1m, 5m - -##-------------------------------------------------------------------- -## MQTT Protocol -##-------------------------------------------------------------------- - -## Maximum MQTT packet size allowed. -## -## Value: Bytes -## Default: 1MB -mqtt.max_packet_size = 1MB - -## Maximum length of MQTT clientId allowed. -## -## Value: Number [23-65535] -mqtt.max_clientid_len = 65535 - -## Maximum topic levels allowed. 0 means no limit. -## -## Value: Number -mqtt.max_topic_levels = 0 - -## Maximum QoS allowed. -## -## Value: 0 | 1 | 2 -mqtt.max_qos_allowed = 2 - -## Maximum Topic Alias, 0 means no topic alias supported. -## -## Value: 0-65535 -mqtt.max_topic_alias = 65535 - -## Whether the Server supports MQTT retained messages. -## -## Value: boolean -mqtt.retain_available = true - -## Whether the Server supports MQTT Wildcard Subscriptions -## -## Value: boolean -mqtt.wildcard_subscription = true - -## Whether the Server supports MQTT Shared Subscriptions. -## -## Value: boolean -mqtt.shared_subscription = true - -## Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -## -## Value: true | false -mqtt.ignore_loop_deliver = false - -## Whether to parse the MQTT frame in strict mode -## -## Value: true | false -mqtt.strict_mode = false - -## Specify the response information returned to the client -## -## Value: String -## mqtt.response_information = example - -##-------------------------------------------------------------------- -## Zones -##-------------------------------------------------------------------- - -##-------------------------------------------------------------------- -## External Zone - -## Idle timeout of the external MQTT connections. -## -## Value: duration -zone.external.idle_timeout = 15s - -## Publish limit for the external MQTT connections. -## -## Value: Number,Duration -## Example: 100 messages per 10 seconds. -## zone.external.publish_limit = 100,10s - -## Enable ACL check. -## -## Value: Flag -zone.external.enable_acl = on - -## Enable ban check. -## -## Value: Flag -zone.external.enable_ban = on - -## Enable per connection statistics. -## -## Value: on | off -zone.external.enable_stats = on - -## The action when acl check reject current operation -## -## Value: ignore | disconnect -## Default: ignore -zone.external.acl_deny_action = ignore - -## Force the MQTT connection process GC after this number of -## messages | bytes passed through. -## -## Numbers delimited by `|'. Zero or negative is to disable. -zone.external.force_gc_policy = 16000|16MB - -## Max message queue length and total heap size to force shutdown -## connection/session process. -## Message queue here is the Erlang process mailbox, but not the number -## of queued MQTT messages of QoS 1 and 2. -## -## Numbers delimited by `|'. Zero or negative is to disable. -## zone.external.force_shutdown_policy = 32000|32MB - -## Maximum MQTT packet size allowed. -## -## Value: Bytes -## Default: 1MB -## zone.external.max_packet_size = 64KB - -## Maximum length of MQTT clientId allowed. -## -## Value: Number [23-65535] -## zone.external.max_clientid_len = 1024 - -## Maximum topic levels allowed. 0 means no limit. -## -## Value: Number -## zone.external.max_topic_levels = 7 - -## Maximum QoS allowed. -## -## Value: 0 | 1 | 2 -## zone.external.max_qos_allowed = 2 - -## Maximum Topic Alias, 0 means no limit. -## -## Value: 0-65535 -## zone.external.max_topic_alias = 65535 - -## Whether the Server supports retained messages. -## -## Value: boolean -## zone.external.retain_available = true - -## Whether the Server supports Wildcard Subscriptions -## -## Value: boolean -## zone.external.wildcard_subscription = false - -## Whether the Server supports Shared Subscriptions -## -## Value: boolean -## zone.external.shared_subscription = false - -## Server Keep Alive -## -## Value: Number -## zone.external.server_keepalive = 0 - -## The backoff for MQTT keepalive timeout. The broker will kick a connection out -## until 'Keepalive * backoff * 2' timeout. -## -## Value: Float > 0.5 -zone.external.keepalive_backoff = 0.75 - -## Maximum number of subscriptions allowed, 0 means no limit. -## -## Value: Number -zone.external.max_subscriptions = 0 - -## Force to upgrade QoS according to subscription. -## -## Value: on | off -zone.external.upgrade_qos = off - -## Maximum size of the Inflight Window storing QoS1/2 messages delivered but unacked. -## -## Value: Number -zone.external.max_inflight = 32 - -## Retry interval for QoS1/2 message delivering. -## -## Value: Duration -zone.external.retry_interval = 30s - -## Maximum QoS2 packets (Client -> Broker) awaiting PUBREL, 0 means no limit. -## -## Value: Number -zone.external.max_awaiting_rel = 100 - -## The QoS2 messages (Client -> Broker) will be dropped if awaiting PUBREL timeout. -## -## Value: Duration -zone.external.await_rel_timeout = 300s - -## Default session expiry interval for MQTT V3.1.1 connections. -## -## Value: Duration -## -d: day -## -h: hour -## -m: minute -## -s: second -## -## Default: 2h, 2 hours -zone.external.session_expiry_interval = 2h - -## Maximum queue length. Enqueued messages when persistent client disconnected, -## or inflight window is full. 0 means no limit. -## -## Value: Number >= 0 -zone.external.max_mqueue_len = 1000 - -## Topic priorities. -## 'none' to indicate no priority table (by default), hence all messages -## are treated equal -## -## Priority number [1-255] -## Example: topic/1=10,topic/2=8 -## NOTE: comma and equal signs are not allowed for priority topic names -## NOTE: messages for topics not in the priority table are treated as -## either highest or lowest priority depending on the configured -## value for mqueue_default_priority -## -zone.external.mqueue_priorities = none - -## Default to highest priority for topics not matching priority table -## -## Value: highest | lowest -zone.external.mqueue_default_priority = highest - -## Whether to enqueue QoS0 messages. -## -## Value: false | true -zone.external.mqueue_store_qos0 = true - -## Whether to turn on flapping detect -## -## Value: on | off -zone.external.enable_flapping_detect = off - -## All the topics will be prefixed with the mountpoint path if this option is enabled. -## -## Variables in mountpoint path: -## - %c: clientid -## - %u: username -## -## Value: String -## zone.external.mountpoint = devicebound/ - -## Whether use username replace client id -## -## Value: boolean -## Default: false -zone.external.use_username_as_clientid = false - -## Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -## -## Value: true | false -zone.external.ignore_loop_deliver = false - -## Whether to parse the MQTT frame in strict mode -## -## Value: true | false -zone.external.strict_mode = false - -## Specify the response information returned to the client -## -## Value: String -## zone.external.response_information = example - -##-------------------------------------------------------------------- -## Internal Zone - -zone.internal.allow_anonymous = true - -## Enable per connection stats. -## -## Value: Flag -zone.internal.enable_stats = on - -## Enable ACL check. -## -## Value: Flag -zone.internal.enable_acl = off - -## The action when acl check reject current operation -## -## Value: ignore | disconnect -## Default: ignore -zone.internal.acl_deny_action = ignore - -## See zone.$name.force_gc_policy -## zone.internal.force_gc_policy = 128000|128MB - -## See zone.$name.wildcard_subscription. -## -## Value: boolean -## zone.internal.wildcard_subscription = true - -## See zone.$name.shared_subscription. -## -## Value: boolean -## zone.internal.shared_subscription = true - -## See zone.$name.max_subscriptions. -## -## Value: Integer -zone.internal.max_subscriptions = 0 - -## See zone.$name.max_inflight -## -## Value: Number -zone.internal.max_inflight = 128 - -## See zone.$name.max_awaiting_rel -## -## Value: Number -zone.internal.max_awaiting_rel = 1000 - -## See zone.$name.max_mqueue_len -## -## Value: Number >= 0 -zone.internal.max_mqueue_len = 10000 - -## Whether to enqueue Qos0 messages. -## -## Value: false | true -zone.internal.mqueue_store_qos0 = true - -## Whether to turn on flapping detect -## -## Value: on | off -zone.internal.enable_flapping_detect = off - -## See zone.$name.force_shutdown_policy -## zone.internal.force_shutdown_policy = 128000|128MB - -## All the topics will be prefixed with the mountpoint path if this option is enabled. -## -## Variables in mountpoint path: -## - %c: clientid -## - %u: username -## -## Value: String -## zone.internal.mountpoint = cloudbound/ - -## Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -## -## Value: true | false -zone.internal.ignore_loop_deliver = false - -## Whether to parse the MQTT frame in strict mode -## -## Value: true | false -zone.internal.strict_mode = false - -## Specify the response information returned to the client -## -## Value: String -## zone.internal.response_information = example - -## Allow the zone's clients to bypass authentication step -## -## Value: true | false -zone.internal.bypass_auth_plugins = true - -##-------------------------------------------------------------------- -## Listeners -##-------------------------------------------------------------------- - -##-------------------------------------------------------------------- -## MQTT/TCP - External TCP Listener for MQTT Protocol - -## listener.tcp.$name is the IP address and port that the MQTT/TCP -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 1883, 127.0.0.1:1883, ::1:1883 -listener.tcp.external = 0.0.0.0:1883 - -## The acceptor pool for external MQTT/TCP listener. -## -## Value: Number -listener.tcp.external.acceptors = 8 - -## Maximum number of concurrent MQTT/TCP connections. -## -## Value: Number -listener.tcp.external.max_connections = 1024000 - -## Maximum external connections per second. -## -## Value: Number -listener.tcp.external.max_conn_rate = 1000 - -## Specify the {active, N} option for the external MQTT/TCP Socket. -## -## Value: Number -listener.tcp.external.active_n = 100 - -## Zone of the external MQTT/TCP listener belonged to. -## -## See: zone.$name.* -## -## Value: String -listener.tcp.external.zone = external - -## Rate limit for the external MQTT/TCP connections. Format is 'limit,duration'. -## -## Value: limit,duration -## Default: 100KB incoming per 10 seconds. -## listener.tcp.external.rate_limit = 100KB,10s - -## The access control rules for the MQTT/TCP listener. -## -## See: https://hub.fastgit.org/emqtt/esockd#allowdeny -## -## Value: ACL Rule -## -## Example: allow 192.168.0.0/24 -listener.tcp.external.access.1 = allow all - -## Enable the Proxy Protocol V1/2 if the EMQ X cluster is deployed -## behind HAProxy or Nginx. -## -## See: https://www.haproxy.com/blog/haproxy/proxy-protocol/ -## -## Value: on | off -## listener.tcp.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. EMQ X will close the TCP connection -## if no proxy protocol packet recevied within the timeout. -## -## Value: Duration -## listener.tcp.external.proxy_protocol_timeout = 3s - -## Enable the option for X.509 certificate based authentication. -## EMQX will use the common name of certificate as MQTT username. -## -## Value: cn | dn | crt -## listener.tcp.external.peer_cert_as_username = cn - -## The TCP backlog defines the maximum length that the queue of pending -## connections can grow to. -## -## Value: Number >= 0 -listener.tcp.external.backlog = 1024 - -## The TCP send timeout for external MQTT connections. -## -## Value: Duration -listener.tcp.external.send_timeout = 15s - -## Close the TCP connection if send timeout. -## -## Value: on | off -listener.tcp.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for MQTT connections. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -## listener.tcp.external.recbuf = 2KB - -## The TCP send buffer(os kernel) for MQTT connections. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -## listener.tcp.external.sndbuf = 2KB - -## The size of the user-level software buffer used by the driver. -## Not to be confused with options sndbuf and recbuf, which correspond -## to the Kernel socket buffers. It is recommended to have val(buffer) -## >= max(val(sndbuf),val(recbuf)) to avoid performance issues because -## of unnecessary copying. val(buffer) is automatically set to the above -## maximum when values sndbuf or recbuf are set. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -## listener.tcp.external.buffer = 2KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## Value: on | off -## listener.tcp.external.tune_buffer = off - -## The TCP_NODELAY flag for MQTT connections. Small amounts of data are -## sent immediately if the option is enabled. -## -## Value: true | false -listener.tcp.external.nodelay = true - -## The SO_REUSEADDR flag for TCP listener. -## -## Value: true | false -listener.tcp.external.reuseaddr = true - -##-------------------------------------------------------------------- -## Internal TCP Listener for MQTT Protocol - -## The IP address and port that the internal MQTT/TCP protocol listener -## will bind. -## -## Value: IP:Port, Port -## -## Examples: 11883, 127.0.0.1:11883, ::1:11883 -listener.tcp.internal = 127.0.0.1:11883 - -## The acceptor pool for internal MQTT/TCP listener. -## -## Value: Number -listener.tcp.internal.acceptors = 4 - -## Maximum number of concurrent MQTT/TCP connections. -## -## Value: Number -listener.tcp.internal.max_connections = 1024000 - -## Maximum internal connections per second. -## -## Value: Number -listener.tcp.internal.max_conn_rate = 1000 - -## Specify the {active, N} option for the internal MQTT/TCP Socket. -## -## Value: Number -listener.tcp.internal.active_n = 1000 - -## Zone of the internal MQTT/TCP listener belonged to. -## -## Value: String -listener.tcp.internal.zone = internal - -## Rate limit for the internal MQTT/TCP connections. -## -## See: listener.tcp.$name.rate_limit -## -## Value: limit,duration -## Default: 1MB incoming per second. -## listener.tcp.internal.rate_limit = 1MB,1s - -## The TCP backlog of internal MQTT/TCP Listener. -## -## See: listener.tcp.$name.backlog -## -## Value: Number >= 0 -listener.tcp.internal.backlog = 512 - -## The TCP send timeout for internal MQTT connections. -## -## See: listener.tcp.$name.send_timeout -## -## Value: Duration -listener.tcp.internal.send_timeout = 5s - -## Close the MQTT/TCP connection if send timeout. -## -## See: listener.tcp.$name.send_timeout_close -## -## Value: on | off -listener.tcp.internal.send_timeout_close = on - -## The TCP receive buffer(os kernel) for internal MQTT connections. -## -## See: listener.tcp.$name.recbuf -## -## Value: Bytes -listener.tcp.internal.recbuf = 64KB - -## The TCP send buffer(os kernel) for internal MQTT connections. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -listener.tcp.internal.sndbuf = 64KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.tcp.$name.buffer -## -## Value: Bytes -## listener.tcp.internal.buffer = 16KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## See: listener.tcp.$name.tune_buffer -## -## Value: on | off -## listener.tcp.internal.tune_buffer = off - -## The TCP_NODELAY flag for internal MQTT connections. -## -## See: listener.tcp.$name.nodelay -## -## Value: true | false -listener.tcp.internal.nodelay = false - -## The SO_REUSEADDR flag for MQTT/TCP Listener. -## -## Value: true | false -listener.tcp.internal.reuseaddr = true - -##-------------------------------------------------------------------- -## MQTT/SSL - External SSL Listener for MQTT Protocol - -## listener.ssl.$name is the IP address and port that the MQTT/SSL -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 8883, 127.0.0.1:8883, ::1:8883 -listener.ssl.external = 8883 - -## The acceptor pool for external MQTT/SSL listener. -## -## Value: Number -listener.ssl.external.acceptors = 16 - -## Maximum number of concurrent MQTT/SSL connections. -## -## Value: Number -listener.ssl.external.max_connections = 102400 - -## Maximum MQTT/SSL connections per second. -## -## Value: Number -listener.ssl.external.max_conn_rate = 500 - -## Specify the {active, N} option for the internal MQTT/SSL Socket. -## -## Value: Number -listener.ssl.external.active_n = 100 - -## Zone of the external MQTT/SSL listener belonged to. -## -## Value: String -listener.ssl.external.zone = external - -## The access control rules for the MQTT/SSL listener. -## -## See: listener.tcp.$name.access -## -## Value: ACL Rule -listener.ssl.external.access.1 = allow all - -## Rate limit for the external MQTT/SSL connections. -## -## Value: limit,duration -## Default: 100KB incoming per 10 seconds. -## listener.ssl.external.rate_limit = 100KB,10s - -## Enable the Proxy Protocol V1/2 if the EMQ cluster is deployed behind -## HAProxy or Nginx. -## -## See: listener.tcp.$name.proxy_protocol -## -## Value: on | off -## listener.ssl.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. -## -## See: listener.tcp.$name.proxy_protocol_timeout -## -## Value: Duration -## listener.ssl.external.proxy_protocol_timeout = 3s - -## TLS versions only to protect from POODLE attack. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: String, seperated by ',' -## listener.ssl.external.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## TLS Handshake timeout. -## -## Value: Duration -listener.ssl.external.handshake_timeout = 15s - -## Path to the file containing the user's private PEM-encoded key. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: File -listener.ssl.external.keyfile = {{ platform_etc_dir }}/certs/key.pem - -## Path to a file containing the user certificate. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: File -listener.ssl.external.certfile = {{ platform_etc_dir }}/certs/cert.pem - -## Path to the file containing PEM-encoded CA certificates. The CA certificates -## are used during server authentication and when building the client certificate chain. -## -## Value: File -## listener.ssl.external.cacertfile = {{ platform_etc_dir }}/certs/cacert.pem - -## The Ephemeral Diffie-Helman key exchange is a very effective way of -## ensuring Forward Secrecy by exchanging a set of keys that never hit -## the wire. Since the DH key is effectively signed by the private key, -## it needs to be at least as strong as the private key. In addition, -## the default DH groups that most of the OpenSSL installations have -## are only a handful (since they are distributed with the OpenSSL -## package that has been built for the operating system it’s running on) -## and hence predictable (not to mention, 1024 bits only). -## In order to escape this situation, first we need to generate a fresh, -## strong DH group, store it in a file and then use the option above, -## to force our SSL application to use the new DH group. Fortunately, -## OpenSSL provides us with a tool to do that. Simply run: -## openssl dhparam -out dh-params.pem 2048 -## -## Value: File -## listener.ssl.external.dhfile = {{ platform_etc_dir }}/certs/dh-params.pem - -## A server only does x509-path validation in mode verify_peer, -## as it then sends a certificate request to the client (this -## message is not sent if the verify option is verify_none). -## You can then also want to specify option fail_if_no_peer_cert. -## More information at: http://erlang.org/doc/man/ssl.html -## -## Value: verify_peer | verify_none -## listener.ssl.external.verify = verify_peer - -## Used together with {verify, verify_peer} by an SSL server. If set to true, -## the server fails if the client does not have a certificate to send, that is, -## sends an empty certificate. -## -## Value: true | false -## listener.ssl.external.fail_if_no_peer_cert = true - -## This is the single most important configuration option of an Erlang SSL -## application. Ciphers (and their ordering) define the way the client and -## server encrypt information over the wire, from the initial Diffie-Helman -## key exchange, the session key encryption ## algorithm and the message -## digest algorithm. Selecting a good cipher suite is critical for the -## application’s data security, confidentiality and performance. -## -## The cipher list above offers: -## -## A good balance between compatibility with older browsers. -## It can get stricter for Machine-To-Machine scenarios. -## Perfect Forward Secrecy. -## No old/insecure encryption and HMAC algorithms -## -## Most of it was copied from Mozilla’s Server Side TLS article -## -## Value: Ciphers -listener.ssl.external.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA - -## Ciphers for TLS PSK. -## Note that 'listener.ssl.external.ciphers' and 'listener.ssl.external.psk_ciphers' cannot -## be configured at the same time. -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -#listener.ssl.external.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## SSL parameter renegotiation is a feature that allows a client and a server -## to renegotiate the parameters of the SSL connection on the fly. -## RFC 5746 defines a more secure way of doing this. By enabling secure renegotiation, -## you drop support for the insecure renegotiation, prone to MitM attacks. -## -## Value: on | off -## listener.ssl.external.secure_renegotiate = off - -## A performance optimization setting, it allows clients to reuse -## pre-existing sessions, instead of initializing new ones. -## Read more about it here. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: on | off -## listener.ssl.external.reuse_sessions = on - -## An important security setting, it forces the cipher to be set based -## on the server-specified order instead of the client-specified order, -## hence enforcing the (usually more properly configured) security -## ordering of the server administrator. -## -## Value: on | off -## listener.ssl.external.honor_cipher_order = on - -## Use the CN, DN or CRT field from the client certificate as a username. -## Notice that 'verify' should be set as 'verify_peer'. -## -## Value: cn | dn | crt -## listener.ssl.external.peer_cert_as_username = cn - -## TCP backlog for the SSL connection. -## -## See listener.tcp.$name.backlog -## -## Value: Number >= 0 -## listener.ssl.external.backlog = 1024 - -## The TCP send timeout for the SSL connection. -## -## See listener.tcp.$name.send_timeout -## -## Value: Duration -## listener.ssl.external.send_timeout = 15s - -## Close the SSL connection if send timeout. -## -## See: listener.tcp.$name.send_timeout_close -## -## Value: on | off -## listener.ssl.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for the SSL connections. -## -## See: listener.tcp.$name.recbuf -## -## Value: Bytes -## listener.ssl.external.recbuf = 4KB - -## The TCP send buffer(os kernel) for internal MQTT connections. -## -## See: listener.tcp.$name.sndbuf -## -## Value: Bytes -## listener.ssl.external.sndbuf = 4KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.tcp.$name.buffer -## -## Value: Bytes -## listener.ssl.external.buffer = 4KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## See: listener.tcp.$name.tune_buffer -## -## Value: on | off -## listener.ssl.external.tune_buffer = off - -## The TCP_NODELAY flag for SSL connections. -## -## See: listener.tcp.$name.nodelay -## -## Value: true | false -## listener.ssl.external.nodelay = true - -## The SO_REUSEADDR flag for MQTT/SSL Listener. -## -## Value: true | false -listener.ssl.external.reuseaddr = true - -##-------------------------------------------------------------------- -## External WebSocket listener for MQTT protocol - -## listener.ws.$name is the IP address and port that the MQTT/WebSocket -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 8083, 127.0.0.1:8083, ::1:8083 -listener.ws.external = 8083 - -## The path of WebSocket MQTT endpoint -## -## Value: URL Path -listener.ws.external.mqtt_path = /mqtt - -## The acceptor pool for external MQTT/WebSocket listener. -## -## Value: Number -listener.ws.external.acceptors = 4 - -## Maximum number of concurrent MQTT/WebSocket connections. -## -## Value: Number -listener.ws.external.max_connections = 102400 - -## Maximum MQTT/WebSocket connections per second. -## -## Value: Number -listener.ws.external.max_conn_rate = 1000 - -## Simulate the {active, N} option for the MQTT/WebSocket connections. -## -## Value: Number -listener.ws.external.active_n = 100 - -## Rate limit for the MQTT/WebSocket connections. -## -## Value: Limit,Duration -## Default: 100KB incoming per 10 seconds. -## listener.ws.external.rate_limit = 100KB,10s - -## Zone of the external MQTT/WebSocket listener belonged to. -## -## Value: String -listener.ws.external.zone = external - -## The access control for the MQTT/WebSocket listener. -## -## See: listener.ws.$name.access -## -## Value: ACL Rule -listener.ws.external.access.1 = allow all - -## Verify if the protocol header is valid. Turn off for WeChat MiniApp. -## -## Value: on | off -listener.ws.external.verify_protocol_header = on - -## Enable the Proxy Protocol V1/2 if the EMQ cluster is deployed behind -## HAProxy or Nginx. -## -## See: listener.ws.$name.proxy_protocol -## -## Value: on | off -## listener.ws.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. -## -## See: listener.ws.$name.proxy_protocol_timeout -## -## Value: Duration -## listener.ws.external.proxy_protocol_timeout = 3s - -## The TCP backlog of external MQTT/WebSocket Listener. -## -## See: listener.ws.$name.backlog -## -## Value: Number >= 0 -listener.ws.external.backlog = 1024 - -## The TCP send timeout for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.send_timeout -## -## Value: Duration -listener.ws.external.send_timeout = 15s - -## Close the MQTT/WebSocket connection if send timeout. -## -## See: listener.ws.$name.send_timeout_close -## -## Value: on | off -listener.ws.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.recbuf -## -## Value: Bytes -## listener.ws.external.recbuf = 2KB - -## The TCP send buffer(os kernel) for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.sndbuf -## -## Value: Bytes -## listener.ws.external.sndbuf = 2KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.ws.$name.buffer -## -## Value: Bytes -## listener.ws.external.buffer = 2KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## See: listener.ws.$name.tune_buffer -## -## Value: on | off -## listener.ws.external.tune_buffer = off - -## The TCP_NODELAY flag for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.nodelay -## -## Value: true | false -listener.ws.external.nodelay = true - -## The compress flag for external MQTT/WebSocket connections. -## -## If this Value is set true,the websocket message would be compressed -## -## Value: true | false -## listener.ws.external.compress = true - -## The level of deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.level -## -## Value: none | default | best_compression | best_speed -## listener.ws.external.deflate_opts.level = default - -## The mem_level of deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.mem_level -## -## Valid range is 1-9 -## listener.ws.external.deflate_opts.mem_level = 8 - -## The strategy of deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.strategy -## -## Value: default | filtered | huffman_only | rle -## listener.ws.external.deflate_opts.strategy = default - -## The deflate option for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.server_context_takeover -## -## Value: takeover | no_takeover -## listener.ws.external.deflate_opts.server_context_takeover = takeover - -## The deflate option for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.client_context_takeover -## -## Value: takeover | no_takeover -## listener.ws.external.deflate_opts.client_context_takeover = takeover - -## The deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.server_max_window_bits -## -## Valid range is 8-15 -## listener.ws.external.deflate_opts.server_max_window_bits = 15 - -## The deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.client_max_window_bits -## -## Valid range is 8-15 -## listener.ws.external.deflate_opts.client_max_window_bits = 15 - -## The idle timeout for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.idle_timeout -## -## Value: Duration -## listener.ws.external.idle_timeout = 60s - -## The max frame size for external MQTT/WebSocket connections. -## -## -## Value: Number -## listener.ws.external.max_frame_size = 0 - -##-------------------------------------------------------------------- -## External WebSocket/SSL listener for MQTT Protocol - -## listener.wss.$name is the IP address and port that the MQTT/WebSocket/SSL -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 8084, 127.0.0.1:8084, ::1:8084 -listener.wss.external = 8084 - -## The path of WebSocket MQTT endpoint -## -## Value: URL Path -listener.wss.external.mqtt_path = /mqtt - -## The acceptor pool for external MQTT/WebSocket/SSL listener. -## -## Value: Number -listener.wss.external.acceptors = 4 - -## Maximum number of concurrent MQTT/Webwocket/SSL connections. -## -## Value: Number -listener.wss.external.max_connections = 16 - -## Maximum MQTT/WebSocket/SSL connections per second. -## -## See: listener.tcp.$name.max_conn_rate -## -## Value: Number -listener.wss.external.max_conn_rate = 1000 - -## Simulate the {active, N} option for the MQTT/WebSocket/SSL connections. -## -## Value: Number -listener.wss.external.active_n = 100 - -## Rate limit for the MQTT/WebSocket/SSL connections. -## -## Value: Limit,Duration -## Default: 100KB incoming per 10 seconds. -## listener.wss.external.rate_limit = 100KB,10s - -## Zone of the external MQTT/WebSocket/SSL listener belonged to. -## -## Value: String -listener.wss.external.zone = external - -## The access control rules for the MQTT/WebSocket/SSL listener. -## -## See: listener.tcp.$name.access. -## -## Value: ACL Rule -listener.wss.external.access.1 = allow all - -## See: listener.ws.external.verify_protocol_header -## -## Value: on | off -listener.wss.external.verify_protocol_header = on - -## Enable the Proxy Protocol V1/2 support. -## -## See: listener.tcp.$name.proxy_protocol -## -## Value: on | off -## listener.wss.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. -## -## See: listener.tcp.$name.proxy_protocol_timeout -## -## Value: Duration -## listener.wss.external.proxy_protocol_timeout = 3s - -## TLS versions only to protect from POODLE attack. -## -## See: listener.ssl.$name.tls_versions -## -## Value: String, seperated by ',' -## listener.wss.external.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## Path to the file containing the user's private PEM-encoded key. -## -## See: listener.ssl.$name.keyfile -## -## Value: File -listener.wss.external.keyfile = {{ platform_etc_dir }}/certs/key.pem - -## Path to a file containing the user certificate. -## -## See: listener.ssl.$name.certfile -## -## Value: File -listener.wss.external.certfile = {{ platform_etc_dir }}/certs/cert.pem - -## Path to the file containing PEM-encoded CA certificates. -## -## See: listener.ssl.$name.cacert -## -## Value: File -## listener.wss.external.cacertfile = {{ platform_etc_dir }}/certs/cacert.pem - -## See: listener.ssl.$name.dhfile -## -## Value: File -## listener.ssl.external.dhfile = {{ platform_etc_dir }}/certs/dh-params.pem - -## See: listener.ssl.$name.vefify -## -## Value: vefify_peer | verify_none -## listener.wss.external.verify = verify_peer - -## See: listener.ssl.$name.fail_if_no_peer_cert -## -## Value: false | true -## listener.wss.external.fail_if_no_peer_cert = true - -## See: listener.ssl.$name.ciphers -## -## Value: Ciphers -listener.wss.external.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA - -## Ciphers for TLS PSK. -## Note that 'listener.wss.external.ciphers' and 'listener.wss.external.psk_ciphers' cannot -## be configured at the same time. -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -## listener.wss.external.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## See: listener.ssl.$name.secure_renegotiate -## -## Value: on | off -## listener.wss.external.secure_renegotiate = off - -## See: listener.ssl.$name.reuse_sessions -## -## Value: on | off -## listener.wss.external.reuse_sessions = on - -## See: listener.ssl.$name.honor_cipher_order -## -## Value: on | off -## listener.wss.external.honor_cipher_order = on - -## See: listener.ssl.$name.peer_cert_as_username -## -## Value: cn | dn | crt -## listener.wss.external.peer_cert_as_username = cn - -## TCP backlog for the WebSocket/SSL connection. -## -## See: listener.tcp.$name.backlog -## -## Value: Number >= 0 -listener.wss.external.backlog = 1024 - -## The TCP send timeout for the WebSocket/SSL connection. -## -## See: listener.tcp.$name.send_timeout -## -## Value: Duration -listener.wss.external.send_timeout = 15s - -## Close the WebSocket/SSL connection if send timeout. -## -## See: listener.tcp.$name.send_timeout_close -## -## Value: on | off -listener.wss.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for the WebSocket/SSL connections. -## -## See: listener.tcp.$name.recbuf -## -## Value: Bytes -## listener.wss.external.recbuf = 4KB - -## The TCP send buffer(os kernel) for the WebSocket/SSL connections. -## -## See: listener.tcp.$name.sndbuf -## -## Value: Bytes -## listener.wss.external.sndbuf = 4KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.tcp.$name.buffer -## -## Value: Bytes -## listener.wss.external.buffer = 4KB - -## The TCP_NODELAY flag for WebSocket/SSL connections. -## -## See: listener.tcp.$name.nodelay -## -## Value: true | false -## listener.wss.external.nodelay = true - -## The compress flag for external WebSocket/SSL connections. -## -## If this Value is set true,the websocket message would be compressed -## -## Value: true | false -## listener.wss.external.compress = true - -## The level of deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.level -## -## Value: none | default | best_compression | best_speed -## listener.wss.external.deflate_opts.level = default - -## The mem_level of deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.mem_level -## -## Valid range is 1-9 -## listener.wss.external.deflate_opts.mem_level = 8 - -## The strategy of deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.strategy -## -## Value: default | filtered | huffman_only | rle -## listener.wss.external.deflate_opts.strategy = default - -## The deflate option for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.server_context_takeover -## -## Value: takeover | no_takeover -## listener.wss.external.deflate_opts.server_context_takeover = takeover - -## The deflate option for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.client_context_takeover -## -## Value: takeover | no_takeover -## listener.wss.external.deflate_opts.client_context_takeover = takeover - -## The deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.server_max_window_bits -## -## Valid range is 8-15 -## listener.wss.external.deflate_opts.server_max_window_bits = 15 - -## The deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.client_max_window_bits -## -## Valid range is 8-15 -## listener.wss.external.deflate_opts.client_max_window_bits = 15 - -## The idle timeout for external WebSocket/SSL connections. -## -## See: listener.wss.$name.idle_timeout -## -## Value: Duration -## listener.wss.external.idle_timeout = 60s - -## The max frame size for external WebSocket/SSL connections. -## -## Value: Number -## listener.wss.external.max_frame_size = 0 - -##-------------------------------------------------------------------- -## Modules -##-------------------------------------------------------------------- -## The file to store loaded module names. -## -## Value: File -modules.loaded_file = {{ platform_data_dir }}/loaded_modules - -##-------------------------------------------------------------------- -## Presence Module - -## Sets the QoS for presence MQTT message. -## -## Value: 0 | 1 | 2 -module.presence.qos = 1 - -##-------------------------------------------------------------------- -## Subscription Module - -## Subscribe the Topics automatically when client connected. -## -## Value: String -## module.subscription.1.topic = connected/%c/%u - -## Qos of the proxy subscription. -## -## Value: 0 | 1 | 2 -## Default: 0 -## module.subscription.1.qos = 0 - -## No Local of the proxy subscription options. -## This configuration only takes effect in the MQTT V5 protocol. -## -## Value: 0 | 1 -## Default: 0 -## module.subscription.1.nl = 0 - -## Retain As Published of the proxy subscription options. -## This configuration only takes effect in the MQTT V5 protocol. -## -## Value: 0 | 1 -## Default: 0 -## module.subscription.1.rap = 0 - -## Retain Handling of the proxy subscription options. -## This configuration only takes effect in the MQTT V5 protocol. -## -## Value: 0 | 1 | 2 -## Default: 0 -## module.subscription.1.rh = 0 - -##-------------------------------------------------------------------- -## Rewrite Module - -## {rewrite, Topic, Re, Dest} -## module.rewrite.rule.1 = x/# ^x/y/(.+)$ z/y/$1 -## module.rewrite.rule.2 = y/+/z/# ^y/(.+)/z/(.+)$ y/z/$2 - -##------------------------------------------------------------------- -## Plugins -##------------------------------------------------------------------- - -## The etc dir for plugins' config. -## -## Value: Folder -plugins.etc_dir = {{ platform_etc_dir }}/plugins/ - -## The file to store loaded plugin names. -## -## Value: File -plugins.loaded_file = {{ platform_data_dir }}/loaded_plugins - -## The directory of extension plugins. -## -## Value: File -plugins.expand_plugins_dir = {{ platform_plugins_dir }}/ - -##-------------------------------------------------------------------- -## Broker -##-------------------------------------------------------------------- - -## System interval of publishing $SYS messages. -## -## Value: Duration -## Default: 1m, 1 minute -broker.sys_interval = 1m - -## System heartbeat interval of publishing following heart beat message: -## - "$SYS/brokers//uptime" -## - "$SYS/brokers//datetime" -## -## Value: Duration -## Default: 30s -broker.sys_heartbeat = 30s - -## Session locking strategy in a cluster. -## -## Value: Enum -## - local -## - one -## - quorum -## - all -broker.session_locking_strategy = quorum - -## Dispatch strategy for shared subscription -## -## Value: Enum -## - random -## - round_robin -## - sticky -## - hash -broker.shared_subscription_strategy = random - -## Enable/disable shared dispatch acknowledgement for QoS1 and QoS2 messages -## This should allow messages to be dispatched to a different subscriber in -## the group in case the picked (based on shared_subscription_strategy) one # is offline -## -## Value: Enum -## - true -## - false -broker.shared_dispatch_ack_enabled = false - -## Enable batch clean for deleted routes. -## -## Value: Flag -broker.route_batch_clean = off - -##-------------------------------------------------------------------- -## System Monitor -##-------------------------------------------------------------------- - -## Enable Long GC monitoring. Disable if the value is 0. -## Notice: don't enable the monitor in production for: -## https://hub.fastgit.org/erlang/otp/blob/feb45017da36be78d4c5784d758ede619fa7bfd3/erts/emulator/beam/erl_gc.c#L421 -## -## Value: Duration -## - h: hour -## - m: minute -## - s: second -## - ms: milliseconds -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 0.1s: 0.1 seconds -## - 100ms : 100 milliseconds -## -## Default: 0ms -sysmon.long_gc = 0 - -## Enable Long Schedule(ms) monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: Duration -## - h: hour -## - m: minute -## - s: second -## - ms: milliseconds -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 0.1s: 0.1 seconds -## - 100ms: 100 milliseconds -## -## Default: 0ms -sysmon.long_schedule = 240ms - -## Enable Large Heap monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: bytes -## -## Default: 8M words. 32MB on 32-bit VM, 64MB on 64-bit VM. -sysmon.large_heap = 8MB - -## Enable Busy Port monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: true | false -sysmon.busy_port = false - -## Enable Busy Dist Port monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: true | false -sysmon.busy_dist_port = true - -## The time interval for the periodic cpu check -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 60s -os_mon.cpu_check_interval = 60s - -## The threshold, as percentage of system cpu, for how much system cpu can be used before the corresponding alarm is set. -## -## Default: 80% -os_mon.cpu_high_watermark = 80% - -## The threshold, as percentage of system cpu, for how much system cpu can be used before the corresponding alarm is clear. -## -## Default: 60% -os_mon.cpu_low_watermark = 60% - -## The time interval for the periodic memory check -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 60s -os_mon.mem_check_interval = 60s - -## The threshold, as percentage of system memory, for how much system memory can be allocated before the corresponding alarm is set. -## -## Default: 70% -os_mon.sysmem_high_watermark = 70% - -## The threshold, as percentage of system memory, for how much system memory can be allocated by one Erlang process before the corresponding alarm is set. -## -## Default: 5% -os_mon.procmem_high_watermark = 5% - -## The time interval for the periodic process limit check -## -## Value: Duration -## -## Default: 30s -vm_mon.check_interval = 30s - -## The threshold, as percentage of processes, for how many processes can simultaneously exist at the local node before the corresponding alarm is set. -## -## Default: 80% -vm_mon.process_high_watermark = 80% - -## The threshold, as percentage of processes, for how many processes can simultaneously exist at the local node before the corresponding alarm is clear. -## -## Default: 60% -vm_mon.process_low_watermark = 60% - -{{ additional_configs }} diff --git a/_build/emqx/conf/plugins/emqx_bridge_mqtt.conf b/_build/emqx/conf/plugins/emqx_bridge_mqtt.conf deleted file mode 100644 index 54c2ac1c0c..0000000000 --- a/_build/emqx/conf/plugins/emqx_bridge_mqtt.conf +++ /dev/null @@ -1,169 +0,0 @@ -##==================================================================== -## Configuration for EMQ X MQTT Broker Bridge -##==================================================================== - -##-------------------------------------------------------------------- -## Bridges to aws -##-------------------------------------------------------------------- - -## Bridge address: node name for local bridge, host:port for remote. -## -## Value: String -## Example: emqx@127.0.0.1, 127.0.0.1:1883 -bridge.mqtt.aws.address = 127.0.0.1:1883 - -## Protocol version of the bridge. -## -## Value: Enum -## - mqttv5 -## - mqttv4 -## - mqttv3 -bridge.mqtt.aws.proto_ver = mqttv4 - -## Start type of the bridge. -## -## Value: enum -## manual -## auto -bridge.mqtt.aws.start_type = manual - -## Whether to enable bridge mode for mqtt bridge -## -## This option is prepared for the mqtt broker which does not -## support bridge_mode such as the mqtt-plugin of the rabbitmq -## -## Value: boolean -bridge.mqtt.aws.bridge_mode = true - -## The ClientId of a remote bridge. -## -## Value: String -bridge.mqtt.aws.clientid = bridge_aws - -## The Clean start flag of a remote bridge. -## -## Value: boolean -## Default: true -## -## NOTE: Some IoT platforms require clean_start -## must be set to 'true' -bridge.mqtt.aws.clean_start = true - -## The username for a remote bridge. -## -## Value: String -bridge.mqtt.aws.username = user - -## The password for a remote bridge. -## -## Value: String -bridge.mqtt.aws.password = passwd - -## Topics that need to be forward to AWS IoTHUB -## -## Value: String -## Example: topic1/#,topic2/# -bridge.mqtt.aws.forwards = topic1/#,topic2/# - -## Forward messages to the mountpoint of an AWS IoTHUB -## -## Value: String -bridge.mqtt.aws.forward_mountpoint = bridge/aws/${node}/ - -## Need to subscribe to AWS topics -## -## Value: String -## bridge.mqtt.aws.subscription.1.topic = cmd/topic1 - -## Need to subscribe to AWS topics QoS. -## -## Value: Number -## bridge.mqtt.aws.subscription.1.qos = 1 - -## A mountpoint that receives messages from AWS IoTHUB -## -## Value: String -## bridge.mqtt.aws.receive_mountpoint = receive/aws/ - - -## Bribge to remote server via SSL. -## -## Value: on | off -bridge.mqtt.aws.ssl = off - -## PEM-encoded CA certificates of the bridge. -## -## Value: File -bridge.mqtt.aws.cacertfile = {{ platform_etc_dir }}/certs/cacert.pem - -## Client SSL Certfile of the bridge. -## -## Value: File -bridge.mqtt.aws.certfile = {{ platform_etc_dir }}/certs/client-cert.pem - -## Client SSL Keyfile of the bridge. -## -## Value: File -bridge.mqtt.aws.keyfile = {{ platform_etc_dir }}/certs/client-key.pem - -## SSL Ciphers used by the bridge. -## -## Value: String -bridge.mqtt.aws.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384 - -## Ciphers for TLS PSK. -## Note that 'bridge.${BridgeName}.ciphers' and 'bridge.${BridgeName}.psk_ciphers' cannot -## be configured at the same time. -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -bridge.mqtt.aws.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## Ping interval of a down bridge. -## -## Value: Duration -## Default: 10 seconds -bridge.mqtt.aws.keepalive = 60s - -## TLS versions used by the bridge. -## -## Value: String -bridge.mqtt.aws.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## Bridge reconnect time. -## -## Value: Duration -## Default: 30 seconds -bridge.mqtt.aws.reconnect_interval = 30s - -## Retry interval for bridge QoS1 message delivering. -## -## Value: Duration -bridge.mqtt.aws.retry_interval = 20s - -## Publish messages in batches, only RPC Bridge supports -## -## Value: Integer -## default: 32 -bridge.mqtt.aws.batch_size = 32 - -## Inflight size. -## -## Value: Integer -bridge.mqtt.aws.max_inflight_size = 32 - -## Base directory for replayq to store messages on disk -## If this config entry is missing or set to undefined, -## replayq works in a mem-only manner. -## -## Value: String -bridge.mqtt.aws.queue.replayq_dir = {{ platform_data_dir }}/emqx_aws_bridge/ - -## Replayq segment size -## -## Value: Bytesize -bridge.mqtt.aws.queue.replayq_seg_bytes = 10MB - -## Replayq max total size -## -## Value: Bytesize -bridge.mqtt.aws.queue.max_total_size = 5GB - diff --git a/_build/emqx/conf/plugins/emqx_dashboard.conf b/_build/emqx/conf/plugins/emqx_dashboard.conf deleted file mode 100644 index 7c2125b4ce..0000000000 --- a/_build/emqx/conf/plugins/emqx_dashboard.conf +++ /dev/null @@ -1,129 +0,0 @@ -##-------------------------------------------------------------------- -## EMQ X Dashboard -##-------------------------------------------------------------------- - -## Default user's login name. -## -## Value: String -dashboard.default_user.login = admin - -## Default user's password. -## -## Value: String -dashboard.default_user.password = public - -##-------------------------------------------------------------------- -## HTTP Listener - -## The port that the Dashboard HTTP listener will bind. -## -## Value: Port -## -## Examples: 18083 -dashboard.listener.http = 18083 - -## The acceptor pool for external Dashboard HTTP listener. -## -## Value: Number -dashboard.listener.http.acceptors = 4 - -## Maximum number of concurrent Dashboard HTTP connections. -## -## Value: Number -dashboard.listener.http.max_clients = 512 - -## Set up the socket for IPv6. -## -## Value: false | true -dashboard.listener.http.inet6 = false - -## Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -## -## Value: false | true -dashboard.listener.http.ipv6_v6only = false - -##-------------------------------------------------------------------- -## HTTPS Listener - -## The port that the Dashboard HTTPS listener will bind. -## -## Value: Port -## -## Examples: 18084 -## dashboard.listener.https = 18084 - -## The acceptor pool for external Dashboard HTTPS listener. -## -## Value: Number -## dashboard.listener.https.acceptors = 2 - -## Maximum number of concurrent Dashboard HTTPS connections. -## -## Value: Number -## dashboard.listener.https.max_clients = 512 - -## Set up the socket for IPv6. -## -## Value: false | true -## dashboard.listener.https.inet6 = false - -## Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -## -## Value: false | true -## dashboard.listener.https.ipv6_v6only = false - -## Path to the file containing the user's private PEM-encoded key. -## -## Value: File -## dashboard.listener.https.keyfile = etc/certs/key.pem - -## Path to a file containing the user certificate. -## -## Value: File -## dashboard.listener.https.certfile = etc/certs/cert.pem - -## Path to the file containing PEM-encoded CA certificates. -## -## Value: File -## dashboard.listener.https.cacertfile = etc/certs/cacert.pem - -## See: 'listener.ssl..dhfile' in emq.conf -## -## Value: File -## dashboard.listener.https.dhfile = {{ platform_etc_dir }}/certs/dh-params.pem - -## See: 'listener.ssl..vefify' in emq.conf -## -## Value: vefify_peer | verify_none -## dashboard.listener.https.verify = verify_peer - -## See: 'listener.ssl..fail_if_no_peer_cert' in emq.conf -## -## Value: false | true -## dashboard.listener.https.fail_if_no_peer_cert = true - -## TLS versions only to protect from POODLE attack. -## -## Value: String, seperated by ',' -## dashboard.listener.https.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## See: 'listener.ssl..ciphers' in emq.conf -## -## Value: Ciphers -## dashboard.listener.https.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA - -## See: 'listener.ssl..secure_renegotiate' in emq.conf -## -## Value: on | off -## dashboard.listener.https.secure_renegotiate = off - -## See: 'listener.ssl..reuse_sessions' in emq.conf -## -## Value: on | off -## dashboard.listener.https.reuse_sessions = on - -## See: 'listener.ssl..honor_cipher_order' in emq.conf -## -## Value: on | off -## dashboard.listener.https.honor_cipher_order = on - diff --git a/_build/emqx/conf/plugins/emqx_extension_hook.conf b/_build/emqx/conf/plugins/emqx_extension_hook.conf deleted file mode 100644 index cb44be2a6b..0000000000 --- a/_build/emqx/conf/plugins/emqx_extension_hook.conf +++ /dev/null @@ -1,24 +0,0 @@ -##==================================================================== -## EMQ X Hooks -##==================================================================== - -##-------------------------------------------------------------------- -## Driver confs - -## Setup the supported drivers -## -## Value: python2 | python3 | java -exhook.drivers = python3 - -## Search path for scripts/library -## -exhook.drivers.python3.path = {{ platform_data_dir }}/extension/ - -## Call timeout -## -## Value: Duration -##exhook.drivers.python3.call_timeout = 5s - -## Initial module name -## -##exhook.drivers.python3.init_module = main diff --git a/_build/emqx/conf/plugins/emqx_lua_hook.conf b/_build/emqx/conf/plugins/emqx_lua_hook.conf deleted file mode 100644 index f0256afaec..0000000000 --- a/_build/emqx/conf/plugins/emqx_lua_hook.conf +++ /dev/null @@ -1,4 +0,0 @@ -##-------------------------------------------------------------------- -## EMQ X Lua Hook -##-------------------------------------------------------------------- - diff --git a/_build/emqx/conf/plugins/emqx_management.conf b/_build/emqx/conf/plugins/emqx_management.conf deleted file mode 100644 index 31a3c1dc53..0000000000 --- a/_build/emqx/conf/plugins/emqx_management.conf +++ /dev/null @@ -1,52 +0,0 @@ -##-------------------------------------------------------------------- -## EMQ X Management Plugin -##-------------------------------------------------------------------- - -## Max Row Limit -management.max_row_limit = 10000 - -## Application default secret -## -## Value: String -## management.application.default_secret = public - -## Default Application ID -## -## Value: String -management.default_application.id = admin - -## Default Application Secret -## -## Value: String -management.default_application.secret = public - -##-------------------------------------------------------------------- -## HTTP Listener - -management.listener.http = 8081 -management.listener.http.acceptors = 2 -management.listener.http.max_clients = 512 -management.listener.http.backlog = 512 -management.listener.http.send_timeout = 15s -management.listener.http.send_timeout_close = on -management.listener.http.inet6 = false -management.listener.http.ipv6_v6only = false - -##-------------------------------------------------------------------- -## HTTPS Listener - -## management.listener.https = 8081 -## management.listener.https.acceptors = 2 -## management.listener.https.max_clients = 512 -## management.listener.https.backlog = 512 -## management.listener.https.send_timeout = 15s -## management.listener.https.send_timeout_close = on -## management.listener.https.certfile = etc/certs/cert.pem -## management.listener.https.keyfile = etc/certs/key.pem -## management.listener.https.cacertfile = etc/certs/cacert.pem -## management.listener.https.verify = verify_peer -## management.listener.https.tls_versions = tlsv1.2,tlsv1.1,tlsv1 -## management.listener.https.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA -## management.listener.https.fail_if_no_peer_cert = true -## management.listener.https.inet6 = false -## management.listener.https.ipv6_v6only = false diff --git a/_build/emqx/conf/plugins/emqx_psk_file.conf b/_build/emqx/conf/plugins/emqx_psk_file.conf deleted file mode 100644 index 3cee1c9266..0000000000 --- a/_build/emqx/conf/plugins/emqx_psk_file.conf +++ /dev/null @@ -1,2 +0,0 @@ -psk.file.path = {{ platform_etc_dir }}/psk.txt -psk.file.delimiter = : \ No newline at end of file diff --git a/_build/emqx/conf/plugins/emqx_recon.conf b/_build/emqx/conf/plugins/emqx_recon.conf deleted file mode 100644 index 1ca23bfc21..0000000000 --- a/_build/emqx/conf/plugins/emqx_recon.conf +++ /dev/null @@ -1,4 +0,0 @@ -##-------------------------------------------------------------------- -## Recon Plugin -##-------------------------------------------------------------------- - diff --git a/_build/emqx/conf/plugins/emqx_reloader.conf b/_build/emqx/conf/plugins/emqx_reloader.conf deleted file mode 100644 index d174ca37eb..0000000000 --- a/_build/emqx/conf/plugins/emqx_reloader.conf +++ /dev/null @@ -1,18 +0,0 @@ -##-------------------------------------------------------------------- -## Reloader Plugin -##-------------------------------------------------------------------- - -## Interval of hot code reloading. -## -## Value: Duration -## - h: hour -## - m: minute -## - s: second -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 20s: 20 seconds -## -## Defaut: 60s -reloader.interval = 60s diff --git a/_build/emqx/conf/plugins/emqx_retainer.conf b/_build/emqx/conf/plugins/emqx_retainer.conf deleted file mode 100644 index 0a883cee56..0000000000 --- a/_build/emqx/conf/plugins/emqx_retainer.conf +++ /dev/null @@ -1,41 +0,0 @@ -##-------------------------------------------------------------------- -## EMQ X Retainer -##-------------------------------------------------------------------- - -## Where to store the retained messages. -## -## Notice that all nodes in the same cluster have to be configured to -## use the same storage_type. -## -## Value: ram | disc | disc_only -## - ram: memory only -## - disc: both memory and disc -## - disc_only: disc only -## -## Default: ram -retainer.storage_type = ram - -## Maximum number of retained messages. 0 means no limit. -## -## Value: Number >= 0 -retainer.max_retained_messages = 0 - -## Maximum retained message size. -## -## Value: Bytes -retainer.max_payload_size = 1MB - -## Expiry interval of the retained messages. Never expire if the value is 0. -## -## Value: Duration -## - h: hour -## - m: minute -## - s: second -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 20s: 20 seconds -## -## Defaut: 0 -retainer.expiry_interval = 0 diff --git a/_build/emqx/conf/plugins/emqx_rule_engine.conf b/_build/emqx/conf/plugins/emqx_rule_engine.conf deleted file mode 100644 index 2fe9467798..0000000000 --- a/_build/emqx/conf/plugins/emqx_rule_engine.conf +++ /dev/null @@ -1,42 +0,0 @@ -##==================================================================== -## Rule Engine for EMQ X R4.0 -##==================================================================== - -rule_engine.ignore_sys_message = on - -## Event Messages -## -## If enabled (on), rule engine publishes the event as an MQTT message -## with topic='$events/' on the occurrence of an emqx event. -## -## If disabled, rule engine stops publishing the event messages, but -## the event message can still be processed by the rule SQL. e.g. rule SQL: -## -## SELECT * FROM "$events/client_connected" -## -## will still work even if 'rule_engine.events.client_connected' is set to 'off' -## -## EMQ Event to event message mapping: -## -## - client.connected -> $events/client_connected -## - client.disconnected -> $events/client_disconnected -## - session.subscribed -> $events/session_subscribed -## - session.unsubscribed -> $events/session_unsubscribed -## - message.delivered -> $events/message_delivered -## - message.acked -> $events/message_acked -## - message.dropped -> $events/message_dropped -## -## Config Value Format: Toggle, QoS-Level -## -## Toggle: on/off -## -## QoS-Level: qos0/qos1/qos2 - -#rule_engine.events.client_connected = on, qos1 -rule_engine.events.client_connected = off -rule_engine.events.client_disconnected = off -rule_engine.events.session_subscribed = off -rule_engine.events.session_unsubscribed = off -rule_engine.events.message_delivered = off -rule_engine.events.message_acked = off -rule_engine.events.message_dropped = off diff --git a/_build/emqx/conf/plugins/emqx_sasl.conf b/_build/emqx/conf/plugins/emqx_sasl.conf deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/_build/emqx/conf/plugins/emqx_statsd.conf b/_build/emqx/conf/plugins/emqx_statsd.conf deleted file mode 100644 index c19301e0ad..0000000000 --- a/_build/emqx/conf/plugins/emqx_statsd.conf +++ /dev/null @@ -1,9 +0,0 @@ -##-------------------------------------------------------------------- -## Statsd for EMQ X -##-------------------------------------------------------------------- - -statsd.push.gateway.server = http://127.0.0.1:9091 - -statsd.interval = 15000 - -#prometheus.collector.1 = emqx_statsd diff --git a/_build/emqx/conf/plugins/emqx_web_hook.conf b/_build/emqx/conf/plugins/emqx_web_hook.conf deleted file mode 100644 index e4cb0c5f1f..0000000000 --- a/_build/emqx/conf/plugins/emqx_web_hook.conf +++ /dev/null @@ -1,33 +0,0 @@ -##==================================================================== -## WebHook -##==================================================================== - -## The web services URL for Hook request -## -## Value: String -web.hook.api.url = http://127.0.0.1:8080 - -## Encode message payload field -## -## Value: base64 | base62 -## web.hook.encode_payload = base64 - -##-------------------------------------------------------------------- -## Hook Rules - -## These configuration items represent a list of events should be forwarded -## -## Format: -## web.hook.rule.. = -web.hook.rule.client.connect.1 = {"action": "on_client_connect"} -web.hook.rule.client.connack.1 = {"action": "on_client_connack"} -web.hook.rule.client.connected.1 = {"action": "on_client_connected"} -web.hook.rule.client.disconnected.1 = {"action": "on_client_disconnected"} -web.hook.rule.client.subscribe.1 = {"action": "on_client_subscribe"} -web.hook.rule.client.unsubscribe.1 = {"action": "on_client_unsubscribe"} -web.hook.rule.session.subscribed.1 = {"action": "on_session_subscribed"} -web.hook.rule.session.unsubscribed.1 = {"action": "on_session_unsubscribed"} -web.hook.rule.session.terminated.1 = {"action": "on_session_terminated"} -web.hook.rule.message.publish.1 = {"action": "on_message_publish"} -web.hook.rule.message.delivered.1 = {"action": "on_message_delivered"} -web.hook.rule.message.acked.1 = {"action": "on_message_acked"} diff --git a/_build/emqx/conf/schema/emqx.schema b/_build/emqx/conf/schema/emqx.schema deleted file mode 100644 index 6cb56cd073..0000000000 --- a/_build/emqx/conf/schema/emqx.schema +++ /dev/null @@ -1,2093 +0,0 @@ -%%-*- mode: erlang -*- -%% EMQ X R4.0 config mapping - -%%-------------------------------------------------------------------- -%% Cluster -%%-------------------------------------------------------------------- - -%% @doc Cluster name -{mapping, "cluster.name", "ekka.cluster_name", [ - {default, emqxcl}, - {datatype, atom} -]}. - -%% @doc Cluster discovery -{mapping, "cluster.discovery", "ekka.cluster_discovery", [ - {default, manual}, - {datatype, atom} -]}. - -%% @doc Clean down node from the cluster -{mapping, "cluster.autoclean", "ekka.cluster_autoclean", [ - {datatype, {duration, ms}} -]}. - -%% @doc Cluster autoheal -{mapping, "cluster.autoheal", "ekka.cluster_autoheal", [ - {datatype, flag}, - {default, off} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by static node list - -{mapping, "cluster.static.seeds", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by UDP Multicast - -{mapping, "cluster.mcast.addr", "ekka.cluster_discovery", [ - {default, "239.192.0.1"}, - {datatype, string} -]}. - -{mapping, "cluster.mcast.ports", "ekka.cluster_discovery", [ - {default, "4369"}, - {datatype, string} -]}. - -{mapping, "cluster.mcast.iface", "ekka.cluster_discovery", [ - {datatype, string}, - {default, "0.0.0.0"} -]}. - -{mapping, "cluster.mcast.ttl", "ekka.cluster_discovery", [ - {datatype, integer}, - {default, 255} -]}. - -{mapping, "cluster.mcast.loop", "ekka.cluster_discovery", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "cluster.mcast.sndbuf", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "16KB"} -]}. - -{mapping, "cluster.mcast.recbuf", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "16KB"} -]}. - -{mapping, "cluster.mcast.buffer", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "32KB"} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by DNS A Record - -{mapping, "cluster.dns.name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%% @doc The erlang distributed protocol -{mapping, "cluster.proto_dist", "ekka.proto_dist", [ - {default, "inet_tcp"}, - {datatype, {enum, [inet_tcp, inet6_tcp, inet_tls]}}, - hidden -]}. - -{mapping, "cluster.dns.app", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster using etcd - -{mapping, "cluster.etcd.server", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.prefix", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.node_ttl", "ekka.cluster_discovery", [ - {datatype, {duration, ms}}, - {default, "1m"} -]}. - -{mapping, "cluster.etcd.ssl.keyfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.ssl.certfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.ssl.cacertfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster on K8s - -{mapping, "cluster.k8s.apiserver", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.service_name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.address_type", "ekka.cluster_discovery", [ - {datatype, {enum, [ip, dns, hostname]}} -]}. - -{mapping, "cluster.k8s.app_name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.namespace", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.suffix", "ekka.cluster_discovery", [ - {datatype, string}, - {default, ""} - ]}. - -{translation, "ekka.cluster_discovery", fun(Conf) -> - Strategy = cuttlefish:conf_get("cluster.discovery", Conf), - Filter = fun(Opts) -> [{K, V} || {K, V} <- Opts, V =/= undefined] end, - IpPort = fun(S) -> - [Addr, Port] = string:tokens(S, ":"), - {ok, Ip} = inet:parse_address(Addr), - {Ip, Port} - end, - Options = fun(static) -> - [{seeds, [list_to_atom(S) || S <- string:tokens(cuttlefish:conf_get("cluster.static.seeds", Conf, ""), ",")]}]; - (mcast) -> - {ok, Addr} = inet:parse_address(cuttlefish:conf_get("cluster.mcast.addr", Conf)), - {ok, Iface} = inet:parse_address(cuttlefish:conf_get("cluster.mcast.iface", Conf)), - Ports = [list_to_integer(S) || S <- string:tokens(cuttlefish:conf_get("cluster.mcast.ports", Conf), ",")], - [{addr, Addr}, {ports, Ports}, {iface, Iface}, - {ttl, cuttlefish:conf_get("cluster.mcast.ttl", Conf, 1)}, - {loop, cuttlefish:conf_get("cluster.mcast.loop", Conf, true)}]; - (dns) -> - [{name, cuttlefish:conf_get("cluster.dns.name", Conf)}, - {app, cuttlefish:conf_get("cluster.dns.app", Conf)}]; - (etcd) -> - SslOpts = fun(Conf) -> - Options = cuttlefish_variable:filter_by_prefix("cluster.etcd.ssl", Conf), - lists:map(fun({["cluster", "etcd", "ssl", Name], Value}) -> - {list_to_atom(Name), Value} - end, Options) - end, - [{server, string:tokens(cuttlefish:conf_get("cluster.etcd.server", Conf), ",")}, - {prefix, cuttlefish:conf_get("cluster.etcd.prefix", Conf, "emqcl")}, - {node_ttl, cuttlefish:conf_get("cluster.etcd.node_ttl", Conf, 60)}, - {ssl_options, SslOpts(Conf)}]; - (k8s) -> - [{apiserver, cuttlefish:conf_get("cluster.k8s.apiserver", Conf)}, - {service_name, cuttlefish:conf_get("cluster.k8s.service_name", Conf)}, - {address_type, cuttlefish:conf_get("cluster.k8s.address_type", Conf, ip)}, - {app_name, cuttlefish:conf_get("cluster.k8s.app_name", Conf)}, - {namespace, cuttlefish:conf_get("cluster.k8s.namespace", Conf)}, - {suffix, cuttlefish:conf_get("cluster.k8s.suffix", Conf, "")}]; - (manual) -> - [ ] - end, - {Strategy, Filter(Options(Strategy))} -end}. - -%%-------------------------------------------------------------------- -%% Node -%%-------------------------------------------------------------------- - -%% @doc Node name -{mapping, "node.name", "vm_args.-name", [ - {default, "emqx@127.0.0.1"} -]}. - -%% @doc Specify SSL Options in the file if using SSL for erlang distribution -{mapping, "node.ssl_dist_optfile", "vm_args.-ssl_dist_optfile", [ - {datatype, string}, - hidden -]}. - -%% @doc Secret cookie for distributed erlang node -{mapping, "node.cookie", "vm_args.-setcookie", [ - {default, "emqxsecretcookie"} -]}. - -{mapping, "node.data_dir", "emqx.data_dir", [ - {datatype, string} -]}. - -%% @doc http://erlang.org/doc/man/heart.html -{mapping, "node.heartbeat", "vm_args.-heart", [ - {datatype, flag}, - hidden -]}. - -{translation, "vm_args.-heart", fun(Conf) -> - case cuttlefish:conf_get("node.heartbeat", Conf) of - true -> ""; - false -> cuttlefish:invalid("should be 'on' or comment the line!") - end -end}. - -%% @doc More information at: http://erlang.org/doc/man/erl.html -{mapping, "node.async_threads", "vm_args.+A", [ - {datatype, integer}, - {validators, ["range:0-1024"]} -]}. - -%% @doc Erlang Process Limit -{mapping, "node.process_limit", "vm_args.+P", [ - {datatype, integer}, - hidden -]}. - -%% @doc The maximum number of concurrent ports/sockets. -%% Valid range is 1024-134217727 -{mapping, "node.max_ports", "vm_args.+Q", [ - {datatype, integer}, - {validators, ["range4ports"]} -]}. - -{validator, "range4ports", "must be 1024 to 134217727", - fun(X) -> X >= 1024 andalso X =< 134217727 end}. - -%% @doc http://www.erlang.org/doc/man/erl.html#%2bzdbbl -{mapping, "node.dist_buffer_size", "vm_args.+zdbbl", [ - {datatype, bytesize}, - {commented, "32MB"}, - hidden, - {validators, ["zdbbl_range"]} -]}. - -{translation, "vm_args.+zdbbl", - fun(Conf) -> - ZDBBL = cuttlefish:conf_get("node.dist_buffer_size", Conf, undefined), - case ZDBBL of - undefined -> undefined; - X when is_integer(X) -> cuttlefish_util:ceiling(X / 1024); %% Bytes to Kilobytes; - _ -> undefined - end - end}. - -{validator, "zdbbl_range", "must be between 1KB and 2097151KB", - fun(ZDBBL) -> - %% 2097151KB = 2147482624 - ZDBBL >= 1024 andalso ZDBBL =< 2147482624 - end -}. - -%% @doc Global GC Interval -{mapping, "node.global_gc_interval", "emqx.global_gc_interval", [ - {datatype, {duration, s}} -]}. - -%% @doc http://www.erlang.org/doc/man/erlang.html#system_flag-2 -{mapping, "node.fullsweep_after", "vm_args.-env ERL_FULLSWEEP_AFTER", [ - {default, 1000}, - {datatype, integer}, - hidden, - {validators, ["positive_integer"]} -]}. - -{validator, "positive_integer", "must be a positive integer", - fun(X) -> X >= 0 end}. - -%% Note: OTP R15 and earlier uses -env ERL_MAX_ETS_TABLES, -%% R16+ uses +e -%% @doc The ETS table limit -{mapping, "node.max_ets_tables", - cuttlefish:otp("R16", "vm_args.+e", "vm_args.-env ERL_MAX_ETS_TABLES"), [ - {default, 256000}, - {datatype, integer}, - hidden -]}. - -%% @doc Set the location of crash dumps -{mapping, "node.crash_dump", "vm_args.-env ERL_CRASH_DUMP", [ - {default, "{{crash_dump}}"}, - {datatype, file}, - hidden -]}. - -%% @doc http://www.erlang.org/doc/man/kernel_app.html#net_ticktime -{mapping, "node.dist_net_ticktime", "vm_args.-kernel net_ticktime", [ - {datatype, integer}, - hidden -]}. - -%% @doc http://www.erlang.org/doc/man/kernel_app.html -{mapping, "node.dist_listen_min", "kernel.inet_dist_listen_min", [ - {commented, 6369}, - {datatype, integer}, - hidden -]}. - -%% @see node.dist_listen_min -{mapping, "node.dist_listen_max", "kernel.inet_dist_listen_max", [ - {commented, 6369}, - {datatype, integer}, - hidden -]}. - -%%-------------------------------------------------------------------- -%% RPC -%%-------------------------------------------------------------------- - -%% RPC Mode. -{mapping, "rpc.mode", "emqx.rpc_mode", [ - {default, async}, - {datatype, {enum, [sync, async]}} -]}. - -{mapping, "rpc.async_batch_size", "gen_rpc.max_batch_size", [ - {default, 256}, - {datatype, integer} -]}. - -%% RPC server port. -{mapping, "rpc.tcp_server_port", "gen_rpc.tcp_server_port", [ - {default, 5369}, - {datatype, integer} -]}. - -%% Default TCP port for outgoing connections -{mapping, "rpc.tcp_client_port", "gen_rpc.tcp_client_port", [ - {default, 5369}, - {datatype, integer} -]}. - -%% Default TCP port for outgoing connections -{mapping, "rpc.tcp_client_num", "gen_rpc.tcp_client_num", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:gt_0_lt_256"]} -]}. - -{translation, "gen_rpc.tcp_client_num", fun(Conf) -> - case cuttlefish:conf_get("rpc.tcp_client_num", Conf) of - 0 -> max(1, erlang:system_info(schedulers) div 2); - V -> V - end -end}. - -%% Client connect timeout -{mapping, "rpc.connect_timeout", "gen_rpc.connect_timeout", [ - {default, "5s"}, - {datatype, {duration, ms}} -]}. - -%% Client and Server send timeout -{mapping, "rpc.send_timeout", "gen_rpc.send_timeout", [ - {default, 5000}, - {datatype, {duration, ms}} -]}. - -%% Authentication timeout -{mapping, "rpc.authentication_timeout", "gen_rpc.authentication_timeout", [ - {default, 5000}, - {datatype, {duration, ms}} -]}. - -%% Default receive timeout for call() functions -{mapping, "rpc.call_receive_timeout", "gen_rpc.call_receive_timeout", [ - {default, 15000}, - {datatype, {duration, ms}} -]}. - -%% Socket keepalive configuration -{mapping, "rpc.socket_keepalive_idle", "gen_rpc.socket_keepalive_idle", [ - {default, 7200}, - {datatype, {duration, s}} -]}. - -%% Seconds between probes -{mapping, "rpc.socket_keepalive_interval", "gen_rpc.socket_keepalive_interval", [ - {default, 75}, - {datatype, {duration, s}} -]}. - -%% Probes lost to close the connection -{mapping, "rpc.socket_keepalive_count", "gen_rpc.socket_keepalive_count", [ - {default, 9}, - {datatype, integer} -]}. - -%% Size of TCP send buffer -{mapping, "rpc.socket_sndbuf", "gen_rpc.socket_sndbuf", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -%% Size of TCP receive buffer -{mapping, "rpc.socket_recbuf", "gen_rpc.socket_recbuf", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -%% Size of TCP receive buffer -{mapping, "rpc.socket_buffer", "gen_rpc.socket_buffer", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -{validator, "range:gt_0_lt_256", "must greater than 0 and less than 256", - fun(X) -> X >= 0 andalso X < 256 end -}. - -%%-------------------------------------------------------------------- -%% Log -%%-------------------------------------------------------------------- - -{mapping, "log.to", "kernel.logger", [ - {default, console}, - {datatype, {enum, [off, file, console, both]}} -]}. - -{mapping, "log.level", "kernel.logger", [ - {default, warning}, - {datatype, {enum, [debug, info, notice, warning, error, critical, alert, emergency, all]}} -]}. - -{mapping, "log.primary_log_level", "kernel.logger_level", [ - {default, warning}, - {datatype, {enum, [debug, info, notice, warning, error, critical, alert, emergency, all]}} -]}. - -{mapping, "log.logger_sasl_compatible", "kernel.logger_sasl_compatible", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "log.dir", "kernel.logger", [ - {default, "log"}, - {datatype, string} -]}. - -{mapping, "log.file", "kernel.logger", [ - {default, "emqx.log"}, - {datatype, file} -]}. - -{mapping, "log.chars_limit", "kernel.logger", [ - {default, -1}, - {datatype, integer} -]}. - -{mapping, "log.rotation", "kernel.logger", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "log.rotation.size", "kernel.logger", [ - {default, "10MB"}, - {datatype, bytesize} -]}. - -{mapping, "log.size", "kernel.logger", [ - {default, infinity}, - {datatype, [bytesize, atom]} -]}. - -{mapping, "log.rotation.count", "kernel.logger", [ - {default, 5}, - {datatype, integer} -]}. - -{mapping, "log.$level.file", "kernel.logger", [ - {datatype, file} -]}. - -{mapping, "log.sync_mode_qlen", "kernel.logger", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "log.drop_mode_qlen", "kernel.logger", [ - {default, 3000}, - {datatype, integer} -]}. - -{mapping, "log.flush_qlen", "kernel.logger", [ - {default, 8000}, - {datatype, integer} -]}. - -{mapping, "log.overload_kill", "kernel.logger", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "log.overload_kill_mem_size", "kernel.logger", [ - {default, "30MB"}, - {datatype, bytesize} -]}. - -{mapping, "log.overload_kill_qlen", "kernel.logger", [ - {default, 20000}, - {datatype, integer} -]}. - -{mapping, "log.overload_kill_restart_after", "kernel.logger", [ - {default, "5s"}, - {datatype, [{duration, ms}, atom]} -]}. - -{mapping, "log.burst_limit", "kernel.logger", [ - {default, "disabled"}, - {datatype, string} -]}. - -{mapping, "log.sasl", "sasl.sasl_error_logger", [ - {default, off}, - {datatype, flag}, - hidden -]}. - -{mapping, "log.error_logger", "kernel.error_logger", [ - {default, silent}, - {datatype, {enum, [silent]}}, - hidden -]}. - -%% disable lager -{mapping, "lager.handlers", "lager.handlers", [ - {default, []}, - hidden -]}. -{mapping, "lager.crash_log", "lager.crash_log", [ - {default, off}, - {datatype, flag}, - hidden -]}. - -{translation, "kernel.logger_level", fun(_, _, Conf) -> - cuttlefish:conf_get("log.level", Conf) -end}. - -{translation, "kernel.logger", fun(Conf) -> - LogTo = cuttlefish:conf_get("log.to", Conf), - LogLevel = cuttlefish:conf_get("log.level", Conf), - LogType = case cuttlefish:conf_get("log.rotation", Conf) of - true -> wrap; - false -> halt - end, - CharsLimit = case cuttlefish:conf_get("log.chars_limit", Conf) of - -1 -> unlimited; - V -> V - end, - Formatter = {emqx_logger_formatter, - #{template => - [time," [",level,"] ", - {clientid, - [{peername, - [clientid,"@",peername," "], - [clientid, " "]}], - [{peername, - [peername," "], - []}]}, - msg,"\n"], - chars_limit => CharsLimit}}, - {BustLimitOn, {MaxBurstCount, TimeWindow}} = - case string:tokens(cuttlefish:conf_get("log.burst_limit", Conf), ", ") of - ["disabled"] -> {false, {20000, 1000}}; - [Count, Window] -> - {true, {list_to_integer(Count), - case cuttlefish_duration:parse(Window, ms) of - Secs when is_integer(Secs) -> Secs; - {error, Reason1} -> error(Reason1) - end}} - end, - FileConf = fun(Filename) -> - BasicConf = - #{type => LogType, - file => filename:join(cuttlefish:conf_get("log.dir", Conf), Filename), - max_no_files => cuttlefish:conf_get("log.rotation.count", Conf), - sync_mode_qlen => cuttlefish:conf_get("log.sync_mode_qlen", Conf), - drop_mode_qlen => cuttlefish:conf_get("log.drop_mode_qlen", Conf), - flush_qlen => cuttlefish:conf_get("log.flush_qlen", Conf), - overload_kill_enable => cuttlefish:conf_get("log.overload_kill", Conf), - overload_kill_qlen => cuttlefish:conf_get("log.overload_kill_qlen", Conf), - overload_kill_mem_size => cuttlefish:conf_get("log.overload_kill_mem_size", Conf), - overload_kill_restart_after => cuttlefish:conf_get("log.overload_kill_restart_after", Conf), - burst_limit_enable => BustLimitOn, - burst_limit_max_count => MaxBurstCount, - burst_limit_window_time => TimeWindow - }, - MaxNoBytes = case LogType of - wrap -> cuttlefish:conf_get("log.rotation.size", Conf); - halt -> cuttlefish:conf_get("log.size", Conf) - end, - BasicConf#{max_no_bytes => MaxNoBytes} - end, - - %% For the default logger that outputs to console - DefaultHandler = - if LogTo =:= console orelse LogTo =:= both -> - [{handler, default, logger_std_h, - #{level => LogLevel, - config => #{type => standard_io}, - formatter => Formatter}}]; - true -> - [{handler, default, undefined}] - end, - - %% For the file logger - FileHandler = - if LogTo =:= file orelse LogTo =:= both -> - [{handler, file, logger_disk_log_h, - #{level => LogLevel, - config => FileConf(cuttlefish:conf_get("log.file", Conf)), - formatter => Formatter, - filesync_repeat_interval => no_repeat}}]; - true -> [] - end, - - %% For creating additional log files for specific log levels. - AdditionalLogFiles = - lists:foldl( - fun({[_, Level, _] = K, Filename}, Acc) when LogTo =:= file; LogTo =:= both -> - case cuttlefish_variable:is_fuzzy_match(K, ["log", "$level", "file"]) of - true -> [{Level, Filename} | Acc]; - false -> Acc - end; - ({_K, _V}, Acc) -> - Acc - end, [], Conf), - AdditionalHandlers = - [{handler, list_to_atom("file_for_"++Level), logger_disk_log_h, - #{level => list_to_atom(Level), - config => FileConf(Filename), - formatter => Formatter, - filesync_repeat_interval => no_repeat}} - || {Level, Filename} <- AdditionalLogFiles], - - DefaultHandler ++ FileHandler ++ AdditionalHandlers -end}. - -%%-------------------------------------------------------------------- -%% Authentication/ACL -%%-------------------------------------------------------------------- - -%% @doc Allow anonymous authentication. -{mapping, "allow_anonymous", "emqx.allow_anonymous", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc ACL nomatch. -{mapping, "acl_nomatch", "emqx.acl_nomatch", [ - {default, deny}, - {datatype, {enum, [allow, deny]}} -]}. - -%% @doc Default ACL file. -{mapping, "acl_file", "emqx.acl_file", [ - {datatype, string}, - hidden -]}. - -%% @doc Enable ACL cache for publish. -{mapping, "enable_acl_cache", "emqx.enable_acl_cache", [ - {default, on}, - {datatype, flag} -]}. - -%% @doc ACL cache time-to-live. -{mapping, "acl_cache_ttl", "emqx.acl_cache_ttl", [ - {default, "1m"}, - {datatype, {duration, ms}} -]}. - -%% @doc ACL cache size. -{mapping, "acl_cache_max_size", "emqx.acl_cache_max_size", [ - {default, 32}, - {datatype, integer}, - {validators, ["range:gt_0"]} -]}. - -%% @doc Action when acl check reject current operation -{mapping, "acl_deny_action", "emqx.acl_deny_action", [ - {default, ignore}, - {datatype, {enum, [ignore, disconnect]}} -]}. - -%% @doc Flapping detect policy -{mapping, "flapping_detect_policy", "emqx.flapping_detect_policy", [ - {datatype, string}, - {default, "30,1m,5m"} -]}. - -{translation, "emqx.flapping_detect_policy", fun(Conf) -> - Policy = cuttlefish:conf_get("flapping_detect_policy", Conf), - [Threshold, Duration, Interval] = string:tokens(Policy, ", "), - ParseDuration = fun(S, Dur) -> - case cuttlefish_duration:parse(S, Dur) of - I when is_integer(I) -> I; - {error, Reason} -> error(Reason) - end - end, - #{threshold => list_to_integer(Threshold), - duration => ParseDuration(Duration, ms), - banned_interval => ParseDuration(Interval, s) - } -end}. - -{validator, "range:gt_0", "must greater than 0", - fun(X) -> X > 0 end -}. - -%%-------------------------------------------------------------------- -%% MQTT Protocol -%%-------------------------------------------------------------------- - -%% @doc Max Packet Size Allowed, 1MB by default. -{mapping, "mqtt.max_packet_size", "emqx.max_packet_size", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -%% @doc Set the Max ClientId Length Allowed. -{mapping, "mqtt.max_clientid_len", "emqx.max_clientid_len", [ - {default, 65535}, - {datatype, integer} -]}. - -%% @doc Set the Maximum topic levels. -{mapping, "mqtt.max_topic_levels", "emqx.max_topic_levels", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Set the Maximum QoS allowed. -{mapping, "mqtt.max_qos_allowed", "emqx.max_qos_allowed", [ - {default, 2}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -%% @doc Set the Maximum Topic Alias. -{mapping, "mqtt.max_topic_alias", "emqx.max_topic_alias", [ - {default, 65535}, - {datatype, integer} -]}. - -%% @doc Whether the server supports MQTT retained messages. -{mapping, "mqtt.retain_available", "emqx.retain_available", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports MQTT Wildcard Subscriptions. -{mapping, "mqtt.wildcard_subscription", "emqx.wildcard_subscription", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports MQTT Shared Subscriptions. -{mapping, "mqtt.shared_subscription", "emqx.shared_subscription", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -{mapping, "mqtt.ignore_loop_deliver", "emqx.ignore_loop_deliver", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether to parse the MQTT frame in strict mode -{mapping, "mqtt.strict_mode", "emqx.strict_mode", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Specify the response information returned to the client -{mapping, "mqtt.response_information", "emqx.response_information", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Zones -%%-------------------------------------------------------------------- - -%% @doc Idle timeout of the MQTT connection. -{mapping, "zone.$name.idle_timeout", "emqx.zones", [ - {default, "15s"}, - {datatype, {duration, ms}} -]}. - -{mapping, "zone.$name.allow_anonymous", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "zone.$name.acl_nomatch", "emqx.zones", [ - {datatype, {enum, [allow, deny]}} -]}. - -%% @doc Enable ACL check. -{mapping, "zone.$name.enable_acl", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Action when acl check reject current operation -{mapping, "zone.$name.acl_deny_action", "emqx.zones", [ - {default, ignore}, - {datatype, {enum, [ignore, disconnect]}} -]}. - -%% @doc Enable Ban. -{mapping, "zone.$name.enable_ban", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Enable per connection statistics. -{mapping, "zone.$name.enable_stats", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Publish limit of the MQTT connections. -{mapping, "zone.$name.publish_limit", "emqx.zones", [ - {datatype, string} -]}. - -%% @doc Max Packet Size Allowed, 64K by default. -{mapping, "zone.$name.max_packet_size", "emqx.zones", [ - {datatype, bytesize} -]}. - -%% @doc Set the Max ClientId Length Allowed. -{mapping, "zone.$name.max_clientid_len", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Set the Maximum topic levels. -{mapping, "zone.$name.max_topic_levels", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Set the Maximum QoS allowed. -{mapping, "zone.$name.max_qos_allowed", "emqx.zones", [ - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -%% @doc Set the Maximum topic alias. -{mapping, "zone.$name.max_topic_alias", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Whether the server supports retained messages. -{mapping, "zone.$name.retain_available", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports Wildcard Subscriptions. -{mapping, "zone.$name.wildcard_subscription", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports Shared Subscriptions. -{mapping, "zone.$name.shared_subscription", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Server Keepalive -{mapping, "zone.$name.server_keepalive", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Keepalive backoff -{mapping, "zone.$name.keepalive_backoff", "emqx.zones", [ - {default, 0.75}, - {datatype, float} -]}. - -%% @doc Max Number of Subscriptions Allowed. -{mapping, "zone.$name.max_subscriptions", "emqx.zones", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Upgrade QoS according to subscription? -{mapping, "zone.$name.upgrade_qos", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Max number of QoS 1 and 2 messages that can be “inflight” at one time. -%% 0 means no limit -{mapping, "zone.$name.max_inflight", "emqx.zones", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Retry interval for redelivering QoS1/2 messages. -{mapping, "zone.$name.retry_interval", "emqx.zones", [ - {default, "30s"}, - {datatype, {duration, s}} -]}. - -%% @doc Max Packets that Awaiting PUBREL, 0 means no limit -{mapping, "zone.$name.max_awaiting_rel", "emqx.zones", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Awaiting PUBREL timeout -{mapping, "zone.$name.await_rel_timeout", "emqx.zones", [ - {default, "300s"}, - {datatype, {duration, s}} -]}. - -%% @doc Ignore loop delivery of messages -{mapping, "zone.$name.ignore_loop_deliver", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Session Expiry Interval -{mapping, "zone.$name.session_expiry_interval", "emqx.zones", [ - {default, "2h"}, - {datatype, {duration, s}} -]}. - -%% @doc Max queue length. Enqueued messages when persistent client -%% disconnected, or inflight window is full. 0 means no limit. -{mapping, "zone.$name.max_mqueue_len", "emqx.zones", [ - {default, 1000}, - {datatype, integer} -]}. - -%% @doc Topic Priorities, comma separated topic=priority pairs, -%% where priority should be integer in range 1-255 (inclusive) -%% 1 being the lowest and 255 being the highest. -%% default value `none` to indicate no priority table, hence all -%% messages are treated equal, which means either highest ('infinity'), -%% or lowest (0) depending on mqueue_default_priority config. -{mapping, "zone.$name.mqueue_priorities", "emqx.zones", [ - {default, "none"}, - {datatype, string} -]}. - -%% @doc Default priority for topics not in priority table. -{mapping, "zone.$name.mqueue_default_priority", "emqx.zones", [ - {default, lowest}, - {datatype, {enum, [highest, lowest]}} -]}. - -%% @doc Queue Qos0 messages? -{mapping, "zone.$name.mqueue_store_qos0", "emqx.zones", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "zone.$name.enable_flapping_detect", "emqx.zones", [ - {datatype, flag}, - {default, off} -]}. - -%% @doc Force connection/session process GC after this number of -%% messages | bytes passed through. -%% Numbers delimited by `|'. Zero or negative is to disable. -{mapping, "zone.$name.force_gc_policy", "emqx.zones", [ - {datatype, string} - ]}. - -%% @doc Max message queue length and total heap size to force shutdown -%% connection/session process. -%% Message queue here is the Erlang process mailbox, but not the number -%% of queued MQTT messages of QoS 1 and 2. -%% Zero or negative is to disable. -{mapping, "zone.$name.force_shutdown_policy", "emqx.zones", [ - {datatype, string} -]}. - -{mapping, "zone.$name.mountpoint", "emqx.zones", [ - {datatype, string} -]}. - -%% @doc Use username replace client id -{mapping, "zone.$name.use_username_as_clientid", "emqx.zones", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether to parse the MQTT frame in strict mode -{mapping, "zone.$name.strict_mode", "emqx.zones", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Specify the response information returned to the client -{mapping, "zone.$name.response_information", "emqx.zones", [ - {datatype, string} -]}. - -%% @doc Whether to bypass the authentication step -{mapping, "zone.$name.bypass_auth_plugins", "emqx.zones", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -{translation, "emqx.zones", fun(Conf) -> - Mapping = fun("publish_limit", Val) -> - [L, D] = string:tokens(Val, ", "), - Limit = list_to_integer(L), - Duration = case cuttlefish_duration:parse(D, s) of - Secs when is_integer(Secs) -> Secs; - {error, Reason} -> error(Reason) - end, - Rate = Limit / Duration, - {publish_limit, {Rate, Limit}}; - ("force_gc_policy", Val) -> - [Count, Bytes] = string:tokens(Val, "| "), - GcPolicy = case cuttlefish_bytesize:parse(Bytes) of - {error, Reason} -> - error(Reason); - Bytes1 -> - #{bytes => Bytes1, - count => list_to_integer(Count)} - end, - {force_gc_policy, GcPolicy}; - ("force_shutdown_policy", Val) -> - [Len, Siz] = string:tokens(Val, "| "), - MaxSiz = case WordSize = erlang:system_info(wordsize) of - 8 -> % arch_64 - (1 bsl 59) - 1; - 4 -> % arch_32 - (1 bsl 27) - 1 - end, - ShutdownPolicy = - case cuttlefish_bytesize:parse(Siz) of - {error, Reason} -> - error(Reason); - Siz1 when Siz1 > MaxSiz -> - cuttlefish:invalid(io_lib:format("force_shutdown_policy: heap-size ~s is too large", [Siz])); - Siz1 -> - #{message_queue_len => list_to_integer(Len), - max_heap_size => Siz1 div WordSize} - end, - {force_shutdown_policy, ShutdownPolicy}; - ("mqueue_priorities", Val) -> - case Val of - "none" -> {mqueue_priorities, none}; % NO_PRIORITY_TABLE - _ -> - MqueuePriorities = lists:foldl(fun(T, Acc) -> - %% NOTE: space in "= " is intended - [Topic, Prio] = string:tokens(T, "= "), - P = list_to_integer(Prio), - (P < 0 orelse P > 255) andalso error({bad_priority, Topic, Prio}), - maps:put(iolist_to_binary(Topic), P, Acc) - end, #{}, string:tokens(Val, ",")), - {mqueue_priorities, MqueuePriorities} - end; - ("mountpoint", Val) -> - {mountpoint, iolist_to_binary(Val)}; - ("response_information", Val) -> - {response_information, iolist_to_binary(Val)}; - (Opt, Val) -> - {list_to_atom(Opt), Val} - end, - maps:to_list( - lists:foldl( - fun({["zone", Name, Opt], Val}, Zones) -> - maps:update_with(list_to_atom(Name), - fun(Opts) -> [Mapping(Opt, Val)|Opts] end, - [Mapping(Opt, Val)], Zones) - end, #{}, lists:usort(cuttlefish_variable:filter_by_prefix("zone.", Conf)))) -end}. - -%%-------------------------------------------------------------------- -%% Listeners -%%-------------------------------------------------------------------- - -%%-------------------------------------------------------------------- -%% TCP Listeners - -{mapping, "listener.tcp.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.tcp.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.tcp.$name.rate_limit", "emqx.listeners", [ - {default, undefined}, - {datatype, string} -]}. - -{mapping, "listener.tcp.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.tcp.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.tcp.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -{mapping, "listener.tcp.$name.peer_cert_as_username", "emqx.listeners", [ - {datatype, {enum, [cn, dn, crt]}} -]}. - -{mapping, "listener.tcp.$name.backlog", "emqx.listeners", [ - {datatype, integer}, - {default, 1024} -]}. - -{mapping, "listener.tcp.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.tcp.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.tcp.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.tcp.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.tcp.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.tcp.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.tcp.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.tcp.$name.reuseaddr", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -%%-------------------------------------------------------------------- -%% SSL Listeners - -{mapping, "listener.ssl.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.ssl.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.rate_limit", "emqx.listeners", [ - {default, undefined}, - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -{mapping, "listener.ssl.$name.backlog", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.ssl.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.ssl.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ssl.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ssl.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ssl.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.ssl.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ssl.$name.reuseaddr", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ssl.$name.tls_versions", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.psk_ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.handshake_timeout", "emqx.listeners", [ - {default, "15s"}, - {datatype, {duration, ms}} -]}. - -{mapping, "listener.ssl.$name.dhfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.keyfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.certfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.cacertfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.verify", "emqx.listeners", [ - {datatype, atom} -]}. - -{mapping, "listener.ssl.$name.fail_if_no_peer_cert", "emqx.listeners", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "listener.ssl.$name.secure_renegotiate", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.reuse_sessions", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.honor_cipher_order", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.peer_cert_as_username", "emqx.listeners", [ - {datatype, {enum, [cn, dn, crt]}} -]}. - -%%-------------------------------------------------------------------- -%% MQTT/WebSocket Listeners - -{mapping, "listener.ws.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.ws.$name.mqtt_path", "emqx.listeners", [ - {default, "/mqtt"}, - {datatype, string} -]}. - -{mapping, "listener.ws.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ws.$name.rate_limit", "emqx.listeners", [ - {default, undefined}, - {datatype, string} -]}. - -{mapping, "listener.ws.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ws.$name.verify_protocol_header", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.ws.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ws.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -{mapping, "listener.ws.$name.backlog", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.ws.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.ws.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ws.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ws.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ws.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.ws.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ws.$name.compress", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.level", "emqx.listeners", [ - {datatype, {enum, [none, default, best_compression, best_speed]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.mem_level", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:1-9"]}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.strategy", "emqx.listeners", [ - {datatype, {enum, [default, filtered, huffman_only, rle]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.server_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.client_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.server_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.client_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - -{mapping, "listener.ws.$name.idle_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - hidden -]}. - -{mapping, "listener.ws.$name.max_frame_size", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - -%%-------------------------------------------------------------------- -%% MQTT/WebSocket/SSL Listeners - -{mapping, "listener.wss.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.wss.$name.mqtt_path", "emqx.listeners", [ - {default, "/mqtt"}, - {datatype, string} -]}. - -{mapping, "listener.wss.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.rate_limit", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.verify_protocol_header", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -%%{mapping, "listener.wss.$name.handshake_timeout", "emqx.listeners", [ -%% {default, "15s"}, -%% {datatype, {duration, ms}} -%%]}. - -{mapping, "listener.wss.$name.backlog", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.wss.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.wss.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.wss.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.wss.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.wss.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.wss.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.wss.$name.tls_versions", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.psk_ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.keyfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.certfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.cacertfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.verify", "emqx.listeners", [ - {datatype, atom} -]}. - -{mapping, "listener.wss.$name.fail_if_no_peer_cert", "emqx.listeners", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "listener.wss.$name.secure_renegotiate", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.reuse_sessions", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.honor_cipher_order", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.peer_cert_as_username", "emqx.listeners", [ - {datatype, {enum, [cn, dn, crt]}} -]}. - -{mapping, "listener.wss.$name.compress", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.level", "emqx.listeners", [ - {datatype, {enum, [none, default, best_compression, best_speed]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.mem_level", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:1-9"]}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.strategy", "emqx.listeners", [ - {datatype, {enum, [default, filtered, huffman_only, rle]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.server_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.client_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.server_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:8-15"]}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.client_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:8-15"]}, - hidden -]}. - -{mapping, "listener.wss.$name.idle_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - hidden -]}. - -{mapping, "listener.wss.$name.max_frame_size", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - - - -{translation, "emqx.listeners", fun(Conf) -> - - Filter = fun(Opts) -> [{K, V} || {K, V} <- Opts, V =/= undefined] end, - - Atom = fun(undefined) -> undefined; (S) -> list_to_atom(S) end, - - Access = fun(S) -> - [A, CIDR] = string:tokens(S, " "), - {list_to_atom(A), case CIDR of "all" -> all; _ -> CIDR end} - end, - - AccOpts = fun(Prefix) -> - case cuttlefish_variable:filter_by_prefix(Prefix ++ ".access", Conf) of - [] -> []; - Rules -> [{access_rules, [Access(Rule) || {_, Rule} <- Rules]}] - end - end, - - RateLimit = fun(undefined) -> - undefined; - (Val) -> - [L, D] = string:tokens(Val, ", "), - Limit = case cuttlefish_bytesize:parse(L) of - Sz when is_integer(Sz) -> Sz; - {error, Reason} -> error(Reason) - end, - Duration = case cuttlefish_duration:parse(D, s) of - Secs when is_integer(Secs) -> Secs; - {error, Reason1} -> error(Reason1) - end, - Rate = Limit / Duration, - {Rate, Limit} - end, - - LisOpts = fun(Prefix) -> - Filter([{acceptors, cuttlefish:conf_get(Prefix ++ ".acceptors", Conf)}, - {mqtt_path, cuttlefish:conf_get(Prefix ++ ".mqtt_path", Conf, undefined)}, - {max_connections, cuttlefish:conf_get(Prefix ++ ".max_connections", Conf)}, - {max_conn_rate, cuttlefish:conf_get(Prefix ++ ".max_conn_rate", Conf, undefined)}, - {active_n, cuttlefish:conf_get(Prefix ++ ".active_n", Conf, undefined)}, - {tune_buffer, cuttlefish:conf_get(Prefix ++ ".tune_buffer", Conf, undefined)}, - {zone, Atom(cuttlefish:conf_get(Prefix ++ ".zone", Conf, undefined))}, - {rate_limit, RateLimit(cuttlefish:conf_get(Prefix ++ ".rate_limit", Conf, undefined))}, - {proxy_protocol, cuttlefish:conf_get(Prefix ++ ".proxy_protocol", Conf, undefined)}, - {proxy_protocol_timeout, cuttlefish:conf_get(Prefix ++ ".proxy_protocol_timeout", Conf, undefined)}, - {verify_protocol_header, cuttlefish:conf_get(Prefix ++ ".verify_protocol_header", Conf, undefined)}, - {peer_cert_as_username, cuttlefish:conf_get(Prefix ++ ".peer_cert_as_username", Conf, undefined)}, - {compress, cuttlefish:conf_get(Prefix ++ ".compress", Conf, undefined)}, - {idle_timeout, cuttlefish:conf_get(Prefix ++ ".idle_timeout", Conf, undefined)}, - {max_frame_size, cuttlefish:conf_get(Prefix ++ ".max_frame_size", Conf, undefined)} | AccOpts(Prefix)]) - end, - DeflateOpts = fun(Prefix) -> - Filter([{level, cuttlefish:conf_get(Prefix ++ ".deflate_opts.level", Conf, undefined)}, - {mem_level, cuttlefish:conf_get(Prefix ++ ".deflate_opts.mem_level", Conf, undefined)}, - {strategy, cuttlefish:conf_get(Prefix ++ ".deflate_opts.strategy", Conf, undefined)}, - {server_context_takeover, cuttlefish:conf_get(Prefix ++ ".deflate_opts.server_context_takeover", Conf, undefined)}, - {client_context_takeover, cuttlefish:conf_get(Prefix ++ ".deflate_opts.client_context_takeover", Conf, undefined)}, - {server_max_windows_bits, cuttlefish:conf_get(Prefix ++ ".deflate_opts.server_max_window_bits", Conf, undefined)}, - {client_max_windows_bits, cuttlefish:conf_get(Prefix ++ ".deflate_opts.client_max_window_bits", Conf, undefined)}]) - end, - TcpOpts = fun(Prefix) -> - Filter([{backlog, cuttlefish:conf_get(Prefix ++ ".backlog", Conf, undefined)}, - {send_timeout, cuttlefish:conf_get(Prefix ++ ".send_timeout", Conf, undefined)}, - {send_timeout_close, cuttlefish:conf_get(Prefix ++ ".send_timeout_close", Conf, undefined)}, - {recbuf, cuttlefish:conf_get(Prefix ++ ".recbuf", Conf, undefined)}, - {sndbuf, cuttlefish:conf_get(Prefix ++ ".sndbuf", Conf, undefined)}, - {buffer, cuttlefish:conf_get(Prefix ++ ".buffer", Conf, undefined)}, - {nodelay, cuttlefish:conf_get(Prefix ++ ".nodelay", Conf, true)}, - {reuseaddr, cuttlefish:conf_get(Prefix ++ ".reuseaddr", Conf, undefined)}]) - end, - SplitFun = fun(undefined) -> undefined; (S) -> string:tokens(S, ",") end, - MapPSKCiphers = fun(PSKCiphers) -> - lists:map( - fun("PSK-AES128-CBC-SHA") -> {psk, aes_128_cbc, sha}; - ("PSK-AES256-CBC-SHA") -> {psk, aes_256_cbc, sha}; - ("PSK-3DES-EDE-CBC-SHA") -> {psk, '3des_ede_cbc', sha}; - ("PSK-RC4-SHA") -> {psk, rc4_128, sha} - end, PSKCiphers) - end, - SslOpts = fun(Prefix) -> - Versions = case SplitFun(cuttlefish:conf_get(Prefix ++ ".tls_versions", Conf, undefined)) of - undefined -> undefined; - L -> [list_to_atom(V) || V <- L] - end, - TLSCiphers = cuttlefish:conf_get(Prefix++".ciphers", Conf, undefined), - PSKCiphers = cuttlefish:conf_get(Prefix++".psk_ciphers", Conf, undefined), - Ciphers = - case {TLSCiphers, PSKCiphers} of - {undefined, undefined} -> - cuttlefish:invalid(Prefix++".ciphers or "++Prefix++".psk_ciphers is absent"); - {TLSCiphers, undefined} -> - SplitFun(TLSCiphers); - {undefined, PSKCiphers} -> - MapPSKCiphers(SplitFun(PSKCiphers)); - {_TLSCiphers, _PSKCiphers} -> - cuttlefish:invalid(Prefix++".ciphers and "++Prefix++".psk_ciphers cannot be configured at the same time") - end, - UserLookupFun = - case PSKCiphers of - undefined -> undefined; - _ -> {fun emqx_psk:lookup/3, <<>>} - end, - Filter([{versions, Versions}, - {ciphers, Ciphers}, - {user_lookup_fun, UserLookupFun}, - {handshake_timeout, cuttlefish:conf_get(Prefix ++ ".handshake_timeout", Conf, undefined)}, - {dhfile, cuttlefish:conf_get(Prefix ++ ".dhfile", Conf, undefined)}, - {keyfile, cuttlefish:conf_get(Prefix ++ ".keyfile", Conf, undefined)}, - {certfile, cuttlefish:conf_get(Prefix ++ ".certfile", Conf, undefined)}, - {cacertfile, cuttlefish:conf_get(Prefix ++ ".cacertfile", Conf, undefined)}, - {verify, cuttlefish:conf_get(Prefix ++ ".verify", Conf, undefined)}, - {fail_if_no_peer_cert, cuttlefish:conf_get(Prefix ++ ".fail_if_no_peer_cert", Conf, undefined)}, - {secure_renegotiate, cuttlefish:conf_get(Prefix ++ ".secure_renegotiate", Conf, undefined)}, - {reuse_sessions, cuttlefish:conf_get(Prefix ++ ".reuse_sessions", Conf, undefined)}, - {honor_cipher_order, cuttlefish:conf_get(Prefix ++ ".honor_cipher_order", Conf, undefined)}]) - end, - - TcpListeners = fun(Type, Name) -> - Prefix = string:join(["listener", Type, Name], "."), - case cuttlefish:conf_get(Prefix, Conf, undefined) of - undefined -> []; - ListenOn -> - [{Atom(Type), ListenOn, [{deflate_options, DeflateOpts(Prefix)}, - {tcp_options, TcpOpts(Prefix)} | LisOpts(Prefix)]}] - end - end, - - SslListeners = fun(Type, Name) -> - Prefix = string:join(["listener", Type, Name], "."), - case cuttlefish:conf_get(Prefix, Conf, undefined) of - undefined -> - []; - ListenOn -> - [{Atom(Type), ListenOn, [{deflate_options, DeflateOpts(Prefix)}, - {tcp_options, TcpOpts(Prefix)}, - {ssl_options, SslOpts(Prefix)} | LisOpts(Prefix)]}] - end - end, - - lists:flatten([TcpListeners(Type, Name) || {["listener", Type, Name], ListenOn} - <- cuttlefish_variable:filter_by_prefix("listener.tcp", Conf) - ++ cuttlefish_variable:filter_by_prefix("listener.ws", Conf)] - ++ - [SslListeners(Type, Name) || {["listener", Type, Name], ListenOn} - <- cuttlefish_variable:filter_by_prefix("listener.ssl", Conf) - ++ cuttlefish_variable:filter_by_prefix("listener.wss", Conf)]) -end}. - -%%-------------------------------------------------------------------- -%% Modules -%%-------------------------------------------------------------------- - -{mapping, "modules.loaded_file", "emqx.modules_loaded_file", [ - {datatype, string} -]}. - -{mapping, "module.presence.qos", "emqx.modules", [ - {default, 1}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -{mapping, "module.subscription.$id.topic", "emqx.modules", [ - {datatype, string} -]}. - -{mapping, "module.subscription.$id.qos", "emqx.modules", [ - {default, 1}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -{mapping, "module.subscription.$id.nl", "emqx.modules", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:0-1"]} -]}. - -{mapping, "module.subscription.$id.rap", "emqx.modules", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:0-1"]} -]}. - -{mapping, "module.subscription.$id.rh", "emqx.modules", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -{mapping, "module.rewrite.rule.$id", "emqx.modules", [ - {datatype, string} -]}. - -{translation, "emqx.modules", fun(Conf) -> - Subscriptions = fun() -> - List = cuttlefish_variable:filter_by_prefix("module.subscription", Conf), - TopicList = [{N, Topic}|| {[_,"subscription",N,"topic"], Topic} <- List], - [{iolist_to_binary(T), #{ qos => cuttlefish:conf_get("module.subscription." ++ N ++ ".qos", Conf, 0), - nl => cuttlefish:conf_get("module.subscription." ++ N ++ ".nl", Conf, 0), - rap => cuttlefish:conf_get("module.subscription." ++ N ++ ".rap", Conf, 0), - rh => cuttlefish:conf_get("module.subscription." ++ N ++ ".rh", Conf, 0) - }} || {N, T} <- TopicList] - end, - Rewrites = fun() -> - Rules = cuttlefish_variable:filter_by_prefix("module.rewrite.rule", Conf), - lists:map(fun({[_, "rewrite", "rule", I], Rule}) -> - [Topic, Re, Dest] = string:tokens(Rule, " "), - {rewrite, list_to_binary(Topic), list_to_binary(Re), list_to_binary(Dest)} - end, Rules) - end, - lists:append([ - [{emqx_mod_presence, [{qos, cuttlefish:conf_get("module.presence.qos", Conf, 1)}]}], - [{emqx_mod_subscription, Subscriptions()}], - [{emqx_mod_rewrite, Rewrites()}], - [{emqx_mod_topic_metrics, []}], - [{emqx_mod_delayed, []}], - [{emqx_mod_acl_internal, []}] - ]) -end}. - -%%------------------------------------------------------------------- -%% Plugins -%%------------------------------------------------------------------- - -{mapping, "plugins.etc_dir", "emqx.plugins_etc_dir", [ - {datatype, string} -]}. - -{mapping, "plugins.loaded_file", "emqx.plugins_loaded_file", [ - {datatype, string} -]}. - -{mapping, "plugins.expand_plugins_dir", "emqx.expand_plugins_dir", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Broker -%%-------------------------------------------------------------------- - -{mapping, "broker.sys_interval", "emqx.broker_sys_interval", [ - {datatype, {duration, ms}}, - {default, "1m"} -]}. - -{mapping, "broker.sys_heartbeat", "emqx.broker_sys_heartbeat", [ - {datatype, {duration, ms}}, - {default, "30s"} -]}. - -{mapping, "broker.enable_session_registry", "emqx.enable_session_registry", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "broker.session_locking_strategy", "emqx.session_locking_strategy", [ - {default, quorum}, - {datatype, {enum, [local,one,quorum,all]}} -]}. - -%% @doc Shared Subscription Dispatch Strategy. -{mapping, "broker.shared_subscription_strategy", "emqx.shared_subscription_strategy", [ - {default, round_robin}, - {datatype, - {enum, - [random, %% randomly pick a subscriber - round_robin, %% round robin alive subscribers one message after another - sticky, %% pick a random subscriber and stick to it - hash %% hash client ID to a group member - ]}} -]}. - -%% @doc Enable or disable shared dispatch acknowledgement for QoS1 and QoS2 messages -{mapping, "broker.shared_dispatch_ack_enabled", "emqx.shared_dispatch_ack_enabled", - [ {default, false}, - {datatype, {enum, [true, false]}} - ]}. - -{mapping, "broker.route_batch_clean", "emqx.route_batch_clean", [ - {default, on}, - {datatype, flag} -]}. - -%%-------------------------------------------------------------------- -%% System Monitor -%%-------------------------------------------------------------------- - -%% @doc Long GC, don't monitor in production mode for: -%% https://hub.fastgit.org/erlang/otp/blob/feb45017da36be78d4c5784d758ede619fa7bfd3/erts/emulator/beam/erl_gc.c#L421 -{mapping, "sysmon.long_gc", "emqx.sysmon", [ - {default, 0}, - {datatype, [integer, {duration, ms}]} -]}. - -%% @doc Long Schedule(ms) -{mapping, "sysmon.long_schedule", "emqx.sysmon", [ - {default, 240}, - {datatype, [integer, {duration, ms}]} -]}. - -%% @doc Large Heap -{mapping, "sysmon.large_heap", "emqx.sysmon", [ - {default, "8MB"}, - {datatype, bytesize} -]}. - -%% @doc Monitor Busy Port -{mapping, "sysmon.busy_port", "emqx.sysmon", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Monitor Busy Dist Port -{mapping, "sysmon.busy_dist_port", "emqx.sysmon", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{translation, "emqx.sysmon", fun(Conf) -> - Configs = cuttlefish_variable:filter_by_prefix("sysmon", Conf), - [{list_to_atom(Name), Value} || {[_, Name], Value} <- Configs] -end}. - -%%-------------------------------------------------------------------- -%% Operating System Monitor -%%-------------------------------------------------------------------- - -{mapping, "os_mon.cpu_check_interval", "emqx.os_mon", [ - {default, 60}, - {datatype, {duration, s}} -]}. - -{mapping, "os_mon.cpu_high_watermark", "emqx.os_mon", [ - {default, "80%"}, - {datatype, {percent, float}} -]}. - -{mapping, "os_mon.cpu_low_watermark", "emqx.os_mon", [ - {default, "60%"}, - {datatype, {percent, float}} -]}. - -{mapping, "os_mon.mem_check_interval", "emqx.os_mon", [ - {default, 60}, - {datatype, {duration, s}} -]}. - -{mapping, "os_mon.sysmem_high_watermark", "emqx.os_mon", [ - {default, "70%"}, - {datatype, {percent, float}} -]}. - -{mapping, "os_mon.procmem_high_watermark", "emqx.os_mon", [ - {default, "5%"}, - {datatype, {percent, float}} -]}. - -{translation, "emqx.os_mon", fun(Conf) -> - Configs = cuttlefish_variable:filter_by_prefix("os_mon", Conf), - [{list_to_atom(Name), Value} || {[_, Name], Value} <- Configs] -end}. - -%%-------------------------------------------------------------------- -%% VM Monitor -%%-------------------------------------------------------------------- -{mapping, "vm_mon.check_interval", "emqx.vm_mon", [ - {default, 30}, - {datatype, {duration, s}} -]}. - -{mapping, "vm_mon.process_high_watermark", "emqx.vm_mon", [ - {default, "80%"}, - {datatype, {percent, float}} -]}. - -{mapping, "vm_mon.process_low_watermark", "emqx.vm_mon", [ - {default, "60%"}, - {datatype, {percent, float}} -]}. - -{translation, "emqx.vm_mon", fun(Conf) -> - Configs = cuttlefish_variable:filter_by_prefix("vm_mon", Conf), - [{list_to_atom(Name), Value} || {[_, Name], Value} <- Configs] -end}. diff --git a/_build/emqx/conf/ssl_dist.conf b/_build/emqx/conf/ssl_dist.conf deleted file mode 100644 index 50b0e32796..0000000000 --- a/_build/emqx/conf/ssl_dist.conf +++ /dev/null @@ -1,11 +0,0 @@ -%% The options in the {server, Opts} tuple are used when calling ssl:ssl_accept/3, -%% and the options in the {client, Opts} tuple are used when calling ssl:connect/4. -%% -%% More information at: http://erlang.org/doc/apps/ssl/ssl_distribution.html -[{server, - [{certfile, "{{ platform_etc_dir }}/certs/cert.pem"}, - {keyfile, "{{ platform_etc_dir }}/certs/key.pem"}, - {secure_renegotiate, true}, - {depth, 0}]}, - {client, - [{secure_renegotiate, true}]}]. diff --git a/_build/emqx/lib/cowboy/.gitattributes b/_build/emqx/lib/cowboy/.gitattributes deleted file mode 100644 index 9ad9fa04d1..0000000000 --- a/_build/emqx/lib/cowboy/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -erlang.mk -diff diff --git a/_build/emqx/lib/cowboy/.gitignore b/_build/emqx/lib/cowboy/.gitignore deleted file mode 100644 index 4e65a958d7..0000000000 --- a/_build/emqx/lib/cowboy/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -.cowboy.plt -.erlang.mk -_rel -cowboy.d -deps -doc/guide.pdf -doc/html -doc/man3 -doc/man7 -ebin/*.beam -ebin/test -examples/*/ebin -examples/*/*.d -logs -relx -test/*.beam -_build/ -rebar.lock diff --git a/_build/emqx/lib/cowboy/.rebar3/rebar_compiler_erl/source.dag b/_build/emqx/lib/cowboy/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index a4a192a901..0000000000 Binary files a/_build/emqx/lib/cowboy/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/emqx/lib/cowboy/CONTRIBUTING.asciidoc b/_build/emqx/lib/cowboy/CONTRIBUTING.asciidoc deleted file mode 100644 index 7a3bc848ef..0000000000 --- a/_build/emqx/lib/cowboy/CONTRIBUTING.asciidoc +++ /dev/null @@ -1,334 +0,0 @@ -= Contributing - -This document is a guide on how to best contribute to this project. - -== Definitions - -*SHOULD* describes optional steps. *MUST* describes mandatory steps. - -*SHOULD NOT* and *MUST NOT* describes pitfalls to avoid. - -_Your local copy_ refers to the copy of the repository that you have -on your computer. _origin_ refers to your fork of the project. _upstream_ -refers to the official repository for this project. - -== Discussions - -For general discussion about this project, please open a ticket. -Feedback is always welcome and may transform in tasks to improve -the project, so having the discussion start there is a plus. - -Alternatively you may try the #ninenines IRC channel on Freenode, -or, if you need the discussion to stay private, you can send an -email at contact@ninenines.eu. - -== Support - -Free support is generally not available. The rule is that free -support is only given if doing so benefits most users. In practice -this means that free support will only be given if the issues are -due to a fault in the project itself or its documentation. - -Paid support is available for all price ranges. Please send an -email to contact@ninenines.eu for more information. - -== Bug reports - -You *SHOULD* open a ticket for every bug you encounter, regardless -of the version you use. A ticket not only helps the project ensure -that bugs are squashed, it also helps other users who later run -into this issue. You *SHOULD* give as much information as possible -including what commit/branch, what OS/version and so on. - -You *SHOULD NOT* open a ticket if another already exists for the -same issue. You *SHOULD* instead either add more information by -commenting on it, or simply comment to inform the maintainer that -you are also affected. The maintainer *SHOULD* reply to every -new ticket when they are opened. If the maintainer didn't say -anything after a few days, you *SHOULD* write a new comment asking -for more information. - -You *SHOULD* provide a reproducible test case, either in the -ticket or by sending a pull request and updating the test suite. - -When you have a fix ready, you *SHOULD* open a pull request, -even if the code does not fit the requirements discussed below. -Providing a fix, even a dirty one, can help other users and/or -at least get the maintainer on the right tracks. - -You *SHOULD* try to relax and be patient. Some tickets are merged -or fixed quickly, others aren't. There's no real rules around that. -You can become a paying customer if you need something fast. - -== Security reports - -You *SHOULD* open a ticket when you identify a DoS vulnerability -in this project. You *SHOULD* include the resources needed to -DoS the project; every project can be brought down if you have -the necessary resources. - -You *SHOULD* send an email to contact@ninenines.eu when you -identify a security vulnerability. If the vulnerability originates -from code inside Erlang/OTP itself, you *SHOULD* also consult -with OTP Team directly to get the problem fixed upstream. - -== Feature requests - -Feature requests are always welcome. To be accepted, however, they -must be well defined, make sense in the context of the project and -benefit most users. - -Feature requests not benefiting most users may only be accepted -when accompanied with a proper pull request. - -You *MUST* open a ticket to explain what the new feature is, even -if you are going to submit a pull request for it. - -All these conditions are meant to ensure that the project stays -lightweight and maintainable. - -== Documentation submissions - -You *SHOULD* follow the code submission guidelines to submit -documentation. - -The documentation is available in the 'doc/src/' directory. There -are three kinds of documentation: manual, guide and tutorials. The -format for the documentation is Asciidoc. - -You *SHOULD* follow the same style as the surrounding documentation -when editing existing files. - -You *MUST* include the source when providing media. - -== Examples submissions - -You *SHOULD* follow the code submission guidelines to submit examples. - -The examples are available in the 'examples/' directory. - -You *SHOULD* focus on exactly one thing per example. - -== Code submissions - -You *SHOULD* open a pull request to submit code. - -You *SHOULD* open a ticket to discuss backward incompatible changes -before you submit code. This step ensures that you do not work on -a large change that will then be rejected. - -You *SHOULD* send your code submission using a pull request on GitHub. -If you can't, please send an email to contact@ninenines.eu with your -patch. - -The following sections explain the normal GitHub workflow. - -=== Cloning - -You *MUST* fork the project's repository on GitHub by clicking on the -_Fork_ button. - -On the right page of your fork's page is a field named _SSH clone URL_. -Its contents will be identified as `$ORIGIN_URL` in the following snippet. - -On the right side of the project's repository page is a similar field. -Its contents will be identified as `$UPSTREAM_URL`. - -Finally, `$PROJECT` is the name of this project. - -To setup your clone and be able to rebase when requested, run the -following commands: - -[source,bash] -$ git clone $ORIGIN_URL -$ cd $PROJECT -$ git remote add upstream $UPSTREAM_URL - -=== Branching - -You *SHOULD* base your branch on _master_, unless your patch applies -to a stable release, in which case you need to base your branch on -the stable branch, for example _1.0.x_. - -The first step is therefore to checkout the branch in question: - -[source,bash] -$ git checkout 1.0.x - -The next step is to update the branch to the current version from -_upstream_. In the following snippet, replace _1.0.x_ by _master_ -if you are patching _master_. - -[source,bash] -$ git fetch upstream -$ git rebase upstream/1.0.x - -This last command may fail and ask you to stash your changes. When -that happens, run the following sequence of commands: - -[source,bash] -$ git stash -$ git rebase upstream/1.0.x -$ git stash pop - -The final step is to create a new branch you can work in. The name -of the new branch is up to you, there is no particular requirement. -Replace `$BRANCH` with the branch name you came up with: - -[source,bash] -$ git checkout -b $BRANCH - -_Your local copy_ is now ready. - -=== Source editing - -There are very few rules with regard to source code editing. - -You *MUST* use horizontal tabs for indentation. Use one tab -per indentation level. - -You *MUST NOT* align code. You can only add or remove one -indentation level compared to the previous line. - -You *SHOULD NOT* write lines more than about a hundred -characters. There is no hard limit, just try to keep it -as readable as possible. - -You *SHOULD* write small functions when possible. - -You *SHOULD* avoid a too big hierarchy of case clauses inside -a single function. - -You *SHOULD* add tests to make sure your code works. - -=== Committing - -You *SHOULD* run Dialyzer and the test suite while working on -your patch, and you *SHOULD* ensure that no additional tests -fail when you finish. - -You can use the following command to run Dialyzer: - -[source,bash] -$ make dialyze - -You have two options to run tests. You can either run tests -across all supported Erlang versions, or just on the version -you are currently using. - -To test across all supported Erlang versions: - -[source,bash] -$ make -k ci - -To test using the current version: - -[source,bash] -$ make tests - -You can then open Common Test logs in 'logs/all_runs.html'. - -By default Cowboy excludes a few test suites that take too -long to complete. For example all the examples are built and -tested, and one Websocket test suite is very extensive. In -order to run everything, do: - -[source,bash] -$ make tests FULL=1 - -Once all tests pass (or at least, no new tests are failing), -you can commit your changes. - -First you need to add your changes: - -[source,bash] -$ git add src/file_you_edited.erl - -If you want an interactive session, allowing you to filter -out changes that have nothing to do with this commit: - -[source,bash] -$ git add -p - -You *MUST* put all related changes inside a single commit. The -general rule is that all commits must pass tests. Fix one bug -per commit. Add one feature per commit. Separate features in -multiple commits only if smaller parts of the feature make -sense on their own. - -Finally once all changes are added you can commit. This -command will open the editor of your choice where you can -put a proper commit title and message. - -[source,bash] -$ git commit - -Do not use the `-m` option as it makes it easy to break the -following rules: - -You *MUST* write a proper commit title and message. The commit -title is the first line and *MUST* be at most 72 characters. -The second line *MUST* be left blank. Everything after that is -the commit message. You *SHOULD* write a detailed commit -message. The lines of the message *MUST* be at most 80 characters. -You *SHOULD* explain what the commit does, what references you -used and any other information that helps understanding why -this commit exists. You *MUST NOT* include commands to close -GitHub tickets automatically. - -=== Cleaning the commit history - -If you create a new commit every time you make a change, however -insignificant, you *MUST* consolidate those commits before -sending the pull request. - -This is done through _rebasing_. The easiest way to do so is -to use interactive rebasing, which allows you to choose which -commits to keep, squash, edit and so on. To rebase, you need -to give the original commit before you made your changes. If -you only did two changes, you can use the shortcut form `HEAD^^`: - -[source,bash] -$ git rebase -i HEAD^^ - -=== Submitting the pull request - -You *MUST* push your branch to your fork on GitHub. Replace -`$BRANCH` with your branch name: - -[source,bash] -$ git push origin $BRANCH - -You can then submit the pull request using the GitHub interface. -You *SHOULD* provide an explanatory message and refer to any -previous ticket related to this patch. You *MUST NOT* include -commands to close other tickets automatically. - -=== Updating the pull request - -Sometimes the maintainer will ask you to change a few things. -Other times you will notice problems with your submission and -want to fix them on your own. - -In either case you do not need to close the pull request. You -can just push your changes again and, if needed, force them. -This will update the pull request automatically. - -[source,bash] -$ git push -f origin $BRANCH - -=== Merging - -This is an open source project maintained by independent developers. -Please be patient when your changes aren't merged immediately. - -All pull requests run through a Continuous Integration service -to ensure nothing gets broken by the changes submitted. - -Bug fixes will be merged immediately when all tests pass. -The maintainer may do style changes in the merge commit if -the submitter is not available. The maintainer *MUST* open -a new ticket if the solution could still be improved. - -New features and backward incompatible changes will be merged -when all tests pass and all other requirements are fulfilled. diff --git a/_build/emqx/lib/cowboy/LICENSE b/_build/emqx/lib/cowboy/LICENSE deleted file mode 100644 index 9d28158fb7..0000000000 --- a/_build/emqx/lib/cowboy/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2011-2017, Loïc Hoguin - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/_build/emqx/lib/cowboy/Makefile b/_build/emqx/lib/cowboy/Makefile deleted file mode 100644 index 75165ecd6a..0000000000 --- a/_build/emqx/lib/cowboy/Makefile +++ /dev/null @@ -1,34 +0,0 @@ -REBAR := rebar3 - -.PHONY: all -all: compile - -compile: - $(REBAR) compile - -.PHONY: clean -clean: distclean - -.PHONY: distclean -distclean: - @rm -rf _build erl_crash.dump rebar3.crashdump rebar.lock - -.PHONY: xref -xref: - $(REBAR) xref - -.PHONY: eunit -eunit: compile - $(REBAR) eunit verbose=truen - -.PHONY: ct -ct: compile - $(REBAR) as test ct -v - -cover: - $(REBAR) cover - -.PHONY: dialyzer -dialyzer: - $(REBAR) dialyzer - diff --git a/_build/emqx/lib/cowboy/README.asciidoc b/_build/emqx/lib/cowboy/README.asciidoc deleted file mode 100644 index ae9c7b5300..0000000000 --- a/_build/emqx/lib/cowboy/README.asciidoc +++ /dev/null @@ -1,37 +0,0 @@ -= Cowboy - -Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - -== Goals - -Cowboy aims to provide a *complete* HTTP stack in a *small* code base. -It is optimized for *low latency* and *low memory usage*, in part -because it uses *binary strings*. - -Cowboy provides *routing* capabilities, selectively dispatching requests -to handlers written in Erlang. - -Because it uses Ranch for managing connections, Cowboy can easily be -*embedded* in any other application. - -Cowboy is *clean* and *well tested* Erlang code. - -== Online documentation - -* https://ninenines.eu/docs/en/cowboy/2.6/guide[User guide] -* https://ninenines.eu/docs/en/cowboy/2.6/manual[Function reference] - -== Offline documentation - -* While still online, run `make docs` -* User guide available in `doc/` in PDF and HTML formats -* Function reference man pages available in `doc/man3/` and `doc/man7/` -* Run `make install-docs` to install man pages on your system -* Full documentation in Asciidoc available in `doc/src/` -* Examples available in `examples/` - -== Getting help - -* Official IRC Channel: #ninenines on irc.freenode.net -* https://hub.fastgit.org/ninenines/cowboy/issues[Issues tracker] -* https://ninenines.eu/services[Commercial Support] diff --git a/_build/emqx/lib/cowboy/doc/src/guide/book.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/book.asciidoc deleted file mode 100644 index f5989eb921..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/book.asciidoc +++ /dev/null @@ -1,92 +0,0 @@ -// a2x: --dblatex-opts "-P latex.output.revhistory=0 -P doc.publisher.show=0 -P index.numbered=0" -// a2x: --dblatex-opts "-s cowboy" -// a2x: -d book --attribute tabsize=4 - -= Cowboy User Guide - -// REST: where should i handle bindings? init, probably. qs? in media type functions -// REST: explain how a module per media type is good; module may be shared between client/server - -= Rationale - -include::modern_web.asciidoc[The modern Web] - -include::erlang_web.asciidoc[Erlang and the Web] - -= Introduction - -include::introduction.asciidoc[Introduction] - -include::getting_started.asciidoc[Getting started] - -include::flow_diagram.asciidoc[Flow diagram] - -= Configuration - -include::listeners.asciidoc[Listeners] - -include::routing.asciidoc[Routing] - -include::constraints.asciidoc[Constraints] - -= Handlers - -include::handlers.asciidoc[Handlers] - -include::loop_handlers.asciidoc[Loop handlers] - -include::static_files.asciidoc[Static files] - -= Request and response - -include::req.asciidoc[Request details] - -include::req_body.asciidoc[Reading the request body] - -include::resp.asciidoc[Sending a response] - -include::cookies.asciidoc[Using cookies] - -include::multipart.asciidoc[Multipart] - -= REST - -include::rest_principles.asciidoc[REST principles] - -include::rest_handlers.asciidoc[Handling REST requests] - -include::rest_flowcharts.asciidoc[REST flowcharts] - -include::resource_design.asciidoc[Designing a resource handler] - -= Websocket - -include::ws_protocol.asciidoc[The Websocket protocol] - -include::ws_handlers.asciidoc[Websocket handlers] - -= Advanced - -include::streams.asciidoc[Streams] - -include::middlewares.asciidoc[Middlewares] - -= Additional information - -include::migrating_from_2.6.asciidoc[Migrating from Cowboy 2.6 to 2.7] - -include::migrating_from_2.5.asciidoc[Migrating from Cowboy 2.5 to 2.6] - -include::migrating_from_2.4.asciidoc[Migrating from Cowboy 2.4 to 2.5] - -include::migrating_from_2.3.asciidoc[Migrating from Cowboy 2.3 to 2.4] - -include::migrating_from_2.2.asciidoc[Migrating from Cowboy 2.2 to 2.3] - -include::migrating_from_2.1.asciidoc[Migrating from Cowboy 2.1 to 2.2] - -include::migrating_from_2.0.asciidoc[Migrating from Cowboy 2.0 to 2.1] - -include::migrating_from_1.0.asciidoc[Migrating from Cowboy 1.0 to 2.0] - -include::specs.asciidoc[HTTP and other specifications] diff --git a/_build/emqx/lib/cowboy/doc/src/guide/constraints.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/constraints.asciidoc deleted file mode 100644 index 6cc10752e6..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/constraints.asciidoc +++ /dev/null @@ -1,123 +0,0 @@ -[[constraints]] -== Constraints - -Constraints are validation and conversion functions applied -to user input. - -They are used in various places in Cowboy, including the -router and the `cowboy_req` match functions. - -=== Syntax - -Constraints are provided as a list of fields. For each field -in the list, specific constraints can be applied, as well as -a default value if the field is missing. - -A field can take the form of an atom `field`, a tuple with -constraints `{field, Constraints}` or a tuple with constraints -and a default value `{field, Constraints, Default}`. -The `field` form indicates the field is mandatory. - -Note that when used with the router, only the second form -makes sense, as it does not use the default and the field -is always defined. - -Constraints for each field are provided as an ordered list -of atoms or funs to apply. Built-in constraints are provided -as atoms, while custom constraints are provided as funs. - -When multiple constraints are provided, they are applied in -the order given. If the value has been modified by a constraint -then the next one receives the new value. - -For example, the following constraints will first validate -and convert the field `my_value` to an integer, and then -check that the integer is positive: - -[source,erlang] ----- -PositiveFun = fun - (_, V) when V > 0 -> - {ok, V}; - (_, _) -> - {error, not_positive} -end, -{my_value, [int, PositiveFun]}. ----- - -We ignore the first fun argument in this snippet. We shouldn't. -We will simply learn what it is later in this chapter. - -When there's only one constraint, it can be provided directly -without wrapping it into a list: - -[source,erlang] ----- -{my_value, int} ----- - -=== Built-in constraints - -Built-in constraints are specified as an atom: - -[cols="<,<",options="header"] -|=== -| Constraint | Description -| int | Converts binary value to integer. -| nonempty | Ensures the binary value is non-empty. -|=== - -=== Custom constraints - -Custom constraints are specified as a fun. This fun takes -two arguments. The first argument indicates the operation -to be performed, and the second is the value. What the -value is and what must be returned depends on the operation. - -Cowboy currently defines three operations. The operation -used for validating and converting user input is the `forward` -operation. - -[source,erlang] ----- -int(forward, Value) -> - try - {ok, binary_to_integer(Value)} - catch _:_ -> - {error, not_an_integer} - end; ----- - -The value must be returned even if it is not converted -by the constraint. - -The `reverse` operation does the opposite: it -takes a converted value and changes it back to what the -user input would have been. - -[source,erlang] ----- -int(reverse, Value) -> - try - {ok, integer_to_binary(Value)} - catch _:_ -> - {error, not_an_integer} - end; ----- - -Finally, the `format_error` operation takes an error -returned by any other operation and returns a formatted -human-readable error message. - -[source,erlang] ----- -int(format_error, {not_an_integer, Value}) -> - io_lib:format("The value ~p is not an integer.", [Value]). ----- - -Notice that for this case you get both the error and -the value that was given to the constraint that produced -this error. - -Cowboy will not catch exceptions coming from constraint -functions. They should be written to not emit any exceptions. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/cookies.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/cookies.asciidoc deleted file mode 100644 index 4825031bf5..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/cookies.asciidoc +++ /dev/null @@ -1,139 +0,0 @@ -[[cookies]] -== Using cookies - -Cookies are a mechanism allowing applications to maintain -state on top of the stateless HTTP protocol. - -Cookies are a name/value store where the names and values are -stored in plain text. They expire either after a delay -or when the browser closes. They can be configured on a -specific domain name or path, and restricted to secure -resources (sent or downloaded over HTTPS), or restricted -to the server (disallowing access from client-side scripts). - -Cookie names are de facto case sensitive. - -Cookies are stored client-side and sent with every subsequent -request that matches the domain and path for which they were -stored, until they expire. This can create a non-negligible -cost. - -Cookies should not be considered secure. They are stored on -the user's computer in plain text, and can be read by any -program. They can also be read by proxies when using clear -connections. Always validate the value before using it, -and never store any sensitive information inside it. - -Cookies set by the server are only available in requests -following the client reception of the response containing -them. - -Cookies may be sent repeatedly. This is often useful to -update the expiration time and avoid losing a cookie. - -=== Setting cookies - -By default cookies are defined for the duration of the session: - -[source,erlang] ----- -SessionID = generate_session_id(), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0). ----- - -They can also be set for a duration in seconds: - -[source,erlang] ----- -SessionID = generate_session_id(), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0, - #{max_age => 3600}). ----- - -To delete cookies, set `max_age` to 0: - -[source,erlang] ----- -SessionID = generate_session_id(), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0, - #{max_age => 0}). ----- - -To restrict cookies to a specific domain and path, the options -of the same name can be used: - -[source,erlang] ----- -Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, Req0, - #{domain => "my.example.org", path => "/account"}). ----- - -Cookies will be sent with requests to this domain and all -its subdomains, and to resources on this path or deeper -in the path hierarchy. - -To restrict cookies to secure channels (typically resources -available over HTTPS): - -[source,erlang] ----- -SessionID = generate_session_id(), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0, - #{secure => true}). ----- - -To prevent client-side scripts from accessing a cookie: - -[source,erlang] ----- -SessionID = generate_session_id(), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0, - #{http_only => true}). ----- - -Cookies may also be set client-side, for example using -Javascript. - -=== Reading cookies - -The client only ever sends back the cookie name and value. -All other options that can be set are never sent back. - -Cowboy provides two functions for reading cookies. Both -involve parsing the cookie header(s) and so should not -be called repeatedly. - -You can get all cookies as a key/value list: - -[source,erlang] -Cookies = cowboy_req:parse_cookies(Req), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Cookies). - -Or you can perform a match against cookies and retrieve -only the ones you need, while at the same time doing -any required post processing using xref:constraints[constraints]. -This function returns a map: - -[source,erlang] -#{id := ID, lang := Lang} = cowboy_req:match_cookies([id, lang], Req). - -You can use constraints to validate the values while matching -them. The following snippet will crash if the `id` cookie is -not an integer number or if the `lang` cookie is empty. Additionally -the `id` cookie value will be converted to an integer term: - -[source,erlang] -CookiesMap = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req). - -Note that if two cookies share the same name, then the map value -will be a list of the two cookie values. - -A default value can be provided. The default will be used -if the `lang` cookie is not found. It will not be used if -the cookie is found but has an empty value: - -[source,erlang] -#{lang := Lang} = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req). - -If no default is provided and the value is missing, an -exception is thrown. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/cowboy.sty b/_build/emqx/lib/cowboy/doc/src/guide/cowboy.sty deleted file mode 100644 index d5e0d3be0c..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/cowboy.sty +++ /dev/null @@ -1,8 +0,0 @@ -\NeedsTeXFormat{LaTeX2e} -\ProvidesPackage{asciidoc-dblatex}[2012/10/24 AsciiDoc DocBook Style] - -%% Just use the original package and pass the options. -\RequirePackageWithOptions{docbook} - -%% Define an alias for make snippets to be compatible with source-highlighter. -\lstalias{makefile}{make} diff --git a/_build/emqx/lib/cowboy/doc/src/guide/erlang_web.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/erlang_web.asciidoc deleted file mode 100644 index f528adc3f5..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/erlang_web.asciidoc +++ /dev/null @@ -1,209 +0,0 @@ -[[erlang_web]] -== Erlang and the Web - -Erlang is the ideal platform for writing Web applications. -Its features are a perfect match for the requirements of -modern Web applications. - -=== The Web is concurrent - -When you access a website there is little concurrency -involved. A few connections are opened and requests -are sent through these connections. Then the web page -is displayed on your screen. Your browser will only -open up to 4 or 8 connections to the server, depending -on your settings. This isn't much. - -But think about it. You are not the only one accessing -the server at the same time. There can be hundreds, if -not thousands, if not millions of connections to the -same server at the same time. - -Even today a lot of systems used in production haven't -solved the C10K problem (ten thousand concurrent connections). -And the ones who did are trying hard to get to the next -step, C100K, and are pretty far from it. - -Erlang meanwhile has no problem handling millions of -connections. At the time of writing there are application -servers written in Erlang that can handle more than two -million connections on a single server in a real production -application, with spare memory and CPU! - -The Web is concurrent, and Erlang is a language designed -for concurrency, so it is a perfect match. - -Of course, various platforms need to scale beyond a few -million connections. This is where Erlang's built-in -distribution mechanisms come in. If one server isn't -enough, add more! Erlang allows you to use the same code -for talking to local processes or to processes in other -parts of your cluster, which means you can scale very -quickly if the need arises. - -The Web has large userbases, and the Erlang platform was -designed to work in a distributed setting, so it is a -perfect match. - -Or is it? Surely you can find solutions to handle that many -concurrent connections with your favorite language... But all -these solutions will break down in the next few years. Why? -Firstly because servers don't get any more powerful, they -instead get a lot more cores and memory. This is only useful -if your application can use them properly, and Erlang is -light-years away from anything else in that area. Secondly, -today your computer and your phone are online, tomorrow your -watch, goggles, bike, car, fridge and tons of other devices -will also connect to various applications on the Internet. - -Only Erlang is prepared to deal with what's coming. - -=== The Web is soft real time - -What does soft real time mean, you ask? It means we want the -operations done as quickly as possible, and in the case of -web applications, it means we want the data propagated fast. - -In comparison, hard real time has a similar meaning, but also -has a hard time constraint, for example an operation needs to -be done in under N milliseconds otherwise the system fails -entirely. - -Users aren't that needy yet, they just want to get access -to their content in a reasonable delay, and they want the -actions they make to register at most a few seconds after -they submitted them, otherwise they'll start worrying about -whether it successfully went through. - -The Web is soft real time because taking longer to perform an -operation would be seen as bad quality of service. - -Erlang is a soft real time system. It will always run -processes fairly, a little at a time, switching to another -process after a while and preventing a single process to -steal resources from all others. This means that Erlang -can guarantee stable low latency of operations. - -Erlang provides the guarantees that the soft real time Web -requires. - -=== The Web is asynchronous - -Long ago, the Web was synchronous because HTTP was synchronous. -You fired a request, and then waited for a response. Not anymore. -It all began when XmlHttpRequest started being used. It allowed -the client to perform asynchronous calls to the server. - -Then Websocket appeared and allowed both the server and the client -to send data to the other endpoint completely asynchronously. The -data is contained within frames and no response is necessary. - -Erlang processes work the same. They send each other data contained -within messages and then continue running without needing a response. -They tend to spend most of their time inactive, waiting for a new -message, and the Erlang VM happily activate them when one is received. - -It is therefore quite easy to imagine Erlang being good at receiving -Websocket frames, which may come in at unpredictable times, pass the -data to the responsible processes which are always ready waiting for -new messages, and perform the operations required by only activating -the required parts of the system. - -The more recent Web technologies, like Websocket of course, but also -HTTP/2.0, are all fully asynchronous protocols. The concept -of requests and responses is retained of course, but anything could -be sent in between, by both the client or the browser, and the -responses could also be received in a completely different order. - -Erlang is by nature asynchronous and really good at it thanks to the -great engineering that has been done in the VM over the years. It's -only natural that it's so good at dealing with the asynchronous Web. - -=== The Web is omnipresent - -The Web has taken a very important part of our lives. We're -connected at all times, when we're on our phone, using our computer, -passing time using a tablet while in the bathroom... And this -isn't going to slow down, every single device at home or on us -will be connected. - -All these devices are always connected. And with the number of -alternatives to give you access to the content you seek, users -tend to not stick around when problems arise. Users today want -their applications to be always available and if it's having -too many issues they just move on. - -Despite this, when developers choose a product to use for building -web applications, their only concern seems to be "Is it fast?", -and they look around for synthetic benchmarks showing which one -is the fastest at sending "Hello world" with only a handful -concurrent connections. Web benchmarks haven't been representative -of reality in a long time, and are drifting further away as -time goes on. - -What developers should really ask themselves is "Can I service -all my users with no interruption?" and they'd find that they have -two choices. They can either hope for the best, or they can use -Erlang. - -Erlang is built for fault tolerance. When writing code in any other -language, you have to check all the return values and act accordingly -to avoid any unforeseen issues. If you're lucky, you won't miss -anything important. When writing Erlang code, you can just check -the success condition and ignore all errors. If an error happens, -the Erlang process crashes and is then restarted by a special -process called a supervisor. - -Erlang developers thus have no need to fear unhandled -errors, and can focus on handling only the errors that should -give some feedback to the user and let the system take care of -the rest. This also has the advantage of allowing them to write -a lot less code, and let them sleep at night. - -Erlang's fault tolerance oriented design is the first piece of -what makes it the best choice for the omnipresent, always available -Web. - -The second piece is Erlang's built-in distribution. Distribution -is a key part of building a fault tolerant system, because it -allows you to handle bigger failures, like a whole server going -down, or even a data center entirely. - -Fault tolerance and distribution are important today, and will be -vital in the future of the Web. Erlang is ready. - -=== Learn Erlang - -If you are new to Erlang, you may want to grab a book or -two to get started. Those are my recommendations as the -author of Cowboy. - -==== The Erlanger Playbook - -The Erlanger Playbook is an ebook I am currently writing, -which covers a number of different topics from code to -documentation to testing Erlang applications. It also has -an Erlang section where it covers directly the building -blocks and patterns, rather than details like the syntax. - -You can most likely read it as a complete beginner, but -you will need a companion book to make the most of it. -Buy it from the https://ninenines.eu[Nine Nines website]. - -==== Programming Erlang - -This book is from one of the creator of Erlang, Joe -Armstrong. It provides a very good explanation of what -Erlang is and why it is so. It serves as a very good -introduction to the language and platform. - -The book is http://pragprog.com/book/jaerlang2/programming-erlang[Programming Erlang], -and it also features a chapter on Cowboy. - -==== Learn You Some Erlang for Great Good! - -http://learnyousomeerlang.com[LYSE] is a much more complete -book covering many aspects of Erlang, while also providing -stories and humor. Be warned: it's pretty verbose. It comes -with a free online version and a more refined paper and -ebook version. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/flow_diagram.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/flow_diagram.asciidoc deleted file mode 100644 index 2d35d4d687..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/flow_diagram.asciidoc +++ /dev/null @@ -1,109 +0,0 @@ -[[flow_diagram]] -== Flow diagram - -Cowboy is a lightweight HTTP server with support for HTTP/1.1, -HTTP/2 and Websocket. - -It is built on top of Ranch. Please see the Ranch guide for more -information about how the network connections are handled. - -=== Overview - -image::http_req_resp.png[HTTP request/response flowchart] - -As you can see on the diagram, the client -begins by connecting to the server. This step is handled -by a Ranch acceptor, which is a process dedicated to -accepting new connections. - -After Ranch accepts a new connection, whether it is an -HTTP/1.1 or HTTP/2 connection, Cowboy starts receiving -requests and handling them. - -In HTTP/1.1 all requests come sequentially. In HTTP/2 -the requests may arrive and be processed concurrently. - -When a request comes in, Cowboy creates a stream, which -is a set of request/response and all the events associated -with them. The protocol code in Cowboy defers the handling -of these streams to stream handler modules. When you -configure Cowboy you may define one or more module that -will receive all events associated with a stream, including -the request, response, bodies, Erlang messages and more. - -By default Cowboy comes configured with a stream handler -called `cowboy_stream_h`. This stream handler will create -a new process for every request coming in, and then -communicate with this process to read the body or send -a response back. The request process executes middlewares -which, by default, including the router and then the -execution of handlers. Like stream handlers, middlewares -may also be customized. - -A response may be sent at almost any point in this -diagram. If the response must be sent before the stream -is initialized (because an error occurred early, for -example) then stream handlers receive a special event -indicating this error. - -=== Protocol-specific headers - -Cowboy takes care of protocol-specific headers and prevents -you from sending them manually. For HTTP/1.1 this includes -the `transfer-encoding` and `connection` headers. For HTTP/2 -this includes the colon headers like `:status`. - -Cowboy will also remove protocol-specific headers from -requests before passing them to stream handlers. Cowboy -tries to hide the implementation details of all protocols -as well as possible. - -=== Number of processes per connection - -By default, Cowboy will use one process per connection, -plus one process per set of request/response (called a -stream, internally). - -The reason it creates a new process for every request is due -to the requirements of HTTP/2 where requests are executed -concurrently and independently from the connection. The -frames from the different requests end up interleaved on -the single TCP connection. - -The request processes are never reused. There is therefore -no need to perform any cleanup after the response has been -sent. The process will terminate and Erlang/OTP will reclaim -all memory at once. - -Cowboy ultimately does not require more than one process -per connection. It is possible to interact with the connection -directly from a stream handler, a low level interface to Cowboy. -They are executed from within the connection process, and can -handle the incoming requests and send responses. This is however -not recommended in normal circumstances, as a stream handler -taking too long to execute could have a negative impact on -concurrent requests or the state of the connection itself. - -=== Date header - -Because querying for the current date and time can be expensive, -Cowboy generates one 'Date' header value every second, shares it -to all other processes, which then simply copy it in the response. -This allows compliance with HTTP/1.1 with no actual performance loss. - -=== Binaries - -Cowboy makes extensive use of binaries. - -Binaries are more efficient than lists for representing -strings because they take less memory space. Processing -performance can vary depending on the operation. Binaries -are known for generally getting a great boost if the code -is compiled natively. Please see the HiPE documentation -for more details. - -Binaries may end up being shared between processes. This -can lead to some large memory usage when one process keeps -the binary data around forever without freeing it. If you -see some weird memory usage in your application, this might -be the cause. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/getting_started.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/getting_started.asciidoc deleted file mode 100644 index 079bea72d3..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/getting_started.asciidoc +++ /dev/null @@ -1,148 +0,0 @@ -[[getting_started]] -== Getting started - -Erlang is more than a language, it is also an operating system -for your applications. Erlang developers rarely write standalone -modules, they write libraries or applications, and then bundle -those into what is called a release. A release contains the -Erlang VM plus all applications required to run the node, so -it can be pushed to production directly. - -This chapter walks you through all the steps of setting up -Cowboy, writing your first application and generating your first -release. At the end of this chapter you should know everything -you need to push your first Cowboy application to production. - -=== Prerequisites - -We are going to use the https://hub.fastgit.org/ninenines/erlang.mk[Erlang.mk] -build system. If you are using Windows, please check the -http://erlang.mk/guide/installation.html[Installation instructions] -to get your environment setup before you continue. - -=== Bootstrap - -First, let's create the directory for our application. - -[source,bash] -$ mkdir hello_erlang -$ cd hello_erlang - -Then we need to download Erlang.mk. Either use the following -command or download it manually. - -[source,bash] -$ wget https://erlang.mk/erlang.mk - -We can now bootstrap our application. Since we are going to generate -a release, we will also bootstrap it at the same time. - -[source,bash] -$ make -f erlang.mk bootstrap bootstrap-rel - -This creates a Makefile, a base application, and the release files -necessary for creating the release. We can already build and start -this release. - -[source,bash] ----- -$ make run -... -(hello_erlang@127.0.0.1)1> ----- - -Entering the command `i().` will show the running processes, including -one called `hello_erlang_sup`. This is the supervisor for our -application. - -The release currently does nothing. In the rest of this chapter we -will add Cowboy as a dependency and write a simple "Hello world!" -handler. - -=== Cowboy setup - -We will modify the 'Makefile' to tell the build system it needs to -fetch and compile Cowboy: - -[source,makefile] ----- -PROJECT = hello_erlang - -DEPS = cowboy -dep_cowboy_commit = 2.7.0 - -DEP_PLUGINS = cowboy - -include erlang.mk ----- - -The `DEP_PLUGINS` line tells the build system to load the plugins -Cowboy provides. These include predefined templates that we will -use soon. - -If you do `make run` now, Cowboy will be included in the release -and started automatically. This is not enough however, as Cowboy -doesn't do anything by default. We still need to tell Cowboy to -listen for connections. - -=== Listening for connections - -First we define the routes that Cowboy will use to map requests -to handler modules, and then we start the listener. This is best -done at application startup. - -Open the 'src/hello_erlang_app.erl' file and add the necessary -code to the `start/2` function to make it look like this: - -[source,erlang] ----- -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [{"/", hello_handler, []}]} - ]), - {ok, _} = cowboy:start_clear(my_http_listener, - [{port, 8080}], - #{env => #{dispatch => Dispatch}} - ), - hello_erlang_sup:start_link(). ----- - -Routes are explained in details in the xref:routing[Routing] -chapter. For this tutorial we map the path `/` to the handler -module `hello_handler`. This module doesn't exist yet. - -Build and start the release, then open http://localhost:8080 -in your browser. You will get a 500 error because the module is missing. -Any other URL, like http://localhost:8080/test, will result in a -404 error. - -=== Handling requests - -Cowboy features different kinds of handlers, including REST -and Websocket handlers. For this tutorial we will use a plain -HTTP handler. - -Generate a handler from a template: - -[source,bash] -$ make new t=cowboy.http n=hello_handler - -Then, open the 'src/hello_handler.erl' file and modify -the `init/2` function like this to send a reply. - -[source,erlang] ----- -init(Req0, State) -> - Req = cowboy_req:reply(200, - #{<<"content-type">> => <<"text/plain">>}, - <<"Hello Erlang!">>, - Req0), - {ok, Req, State}. ----- - -What the above code does is send a 200 OK reply, with the -Content-type header set to `text/plain` and the response -body set to `Hello Erlang!`. - -If you run the release and open http://localhost:8080 -in your browser, you should get a nice `Hello Erlang!` displayed! diff --git a/_build/emqx/lib/cowboy/doc/src/guide/handlers.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/handlers.asciidoc deleted file mode 100644 index fe6f462397..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/handlers.asciidoc +++ /dev/null @@ -1,90 +0,0 @@ -[[handlers]] -== Handlers - -Handlers are Erlang modules that handle HTTP requests. - -=== Plain HTTP handlers - -The most basic handler in Cowboy implements the mandatory -`init/2` callback, manipulates the request, optionally -sends a response and then returns. - -This callback receives the xref:req[Req object] and the initial -state defined in the xref:routing[router configuration]. - -A handler that does nothing would look like this: - -[source,erlang] ----- -init(Req, State) -> - {ok, Req, State}. ----- - -Despite sending no reply, a `204 No Content` response will be -sent to the client, as Cowboy makes sure that a response is -sent for every request. - -We need to use the Req object to reply. - -[source,erlang] ----- -init(Req0, State) -> - Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> - }, <<"Hello World!">>, Req0), - {ok, Req, State}. ----- - -Cowboy will immediately send a response when `cowboy:reply/4` -is called. - -We then return a 3-tuple. `ok` means that the handler ran -successfully. We also give the modified Req back to Cowboy. - -The last value of the tuple is a state that will be used -in every subsequent callbacks to this handler. Plain HTTP -handlers only have one additional callback, the optional -and rarely used `terminate/3`. - -=== Other handlers - -The `init/2` callback can also be used to inform Cowboy -that this is a different kind of handler and that Cowboy -should switch to it. To do this you simply need to return -the module name of the handler type you want to switch to. - -Cowboy comes with three handler types you can switch to: -xref:rest_handlers[cowboy_rest], xref:ws_handlers[cowboy_websocket] -and xref:loop_handlers[cowboy_loop]. In addition to those you -can define your own handler types. - -Switching is simple. Instead of returning `ok`, you simply -return the name of the handler type you want to use. The -following snippet switches to a Websocket handler: - -[source,erlang] ----- -init(Req, State) -> - {cowboy_websocket, Req, State}. ----- - -=== Cleaning up - -All handler types provide the optional `terminate/3` callback. - -[source,erlang] ----- -terminate(_Reason, _Req, _State) -> - ok. ----- - -This callback is strictly reserved for any required cleanup. -You cannot send a response from this function. There is no -other return value. - -This callback is optional because it is rarely necessary. -Cleanup should be done in separate processes directly (by -monitoring the handler process to detect when it exits). - -Cowboy does not reuse processes for different requests. The -process will terminate soon after this call returns. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/http_req_resp.png b/_build/emqx/lib/cowboy/doc/src/guide/http_req_resp.png deleted file mode 100644 index 41c17c8a55..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/http_req_resp.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/http_req_resp.svg b/_build/emqx/lib/cowboy/doc/src/guide/http_req_resp.svg deleted file mode 100644 index acedb152b8..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/http_req_resp.svg +++ /dev/null @@ -1,543 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - - - - acceptor - - - - - protocol - - - - router - - some text - - - handler - - middlewares - some text - - - client - - - - stream - - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/introduction.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/introduction.asciidoc deleted file mode 100644 index 18023ae739..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/introduction.asciidoc +++ /dev/null @@ -1,75 +0,0 @@ -[[introduction]] -== Introduction - -Cowboy is a small, fast and modern HTTP server for Erlang/OTP. - -Cowboy aims to provide a complete xref:modern_web[modern Web stack]. -This includes HTTP/1.1, HTTP/2, Websocket, Server-Sent Events and -Webmachine-based REST. - -Cowboy comes with functions for introspection and tracing, enabling -developers to know precisely what is happening at any time. Its modular -design also easily enable developers to add instrumentation. - -Cowboy is a high quality project. It has a small code base, is very -efficient (both in latency and memory use) and can easily be embedded -in another application. - -Cowboy is clean Erlang code. It includes hundreds of tests and its code -is fully compliant with the Dialyzer. It is also well documented and -features a Function Reference, a User Guide and numerous Tutorials. - -=== Prerequisites - -Beginner Erlang knowledge is recommended for reading this guide. - -Knowledge of the HTTP protocol is recommended but not required, as it -will be detailed throughout the guide. - -=== Supported platforms - -Cowboy is tested and supported on Linux, FreeBSD, Windows and OSX. - -Cowboy has been reported to work on other platforms, but we make no -guarantee that the experience will be safe and smooth. You are advised -to perform the necessary testing and security audits prior to deploying -on other platforms. - -Cowboy is developed for Erlang/OTP 20.0 and newer. - -=== License - -Cowboy uses the ISC License. - ----- -Copyright (c) 2011-2019, Loïc Hoguin - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ----- - -=== Versioning - -Cowboy uses http://semver.org/[Semantic Versioning 2.0.0]. - -=== Conventions - -In the HTTP protocol, the method name is case sensitive. All standard -method names are uppercase. - -Header names are case insensitive. When using HTTP/1.1, Cowboy converts -all the request header names to lowercase. HTTP/2 requires clients to -send them as lowercase. Any other header name is expected to be provided -lowercased, including when querying information about the request or -when sending responses. - -The same applies to any other case insensitive value. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/listeners.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/listeners.asciidoc deleted file mode 100644 index 04169f9a0b..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/listeners.asciidoc +++ /dev/null @@ -1,128 +0,0 @@ -[[listeners]] -== Listeners - -A listener is a set of processes that listens on a port for -new connections. Incoming connections get handled by Cowboy. -Depending on the connection handshake, one or another protocol -may be used. - -This chapter is specific to Cowboy. Please refer to the -https://ninenines.eu/docs/en/ranch/1.3/guide/listeners/[Ranch User Guide] -for more information about listeners. - -Cowboy provides two types of listeners: one listening for -clear TCP connections, and one listening for secure TLS -connections. Both of them support the HTTP/1.1 and HTTP/2 -protocols. - -=== Clear TCP listener - -The clear TCP listener will accept connections on the -given port. A typical HTTP server would listen on port 80. -Port 80 requires special permissions on most platforms -however so a common alternative is port 8080. - -The following snippet starts listening for connections -on port 8080: - -[source,erlang] ----- -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [{"/", hello_handler, []}]} - ]), - {ok, _} = cowboy:start_clear(my_http_listener, - [{port, 8080}], - #{env => #{dispatch => Dispatch}} - ), - hello_erlang_sup:start_link(). ----- - -The xref:getting_started[Getting Started] chapter uses a -clear TCP listener. - -Clients connecting to Cowboy on the clear listener port are -expected to use either HTTP/1.1 or HTTP/2. - -Cowboy supports both methods of initiating a clear -HTTP/2 connection: through the Upgrade mechanism -(https://tools.ietf.org/html/rfc7540#section-3.2[RFC 7540 3.2]) -or by sending the preface directly -(https://tools.ietf.org/html/rfc7540#section-3.4[RFC 7540 3.4]). - -Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 -implementation. - -=== Secure TLS listener - -The secure TLS listener will accept connections on the -given port. A typical HTTPS server would listen on port 443. -Port 443 requires special permissions on most platforms -however so a common alternative is port 8443. - -// @todo Make a complete list of restrictions. - -The function provided by Cowboy will ensure that the TLS -options given are following the HTTP/2 RFC with regards -to security. For example some TLS extensions or ciphers -may be disabled. This also applies to HTTP/1.1 connections -on this listener. If this is not desirable, Ranch can be -used directly to set up a custom listener. - -[source,erlang] ----- -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [{"/", hello_handler, []}]} - ]), - {ok, _} = cowboy:start_tls(my_https_listener, - [ - {port, 8443}, - {certfile, "/path/to/certfile"}, - {keyfile, "/path/to/keyfile"} - ], - #{env => #{dispatch => Dispatch}} - ), - hello_erlang_sup:start_link(). ----- - -Clients connecting to Cowboy on the secure listener are -expected to use the ALPN TLS extension to indicate what -protocols they understand. Cowboy always prefers HTTP/2 -over HTTP/1.1 when both are supported. When neither are -supported by the client, or when the ALPN extension was -missing, Cowboy expects HTTP/1.1 to be used. - -Cowboy also advertises HTTP/2 support through the older -NPN TLS extension for compatibility. Note however that -this support will likely not be enabled by default when -Cowboy 2.0 gets released. - -Compatibility with HTTP/1.0 is provided by Cowboy's HTTP/1.1 -implementation. - -=== Stopping the listener - -When starting listeners along with the application it is -a good idea to also stop the listener when the application -stops. This can be done by calling `cowboy:stop_listener/1` -in the application's stop function: - -[source,erlang] ----- -stop(_State) -> - ok = cowboy:stop_listener(my_http_listener). ----- - -=== Protocol configuration - -The HTTP/1.1 and HTTP/2 protocols share the same semantics; -only their framing differs. The first is a text protocol and -the second a binary protocol. - -Cowboy doesn't separate the configuration for HTTP/1.1 and -HTTP/2. Everything goes into the same map. Many options are -shared. - -// @todo Describe good to know options for both protocols? -// Maybe do that in separate chapters? diff --git a/_build/emqx/lib/cowboy/doc/src/guide/loop_handlers.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/loop_handlers.asciidoc deleted file mode 100644 index e5748548cf..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/loop_handlers.asciidoc +++ /dev/null @@ -1,125 +0,0 @@ -[[loop_handlers]] -== Loop handlers - -Loop handlers are a special kind of HTTP handlers used when the -response can not be sent right away. The handler enters instead -a receive loop waiting for the right message before it can send -a response. - -Loop handlers are used for requests where a response might not -be immediately available, but where you would like to keep the -connection open for a while in case the response arrives. The -most known example of such practice is known as long polling. - -Loop handlers can also be used for requests where a response is -partially available and you need to stream the response body -while the connection is open. The most known example of such -practice is server-sent events, but it also applies to any -response that takes a long time to send. - -While the same can be accomplished using plain HTTP handlers, -it is recommended to use loop handlers because they are well-tested -and allow using built-in features like hibernation and timeouts. - -Loop handlers essentially wait for one or more Erlang messages -and feed these messages to the `info/3` callback. It also features -the `init/2` and `terminate/3` callbacks which work the same as -for plain HTTP handlers. - -=== Initialization - -The `init/2` function must return a `cowboy_loop` tuple to enable -loop handler behavior. This tuple may optionally contain -the atom `hibernate` to make the process enter hibernation -until a message is received. - -This snippet enables the loop handler: - -[source,erlang] ----- -init(Req, State) -> - {cowboy_loop, Req, State}. ----- - -This also makes the process hibernate: - -[source,erlang] ----- -init(Req, State) -> - {cowboy_loop, Req, State, hibernate}. ----- - -=== Receive loop - -Once initialized, Cowboy will wait for messages to arrive -in the process' mailbox. When a message arrives, Cowboy -calls the `info/3` function with the message, the Req object -and the handler's state. - -The following snippet sends a reply when it receives a -`reply` message from another process, or waits for another -message otherwise. - -[source,erlang] ----- -info({reply, Body}, Req, State) -> - cowboy_req:reply(200, #{}, Body, Req), - {stop, Req, State}; -info(_Msg, Req, State) -> - {ok, Req, State, hibernate}. ----- - -Do note that the `reply` tuple here may be any message -and is simply an example. - -This callback may perform any necessary operation including -sending all or parts of a reply, and will subsequently -return a tuple indicating if more messages are to be expected. - -The callback may also choose to do nothing at all and just -skip the message received. - -If a reply is sent, then the `stop` tuple should be returned. -This will instruct Cowboy to end the request. - -Otherwise an `ok` tuple should be returned. - -=== Streaming loop - -Another common case well suited for loop handlers is -streaming data received in the form of Erlang messages. -This can be done by initiating a chunked reply in the -`init/2` callback and then using `cowboy_req:chunk/2` -every time a message is received. - -The following snippet does exactly that. As you can see -a chunk is sent every time an `event` message is received, -and the loop is stopped by sending an `eof` message. - -[source,erlang] ----- -init(Req, State) -> - Req2 = cowboy_req:stream_reply(200, Req), - {cowboy_loop, Req2, State}. - -info(eof, Req, State) -> - {stop, Req, State}; -info({event, Data}, Req, State) -> - cowboy_req:stream_body(Data, nofin, Req), - {ok, Req, State}; -info(_Msg, Req, State) -> - {ok, Req, State}. ----- - -=== Cleaning up - -Please refer to the xref:handlers[Handlers chapter] -for general instructions about cleaning up. - -=== Hibernate - -To save memory, you may hibernate the process in between -messages received. This is done by returning the atom -`hibernate` as part of the `loop` tuple callbacks normally -return. Just add the atom at the end and Cowboy will hibernate -accordingly. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/middlewares.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/middlewares.asciidoc deleted file mode 100644 index e6be30dd5b..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/middlewares.asciidoc +++ /dev/null @@ -1,69 +0,0 @@ -[[middlewares]] -== Middlewares - -Cowboy delegates the request processing to middleware components. -By default, two middlewares are defined, for the routing and handling -of the request, as is detailed in most of this guide. - -Middlewares give you complete control over how requests are to be -processed. You can add your own middlewares to the mix or completely -change the chain of middlewares as needed. - -Cowboy will execute all middlewares in the given order, unless one -of them decides to stop processing. - -=== Usage - -Middlewares only need to implement a single callback: `execute/2`. -It is defined in the `cowboy_middleware` behavior. - -This callback has two arguments. The first is the `Req` object. -The second is the environment. - -Middlewares can return one of three different values: - -* `{ok, Req, Env}` to continue the request processing -* `{suspend, Module, Function, Args}` to hibernate -* `{stop, Req}` to stop processing and move on to the next request - -Of note is that when hibernating, processing will resume on the given -MFA, discarding all previous stacktrace. Make sure you keep the `Req` -and `Env` in the arguments of this MFA for later use. - -If an error happens during middleware processing, Cowboy will not try -to send an error back to the socket, the process will just crash. It -is up to the middleware to make sure that a reply is sent if something -goes wrong. - -=== Configuration - -The middleware environment is defined as the `env` protocol option. -In the previous chapters we saw it briefly when we needed to pass -the routing information. It is a list of tuples with the first -element being an atom and the second any Erlang term. - -Two values in the environment are reserved: - -* `listener` contains the name of the listener -* `result` contains the result of the processing - -The `listener` value is always defined. The `result` value can be -set by any middleware. If set to anything other than `ok`, Cowboy -will not process any subsequent requests on this connection. - -The middlewares that come with Cowboy may define or require other -environment values to perform. - -You can update the environment by calling the `cowboy:set_env/3` -convenience function, adding or replacing a value in the environment. - -=== Routing middleware - -The routing middleware requires the `dispatch` value. If routing -succeeds, it will put the handler name and options in the `handler` -and `handler_opts` values of the environment, respectively. - -=== Handler middleware - -The handler middleware requires the `handler` and `handler_opts` -values. It puts the result of the request handling into `result`. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_1.0.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_1.0.asciidoc deleted file mode 100644 index 4f4ea5bfbf..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_1.0.asciidoc +++ /dev/null @@ -1,214 +0,0 @@ -[appendix] -== Migrating from Cowboy 1.0 to 2.0 - -A lot has changed between Cowboy 1.0 and 2.0. The `cowboy_req` -interface in particular has seen a massive revamp. Hooks are -gone, their functionality can now be achieved via stream -handlers. - -The documentation has seen great work, in particular the -manual. Each module and each function now has its own dedicated -manual page with full details and examples. - -=== Compatibility - -Compatibility with Erlang/OTP R16, 17 and 18 has been dropped. -Erlang/OTP 19.0 or above is required. It is non-trivial to -make Cowboy 2.0 work with older Erlang/OTP versions. - -Cowboy 2.0 is not compatible with Cowlib versions older than -2.0. It should be compatible with Ranch 1.0 or above, however -it has not been tested with Ranch versions older than 1.4. - -Cowboy 2.0 is tested on Arch Linux, Ubuntu, FreeBSD, Windows -and OSX. It is tested with every point release (latest patch -release) and also with HiPE on the most recent release. - -Cowboy 2.0 now comes with Erlang.mk templates. - -=== Features added - -* The HTTP/2 protocol is now supported. - -* Cowboy no longer uses only one process per connection. - It now uses one process per connection plus one process - per request by default. This is necessary for HTTP/2. - There might be a slight drop in performance for HTTP/1.1 - connections due to this change. - -* Cowboy internals have largely been reworked in order to - support HTTP/2. This opened the way to stream handlers, - which are a chain of modules that are called whenever - something happens relating to a request/response. - -* The `cowboy_stream_h` stream handler has been added. - It provides most of Cowboy's default behavior. - -* The `cowboy_compress_h` stream handler has been added. - It compresses responses when possible. It's worth noting - that it compresses in more cases than Cowboy 1.0 ever did. - -* Because of the many changes in the internals of Cowboy, - many options have been added or modified. Of note is that - the Websocket options are now given per handler rather - than for the entire listener. - -* Websocket permessage-deflate compression is now supported - via the `compress` option. - -* Static file handlers will now correctly find files found - in '.ez' archives. - -* Constraints have been generalized and are now used not only - in the router but also in some `cowboy_req` functions. Their - interface has also been modified to allow for reverse - operations and formatting of errors. - -=== Features removed - -* SPDY support has been removed. Use HTTP/2 instead. - -* Hooks have been removed. Use xref:streams[stream handlers] instead. - -* The undocumented `waiting_stream` hack has been removed. - It allowed disabling chunked transfer-encoding for HTTP/1.1. - It has no equivalent in Cowboy 2.0. Open a ticket if necessary. - -* Sub protocols still exist, but their interface has largely changed - and they are no longer documented for the time being. - -=== Changed behaviors - -* The handler behaviors have been renamed and are now `cowboy_handler`, - `cowboy_loop`, `cowboy_rest` and `cowboy_websocket`. - -* Plain HTTP, loop, REST and Websocket handlers have had their - init and terminate callbacks unified. They now all use the - `init/2` and `terminate/3` callbacks. The latter is now optional. - The terminate reason has now been documented for all handlers. - -* The tuple returned to switch to a different handler type has - changed. It now takes the form `{Module, Req, State}` or - `{Module, Req, State, Opts}`, where `Opts` is a map of options - to configure the handler. The timeout and hibernate options - must now be specified using this map, where applicable. - -* All behaviors that used to accept `halt` or `shutdown` tuples - as a return value no longer do so. The return value is now - a `stop` tuple, consistent across Cowboy. - -* Middlewares can no longer return an `error` tuple. They have - to send the response and return a `stop` tuple instead. - -* The `known_content_type` REST handler callback has been removed - as it was found unnecessary. - -* Websocket handlers have both the normal `init/2` and - an optional `websocket_init/1` function. The reason for - that exception is that the `websocket_*` callbacks execute - in a separate process from the `init/2` callback, and it - was therefore not obvious how timers or monitors should - be setup properly. They are effectively initializing the - handler before and after the HTTP/1.1 upgrade. - -* Websocket handlers can now send frames directly from - `websocket_init/1`. The frames will be sent immediately - after the handshake. - -* Websocket handler callbacks no longer receive the Req - argument. The `init/2` callback still receives it and - can be used to extract relevant information. The `terminate/3` - callback, if implemented, may still receive the Req - (see next bullet point). - -* Websocket handlers have a new `req_filter` option that - can be used to customize how much information should be - discarded from the Req object after the handshake. Note - that the Req object is only available in `terminate/3` - past that point. - -* Websocket handlers have their timeout default changed - from infinity to 60 seconds. - -=== New functions - -* The `cowboy_req:scheme/1` function has been added. - -* The `cowboy_req:uri/1,2` function has been added, replacing the - less powerful functions `cowboy_req:url/1` and `cowboy_req:host_url/1`. - -* The functions `cowboy_req:match_qs/2` and `cowboy_req:match_cookies/2` - allow matching query string and cookies against constraints. - -* The function `cowboy_req:set_resp_cookie/3` has been added to - complement `cowboy_req:set_resp_cookie/4`. - -* The functions `cowboy_req:resp_header/2,3` and `cowboy_req:resp_headers/1` - have been added. They can be used to retrieve response headers - that were previously set. - -* The function `cowboy_req:set_resp_headers/2` has been added. It - allows setting many response headers at once. - -* The functions `cowboy_req:push/3,4` can be used to push resources - for protocols that support it (by default only HTTP/2). - -=== Changed functions - -* The `cowboy:start_http/4` function was renamed to `cowboy:start_clear/3`. - -* The `cowboy:start_https/4` function was renamed to `cowboy:start_tls/3`. - -* Most, if not all, functions in the `cowboy_req` module have been modified. - Please consult the changelog of each individual functions. The changes - are mainly about simplifying and clarifying the interface. The Req is no - longer returned when not necessary, maps are used wherever possible, - and some functions have been renamed. - -* The position of the `Opts` argument for `cowboy_req:set_resp_cookie/4` - has changed to improve consistency. It is now the last argument. - -=== Removed functions - -* The functions `cowboy_req:url/1` and `cowboy_req:host_url/1` have been - removed in favor of the new function `cowboy_req:uri/1,2`. - -* The functions `cowboy_req:meta/2,3` and `cowboy_req:set_meta/3` have - been removed. The Req object is now a public map, therefore they became - unnecessary. - -* The functions `cowboy_req:set_resp_body_fun/2,3` have been removed. - For sending files, the function `cowboy_req:set_resp_body/2` can now - take a sendfile tuple. - -* Remove many undocumented functions from `cowboy_req`, including the - functions `cowboy_req:get/2` and `cowboy_req:set/3`. - -=== Other changes - -* The correct percent-decoding algorithm is now used for path elements - during routing. It will no longer decode `+` characters. - -* The router will now properly handle path segments `.` and `..`. - -* Routing behavior has changed for URIs containing latin1 characters. - They are no longer allowed. URIs are expected to be in UTF-8 once - they are percent-decoded. - -* Clients that send multiple headers of the same name - will have the values of those headers concatenated into a - comma-separated list. This is of special importance in the - case of the content-type header, as previously only the - first value was used in the `content_types_accepted/2` step - in REST handlers. - -* Etag comparison in REST handlers has been fixed. Some requests may - now fail when they succeeded in the past. - -* The `If-*-Since` headers are now ignored in REST handlers if - the corresponding `If*-Match` header exist. The former is - largely a backward compatible header and this shouldn't create - any issue. The new behavior follows the current RFCs more closely. - -* The static file handler has been improved to handle more special - characters on systems that accept them. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.0.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.0.asciidoc deleted file mode 100644 index c76430c2f6..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.0.asciidoc +++ /dev/null @@ -1,107 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.0 to 2.1 - -Cowboy 2.1 focused on adding features that were temporarily -removed in Cowboy 2.0. A number of bugs found in the 2.0 -release were also fixed. - -=== Features added - -* It is now possible to obtain the client TLS certificate - and the local IP/port for the connection from the Req object. - -* Informational responses (1XX responses) can now be sent. - They must be sent before initiating the final response. - -* The `expect: 100-continue` header is now handled - automatically. The 100 response will be sent on the - first `cowboy_req:read_body/2,3,4` call. This only applies - when using the default `cowboy_stream_h` stream handler. - -=== Experimental features added - -Experimental features are previews of features that will be -added in a future release. They are not documented and their -interface may change at any time. You are welcome to try them -and provide feedback. - -* The `cowboy_metrics_h` stream handler can be used to - extract metrics out of Cowboy. It must be used first in - the list of stream handlers, and will record all events - related to requests, responses and spawned processes. - When the stream terminates it will pass this information - to a user-defined callback. - -* The `cowboy_tracer_h` stream handler can be used to setup - automatic tracing of specific requests. You can conditionally - enable tracing based on a function, header, path or any other - element from the request and the trace will apply to the - entire connection and any processes created by it. This is - meant to be used for debugging both in tests and production. - -=== Changed behaviors - -* The `cowboy_rest` handler now implements a mechanism for - switching to a different type of handler from any callback - where `stop` is also allowed. Switch by returning - `{switch_handler, Module}` or `{switch_handler, Module, Opts}`. - This is especially useful for switching to `cowboy_loop` - for streaming the request or response body. - -* REST callbacks that do not allow `stop` as a return value - are now explicitly listed in the documentation. - -=== New functions - -* The function `cowboy_req:sock/1` returns the IP/port - of the local socket. - -* The function `cowboy_req:cert/1` returns the client - TLS certificate or `undefined` if it isn't available. - -* The function `cowboy_req:inform/2,3` sends an - informational response. - -=== Bugs fixed - -* Ensure HTTP/2 connections are not closed prematurely - when the user code does not read the request body. - -* Ensure HTTP/1.1 streams are not terminated too early. - Their behavior is now consistent with the HTTP/2 code - where the stream handler is only terminated when the - `stop` command is returned. - -* Sending zero-sized data from stream handlers or from - `cowboy_req:stream_body/3` could lead to issues with - HTTP/1.1. This has been fixed. - -* The final chunk sent by Cowboy when it terminates a - chunked body after the handler process exits was not - passed through stream handlers, which could lead to - issues when `cowboy_compress_h` was being used. This - is now corrected. - -* The stream handler state was discarded in some cases - where Cowboy had to send a response or response data - automatically when ending a stream. This has now - been corrected. - -* The stream handler callback `terminate/3` will now be - called when switching to another protocol using the - command `switch_protocol`. This doesn't apply when - doing upgrades to HTTP/2 as those occur before the - stream is initialized. - -* Cowlib has been updated to 2.0.1 to fix an issue with - Websocket compression when using Erlang/OTP 20.1. Note - that at the time of writing all 20.1 versions (from - 20.1 to 20.1.4) have issues when compression is enabled. - It is expected to work properly from 20.1.5 onward. In - the meantime it is recommended to run the plain 20.1 - release and disable Websocket compression, or use a - release before 20.1. - -* Cowboy will no longer crash when the `cowboy_clock` - process is not running. This can happen when Cowboy - is being restarted during upgrades, for example. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.1.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.1.asciidoc deleted file mode 100644 index 3c0681ff87..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.1.asciidoc +++ /dev/null @@ -1,107 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.1 to 2.2 - -Cowboy 2.2 focused on adding features required for writing -gRPC servers and on completing test suites for the core -HTTP RFCs, fixing many bugs along the way. - -=== Features added - -* Add support for sending trailers at the end of response bodies. - Trailers are additional header fields that may be sent after the - body to add more information to the response. Their usage is - required in gRPC servers. They are optional and may be discarded - in other scenarios (for example if the request goes through an - HTTP/1.0 proxy, as HTTP/1.0 does not support trailers). - -* The `max_skip_body_length` option was added to `cowboy_http`. - It controls how much of a request body Cowboy is willing to skip - when the handler did not touch it. If the remaining body size is - too large Cowboy instead closes the connection. It defaults to 1MB. - -* The CONNECT and TRACE methods are now rejected as they are - currently not implemented and must be handled differently than - other methods. They will be implemented in a future release. - -=== New functions - -* The function `stream_trailers/2` has been added. It terminates - a stream and adds trailer fields at the end of the response. A - corresponding stream handler command `{trailers, Trailers}` - has also been added. - -=== Bugs fixed - -* Test suites for the core HTTP RFCs RFC7230, RFC7231 and RFC7540 - have been completed. Many of the bugs listed here were fixed as - a result of this work. - -* Many HTTP/2 edge cases when clients are misbehaving have been - corrected. This includes many cases where the request is malformed - (for example when a pseudo-header is present twice). - -* When the HTTP/2 SETTINGS_INITIAL_WINDOW_SIZE value changes, - Cowboy now properly updates the flow control windows. - -* HTTP/2 could mistakenly log stray messages that actually were - expected. This is no longer the case. - -* We no longer send a GOAWAY frame when the HTTP/2 preface is invalid. - -* Some values in the Req object of pushed requests were in the - wrong type. They are now the expected binary instead of iolist. - -* A response body was sometimes sent in response to HEAD requests - when using HTTP/2. The body is now ignored. - -* The `max_headers` option for `cowboy_http` was not always respected - depending on the contents of the buffer. The limit is now strict. - -* When an early error occurred on the HTTP/1.1 request line, the - partial Req given to stream handlers was missing the `ref` and - `peer` information. This has been corrected. - -* Absolute URIs with a userinfo component, or without an authority - component, are now properly rejected for HTTP/1.0 and HTTP/1.1. - -* Whitespace is no longer allowed in header lines before the colon. - -* 408 responses to HTTP/1.1 requests now properly include a - connection: close header indicating that we are going to - close the connection. This header will also be sent for - other early errors resulting in the closing of the connection. - -* When both the transfer-encoding and content-length headers are - sent in an HTTP/1.1 request, the transfer-encoding now takes - precedence over the content-length header and the latter is - removed from the Req object. - -* A 400 response is now returned when the transfer-encoding - header is invalid or contains any transfer-coding other - than chunked. - -* Invalid chunk sizes are now rejected immediately. - -* Chunk extensions are now limited to 129 characters. They are - not used in practice and are still ignored by Cowboy. The limit - is not configurable. - -* The final chunk was mistakenly sent in responses to HEAD - requests. This is now corrected. - -* `OPTIONS *` requests were broken in Cowboy 2.0. They are now - working again. Both the routing and `cowboy_req:uri/1,2` have - been corrected. - -* 204 responses no longer include a content-length header. - -* A packet could be lost when switching to Websocket or any - other protocol via the `switch_protocol` command. This is - now fixed. - -* A 426 response will now be sent when a handler requires - the client to upgrade to Websocket and the request did not - include the required headers. - -* Both experimental stream handlers `cowboy_metrics_h` and - `cowboy_tracer_h` received a number of fixes and improvements. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.2.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.2.asciidoc deleted file mode 100644 index dacf790e30..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.2.asciidoc +++ /dev/null @@ -1,56 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.2 to 2.3 - -Cowboy 2.3 focused on making the Cowboy processes behave -properly according to OTP principles. This version is a -very good milestone toward that goal and most of everything -should now work. Release upgrades and a few details will -be improved in future versions. - -=== Features added - -* Add support for all functions from the module `sys`. Note - that Cowboy currently does not implement the `sys` debugging - mechanisms as tracing is recommended instead. - -* Add a `max_frame_size` option for Websocket handlers - to close the connection when the client attempts to - send a frame that's too large. It currently defaults - to `infinity` to avoid breaking existing code but will - be changed in a future version. - -* Update Cowlib to 2.2.1. - -* Add support for the 308 status code and a test suite - for RFC7538 where it is defined. - -=== Bugs fixed - -* Ensure timeout options accept the value `infinity` as - documented. - -* Properly reject HTTP/2 requests with an invalid content-length - header instead of simply crashing. - -* When switching from HTTP/1.1 to Websocket or user protocols - all the messages in the mailbox were flushed. Only messages - specific to `cowboy_http` should now be flushed. - -* Parsing of the x-forwarded-for header has been corrected. - It now supports IPv6 addresses both with and without port. - -* Websocket subprotocol tokens are now parsed in a case - insensitive manner, according to the spec. - -* Cookies without values are now allowed. For example `Cookie: foo`. - -* Colons are now allowed within path segments in routes provided - to `cowboy_router:compile/1` as long as they are not the first - character of the path segment. - -* The `cowboy_req:delete_resp_header/2` function will no longer - crash when no response header was set before calling it. - -* A miscount of the output HTTP/2 flow control window has been - fixed. It prevented sending the response body fully to some - clients. The issue only affected response bodies sent as iolists. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.3.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.3.asciidoc deleted file mode 100644 index 6a604f97c2..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.3.asciidoc +++ /dev/null @@ -1,66 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.3 to 2.4 - -Cowboy 2.4 focused on improving the HTTP/2 implementation. -All existing tests from RFC7540 and the h2spec test suite -now all pass. Numerous options have been added to control -SETTINGS and related behavior. In addition experimental -support for Websocket over HTTP/2 was added. - -=== Features added - -* Add experimental support for Websocket over HTTP/2. - You can use the `enable_connect_protocol` option to - enable. It implements the following draft: - https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-01 - -* Add options `max_decode_table_size` and - `max_encode_table_size` to restrict the size of the - HPACK compression dictionary. - -* Add option `max_concurrent_streams` to restrict the - number of HTTP/2 streams that can be opened concurrently. - -* Add options `initial_connection_window_size` and - `initial_stream_window_size` to restrict the size of - the HTTP/2 request body buffers for the whole connection - and per stream, respectively. - -* Add options `max_frame_size_received` and - `max_frame_size_sent` to restrict the size of - HTTP/2 frames. - -* Add option `settings_timeout` to reject clients that - did not send a SETTINGS ack. Note that this currently - may only occur at the beginning of the connection. - -* Update Ranch to 1.5.0 - -* Update Cowlib to 2.3.0 - -=== Bugs fixed - -* Fix the END_STREAM flag for informational responses - when using HTTP/2. - -* Receive and ignore HTTP/2 request trailers if any - for HTTP/2 requests. Request trailer information will - be propagated to the user code in a future release. - -* Reject WINDOW_UPDATE frames that are sent after the - client sent an RST_STREAM. Note that Cowboy will not - keep state information about terminated streams - forever and so the behavior might differ depending - on when the stream was reset. - -* Reject streams that depend on themselves. Note that - Cowboy currently does not implement HTTP/2's priority - mechanisms so this issue was harmless. - -* Reject HTTP/2 requests where the body size is different - than the content-length value. Note that due to how Cowboy - works some requests might go through regardless, for - example when the user code does not read the request body. - -* Fix all existing test failures from RFC7540. This was - mostly incorrect test cases or intermittent failures. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.4.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.4.asciidoc deleted file mode 100644 index 3cdeaa549e..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.4.asciidoc +++ /dev/null @@ -1,109 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.4 to 2.5 - -Cowboy 2.5 focused on making the test suites pass. A -variety of new features, fixes and improvements have -also been worked on. - -=== Features added - -* Add option `linger_timeout` to control how long - Cowboy will wait before closing the socket when - shutting down the connection. This helps avoid - the TCP reset problem HTTP/1.1 suffers from. The - default is now 1000 ms. - -* It is now possible to stream a response body - without using chunked transfer-encoding when the - protocol is HTTP/1.1. To enable this behavior, - simply pass the content-length header with the - expected size when initiating the streamed response. - -* Update Ranch to 1.6.2 - -* Update Cowlib to 2.6.0 - -=== Experimental features added - -* Websocket handlers now feature a commands-based interface. - The return value from the callbacks can now take the form - `{Commands, State}` where `Commands` can be frames to be - sent or commands yet to be introduced. New commands will - be available only through this new interface. - -* Add the `{active, boolean()}` Websocket handler command. - It allows disabling reading from the socket when `false` - is returned. `true` reenables reading from the socket. - -* Add the protocol option `logger` that allows configuring - which logger module will be used. The logger module must - follow the interface of the new `logger` module in Erlang/OTP 21, - or be set to `error_logger` to keep the old behavior. A - similar transport option exists in Ranch 1.6; both options - are necessary to override Cowboy's default behavior completely. - -* Add the `{log, Level, Format, Args}` stream handler command. - Making it a command rather than a direct call will simplify - silencing particular log messages. - -=== New functions - -* The function `cowboy_req:stream_events/3` streams one or more - text/event-stream events, encoding them automatically. - -* The functions `cowboy_req:read_and_match_urlencoded_body/2,3` - can be used to read, parse and match application/x-www-form-urlencoded - request bodies, in a similar way to `cowboy_req:match_qs/2`. - -=== Bugs fixed - -* Fix Erlang/OTP 21 warnings. - -* Ensure that the port number is always defined in the - Req object. When it is not provided in the request, - the default port number for the protocol being used - will be set. - -* Ensure stream handlers can run after `cowboy_stream_h`. - -* Honor the SETTINGS_ENABLE_PUSH HTTP/2 setting: don't - send PUSH frames to clients that disabled it. - -* Fix HTTP/2 `settings_timeout` option when the value - is set to `infinity`. - -* HTTP/1.1 responses will no longer include a trailer header - when the request had no te header. - -* HTTP/1.1 204 responses no longer send the transfer-encoding - header when `cowboy_req:stream_reply/2,3` is used to send - a response. - -* Improve HTTP/1.1 keepalive handling to avoid processing - requests that follow the final request that will receive - a response. - -* Improve the validation of HTTP/1.1 absolute-form requests. - -* When the `switch_protocol` is used after a response was - sent, Cowboy will no longer attempt to send the 101 informational - response for the protocol upgrade. This caused a crash of the - connection previously. - -* Errors that occur when a callback returned by - `content_types_provided` does not exist have been improved. - -* Prevent annoying error logs when using sendfile in - Erlang/OTP 20 and lower. - -* Add missing frame types to `websocket_handle`. - -* A test suite has been added for RFC8297 to ensure that - 103 informational responses can be sent. - -* Numerous test cases have been fixed, improved or removed in order - to make the test suites pass. Most of the failures were caused - by broken tests. - -* Some misguiding or incorrect statements in the documentation - have been removed or clarified. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.5.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.5.asciidoc deleted file mode 100644 index b91b617f1c..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.5.asciidoc +++ /dev/null @@ -1,148 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.5 to 2.6 - -Cowboy 2.6 greatly refactored the HTTP/2 code, a large -part of which was moved to Cowlib and is now used by -both the Cowboy server and the Gun client. - -A large number of tickets were also closed which -resulted in many bugs fixed and many features and -options added, although some of them are still -experimental. - -=== Features added - -* Add support for the PROXY protocol header. - It can be enabled via the `proxy_header` option. - The proxy information can then be found under - the `proxy_info` key in the Req object. - -* Allow using sendfile tuples in `cowboy_req:stream_body/3` - and in the data command in stream handlers. The only - caveat is that when using `cowboy_compress_h` the - sendfile tuples may have to be converted to in-memory - data in order to compress them. This is the case for - gzip compression. - -* The stream handlers `cowboy_stream_h` and - `cowboy_compress_h` are now documented. - -* Add the `chunked` option to allow disabling chunked - transfer-encoding for HTTP/1.1 connections. - -* Add the `http10_keepalive` option to allow disabling - keep-alive for HTTP/1.0 connections. - -* Add the `idle_timeout` option for HTTP/2. - -* Add the `sendfile` option to both HTTP/1.1 and HTTP/2. - It allows disabling the sendfile syscall entirely for - all connections. It is recommended to disable sendfile - when using VirtualBox shared folders. - -* Add the `rate_limited/2` callback to REST handlers. - -* Add the `deflate_opts` option to Websocket handlers that - allows configuring deflate options for the - permessage-deflate extension. - -* Add the `charset` option to `cowboy_static`. - -* Add support for the SameSite cookie attribute. - -* Update Ranch to 1.7.0 - -* Update Cowlib to 2.7.0 - -=== Experimental features added - -* Add support for range requests (RFC7233) in REST handlers. - This adds two new callbacks: `ranges_accepted/2` and - `range_satisfiable/2` along with the user-specified - `ProvideRangeCallback/2`. - -* Add automatic handling of range requests to REST handlers - that return the callback `auto` from `ranges_accepted/2`. - Cowboy will call the configured `ProvideCallback` and - then split the ouput automatically for the ranged response. - -* Enable range requests support in `cowboy_static`. - -* Add the `{deflate, boolean()}` Websocket handler - command to disable permessage-deflate compression - temporarily. - -* Add the `compress_threshold` option which allows - configuring how much data must be present in a - response body to compress it. This only applies - to non-streamed bodies at this time. - -* Add the `compress_buffering` option which allows - controlling whether some buffering may be done - when streaming a response body. Change the default - behavior to not buffer to make sure it works by - default in all scenarios. - -* Add the `{set_options, map()}` command to stream - handlers and Websocket handlers. This can be used - to update options on a per-request basis. Allow - overriding the `idle_timeout` option for both - HTTP/1.1 and Websocket, the `cowboy_compress_h` - options for HTTP/1.1 and HTTP/2 and the `chunked` - option for HTTP/1.1. - -=== Bugs fixed - -* Do not send a content-length automatically with - 304 responses. This status code allows a content-length - that corresponds to what would have been sent for a 200 - response, but is never followed by a body. - -* HTTP/2 streams are now terminated once the body - has been sent fully, instead of immediately once - the stop command is returned (by default when the - request process exits). Metrics will therefore - more accurately represent when a stream ended. - -* Terminate connection processes gracefully when the - parent process exists or when sys:terminate/2,3 - is called. - -* Automatically ignore the boundary parameter of multipart - media types when using REST handlers. This is a special - parameter that may change with all requests and cannot - be predicted. - -* Fix parsing of the accept header when it contains charset - parameters. They are case insensitive and will now be - lowercased, like for accept-charset and content-type. - -* Handle the charset parameter using `charsets_provided` - when it is present in the accept header when using - REST handlers. - -* Don't select charsets when the q-value is 0 in REST - handlers. - -* Handle accept-charset headers that include a wildcard - in REST handlers. - -* Only send a charset header when the content-type - negotiated is of type text in REST handlers. - -* Remove the default charset iso-8859-1 from REST - handlers when no other is provided. This has been - removed from the HTTP specifications for a long time. - -* Many cases where a content-type header was sent - unnecessarily in the REST handlers response have - been fixed. - -* Handle error_response commands in `cowboy_metrics_h`. - -* A number of types and function specifications were - fixed or improved. Dialyzer is now run against both - the code and tests to help uncover issues. - -* An undefined `cowboy_router` behavior has been - documented. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.6.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.6.asciidoc deleted file mode 100644 index 91d1588745..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/migrating_from_2.6.asciidoc +++ /dev/null @@ -1,224 +0,0 @@ -[appendix] -== Migrating from Cowboy 2.6 to 2.7 - -Cowboy 2.7 improves the HTTP/2 code with optimizations -around the sending of DATA and WINDOW_UPDATE frames; -graceful shutdown of the connection when the client is -going away; and rate limiting mechanisms. New options -and mechanisms have also been added to control the -amount of memory Cowboy ends up using with both HTTP/1.1 -and HTTP/2. Much, but not all, of this work was done -to address HTTP/2 CVEs about potential denial of service. - -In addition, many of the experimental features introduced -in previous releases have been marked stable and are now -documented. - -Cowboy 2.7 requires Erlang/OTP 20.0 or greater. - -=== Features added - -* Cowboy is now compatible with both Ranch 1.7 and the - upcoming Ranch 2.0. - -* The number of HTTP/2 WINDOW_UPDATE frames Cowboy sends - has been greatly reduced. Cowboy now applies heuristics - to determine whether it is necessary to update the window, - based on the current window size and the amount of data - requested by streams (the `cowboy_req:read_body/2` length - for example). Six new options have been added to control - this behavior: `connection_window_margin_size`, - `connection_window_update_threshold`, - `max_connection_window_size`, `max_stream_window_size`, - `stream_window_margin_size` and - `stream_window_update_threshold`. - -* HTTP/2 connections will now be shut down gracefully - when receiving a GOAWAY frame. Cowboy will simply - wait for existing streams to finish before closing - the connection. - -* Functions that stream the response body now have - backpressure applied. They now wait for a message - to be sent back. The message will be held off when - using HTTP/2 and the buffer sizes exceed either - `max_connection_buffer_size` or `max_stream_buffer_size`. - For HTTP/1.1 the data is sent synchronously and we - rely instead on the TCP backpressure. - -* A new HTTP/2 option `stream_window_data_threshold` - can be used to control how little the DATA frames that - Cowboy sends can get. By default Cowboy will wait for - the window to be large enough to send either everything - queued or to reach the default maximum frame size of - 16384 bytes. - -* A new HTTP/2 option `max_receive_frame_rate` can be - used to control how fast the server is willing to receive - frames. By default it will accept 1000 frames every 10 - seconds. - -* A new HTTP/2 option `max_reset_stream_rate` can be - used to control the rate of errors the server is - willing to accept. By default it will accept 10 - stream resets every 10 seconds. - -* Flow control for incoming data has been implemented - for HTTP/1.1. Cowboy will now wait for the user code - to ask for the request body before reading it from - the socket. The option `initial_stream_flow_size` - controls how much data Cowboy will read without - being asked. - -* The HTTP/1.1 and HTTP/2 option `logger` is now - documented. - -* The Websocket option `validate_utf8` has been - added. It can be used to disable the expensive UTF-8 - validation for incoming text and close frames. - -* The experimental commands based Websocket interface - is now considered stable and has been documented. - The old interface is now deprecated. - -* A new Websocket handler command `shutdown_reason` - can be used to change the normal exit reason of - Websocket processes. By default `normal` is used; - with this command the exit reason can be changed - to `{shutdown, ShutdownReason}`. - -* The experimental stream handlers `cowboy_metrics_h` - and `cowboy_tracer_h` are now considered stable and - have been documented. - -* The stream handler commands `set_options` and `log` - are now considered stable and have been documented. - -* The router is now capable of retrieving dispatch - rules directly from the `persistent_term` storage - (available starting from Erlang/OTP 21.2). - -* Support for the status codes 208 and 508 has been - added. - -* Update Ranch to 1.7.1. - -* Update Cowlib to 2.8.0. - -=== Experimental features added - -* It is now possible to read the response body from any - process, as well as doing any other `cowboy_req` - operations. Since this is not recommended due to - race condition concerns this feature will always - remain experimental. - -=== New functions - -* The function `cowboy_req:filter_cookies/2` has been - added. It can be called before parsing/matching - cookies in order to filter out undesirables. The - main reason for doing this is to avoid most parse - errors that may occur when dealing with Web browsers - (which have a string-based Javascript interface to - cookies that is very permissive of invalid content) - and to be able to recover in other cases. - -* The function `cowboy_req:cast/2` has been added. - It can be used to send events to stream handlers. - -=== Bugs fixed - -* A number of fixes and additions were made to address the - HTTP/2 CVEs CVE-2019-9511 through CVE-2019-9518, except - for CVE-2019-9513 which required no intervention as the - relevant protocol feature is not implemented by Cowboy. - -* The HTTP/2 connection window could become larger than the - protocol allows, leading to errors. This has been corrected. - -* The presence of empty header names in HTTP/2 requests now - results in the request to be rejected. - -* Cowboy will now remove headers specific to HTTP/1.1 - (the hop by hop headers such as connection or upgrade) - when building an HTTP/2 response. - -* A bug in the HTTP/2 code that resulted in the failure to - fully send iolist response bodies has been fixed. Cowboy - would just wait indefinitely in those cases. - -* It was possible for a final empty HTTP/2 DATA frame to get - stuck and never sent when the window reached 0 and the remote - end did not increase the window anymore. This has been - corrected. - -* Cowboy now uses the host header when the HTTP/2 - :authority pseudo header is missing. A common scenario - where this occurs is when proxies translate incoming - HTTP/1.1 requests to HTTP/2. - -* HTTP/1.1 connections are now properly closed when the - user code sends less data than advertised in the response - headers. - -* Cowboy will now close HTTP/1.1 connections immediately when - a header line is missing a colon separator. Previously it - was waiting for more data. - -* It was possible for Cowboy to receive stray timeout messages - for HTTP/1.1 connections, resulting in crashes. The timeout - handling in HTTP/1.1 has been reworked and the issue should - no longer occur. - -* The type for the Req object has been updated to accept - custom fields as was already documented. - -* The authentication scheme returned when parsing the - authorization header is now case insensitive, which - means it will be returned as lowercase. - -* Cowboy no longer discards data that follows a Websocket - upgrade request. Note that the protocol does not allow - sending data before receiving a successful Websocket - upgrade response, so this fix is more out of principle - rather than to fix a real world issue. - -* The `cowboy_static` handler will now properly detect - the type of files that have an uppercase or mixed - extension component. - -* The `cowboy_static` handler is now consistent across all - supported platforms. It now explicitly rejects `path_info` - components that include a forward slash, backward slash - or NUL character. - -* The update to Ranch 1.7.1 fixes an issue with the PROXY - protocol that would cause checksum verification to fail. - -* The HTTP/1.1 error reason for `stream_error` mistakenly - contained an extra element. It has now been removed. - -* The `PartialReq` given to the `early_error` stream handler - callback now includes headers when the protocol is HTTP/2. - -* A bug where the stacktrace was incorrect in error messages - has been fixed. The problem occurred when an exception - occurred in the handler's terminate callback. - -* The REST flowchart for POST, PATCH and PUT has received - a number of fixes and had to be greatly reworked as a - result. When the method is PUT, we do not check for - the location header in the response. When the resource - doesn't exist and the method was PUT the flowchart was - largely incorrect. A 415 response may occur after the - `content_types_accepted` callback and was missing from - the flowchart. - -* The documentation for `content_types_accepted` now - includes the media type wildcard that was previously - missing. - -* The documentation for a type found in `cow_cookie` - was missing. A manual page for `cow_cookie` was added - and can be found in the Cowlib documentation. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/modern_web.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/modern_web.asciidoc deleted file mode 100644 index 485257323a..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/modern_web.asciidoc +++ /dev/null @@ -1,122 +0,0 @@ -[[modern_web]] -== The modern Web - -Cowboy is a server for the modern Web. This chapter explains -what it means and details all the standards involved. - -Cowboy supports all the standards listed in this document. - -=== HTTP/2 - -HTTP/2 is the most efficient protocol for consuming Web -services. It enables clients to keep a connection open -for long periods of time; to send requests concurrently; -to reduce the size of requests through HTTP headers -compression; and more. The protocol is binary, greatly -reducing the resources needed to parse it. - -HTTP/2 also enables the server to push messages to the -client. This can be used for various purposes, including -the sending of related resources before the client requests -them, in an effort to reduce latency. This can also be used -to enable bidirectional communication. - -Cowboy provides transparent support for HTTP/2. Clients -that know it can use it; others fall back to HTTP/1.1 -automatically. - -HTTP/2 is compatible with the HTTP/1.1 semantics. - -HTTP/2 is defined by RFC 7540 and RFC 7541. - -=== HTTP/1.1 - -HTTP/1.1 is the previous version of the HTTP protocol. -The protocol itself is text-based and suffers from numerous -issues and limitations. In particular it is not possible -to execute requests concurrently (though pipelining is -sometimes possible), and it's also sometimes difficult -to detect that a client disconnected. - -HTTP/1.1 does provide very good semantics for interacting -with Web services. It defines the standard methods, headers -and status codes used by HTTP/1.1 and HTTP/2 clients and -servers. - -HTTP/1.1 also defines compatibility with an older version -of the protocol, HTTP/1.0, which was never really standardized -across implementations. - -The core of HTTP/1.1 is defined by RFC 7230, RFC 7231, -RFC 7232, RFC 7233, RFC 7234 and RFC 7235. Numerous RFCs -and other specifications exist defining additional HTTP -methods, status codes, headers or semantics. - -=== Websocket - -xref:ws_protocol[Websocket] is a protocol built on top of HTTP/1.1 -that provides a two-ways communication channel between the client and -the server. Communication is asynchronous and can occur concurrently. - -It consists of a Javascript object allowing setting up a -Websocket connection to the server, and a binary based -protocol for sending data to the server or the client. - -Websocket connections can transfer either UTF-8 encoded text -data or binary data. The protocol also includes support for -implementing a ping/pong mechanism, allowing the server and -the client to have more confidence that the connection is still -alive. - -A Websocket connection can be used to transfer any kind of data, -small or big, text or binary. Because of this Websocket is -sometimes used for communication between systems. - -Websocket messages have no semantics on their own. Websocket -is closer to TCP in that aspect, and requires you to design -and implement your own protocol on top of it; or adapt an -existing protocol to Websocket. - -Cowboy provides an interface known as xref:ws_handlers[Websocket handlers] -that gives complete control over a Websocket connection. - -The Websocket protocol is defined by RFC 6455. - -=== Long-lived requests - -Cowboy provides an interface that can be used to support -long-polling or to stream large amounts of data reliably, -including using Server-Sent Events. - -Long-polling is a mechanism in which the client performs -a request which may not be immediately answered by the -server. It allows clients to request resources that may -not currently exist, but are expected to be created soon, -and which will be returned as soon as they are. - -Long-polling is essentially a hack, but it is widely used -to overcome limitations on older clients and servers. - -Server-Sent Events is a small protocol defined as a media -type, `text/event-stream`, along with a new HTTP header, -`Last-Event-ID`. It is defined in the EventSource W3C -specification. - -Cowboy provides an interface known as xref:loop_handlers[loop handlers] -that facilitates the implementation of long-polling or stream -mechanisms. It works regardless of the underlying protocol. - -=== REST - -xref:rest_principles[REST, or REpresentational State Transfer], -is a style of architecture for loosely connected distributed -systems. It can easily be implemented on top of HTTP. - -REST is essentially a set of constraints to be followed. -Many of these constraints are purely architectural and -solved by simply using HTTP. Some constraints must be -explicitly followed by the developer. - -Cowboy provides an interface known as xref:rest_handlers[REST handlers] -that simplifies the implementation of a REST API on top of -the HTTP protocol. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/multipart.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/multipart.asciidoc deleted file mode 100644 index 0825244ccb..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/multipart.asciidoc +++ /dev/null @@ -1,169 +0,0 @@ -[[multipart]] -== Multipart requests - -Multipart originates from MIME, an Internet standard that -extends the format of emails. - -A multipart message is a list of parts. A part contains -headers and a body. The body of the parts may be -of any media type, and contain text or binary data. -It is possible for parts to contain a multipart media -type. - -In the context of HTTP, multipart is most often used -with the `multipart/form-data` media type. It is what -browsers use to upload files through HTML forms. - -The `multipart/byteranges` is also common. It is the -media type used to send arbitrary bytes from a resource, -enabling clients to resume downloads. - -=== Form-data - -In the normal case, when a form is submitted, the -browser will use the `application/x-www-form-urlencoded` -content-type. This type is just a list of keys and -values and is therefore not fit for uploading files. - -That's where the `multipart/form-data` content-type -comes in. When the form is configured to use this -content-type, the browser will create a multipart -message where each part corresponds to a field on -the form. For files, it also adds some metadata in -the part headers, like the file name. - -A form with a text input, a file input and a select -choice box will result in a multipart message with -three parts, one for each field. - -The browser does its best to determine the media type -of the files it sends this way, but you should not -rely on it for determining the contents of the file. -Proper investigation of the contents is recommended. - -=== Checking for multipart messages - -The content-type header indicates the presence of -a multipart message: - -[source,erlang] ----- -{<<"multipart">>, <<"form-data">>, _} - = cowboy_req:parse_header(<<"content-type">>, Req). ----- - -=== Reading a multipart message - -Cowboy provides two sets of functions for reading -request bodies as multipart messages. - -The `cowboy_req:read_part/1,2` functions return the -next part's headers, if any. - -The `cowboy_req:read_part_body/1,2` functions return -the current part's body. For large bodies you may -need to call the function multiple times. - -To read a multipart message you need to iterate over -all its parts: - -[source,erlang] ----- -multipart(Req0) -> - case cowboy_req:read_part(Req0) of - {ok, _Headers, Req1} -> - {ok, _Body, Req} = cowboy_req:read_part_body(Req1), - multipart(Req); - {done, Req} -> - Req - end. ----- - -When part bodies are too large, Cowboy will return -a `more` tuple, and allow you to loop until the part -body has been fully read. - -The function `cow_multipart:form_data/1` can be used -to quickly obtain information about a part from a -`multipart/form-data` message. The function returns -a `data` or a `file` tuple depending on whether this -is a normal field or a file being uploaded. - -The following snippet will use this function and -use different strategies depending on whether the -part is a file: - -[source,erlang] ----- -multipart(Req0) -> - case cowboy_req:read_part(Req0) of - {ok, Headers, Req1} -> - Req = case cow_multipart:form_data(Headers) of - {data, _FieldName} -> - {ok, _Body, Req2} = cowboy_req:read_part_body(Req1), - Req2; - {file, _FieldName, _Filename, _CType} -> - stream_file(Req1) - end, - multipart(Req); - {done, Req} -> - Req - end. - -stream_file(Req0) -> - case cowboy_req:read_part_body(Req0) of - {ok, _LastBodyChunk, Req} -> - Req; - {more, _BodyChunk, Req} -> - stream_file(Req) - end. ----- - -Both the part header and body reading functions can take -options that will be given to the request body reading -functions. By default, `cowboy_req:read_part/1` reads -up to 64KB for up to 5 seconds. `cowboy_req:read_part_body/1` -has the same defaults as `cowboy_req:read_body/1`. - -To change the defaults for part headers: - -[source,erlang] -cowboy_req:read_part(Req, #{length => 128000}). - -And for part bodies: - -[source,erlang] -cowboy_req:read_part_body(Req, #{length => 1000000, period => 7000}). - -=== Skipping unwanted parts - -Part bodies do not have to be read. Cowboy will automatically -skip it when you request the next part's body. - -The following snippet reads all part headers and skips -all bodies: - -[source,erlang] ----- -multipart(Req0) -> - case cowboy_req:read_part(Req0) of - {ok, _Headers, Req} -> - multipart(Req); - {done, Req} -> - Req - end. ----- - -Similarly, if you start reading the body and it ends up -being too big, you can simply continue with the next part. -Cowboy will automatically skip what remains. - -While Cowboy can skip part bodies automatically, the read -rate is not configurable. Depending on your application -you may want to skip manually, in particular if you observe -poor performance while skipping. - -You do not have to read all parts either. You can stop -reading as soon as you find the data you need. - -// @todo Cover the building of multipart messages. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/req.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/req.asciidoc deleted file mode 100644 index 9d04ce05b6..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/req.asciidoc +++ /dev/null @@ -1,365 +0,0 @@ -[[req]] -== The Req object - -The Req object is a variable used for obtaining information -about a request, read its body or send a response. - -It is not really an object in the object-oriented sense. -It is a simple map that can be directly accessed or -used when calling functions from the `cowboy_req` module. - -The Req object is the subject of a few different chapters. -In this chapter we will learn about the Req object and -look at how to retrieve information about the request. - -=== Direct access - -The Req map contains a number of fields which are documented -and can be accessed directly. They are the fields that have -a direct mapping to HTTP: the request `method`; the HTTP -`version` used; the effective URI components `scheme`, -`host`, `port`, `path` and `qs`; the request `headers`; -the connection `peer` address and port; and the TLS -certificate `cert` when applicable. - -Note that the `version` field can be used to determine -whether a connection is using HTTP/2. - -To access a field, you can simply match in the function -head. The following example sends a simple "Hello world!" -response when the `method` is GET, and a 405 error -otherwise. - -[source,erlang] ----- -init(Req0=#{method := <<"GET">>}, State) -> - Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> - }, <<"Hello world!">>, Req0), - {ok, Req, State}; -init(Req0, State) -> - Req = cowboy_req:reply(405, #{ - <<"allow">> => <<"GET">> - }, Req0), - {ok, Req, State}. ----- - -Any other field is internal and should not be accessed. -They may change in future releases, including maintenance -releases, without notice. - -Modifying the Req object, while allowed, is not recommended -unless strictly necessary. If adding new fields, make sure -to namespace the field names so that no conflict can occur -with future Cowboy updates or third party projects. - -=== Introduction to the cowboy_req interface - -// @todo Link to cowboy_req manual - -Functions in the `cowboy_req` module provide access to -the request information but also various operations that -are common when dealing with HTTP requests. - -All the functions that begin with a verb indicate an action. -Other functions simply return the corresponding value -(sometimes that value does need to be built, but the -cost of the operation is equivalent to retrieving a value). - -Some of the `cowboy_req` functions return an updated Req -object. They are the read, reply, set and delete functions. -While ignoring the returned Req will not cause incorrect -behavior for some of them, it is highly recommended to -always keep and use the last returned Req object. The -manual for `cowboy_req` details these functions and what -modifications are done to the Req object. - -Some of the calls to `cowboy_req` have side effects. This -is the case of the read and reply functions. Cowboy reads -the request body or replies immediately when the function -is called. - -All functions will crash if something goes wrong. There -is usually no need to catch these errors, Cowboy will -send the appropriate 4xx or 5xx response depending on -where the crash occurred. - -=== Request method - -The request method can be retrieved directly: - -[source, erlang] -#{method := Method} = Req. - -Or using a function: - -[source,erlang] -Method = cowboy_req:method(Req). - -The method is a case sensitive binary string. Standard -methods include GET, HEAD, OPTIONS, PATCH, POST, PUT -or DELETE. - -=== HTTP version - -The HTTP version is informational. It does not indicate that -the client implements the protocol well or fully. - -There is typically no need to change behavior based on the -HTTP version: Cowboy already does it for you. - -It can be useful in some cases, though. For example, one may -want to redirect HTTP/1.1 clients to use Websocket, while HTTP/2 -clients keep using HTTP/2. - -The HTTP version can be retrieved directly: - -[source,erlang] -#{version := Version} = Req. - -Or using a function: - -[source,erlang] -Version = cowboy_req:version(Req). - -Cowboy defines the `'HTTP/1.0'`, `'HTTP/1.1'` and `'HTTP/2'` -versions. Custom protocols can define their own values as -atoms. - -=== Effective request URI - -The scheme, host, port, path and query string components -of the effective request URI can all be retrieved directly: - -[source,erlang] ----- -#{ - scheme := Scheme, - host := Host, - port := Port, - path := Path, - qs := Qs -} = Req. ----- - -Or using the related functions: - -[source,erlang] -Scheme = cowboy_req:scheme(Req), -Host = cowboy_req:host(Req), -Port = cowboy_req:port(Req), -Path = cowboy_req:path(Req). -Qs = cowboy_req:qs(Req). - -The scheme and host are lowercased case insensitive binary -strings. The port is an integer representing the port number. -The path and query string are case sensitive binary strings. - -Cowboy defines only the `<<"http">>` and `<<"https">>` schemes. -They are chosen so that the scheme will only be `<<"https">>` -for requests on secure HTTP/1.1 or HTTP/2 connections. -// @todo Is that tested well? - -The effective request URI itself can be reconstructed with -the `cowboy_req:uri/1,2` function. By default, an absolute -URI is returned: - -[source,erlang] -%% scheme://host[:port]/path[?qs] -URI = cowboy_req:uri(Req). - -Options are available to either disable or replace some -or all of the components. Various URIs or URI formats can -be generated this way, including the origin form: - -[source,erlang] -%% /path[?qs] -URI = cowboy_req:uri(Req, #{host => undefined}). - -The protocol relative form: - -[source,erlang] -%% //host[:port]/path[?qs] -URI = cowboy_req:uri(Req, #{scheme => undefined}). - -The absolute URI without a query string: - -[source,erlang] -URI = cowboy_req:uri(Req, #{qs => undefined}). - -A different host: - -[source,erlang] -URI = cowboy_req:uri(Req, #{host => <<"example.org">>}). - -And any other combination. - -=== Bindings - -Bindings are the host and path components that you chose -to extract when defining the routes of your application. -They are only available after the routing. - -Cowboy provides functions to retrieve one or all bindings. - -To retrieve a single value: - -[source,erlang] -Value = cowboy_req:binding(userid, Req). - -When attempting to retrieve a value that was not bound, -`undefined` will be returned. A different default value -can be provided: - -[source,erlang] -Value = cowboy_req:binding(userid, Req, 42). - -To retrieve everything that was bound: - -[source,erlang] -Bindings = cowboy_req:bindings(Req). - -They are returned as a map, with keys being atoms. - -The Cowboy router also allows you to capture many host -or path segments at once using the `...` qualifier. - -To retrieve the segments captured from the host name: - -[source,erlang] -HostInfo = cowboy_req:host_info(Req). - -And the path segments: - -[source,erlang] -PathInfo = cowboy_req:path_info(Req). - -Cowboy will return `undefined` if `...` was not used -in the route. - -=== Query parameters - -Cowboy provides two functions to access query parameters. -You can use the first to get the entire list of parameters. - -[source,erlang] -QsVals = cowboy_req:parse_qs(Req), -{_, Lang} = lists:keyfind(<<"lang">>, 1, QsVals). - -Cowboy will only parse the query string, and not do any -transformation. This function may therefore return duplicates, -or parameter names without an associated value. The order of -the list returned is undefined. - -When a query string is `key=1&key=2`, the list returned will -contain two parameters of name `key`. - -The same is true when trying to use the PHP-style suffix `[]`. -When a query string is `key[]=1&key[]=2`, the list returned will -contain two parameters of name `key[]`. - -When a query string is simply `key`, Cowboy will return the -list `[{<<"key">>, true}]`, using `true` to indicate that the -parameter `key` was defined, but with no value. - -The second function Cowboy provides allows you to match out -only the parameters you are interested in, and at the same -time do any post processing you require using xref:constraints[constraints]. -This function returns a map. - -[source,erlang] -#{id := ID, lang := Lang} = cowboy_req:match_qs([id, lang], Req). - -Constraints can be applied automatically. The following -snippet will crash when the `id` parameter is not an integer, -or when the `lang` parameter is empty. At the same time, the -value for `id` will be converted to an integer term: - -[source,erlang] -QsMap = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req). - -A default value may also be provided. The default will be used -if the `lang` key is not found. It will not be used if -the key is found but has an empty value. - -[source,erlang] -#{lang := Lang} = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req). - -If no default is provided and the value is missing, the -query string is deemed invalid and the process will crash. - -When the query string is `key=1&key=2`, the value for `key` -will be the list `[1, 2]`. Parameter names do not need to -include the PHP-style suffix. Constraints may be used to -ensure that only one value was passed through. - -=== Headers - -Header values can be retrieved either as a binary string -or parsed into a more meaningful representation. - -The get the raw value: - -[source,erlang] -HeaderVal = cowboy_req:header(<<"content-type">>, Req). - -Cowboy expects all header names to be provided as lowercase -binary strings. This is true for both requests and responses, -regardless of the underlying protocol. - -When the header is missing from the request, `undefined` -will be returned. A different default can be provided: - -[source,erlang] -HeaderVal = cowboy_req:header(<<"content-type">>, Req, <<"text/plain">>). - -All headers can be retrieved at once, either directly: - -[source,erlang] -#{headers := AllHeaders} = Req. - -Or using a function: - -[source,erlang] -AllHeaders = cowboy_req:headers(Req). - -Cowboy provides equivalent functions to parse individual -headers. There is no function to parse all headers at once. - -To parse a specific header: - -[source,erlang] -ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req). - -An exception will be thrown if it doesn't know how to parse the -given header, or if the value is invalid. The list of known headers -and default values can be found in the manual. - -When the header is missing, `undefined` is returned. You can -change the default value. Note that it should be the parsed value -directly: - -[source,erlang] ----- -ParsedVal = cowboy_req:parse_header(<<"content-type">>, Req, - {<<"text">>, <<"plain">>, []}). ----- - -=== Peer - -The peer address and port number for the connection can be -retrieved either directly or using a function. - -To retrieve the peer directly: - -[source,erlang] -#{peer := {IP, Port}} = Req. - -And using a function: - -[source,erlang] -{IP, Port} = cowboy_req:peer(Req). - -Note that the peer corresponds to the remote end of the -connection to the server, which may or may not be the -client itself. It may also be a proxy or a gateway. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/req_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/req_body.asciidoc deleted file mode 100644 index 4906811ef9..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/req_body.asciidoc +++ /dev/null @@ -1,130 +0,0 @@ -[[req_body]] -== Reading the request body - -The request body can be read using the Req object. - -Cowboy will not attempt to read the body until requested. -You need to call the body reading functions in order to -retrieve it. - -Cowboy will not cache the body, it is therefore only -possible to read it once. - -You are not required to read it, however. If a body is -present and was not read, Cowboy will either cancel or -skip its download, depending on the protocol. - -Cowboy provides functions for reading the body raw, -and read and parse form urlencoded or xref:multipart[multipart bodies]. -The latter is covered in its own chapter. - -=== Request body presence - -Not all requests come with a body. You can check for -the presence of a request body with this function: - -[source,erlang] -cowboy_req:has_body(Req). - -It returns `true` if there is a body; `false` otherwise. - -In practice, this function is rarely used. When the -method is `POST`, `PUT` or `PATCH`, the request body -is often required by the application, which should -just attempt to read it directly. - -=== Request body length - -You can obtain the length of the body: - -[source,erlang] -Length = cowboy_req:body_length(Req). - -Note that the length may not be known in advance. In -that case `undefined` will be returned. This can happen -with HTTP/1.1's chunked transfer-encoding, or HTTP/2 -when no content-length was provided. - -Cowboy will update the body length in the Req object -once the body has been read completely. A length will -always be returned when attempting to call this function -after reading the body completely. - -=== Reading the body - -You can read the entire body with one function call: - -[source,erlang] -{ok, Data, Req} = cowboy_req:read_body(Req0). - -Cowboy returns an `ok` tuple when the body has been -read fully. - -By default, Cowboy will attempt to read up to 8MB -of data, for up to 15 seconds. The call will return -once Cowboy has read at least 8MB of data, or at -the end of the 15 seconds period. - -These values can be customized. For example, to read -only up to 1MB for up to 5 seconds: - -[source,erlang] ----- -{ok, Data, Req} = cowboy_req:read_body(Req0, - #{length => 1000000, period => 5000}). ----- - -You may also disable the length limit: - -[source,erlang] -{ok, Data, Req} = cowboy_req:read_body(Req0, #{length => infinity}). - -This makes the function wait 15 seconds and return with -whatever arrived during that period. This is not -recommended for public facing applications. - -These two options can effectively be used to control -the rate of transmission of the request body. - -=== Streaming the body - -When the body is too large, the first call will return -a `more` tuple instead of `ok`. You can call the -function again to read more of the body, reading -it one chunk at a time. - -[source,erlang] ----- -read_body_to_console(Req0) -> - case cowboy_req:read_body(Req0) of - {ok, Data, Req} -> - io:format("~s", [Data]), - Req; - {more, Data, Req} -> - io:format("~s", [Data]), - read_body_to_console(Req) - end. ----- - -The `length` and `period` options can also be used. -They need to be passed for every call. - -=== Reading a form urlencoded body - -Cowboy provides a convenient function for reading and -parsing bodies sent as application/x-www-form-urlencoded. - -[source,erlang] -{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0). - -This function returns a list of key/values, exactly like -the function `cowboy_req:parse_qs/1`. - -The defaults for this function are different. Cowboy will -read for up to 64KB and up to 5 seconds. They can be modified: - -[source,erlang] ----- -{ok, KeyValues, Req} = cowboy_req:read_urlencoded_body(Req0, - #{length => 4096, period => 3000}). ----- diff --git a/_build/emqx/lib/cowboy/doc/src/guide/resource_design.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/resource_design.asciidoc deleted file mode 100644 index 954d87d559..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/resource_design.asciidoc +++ /dev/null @@ -1,226 +0,0 @@ -[[resource_design]] -== Designing a resource handler - -This chapter aims to provide you with a list of questions -you must answer in order to write a good resource handler. -It is meant to be usable as a step by step guide. - -=== The service - -Can the service become unavailable, and when it does, can -we detect it? For example, database connectivity problems -may be detected early. We may also have planned outages -of all or parts of the system. Implement the -`service_available` callback. - -What HTTP methods does the service implement? Do we need -more than the standard OPTIONS, HEAD, GET, PUT, POST, -PATCH and DELETE? Are we not using one of those at all? -Implement the `known_methods` callback. - -=== Type of resource handler - -Am I writing a handler for a collection of resources, -or for a single resource? - -The semantics for each of these are quite different. -You should not mix collection and single resource in -the same handler. - -=== Collection handler - -Skip this section if you are not doing a collection. - -Is the collection hardcoded or dynamic? For example, -if you use the route `/users` for the collection of -users then the collection is hardcoded; if you use -`/forums/:category` for the collection of threads -then it isn't. When the collection is hardcoded you -can safely assume the resource always exists. - -What methods should I implement? - -OPTIONS is used to get some information about the -collection. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in. - -HEAD and GET are used to retrieve the collection. -If you allow GET, also allow HEAD as there's no extra -work required to make it work. - -POST is used to create a new resource inside the -collection. Creating a resource by using POST on -the collection is useful when resources may be -created before knowing their URI, usually because -parts of it are generated dynamically. A common -case is some kind of auto incremented integer -identifier. - -The next methods are more rarely allowed. - -PUT is used to create a new collection (when -the collection isn't hardcoded), or replace -the entire collection. - -DELETE is used to delete the entire collection. - -PATCH is used to modify the collection using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for such things as reordering; adding, -modifying or deleting parts of the collection. - -=== Single resource handler - -Skip this section if you are doing a collection. - -What methods should I implement? - -OPTIONS is used to get some information about the -resource. It is recommended to allow it even if you -do not implement it, as Cowboy has a default -implementation built-in. - -HEAD and GET are used to retrieve the resource. -If you allow GET, also allow HEAD as there's no extra -work required to make it work. - -POST is used to update the resource. - -PUT is used to create a new resource (when it doesn't -already exist) or replace the resource. - -DELETE is used to delete the resource. - -PATCH is used to modify the resource using -instructions given in the request body. A PATCH -operation is atomic. The PATCH operation may -be used for adding, removing or modifying specific -values in the resource. - -=== The resource - -Following the above discussion, implement the -`allowed_methods` callback. - -Does the resource always exist? If it may not, implement -the `resource_exists` callback. - -Do I need to authenticate the client before they can -access the resource? What authentication mechanisms -should I provide? This may include form-based, token-based -(in the URL or a cookie), HTTP basic, HTTP digest, -SSL certificate or any other form of authentication. -Implement the `is_authorized` callback. - -Do I need fine-grained access control? How do I determine -that they are authorized access? Handle that in your -`is_authorized` callback. - -Can access to a resource be forbidden regardless of access -being authorized? A simple example of that is censorship -of a resource. Implement the `forbidden` callback. - -Can access be rate-limited for authenticated users? Use the -`rate_limited` callback. - -Are there any constraints on the length of the resource URI? -For example, the URI may be used as a key in storage and may -have a limit in length. Implement `uri_too_long`. - -=== Representations - -What media types do I provide? If text based, what charsets -are provided? What languages do I provide? - -Implement the mandatory `content_types_provided`. Prefix -the callbacks with `to_` for clarity. For example, `to_html` -or `to_text`. For resources that don't implement methods -GET or HEAD, you must still accept at least one media type, -but you can leave the callback as `undefined` since it will -never be called. - -Implement the `languages_provided` or `charsets_provided` -callbacks if applicable. - -Is there any other header that may make the representation -of the resource vary? Implement the `variances` callback. - -Depending on your choices for caching content, you may -want to implement one or more of the `generate_etag`, -`last_modified` and `expires` callbacks. - -Do I want the user or user agent to actively choose a -representation available? Send a list of available -representations in the response body and implement -the `multiple_choices` callback. - -=== Redirections - -Do I need to keep track of what resources were deleted? -For example, you may have a mechanism where moving a -resource leaves a redirect link to its new location. -Implement the `previously_existed` callback. - -Was the resource moved, and is the move temporary? If -it is explicitly temporary, for example due to maintenance, -implement the `moved_temporarily` callback. Otherwise, -implement the `moved_permanently` callback. - -=== The request - -Do you need to read the query string? Individual headers? -Implement `malformed_request` and do all the parsing and -validation in this function. Note that the body should not -be read at this point. - -May there be a request body? Will I know its size? -What's the maximum size of the request body I'm willing -to accept? Implement `valid_entity_length`. - -Finally, take a look at the sections corresponding to the -methods you are implementing. - -=== OPTIONS method - -Cowboy by default will send back a list of allowed methods. -Do I need to add more information to the response? Implement -the `options` method. - -=== GET and HEAD methods - -If you implement the methods GET and/or HEAD, you must -implement one `ProvideResource` callback for each -content-type returned by the `content_types_provided` -callback. - -=== PUT, POST and PATCH methods - -If you implement the methods PUT, POST and/or PATCH, -you must implement the `content_types_accepted` callback, -and one `AcceptCallback` callback for each content-type -it returns. Prefix the `AcceptCallback` callback names -with `from_` for clarity. For example, `from_html` or -`from_json`. - -Do we want to allow the POST method to create individual -resources directly through their URI (like PUT)? Implement -the `allow_missing_post` callback. It is recommended to -explicitly use PUT in these cases instead. - -May there be conflicts when using PUT to create or replace -a resource? Do we want to make sure that two updates around -the same time are not cancelling one another? Implement the -`is_conflict` callback. - -=== DELETE methods - -If you implement the method DELETE, you must implement -the `delete_resource` callback. - -When `delete_resource` returns, is the resource completely -removed from the server, including from any caching service? -If not, and/or if the deletion is asynchronous and we have -no way of knowing it has been completed yet, implement the -`delete_completed` callback. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/resp.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/resp.asciidoc deleted file mode 100644 index 1664aefc80..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/resp.asciidoc +++ /dev/null @@ -1,368 +0,0 @@ -[[resp]] -== Sending a response - -The response must be sent using the Req object. - -Cowboy provides two different ways of sending responses: -either directly or by streaming the body. Response headers -and body may be set in advance. The response is sent as -soon as one of the reply or stream reply function is -called. - -Cowboy also provides a simplified interface for sending -files. It can also send only specific parts of a file. - -While only one response is allowed for every request, -HTTP/2 introduced a mechanism that allows the server -to push additional resources related to the response. -This chapter also describes how this feature works in -Cowboy. - -=== Reply - -Cowboy provides three functions for sending the entire reply, -depending on whether you need to set headers and body. In all -cases, Cowboy will add any headers required by the protocol -(for example the date header will always be sent). - -When you need to set only the status code, -use `cowboy_req:reply/2`: - -[source,erlang] -Req = cowboy_req:reply(200, Req0). - -When you need to set response headers at the same time, -use `cowboy_req:reply/3`: - -[source,erlang] ----- -Req = cowboy_req:reply(303, #{ - <<"location">> => <<"https://ninenines.eu">> -}, Req0). ----- - -Note that the header name must always be a lowercase -binary. - -When you also need to set the response body, -use `cowboy_req:reply/4`: - -[source,erlang] ----- -Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0). ----- - -You should always set the content-type header when the -response has a body. There is however no need to set -the content-length header; Cowboy does it automatically. - -The response body and the header values must be either -a binary or an iolist. An iolist is a list containing -binaries, characters, strings or other iolists. This -allows you to build a response from different parts -without having to do any concatenation: - -[source,erlang] ----- -Title = "Hello world!", -Body = <<"Hats off!">>, -Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/html">> -}, ["", Title, "", - "

", Body, "

"], Req0). ----- - -This method of building responses is more efficient than -concatenating. Behind the scenes, each element of the list -is simply a pointer, and those pointers are used directly -when writing to the socket. - -=== Stream reply - -Cowboy provides two functions for initiating a response, -and an additional function for streaming the response body. -Cowboy will add any required headers to the response. - -// @todo For HTTP/1.1 Cowboy should probably not use chunked transfer-encoding if the content-length is set. - -When you need to set only the status code, -use `cowboy_req:stream_reply/2`: - -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, Req0), - -cowboy_req:stream_body("Hello...", nofin, Req), -cowboy_req:stream_body("chunked...", nofin, Req), -cowboy_req:stream_body("world!!", fin, Req). ----- - -The second argument to `cowboy_req:stream_body/3` indicates -whether this data terminates the body. Use `fin` for the -final flag, and `nofin` otherwise. - -This snippet does not set a content-type header. This is -not recommended. All responses with a body should have -a content-type. The header can be set beforehand, or -using the `cowboy_req:stream_reply/3`: - -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/html">> -}, Req0), - -cowboy_req:stream_body("Hello world!", nofin, Req), -cowboy_req:stream_body("

Hats off!

", fin, Req). ----- - -HTTP provides a few different ways to stream response bodies. -Cowboy will select the most appropriate one based on the HTTP -version and the request and response headers. - -While not required by any means, it is recommended that you -set the content-length header in the response if you know it -in advance. This will ensure that the best response method -is selected and help clients understand when the response -is fully received. - -Cowboy also provides a function to send response trailers. -Response trailers are semantically equivalent to the headers -you send in the response, only they are sent at the end. -This is especially useful to attach information to the -response that could not be generated until the response -body was fully generated. - -Trailer fields must be listed in the trailer header. Any -field not listed might be dropped by the client or an intermediary. - -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/html">>, - <<"trailer">> => <<"expires, content-md5">> -}, Req0), - -cowboy_req:stream_body("Hello world!", nofin, Req), -cowboy_req:stream_body("

Hats off!

", nofin, Req), - -cowboy_req:stream_trailers(#{ - <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>, - <<"content-md5">> => <<"c6081d20ff41a42ce17048ed1c0345e2">> -}, Req). ----- - -The stream ends with trailers. It is no longer possible to -send data after sending trailers. You cannot send trailers -after setting the `fin` flag when streaming the body. - -=== Preset response headers - -Cowboy provides functions to set response headers without -immediately sending them. They are stored in the Req object -and sent as part of the response when a reply function is -called. - -To set response headers: - -[source,erlang] -Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0). - -Header names must be a lowercase binary. - -Do not use this function for setting cookies. Refer to -the xref:cookies[Cookies] chapter for more information. - -To check if a response header has already been set: - -[source,erlang] -cowboy_req:has_resp_header(<<"allow">>, Req). - -It returns `true` if the header was set, `false` otherwise. - -To delete a response header that was set previously: - -[source,erlang] -Req = cowboy_req:delete_resp_header(<<"allow">>, Req0). - -=== Overriding headers - -As Cowboy provides different ways of setting response -headers and body, clashes may occur, so it's important -to understand what happens when a header is set twice. - -Headers come from five different origins: - -* Protocol-specific headers (for example HTTP/1.1's connection header) -* Other required headers (for example the date header) -* Preset headers -* Headers given to the reply function -* Set-cookie headers - -Cowboy does not allow overriding protocol-specific headers. - -Set-cookie headers will always be appended at the end of -the list of headers before sending the response. - -Headers given to the reply function will always override -preset headers and required headers. If a header is found -in two or three of these, then the one in the reply function -is picked and the others are dropped. - -Similarly, preset headers will always override required -headers. - -To illustrate, look at the following snippet. Cowboy by -default sends the server header with the value "Cowboy". -We can override it: - -[source,erlang] ----- -Req = cowboy_req:reply(200, #{ - <<"server">> => <<"yaws">> -}, Req0). ----- - -=== Preset response body - -Cowboy provides functions to set the response body without -immediately sending it. It is stored in the Req object and -sent when the reply function is called. - -To set the response body: - -[source,erlang] -Req = cowboy_req:set_resp_body("Hello world!", Req0). - -// @todo Yeah we probably should add that function that -// also sets the content-type at the same time... - -To check if a response body has already been set: - -[source,erlang] -cowboy_req:has_resp_body(Req). - -It returns `true` if the body was set and is non-empty, -`false` otherwise. - -// @todo We probably should also have a function that -// properly removes the response body, including any -// content-* headers. - -The preset response body is only sent if the reply function -used is `cowboy_req:reply/2` or `cowboy_req:reply/3`. - -=== Sending files - -Cowboy provides a shortcut for sending files. When -using `cowboy_req:reply/4`, or when presetting the -response header, you can give a `sendfile` tuple to -Cowboy: - -[source,erlang] -{sendfile, Offset, Length, Filename} - -Depending on the values for `Offset` or `Length`, the -entire file may be sent, or just a part of it. - -The length is required even for sending the entire file. -Cowboy sends it in the content-length header. - -To send a file while replying: - -[source,erlang] ----- -Req = cowboy_req:reply(200, #{ - <<"content-type">> => "image/png" -}, {sendfile, 0, 12345, "path/to/logo.png"}, Req0). ----- - -// @todo An example of presetting a file would be useful, -// but let's wait for the function that can set the -// content-type at the same time. - -// @todo What about streaming many files? For example -// it should be possible to build a tar file on the fly -// while still using sendfile. Another example could be -// proper support for multipart byte ranges. Yet another -// example would be automatic concatenation of CSS or JS -// files. - -=== Informational responses - -Cowboy allows you to send informational responses. - -Informational responses are responses that have a status -code between 100 and 199. Any number can be sent before -the proper response. Sending an informational response -does not change the behavior of the proper response, and -clients are expected to ignore any informational response -they do not understand. - -The following snippet sends a 103 informational response -with some headers that are expected to be in the final -response. - -[source,erlang] ----- -Req = cowboy_req:inform(103, #{ - <<"link">> => <<"; rel=preload; as=style, ; rel=preload; as=script">> -}, Req0). ----- - -=== Push - -The HTTP/2 protocol introduced the ability to push resources -related to the one sent in the response. Cowboy provides two -functions for that purpose: `cowboy_req:push/3,4`. - -Push is only available for HTTP/2. Cowboy will automatically -ignore push requests if the protocol doesn't support it. - -The push function must be called before any of the reply -functions. Doing otherwise will result in a crash. - -To push a resource, you need to provide the same information -as a client performing a request would. This includes the -HTTP method, the URI and any necessary request headers. - -Cowboy by default only requires you to give the path to -the resource and the request headers. The rest of the URI -is taken from the current request (excluding the query -string, set to empty) and the method is GET by default. - -The following snippet pushes a CSS file that is linked to -in the response: - -[source,erlang] ----- -cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req0), -Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/html">> -}, ["My web page", - "", - "

Welcome to Erlang!

"], Req0). ----- - -To override the method, scheme, host, port or query string, -simply pass in a fourth argument. The following snippet -uses a different host name: - -[source,erlang] ----- -cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, #{host => <<"cdn.example.org">>}, Req), ----- - -Pushed resources don't have to be files. As long as the push -request is cacheable, safe and does not include a body, the -resource can be pushed. - -Under the hood, Cowboy handles pushed requests the same as -normal requests: a different process is created which will -ultimately send a response to the client. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_cond.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_cond.png deleted file mode 100644 index 64cda34796..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_cond.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_cond.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_cond.svg deleted file mode 100644 index 542ae17d6a..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_cond.svg +++ /dev/null @@ -1,1656 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - has if-unmodified-since? - has if-none-match? - some text - ... - generate_etag - has if-modified-since? - has if-match? - generate_etag - last_modified - - true - match* - true - not modified* - true - no match* - - - - - false - false, orinvalid - modified* - false - - - - - - 412 precondition failed - - middlewares - - - - - - - - - - - - - - - - - no match* - - - - - - date is in the future? - - - - - - - - - - last_modified - - - - - - 304 not modified - - ... - false, orinvalid - match* - - method is GET/HEAD? - true - false - true - false - true - modified* - not modified* - - - - - - generate_etag - - - - - - expires - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_conneg.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_conneg.png deleted file mode 100644 index 65ecdcf37d..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_conneg.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_conneg.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_conneg.svg deleted file mode 100644 index 247567a091..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_conneg.svg +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - has accept-language? - has accept-charset? - some text - start - charsets_provided - variances - has accept? - content_types_provided - languages_provided - - true - provided* - true - provided* - true - provided* - - - - - false - false - not provided* - false - not provided* - - - - - - 406 not acceptable - - middlewares - - - - - - - - - - - - - - - - - not provided* - - ... - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_delete.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_delete.png deleted file mode 100644 index 56a861c07e..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_delete.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_delete.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_delete.svg deleted file mode 100644 index 2f5513cd24..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_delete.svg +++ /dev/null @@ -1,1718 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - delete_completed - has response body? - some text - conneg - multiple_choices - resource_exists - delete_resource - - true - false - - - - - false - - - - - - middlewares - - - - - true - true - - - - - - cond - - 300 multiple choices - - 200 OK - - - - - - has if-match? - false - - - - - - - - - - previously_existed - - 404 not found - false - - - - - - - - - - moved_permanently - - - - - - 412 precondition failed - true - true* - false - - 301 moved permanently - - - - - - - - - - moved_temporarily - true* - false - - 307 moved temporarily - - 410 gone - - - - - false - - 202 accepted - - 204 no content - true - true - - 500 internal server error - false - true - false - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_flowcharts.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/rest_flowcharts.asciidoc deleted file mode 100644 index 308a919e87..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_flowcharts.asciidoc +++ /dev/null @@ -1,249 +0,0 @@ -[[rest_flowcharts]] -== REST flowcharts - -This chapter will explain the REST handler state machine through -a number of different diagrams. - -There are four main paths that requests may follow. One for the -method OPTIONS; one for the methods GET and HEAD; one for the -methods PUT, POST and PATCH; and one for the method DELETE. - -All paths start with the "Start" diagram, and all paths excluding -the OPTIONS path go through the "Content negotiation" diagram -and optionally the "Conditional requests" diagram if the resource -exists. - -The red squares refer to another diagram. The light green squares -indicate a response. Other squares may be either a callback or a -question answered by Cowboy itself. Green arrows tend to indicate -the default behavior if the callback is undefined. The star next -to values indicate that the value is descriptive rather than exact. - -=== Start - -All requests start from here. - -image::rest_start.png[REST starting flowchart] - -A series of callbacks are called in succession to perform -a general checkup of the service, the request line and -request headers. - -The request body, if any, is not expected to have been -received for any of these steps. It is only processed -at the end of the "PUT, POST and PATCH methods" diagram, -when all conditions have been met. - -The `known_methods` and `allowed_methods` callbacks -return a list of methods. Cowboy then checks if the request -method is in the list, and stops otherwise. - -The `is_authorized` callback may be used to check that -access to the resource is authorized. Authentication -may also be performed as needed. When authorization is -denied, the return value from the callback must include -a challenge applicable to the requested resource, which -will be sent back to the client in the www-authenticate -header. - -This diagram is immediately followed by either the -"OPTIONS method" diagram when the request method is -OPTIONS, or the "Content negotiation" diagram otherwise. - -=== OPTIONS method - -This diagram only applies to OPTIONS requests. - -image::rest_options.png[REST OPTIONS method flowchart] - -The `options` callback may be used to add information -about the resource, such as media types or languages -provided; allowed methods; any extra information. A -response body may also be set, although clients should -not be expected to read it. - -If the `options` callback is not defined, Cowboy will -send a response containing the list of allowed methods -by default. - -=== Content negotiation - -This diagram applies to all request methods other than -OPTIONS. It is executed right after the "Start" diagram -is completed. - -image::rest_conneg.png[REST content negotiation flowchart] - -The purpose of these steps is to determine an appropriate -representation to be sent back to the client. - -The request may contain any of the accept header; the -accept-language header; or the accept-charset header. -When present, Cowboy will parse the headers and then -call the corresponding callback to obtain the list -of provided content-type, language or charset for this -resource. It then automatically select the best match -based on the request. - -If a callback is not defined, Cowboy will select the -content-type, language or charset that the client -prefers. - -The `content_types_provided` also returns the name of -a callback for every content-type it accepts. This -callback will only be called at the end of the -"GET and HEAD methods" diagram, when all conditions -have been met. - -The selected content-type, language and charset are -saved as meta values in the Req object. You *should* -use the appropriate representation if you set a -response body manually (alongside an error code, -for example). - -This diagram is immediately followed by -the "GET and HEAD methods" diagram, -the "PUT, POST and PATCH methods" diagram, -or the "DELETE method" diagram, depending on the -method. - -=== GET and HEAD methods - -This diagram only applies to GET and HEAD requests. - -For a description of the `cond` step, please see -the "Conditional requests" diagram. - -image::rest_get_head.png[REST GET/HEAD methods flowchart] - -When the resource exists, and the conditional steps -succeed, the resource can be retrieved. - -Cowboy prepares the response by first retrieving -metadata about the representation, then by calling -the `ProvideResource` callback. This is the callback -you defined for each content-types you returned from -`content_types_provided`. This callback returns the body -that will be sent back to the client, or a fun if the -body must be streamed. - -When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI. - -The `moved_permanently` and `moved_temporarily` callbacks -must return the new location of the resource if it was in -fact moved. - -=== PUT, POST and PATCH methods - -This diagram only applies to PUT, POST and PATCH requests. - -For a description of the `cond` step, please see -the "Conditional requests" diagram. - -image::rest_put_post_patch.png[REST PUT/POST/PATCH methods flowchart] - -When the resource exists, first the conditional steps -are executed. When that succeeds, and the method is PUT, -Cowboy will call the `is_conflict` callback. This function -can be used to prevent potential race conditions, by locking -the resource for example. - -Then all three methods reach the `content_types_accepted` -step that we will describe in a few paragraphs. - -When the resource does not exist, and the method is PUT, -Cowboy will check for conflicts and then move on to the -`content_types_accepted` step. For other methods, Cowboy -will figure out whether the resource existed previously, -and if so whether it was moved elsewhere. If the resource -is truly non-existent, the method is POST and the call -for `allow_missing_post` returns `true`, then Cowboy will -move on to the `content_types_accepted` step. Otherwise -the request processing ends there. - -The `moved_permanently` and `moved_temporarily` callbacks -must return the new location of the resource if it was in -fact moved. - -The `content_types_accepted` returns a list of -content-types it accepts, but also the name of a callback -for each of them. Cowboy will select the appropriate -callback for processing the request body and call it. - -This callback may return one of three different return -values. - -If an error occurred while processing the request body, -it must return `false` and Cowboy will send an -appropriate error response. - -If the method is POST, then you may return `true` with -an URI of where the resource has been created. This is -especially useful for writing handlers for collections. - -Otherwise, return `true` to indicate success. Cowboy -will select the appropriate response to be sent depending -on whether a resource has been created, rather than -modified, and on the availability of a location header -or a body in the response. - -=== DELETE method - -This diagram only applies to DELETE requests. - -For a description of the `cond` step, please see -the "Conditional requests" diagram. - -image::rest_delete.png[REST DELETE method flowchart] - -When the resource exists, and the conditional steps -succeed, the resource can be deleted. - -Deleting the resource is a two steps process. First -the callback `delete_resource` is executed. Use this -callback to delete the resource. - -Because the resource may be cached, you must also -delete all cached representations of this resource -in the system. This operation may take a while though, -so you may return before it finished. - -Cowboy will then call the `delete_completed` callback. -If you know that the resource has been completely -deleted from your system, including from caches, then -you can return `true`. If any doubts persist, return -`false`. Cowboy will assume `true` by default. - -To finish, Cowboy checks if you set a response body, -and depending on that, sends the appropriate response. - -When the resource does not exist, Cowboy will figure out -whether the resource existed previously, and if so whether -it was moved elsewhere in order to redirect the client to -the new URI. - -The `moved_permanently` and `moved_temporarily` callbacks -must return the new location of the resource if it was in -fact moved. - -=== Conditional requests - -This diagram applies to all request methods other than -OPTIONS. It is executed right after the `resource_exists` -callback, when the resource exists. - -image::rest_cond.png[REST conditional requests flowchart] - -A request becomes conditional when it includes either of -the if-match header; the if-unmodified-since header; the -if-none-match header; or the if-modified-since header. - -If the condition fails, the request ends immediately -without any retrieval or modification of the resource. - -The `generate_etag` and `last_modified` are called as -needed. Cowboy will only call them once and then cache -the results for subsequent use. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_get_head.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_get_head.png deleted file mode 100644 index 211ab60356..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_get_head.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_get_head.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_get_head.svg deleted file mode 100644 index 92030cf3c6..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_get_head.svg +++ /dev/null @@ -1,1523 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - last_modified - ProvideCallback - some text - conneg - multiple_choices - resource_exists - generate_etag - expires - - true - false - - - - - false - - - - - - middlewares - - - - - true - true - - - - - - cond - - 300 multiple choices - - 200 OK - - - - - - has if-match? - false - - - - - - - - - - previously_existed - - 404 not found - false - - - - - - - - - - moved_permanently - - - - - - 412 precondition failed - true - true* - false - - 301 moved permanently - - - - - - - - - - moved_temporarily - true* - false - - 307 moved temporarily - - 410 gone - - - - - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_handlers.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/rest_handlers.asciidoc deleted file mode 100644 index 31f68a1d6d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_handlers.asciidoc +++ /dev/null @@ -1,139 +0,0 @@ -[[rest_handlers]] -== REST handlers - -REST is implemented in Cowboy as a sub protocol. The request -is handled as a state machine with many optional callbacks -describing the resource and modifying the machine's behavior. - -The REST handler is the recommended way to handle HTTP requests. - -=== Initialization - -First, the `init/2` callback is called. This callback is common -to all handlers. To use REST for the current request, this function -must return a `cowboy_rest` tuple. - -[source,erlang] ----- -init(Req, State) -> - {cowboy_rest, Req, State}. ----- - -Cowboy will then switch to the REST protocol and start executing -the state machine. - -After reaching the end of the flowchart, the `terminate/3` callback -will be called if it is defined. - -=== Methods - -The REST component has code for handling the following HTTP methods: -HEAD, GET, POST, PATCH, PUT, DELETE and OPTIONS. - -Other methods can be accepted, however they have no specific callback -defined for them at this time. - -=== Callbacks - -All callbacks are optional. Some may become mandatory depending -on what other defined callbacks return. The various flowcharts -in the next chapter should be a useful to determine which callbacks -you need. - -All callbacks take two arguments, the Req object and the State, -and return a three-element tuple of the form `{Value, Req, State}`. - -Nearly all callbacks can also return `{stop, Req, State}` to -stop execution of the request, and -`{{switch_handler, Module}, Req, State}` or -`{{switch_handler, Module, Opts}, Req, State}` to switch to -a different handler type. The exceptions are `expires` -`generate_etag`, `last_modified` and `variances`. - -The following table summarizes the callbacks and their default values. -If the callback isn't defined, then the default value will be used. -Please look at the flowcharts to find out the result of each return -value. - -In the following table, "skip" means the callback is entirely skipped -if it is undefined, moving directly to the next step. Similarly, -"none" means there is no default value for this callback. - -[cols="<,^",options="header"] -|=== -| Callback name | Default value -| allowed_methods | `[<<"GET">>, <<"HEAD">>, <<"OPTIONS">>]` -| allow_missing_post | `true` -| charsets_provided | skip -| content_types_accepted | none -// @todo Space required for the time being: https://hub.fastgit.org/spf13/hugo/issues/2398 -| content_types_provided | `[{{ <<"text">>, <<"html">>, '*'}, to_html}]` -| delete_completed | `true` -| delete_resource | `false` -| expires | `undefined` -| forbidden | `false` -| generate_etag | `undefined` -| is_authorized | `true` -| is_conflict | `false` -| known_methods | `[<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>]` -| languages_provided | skip -| last_modified | `undefined` -| malformed_request | `false` -| moved_permanently | `false` -| moved_temporarily | `false` -| multiple_choices | `false` -| options | `ok` -| previously_existed | `false` -| rate_limited | `false` -| resource_exists | `true` -| service_available | `true` -| uri_too_long | `false` -| valid_content_headers | `true` -| valid_entity_length | `true` -| variances | `[]` -|=== - -As you can see, Cowboy tries to move on with the request whenever -possible by using well thought out default values. - -In addition to these, there can be any number of user-defined -callbacks that are specified through `content_types_accepted/2` -and `content_types_provided/2`. They can take any name, however -it is recommended to use a separate prefix for the callbacks of -each function. For example, `from_html` and `to_html` indicate -in the first case that we're accepting a resource given as HTML, -and in the second case that we send one as HTML. - -=== Meta data - -Cowboy will set informative values to the Req object at various -points of the execution. You can retrieve them by matching the -Req object directly. The values are defined in the following table: - -[cols="<,<",options="header"] -|=== -| Key | Details -| media_type | The content-type negotiated for the response entity. -| language | The language negotiated for the response entity. -| charset | The charset negotiated for the response entity. -|=== - -They can be used to send a proper body with the response to a -request that used a method other than HEAD or GET. - -=== Response headers - -Cowboy will set response headers automatically over the execution -of the REST code. They are listed in the following table. - -[cols="<,<",options="header"] -|=== -| Header name | Details -| content-language | Language used in the response body -| content-type | Media type and charset of the response body -| etag | Etag of the resource -| expires | Expiration date of the resource -| last-modified | Last modification date for the resource -| location | Relative or absolute URI to the requested resource -| vary | List of headers that may change the representation of the resource -|=== diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_options.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_options.png deleted file mode 100644 index 90fd6f0695..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_options.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_options.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_options.svg deleted file mode 100644 index 496c050c02..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_options.svg +++ /dev/null @@ -1,387 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - some text - start - options - 200 OK - - - - - - - middlewares - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_principles.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/rest_principles.asciidoc deleted file mode 100644 index 66939cb716..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_principles.asciidoc +++ /dev/null @@ -1,160 +0,0 @@ -[[rest_principles]] -== REST principles - -This chapter will attempt to define the concepts behind REST -and explain what makes a service RESTful. - -REST is often confused with performing a distinct operation -depending on the HTTP method, while using more than the GET -and POST methods. That's highly misguided at best. - -We will first attempt to define REST and will look at what -it means in the context of HTTP and the Web. -For a more in-depth explanation of REST, you can read -http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm[Roy T. Fielding's dissertation] -as it does a great job explaining where it comes from and -what it achieves. - -=== REST architecture - -REST is a *client-server* architecture. The client and the server -both have a different set of concerns. The server stores and/or -manipulates information and makes it available to the user in -an efficient manner. The client takes that information and -displays it to the user and/or uses it to perform subsequent -requests for information. This separation of concerns allows both -the client and the server to evolve independently as it only -requires that the interface stays the same. - -REST is *stateless*. That means the communication between the -client and the server always contains all the information needed -to perform the request. There is no session state in the server, -it is kept entirely on the client's side. If access to a resource -requires authentication, then the client needs to authenticate -itself with every request. - -REST is *cacheable*. The client, the server and any intermediary -components can all cache resources in order to improve performance. - -REST provides a *uniform interface* between components. This -simplifies the architecture, as all components follow the same -rules to speak to one another. It also makes it easier to understand -the interactions between the different components of the system. -A number of constraints are required to achieve this. They are -covered in the rest of the chapter. - -REST is a *layered system*. Individual components cannot see -beyond the immediate layer with which they are interacting. This -means that a client connecting to an intermediate component, like -a proxy, has no knowledge of what lies beyond. This allows -components to be independent and thus easily replaceable or -extendable. - -REST optionally provides *code on demand*. Code may be downloaded -to extend client functionality. This is optional however because -the client may not be able to download or run this code, and so -a REST component cannot rely on it being executed. - -=== Resources and resource identifiers - -A resource is an abstract concept. In a REST system, any information -that can be named may be a resource. This includes documents, images, -a collection of resources and any other information. Any information -that can be the target of an hypertext link can be a resource. - -A resource is a conceptual mapping to a set of entities. The set of -entities evolves over time; a resource doesn't. For example, a resource -can map to "users who have logged in this past month" and another -to "all users". At some point in time they may map to the same set of -entities, because all users logged in this past month. But they are -still different resources. Similarly, if nobody logged in recently, -then the first resource may map to the empty set. This resource exists -regardless of the information it maps to. - -Resources are identified by uniform resource identifiers, also known -as URIs. Sometimes internationalized resource identifiers, or IRIs, -may also be used, but these can be directly translated into a URI. - -In practice we will identify two kinds of resources. Individual -resources map to a set of one element, for example "user Joe". -Collection of resources map to a set of 0 to N elements, -for example "all users". - -=== Resource representations - -The representation of a resource is a sequence of bytes associated -with metadata. - -The metadata comes as a list of key-value pairs, where the name -corresponds to a standard that defines the value's structure and -semantics. With HTTP, the metadata comes in the form of request -or response headers. The headers' structure and semantics are well -defined in the HTTP standard. Metadata includes representation -metadata, resource metadata and control data. - -The representation metadata gives information about the -representation, such as its media type, the date of last -modification, or even a checksum. - -Resource metadata could be link to related resources or -information about additional representations of the resource. - -Control data allows parameterizing the request or response. -For example, we may only want the representation returned if -it is more recent than the one we have in cache. Similarly, -we may want to instruct the client about how it should cache -the representation. This isn't restricted to caching. We may, -for example, want to store a new representation of a resource -only if it wasn't modified since we first retrieved it. - -The data format of a representation is also known as the media -type. Some media types are intended for direct rendering to the -user, while others are intended for automated processing. The -media type is a key component of the REST architecture. - -=== Self-descriptive messages - -Messages must be self-descriptive. That means that the data -format of a representation must always come with its media -type (and similarly requesting a resource involves choosing -the media type of the representation returned). If you are -sending HTML, then you must say it is HTML by sending the -media type with the representation. In HTTP this is done -using the content-type header. - -The media type is often an IANA registered media type, like -`text/html` or `image/png`, but does not need to be. Exactly -two things are important for respecting this constraint: that -the media type is well specified, and that the sender and -recipient agree about what the media type refers to. - -This means that you can create your own media types, like -`application/x-mine`, and that as long as you write the -specifications for it and that both endpoints agree about -it then the constraint is respected. - -=== Hypermedia as the engine of application state - -The last constraint is generally where services that claim -to be RESTful fail. Interactions with a server must be -entirely driven by hypermedia. The client does not need -any prior knowledge of the service in order to use it, -other than an entry point and of course basic understanding -of the media type of the representations, at the very least -enough to find and identify hyperlinks and link relations. - -To give a simple example, if your service only works with -the `application/json` media type then this constraint -cannot be respected (as there are no concept of links in -JSON) and thus your service isn't RESTful. This is the case -for the majority of self-proclaimed REST services. - -On the other hand if you create a JSON based media type -that has a concept of links and link relations, then -your service might be RESTful. - -Respecting this constraint means that the entirety of the -service becomes self-discoverable, not only the resources -in it, but also the operations you can perform on it. This -makes clients very thin as there is no need to implement -anything specific to the service to operate on it. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_put_post_patch.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_put_post_patch.png deleted file mode 100644 index d287036c0d..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_put_post_patch.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_put_post_patch.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_put_post_patch.svg deleted file mode 100644 index 4562722acc..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_put_post_patch.svg +++ /dev/null @@ -1,3143 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - some text - conneg - resource_exists - - true - - - - - false - - - - - - middlewares - - - - - true - - - - - - - - - - - cond - - - - - - has if-match? - false - - - - - - method is POST/PATCH? - true - - - - - - - - - - - method is POST? - - 412 precondition failed - - - - - - - - - - - - - - previously_existed - false - - - - - - - - - true* - false - - 301 moved permanently - - - - - - - - - - moved_temporarily - true* - false - - 307 moved temporarily - - 400 bad request - - - - - allow_missing_post - - - - - - method is PUT - - - - - - is_conflict - true - - 409 conflict - - - - - - content_types_accepted - - AcceptCallback - - - - - - - - - - new resource? - - - - - - - - - - new resource? - - 201 created - - 303 see other - - - - - - method is PUT? - - - - - - - - - - - has resp body? - - - - - - - - - - multiple_choices - false - - 300 multiple choices - - 200 OK - 204 no content - true - - - - - true - - moved_permanently - - 410 gone - false - false - - - - - true - - - - - true, URI* - - - - - true - false - true - true - false - true - false - true - false - false - - true - - - - - false - - - - - - - - - - 404 not found - - - - - - allow_missing_post - - method is POST? - false - true - false - true - - has resp location? - false - true - - 415 unsupported media type - not accepted* - - moved_permanently - - 301 moved permanently - true* - false - - - - - false - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_start.png b/_build/emqx/lib/cowboy/doc/src/guide/rest_start.png deleted file mode 100644 index 4c230a020d..0000000000 Binary files a/_build/emqx/lib/cowboy/doc/src/guide/rest_start.png and /dev/null differ diff --git a/_build/emqx/lib/cowboy/doc/src/guide/rest_start.svg b/_build/emqx/lib/cowboy/doc/src/guide/rest_start.svg deleted file mode 100644 index 6f1dd8715a..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/rest_start.svg +++ /dev/null @@ -1,1656 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - some text - some text - uri_too_long - malformed_request - some text - init - is_authorized - forbidden - valid_content_headers - valid_entity_length - ... - service_available - known_methods - allowed_methods - - true - known* - false - allowed* - false - true - false - true - true - - - - - false - unknown* - true - unallowed* - true - false* - true - false - false - - 503 service unavailable - - - - - - - - - 501 not implemented - 414 request URI too long - 405 method not allowed - 400 bad request - 401 unauthorized - 403 forbidden - 501 not implemented - 413 request entity too large - - middlewares - - - - - - - - - - - rate_limited - ... - true - false - true* - - 429 too many requests - - diff --git a/_build/emqx/lib/cowboy/doc/src/guide/routing.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/routing.asciidoc deleted file mode 100644 index 9e2ef25b9d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/routing.asciidoc +++ /dev/null @@ -1,254 +0,0 @@ -[[routing]] -== Routing - -Cowboy does nothing by default. - -To make Cowboy useful, you need to map URIs to Erlang modules that will -handle the requests. This is called routing. - -When Cowboy receives a request, it tries to match the requested host and -path to the configured routes. When there's a match, the route's -associated handler is executed. - -Routes need to be compiled before they can be used by Cowboy. -The result of the compilation is the dispatch rules. - -=== Syntax - -The general structure for the routes is defined as follow. - -[source,erlang] -Routes = [Host1, Host2, ... HostN]. - -Each host contains matching rules for the host along with optional -constraints, and a list of routes for the path component. - -[source,erlang] -Host1 = {HostMatch, PathsList}. -Host2 = {HostMatch, Constraints, PathsList}. - -The list of routes for the path component is defined similar to the -list of hosts. - -[source,erlang] -PathsList = [Path1, Path2, ... PathN]. - -Finally, each path contains matching rules for the path along with -optional constraints, and gives us the handler module to be used -along with its initial state. - -[source,erlang] -Path1 = {PathMatch, Handler, InitialState}. -Path2 = {PathMatch, Constraints, Handler, InitialState}. - -Continue reading to learn more about the match syntax and the optional -constraints. - -=== Match syntax - -The match syntax is used to associate host names and paths with their -respective handlers. - -The match syntax is the same for host and path with a few subtleties. -Indeed, the segments separator is different, and the host is matched -starting from the last segment going to the first. All examples will -feature both host and path match rules and explain the differences -when encountered. - -Excluding special values that we will explain at the end of this section, -the simplest match value is a host or a path. It can be given as either -a `string()` or a `binary()`. - -[source,erlang] ----- -PathMatch1 = "/". -PathMatch2 = "/path/to/resource". - -HostMatch1 = "cowboy.example.org". ----- - -As you can see, all paths defined this way must start with a slash -character. Note that these two paths are identical as far as routing -is concerned. - -[source,erlang] -PathMatch2 = "/path/to/resource". -PathMatch3 = "/path/to/resource/". - -Hosts with and without a trailing dot are equivalent for routing. -Similarly, hosts with and without a leading dot are also equivalent. - -[source,erlang] -HostMatch1 = "cowboy.example.org". -HostMatch2 = "cowboy.example.org.". -HostMatch3 = ".cowboy.example.org". - -It is possible to extract segments of the host and path and to store -the values in the `Req` object for later use. We call these kind of -values bindings. - -The syntax for bindings is very simple. A segment that begins with -the `:` character means that what follows until the end of the segment -is the name of the binding in which the segment value will be stored. - -[source,erlang] -PathMatch = "/hats/:name/prices". -HostMatch = ":subdomain.example.org". - -If these two end up matching when routing, you will end up with two -bindings defined, `subdomain` and `name`, each containing the -segment value where they were defined. For example, the URL -`http://test.example.org/hats/wild_cowboy_legendary/prices` will -result in having the value `test` bound to the name `subdomain` -and the value `wild_cowboy_legendary` bound to the name `name`. -They can later be retrieved using `cowboy_req:binding/{2,3}`. The -binding name must be given as an atom. - -There is a special binding name you can use to mimic the underscore -variable in Erlang. Any match against the `_` binding will succeed -but the data will be discarded. This is especially useful for -matching against many domain names in one go. - -[source,erlang] -HostMatch = "ninenines.:_". - -Similarly, it is possible to have optional segments. Anything -between brackets is optional. - -[source,erlang] -PathMatch = "/hats/[page/:number]". -HostMatch = "[www.]ninenines.eu". - -You can also have imbricated optional segments. - -[source,erlang] -PathMatch = "/hats/[page/[:number]]". - -While Cowboy does not reject multiple brackets in a route, -the behavior may be undefined if the route is under-specified. -For example, this route requires constraints to determine what -is a chapter and what is a page, since they are both optional: - -[source,erlang] -PathMatch = "/book/[:chapter]/[:page]". - -You can retrieve the rest of the host or path using `[...]`. -In the case of hosts it will match anything before, in the case -of paths anything after the previously matched segments. It is -a special case of optional segments, in that it can have -zero, one or many segments. You can then find the segments using -`cowboy_req:host_info/1` and `cowboy_req:path_info/1` respectively. -They will be represented as a list of segments. - -[source,erlang] -PathMatch = "/hats/[...]". -HostMatch = "[...]ninenines.eu". - -If a binding appears twice in the routing rules, then the match -will succeed only if they share the same value. This copies the -Erlang pattern matching behavior. - -[source,erlang] -PathMatch = "/hats/:name/:name". - -This is also true when an optional segment is present. In this -case the two values must be identical only if the segment is -available. - -[source,erlang] -PathMatch = "/hats/:name/[:name]". - -If a binding is defined in both the host and path, then they must -also share the same value. - -[source,erlang] -PathMatch = "/:user/[...]". -HostMatch = ":user.github.com". - -Finally, there are two special match values that can be used. The -first is the atom `'_'` which will match any host or path. - -[source,erlang] -PathMatch = '_'. -HostMatch = '_'. - -The second is the special host match `"*"` which will match the -wildcard path, generally used alongside the `OPTIONS` method. - -[source,erlang] -HostMatch = "*". - -=== Constraints - -After the matching has completed, the resulting bindings can be tested -against a set of constraints. Constraints are only tested when the -binding is defined. They run in the order you defined them. The match -will succeed only if they all succeed. If the match fails, then Cowboy -tries the next route in the list. - -The format used for constraints is the same as match functions in -`cowboy_req`: they are provided as a list of fields which may have -one or more constraints. While the router accepts the same format, -it will skip fields with no constraints and will also ignore default -values, if any. - -Read more about xref:constraints[constraints]. - -=== Compilation - -The routes must be compiled before Cowboy can use them. The compilation -step normalizes the routes to simplify the code and speed up the -execution, but the routes are still looked up one by one in the end. -Faster compilation strategies could be to compile the routes directly -to Erlang code, but would require heavier dependencies. - -To compile routes, just call the appropriate function: - -[source,erlang] ----- -Dispatch = cowboy_router:compile([ - %% {HostMatch, list({PathMatch, Handler, InitialState})} - {'_', [{'_', my_handler, #{}}]} -]), -%% Name, TransOpts, ProtoOpts -cowboy:start_clear(my_http_listener, - [{port, 8080}], - #{env => #{dispatch => Dispatch}} -). ----- - -=== Using persistent_term - -The routes can be stored in `persistent_term` starting from -Erlang/OTP 21.2. This may give a performance improvement when -there are a large number of routes. - -To use this functionality you need to compile the routes, -store them in `persistent_term` and then inform Cowboy: - -[source,erlang] ----- -Dispatch = cowboy_router:compile([ - {'_', [{'_', my_handler, #{}}]} -]), -persistent_term:put(my_app_dispatch, Dispatch), -cowboy:start_clear(my_http_listener, - [{port, 8080}], - #{env => #{dispatch => {persistent_term, my_app_dispatch}}} -). ----- - -=== Live update - -You can use the `cowboy:set_env/3` function for updating the dispatch -list used by routing. This will apply to all new connections accepted -by the listener: - -[source,erlang] -Dispatch = cowboy_router:compile(Routes), -cowboy:set_env(my_http_listener, dispatch, Dispatch). - -Note that you need to compile the routes again before updating. - -When using `persistent_term` there is no need to call this function, -you can simply put the new routes in the storage. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/specs.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/specs.asciidoc deleted file mode 100644 index 2f0113feb4..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/specs.asciidoc +++ /dev/null @@ -1,207 +0,0 @@ -[appendix] -== HTTP and other specifications - -This chapter intends to list all the specification documents -for or related to HTTP. - -=== HTTP - -==== IANA Registries - -* https://www.iana.org/assignments/http-methods/http-methods.xhtml[HTTP Method Registry] -* https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml[HTTP Status Code Registry] -* https://www.iana.org/assignments/message-headers/message-headers.xhtml[Message Headers] -* https://www.iana.org/assignments/http-parameters/http-parameters.xhtml[HTTP Parameters] -* https://www.iana.org/assignments/http-alt-svc-parameters/http-alt-svc-parameters.xhtml[HTTP Alt-Svc Parameter Registry] -* https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml[HTTP Authentication Scheme Registry] -* https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml[HTTP Cache Directive Registry] -* https://www.iana.org/assignments/http-dig-alg/http-dig-alg.xhtml[HTTP Digest Algorithm Values] -* https://www.iana.org/assignments/hoba-device-identifiers/hoba-device-identifiers.xhtml[HTTP Origin-Bound Authentication Device Identifier Types] -* https://www.iana.org/assignments/http-upgrade-tokens/http-upgrade-tokens.xhtml[HTTP Upgrade Token Registry] -* https://www.iana.org/assignments/http-warn-codes/http-warn-codes.xhtml[HTTP Warn Codes] -* https://www.iana.org/assignments/http2-parameters/http2-parameters.xhtml[HTTP/2 Parameters] -* https://www.ietf.org/assignments/websocket/websocket.xml[WebSocket Protocol Registries] - -==== Current - -* http://www.w3.org/TR/cors/[CORS]: Cross-Origin Resource Sharing -* http://www.w3.org/TR/CSP2/[CSP2]: Content Security Policy Level 2 -* http://www.w3.org/TR/tracking-dnt/[DNT]: Tracking Preference Expression (DNT) -* http://www.w3.org/TR/eventsource/[eventsource]: Server-Sent Events -* https://www.w3.org/TR/html4/interact/forms.html#h-17.13.4[Form content types]: Form content types -* https://www.w3.org/TR/preload/[Preload]: Preload -* https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt[PROXY]: The PROXY protocol -* http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm[REST]: Fielding's Dissertation -* https://tools.ietf.org/html/rfc1945[RFC 1945]: HTTP/1.0 -* https://tools.ietf.org/html/rfc1951[RFC 1951]: DEFLATE Compressed Data Format Specification version 1.3 -* https://tools.ietf.org/html/rfc1952[RFC 1952]: GZIP file format specification version 4.3 -* https://tools.ietf.org/html/rfc2046#section-5.1[RFC 2046]: Multipart media type (in MIME Part Two: Media Types) -* https://tools.ietf.org/html/rfc2295[RFC 2295]: Transparent Content Negotiation in HTTP -* https://tools.ietf.org/html/rfc2296[RFC 2296]: HTTP Remote Variant Selection Algorithm: RVSA/1.0 -* https://tools.ietf.org/html/rfc2817[RFC 2817]: Upgrading to TLS Within HTTP/1.1 -* https://tools.ietf.org/html/rfc2818[RFC 2818]: HTTP Over TLS -* https://tools.ietf.org/html/rfc3230[RFC 3230]: Instance Digests in HTTP -* https://tools.ietf.org/html/rfc4559[RFC 4559]: SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows -* https://tools.ietf.org/html/rfc5789[RFC 5789]: PATCH Method for HTTP -* https://tools.ietf.org/html/rfc5843[RFC 5843]: Additional Hash Algorithms for HTTP Instance Digests -* https://tools.ietf.org/html/rfc5861[RFC 5861]: HTTP Cache-Control Extensions for Stale Content -* https://tools.ietf.org/html/rfc5988[RFC 5988]: Web Linking -* https://tools.ietf.org/html/rfc6265[RFC 6265]: HTTP State Management Mechanism -* https://tools.ietf.org/html/rfc6266[RFC 6266]: Use of the Content-Disposition Header Field -* https://tools.ietf.org/html/rfc6454[RFC 6454]: The Web Origin Concept -* https://tools.ietf.org/html/rfc6455[RFC 6455]: The WebSocket Protocol -* https://tools.ietf.org/html/rfc6585[RFC 6585]: Additional HTTP Status Codes -* https://tools.ietf.org/html/rfc6750[RFC 6750]: The OAuth 2.0 Authorization Framework: Bearer Token Usage -* https://tools.ietf.org/html/rfc6797[RFC 6797]: HTTP Strict Transport Security (HSTS) -* https://tools.ietf.org/html/rfc6903[RFC 6903]: Additional Link Relation Types -* https://tools.ietf.org/html/rfc7034[RFC 7034]: HTTP Header Field X-Frame-Options -* https://tools.ietf.org/html/rfc7089[RFC 7089]: Time-Based Access to Resource States: Memento -* https://tools.ietf.org/html/rfc7230[RFC 7230]: HTTP/1.1 Message Syntax and Routing -* https://tools.ietf.org/html/rfc7231[RFC 7231]: HTTP/1.1 Semantics and Content -* https://tools.ietf.org/html/rfc7232[RFC 7232]: HTTP/1.1 Conditional Requests -* https://tools.ietf.org/html/rfc7233[RFC 7233]: HTTP/1.1 Range Requests -* https://tools.ietf.org/html/rfc7234[RFC 7234]: HTTP/1.1 Caching -* https://tools.ietf.org/html/rfc7235[RFC 7235]: HTTP/1.1 Authentication -* https://tools.ietf.org/html/rfc7239[RFC 7239]: Forwarded HTTP Extension -* https://tools.ietf.org/html/rfc7240[RFC 7240]: Prefer Header for HTTP -* https://tools.ietf.org/html/rfc7469[RFC 7469]: Public Key Pinning Extension for HTTP -* https://tools.ietf.org/html/rfc7486[RFC 7486]: HTTP Origin-Bound Authentication (HOBA) -* https://tools.ietf.org/html/rfc7538[RFC 7538]: HTTP Status Code 308 (Permanent Redirect) -* https://tools.ietf.org/html/rfc7540[RFC 7540]: Hypertext Transfer Protocol Version 2 (HTTP/2) -* https://tools.ietf.org/html/rfc7541[RFC 7541]: HPACK: Header Compression for HTTP/2 -* https://tools.ietf.org/html/rfc7578[RFC 7578]: Returning Values from Forms: multipart/form-data -* https://tools.ietf.org/html/rfc7615[RFC 7615]: HTTP Authentication-Info and Proxy-Authentication-Info Response Header Fields -* https://tools.ietf.org/html/rfc7616[RFC 7616]: HTTP Digest Access Authentication -* https://tools.ietf.org/html/rfc7617[RFC 7617]: The 'Basic' HTTP Authentication Scheme -* https://tools.ietf.org/html/rfc7639[RFC 7639]: The ALPN HTTP Header Field -* https://tools.ietf.org/html/rfc7692[RFC 7692]: Compression Extensions for WebSocket -* https://tools.ietf.org/html/rfc7694[RFC 7694]: HTTP Client-Initiated Content-Encoding -* https://tools.ietf.org/html/rfc7725[RFC 7725]: An HTTP Status Code to Report Legal Obstacles -* https://tools.ietf.org/html/rfc7804[RFC 7804]: Salted Challenge Response HTTP Authentication Mechanism -* https://tools.ietf.org/html/rfc7838[RFC 7838]: HTTP Alternative Services -* https://tools.ietf.org/html/rfc7932[RFC 7932]: Brotli Compressed Data Format -* https://tools.ietf.org/html/rfc7936[RFC 7936]: Clarifying Registry Procedures for the WebSocket Subprotocol Name Registry -* https://tools.ietf.org/html/rfc8053[RFC 8053]: HTTP Authentication Extensions for Interactive Clients -* https://tools.ietf.org/html/rfc8164[RFC 8164]: Opportunistic Security for HTTP/2 -* https://tools.ietf.org/html/rfc8187[RFC 8187]: Indicating Character Encoding and Language for HTTP Header Field Parameters -* https://tools.ietf.org/html/rfc8188[RFC 8188]: Encrypted Content-Encoding for HTTP -* https://tools.ietf.org/html/rfc8246[RFC 8246]: HTTP Immutable Responses -* https://tools.ietf.org/html/rfc8297[RFC 8297]: An HTTP Status Code for Indicating Hints -* https://tools.ietf.org/html/rfc8336[RFC 8336]: The ORIGIN HTTP/2 Frame -* https://tools.ietf.org/html/rfc8441[RFC 8441]: Bootstrapping WebSockets with HTTP/2 -* https://tools.ietf.org/html/rfc8470[RFC 8470]: Using Early Data in HTTP -* https://tools.ietf.org/html/rfc8473[RFC 8473]: Token Binding over HTTP -* https://tools.ietf.org/html/rfc8586[RFC 8586]: Loop Detection in Content Delivery Networks (CDNs) -* https://tools.ietf.org/html/rfc8594[RFC 8594]: The Sunset HTTP Header Field -* https://www.w3.org/TR/webmention/[Webmention]: Webmention - -==== Upcoming - -* https://www.w3.org/TR/clear-site-data/[Clear Site Data] -* https://www.w3.org/TR/csp-cookies/[Content Security Policy: Cookie Controls] -* https://www.w3.org/TR/csp-embedded-enforcement/[Content Security Policy: Embedded Enforcement] -* https://www.w3.org/TR/CSP3/[Content Security Policy Level 3] -* https://www.w3.org/TR/csp-pinning/[Content Security Policy Pinning] -* http://www.w3.org/TR/referrer-policy/[Referrer Policy] -* http://www.w3.org/TR/UISecurity/[User Interface Security Directives for Content Security Policy] - -==== Informative - -* http://www.w3.org/TR/webarch/[Architecture of the World Wide Web] -* https://tools.ietf.org/html/rfc2936[RFC 2936]: HTTP MIME Type Handler Detection -* https://tools.ietf.org/html/rfc2964[RFC 2964]: Use of HTTP State Management -* https://tools.ietf.org/html/rfc3143[RFC 3143]: Known HTTP Proxy/Caching Problems -* https://tools.ietf.org/html/rfc6202[RFC 6202]: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP -* https://tools.ietf.org/html/rfc6838[RFC 6838]: Media Type Specifications and Registration Procedures -* https://tools.ietf.org/html/rfc7478[RFC 7478]: Web Real-Time Communication Use Cases and Requirements - -==== Related - -* http://www.w3.org/TR/app-uri/[app: URL Scheme] -* http://www.w3.org/TR/beacon/[Beacon] -* http://www.w3.org/TR/FileAPI/[File API] -* https://tools.ietf.org/html/rfc8030[Generic Event Delivery Using HTTP Push] -* http://www.w3.org/TR/capability-urls/[Good Practices for Capability URLs] -* https://html.spec.whatwg.org/multipage/[HTML Living Standard] -* https://developers.whatwg.org/[HTML Living Standard for Web developers] -* http://www.w3.org/TR/html401/[HTML4.01] -* http://www.w3.org/TR/html5/[HTML5] -* http://www.w3.org/TR/html51/[HTML5.1] -* https://www.w3.org/TR/html52/[HTML5.2] -* http://www.w3.org/TR/media-frags/[Media Fragments URI 1.0] -* https://tools.ietf.org/html/rfc5829[RFC 5829]: Link Relation Types for Simple Version Navigation between Web Resources -* https://tools.ietf.org/html/rfc6657[RFC 6657]: Update to MIME regarding "charset" Parameter Handling in Textual Media Types -* https://tools.ietf.org/html/rfc6690[RFC 6690]: Constrained RESTful Environments (CoRE) Link Format -* https://tools.ietf.org/html/rfc7807[RFC 7807]: Problem Details for HTTP APIs -* https://tools.ietf.org/html/rfc6906[RFC 6906]: The 'profile' Link Relation Type -* https://tools.ietf.org/html/rfc8631[RFC 8631]: Link Relation Types for Web Services -* http://www.w3.org/TR/SRI/[Subresource Integrity] -* http://www.w3.org/TR/tracking-compliance/[Tracking Compliance and Scope] -* http://www.w3.org/TR/media-frags-reqs/[Use cases and requirements for Media Fragments] -* http://www.w3.org/TR/webrtc/[WebRTC 1.0: Real-time Communication Between Browsers] -* http://www.w3.org/TR/websockets/[Websocket API] -* http://www.w3.org/TR/XMLHttpRequest/[XMLHttpRequest Level 1] -* https://xhr.spec.whatwg.org/[XMLHttpRequest Living Standard] - -==== Seemingly obsolete - -* https://tools.ietf.org/html/rfc2227[RFC 2227]: Simple Hit-Metering and Usage-Limiting for HTTP -* https://tools.ietf.org/html/rfc2310[RFC 2310]: The Safe Response Header Field -* https://tools.ietf.org/html/rfc2324[RFC 2324]: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) -* https://tools.ietf.org/html/rfc2660[RFC 2660]: The Secure HyperText Transfer Protocol -* https://tools.ietf.org/html/rfc2774[RFC 2774]: An HTTP Extension Framework -* https://tools.ietf.org/html/rfc2965[RFC 2965]: HTTP State Management Mechanism (Cookie2) -* https://tools.ietf.org/html/rfc3229[RFC 3229]: Delta encoding in HTTP -* https://tools.ietf.org/html/rfc7168[RFC 7168]: The Hyper Text Coffee Pot Control Protocol for Tea Efflux Appliances (HTCPCP-TEA) -* https://tools.ietf.org/html/rfc8565[RFC 8565]: Hypertext Jeopardy Protocol (HTJP/1.0) -* http://dev.chromium.org/spdy/spdy-protocol[SPDY]: SPDY Protocol -* https://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate-06[x-webkit-deflate-frame]: Deprecated Websocket compression - -=== URL - -* https://tools.ietf.org/html/rfc3986[RFC 3986]: URI Generic Syntax -* https://tools.ietf.org/html/rfc6570[RFC 6570]: URI Template -* https://tools.ietf.org/html/rfc6874[RFC 6874]: Representing IPv6 Zone Identifiers in Address Literals and URIs -* https://tools.ietf.org/html/rfc7320[RFC 7320]: URI Design and Ownership -* https://tools.ietf.org/html/rfc8615[RFC 8615]: Well-Known URIs -* http://www.w3.org/TR/url-1/[URL] -* https://url.spec.whatwg.org/[URL Living Standard] - -=== WebDAV - -* https://tools.ietf.org/html/rfc3253[RFC 3253]: Versioning Extensions to WebDAV -* https://tools.ietf.org/html/rfc3648[RFC 3648]: WebDAV Ordered Collections Protocol -* https://tools.ietf.org/html/rfc3744[RFC 3744]: WebDAV Access Control Protocol -* https://tools.ietf.org/html/rfc4316[RFC 4316]: Datatypes for WebDAV Properties -* https://tools.ietf.org/html/rfc4331[RFC 4331]: Quota and Size Properties for DAV Collections -* https://tools.ietf.org/html/rfc4437[RFC 4437]: WebDAV Redirect Reference Resources -* https://tools.ietf.org/html/rfc4709[RFC 4709]: Mounting WebDAV Servers -* https://tools.ietf.org/html/rfc4791[RFC 4791]: Calendaring Extensions to WebDAV (CalDAV) -* https://tools.ietf.org/html/rfc4918[RFC 4918]: HTTP Extensions for WebDAV -* https://tools.ietf.org/html/rfc5323[RFC 5323]: WebDAV SEARCH -* https://tools.ietf.org/html/rfc5397[RFC 5397]: WebDAV Current Principal Extension -* https://tools.ietf.org/html/rfc5689[RFC 5689]: Extended MKCOL for WebDAV -* https://tools.ietf.org/html/rfc5842[RFC 5842]: Binding Extensions to WebDAV -* https://tools.ietf.org/html/rfc5995[RFC 5995]: Using POST to Add Members to WebDAV Collections -* https://tools.ietf.org/html/rfc6352[RFC 6352]: CardDAV: vCard Extensions to WebDAV -* https://tools.ietf.org/html/rfc6578[RFC 6578]: Collection Synchronization for WebDAV -* https://tools.ietf.org/html/rfc6638[RFC 6638]: Scheduling Extensions to CalDAV -* https://tools.ietf.org/html/rfc6764[RFC 6764]: Locating Services for Calendaring Extensions to WebDAV (CalDAV) and vCard Extensions to WebDAV (CardDAV) -* https://tools.ietf.org/html/rfc7809[RFC 7809]: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference -* https://tools.ietf.org/html/rfc7953[RFC 7953]: Calendar Availability -* https://tools.ietf.org/html/rfc8144[RFC 8144]: Use of the Prefer Header Field in WebDAV -* https://tools.ietf.org/html/rfc8607[RFC 8607]: Calendaring Extensions to WebDAV (CalDAV): Managed Attachments - -=== CoAP - -* https://tools.ietf.org/html/rfc7252[RFC 7252]: The Constrained Application Protocol (CoAP) -* https://tools.ietf.org/html/rfc7390[RFC 7390]: Group Communication for CoAP -* https://tools.ietf.org/html/rfc7641[RFC 7641]: Observing Resources in CoAP -* https://tools.ietf.org/html/rfc7650[RFC 7650]: A CoAP Usage for REsource LOcation And Discovery (RELOAD) -* https://tools.ietf.org/html/rfc7959[RFC 7959]: Block-Wise Transfers in CoAP -* https://tools.ietf.org/html/rfc7967[RFC 7967]: CoAP Option for No Server Response -* https://tools.ietf.org/html/rfc8075[RFC 8075]: Guidelines for Mapping Implementations: HTTP to CoAP -* https://tools.ietf.org/html/rfc8132[RFC 8132]: PATCH and FETCH Methods for CoAP -* https://tools.ietf.org/html/rfc8323[RFC 8323]: CoAP over TCP, TLS, and WebSockets -* https://tools.ietf.org/html/rfc8516[RFC 8516]: "Too Many Requests" Response Code for CoAP -* https://tools.ietf.org/html/rfc8613[RFC 8613]: Object Security for Constrained RESTful Environments diff --git a/_build/emqx/lib/cowboy/doc/src/guide/static_files.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/static_files.asciidoc deleted file mode 100644 index 5af911be37..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/static_files.asciidoc +++ /dev/null @@ -1,163 +0,0 @@ -[[static_files]] -== Static files - -Cowboy comes with a ready to use handler for serving static -files. It is provided as a convenience for serving files -during development. - -For systems in production, consider using one of the many -Content Distribution Network (CDN) available on the market, -as they are the best solution for serving files. - -The static handler can serve either one file or all files -from a given directory. The etag generation and mime types -can be configured. - -=== Serve one file - -You can use the static handler to serve one specific file -from an application's private directory. This is particularly -useful to serve an 'index.html' file when the client requests -the `/` path, for example. The path configured is relative -to the given application's private directory. - -The following rule will serve the file 'static/index.html' -from the application `my_app`'s priv directory whenever the -path `/` is accessed: - -[source,erlang] -{"/", cowboy_static, {priv_file, my_app, "static/index.html"}} - -You can also specify the absolute path to a file, or the -path to the file relative to the current directory: - -[source,erlang] -{"/", cowboy_static, {file, "/var/www/index.html"}} - -=== Serve all files from a directory - -You can also use the static handler to serve all files that -can be found in the configured directory. The handler will -use the `path_info` information to resolve the file location, -which means that your route must end with a `[...]` pattern -for it to work. All files are served, including the ones that -may be found in subfolders. - -You can specify the directory relative to the application's -private directory (e.g. `my_app/priv`). - -The following rule will serve any file found in the `my_app` -application's private directory in the `my_app/priv/static/assets` -folder whenever the requested path begins with `/assets/`: - -[source,erlang] -{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets"}} - -You can also specify the absolute path to the directory or -set it relative to the current directory: - -[source,erlang] -{"/assets/[...]", cowboy_static, {dir, "/var/www/assets"}} - -=== Customize the mimetype detection - -By default, Cowboy will attempt to recognize the mimetype -of your static files by looking at the extension. - -You can override the function that figures out the mimetype -of the static files. It can be useful when Cowboy is missing -a mimetype you need to handle, or when you want to reduce -the list to make lookups faster. You can also give a -hard-coded mimetype that will be used unconditionally. - -Cowboy comes with two functions built-in. The default -function only handles common file types used when building -Web applications. The other function is an extensive list -of hundreds of mimetypes that should cover almost any need -you may have. You can of course create your own function. - -To use the default function, you should not have to configure -anything, as it is the default. If you insist, though, the -following will do the job: - -[source,erlang] ----- -{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets", - [{mimetypes, cow_mimetypes, web}]}} ----- - -As you can see, there is an optional field that may contain -a list of less used options, like mimetypes or etag. All option -types have this optional field. - -To use the function that will detect almost any mimetype, -the following configuration will do: - -[source,erlang] ----- -{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets", - [{mimetypes, cow_mimetypes, all}]}} ----- - -You probably noticed the pattern by now. The configuration -expects a module and a function name, so you can use any -of your own functions instead: - -[source,erlang] ----- -{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets", - [{mimetypes, Module, Function}]}} ----- - -The function that performs the mimetype detection receives -a single argument that is the path to the file on disk. It -is recommended to return the mimetype in tuple form, although -a binary string is also allowed (but will require extra -processing). If the function can't figure out the mimetype, -then it should return `{<<"application">>, <<"octet-stream">>, []}`. - -When the static handler fails to find the extension, -it will send the file as `application/octet-stream`. -A browser receiving such file will attempt to download it -directly to disk. - -Finally, the mimetype can be hard-coded for all files. -This is especially useful in combination with the `file` -and `priv_file` options as it avoids needless computation: - -[source,erlang] ----- -{"/", cowboy_static, {priv_file, my_app, "static/index.html", - [{mimetypes, {<<"text">>, <<"html">>, []}}]}} ----- - -=== Generate an etag - -By default, the static handler will generate an etag header -value based on the size and modified time. This solution -can not be applied to all systems though. It would perform -rather poorly over a cluster of nodes, for example, as the -file metadata will vary from server to server, giving a -different etag on each server. - -You can however change the way the etag is calculated: - -[source,erlang] ----- -{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets", - [{etag, Module, Function}]}} ----- - -This function will receive three arguments: the path to the -file on disk, the size of the file and the last modification -time. In a distributed setup, you would typically use the -file path to retrieve an etag value that is identical across -all your servers. - -You can also completely disable etag handling: - -[source,erlang] ----- -{"/assets/[...]", cowboy_static, {priv_dir, my_app, "static/assets", - [{etag, false}]}} ----- diff --git a/_build/emqx/lib/cowboy/doc/src/guide/streams.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/streams.asciidoc deleted file mode 100644 index 39b5203942..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/streams.asciidoc +++ /dev/null @@ -1,75 +0,0 @@ -[[streams]] -== Streams - -A stream is the set of messages that form an HTTP -request/response pair. - -The term stream comes from HTTP/2. In Cowboy, it is -also used when talking about HTTP/1.1 or HTTP/1.0. -It should not be confused with streaming the request -or response body. - -All versions of HTTP allow clients to initiate -streams. HTTP/2 is the only one also allowing servers, -through its server push feature. Both client and -server-initiated streams go through the same process -in Cowboy. - -=== Stream handlers - -link:man:cowboy_stream(3)[Stream handlers] -must implement five different callbacks. -Four of them are directly related; one is special. - -All callbacks receives the stream ID as first argument. - -Most of them can return a list of commands to be executed -by Cowboy. When callbacks are chained, it is possible to -intercept and modify these commands. This can be useful -for modifying responses for example. - -The `init/3` callback is invoked when a new request -comes in. It receives the Req object and the protocol options -for this listener. - -The `data/4` callback is invoked when data from the request -body is received. It receives both this data and a flag -indicating whether more is to be expected. - -The `info/3` callback is invoked when an Erlang message is -received for this stream. They will typically be messages -sent by the request process. - -Finally the `terminate/3` callback is invoked with the -terminate reason for the stream. The return value is ignored. -Note that as with all terminate callbacks in Erlang, there -is no strong guarantee that it will be called. - -The special callback `early_error/5` is called when an error -occurs before the request headers were fully received and -Cowboy is sending a response. It receives the partial Req -object, the error reason, the protocol options and the response -Cowboy will send. This response must be returned, possibly -modified. - -=== Built-in handlers - -Cowboy comes with two handlers. - -link:man:cowboy_stream_h(3)[cowboy_stream_h] is the default -stream handler. It is the core of much of the functionality -of Cowboy. All chains of stream handlers should call it last. - -link:man:cowboy_compress_h(3)[cowboy_compress_h] will -automatically compress responses when possible. It is not -enabled by default. It is a good example for writing your -own handlers that will modify responses. - -link:man:cowboy_metrics_h(3)[cowboy_metrics_h] gathers -metrics about a stream then passes them to a configurable -function. It is not enabled by default. - -link:man:cowboy_tracer_h(3)[cowboy_tracer_h] can be used to -conditionally trace streams based on the contents of the -request or its origin. Trace events are passed to a -configurable function. It is not enabled by default. diff --git a/_build/emqx/lib/cowboy/doc/src/guide/ws_handlers.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/ws_handlers.asciidoc deleted file mode 100644 index 5cfdcb167d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/ws_handlers.asciidoc +++ /dev/null @@ -1,292 +0,0 @@ -[[ws_handlers]] -== Websocket handlers - -Websocket handlers provide an interface for upgrading HTTP/1.1 -connections to Websocket and sending or receiving frames on -the Websocket connection. - -As Websocket connections are established through the HTTP/1.1 -upgrade mechanism, Websocket handlers need to be able to first -receive the HTTP request for the upgrade, before switching to -Websocket and taking over the connection. They can then receive -or send Websocket frames, handle incoming Erlang messages or -close the connection. - -=== Upgrade - -The `init/2` callback is called when the request is received. -To establish a Websocket connection, you must switch to the -`cowboy_websocket` module: - -[source,erlang] ----- -init(Req, State) -> - {cowboy_websocket, Req, State}. ----- - -Cowboy will perform the Websocket handshake immediately. Note -that the handshake will fail if the client did not request an -upgrade to Websocket. - -The Req object becomes unavailable after this function returns. -Any information required for proper execution of the Websocket -handler must be saved in the state. - -=== Subprotocol - -The client may provide a list of Websocket subprotocols it -supports in the sec-websocket-protocol header. The server *must* -select one of them and send it back to the client or the -handshake will fail. - -For example, a client could understand both STOMP and MQTT over -Websocket, and provide the header: - ----- -sec-websocket-protocol: v12.stomp, mqtt ----- - -If the server only understands MQTT it can return: - ----- -sec-websocket-protocol: mqtt ----- - -This selection must be done in `init/2`. An example usage could -be: - -[source,erlang] ----- -init(Req0, State) -> - case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of - undefined -> - {cowboy_websocket, Req0, State}; - Subprotocols -> - case lists:keymember(<<"mqtt">>, 1, Subprotocols) of - true -> - Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>, - <<"mqtt">>, Req0), - {cowboy_websocket, Req, State}; - false -> - Req = cowboy_req:reply(400, Req0), - {ok, Req, State} - end - end. ----- - -=== Post-upgrade initialization - -Cowboy has separate processes for handling the connection -and requests. Because Websocket takes over the connection, -the Websocket protocol handling occurs in a different -process than the request handling. - -This is reflected in the different callbacks Websocket -handlers have. The `init/2` callback is called from the -temporary request process and the `websocket_` callbacks -from the connection process. - -This means that some initialization cannot be done from -`init/2`. Anything that would require the current pid, -or be tied to the current pid, will not work as intended. -The optional `websocket_init/1` can be used instead: - -[source,erlang] ----- -websocket_init(State) -> - erlang:start_timer(1000, self(), <<"Hello!">>), - {ok, State}. ----- - -All Websocket callbacks share the same return values. This -means that we can send frames to the client right after -the upgrade: - -[source,erlang] ----- -websocket_init(State) -> - {[{text, <<"Hello!">>}], State}. ----- - -=== Receiving frames - -Cowboy will call `websocket_handle/2` whenever a text, binary, -ping or pong frame arrives from the client. - -The handler can handle or ignore the frames. It can also -send frames back to the client or stop the connection. - -The following snippet echoes back any text frame received and -ignores all others: - -[source,erlang] ----- -websocket_handle(Frame = {text, _}, State) -> - {[Frame], State}; -websocket_handle(_Frame, State) -> - {ok, State}. ----- - -Note that ping and pong frames require no action from the -handler as Cowboy will automatically reply to ping frames. -They are provided for informative purposes only. - -=== Receiving Erlang messages - -Cowboy will call `websocket_info/2` whenever an Erlang message -arrives. - -The handler can handle or ignore the messages. It can also -send frames to the client or stop the connection. - -The following snippet forwards log messages to the client -and ignores all others: - -[source,erlang] ----- -websocket_info({log, Text}, State) -> - {[{text, Text}], State}; -websocket_info(_Info, State) -> - {ok, State}. ----- - -=== Sending frames - -// @todo This will be deprecated and eventually replaced with a -// {Commands, State} interface that allows providing more -// functionality easily. - -All `websocket_` callbacks share return values. They may -send zero, one or many frames to the client. - -To send nothing, just return an ok tuple: - -[source,erlang] ----- -websocket_info(_Info, State) -> - {ok, State}. ----- - -To send one frame, return the frame to be sent: - -[source,erlang] ----- -websocket_info(_Info, State) -> - {[{text, <<"Hello!">>}], State}. ----- - -You can send frames of any type: text, binary, ping, pong -or close frames. - -You can send many frames at the same time: - -[source,erlang] ----- -websocket_info(_Info, State) -> - {[ - {text, "Hello"}, - {text, <<"world!">>}, - {binary, <<0:8000>>} - ], State}. ----- - -They are sent in the given order. - -=== Keeping the connection alive - -Cowboy will automatically respond to ping frames sent by -the client. They are still forwarded to the handler for -informative purposes, but no further action is required. - -Cowboy does not send ping frames itself. The handler can -do it if required. A better solution in most cases is to -let the client handle pings. Doing it from the handler -would imply having an additional timer per connection and -this can be a considerable cost for servers that need to -handle large numbers of connections. - -Cowboy can be configured to close idle connections -automatically. It is highly recommended to configure -a timeout here, to avoid having processes linger longer -than needed. - -The `init/2` callback can set the timeout to be used -for the connection. For example, this would make Cowboy -close connections idle for more than 30 seconds: - -[source,erlang] ----- -init(Req, State) -> - {cowboy_websocket, Req, State, #{ - idle_timeout => 30000}}. ----- - -This value cannot be changed once it is set. It defaults to -`60000`. - -=== Limiting frame sizes - -Cowboy accepts frames of any size by default. You should -limit the size depending on what your handler may handle. -You can do this via the `init/2` callback: - -[source,erlang] ----- -init(Req, State) -> - {cowboy_websocket, Req, State, #{ - max_frame_size => 8000000}}. ----- - -The lack of limit is historical. A future version of -Cowboy will have a more reasonable default. - -=== Saving memory - -The Websocket connection process can be set to hibernate -after the callback returns. - -Simply add an `hibernate` field to the returned tuple: - -[source,erlang] ----- -websocket_init(State) -> - {[], State, hibernate}. - -websocket_handle(_Frame, State) -> - {[], State, hibernate}. - -websocket_info(_Info, State) -> - {[{text, <<"Hello!">>}], State, hibernate}. ----- - -It is highly recommended to write your handlers with -hibernate enabled, as this allows to greatly reduce the -memory usage. Do note however that an increase in the -CPU usage or latency can be observed instead, in particular -for the more busy connections. - -=== Closing the connection - -The connection can be closed at any time, either by telling -Cowboy to stop it or by sending a close frame. - -To tell Cowboy to close the connection, use a stop tuple: - -[source,erlang] ----- -websocket_info(_Info, State) -> - {stop, State}. ----- - -Sending a `close` frame will immediately initiate the closing -of the Websocket connection. Note that when sending a list of -frames that include a close frame, any frame found after the -close frame will not be sent. - -The following example sends a close frame with a reason message: - -[source,erlang] ----- -websocket_info(_Info, State) -> - {[{close, 1000, <<"some-reason">>}], State}. ----- diff --git a/_build/emqx/lib/cowboy/doc/src/guide/ws_protocol.asciidoc b/_build/emqx/lib/cowboy/doc/src/guide/ws_protocol.asciidoc deleted file mode 100644 index 8fa0673d17..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/guide/ws_protocol.asciidoc +++ /dev/null @@ -1,69 +0,0 @@ -[[ws_protocol]] -== The Websocket protocol - -This chapter explains what Websocket is and why it is -a vital component of soft realtime Web applications. - -=== Description - -Websocket is an extension to HTTP that emulates plain TCP -connections between the client, typically a Web browser, -and the server. It uses the HTTP Upgrade mechanism to -establish the connection. - -Websocket connections are fully asynchronous, unlike -HTTP/1.1 (synchronous) and HTTP/2 (asynchronous, but the -server can only initiate streams in response to requests). -With Websocket, the client and the server can both send -frames at any time without any restriction. It is closer -to TCP than any of the HTTP protocols. - -Websocket is an IETF standard. Cowboy supports the standard -and all drafts that were previously implemented by browsers, -excluding the initial flawed draft sometimes known as -"version 0". - -=== Websocket vs HTTP/2 - -For a few years Websocket was the only way to have a -bidirectional asynchronous connection with the server. -This changed when HTTP/2 was introduced. While HTTP/2 -requires the client to first perform a request before -the server can push data, this is only a minor restriction -as the client can do so just as it connects. - -Websocket was designed as a kind-of-TCP channel to a -server. It only defines the framing and connection -management and lets the developer implement a protocol -on top of it. For example you could implement IRC over -Websocket and use a Javascript IRC client to speak to -the server. - -HTTP/2 on the other hand is just an improvement over -the HTTP/1.1 connection and request/response mechanism. -It has the same semantics as HTTP/1.1. - -If all you need is to access an HTTP API, then HTTP/2 -should be your first choice. On the other hand, if what -you need is a different protocol, then you can use -Websocket to implement it. - -=== Implementation - -Cowboy implements Websocket as a protocol upgrade. Once the -upgrade is performed from the `init/2` callback, Cowboy -switches to Websocket. Please consult the next chapter for -more information on initiating and handling Websocket -connections. - -The implementation of Websocket in Cowboy is validated using -the Autobahn test suite, which is an extensive suite of tests -covering all aspects of the protocol. Cowboy passes the -suite with 100% success, including all optional tests. - -Cowboy's Websocket implementation also includes the -permessage-deflate and x-webkit-deflate-frame compression -extensions. - -Cowboy will automatically use compression when the -`compress` option is returned from the `init/2` function. diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy.asciidoc deleted file mode 100644 index c213df09f8..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.asciidoc +++ /dev/null @@ -1,95 +0,0 @@ -= cowboy(3) - -== Name - -cowboy - HTTP server - -== Description - -The module `cowboy` provides convenience functions for -manipulating Ranch listeners. - -== Exports - -* link:man:cowboy:start_clear(3)[cowboy:start_clear(3)] - Listen for connections using plain TCP -* link:man:cowboy:start_tls(3)[cowboy:start_tls(3)] - Listen for connections using TLS -* link:man:cowboy:stop_listener(3)[cowboy:stop_listener(3)] - Stop the given listener -* link:man:cowboy:set_env(3)[cowboy:set_env(3)] - Update a listener's environment value - -== Types - -=== fields() - -[source,erlang] ----- -fields() :: [Name - | {Name, Constraints} - | {Name, Constraints, Default}] - -Name :: atom() -Constraints :: Constraint | [Constraint] -Constraint :: cowboy_constraints:constraint() -Default :: any() ----- - -Fields description for match operations. - -This type is used in link:man:cowboy_router(3)[cowboy_router(3)] -for matching bindings and in the match functions found in -link:man:cowboy_req(3)[cowboy_req(3)]. - -=== http_headers() - -[source,erlang] ----- -http_headers() :: #{binary() => iodata()} ----- - -HTTP headers. - -=== http_status() - -[source,erlang] ----- -http_status() :: non_neg_integer() | binary() ----- - -HTTP response status. - -A binary status can be used to set a reason phrase. Note -however that HTTP/2 only sends the status code and drops -the reason phrase entirely. - -=== http_version() - -[source,erlang] ----- -http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0' ----- - -HTTP version. - -Note that semantically, HTTP/1.1 and HTTP/2 are equivalent. - -=== opts() - -[source,erlang] ----- -opts() :: map() ----- - -Options for the HTTP/1.1, HTTP/2 and Websocket protocols. - -The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. - -The HTTP/1.1 options are documented in the -link:man:cowboy_http(3)[cowboy_http(3)] manual -and the HTTP/2 options in -link:man:cowboy_http2(3)[cowboy_http2(3)]. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:ranch(3)[ranch(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.set_env.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy.set_env.asciidoc deleted file mode 100644 index 30af485f2a..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.set_env.asciidoc +++ /dev/null @@ -1,79 +0,0 @@ -= cowboy:set_env(3) - -== Name - -cowboy:set_env - Update a listener's environment value - -== Description - -[source,erlang] ----- -set_env(Name :: ranch:ref(), - Key :: atom(), - Value :: any()) - -> ok ----- - -Set or update an environment value for a previously started -listener. - -This is most useful for updating the routes dynamically, -without having to restart the listener. - -The new value will only be available to new connections. -Pre-existing connections will still use the old value. - -== Arguments - -Name:: - -The name of the listener to update. -+ -The name of the listener is the first argument given to the -link:man:cowboy:start_clear(3)[cowboy:start_clear(3)], -link:man:cowboy:start_tls(3)[cowboy:start_tls(3)] or -link:man:ranch:start_listener(3)[ranch:start_listener(3)] function. - -Key:: - -The key in the environment map. Common keys include `dispatch` -and `middlewares`. - -Value:: - -The new value. -+ -The type of the value differs depending on the key. - -== Return value - -The atom `ok` is returned on success. - -An `exit:badarg` exception is thrown when the listener does -not exist. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Update a listener's routes -[source,erlang] ----- -Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []}, - {"/ws", websocket_h, []} - ]} -]), - -cowboy:set_env(example, dispatch, Dispatch). ----- - -== See also - -link:man:cowboy(3)[cowboy(3)], -link:man:cowboy:start_clear(3)[cowboy:start_clear(3)], -link:man:cowboy:start_tls(3)[cowboy:start_tls(3)], -link:man:ranch:set_protocol_options(3)[ranch:set_protocol_options(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.start_clear.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy.start_clear.asciidoc deleted file mode 100644 index 3d09935698..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.start_clear.asciidoc +++ /dev/null @@ -1,106 +0,0 @@ -= cowboy:start_clear(3) - -== Name - -cowboy:start_clear - Listen for connections using plain TCP - -== Description - -[source,erlang] ----- -start_clear(Name :: ranch:ref(), - TransportOpts :: ranch_tcp:opts(), - ProtocolOpts :: opts()) - -> {ok, ListenerPid :: pid()} - | {error, any()} ----- - -Start listening for connections over a clear TCP channel. - -Both HTTP/1.1 and HTTP/2 are supported on this listener. -HTTP/2 has two methods of establishing a connection over -a clear TCP channel. Both the upgrade and the prior knowledge -methods are supported. - -== Arguments - -Name:: - -The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -+ -It can be any Erlang term. An atom is generally good enough, -for example `api`, `my_app_clear` or `my_app_tls`. - -TransportOpts:: - -The transport options are where the TCP options, including -the listener's port number, are defined. Transport options -are provided as a list of keys and values, for example -`[{port, 8080}]`. -+ -The available options are documented in the -link:man:ranch_tcp(3)[ranch_tcp(3)] manual. - -ProtocolOpts:: - -The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -+ -The HTTP/1.1 options are documented in the -link:man:cowboy_http(3)[cowboy_http(3)] manual; -and the HTTP/2 options in -link:man:cowboy_http2(3)[cowboy_http2(3)]. - -== Return value - -An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener. - -An error tuple is returned on error. The error reason may -be any Erlang term. - -A common error is `eaddrinuse`. It indicates that the port -configured for Cowboy is already in use. - -== Changelog - -* *2.0*: HTTP/2 support added. -* *2.0*: Function introduced. Replaces `cowboy:start_http/4`. - -== Examples - -.Start a listener -[source,erlang] ----- -Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} -]), - -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}). ----- - -.Start a listener on a random port -[source,erlang] ----- -Name = example, - -{ok, _} = cowboy:start_clear(Name, [], #{ - env => #{dispatch => Dispatch} -}), - -Port = ranch:get_port(Name). ----- - -== See also - -link:man:cowboy(3)[cowboy(3)], -link:man:cowboy:start_tls(3)[cowboy:start_tls(3)], -link:man:cowboy:stop_listener(3)[cowboy:stop_listener(3)], -link:man:ranch(3)[ranch(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.start_tls.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy.start_tls.asciidoc deleted file mode 100644 index 8880bf3189..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.start_tls.asciidoc +++ /dev/null @@ -1,111 +0,0 @@ -= cowboy:start_tls(3) - -== Name - -cowboy:start_tls - Listen for connections using TLS - -== Description - -[source,erlang] ----- -start_tls(Name :: ranch:ref(), - TransportOpts :: ranch_ssl:opts(), - ProtocolOpts :: opts()) - -> {ok, ListenerPid :: pid()} - | {error, any()} ----- - -Start listening for connections over a secure TLS channel. - -Both HTTP/1.1 and HTTP/2 are supported on this listener. -The ALPN TLS extension must be used to initiate an HTTP/2 -connection. - -== Arguments - -Name:: - -The listener name is used to refer to this listener in -future calls, for example when stopping it or when -updating the routes defined. -+ -It can be any Erlang term. An atom is generally good enough, -for example `api`, `my_app_clear` or `my_app_tls`. - -TransportOpts:: - -The transport options are where the TCP options, including -the listener's port number, are defined. They also contain -the TLS options, like the server's certificate. Transport options -are provided as a list of keys and values, for example -`[{port, 8443}, {certfile, "path/to/cert.pem"}]`. -+ -The available options are documented in the -link:man:ranch_ssl(3)[ranch_ssl(3)] manual. - -ProtocolOpts:: - -The protocol options are in a map containing all the options for -the different protocols that may be involved when connecting -to the listener, including HTTP/1.1 and HTTP/2. -+ -The HTTP/1.1 options are documented in the -link:man:cowboy_http(3)[cowboy_http(3)] manual; -and the HTTP/2 options in -link:man:cowboy_http2(3)[cowboy_http2(3)]. - -== Return value - -An ok tuple is returned on success. It contains the pid of -the top-level supervisor for the listener. - -An error tuple is returned on error. The error reason may -be any Erlang term. - -A common error is `eaddrinuse`. It indicates that the port -configured for Cowboy is already in use. - -== Changelog - -* *2.0*: HTTP/2 support added. -* *2.0*: Function introduced. Replaces `cowboy:start_https/4`. - -== Examples - -.Start a listener -[source,erlang] ----- -Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} -]), - -{ok, _} = cowboy:start_tls(example, [ - {port, 8443}, - {certfile, "path/to/cert.pem"} -], #{ - env => #{dispatch => Dispatch} -}). ----- - -.Start a listener on a random port -[source,erlang] ----- -Name = example, - -{ok, _} = cowboy:start_tls(Name, [ - {certfile, "path/to/cert.pem"} -], #{ - env => #{dispatch => Dispatch} -}), - -Port = ranch:get_port(Name). ----- - -== See also - -link:man:cowboy(3)[cowboy(3)], -link:man:cowboy:start_clear(3)[cowboy:start_clear(3)], -link:man:cowboy:stop_listener(3)[cowboy:stop_listener(3)], -link:man:ranch(3)[ranch(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.stop_listener.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy.stop_listener.asciidoc deleted file mode 100644 index 7998189b17..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy.stop_listener.asciidoc +++ /dev/null @@ -1,55 +0,0 @@ -= cowboy:stop_listener(3) - -== Name - -cowboy:stop_listener - Stop the given listener - -== Description - -[source,erlang] ----- -stop_listener(Name :: ranch:ref()) - -> ok | {error, not_found}. ----- - -Stop a previously started listener. - -Alias of link:man:ranch:stop_listener(3)[ranch:stop_listener(3)]. - -== Arguments - -Name:: - -The name of the listener to be stopped. -+ -The name of the listener is the first argument given to the -link:man:cowboy:start_clear(3)[cowboy:start_clear(3)], -link:man:cowboy:start_tls(3)[cowboy:start_tls(3)] or -link:man:ranch:start_listener(3)[ranch:start_listener(3)] function. - -== Return value - -The atom `ok` is returned on success. - -The `{error, not_found}` tuple is returned when the listener -does not exist. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Stop a listener -[source,erlang] ----- -ok = cowboy:stop_listener(example). ----- - -== See also - -link:man:cowboy(3)[cowboy(3)], -link:man:cowboy:start_clear(3)[cowboy:start_clear(3)], -link:man:cowboy:start_tls(3)[cowboy:start_tls(3)], -link:man:ranch(3)[ranch(3)], -link:man:ranch:start_listener(3)[ranch:start_listener(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_app.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_app.asciidoc deleted file mode 100644 index 8db84b1f56..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_app.asciidoc +++ /dev/null @@ -1,81 +0,0 @@ -= cowboy(7) - -== Name - -cowboy - Small, fast, modern HTTP server for Erlang/OTP - -== Description - -Cowboy is an HTTP server for Erlang/OTP with support for the -HTTP/1.1, HTTP/2 and Websocket protocols. - -Cowboy aims to provide a complete HTTP stack. This includes -the implementation of the HTTP RFCs but also any directly -related standards, like Websocket or Server-Sent Events. - -== Modules - -Functions: - -* link:man:cowboy(3)[cowboy(3)] - Listener management -* link:man:cowboy_req(3)[cowboy_req(3)] - Request and response -* link:man:cowboy_router(3)[cowboy_router(3)] - Router -* link:man:cowboy_constraints(3)[cowboy_constraints(3)] - Constraints - -Protocols: - -* link:man:cowboy_http(3)[cowboy_http(3)] - HTTP/1.1 -* link:man:cowboy_http2(3)[cowboy_http2(3)] - HTTP/2 -* link:man:cowboy_websocket(3)[cowboy_websocket(3)] - Websocket - -Handlers: - -* link:man:cowboy_static(3)[cowboy_static(3)] - Static file handler - -Stream handlers: - -* link:man:cowboy_stream_h(3)[cowboy_stream_h(3)] - Default stream handler -* link:man:cowboy_compress_h(3)[cowboy_compress_h(3)] - Compress stream handler -* link:man:cowboy_metrics_h(3)[cowboy_metrics_h(3)] - Metrics stream handler -* link:man:cowboy_tracer_h(3)[cowboy_tracer_h(3)] - Tracer stream handler - -Behaviors: - -* link:man:cowboy_handler(3)[cowboy_handler(3)] - Plain HTTP handlers -* link:man:cowboy_loop(3)[cowboy_loop(3)] - Loop handlers -* link:man:cowboy_middleware(3)[cowboy_middleware(3)] - Middlewares -* link:man:cowboy_rest(3)[cowboy_rest(3)] - REST handlers -* link:man:cowboy_stream(3)[cowboy_stream(3)] - Stream handlers -* link:man:cowboy_websocket(3)[cowboy_websocket(3)] - Websocket handlers - -Middlewares: - -* link:man:cowboy_router(3)[cowboy_router(3)] - Router middleware -* link:man:cowboy_handler(3)[cowboy_handler(3)] - Handler middleware - -// @todo http_status_codes is not linked to; what to do with it? - -== Dependencies - -* link:man:ranch(7)[ranch(7)] - Socket acceptor pool for TCP protocols -* link:man:cowlib(7)[cowlib(7)] - Support library for manipulating Web protocols -* ssl - Secure communication over sockets -* crypto - Crypto functions - -All these applications must be started before the `cowboy` -application. To start Cowboy and all dependencies at once: - -[source,erlang] ----- -{ok, _} = application:ensure_all_started(cowboy). ----- - -== Environment - -The `cowboy` application does not define any application -environment configuration parameters. - -== See also - -link:man:ranch(7)[ranch(7)], -link:man:cowlib(7)[cowlib(7)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_compress_h.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_compress_h.asciidoc deleted file mode 100644 index 31a916298f..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_compress_h.asciidoc +++ /dev/null @@ -1,68 +0,0 @@ -= cowboy_compress_h(3) - -== Name - -cowboy_compress_h - Compress stream handler - -== Description - -The module `cowboy_compress_h` compresses response bodies -automatically when the client supports it. It will not -try to compress responses that already have a content -encoding. - -Normal responses will only be compressed when their -size is lower than the configured threshold. Streamed -responses are always compressed, including when the -sendfile command is used. Because the file must be -read in memory to be compressed, this module is *not* -suitable for automatically compressing large files. - -== Options - -[source,erlang] ----- -opts() :: #{ - compress_buffering => boolean(), - compress_threshold => non_neg_integer() -} ----- - -Configuration for the compress stream handler. - -The default value is given next to the option name: - -compress_buffering (false):: - -Whether the output will be buffered. By default no -buffering is done to provide maximum compatibility -at the cost of a lower compression rate. -+ -This option can be updated at any time using the -`set_options` stream handler command. - -compress_threshold (300):: - -How large the response body must be to be compressed -when the response isn't streamed. -+ -This option can be updated at any time using the -`set_options` stream handler command. - -== Events - -The compress stream handler does not produce any event. - -== Changelog - -* *2.6*: The options `compress_buffering` and - `compress_threshold` were added. -* *2.0*: Module introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_stream(3)[cowboy_stream(3)], -link:man:cowboy_metrics_h(3)[cowboy_metrics_h(3)], -link:man:cowboy_stream_h(3)[cowboy_stream_h(3)], -link:man:cowboy_tracer_h(3)[cowboy_tracer_h(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.asciidoc deleted file mode 100644 index 52ee664aae..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.asciidoc +++ /dev/null @@ -1,60 +0,0 @@ -= cowboy_constraints(3) - -== Name - -cowboy_constraints - Constraints - -== Description - -The module `cowboy_constraints` defines the built-in -constraints in Cowboy and provides an interface for -manipulating these constraints. - -Constraints are functions that define what type of -input is allowed. They are used throughout Cowboy, -from the router to query strings to cookies. - -== Exports - -Built-in constraints: - -* link:man:cowboy_constraints:int(3)[cowboy_constraints:int(3)] - Integer constraint -* link:man:cowboy_constraints:nonempty(3)[cowboy_constraints:nonempty(3)] - Non-empty constraint - -== Types - -=== constraint() - -[source,erlang] ----- -constraint() :: int | nonempty | fun() ----- - -A constraint function. - -The atom constraints are built-in, see the corresponding -function in the exports list above. - -=== reason() - -[source,erlang] ----- -reason() :: {constraint(), Reason, Value} - -Reason :: any() -Value :: any() ----- - -Reason for the constraint failure. - -It includes the constraint function in question, -a machine-readable error reason and the value that -made the constraint fail. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy(3)[cowboy(3)], -link:man:cowboy_router(3)[cowboy_router(3)], -link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)], -link:man:cowboy_req:match_qs(3)[cowboy_req:match_qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.int.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.int.asciidoc deleted file mode 100644 index 28855a4802..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.int.asciidoc +++ /dev/null @@ -1,63 +0,0 @@ -= cowboy_constraints:int(3) - -== Name - -cowboy_constraints:int - Integer constraint - -== Description - -Constraint functions implement a number of different operations. - -[source,erlang] ----- -int(forward, Bin) -> {ok, Int} | {error, not_an_integer} - -Bin :: binary() -Int :: integer() ----- - -Validate and convert the text representation of an integer. - -[source,erlang] ----- -int(reverse, Int) -> {ok, Bin} | {error, not_an_integer} ----- - -Convert an integer back to its text representation. - -[source,erlang] ----- -int(format_error, Error) -> HumanReadable - -Error :: {not_an_integer, Bin | Int} -HumanReadable :: iolist() ----- - -Generate a human-readable error message. - -== Arguments - -Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument. - -== Return value - -The return value varies depending on the operation. - -== Changelog - -* *2.0*: Interface modified to allow for a variety of operations. -* *1.0*: Constraint introduced. - -== Examples - -This function is not meant to be called directly. - -== See also - -link:man:cowboy_constraints(3)[cowboy_constraints(3)], -link:man:cowboy_constraints:nonempty(3)[cowboy_constraints:nonempty(3)], -link:man:cowboy_router(3)[cowboy_router(3)], -link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)], -link:man:cowboy_req:match_qs(3)[cowboy_req:match_qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.nonempty.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.nonempty.asciidoc deleted file mode 100644 index 0c25b4bb91..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_constraints.nonempty.asciidoc +++ /dev/null @@ -1,62 +0,0 @@ -= cowboy_constraints:nonempty(3) - -== Name - -cowboy_constraints:nonempty - Non-empty constraint - -== Description - -Constraint functions implement a number of different operations. - -[source,erlang] ----- -nonempty(forward | reverse, <<>>) -> {error, empty} ----- - -Reject empty values. - -[source,erlang] ----- -nonempty(forward | reverse, Bin) -> {ok, Bin} - -Bin :: binary() ----- - -Accept any other binary values. - -[source,erlang] ----- -nonempty(format_error, Error) -> HumanReadable - -Error :: {empty, Bin} -HumanReadable :: iolist() ----- - -Generate a human-readable error message. - -== Arguments - -Arguments vary depending on the operation. Constraint -functions always take the operation type as first argument, -and the value as second argument. - -== Return value - -The return value varies depending on the operation. - -== Changelog - -* *2.0*: Interface modified to allow for a variety of operations. -* *1.0*: Constraint introduced. - -== Examples - -This function is not meant to be called directly. - -== See also - -link:man:cowboy_constraints(3)[cowboy_constraints(3)], -link:man:cowboy_constraints:int(3)[cowboy_constraints:int(3)], -link:man:cowboy_router(3)[cowboy_router(3)], -link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)], -link:man:cowboy_req:match_qs(3)[cowboy_req:match_qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_handler.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_handler.asciidoc deleted file mode 100644 index 93dad22443..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_handler.asciidoc +++ /dev/null @@ -1,69 +0,0 @@ -= cowboy_handler(3) - -== Name - -cowboy_handler - Plain HTTP handlers - -== Description - -The `cowboy_handler` middleware executes the handler selected -by the router or any other preceding middleware. - -This middleware takes the handler module and initial state -from the `handler` and `handler_opts` environment values, -respectively. On completion, it adds a `result` value to -the middleware environment, containing the return value -of the `terminate/3` callback (if defined) and `ok` otherwise. - -This module also defines a callback interface for handling -HTTP requests. - -== Callbacks - -Plain HTTP handlers implement the following interface: - -[source,erlang] ----- -init(Req, State) -> {ok, Req, State} - -terminate(Reason, Req, State) -> ok %% optional - -Req :: cowboy_req:req() -State :: any() -Reason :: normal - | {crash, error | exit | throw, any()} ----- - -These two callbacks are common to all handlers. - -Plain HTTP handlers do all their work in the `init/2` -callback. Returning `ok` terminates the handler. If no -response is sent, Cowboy will send a `204 No Content`. - -The optional `terminate/3` callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback. - -The following terminate reasons are defined for plain HTTP -handlers: - -normal:: - The connection was closed normally. - -{crash, Class, Reason}:: - A crash occurred in the handler. `Class` and `Reason` can be - used to obtain more information about the crash. The function - `erlang:get_stacktrace/0` can also be called to obtain the - stacktrace of the process when the crash occurred. - -== Exports - -The following function should be called by modules implementing -custom handlers to execute the optional terminate callback: - -* link:man:cowboy_handler:terminate(3)[cowboy_handler:terminate(3)] - Terminate the handler - -== See also - -link:man:cowboy(7)[cowboy(7)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_handler.terminate.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_handler.terminate.asciidoc deleted file mode 100644 index c995ba367f..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_handler.terminate.asciidoc +++ /dev/null @@ -1,64 +0,0 @@ -= cowboy_handler:terminate(3) - -== Name - -cowboy_handler:terminate - Terminate the handler - -== Description - -[source,erlang] ----- -terminate(Reason, PartialReq, State, Handler) -> ok - -Reason :: any() -PartialReq :: map() -State :: any() -Handler :: module() ----- - -Call the optional terminate callback if it is defined. - -Make sure to use this function at the end of the execution -of modules that implement custom handler behaviors. - -== Arguments - -Reason:: - -Reason for termination. - -PartialReq:: - -The Req object. -+ -It is possible to remove fields from the Req object to save memory -when the handler has no concept of requests/responses. The only -requirement is that a map is provided. - -State:: - -Handler state. - -Handler:: - -Handler module. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Terminate a handler normally -[source,erlang] ----- -cowboy_handler:terminate(normal, Req, State, Handler). ----- - -== See also - -link:man:cowboy_handler(3)[cowboy_handler(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_http.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_http.asciidoc deleted file mode 100644 index 8d89ea2b9d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_http.asciidoc +++ /dev/null @@ -1,173 +0,0 @@ -= cowboy_http(3) - -== Name - -cowboy_http - HTTP/1.1 - -== Description - -The module `cowboy_http` implements HTTP/1.1 and HTTP/1.0 -as a Ranch protocol. - -== Options - -// @todo Might be worth moving cowboy_clear/tls options -// to their respective manual, when they are added. - -[source,erlang] ----- -opts() :: #{ - chunked => boolean(), - connection_type => worker | supervisor, - http10_keepalive => boolean(), - idle_timeout => timeout(), - inactivity_timeout => timeout(), - initial_stream_flow_size => non_neg_integer(), - linger_timeout => timeout(), - logger => module(), - max_empty_lines => non_neg_integer(), - max_header_name_length => non_neg_integer(), - max_header_value_length => non_neg_integer(), - max_headers => non_neg_integer(), - max_keepalive => non_neg_integer(), - max_method_length => non_neg_integer(), - max_request_line_length => non_neg_integer(), - max_skip_body_length => non_neg_integer(), - proxy_header => boolean(), - request_timeout => timeout(), - sendfile => boolean(), - stream_handlers => [module()] -} ----- - -Configuration for the HTTP/1.1 protocol. - -This configuration is passed to Cowboy when starting listeners -using `cowboy:start_clear/3` or `cowboy:start_tls/3` functions. - -It can be updated without restarting listeners using the -Ranch functions `ranch:get_protocol_options/1` and -`ranch:set_protocol_options/2`. - -The default value is given next to the option name: - -chunked (true):: - -Whether chunked transfer-encoding is enabled for HTTP/1.1 connections. -Note that a response streamed to the client without the chunked -transfer-encoding and without a content-length header will result -in the connection being closed at the end of the response body. -+ -This option can be updated at any time using the -`set_options` stream handler command. - -connection_type (supervisor):: - -Whether the connection process also acts as a supervisor. - -http10_keepalive (true):: - -Whether keep-alive is enabled for HTTP/1.0 connections. - -idle_timeout (60000):: - -Time in ms with no data received before Cowboy closes the connection. -+ -This option can be updated at any time using the -`set_options` stream handler command. - -inactivity_timeout (300000):: - -Time in ms with nothing received at all before Cowboy closes the connection. - -initial_stream_flow_size (65535):: - -Amount of data in bytes Cowboy will read from the socket -right after a request was fully received. This is a soft -limit. - -linger_timeout (1000):: - -Time in ms that Cowboy will wait when closing the connection. This is -necessary to avoid the TCP reset problem as described in the -https://tools.ietf.org/html/rfc7230#section-6.6[section 6.6 of RFC7230]. - -logger (error_logger):: - -The module that will be used to write log messages. - -max_empty_lines (5):: - -Maximum number of empty lines before a request. - -max_header_name_length (64):: - -Maximum length of header names. - -max_header_value_length (4096):: - -Maximum length of header values. - -max_headers (100):: - -Maximum number of headers allowed per request. - -max_keepalive (100):: - -Maximum number of requests allowed per connection. - -max_method_length (32):: - -Maximum length of the method. - -max_request_line_length (8000):: - -Maximum length of the request line. - -max_skip_body_length (1000000):: - -Maximum length Cowboy is willing to skip when the user code did not read the body fully. -When the remaining length is too large or unknown Cowboy will close the connection. - -proxy_header (false):: - -Whether incoming connections have a PROXY protocol header. The -proxy information will be passed forward via the `proxy_header` -key of the Req object. - -request_timeout (5000):: - -Time in ms with no requests before Cowboy closes the connection. - -sendfile (true):: - -Whether the sendfile syscall may be used. It can be useful to disable -it on systems where the syscall has a buggy implementation, for example -under VirtualBox when using shared folders. - -stream_handlers ([cowboy_stream_h]):: - -Ordered list of stream handlers that will handle all stream events. - -== Changelog - -* *2.7*: The `initial_stream_flow_size` and `logger` options were added. -* *2.6*: The `chunked`, `http10_keepalive`, `proxy_header` and `sendfile` options were added. -* *2.5*: The `linger_timeout` option was added. -* *2.2*: The `max_skip_body_length` option was added. -* *2.0*: The `timeout` option was renamed `request_timeout`. -* *2.0*: The `idle_timeout`, `inactivity_timeout` and `shutdown_timeout` options were added. -* *2.0*: The `max_method_length` option was added. -* *2.0*: The `max_request_line_length` default was increased from 4096 to 8000. -* *2.0*: The `connection_type` option was added. -* *2.0*: The `env` option is now a map instead of a proplist. -* *2.0*: The `stream_handlers` option was added. -* *2.0*: The `compress` option was removed in favor of the `cowboy_compress_h` stream handler. -* *2.0*: Options are now a map instead of a proplist. -* *2.0*: Protocol introduced. Replaces `cowboy_protocol`. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_http2(3)[cowboy_http2(3)], -link:man:cowboy_websocket(3)[cowboy_websocket(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_http2.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_http2.asciidoc deleted file mode 100644 index ccd3bb377c..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_http2.asciidoc +++ /dev/null @@ -1,257 +0,0 @@ -= cowboy_http2(3) - -== Name - -cowboy_http2 - HTTP/2 - -== Description - -The module `cowboy_http2` implements HTTP/2 -as a Ranch protocol. - -== Options - -// @todo Might be worth moving cowboy_clear/tls/stream_h options -// to their respective manual, when they are added. - -[source,erlang] ----- -opts() :: #{ - connection_type => worker | supervisor, - connection_window_margin_size => 0..16#7fffffff, - connection_window_update_threshold => 0..16#7fffffff, - enable_connect_protocol => boolean(), - idle_timeout => timeout(), - inactivity_timeout => timeout(), - initial_connection_window_size => 65535..16#7fffffff, - initial_stream_window_size => 0..16#7fffffff, - logger => module(), - max_concurrent_streams => non_neg_integer() | infinity, - max_connection_buffer_size => non_neg_integer(), - max_connection_window_size => 0..16#7fffffff, - max_decode_table_size => non_neg_integer(), - max_encode_table_size => non_neg_integer(), - max_frame_size_received => 16384..16777215, - max_frame_size_sent => 16384..16777215 | infinity, - max_received_frame_rate => {pos_integer(), timeout()}, - max_reset_stream_rate => {pos_integer(), timeout()}, - max_stream_buffer_size => non_neg_integer(), - max_stream_window_size => 0..16#7fffffff, - preface_timeout => timeout(), - proxy_header => boolean(), - sendfile => boolean(), - settings_timeout => timeout(), - stream_handlers => [module()], - stream_window_data_threshold => 0..16#7fffffff, - stream_window_margin_size => 0..16#7fffffff, - stream_window_update_threshold => 0..16#7fffffff -} ----- - -Configuration for the HTTP/2 protocol. - -This configuration is passed to Cowboy when starting listeners -using `cowboy:start_clear/3` or `cowboy:start_tls/3` functions. - -It can be updated without restarting listeners using the -Ranch functions `ranch:get_protocol_options/1` and -`ranch:set_protocol_options/2`. - -The default value is given next to the option name: - -connection_type (supervisor):: - -Whether the connection process also acts as a supervisor. - -connection_window_margin_size (65535):: - -Extra amount in bytes to be added to the window size when -updating the connection window. This is used to -ensure that there is always some space available in -the window. - -connection_window_update_threshold (163840):: - -The connection window will only get updated when its size -becomes lower than this threshold, in bytes. This is to -avoid sending too many `WINDOW_UPDATE` frames. - -enable_connect_protocol (false):: - -Whether to enable the extended CONNECT method to allow -protocols like Websocket to be used over an HTTP/2 stream. -This option is experimental and disabled by default. - -idle_timeout (60000):: - -Time in ms with no data received before Cowboy closes the connection. - -inactivity_timeout (300000):: - -Time in ms with nothing received at all before Cowboy closes the connection. - -initial_connection_window_size (65535):: - -Initial window size in bytes for the connection. This is the total amount -of data (from request bodies for example) that may be buffered -by the connection across all streams before the user code -explicitly requests it. -+ -Note that this value cannot be lower than the default. - -initial_stream_window_size (65535):: - -Initial window size in bytes for new streams. This is the total amount -of data (from request bodies for example) that may be buffered -by a single stream before the user code explicitly requests it. - -logger (error_logger):: - -The module that will be used to write log messages. - -max_concurrent_streams (infinity):: - -Maximum number of concurrent streams allowed on the connection. - -max_connection_buffer_size (16000000):: - -Maximum size of all stream buffers for this connection, in bytes. -This is a soft limit used to apply backpressure to handlers that -send data faster than the HTTP/2 connection allows. - -max_connection_window_size (16#7fffffff):: - -Maximum connection window size in bytes. This is used as an upper bound -when calculating the window size, either when reading the request -body or receiving said body. - -max_decode_table_size (4096):: - -Maximum header table size in bytes used by the decoder. This is the value -advertised to the client. The client can then choose a header table size -equal or lower to the advertised value. - -max_encode_table_size (4096):: - -Maximum header table size in bytes used by the encoder. The server will -compare this value to what the client advertises and choose the smallest -one as the encoder's header table size. - -max_frame_size_received (16384):: - -Maximum size in bytes of the frames received by the server. This value is -advertised to the remote endpoint which can then decide to use -any value lower or equal for its frame sizes. - -max_frame_size_sent (infinity):: - -Maximum size in bytes of the frames sent by the server. This option allows -setting an upper limit to the frame sizes instead of blindly -following the client's advertised maximum. -+ -Note that actual frame sizes may be lower than the limit when -there is not enough space left in the flow control window. - -max_received_frame_rate ({1000, 10000}):: - -Maximum frame rate allowed per connection. The rate is expressed -as a tuple `{NumFrames, TimeMs}` indicating how many frames are -allowed over the given time period. This is similar to a supervisor -restart intensity/period. - -max_reset_stream_rate ({10, 10000}):: - -Maximum reset stream rate per connection. This can be used to -protect against misbehaving or malicious peers that do not follow -the protocol, leading to the server resetting streams, by limiting -the number of streams that can be reset over a certain time period. -The rate is expressed as a tuple `{NumResets, TimeMs}`. This is -similar to a supervisor restart intensity/period. - -max_stream_buffer_size (8000000):: - -Maximum stream buffer size in bytes. This is a soft limit used -to apply backpressure to handlers that send data faster than -the HTTP/2 connection allows. - -max_stream_window_size (16#7fffffff):: - -Maximum stream window size in bytes. This is used as an upper bound -when calculating the window size, either when reading the request -body or receiving said body. - -preface_timeout (5000):: - -Time in ms Cowboy is willing to wait for the connection preface. - -proxy_header (false):: - -Whether incoming connections have a PROXY protocol header. The -proxy information will be passed forward via the `proxy_header` -key of the Req object. - -sendfile (true):: - -Whether the sendfile syscall may be used. It can be useful to disable -it on systems where the syscall has a buggy implementation, for example -under VirtualBox when using shared folders. - -settings_timeout (5000):: - -Time in ms Cowboy is willing to wait for a SETTINGS ack. - -stream_handlers ([cowboy_stream_h]):: - -Ordered list of stream handlers that will handle all stream events. - -stream_window_data_threshold (16384):: - -Window threshold in bytes below which Cowboy will not attempt -to send data, with one exception. When Cowboy has data to send -and the window is high enough, Cowboy will always send the data, -regardless of this option. - -stream_window_margin_size (65535):: - -Extra amount in bytes to be added to the window size when -updating a stream's window. This is used to -ensure that there is always some space available in -the window. - -stream_window_update_threshold (163840):: - -A stream's window will only get updated when its size -becomes lower than this threshold, in bytes. This is to avoid sending -too many `WINDOW_UPDATE` frames. - -== Changelog - -* *2.7*: Add the options `connection_window_margin_size`, - `connection_window_update_threshold`, - `max_connection_window_size`, `max_stream_window_size`, - `stream_window_margin_size` and - `stream_window_update_threshold` to configure - behavior on sending WINDOW_UPDATE frames; - `max_connection_buffer_size` and - `max_stream_buffer_size` to apply backpressure - when sending data too fast; - `max_received_frame_rate` and `max_reset_stream_rate` - to protect against various flood scenarios; and - `stream_window_data_threshold` to control how small - the DATA frames that Cowboy sends can get. -* *2.7*: The `logger` option was added. -* *2.6*: The `proxy_header` and `sendfile` options were added. -* *2.4*: Add the options `initial_connection_window_size`, - `initial_stream_window_size`, `max_concurrent_streams`, - `max_decode_table_size`, `max_encode_table_size`, - `max_frame_size_received`, `max_frame_size_sent` - and `settings_timeout` to configure HTTP/2 SETTINGS - and related behavior. -* *2.4*: Add the experimental option `enable_connect_protocol`. -* *2.0*: Protocol introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_http(3)[cowboy_http(3)], -link:man:cowboy_websocket(3)[cowboy_websocket(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_loop.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_loop.asciidoc deleted file mode 100644 index 605e265995..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_loop.asciidoc +++ /dev/null @@ -1,80 +0,0 @@ -= cowboy_loop(3) - -== Name - -cowboy_loop - Loop handlers - -== Description - -The module `cowboy_loop` defines a callback interface for -long running HTTP connections. - -You should switch to this behavior for long polling, -server-sent events and similar long-running requests. - -There are generally two usage patterns: - -* Loop until receiving a specific message, then send - a response and stop execution (for example long polling); - -* Or initiate a response in `init/2` and stream the - body in `info/3` as necessary (for example server-sent events). - -== Callbacks - -Loop handlers implement the following interface: - -[source,erlang] ----- -init(Req, State) - -> {cowboy_loop, Req, State} - | {cowboy_loop, Req, State, hibernate} - -info(Info, Req, State) - -> {ok, Req, State} - | {ok, Req, State, hibernate} - | {stop, Req, State} - -terminate(Reason, Req, State) -> ok %% optional - -Req :: cowboy_req:req() -State :: any() -Info :: any() -Reason :: stop - | {crash, error | exit | throw, any()} ----- - -The `init/2` callback is common to all handlers. To switch -to the loop behavior, it must return `cowboy_loop` as the -first element of the tuple. - -The `info/3` callback will be called for every Erlang message -received. It may choose to continue the receive loop or stop -it. - -The optional `terminate/3` callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback. - -The following terminate reasons are defined for loop handlers: - -stop:: - The handler requested to close the connection by returning - a `stop` tuple. - -{crash, Class, Reason}:: - A crash occurred in the handler. `Class` and `Reason` can be - used to obtain more information about the crash. The function - `erlang:get_stacktrace/0` can also be called to obtain the - stacktrace of the process when the crash occurred. - -== Changelog - -* *2.0*: Loop handlers no longer need to handle overflow/timeouts. -* *1.0*: Behavior introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_handler(3)[cowboy_handler(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_metrics_h.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_metrics_h.asciidoc deleted file mode 100644 index c871d57c04..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_metrics_h.asciidoc +++ /dev/null @@ -1,164 +0,0 @@ -= cowboy_metrics_h(3) - -== Name - -cowboy_metrics_h - Metrics stream handler - -== Description - -The module `cowboy_metrics_h` gathers metrics and -other information about a stream. It then calls -the configured callback with this data. - -== Types - -=== metrics() - -[source,erlang] ----- -metrics() :: #{ - %% The identifier for this listener. - ref := ranch:ref(), - - %% The pid for this connection. - pid := pid(), - - %% The streamid also indicates the total number of requests on - %% this connection (StreamID div 2 + 1). - streamid := cowboy_stream:streamid(), - - %% The terminate reason is always useful. - reason := cowboy_stream:reason(), - - %% A filtered Req object or a partial Req object - %% depending on how far the request got to. - req => cowboy_req:req(), - partial_req => cowboy_stream:partial_req(), - - %% Response status. - resp_status := cowboy:http_status(), - - %% Filtered response headers. - resp_headers := cowboy:http_headers(), - - %% Start/end of the processing of the request. - %% - %% This represents the time from this stream handler's init - %% to terminate. - req_start => integer(), - req_end => integer(), - - %% Start/end of the receiving of the request body. - %% Begins when the first packet has been received. - req_body_start => integer(), - req_body_end => integer(), - - %% Start/end of the sending of the response. - %% Begins when we send the headers and ends on the final - %% packet of the response body. If everything is sent at - %% once these values are identical. - resp_start => integer(), - resp_end => integer(), - - %% For early errors all we get is the time we received it. - early_error_time => integer(), - - %% Start/end of spawned processes. This is where most of - %% the user code lies, excluding stream handlers. On a - %% default Cowboy configuration there should be only one - %% process: the request process. - procs => ProcMetrics, - - %% Informational responses sent before the final response. - informational => [InformationalMetrics], - - %% Length of the request and response bodies. This does - %% not include the framing. - req_body_length => non_neg_integer(), - resp_body_length => non_neg_integer(), - - %% Additional metadata set by the user. - user_data => map() -} - -InformationalMetrics :: #{ - %% Informational response status. - status := cowboy:http_status(), - - %% Headers sent with the informational response. - headers := cowboy:http_headers(), - - %% Time when the informational response was sent. - time := integer() -} - -ProcMetrics :: #{pid() => #{ - %% Time at which the process spawned. - spawn := integer(), - - %% Time at which the process exited. - exit => integer(), - - %% Reason for the process exit. - reason => any() -}} ----- - -Metrics given to the callback function. - -Depending on the life of the stream the metrics may include -more or less information. - -The `set_options` command can be used to add additional -metadata in the `user_data` metric. This can be used for -example to add the handler module which was selected by -the router. The option to be set is `metrics_user_data`. -It takes a map which will be merged in the existing -`user_data` map. - -== Options - -[source,erlang] ----- -opts() :: #{ - metrics_callback => fun((metrics()) -> any()), - metrics_req_filter => fun((cowboy_req:req()) -> map()), - metrics_resp_headers_filter => fun((cowboy:http_headers()) -> cowboy:http_headers()) -} ----- - -Configuration for the metrics stream handler. - -metrics_callback - mandatory:: - -The function that will be called upon completion -of the stream. It only takes a single argument, -the `metrics()`. - -metrics_req_filter:: - -A function applied to the Req to compact it and -only keep required information. By default no -filtering is done. - -metrics_resp_headers_filter:: - -A function applied to the response headers to -filter them and only keep required information. -By default no filtering is done. - -== Events - -The metrics stream handler does not produce any event. - -== Changelog - -* *2.7*: Module introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_stream(3)[cowboy_stream(3)], -link:man:cowboy_compress_h(3)[cowboy_compress_h(3)], -link:man:cowboy_stream_h(3)[cowboy_stream_h(3)], -link:man:cowboy_tracer_h(3)[cowboy_tracer_h(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_middleware.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_middleware.asciidoc deleted file mode 100644 index 180fb0ae42..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_middleware.asciidoc +++ /dev/null @@ -1,77 +0,0 @@ -= cowboy_middleware(3) - -== Name - -cowboy_middleware - Middlewares - -== Description - -The module `cowboy_middleware` defines a callback interface for -Cowboy middlewares. - -Middlewares process the request sequentially in the order they -are configured. - -== Callbacks - -Middlewares implement the following interface: - -[source,erlang] ----- -execute(Req, Env) - -> {ok, Req, Env} - | {suspend, module(), atom(), [any()]} - | {stop, Req} - -Req :: cowboy_req:req() -Env :: cowboy_middleware:env() ----- - -The `execute/2` is the only callback that needs to be -implemented. It must execute the middleware and return -with instructions for Cowboy. - -ok:: - -Cowboy should continue processing the request using the -returned Req object and environment. - -suspend:: - -Cowboy will hibernate the process. When resuming, Cowboy -will apply the returned module, function and arguments. - -stop:: - -Cowboy will stop middleware execution. No other middleware -will be executed. This effectively ends the processing of -the request. - -// @todo No need to return the Req when stopping. Fix in 3.0. - -== Types - -=== env() - -[source,erlang] ----- -env() :: #{atom() => any()} ----- - -Middleware environment. - -A new environment is created for every request. The initial -environment contained the user configured environment values -(like `dispatch` for example) plus the `listener` value which -contains the name of the listener for this connection. - -Middlewares may modify the environment as necessary. - -== Changelog - -* *2.0*: The `env` type is now a map instead of a proplist. -* *1.0*: Behavior introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.asciidoc deleted file mode 100644 index 0a1ca1ba13..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.asciidoc +++ /dev/null @@ -1,205 +0,0 @@ -= cowboy_req(3) - -== Name - -cowboy_req - HTTP request and response - -== Description - -The module `cowboy_req` provides functions to access, manipulate -and respond to requests. - -There are four types of functions in this module. They can be -differentiated by their name and their return type: - -[options="header"] -|=== -| Type | Name pattern | Return type -| access | no verb, parse_*, match_* | `Value` -| question | has_* | `boolean()` -| modification | set_* | `Req` -| action | any other verb | `ok \| {Result, Value, Req}` -|=== - -Any `Req` returned must be used in place of the one passed as -argument. Functions that perform an action in particular write -state in the Req object to make sure you are using the function -correctly. For example, it's only possible to send one response, -and to read the body once. - -== Exports - -Connection: - -* link:man:cowboy_req:peer(3)[cowboy_req:peer(3)] - Peer address and port -* link:man:cowboy_req:sock(3)[cowboy_req:sock(3)] - Socket address and port -* link:man:cowboy_req:cert(3)[cowboy_req:cert(3)] - Client TLS certificate - -Raw request: - -* link:man:cowboy_req:method(3)[cowboy_req:method(3)] - HTTP method -* link:man:cowboy_req:version(3)[cowboy_req:version(3)] - HTTP version -* link:man:cowboy_req:scheme(3)[cowboy_req:scheme(3)] - URI scheme -* link:man:cowboy_req:host(3)[cowboy_req:host(3)] - URI host name -* link:man:cowboy_req:port(3)[cowboy_req:port(3)] - URI port number -* link:man:cowboy_req:path(3)[cowboy_req:path(3)] - URI path -* link:man:cowboy_req:qs(3)[cowboy_req:qs(3)] - URI query string -* link:man:cowboy_req:uri(3)[cowboy_req:uri(3)] - Reconstructed URI -* link:man:cowboy_req:header(3)[cowboy_req:header(3)] - HTTP header -* link:man:cowboy_req:headers(3)[cowboy_req:headers(3)] - HTTP headers - -Processed request: - -* link:man:cowboy_req:parse_qs(3)[cowboy_req:parse_qs(3)] - Parse the query string -* link:man:cowboy_req:match_qs(3)[cowboy_req:match_qs(3)] - Match the query string against constraints -* link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(3)] - Parse the given HTTP header -* link:man:cowboy_req:filter_cookies(3)[cowboy_req:filter_cookies(3)] - Filter cookie headers -* link:man:cowboy_req:parse_cookies(3)[cowboy_req:parse_cookies(3)] - Parse cookie headers -* link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)] - Match cookies against constraints -* link:man:cowboy_req:binding(3)[cowboy_req:binding(3)] - Access a value bound from the route -* link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)] - Access all values bound from the route -* link:man:cowboy_req:host_info(3)[cowboy_req:host_info(3)] - Access the route's heading host segments -* link:man:cowboy_req:path_info(3)[cowboy_req:path_info(3)] - Access the route's trailing path segments - -Request body: - -* link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)] - Is there a request body? -* link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)] - Body length -* link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)] - Read the request body -* link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)] - Read and parse a urlencoded request body -* link:man:cowboy_req:read_and_match_urlencoded_body(3)[cowboy_req:read_and_match_urlencoded_body(3)] - Read, parse and match a urlencoded request body against constraints -* link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)] - Read the next multipart headers -* link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] - Read the current part's body - -Response: - -* link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)] - Set a cookie -* link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)] - Set a response header -* link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)] - Set several response headers -* link:man:cowboy_req:has_resp_header(3)[cowboy_req:has_resp_header(3)] - Is the given response header set? -* link:man:cowboy_req:resp_header(3)[cowboy_req:resp_header(3)] - Response header -* link:man:cowboy_req:resp_headers(3)[cowboy_req:resp_headers(3)] - Response headers -* link:man:cowboy_req:delete_resp_header(3)[cowboy_req:delete_resp_header(3)] - Delete a response header -* link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)] - Set the response body -* link:man:cowboy_req:has_resp_body(3)[cowboy_req:has_resp_body(3)] - Is there a response body? -* link:man:cowboy_req:inform(3)[cowboy_req:inform(3)] - Send an informational response -* link:man:cowboy_req:reply(3)[cowboy_req:reply(3)] - Send the response -* link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] - Send the response headers -* link:man:cowboy_req:stream_body(3)[cowboy_req:stream_body(3)] - Stream the response body -* link:man:cowboy_req:stream_events(3)[cowboy_req:stream_events(3)] - Stream events -* link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)] - Send the response trailers -* link:man:cowboy_req:push(3)[cowboy_req:push(3)] - Push a resource to the client - -Stream handlers: - -* link:man:cowboy_req:cast(3)[cowboy_req:cast(3)] - Cast a stream handler event - -== Types - -=== push_opts() - -[source,erlang] ----- -push_opts() :: #{ - method => binary(), %% case sensitive - scheme => binary(), %% lowercase; case insensitive - host => binary(), %% lowercase; case insensitive - port => inet:port_number(), - qs => binary() %% case sensitive -} ----- - -Push options. - -By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request's URI. - -=== read_body_opts() - -[source,erlang] ----- -read_body_opts() :: #{ - length => non_neg_integer(), - period => non_neg_integer(), - timeout => timeout() -} ----- - -Body reading options. - -The defaults are function-specific. - -=== req() - -[source,erlang] ----- -req() :: #{ - method := binary(), %% case sensitive - version := cowboy:http_version() | atom(), - scheme := binary(), %% lowercase; case insensitive - host := binary(), %% lowercase; case insensitive - port := inet:port_number(), - path := binary(), %% case sensitive - qs := binary(), %% case sensitive - headers := cowboy:http_headers(), - peer := {inet:ip_address(), inet:port_number()}, - sock := {inet:ip_address(), inet:port_number()}, - cert := binary() | undefined -} ----- - -The Req object. - -Contains information about the request and response. While -some fields are publicly documented, others aren't and shouldn't -be used. - -You may add custom fields if required. Make sure to namespace -them by prepending an underscore and the name of your application: - -.Setting a custom field -[source,erlang] ----- -Req#{'_myapp_auth_method' => pubkey}. ----- - -=== resp_body() - -[source,erlang] ----- -resp_body() :: iodata() - | {sendfile, Offset, Length, Filename} - -Offset :: non_neg_integer() -Length :: non_neg_integer() -Filename :: file:name_all() ----- - -Response body. - -It can take two forms: the actual data to be sent or a -tuple indicating which file to send. - -When sending data directly, the type is either a binary or -an iolist. Iolists are an efficient way to build output. -Instead of concatenating strings or binaries, you can simply -build a list containing the fragments you want to send in the -order they should be sent: - -.Example iolists usage -[source,erlang] ----- -1> RespBody = ["Hello ", [<<"world">>, $!]]. -["Hello ",[<<"world">>,33]] -2> io:format("~s~n", [RespBody]). -Hello world! ----- - -Note that the length must be greater than zero for any data -to be sent. Cowboy will send an empty body when the length -is zero. - -== See also - -link:man:cowboy(7)[cowboy(7)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.binding.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.binding.asciidoc deleted file mode 100644 index 02f8209945..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.binding.asciidoc +++ /dev/null @@ -1,68 +0,0 @@ -= cowboy_req:binding(3) - -== Name - -cowboy_req:binding - Access a value bound from the route - -== Description - -[source,erlang] ----- -binding(Name, Req) -> binding(Name, Req, undefined) -binding(Name, Req, Default) -> any() | Default - -Name :: atom() -Req :: cowboy_req:req() -Default :: any() ----- - -Return the value for the given binding. - -== Arguments - -Name:: - -Desired binding name as an atom. - -Req:: - -The Req object. - -Default:: - -Default value returned when the binding is missing. - -== Return value - -By default the value is a case sensitive binary string, however -constraints may change the type of this value (for example -automatically converting numbers to integer). - -== Changelog - -* *2.0*: Only the value is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the username from the path -[source,erlang] ----- -%% Route is "/users/:user" -Username = cowboy_req:binding(user, Req). ----- - -.Get the branch name, with a default -[source,erlang] ----- -%% Route is "/log[/:branch]" -Branch = cowboy_req:binding(branch, Req, <<"master">>) ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)], -link:man:cowboy_req:host_info(3)[cowboy_req:host_info(3)], -link:man:cowboy_req:path_info(3)[cowboy_req:path_info(3)], -link:man:cowboy_router(3)[cowboy_router(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.bindings.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.bindings.asciidoc deleted file mode 100644 index b399e95f67..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.bindings.asciidoc +++ /dev/null @@ -1,47 +0,0 @@ -= cowboy_req:bindings(3) - -== Name - -cowboy_req:bindings - Access all values bound from the route - -== Description - -[source,erlang] ----- -bindings(Req :: cowboy_req:req()) -> cowboy_router:bindings() ----- - -Return a map containing all bindings. - -== Arguments - -Req:: - -The Req object. - -== Return value - -By default values are case sensitive binary strings, however -constraints may change the type of this value (for example -automatically converting numbers to integer). - -== Changelog - -* *2.0*: Only the values are returned, they are no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get all bindings -[source,erlang] ----- -Bindings = cowboy_req:bindings(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:binding(3)[cowboy_req:binding(3)], -link:man:cowboy_req:host_info(3)[cowboy_req:host_info(3)], -link:man:cowboy_req:path_info(3)[cowboy_req:path_info(3)], -link:man:cowboy_router(3)[cowboy_router(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.body_length.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.body_length.asciidoc deleted file mode 100644 index 057ab4cae3..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.body_length.asciidoc +++ /dev/null @@ -1,51 +0,0 @@ -= cowboy_req:body_length(3) - -== Name - -cowboy_req:body_length - Body length - -== Description - -[source,erlang] ----- -body_length(Req :: cowboy_req:req()) -> undefined | non_neg_integer() ----- - -Return the length of the request body. - -The length is not always known before reading the body. -In those cases Cowboy will return `undefined`. The body -length is available after the body has been fully read. - -== Arguments - -Req:: - -The Req object. - -== Return value - -The length of the request body, or `undefined` if it is -not known. - -== Changelog - -* *2.0*: Only the length is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the body length -[source,erlang] ----- -Length = cowboy_req:body_length(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)], -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)], -link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)], -link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)], -link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.cast.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.cast.asciidoc deleted file mode 100644 index d6e018faf3..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.cast.asciidoc +++ /dev/null @@ -1,64 +0,0 @@ -= cowboy_req:cast(3) - -== Name - -cowboy_req:cast - Cast a stream handler event - -== Description - -[source,erlang] ----- -cast(Event :: any(), Req :: cowboy_req:req()) -> ok ----- - -Cast a stream handler event. - -The event will be passed to stream handlers through the -`info/3` callback. - -== Arguments - -Event:: - -The event to be sent to stream handlers. - -Req:: - -The Req object. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.7*: Function introduced. - -== Examples - -.Increase the HTTP/1.1 idle timeout -[source,erlang] ----- -cowboy_req:cast({set_options, #{ - idle_timeout => 3600000 -}}, Req). ----- - -.Add user data to metrics ----- -cowboy_req:cast({set_options, #{ - metrics_user_data => #{handler => ?MODULE} -}}, Req). ----- - -.Enable compression buffering ----- -cowboy_req:cast({set_options, #{ - compress_buffering => true -}}, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_stream(3)[cowboy_stream(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.cert.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.cert.asciidoc deleted file mode 100644 index 51f2e3c5f1..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.cert.asciidoc +++ /dev/null @@ -1,71 +0,0 @@ -= cowboy_req:cert(3) - -== Name - -cowboy_req:cert - Client TLS certificate - -== Description - -[source,erlang] ----- -cert(Req :: cowboy_req:req()) -> binary() | undefined ----- - -Return the peer's TLS certificate. - -Using the default configuration this function will always return -`undefined`. You need to explicitly configure Cowboy to request -the client certificate. To do this you need to set the `verify` -transport option to `verify_peer`: - -[source,erlang] ----- -{ok, _} = cowboy:start_tls(example, [ - {port, 8443}, - {certfile, "path/to/cert.pem"}, - {verify, verify_peer} -], #{ - env => #{dispatch => Dispatch} -}). ----- - -You may also want to customize the `verify_fun` function. Please -consult the `ssl` application's manual for more details. - -TCP connections do not allow a certificate and this function -will therefore always return `undefined`. - -The certificate can also be obtained using pattern matching: - -[source,erlang] ----- -#{cert := Cert} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The client TLS certificate. - -== Changelog - -* *2.1*: Function introduced. - -== Examples - -.Get the client TLS certificate. -[source,erlang] ----- -Cert = cowboy_req:cert(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:peer(3)[cowboy_req:peer(3)], -link:man:cowboy_req:sock(3)[cowboy_req:sock(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.delete_resp_header.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.delete_resp_header.asciidoc deleted file mode 100644 index 0b530bef81..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.delete_resp_header.asciidoc +++ /dev/null @@ -1,58 +0,0 @@ -= cowboy_req:delete_resp_header(3) - -== Name - -cowboy_req:delete_resp_header - Delete a response header - -== Description - -[source,erlang] ----- -delete_resp_header(Name, Req :: cowboy_req:req()) -> Req - -Name :: binary() %% lowercase; case insensitive ----- - -Delete the given response header. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -== Arguments - -Name:: - -Header name as a lowercase binary string. - -Req:: - -The Req object. - -== Return value - -A new Req object is returned. - -The returned Req object must be used from that point onward, -otherwise the header will still be sent in the response. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Remove the content-type header from the response -[source,erlang] ----- -Req = cowboy_req:delete_resp_header(<<"content-type">>, Req0), ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:has_resp_header(3)[cowboy_req:has_resp_header(3)], -link:man:cowboy_req:resp_header(3)[cowboy_req:resp_header(3)], -link:man:cowboy_req:resp_headers(3)[cowboy_req:resp_headers(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.filter_cookies.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.filter_cookies.asciidoc deleted file mode 100644 index 20d0a0c505..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.filter_cookies.asciidoc +++ /dev/null @@ -1,70 +0,0 @@ -= cowboy_req:filter_cookies(3) - -== Name - -cowboy_req:filter_cookies - Filter cookie headers - -== Description - -[source,erlang] ----- -filter_cookies(Names, Req) -> Req - -Names :: [atom() | binary()] ----- - -Filter cookie headers. - -This function is meant to be used before attempting to parse -or match cookies in order to remove cookies that are not -relevant and are potentially malformed. Because Cowboy by -default crashes on malformed cookies, this function allows -processing requests that would otherwise result in a 400 -error. - -Malformed cookies are unfortunately fairly common due to -the string-based interface provided by browsers and this -function provides a middle ground between Cowboy's strict -behavior and chaotic real world use cases. - -Note that there may still be crashes even after filtering -cookies because this function does not correct malformed -values. Cookies that have malformed values should probably -be unset in an error response or in a redirect. - -This function can be called even if there are no cookies -in the request. - -== Arguments - -Names:: - -The cookies that should be kept. - -Req:: - -The Req object. - -== Return value - -The Req object is returned with its cookie header value -filtered. - -== Changelog - -* *2.7*: Function introduced. - -== Examples - -.Filter then parse cookies -[source,erlang] ----- -Req = cowboy_req:filter_cookies([session_id, token], Req0), -Cookies = cowboy_req:parse_cookies(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:parse_cookies(3)[cowboy_req:parse_cookies(3)], -link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_body.asciidoc deleted file mode 100644 index 5e985b141d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_body.asciidoc +++ /dev/null @@ -1,45 +0,0 @@ -= cowboy_req:has_body(3) - -== Name - -cowboy_req:has_body - Is there a request body? - -== Description - -[source,erlang] ----- -has_body(Req :: cowboy_req:req()) -> boolean() ----- - -Return whether the request has a body. - -== Arguments - -Req:: - -The Req object. - -== Return value - -A boolean indicating whether the request has a body. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Ensure the request has a body -[source,erlang] ----- -true = cowboy_req:has_body(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)], -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)], -link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)], -link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)], -link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_resp_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_resp_body.asciidoc deleted file mode 100644 index d6b9068282..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_resp_body.asciidoc +++ /dev/null @@ -1,48 +0,0 @@ -= cowboy_req:has_resp_body(3) - -== Name - -cowboy_req:has_resp_body - Is there a response body? - -== Description - -[source,erlang] ----- -has_resp_body(Req :: cowboy_req:req()) -> boolean() ----- - -Return whether a response body has been set. - -== Arguments - -Req:: - -The Req object. - -== Return value - -A boolean indicating whether a response body has been set. - -This function will return `false` when an empty response -body has been set. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Check whether a body has been set -[source,erlang] ----- -false = cowboy_req:has_resp_body(Req0), -Req1 = cowboy_req:set_resp_body(<<"Hello!">>, Req0), -true = cowboy_req:has_resp_body(Req1), -Req = cowboy_req:set_resp_body(<<>>, Req1), -false = cowboy_req:has_resp_body(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_resp_header.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_resp_header.asciidoc deleted file mode 100644 index b8f1ece7d8..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.has_resp_header.asciidoc +++ /dev/null @@ -1,57 +0,0 @@ -= cowboy_req:has_resp_header(3) - -== Name - -cowboy_req:has_resp_header - Is the given response header set? - -== Description - -[source,erlang] ----- -has_resp_header(Name, Req :: cowboy_req:req()) -> boolean() - -Name :: binary() %% lowercase; case insensitive ----- - -Return whether the given response header has been set. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -== Arguments - -Name:: - -Header name as a lowercase binary string. - -Req:: - -The Req object. - -== Return value - -A boolean indicating whether the given response header has been set. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Check whether the content-type header has been set -[source,erlang] ----- -false = cowboy_req:has_resp_header(<<"content-type">>, Req0), -Req = cowboy_req:set_resp_header(<<"content-type">>, <<"text/html">>, Req0), -true = cowboy_req:has_resp_header(<<"content-type">>, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:resp_header(3)[cowboy_req:resp_header(3)], -link:man:cowboy_req:resp_headers(3)[cowboy_req:resp_headers(3)], -link:man:cowboy_req:delete_resp_header(3)[cowboy_req:delete_resp_header(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.header.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.header.asciidoc deleted file mode 100644 index f53890ff8b..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.header.asciidoc +++ /dev/null @@ -1,76 +0,0 @@ -= cowboy_req:header(3) - -== Name - -cowboy_req:header - HTTP header - -== Description - -[source,erlang] ----- -header(Name, Req) -> header(Name, Req, undefined) -header(Name, Req, Default) -> binary() | Default - -Name :: binary() %% lowercase; case insensitive -Req :: cowboy_req:req() -Default :: any() ----- - -Return the value for the given HTTP header. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -Headers can also be obtained using pattern matching: - -[source,erlang] ----- -#{headers := #{Name := Value}} = Req. ----- - -Note that this snippet will crash if the header is missing. - -== Arguments - -Name:: - -Desired HTTP header name as a lowercase binary string. - -Req:: - -The Req object. - -Default:: - -Default value returned when the header is missing. - -== Return value - -The header value is returned as a binary string. When the -header is missing, the default argument is returned. - -== Changelog - -* *2.0*: Only the header value is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the accept header -[source,erlang] ----- -Accept = cowboy_req:header(<<"accept">>, Req). ----- - -.Get the content-length header with a default value -[source,erlang] ----- -Length = cowboy_req:header(<<"content-length">>, Req, <<"0">>). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:headers(3)[cowboy_req:headers(3)], -link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.headers.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.headers.asciidoc deleted file mode 100644 index c370f6d294..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.headers.asciidoc +++ /dev/null @@ -1,51 +0,0 @@ -= cowboy_req:headers(3) - -== Name - -cowboy_req:headers - HTTP headers - -== Description - -[source,erlang] ----- -headers(Req :: cowboy_req:req()) -> cowboy:http_headers() ----- - -Return all request headers. - -Request headers can also be obtained using pattern matching: - -[source,erlang] ----- -#{headers := Headers} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings. - -== Changelog - -* *2.0*: Only the headers are returned, they are no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get all headers -[source,erlang] ----- -Headers = cowboy_req:headers(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:header(3)[cowboy_req:header(3)], -link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.host.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.host.asciidoc deleted file mode 100644 index 2c512e2c1c..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.host.asciidoc +++ /dev/null @@ -1,52 +0,0 @@ -= cowboy_req:host(3) - -== Name - -cowboy_req:host - URI host name - -== Description - -[source,erlang] ----- -host(Req :: cowboy_req:req()) -> Host :: binary() ----- - -Return the host name of the effective request URI. - -The host name can also be obtained using pattern matching: - -[source,erlang] ----- -#{host := Host} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The host name is returned as a lowercase binary string. -It is case insensitive. - -== Changelog - -* *2.0*: Only the host name is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the effective request URI's host name -[source,erlang] ----- -Host = cowboy_req:host(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:binding(3)[cowboy_req:binding(3)], -link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)], -link:man:cowboy_req:host_info(3)[cowboy_req:host_info(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.host_info.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.host_info.asciidoc deleted file mode 100644 index ed613c62a2..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.host_info.asciidoc +++ /dev/null @@ -1,49 +0,0 @@ -= cowboy_req:host_info(3) - -== Name - -cowboy_req:host_info - Access the route's heading host segments - -== Description - -[source,erlang] ----- -host_info(Req :: cowboy_req:req()) -> cowboy_router:tokens() ----- - -Return the tokens for the heading host segments. - -This is the part of the host name that was matched using -the `...` notation. - -== Arguments - -Req:: - -The Req object. - -== Return value - -The tokens are returned as a list of case insensitive -binary strings. - -== Changelog - -* *2.0*: Only the tokens are returned, they are no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the host_info tokens -[source,erlang] ----- -HostInfo = cowboy_req:host_info(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:binding(3)[cowboy_req:binding(3)], -link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)], -link:man:cowboy_req:path_info(3)[cowboy_req:path_info(3)], -link:man:cowboy_router(3)[cowboy_router(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.inform.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.inform.asciidoc deleted file mode 100644 index 1770c14a5b..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.inform.asciidoc +++ /dev/null @@ -1,83 +0,0 @@ -= cowboy_req:inform(3) - -== Name - -cowboy_req:inform - Send an informational response - -== Description - -[source,erlang] ----- -inform(Status, Req :: cowboy_req:req()) - -> inform(StatusCode, #{}, Req) - -inform(Status, Headers, Req :: cowboy_req:req()) - -> ok - -Status :: cowboy:http_status() -Headers :: cowboy:http_headers() ----- - -Send an informational response. - -Informational responses use a status code between 100 and 199. -They cannot include a body. This function will not use any -of the previously set headers. All headers to be sent must -be given directly. - -Any number of informational responses can be sent as long as -they are sent before the proper response. Attempting to use -this function after sending a normal response will result -in an error. - -The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -== Arguments - -Status:: - -The status code for the response. - -Headers:: - -The response headers. -+ -Header names must be given as lowercase binary strings. - -Req:: - -The Req object. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.1*: Function introduced. - -== Examples - -.Send an informational response -[source,erlang] ----- -Req = cowboy_req:inform(102, Req0). ----- - -.Send an informational response with headers -[source,erlang] ----- -Req = cowboy_req:inform(103, #{ - <<"link">> => <<"; rel=preload; as=style">>, - <<"link">> => <<"; rel=preload; as=script">> -}, Req0). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)], -link:man:cowboy_req:push(3)[cowboy_req:push(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.match_cookies.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.match_cookies.asciidoc deleted file mode 100644 index d56b03106f..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.match_cookies.asciidoc +++ /dev/null @@ -1,93 +0,0 @@ -= cowboy_req:match_cookies(3) - -== Name - -cowboy_req:match_cookies - Match cookies against constraints - -== Description - -[source,erlang] ----- -match_cookies(Fields :: cowboy:fields(), Req :: cowboy_req:req()) - -> #{atom() => any()} ----- - -Parse the cookies and match specific values against -constraints. - -Cowboy will only return the cookie values specified in the -fields list, and ignore all others. Fields can be either -the name of the cookie requested; the name along with a -list of constraints; or the name, a list of constraints -and a default value in case the cookie is missing. - -This function will crash if the cookie is missing and no -default value is provided. This function will also crash -if a constraint fails. - -The name of the cookie must be provided as an atom. The -key of the returned map will be that atom. The value may -be converted through the use of constraints, making this -function able to extract, validate and convert values all -in one step. - -This function will crash on invalid cookie data. How to -handle this is explained in details in the manual page for -link:man:cowboy_req:parse_cookies(3)[cowboy_req:parse_cookies(3)]. - -== Arguments - -Fields:: - -Cookies to retrieve. -+ -See link:man:cowboy(3)[cowboy(3)] for a complete description. - -Req:: - -The Req object. - -== Return value - -Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints. - -The map contains the same keys that were given in the fields. - -An exception is triggered when the match fails. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Match fields -[source,erlang] ----- -%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([id, lang], Req). ----- - -.Match fields and apply constraints -[source,erlang] ----- -%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_cookies([{id, int}, {lang, nonempty}], Req). ----- - -.Match fields with default values -[source,erlang] ----- -#{lang := Lang} - = cowboy_req:match_cookies([{lang, [], <<"en-US">>}], Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:filter_cookies(3)[cowboy_req:filter_cookies(3)], -link:man:cowboy_req:parse_cookies(3)[cowboy_req:parse_cookies(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.match_qs.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.match_qs.asciidoc deleted file mode 100644 index 845d09a33a..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.match_qs.asciidoc +++ /dev/null @@ -1,88 +0,0 @@ -= cowboy_req:match_qs(3) - -== Name - -cowboy_req:match_qs - Match the query string against constraints - -== Description - -[source,erlang] ----- -match_qs(Fields :: cowboy:fields(), Req :: cowboy_req:req()) - -> #{atom() => any()} ----- - -Parse the query string and match specific values against -constraints. - -Cowboy will only return the query string values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing. - -This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails. - -The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step. - -== Arguments - -Fields:: - -Fields to retrieve from the query string. -+ -See link:man:cowboy(3)[cowboy(3)] for a complete description. - -Req:: - -The Req object. - -== Return value - -Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints. - -The map contains the same keys that were given in the fields. - -An exception is triggered when the match fails. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Match fields -[source,erlang] ----- -%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([id, lang], Req). ----- - -.Match fields and apply constraints -[source,erlang] ----- -%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:match_qs([{id, int}, {lang, nonempty}], Req). ----- - -.Match fields with default values -[source,erlang] ----- -#{lang := Lang} - = cowboy_req:match_qs([{lang, [], <<"en-US">>}], Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:qs(3)[cowboy_req:qs(3)], -link:man:cowboy_req:parse_qs(3)[cowboy_req:parse_qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.method.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.method.asciidoc deleted file mode 100644 index bb3ad6ee77..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.method.asciidoc +++ /dev/null @@ -1,60 +0,0 @@ -= cowboy_req:method(3) - -== Name - -cowboy_req:method - HTTP method - -== Description - -[source,erlang] ----- -method(Req :: cowboy_req:req()) -> Method :: binary() ----- - -Return the request's HTTP method. - -The method can also be obtained using pattern matching: - -[source,erlang] ----- -#{method := Method} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The request's HTTP method is returned as a binary string. -While methods are case sensitive, standard methods are -always uppercase. - -== Changelog - -* *2.0*: Only the method is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Ensure the request's method is GET -[source,erlang] ----- -<<"GET">> = cowboy_req:method(Req). ----- - -.Allow methods from list -[source,erlang] ----- -init(Req, State) -> - case lists:member(cowboy_req:method(Req), [<<"GET">>, <<"POST">>]) of - true -> handle(Req, State); - false -> method_not_allowed(Req, State) - end. ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_cookies.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_cookies.asciidoc deleted file mode 100644 index 4fece567fb..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_cookies.asciidoc +++ /dev/null @@ -1,81 +0,0 @@ -= cowboy_req:parse_cookies(3) - -== Name - -cowboy_req:parse_cookies - Parse cookie headers - -== Description - -[source,erlang] ----- -parse_cookies(Req) -> [{Name, Value}] - -Name :: binary() %% case sensitive -Value :: binary() %% case sensitive ----- - -Parse cookie headers. - -Alias for link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(<<"cookie">>, Req)]. - -When the cookie header is missing or empty, `[]` is returned. - -This function will crash on invalid cookie data. Because -invalid cookies are fairly common when dealing with browsers -(because of the string interface that the Javascript API provides), -it is recommended to filter the cookie header value before -attempting to parse it. This can be accomplished by calling -the function link:man:cowboy_req:filter_cookies(3)[cowboy_req:filter_cookies(3)] -first. This does not guarantee that parsing succeeds. If it -still fails it is recommended to send an error response or -redirect with instructions to delete the relevant cookies: - -.Recover from cookie parsing errors -[source,erlang] ----- -Req1 = cowboy_req:filter_cookies([session_id, token], Req0), -try cowboy_req:parse_cookies(Req1) of - Cookies -> - do_something(Req1, Cookies) -catch _:_ -> - %% We can't parse the cookies we need, unset them - %% otherwise the browser will continue sending them. - Req2 = cowboy_req:set_resp_cookie(<<"session_id">>, - <<>>, Req1, #{max_age => 0}), - Req = cowboy_req:set_resp_cookie(<<"token">>, - <<>>, Req2, #{max_age => 0}), - cowboy_req:reply(500, Req) -end. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The cookies are returned as a list of key/values. Keys and -values are case sensitive binary strings. - -== Changelog - -* *2.0*: Only the parsed header value is returned, it is no longer wrapped in a tuple. -* *2.0*: Function introduced. Replaces `cookie/2,3` and `cookies/1`. - -== Examples - -.Look for a specific cookie -[source,erlang] ----- -Cookies = cowboy_req:parse_cookies(Req), -{_, Token} = lists:keyfind(<<"token">>, 1, Cookies). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(3)], -link:man:cowboy_req:filter_cookies(3)[cowboy_req:filter_cookies(3)], -link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_header.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_header.asciidoc deleted file mode 100644 index 3f68179876..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_header.asciidoc +++ /dev/null @@ -1,227 +0,0 @@ -= cowboy_req:parse_header(3) - -== Name - -cowboy_req:parse_header - Parse the given HTTP header - -== Description - -[source,erlang] ----- -parse_header(Name, Req) -> ParsedValue | Default -parse_header(Name, Req, Default) -> ParsedValue | Default - -Name :: binary() -Req :: cowboy_req:req() -ParsedValue :: any() -Default :: any() ----- - -Parse the given HTTP header. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -The type of the parsed value varies depending on -the header. Similarly, the default value when calling -`cowboy_req:parse_header/2` differs depending on the -header. - -== Arguments - -Name:: - -Desired HTTP header name as a lowercase binary string. - -Req:: - -The Req object. - -Default:: - -Default value returned when the header is missing. - -== Return value - -The parsed header value varies depending on the header. -When the header is missing, the default argument is returned. - -== Headers - -The following snippets detail the types returned by the -different headers. Unless mentioned otherwise, the -default value when the header is missing will be `undefined`: - -.accept -[source,erlang] ----- -parse_header(<<"accept">>, Req) - -> [{{Type, SubType, Params}, Quality, AcceptExt}] - -Type :: binary() %% case insensitive -SubType :: binary() %% case insensitive -Params :: [{Key, Value}] -Quality :: 0..1000 -AcceptExt :: [Key | {Key, Value}] -Key :: binary() %% case insensitive -Value :: binary() %% case sensitive ----- - -.accept-charset, accept-encoding and accept-language -[source,erlang] ----- -parse_header(Name, Req) -> [{Value, Quality}] - -Name :: <<"accept-charset">> - | <<"accept-encoding">> - | <<"accept-language">> -Value :: binary() %% case insensitive -Quality :: 0..1000 ----- - -.authorization -[source,erlang] ----- -parse_header(<<"authorization">>, Req) - -> {basic, Username :: binary(), Password :: binary()} - | {bearer, Token :: binary()} - | {digest, [{Key :: binary(), Value :: binary()}]} ----- - -// @todo Currently also parses connection. Do we want this? Should it be documented? Use case? - -.content-length -[source,erlang] ----- -parse_header(<<"content-length">>, Req) -> non_neg_integer() ----- - -When the content-length header is missing, `0` is returned. - -.content-type -[source,erlang] ----- -parse_header(<<"content-type">>, Req) - -> {Type, SubType, Params} - -Type :: binary() %% case insensitive -SubType :: binary() %% case insensitive -Params :: [{Key, Value}] -Key :: binary() %% case insensitive -Value :: binary() %% case sensitive; ----- - -Note that the value for the charset parameter is case insensitive -and returned as a lowercase binary string. - -.cookie -[source,erlang] ----- -parse_header(<<"cookie">>, Req) -> [{Name, Value}] - -Name :: binary() %% case sensitive -Value :: binary() %% case sensitive ----- - -When the cookie header is missing, `[]` is returned. - -While an empty cookie header is not valid, some clients do -send it. Cowboy will in this case also return `[]`. - -.expect -[source,erlang] ----- -parse_header(<<"expect">>, Req) -> continue ----- - -.if-match and if-none-match -[source,erlang] ----- -parse_header(Name, Req) - -> '*' | [{weak | strong, OpaqueTag}] - -Name :: <<"if-match">> - | <<"if-none-match">> -OpaqueTag :: binary() %% case sensitive ----- - -.if-modified-since and if-unmodified-since -[source,erlang] ----- -parse_header(Name, Req) -> calendar:datetime() ----- - -.range -[source,erlang] ----- -parse_header(<<"range">>, Req) -> {From, To} | Final - -From :: non_neg_integer() -To :: non_neg_integer() | infinity -Final :: neg_integer() ----- - -.sec-websocket-extensions -[source,erlang] ----- -parse_header(<<"sec-websocket-extensions">>, Req) - -> [{Extension, Params}] - -Extension :: binary() %% case sensitive -Params :: [Key | {Key, Value}] -Key :: binary() %% case sensitive -Value :: binary() %% case sensitive ----- - -.sec-websocket-protocol and upgrade -[source,erlang] ----- -parse_header(Name, Req) -> [Token] - -Name :: <<"sec-websocket-protocol">> - | <<"upgrade">> -Token :: binary() %% case insensitive ----- - -.x-forwarded-for -[source,erlang] ----- -parse_header(<<"x-forwarded-for">>, Req) -> [Token] - -Token :: binary() %% case sensitive ----- - -.Unknown headers -[source,erlang] ----- -parse_header(_, Req) -> {undefined, RawValue} ----- - -== Changelog - -* *2.0*: Only the parsed header value is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Parse the accept header with a custom default value -[source,erlang] ----- -%% Accept everything when header is missing. -Accept = cowboy_req:parse_header(<<"accept">>, Req, - [{{ <<"*">>, <<"*">>, []}, 1000, []}]). ----- - -.Parse the content-length header -[source,erlang] ----- -%% Default content-length is 0. -Length = cowboy_req:header(<<"content-length">>, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:header(3)[cowboy_req:header(3)], -link:man:cowboy_req:headers(3)[cowboy_req:headers(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_qs.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_qs.asciidoc deleted file mode 100644 index 907bc7bc4d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.parse_qs.asciidoc +++ /dev/null @@ -1,58 +0,0 @@ -= cowboy_req:parse_qs(3) - -== Name - -cowboy_req:parse_qs - Parse the query string - -== Description - -[source,erlang] ----- -parse_qs(Req :: cowboy_req:req()) - -> [{Key :: binary(), Value :: binary() | true}] ----- - -Parse the query string as a list of key/value pairs. - -== Arguments - -Req:: - -The Req object. - -== Return value - -The parsed query string is returned as a list of key/value pairs. -The key is a binary string. The value is either a binary string, -or the atom `true`. Both key and value are case sensitive. - -The atom `true` is returned when a key is present in the query -string without a value. For example, in the following URIs -the key `<<"edit">>` will always have the value `true`: - -* `/posts/42?edit` -* `/posts/42?edit&exclusive=1` -* `/posts/42?exclusive=1&edit` -* `/posts/42?exclusive=1&edit&from=web` - -== Changelog - -* *2.0*: The parsed value is not longer cached in the Req object. -* *2.0*: Only the parsed query string is returned, it is no longer wrapped in a tuple. -* *2.0*: Function introduced. Replaces `qs_val/1` and `qs_vals/1`. - -== Examples - -.Parse the query string and convert the keys to atoms -[source,erlang] ----- -ParsedQs = cowboy_req:parse_qs(Req), -AtomsQs = [{binary_to_existing_atom(K, latin1), V} - || {K, V} <- ParsedQs]. ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:qs(3)[cowboy_req:qs(3)], -link:man:cowboy_req:match_qs(3)[cowboy_req:match_qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.path.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.path.asciidoc deleted file mode 100644 index 5f2654822e..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.path.asciidoc +++ /dev/null @@ -1,51 +0,0 @@ -= cowboy_req:path(3) - -== Name - -cowboy_req:path - URI path - -== Description - -[source,erlang] ----- -path(Req :: cowboy_req:req()) -> Path :: binary() ----- - -Return the path of the effective request URI. - -The path can also be obtained using pattern matching: - -[source,erlang] ----- -#{path := Path} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The path is returned as a binary string. It is case sensitive. - -== Changelog - -* *2.0*: Only the path is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the effective request URI's path -[source,erlang] ----- -Path = cowboy_req:path(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:binding(3)[cowboy_req:binding(3)], -link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)], -link:man:cowboy_req:path_info(3)[cowboy_req:path_info(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.path_info.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.path_info.asciidoc deleted file mode 100644 index d6d7541346..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.path_info.asciidoc +++ /dev/null @@ -1,49 +0,0 @@ -= cowboy_req:path_info(3) - -== Name - -cowboy_req:path_info - Access the route's trailing path segments - -== Description - -[source,erlang] ----- -path_info(Req :: cowboy_req:req()) -> cowboy_router:tokens() ----- - -Return the tokens for the trailing path segments. - -This is the part of the host name that was matched using -the `...` notation. - -== Arguments - -Req:: - -The Req object. - -== Return value - -The tokens are returned as a list of case sensitive -binary strings. - -== Changelog - -* *2.0*: Only the tokens are returned, they are no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the path_info tokens -[source,erlang] ----- -PathInfo = cowboy_req:path_info(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:binding(3)[cowboy_req:binding(3)], -link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)], -link:man:cowboy_req:host_info(3)[cowboy_req:host_info(3)], -link:man:cowboy_router(3)[cowboy_router(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.peer.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.peer.asciidoc deleted file mode 100644 index 0f134b3330..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.peer.asciidoc +++ /dev/null @@ -1,61 +0,0 @@ -= cowboy_req:peer(3) - -== Name - -cowboy_req:peer - Peer address and port - -== Description - -[source,erlang] ----- -peer(Req :: cowboy_req:req()) -> Info - -Info :: {inet:ip_address(), inet:port_number()} ----- - -Return the peer's IP address and port number. - -The peer information can also be obtained using pattern matching: - -[source,erlang] ----- -#{peer := {IP, Port}} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The peer's IP address and port number. - -The peer is not necessarily the client's IP address and port. -It is the IP address of the endpoint connecting directly to -the server, which may be a gateway or a proxy. - -The forwarded header can be used to get better information -about the different endpoints from the client to the server. -Note however that it is only informative; there is no reliable -way of determining the source of an HTTP request. - -== Changelog - -* *2.0*: Only the peer is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the peer IP address and port number. -[source,erlang] ----- -{IP, Port} = cowboy_req:peer(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:sock(3)[cowboy_req:sock(3)], -link:man:cowboy_req:cert(3)[cowboy_req:cert(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.port.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.port.asciidoc deleted file mode 100644 index 57f0875af6..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.port.asciidoc +++ /dev/null @@ -1,52 +0,0 @@ -= cowboy_req:port(3) - -== Name - -cowboy_req:port - URI port number - -== Description - -[source,erlang] ----- -port(Req :: cowboy_req:req()) -> Port :: inet:port_number() ----- - -Return the port number of the effective request URI. - -Note that the port number returned by this function is obtained -by parsing the host header. It may be different from the port -the peer used to connect to Cowboy. - -The port number can also be obtained using pattern matching: - -[source,erlang] ----- -#{port := Port} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The port number is returned as an integer. - -== Changelog - -* *2.0*: Only the port number is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the effective request URI's port number -[source,erlang] ----- -Port = cowboy_req:port(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.push.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.push.asciidoc deleted file mode 100644 index 80c1216ce2..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.push.asciidoc +++ /dev/null @@ -1,103 +0,0 @@ -= cowboy_req:push(3) - -== Name - -cowboy_req:push - Push a resource to the client - -== Description - -[source,erlang] ----- -push(Path, Headers, Req :: cowboy_req:req()) - -> push(Path, Headers, Req, #{}) - -push(Path, Headers, Req :: cowboy_req:req(), Opts) - -> ok - -Path :: iodata() %% case sensitive -Headers :: cowboy:http_headers() -Opts :: cowboy_req:push_opts() ----- - -Push a resource to the client. - -Cowboy handles push requests the same way as if they came -from the client, including the creation of a request handling -process, routing and middlewares and so on. - -This function does nothing when the HTTP/1.1 protocol is -used. You may call it safely without first checking whether -the connection uses HTTP/2. - -The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -Note that the headers must be the headers the client is expected -to send if it were to perform the request. They are therefore -request headers, and not response headers. - -By default, Cowboy will use the GET method, an empty query string, -and take the scheme, host and port directly from the current -request's URI. You can override them by passing options. - -Note that clients may cancel the push or ignore it entirely. -For example browsers may ignore the resource when the connection -is not considered secure. - -It is not possible to push resources after sending a response. -Any attempt will result in an error. - -== Arguments - -Path:: - -The status code for the response. - -Headers:: - -The response headers. -+ -Header names must be given as lowercase binary strings. - -Req:: - -The Req object. - -Opts:: - -Customize the HTTP method or the URI scheme, host, port -or query string. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Push a resource -[source,erlang] ----- -cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, Req), ----- - -.Push a resource with a custom host -[source,erlang] ----- -cowboy_req:push("/static/style.css", #{ - <<"accept">> => <<"text/css">> -}, #{host => <<"cdn.example.org">>}, Req), ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:inform(3)[cowboy_req:inform(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.qs.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.qs.asciidoc deleted file mode 100644 index 6e923579e9..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.qs.asciidoc +++ /dev/null @@ -1,50 +0,0 @@ -= cowboy_req:qs(3) - -== Name - -cowboy_req:qs - URI query string - -== Description - -[source,erlang] ----- -qs(Req :: cowboy_req:req()) -> Qs :: binary() ----- - -Return the query string of the effective request URI. - -The query string can also be obtained using pattern matching: - -[source,erlang] ----- -#{qs := Qs} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The query string is returned as a binary string. It is case sensitive. - -== Changelog - -* *2.0*: Only the query string is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the effective request URI's query string -[source,erlang] ----- -Qs = cowboy_req:qs(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:parse_qs(3)[cowboy_req:parse_qs(3)], -link:man:cowboy_req:match_qs(3)[cowboy_req:match_qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_and_match_urlencoded_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_and_match_urlencoded_body.asciidoc deleted file mode 100644 index aa2704cc23..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_and_match_urlencoded_body.asciidoc +++ /dev/null @@ -1,148 +0,0 @@ -= cowboy_req:read_and_match_urlencoded_body(3) - -== Name - -cowboy_req:read_and_match_urlencoded_body - Read, parse -and match a urlencoded request body against constraints - -== Description - -[source,erlang] ----- -read_and_match_urlencoded_body(Fields, Req) - -> read_and_match_urlencoded_body(Fields, Req, #{}) - -read_and_match_urlencoded_body(Fields, Req, Opts) - -> {ok, Body, Req} - -Fields :: cowboy:fields() -Req :: cowboy_req:req() -Opts :: cowboy_req:read_body_opts() -Body :: #{atom() => any()} ----- - -Read, parse and match a urlencoded request body against -constraints. - -This function reads the request body and parses it as -`application/x-www-form-urlencoded`. It then applies -the given field constraints to the urlencoded data -and returns the result as a map. - -The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method. - -Cowboy will only return the values specified -in the fields list, and ignore all others. Fields can be -either the key requested; the key along with a list of -constraints; or the key, a list of constraints and a -default value in case the key is missing. - -This function will crash if the key is missing and no -default value is provided. This function will also crash -if a constraint fails. - -The key must be provided as an atom. The key of the -returned map will be that atom. The value may be converted -through the use of constraints, making this function able -to extract, validate and convert values all in one step. - -Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required. - -Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others. - -Once the body has been read, Cowboy sets the content-length -header if it was not previously provided. - -This function can only be called once. Calling it again will -result in undefined behavior. - -== Arguments - -Fields:: - -Fields to retrieve from the urlencoded body. -+ -See link:man:cowboy(3)[cowboy(3)] for a complete description. - -Req:: - -The Req object. - -Opts:: - -A map of body reading options. Please refer to -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)] -for details about each option. -+ -This function defaults the `length` to 64KB and the `period` -to 5 seconds. - -== Return value - -An `ok` tuple is returned. - -Desired values are returned as a map. The key is the atom -that was given in the list of fields, and the value is the -optionally converted value after applying constraints. - -The map contains the same keys that were given in the fields. - -An exception is triggered when the match fails. - -The Req object returned in the tuple must be used from that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read. - -== Changelog - -* *2.5*: Function introduced. - -== Examples - -.Match fields -[source,erlang] ----- -%% ID and Lang are binaries. -#{id := ID, lang := Lang} - = cowboy_req:read_and_match_urlencoded_body( - [id, lang], Req). ----- - -.Match fields and apply constraints -[source,erlang] ----- -%% ID is an integer and Lang a non-empty binary. -#{id := ID, lang := Lang} - = cowboy_req:read_and_match_urlencoded_body( - [{id, int}, {lang, nonempty}], Req). ----- - -.Match fields with default values -[source,erlang] ----- -#{lang := Lang} - = cowboy_req:read_and_match_urlencoded_body( - [{lang, [], <<"en-US">>}], Req). ----- - -.Allow large urlencoded bodies -[source,erlang] ----- -{ok, Body, Req} = cowboy_req:read_and_match_urlencoded_body( - Fields, Req0, #{length => 1000000}). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)], -link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)], -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)], -link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)], -link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)], -link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_body.asciidoc deleted file mode 100644 index 2b87405806..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_body.asciidoc +++ /dev/null @@ -1,117 +0,0 @@ -= cowboy_req:read_body(3) - -== Name - -cowboy_req:read_body - Read the request body - -== Description - -[source,erlang] ----- -read_body(Req :: cowboy_req:req()) - -> read_body(Req, #{}) - -read_body(Req :: cowboy_req:req(), Opts) - -> {ok, Data :: binary(), Req} - | {more, Data :: binary(), Req} - -Opts :: cowboy_req:read_body_opts() ----- - -Read the request body. - -This function reads a chunk of the request body. A `more` tuple -is returned when more data remains to be read. Call the function -repeatedly until an `ok` tuple is returned to read the entire body. - -An `ok` tuple with empty data is returned when the request has no body, -or when calling this function again after the body has already -been read. It is therefore safe to call this function directly. -Note that the body can only be read once. - -This function reads the request body from the connection process. -The connection process is responsible for reading from the socket. -The exact behavior varies depending on the protocol. - -The options therefore are only related to the communication -between the request process and the connection process. - -Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others. - -Once the body has been read fully, Cowboy sets the content-length -header if it was not previously provided. - -== Arguments - -Req:: - -The Req object. - -Opts:: - -A map of body reading options. -+ -The `length` option can be used to request smaller or bigger -chunks of data to be sent. It is a best effort approach, Cowboy -may send more data than configured on occasions. It defaults -to 8MB. -+ -The `period` indicates how long the connection process will wait -before it provides us with the data it received. It defaults -to 15 seconds. -+ -The connection process sends data to the request process when -either the `length` of data or the `period` of time is reached. -+ -The `timeout` option is a safeguard in case the connection -process becomes unresponsive. The function will crash if no -message was received in that interval. The timeout should be -larger than the period. It defaults to the period + 1 second. - -== Return value - -A `more` tuple is returned when there are more data to be read. - -An `ok` tuple is returned when there are no more data to be read, -either because this is the last chunk of data, the body has already -been read, or there was no body to begin with. - -The data is always returned as a binary. - -The Req object returned in the tuple must be used from that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read. - -== Changelog - -* *2.0*: Function introduced. Replaces `body/1,2`. - -== Examples - -.Read the entire body -[source,erlang] ----- -read_body(Req0, Acc) -> - case cowboy_req:read_body(Req0) of - {ok, Data, Req} -> {ok, << Acc/binary, Data/binary >>, Req}; - {more, Data, Req} -> read_body(Req, << Acc/binary, Data/binary >>) - end. ----- - -.Read the body in small chunks -[source,erlang] ----- -cowboy_req:read_body(Req, #{length => 64000}). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)], -link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)], -link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)], -link:man:cowboy_req:read_and_match_urlencoded_body(3)[cowboy_req:read_and_match_urlencoded_body(3)], -link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)], -link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_part.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_part.asciidoc deleted file mode 100644 index 9123b2eb82..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_part.asciidoc +++ /dev/null @@ -1,135 +0,0 @@ -= cowboy_req:read_part(3) - -== Name - -cowboy_req:read_part - Read the next multipart headers - -== Description - -[source,erlang] ----- -read_part(Req :: cowboy_req:req()) - -> read_part(Req, #{}) - -read_part(Req :: cowboy_req:req(), Opts) - -> {ok, Headers, Req} | {done, Req} - -Opts :: cowboy_req:read_body_opts() -Headers :: #{binary() => binary()} ----- - -Read the next part of a multipart body. - -This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function parses and returns -headers. Examples of multipart media types are -`multipart/form-data` and `multipart/byteranges`. - -Cowboy will skip any data remaining until the beginning of -the next part. This includes the preamble to the multipart -message but also the body of a previous part if it hasn't -been read. Both are skipped automatically when calling this -function. - -Cowboy will read the body before parsing in chunks of size -up to 64KB, with a period of 5 seconds. This is tailored for -reading part headers and might not be the most efficient for -skipping the previous part's body. - -The headers returned are MIME headers, *NOT* HTTP headers. -They can be parsed using the functions from the `cow_multipart` -module. In addition, the `cow_multipart:form_data/1` function -can be used to quickly extract information from `multipart/form-data` -representations. - -// @todo Proper link to cow_multipart:form_data. - -Once a part has been read, it can not be read again. - -Once the body has been read, Cowboy sets the content-length -header if it was not previously provided. - -// @todo Limit the maximum size of multipart headers. - -== Arguments - -Req:: - -The Req object. - -Opts:: - -A map of body reading options. Please refer to -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)] -for details about each option. -+ -This function defaults the `length` to 64KB and the `period` -to 5 seconds. - -== Return value - -An `ok` tuple is returned containing the next part's headers -as a map. - -A `done` tuple is returned if there are no more parts to read. - -The Req object returned in the tuple must be used from that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read. - -== Changelog - -* *2.0*: Function introduced. Replaces `part/1,2`. - -== Examples - -.Read all parts -[source,erlang] ----- -acc_multipart(Req0, Acc) -> - case cowboy_req:read_part(Req0) of - {ok, Headers, Req1} -> - {ok, Body, Req} = stream_body(Req1, <<>>), - acc_multipart(Req, [{Headers, Body}|Acc]); - {done, Req} -> - {lists:reverse(Acc), Req} - end. - -stream_body(Req0, Acc) -> - case cowboy_req:read_part_body(Req0) of - {more, Data, Req} -> - stream_body(Req, << Acc/binary, Data/binary >>); - {ok, Data, Req} -> - {ok, << Acc/binary, Data/binary >>, Req} - end. ----- - -.Read all part headers, skipping bodies -[source,erlang] ----- -skip_body_multipart(Req0, Acc) -> - case cowboy_req:read_part(Req0) of - {ok, Headers, Req} -> - skip_body_multipart(Req, [Headers|Acc]); - {done, Req} -> - {lists:reverse(Acc), Req} - end. ----- - -.Read a part header in larger chunks -[source,erlang] ----- -{ok, Headers, Req} = cowboy_req:read_part(Req0, #{length => 1000000}). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)], -link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)], -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)], -link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)], -link:man:cowboy_req:read_and_match_urlencoded_body(3)[cowboy_req:read_and_match_urlencoded_body(3)], -link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_part_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_part_body.asciidoc deleted file mode 100644 index dc634f3a99..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_part_body.asciidoc +++ /dev/null @@ -1,101 +0,0 @@ -= cowboy_req:read_part_body(3) - -== Name - -cowboy_req:read_part_body - Read the current part's body - -== Description - -[source,erlang] ----- -read_part_body(Req :: cowboy_req:req()) - -> read_part_body(Req, #{}) - -read_part_body(Req :: cowboy_req:req(), Opts) - -> {ok, Data :: binary(), Req} - | {more, Data :: binary(), Req} - -Opts :: cowboy_req:read_body_opts() ----- - -Read the body of the current part of the multipart message. - -This function reads the request body and parses it as -multipart. Each parts of a multipart representation have -their own headers and body. This function returns the -body of the current part. Examples of multipart media types -are `multipart/form-data` and `multipart/byteranges`. - -This function reads a chunk of the part's body. A `more` tuple -is returned when more data remains to be read. Call the function -repeatedly until an `ok` tuple is returned to read the entire body. - -Once a part has been read, it can not be read again. - -Once the body has been read, Cowboy sets the content-length -header if it was not previously provided. - -// @todo Limit the maximum size of multipart headers. - -== Arguments - -Req:: - -The Req object. - -Opts:: - -A map of body reading options. Please refer to -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)] -for details about each option. -+ -This function uses the same default options as the -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)] -function. - -== Return value - -A `more` tuple is returned when there are more data to be read. - -An `ok` tuple is returned when there are no more data to be read. - -The data is always returned as a binary. - -The Req object returned in the tuple must be used from that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read. - -== Changelog - -* *2.0*: Function introduced. Replaces `part_body/1,2`. - -== Examples - -.Read a full part's body -[source,erlang] ----- -stream_body(Req0, Acc) -> - case cowboy_req:read_part_body(Req0) of - {more, Data, Req} -> - stream_body(Req, << Acc/binary, Data/binary >>); - {ok, Data, Req} -> - {ok, << Acc/binary, Data/binary >>, Req} - end. ----- - -.Ensure a part's body is smaller than 64KB -[source,erlang] ----- -{ok, Body, Req} = cowboy_req:read_part_body(Req0, #{length => 64000}). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)], -link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)], -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)], -link:man:cowboy_req:read_urlencoded_body(3)[cowboy_req:read_urlencoded_body(3)], -link:man:cowboy_req:read_and_match_urlencoded_body(3)[cowboy_req:read_and_match_urlencoded_body(3)], -link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_urlencoded_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_urlencoded_body.asciidoc deleted file mode 100644 index e897a69ead..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.read_urlencoded_body.asciidoc +++ /dev/null @@ -1,95 +0,0 @@ -= cowboy_req:read_urlencoded_body(3) - -== Name - -cowboy_req:read_urlencoded_body - Read and parse a urlencoded request body - -== Description - -[source,erlang] ----- -read_urlencoded_body(Req :: cowboy_req:req()) - -> read_urlencoded_body(Req, #{}) - -read_urlencoded_body(Req :: cowboy_req:req(), Opts) - -> {ok, Body, Req} - -Opts :: cowboy_req:read_body_opts() -Body :: [{Key :: binary(), Value :: binary() | true}] ----- - -Read and parse a urlencoded request body. - -This function reads the request body and parses it as -`application/x-www-form-urlencoded`. It returns a list -of key/values. - -The urlencoded media type is used by Web browsers when -submitting HTML forms using the POST method. - -Cowboy needs to read the full body before parsing. By default -it will read bodies of size up to 64KB. It is possible to -provide options to read larger bodies if required. - -Cowboy will automatically handle protocol details including -the expect header, chunked transfer-encoding and others. - -Once the body has been read, Cowboy sets the content-length -header if it was not previously provided. - -This function can only be called once. Calling it again will -result in undefined behavior. - -== Arguments - -Req:: - -The Req object. - -Opts:: - -A map of body reading options. Please refer to -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)] -for details about each option. -+ -This function defaults the `length` to 64KB and the `period` -to 5 seconds. - -== Return value - -An `ok` tuple is returned containing a list of key/values found -in the body. - -The Req object returned in the tuple must be used from that point -onward. It contains a more up to date representation of the request. -For example it may have an added content-length header once the -body has been read. - -== Changelog - -* *2.0*: Function introduced. Replaces `body_qs/1,2`. - -== Examples - -.Read a urlencoded body -[source,erlang] ----- -{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0), -{_, Lang} = lists:keyfind(<<"lang">>, 1, Body). ----- - -.Allow large urlencoded bodies -[source,erlang] ----- -{ok, Body, Req} = cowboy_req:read_urlencoded_body(Req0, #{length => 1000000}). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:has_body(3)[cowboy_req:has_body(3)], -link:man:cowboy_req:body_length(3)[cowboy_req:body_length(3)], -link:man:cowboy_req:read_body(3)[cowboy_req:read_body(3)], -link:man:cowboy_req:read_and_match_urlencoded_body(3)[cowboy_req:read_and_match_urlencoded_body(3)], -link:man:cowboy_req:read_part(3)[cowboy_req:read_part(3)], -link:man:cowboy_req:read_part_body(3)[cowboy_req:read_part_body(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.reply.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.reply.asciidoc deleted file mode 100644 index 265d0eca82..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.reply.asciidoc +++ /dev/null @@ -1,118 +0,0 @@ -= cowboy_req:reply(3) - -== Name - -cowboy_req:reply - Send the response - -== Description - -[source,erlang] ----- -reply(Status, Req :: cowboy_req:req()) - -> reply(StatusCode, #{}, Req) - -reply(Status, Headers, Req :: cowboy_req:req()) - -> Req - -reply(Status, Headers, Body, Req :: cowboy_req:req()) - -> Req - -Status :: cowboy:http_status() -Headers :: cowboy:http_headers() -Body :: cowboy_req:resp_body() ----- - -Send the response. - -The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by `set_resp_header/3` -and `set_resp_headers/2`. - -Use link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)] -instead of this function to set cookies. - -The `reply/2,3` functions will send the body set previously, -if any. The `reply/4` function always sends the given body, -overriding any previously set. - -You do not need to set the content-length header when -sending a response body. Cowboy takes care of it automatically. -You should however provide a content-type header. - -No further data can be transmitted after this function -returns. This includes the push mechanism. Attempting to -send two replies, or to push resources after a reply has -been sent, will result in an error. - -== Arguments - -Status:: - -The status code for the response. - -Headers:: - -The response headers. -+ -Header names must be given as lowercase binary strings. - -Body:: - -The body can be either a binary value, an iolist or a -`sendfile` tuple telling Cowboy to send the contents of -a file. - -Req:: - -The Req object. - -== Return value - -A new Req object is returned. - -The returned Req object should be used from that point onward -as it contains updated information about the state of the request. - -== Changelog - -* *2.0*: Only the Req is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Reply -[source,erlang] ----- -Req = cowboy_req:reply(404, Req0). ----- - -.Reply with custom headers -[source,erlang] ----- -Req = cowboy_req:reply(401, #{ - <<"www-authenticate">> => <<"Basic realm=\"erlang.org\"">> -}, Req0). ----- - -.Reply with custom headers and a body -[source,erlang] ----- -Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, "Hello world!", Req0). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)], -link:man:cowboy_req:inform(3)[cowboy_req:inform(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)], -link:man:cowboy_req:push(3)[cowboy_req:push(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.resp_header.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.resp_header.asciidoc deleted file mode 100644 index 52f95d626a..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.resp_header.asciidoc +++ /dev/null @@ -1,71 +0,0 @@ -= cowboy_req:resp_header(3) - -== Name - -cowboy_req:resp_header - Response header - -== Description - -[source,erlang] ----- -resp_header(Name, Req) -> resp_header(Name, Req, undefined) -resp_header(Name, Req, Default) -> binary() | Default - -Name :: binary() %% lowercase; case insensitive -Req :: cowboy_req:req() -Default :: any() ----- - -Return the value for the given response header. - -The response header must have been set previously using -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)] or -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)]. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -== Arguments - -Name:: - -Desired response header name as a lowercase binary string. - -Req:: - -The Req object. - -Default:: - -Default value returned when the header is missing. - -== Return value - -The header value is returned as a binary string. When the -header is missing, the default argument is returned. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Get the content-type response header -[source,erlang] ----- -Type = cowboy_req:resp_header(<<"content-type">>, Req). ----- - -.Get the content-type response header with a default value -[source,erlang] ----- -Type = cowboy_req:resp_header(<<"content-type">>, Req, <<"text/html">>). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:resp_headers(3)[cowboy_req:resp_headers(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.resp_headers.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.resp_headers.asciidoc deleted file mode 100644 index a3b8f0ee2e..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.resp_headers.asciidoc +++ /dev/null @@ -1,44 +0,0 @@ -= cowboy_req:resp_headers(3) - -== Name - -cowboy_req:resp_headers - Response headers - -== Description - -[source,erlang] ----- -resp_headers(Req :: cowboy_req:req()) -> cowboy:http_headers() ----- - -Return all response headers. - -== Arguments - -Req:: - -The Req object. - -== Return value - -Headers are returned as a map with keys being lowercase -binary strings, and values as binary strings. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Get all response headers -[source,erlang] ----- -Headers = cowboy_req:resp_headers(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:resp_header(3)[cowboy_req:resp_header(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.scheme.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.scheme.asciidoc deleted file mode 100644 index bbe147dbea..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.scheme.asciidoc +++ /dev/null @@ -1,55 +0,0 @@ -= cowboy_req:scheme(3) - -== Name - -cowboy_req:scheme - URI scheme - -== Description - -[source,erlang] ----- -scheme(Req :: cowboy_req:req()) -> Scheme :: binary() ----- - -Return the scheme of the effective request URI. - -The scheme can also be obtained using pattern matching: - -[source,erlang] ----- -#{scheme := Scheme} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The scheme is returned as a binary. It is case insensitive. - -Cowboy will only set the scheme to `<<"http">>` or `<<"https">>`. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Redirect HTTP to HTTPS -[source,erlang] ----- -init(Req0=#{scheme := <<"http">>}, State) -> - Req = cowboy_req:reply(302, #{ - <<"location">> => cowboy_req:uri(Req, #{scheme => <<"https">>}) - }, Req0), - {ok, Req, State}; -init(Req, State) -> - {cowboy_rest, Req, State}. ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_body.asciidoc deleted file mode 100644 index 023b8bb705..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_body.asciidoc +++ /dev/null @@ -1,91 +0,0 @@ -= cowboy_req:set_resp_body(3) - -== Name - -cowboy_req:set_resp_body - Set the response body - -== Description - -[source,erlang] ----- -set_resp_body(Body, Req :: cowboy_req:req()) - -> Req - -Body :: cowboy_req:resp_body() ----- - -Set the response body. - -The response body will be sent when a reply is initiated. -Note that the functions `stream_reply/2,3` and `reply/4` -will override the body set by this function. - -This function can also be used to remove a response body -that was set previously. To do so, simply call this function -with an empty body. - -== Arguments - -Body:: - -The body can be either a binary value, an iolist or a -`sendfile` tuple telling Cowboy to send the contents of -a file. - -Req:: - -The Req object. - -== Return value - -A new Req object is returned. - -The returned Req object must be used from that point onward, -otherwise the body will not be sent in the response. - -== Changelog - -* *2.0*: The function now accepts a `sendfile` tuple. -* *2.0*: The `set_resp_body_fun/2,3` functions were removed. -* *1.0*: Function introduced. - -== Examples - -.Set the response body -[source,erlang] ----- -Req = cowboy_req:set_resp_body(<<"Hello world!">>, Req0). ----- - -.Set the response body as an iolist -[source,erlang] ----- -Req = cowboy_req:set_resp_body([ - "", - page_title(), - "", - page_body(), - "" -], Req0). ----- - -.Tell Cowboy to send data from a file -[source,erlang] ----- -{ok, #file_info{size=Size}} = file:read_file_info(Filename), -Req = cowboy_req:set_resp_body({sendfile, 0, Size, Filename}, Req0). ----- - -.Clear any previously set response body -[source,erlang] ----- -Req = cowboy_req:set_resp_body(<<>>, Req0). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_cookie.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_cookie.asciidoc deleted file mode 100644 index a4bfae7090..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_cookie.asciidoc +++ /dev/null @@ -1,109 +0,0 @@ -= cowboy_req:set_resp_cookie(3) - -== Name - -cowboy_req:set_resp_cookie - Set a cookie - -== Description - -[source,erlang] ----- -set_resp_cookie(Name, Value, Req :: cowboy_req:req()) - -> set_resp_cookie(Name, Value, Req, #{}) - -set_resp_cookie(Name, Value, Req :: cowboy_req:req(), Opts) - -> Req - -Name :: binary() %% case sensitive -Value :: iodata() %% case sensitive -Opts :: cow_cookie:cookie_opts() ----- - -Set a cookie to be sent with the response. - -Note that cookie names are case sensitive. - -== Arguments - -Name:: - -Cookie name. - -Value:: - -Cookie value. - -Req:: - -The Req object. - -Opts:: - -Cookie options. - -== Return value - -A new Req object is returned. - -The returned Req object must be used from that point onward, -otherwise the cookie will not be sent in the response. - -== Changelog - -* *2.0*: `set_resp_cookie/3` introduced as an alias to `set_resp_cookie/4` with no options. -* *2.0*: The first argument type is now `binary()` instead of `iodata()`. -* *1.0*: Function introduced. - -== Examples - -.Set a session cookie -[source,erlang] ----- -SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, Req0). ----- - -.Set a cookie with an expiration time -[source,erlang] ----- -Req = cowboy_req:set_resp_cookie(<<"lang">>, <<"fr-FR">>, - Req0, #{max_age => 3600}). ----- - -.Delete a cookie -[source,erlang] ----- -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, <<>>, - Req0, #{max_age => 0}). ----- - -.Set a cookie for a specific domain and path -[source,erlang] ----- -Req = cowboy_req:set_resp_cookie(<<"inaccount">>, <<"1">>, - Req0, #{domain => "my.example.org", path => "/account"}). ----- - -.Restrict a cookie to HTTPS -[source,erlang] ----- -SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{secure => true}). ----- - -.Restrict a cookie to HTTP -[source,erlang] ----- -SessionID = base64:encode(crypto:strong_rand_bytes(32)), -Req = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, - Req0, #{http_only => true}). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_header.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_header.asciidoc deleted file mode 100644 index 86d29a141d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_header.asciidoc +++ /dev/null @@ -1,81 +0,0 @@ -= cowboy_req:set_resp_header(3) - -== Name - -cowboy_req:set_resp_header - Set a response header - -== Description - -[source,erlang] ----- -set_resp_header(Name, Value, Req :: cowboy_req:req()) - -> Req - -Name :: binary() %% lowercase; case insensitive -Value :: iodata() %% case depends on header ----- - -Set a header to be sent with the response. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. - -Use link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)] -instead of this function to set cookies. - -== Arguments - -Name:: - -Header name as a lowercase binary string. - -Value:: - -Header value. - -Req:: - -The Req object. - -== Return value - -A new Req object is returned. - -The returned Req object must be used from that point onward, -otherwise the header will not be sent in the response. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Set a header in the response -[source,erlang] ----- -Req = cowboy_req:set_resp_header(<<"allow">>, "GET", Req0). ----- - -.Construct a header using iolists -[source,erlang] ----- -Req = cowboy_req:set_resp_header(<<"allow">>, - [allowed_methods(), ", OPTIONS"], Req0). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:has_resp_header(3)[cowboy_req:has_resp_header(3)], -link:man:cowboy_req:resp_header(3)[cowboy_req:resp_header(3)], -link:man:cowboy_req:resp_headers(3)[cowboy_req:resp_headers(3)], -link:man:cowboy_req:delete_resp_header(3)[cowboy_req:delete_resp_header(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_headers.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_headers.asciidoc deleted file mode 100644 index 63fe42416d..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.set_resp_headers.asciidoc +++ /dev/null @@ -1,74 +0,0 @@ -= cowboy_req:set_resp_headers(3) - -== Name - -cowboy_req:set_resp_headers - Set several response headers - -== Description - -[source,erlang] ----- -set_resp_headers(Headers, Req :: cowboy_req:req()) - -> Req - -Headers :: cowboy:http_headers() ----- - -Set several headers to be sent with the response. - -The header name must be given as a lowercase binary string. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -Cowboy does not allow duplicate header names. Headers set -by this function may be overwritten by those set from the -reply functions. Likewise, headers set by this function may -overwrite headers that were set previously. - -Use link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)] -instead of this function to set cookies. - -== Arguments - -Headers:: - -Headers as a map with keys being lowercase binary strings, -and values as binary strings. - -Req:: - -The Req object. - -== Return value - -A new Req object is returned. - -The returned Req object must be used from that point onward, -otherwise the headers will not be sent in the response. - -== Changelog - -* *2.0*: Function introduced. - -== Examples - -.Set several response headers -[source,erlang] ----- -Req = cowboy_req:set_resp_headers(#{ - <<"content-type">> => <<"text/html">>, - <<"content-encoding">> => <<"gzip">> -}, Req0). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:has_resp_header(3)[cowboy_req:has_resp_header(3)], -link:man:cowboy_req:resp_header(3)[cowboy_req:resp_header(3)], -link:man:cowboy_req:resp_headers(3)[cowboy_req:resp_headers(3)], -link:man:cowboy_req:delete_resp_header(3)[cowboy_req:delete_resp_header(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.sock.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.sock.asciidoc deleted file mode 100644 index 92428c9f10..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.sock.asciidoc +++ /dev/null @@ -1,51 +0,0 @@ -= cowboy_req:sock(3) - -== Name - -cowboy_req:sock - Socket address and port - -== Description - -[source,erlang] ----- -sock(Req :: cowboy_req:req()) -> Info - -Info :: {inet:ip_address(), inet:port_number()} ----- - -Return the socket's IP address and port number. - -The socket information can also be obtained using pattern matching: - -[source,erlang] ----- -#{sock := {IP, Port}} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The socket's local IP address and port number. - -== Changelog - -* *2.1*: Function introduced. - -== Examples - -.Get the socket's IP address and port number. -[source,erlang] ----- -{IP, Port} = cowboy_req:sock(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:peer(3)[cowboy_req:peer(3)], -link:man:cowboy_req:cert(3)[cowboy_req:cert(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_body.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_body.asciidoc deleted file mode 100644 index 03e6e70861..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_body.asciidoc +++ /dev/null @@ -1,82 +0,0 @@ -= cowboy_req:stream_body(3) - -== Name - -cowboy_req:stream_body - Stream the response body - -== Description - -[source,erlang] ----- -stream_body(Data, IsFin, Req :: cowboy_req:req()) -> ok - -Data :: cowboy_req:resp_body() -IsFin :: fin | nofin ----- - -Stream the response body. - -This function may be called as many times as needed after -initiating a response using the -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] -function. - -The second argument indicates if this call is the final -call. Use the `nofin` value until you know no more data -will be sent. The final call should use `fin` (possibly -with an empty data value) or be a call to the -link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)] -function. - -Note that not using `fin` for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible. - -You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function. - -== Arguments - -Data:: - -The data to be sent. - -IsFin:: - -A flag indicating whether this is the final piece of data -to be sent. - -Req:: - -The Req object. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.6*: The `Data` argument can now be a sendfile tuple. -* *2.0*: Function introduced. Replaces `chunk/2`. - -== Examples - -.Stream the response body -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, Req0), -cowboy_req:stream_body(<<"Hello\n">>, nofin, Req), -timer:sleep(1000), -cowboy_req:stream_body(<<"World!\n">>, fin, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)], -link:man:cowboy_req:stream_events(3)[cowboy_req:stream_events(3)], -link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_events.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_events.asciidoc deleted file mode 100644 index 72f3c3b1d7..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_events.asciidoc +++ /dev/null @@ -1,101 +0,0 @@ -= cowboy_req:stream_events(3) - -== Name - -cowboy_req:stream_events - Stream events - -== Description - -[source,erlang] ----- -stream_events(Events, IsFin, Req :: cowboy_req:req()) -> ok - -Events :: Event | [Event] -IsFin :: fin | nofin - -Event :: #{ - comment => iodata(), - data => iodata(), - event => iodata() | atom(), - id => iodata(), - retry => non_neg_integer() -} ----- - -Stream events. - -This function should only be used for `text/event-stream` -responses when using server-sent events. Cowboy will -automatically encode the given events to their text -representation. - -This function may be called as many times as needed after -initiating a response using the -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] -function. - -The second argument indicates if this call is the final -call. Use the `nofin` value until you know no more data -will be sent. The final call should use `fin` (possibly -with an empty data value) or be a call to the -link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)] -function. - -Note that not using `fin` for the final call is not an -error; Cowboy will take care of it when the request -handler terminates if needed. Depending on the resource -it may however be more efficient to do it as early as -possible. - -You do not need to handle HEAD requests specifically as -Cowboy will ensure no data is sent when you call this function. - -== Arguments - -Events:: - -Events to be sent. All fields are optional. - -IsFin:: - -A flag indicating whether this is the final piece of data -to be sent. - -Req:: - -The Req object. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.5*: Function introduced. - -== Examples - -.Stream events -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/event-stream">> -}, Req0), -cowboy_req:stream_events(#{ - id => <<"comment-123">>, - event => <<"add_comment">>, - data => <<"Hello,\n\nI noticed something wrong in ...">> -}, nofin, Req), -timer:sleep(1000), -cowboy_req:stream_events(#{ - event => <<"debug">>, - data => io_lib:format("An error occurred: ~p~n", [Error]) -}, fin, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)], -link:man:cowboy_req:stream_body(3)[cowboy_req:stream_body(3)], -link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_reply.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_reply.asciidoc deleted file mode 100644 index 2242908901..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_reply.asciidoc +++ /dev/null @@ -1,115 +0,0 @@ -= cowboy_req:stream_reply(3) - -== Name - -cowboy_req:stream_reply - Send the response headers - -== Description - -[source,erlang] ----- -stream_reply(Status, Req :: cowboy_req:req()) - -> stream_reply(StatusCode, #{}, Req) - -stream_reply(Status, Headers, Req :: cowboy_req:req()) - -> Req - -Status :: cowboy:http_status() -Headers :: cowboy:http_headers() ----- - -Send the response headers. - -The header names must be given as lowercase binary strings. -While header names are case insensitive, Cowboy requires them -to be given as lowercase to function properly. - -Cowboy does not allow duplicate header names. Headers set -by this function may overwrite those set by `set_resp_header/3`. - -Use link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)] -instead of this function to set cookies. - -If a response body was set before calling this function, -it will not be sent. - -Use link:man:cowboy_req:stream_body(3)[cowboy_req:stream_body(3)] -to stream the response body and optionally -link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)] -to send response trailer field values. - -You may want to set the content-length header when using -this function, if it is known in advance. This will allow -clients using HTTP/2 and HTTP/1.0 to process the response -more efficiently. - -The streaming method varies depending on the protocol being -used. HTTP/2 will use the usual DATA frames. HTTP/1.1 will -use chunked transfer-encoding, if the content-length -response header is set the body will be sent without chunked -chunked transfer-encoding. HTTP/1.0 will send the body -unmodified and close the connection at the end if no -content-length was set. - -It is not possible to push resources after this function -returns. Any attempt will result in an error. - -== Arguments - -Status:: - -The status code for the response. - -Headers:: - -The response headers. -+ -Header names must be given as lowercase binary strings. - -Req:: - -The Req object. - -== Return value - -A new Req object is returned. - -The returned Req object must be used from that point onward -in order to be able to stream the response body. - -== Changelog - -* *2.0*: Only the Req is returned, it is no longer wrapped in a tuple. -* *2.0*: Function introduced. Replaces `chunked_reply/1,2`. - -== Examples - -.Initiate the response -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, Req0). ----- - -.Stream the response with custom headers -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/plain">> -}, Req0), -cowboy_req:stream_body(<<"Hello\n">>, nofin, Req), -timer:sleep(1000), -cowboy_req:stream_body(<<"World!\n">>, fin, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:set_resp_cookie(3)[cowboy_req:set_resp_cookie(3)], -link:man:cowboy_req:set_resp_header(3)[cowboy_req:set_resp_header(3)], -link:man:cowboy_req:set_resp_headers(3)[cowboy_req:set_resp_headers(3)], -link:man:cowboy_req:inform(3)[cowboy_req:inform(3)], -link:man:cowboy_req:reply(3)[cowboy_req:reply(3)], -link:man:cowboy_req:stream_body(3)[cowboy_req:stream_body(3)], -link:man:cowboy_req:stream_events(3)[cowboy_req:stream_events(3)], -link:man:cowboy_req:stream_trailers(3)[cowboy_req:stream_trailers(3)], -link:man:cowboy_req:push(3)[cowboy_req:push(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_trailers.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_trailers.asciidoc deleted file mode 100644 index 6d48e18d0b..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.stream_trailers.asciidoc +++ /dev/null @@ -1,71 +0,0 @@ -= cowboy_req:stream_trailers(3) - -== Name - -cowboy_req:stream_trailers - Send the response trailers - -== Description - -[source,erlang] ----- -stream_trailers(Trailers, Req :: cowboy_req:req()) -> ok - -Trailers :: cowboy:http_headers() ----- - -Send the response trailers and terminate the stream. - -This function can only be called once, after initiating -a response using -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)] -and sending zero or more body chunks using -link:man:cowboy_req:stream_body(3)[cowboy_req:stream_body(3)] -with the `nofin` argument set. The function `stream_trailers/2` -implies `fin` and automatically terminate the response. - -You must list all field names sent in trailers in the -trailer header, otherwise they might be dropped by intermediaries -or clients. - -== Arguments - -Trailers:: - -Trailer field values to be sent. - -Req:: - -The Req object. - -== Return value - -The atom `ok` is always returned. It can be safely ignored. - -== Changelog - -* *2.2*: Function introduced. - -== Examples - -.Stream a response body with trailers -[source,erlang] ----- -Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/plain">>, - <<"trailer">> => <<"expires, content-md5">> -}, Req0), -cowboy_req:stream_body(<<"Hello\n">>, nofin, Req), -timer:sleep(1000), -cowboy_req:stream_body(<<"World!\n">>, nofin, Req). -cowboy_req:stream_trailers(#{ - <<"expires">> => <<"Sun, 10 Dec 2017 19:13:47 GMT">>, - <<"content-md5">> => <<"fbf68a8e34b2ded53bba54e68794b4fe">> -}, Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:stream_reply(3)[cowboy_req:stream_reply(3)], -link:man:cowboy_req:stream_body(3)[cowboy_req:stream_body(3)], -link:man:cowboy_req:stream_events(3)[cowboy_req:stream_events(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.uri.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.uri.asciidoc deleted file mode 100644 index 790f863dac..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.uri.asciidoc +++ /dev/null @@ -1,116 +0,0 @@ -= cowboy_req:uri(3) - -== Name - -cowboy_req:uri - Reconstructed URI - -== Description - -[source,erlang] ----- -uri(Req :: cowboy_req:req()) -> uri(Req, #{}) -uri(Req :: cowboy_req:req(), Opts) -> URI :: iodata() - -Opts :: #{ - scheme => iodata() | undefined, - host => iodata() | undefined, - port => inet:port_number() | undefined, - path => iodata() | undefined, - qs => iodata() | undefined, - fragment => iodata() | undefined -} ----- - -Reconstruct the effective request URI, optionally modifying components. - -By default Cowboy will build a URI using the components found -in the request. Options allow disabling or replacing individual -components. - -== Arguments - -Req:: - -The Req object. - -Opts:: - -Map for overriding individual components. -+ -To replace a component, provide its new value as a binary -string or an iolist. To disable a component, set its value -to `undefined`. -+ -As this function always returns a valid URI, there are some -things to note: -+ - * Disabling the host also disables the scheme and port. - * There is no fragment component by default as these are - not sent with the request. - * The port number may not appear in the resulting URI if - it is the default port for the given scheme (http: 80; https: 443). - -== Return value - -The reconstructed URI is returned as an iolist or a binary string. - -== Changelog - -* *2.0*: Individual components can be replaced or disabled. -* *2.0*: Only the URI is returned, it is no longer wrapped in a tuple. -* *2.0*: Function introduced. Replaces `host_url/1` and `url/1`. - -== Examples - -With an effective request URI http://example.org/path/to/res?edit=1 -we can have: - -.Protocol relative form -[source,erlang] ----- -%% //example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => undefined}). ----- - -.Serialized origin for use in the origin header -[source,erlang] ----- -%% http://example.org -cowboy_req:uri(Req, #{path => undefined, qs => undefined}). ----- - -.HTTP/1.1 origin form (path and query string only) -[source,erlang] ----- -%% /path/to/res?edit=1 -cowboy_req:uri(Req, #{host => undefined}). ----- - -.Add a fragment to the URI -[source,erlang] ----- -%% http://example.org/path/to/res?edit=1#errors -cowboy_req:uri(Req, #{fragment => <<"errors">>}). ----- - -.Ensure the scheme is HTTPS -[source,erlang] ----- -%% https://example.org/path/to/res?edit=1 -cowboy_req:uri(Req, #{scheme => <<"https">>}). ----- - -.Convert the URI to a binary string -[source,erlang] ----- -iolist_to_binary(cowboy_req:uri(Req)). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)], -link:man:cowboy_req:scheme(3)[cowboy_req:scheme(3)], -link:man:cowboy_req:host(3)[cowboy_req:host(3)], -link:man:cowboy_req:port(3)[cowboy_req:port(3)], -link:man:cowboy_req:path(3)[cowboy_req:path(3)], -link:man:cowboy_req:qs(3)[cowboy_req:qs(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.version.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.version.asciidoc deleted file mode 100644 index 15920c4196..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_req.version.asciidoc +++ /dev/null @@ -1,49 +0,0 @@ -= cowboy_req:version(3) - -== Name - -cowboy_req:version - HTTP version - -== Description - -[source,erlang] ----- -version(Req :: cowboy_req:req()) -> Version :: cowboy:http_version() ----- - -Return the HTTP version used for the request. - -The version can also be obtained using pattern matching: - -[source,erlang] ----- -#{version := Version} = Req. ----- - -== Arguments - -Req:: - -The Req object. - -== Return value - -The HTTP version used for the request is returned as an -atom. It is provided for informative purposes only. - -== Changelog - -* *2.0*: Only the version is returned, it is no longer wrapped in a tuple. -* *1.0*: Function introduced. - -== Examples - -.Get the HTTP version -[source,erlang] ----- -Version = cowboy_req:version(Req). ----- - -== See also - -link:man:cowboy_req(3)[cowboy_req(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_rest.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_rest.asciidoc deleted file mode 100644 index 9de896c197..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_rest.asciidoc +++ /dev/null @@ -1,738 +0,0 @@ -= cowboy_rest(3) - -== Name - -cowboy_rest - REST handlers - -== Description - -The module `cowboy_rest` implements the HTTP state machine. - -Implementing REST handlers is not enough to provide a REST -interface; this interface must also follow the REST -constraints including HATEOAS (hypermedia as the engine -of application state). - -== Callbacks - -REST handlers implement the following interface: - -[source,erlang] ----- -init(Req, State) - -> {cowboy_rest, Req, State} - -Callback(Req, State) - -> {Result, Req, State} - | {stop, Req, State} - | {{switch_handler, Module}, Req, State} - | {{switch_handler, Module, Opts}, Req, State} - -terminate(Reason, Req, State) -> ok %% optional - -Req :: cowboy_req:req() -State :: any() -Module :: module() -Opts :: any() -Reason :: normal - | {crash, error | exit | throw, any()} - -Callback - see below -Result - see below -Default - see below ----- - -The `init/2` callback is common to all handlers. To switch -to the REST handler behavior, it must return `cowboy_rest` -as the first element of the tuple. - -The `Callback/2` above represents all the REST-specific -callbacks. They are described in the following section -of this manual. REST-specific callbacks differ by their -name, semantics, result and default values. The default -value is the one used when the callback has not been -implemented. They otherwise all follow the same interface. - -The `stop` tuple can be returned to stop REST processing. -If no response was sent before then, Cowboy will send a -'204 No Content'. The `stop` tuple can be returned from -any callback, excluding `expires`, `generate_etag`, -`last_modified` and `variances`. - -A `switch_handler` tuple can be returned from these same -callbacks to stop REST processing and switch to a different -handler type. This is very useful to, for example, to stream -the response body. - -The optional `terminate/3` callback will ultimately be called -with the reason for the termination of the handler. -Cowboy will terminate the process right after this. There -is no need to perform any cleanup in this callback. - -The following terminate reasons are defined for loop handlers: - -normal:: - The handler terminated normally. - -{crash, Class, Reason}:: - A crash occurred in the handler. `Class` and `Reason` can be - used to obtain more information about the crash. The function - `erlang:get_stacktrace/0` can also be called to obtain the - stacktrace of the process when the crash occurred. - -== REST callbacks - -=== AcceptCallback - -[source,erlang] ----- -AcceptCallback(Req, State) -> {Result, Req, State} - -Result :: true | {true, URI :: iodata()} | false} -Default - crash ----- - -Process the request body. - -This function should create or update the resource using the -request body. - -For PUT requests, the body is a representation of the resource -that is being created or replaced. - -For POST requests, the body is typically application-specific -instructions on how to process the request, but it may also -be a representation of the resource. When creating a new -resource with POST at a different location, return `{true, URI}` -with `URI` the new location. - -For PATCH requests, the body is a series of instructions on -how to update the resource. Patch files or JSON Patch are -examples of such media types. - -A response body may be sent. The appropriate media type, charset -and language for the response can be retrieved from the Req -object using the `media_type`, `charset` and `language` keys, -respectively. The body can be set using -link:man:cowboy_req:set_resp_body(3)[cowboy_req:set_resp_body(3)]. - -=== allowed_methods - -[source,erlang] ----- -allowed_methods(Req, State) -> {Result, Req, State} - -Result :: [binary()] %% case sensitive -Default :: [<<"GET">>, <<"HEAD">>, <<"OPTIONS">>] ----- - -Return the list of allowed methods. - -=== allow_missing_post - -[source,erlang] ----- -allow_missing_post(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: true ----- - -Return whether POST is allowed when the resource doesn't exist. - -Returning `true` here means that a new resource will be -created. The URI for the newly created resource should be -returned from the `AcceptCallback` function. - -=== charsets_provided - -[source,erlang] ----- -charsets_provided(Req, State) -> {Result, Req, State} - -Result :: [binary()] %% lowercase; case insensitive -Default - skip this step ----- - -Return the list of charsets the resource provides in order -of preference. - -During content negotiation Cowboy will pick the most -appropriate charset for the client. The client advertises -charsets it prefers with the accept-charset header. When -that header is missing, Cowboy picks the first charset -from the resource. - -// @todo We should explain precisely how charsets are picked. - -Cowboy will add the negotiated `charset` to the Req object -after this step completes: - -[source,erlang] ----- -req() :: #{ - charset => binary() %% lowercase; case insensitive -} ----- - -Note that Cowboy will only append the charset to the -content-type header of the response if the media type is text. - -=== content_types_accepted - -[source,erlang] ----- -content_types_accepted(Req, State) -> {Result, Req, State} - -Result :: [{'*' | binary() | ParsedMime, AcceptCallback :: atom()}] -ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params} -Params :: [{Key :: binary(), Value :: binary()}] - -Default - crash ----- - -// @todo Case sensitivity of parsed mime content? - -Return the list of media types the resource accepts in -order of preference. - -A media type is made of different parts. The media type -`text/html;charset=utf-8` is of type `text`, subtype `html` -and has a single parameter `charset` with value `utf-8`. - -The special value `'*'` can be used to accept any media type. - -// @todo Cowboy needs to ignore the boundary parameter for -// multipart, as we never want to match against it. Or allow -// ignoring specific parameters at the very least. - -Cowboy will match the content-type request header against -the media types the server accepts and select the appropriate -callback. When that header is missing, or when the server does not -accept this media type, the request fails and an error response -is returned. Cowboy will execute the callback immediately otherwise. - -// @todo We should explain precisely how media types are picked. - -An empty parameters list `[]` means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom `'*'`. - -Cowboy treats all parameters as case sensitive, except for the -`charset` parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string. - -// @todo Maybe this should be in the user guide instead. -//This function will be called for POST, PUT and PATCH requests. -//It is entirely possible to define different callbacks for different -//methods if the handling of the request differs. Simply verify -//what the method is with `cowboy_req:method/1` and return a -//different list for each methods. - -=== content_types_provided - -[source,erlang] ----- -content_types_provided(Req, State) -> {Result, Req, State} - -Result :: [{binary() | ParsedMime, ProvideCallback :: atom()}] -ParsedMime :: {Type :: binary(), SubType :: binary(), '*' | Params} -Params :: [{Key :: binary(), Value :: binary()}] - -Default - [{{ <<"text">>, <<"html">>, '*'}, to_html}] ----- - -// @todo Case sensitivity of parsed mime content? -// @todo Space required for the time being: https://hub.fastgit.org/spf13/hugo/issues/2398 - -Return the list of media types the resource provides in -order of preference. - -A media type is made of different parts. The media type -`text/html;charset=utf-8` is of type `text`, subtype `html` -and has a single parameter `charset` with value `utf-8`. - -// @todo Cowboy needs to ignore the boundary parameter for -// multipart, as we never want to match against it. Or allow -// ignoring specific parameters at the very least. - -During content negotiation Cowboy will pick the most appropriate -media type for the client. The client advertises media types it -prefers with the accept header. When that header is missing, -the content negotiation fails and an error response is returned. - -The callback given for the selected media type will be called -at the end of the execution of GET and HEAD requests when a -representation must be sent to the client. - -// @todo We should explain precisely how media types are picked. - -An empty parameters list `[]` means that no parameters will be -accepted. When any parameter is acceptable, the tuple form -should be used with parameters as the atom `'*'`. - -Cowboy treats all parameters as case sensitive, except for the -`charset` parameter, which is known to be case insensitive. You -should therefore always provide the charset as a lowercase -binary string. - -When a charset is given in the media type parameters in the -accept header, Cowboy will do some additional checks to confirm -that it can use this charset. When the wildcard is used then Cowboy -will immediately call `charsets_provided` to confirm the charset -is acceptable. If the callback is undefined Cowboy assumes any -charset is acceptable. When the wildcard is not used and the charset -given in the accept header matches one of the configured media -types Cowboy will use that charset and skip the `charsets_provided` -step entirely. - -Cowboy will add the negotiated `media_type` to the Req object -after this step completes: - -[source,erlang] ----- -req() :: #{ - media_type => ParsedMime -} ----- - -// @todo Case sensitivity of parsed mime content? - -Cowboy may also add the negotiated `charset` to the Req object -after this step completes: - -[source,erlang] ----- -req() :: #{ - charset => binary() %% lowercase; case insensitive -} ----- - -=== delete_completed - -[source,erlang] ----- -delete_completed(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: true ----- - -Return whether the resource has been fully deleted from the -system, including from any internal cache. - -Returning `false` will result in a '202 Accepted' response -being sent instead of a '200 OK' or '204 No Content'. - -=== delete_resource - -[source,erlang] ----- -delete_resource(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Delete the resource. - -Cowboy will send an error response when this function -returns `false`. - -=== expires - -[source,erlang] ----- -expires(Req, State) -> {Result, Req, State} - -Result :: calendar:datetime() | binary() | undefined -Default :: undefined ----- - -Return the resource's expiration date. - -=== forbidden - -[source,erlang] ----- -forbidden(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Return whether access to the resource is forbidden. - -A '403 Forbidden' response will be sent if this -function returns `true`. This status code means that -access is forbidden regardless of authentication, -and that the request shouldn't be repeated. - -=== generate_etag - -[source,erlang] ----- -generate_etag(Req, State) -> {Result, Req, State} - -Result :: binary() | {weak | strong, binary()} -Default - no etag value ----- - -Return the entity tag of the resource. - -When a binary is returned, the value is automatically -parsed to a tuple. The binary must be in the same -format as the etag header, including quotes. - -=== is_authorized - -[source,erlang] ----- -is_authorized(Req, State) -> {Result, Req, State} - -Result :: true | {false, AuthHeader :: iodata()} -Default - true ----- - -Return whether the user is authorized to perform the action. - -This function should be used to perform any necessary -authentication of the user before attempting to perform -any action on the resource. - -When authentication fails, the `AuthHeader` value will -be sent in the www-authenticate header for the -'401 Unauthorized' response. - -=== is_conflict - -[source,erlang] ----- -is_conflict(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Return whether the PUT request results in a conflict. - -A '409 Conflict' response is sent when `true`. - -=== known_methods - -[source,erlang] ----- -known_methods(Req, State) -> {Result, Req, State} - -Result :: [binary()] %% case sensitive -Default :: [<<"GET">>, <<"HEAD">>, <<"POST">>, <<"PUT">>, - <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>] ----- - -Return the list of known methods. - -The full list of methods known by the server should be -returned, regardless of their use in the resource. - -The default value lists the methods Cowboy knows and -implement in `cowboy_rest`. - -=== languages_provided - -[source,erlang] ----- -languages_provided(Req, State) -> {Result, Req, State} - -Result :: [binary()] %% lowercase; case insensitive -Default - skip this step ----- - -Return the list of languages the resource provides in order -of preference. - -During content negotiation Cowboy will pick the most -appropriate language for the client. The client advertises -languages it prefers with the accept-language header. When -that header is missing, Cowboy picks the first language -from the resource. - -// @todo We should explain precisely how languages are picked. - -Cowboy will add the negotiated `language` to the Req object -after this step completes: - -[source,erlang] ----- -req() :: #{ - language => binary() %% lowercase; case insensitive -} ----- - -=== last_modified - -[source,erlang] ----- -last_modified(Req, State) -> {Result, Req, State} - -Result :: calendar:datetime() -Default - no last modified value ----- - -Return the resource's last modification date. - -This date will be used to test against the if-modified-since -and if-unmodified-since headers, and sent as the last-modified -header in the response to GET and HEAD requests. - -=== malformed_request - -[source,erlang] ----- -malformed_request(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Return whether the request is malformed. - -A request is malformed when a component required by the -resource is invalid. This may include the query string -or individual headers. They should be parsed and validated -in this function. The body should not be read at this point. - -=== moved_permanently - -[source,erlang] ----- -moved_permanently(Req, State) -> {Result, Req, State} - -Result :: {true, URI :: iodata()} | false -Default :: false ----- - -Return whether the resource was permanently moved, and -what its new location is. - -=== moved_temporarily - -[source,erlang] ----- -moved_temporarily(Req, State) -> {Result, Req, State} - -Result :: {true, URI :: iodata()} | false -Default :: false ----- - -Return whether the resource was temporarily moved, and -what its new location is. - -=== multiple_choices - -[source,erlang] ----- -multiple_choices(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Return whether the client should engage in reactive -negotiation. - -Return `true` when the server has multiple representations -of a resource, each with their specific identifier, but is -unable to determine which is best for the client. For -example an image might have different sizes and the server -is unable to determine the capabilities of the client. - -When returning `true` the server should send a body with -links to the different representations. If the server has -a preferred representation it can send its link inside a -location header. - -Note that when replying manually in this callback you -should either call `cowboy_req:reply/4` or remove the -response body that Cowboy sets to avoid surprises. - -=== options - -[source,erlang] ----- -options(Req, State) -> {ok, Req, State} ----- - -Respond to an OPTIONS request. - -The response should inform the client the communication -options available for this resource. By default Cowboy -will send a '200 OK' response with the allow header set. - -=== previously_existed - -[source,erlang] ----- -previously_existed(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Return whether the resource existed previously. - -=== ProvideCallback - -[source,erlang] ----- -ProvideCallback(Req, State) -> {Result, Req, State} - -Result :: cowboy_req:resp_body() -Default - crash ----- - -Return the response body. - -The response body can be provided either as the actual data -to be sent or a tuple indicating which file to send. - -This function is called for both GET and HEAD requests. For -the latter the body is not sent, however. - -// @todo Perhaps we can optimize HEAD requests and just -// allow calculating the length instead of returning the -// whole thing. - -Note that there used to be a way to stream the response body. -It was temporarily removed and will be added back in a later -release. - -// @todo Add a way to switch to loop handler for streaming the body. - -=== rate_limited - -[source,erlang] ----- -rate_limited(Req, State) -> {Result, Req, State} - -Result :: false | {true, RetryAfter} -RetryAfter :: non_neg_integer() | calendar:datetime() -Default - false ----- - -Return whether the user is rate limited. - -This function can be used to temporarily restrict -access to a resource when the user has issued too -many requests. - -When the resource is rate limited the `RetryAfter` -value will be sent in the retry-after header for the -'429 Too Many Requests' response. It indicates when -the resource will become available again and can be -specified as a number of seconds in the future or a -specific date/time. - -=== resource_exists - -[source,erlang] ----- -resource_exists(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: true ----- - -Return whether the resource exists. - -=== service_available - -[source,erlang] ----- -service_available(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: true ----- - -Return whether the service is available. - -A '503 Service Unavailable' response will be sent when this -function returns `false`. - -=== uri_too_long - -[source,erlang] ----- -uri_too_long(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: false ----- - -Return whether the requested URI is too long. - -This function can be used to further restrict the length -of the URI for this specific resource. - -=== valid_content_headers - -[source,erlang] ----- -valid_content_headers(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: true ----- - -Return whether the content headers are valid. - -This callback can be used to reject requests that have -invalid content header values, for example an unsupported -content-encoding. - -=== valid_entity_length - -[source,erlang] ----- -valid_entity_length(Req, State) -> {Result, Req, State} - -Result :: boolean() -Default :: true ----- - -Return whether the request body length is within acceptable boundaries. - -A '413 Request Entity Too Large' response will be sent if this -function returns `false`. - -=== variances - -[source,erlang] ----- -variances(Req, State) -> {Result, Req, State} - -Result :: [binary()] %% case insensitive -Default :: [] ----- - -Return the list of request headers that affect the -representation of the resource. - -Cowboy automatically adds the accept, accept-charset and -accept-language headers when necessary. It's also useful -to note that some standard headers also do not need to be -listed here, like the authorization header. - -== Changelog - -* *2.7*: The media type wildcard in `content_types_accepted` - is now documented. -* *2.6*: The callback `rate_limited` was added. -* *2.1*: The `switch_handler` return value was added. -* *1.0*: Behavior introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_handler(3)[cowboy_handler(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_router.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_router.asciidoc deleted file mode 100644 index d3c13064ac..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_router.asciidoc +++ /dev/null @@ -1,96 +0,0 @@ -= cowboy_router(3) - -== Name - -cowboy_router - Router middleware - -== Description - -The `cowboy_router` middleware maps the requested host and -path to the handler to be used for processing the request. - -The router takes the `dispatch` rules as input from the -middleware environment. Dispatch rules are generated by -calling the -link:man:cowboy_router:compile(3)[cowboy_router:compile(3)] -function. The environment can contain the rules directly -or a tuple `{persistent_term, Key}`, in which case Cowboy -will call `persistent_term:get(Key)` to retrieve the -dispatch rules. - -When a route matches, the router sets the `handler` and -`handler_opts` middleware environment values containing -the handler module and initial state, respectively. - -The router will stop execution when no route matches. -It will send a 400 response if no host was found, and -a 404 response otherwise. - -== Exports - -* link:man:cowboy_router:compile(3)[cowboy_router:compile(3)] - Compile routes to the resources - -== Types - -=== bindings() - -[source,erlang] ----- -bindings() :: #{atom() => any()} ----- - -Bindings found during routing. - -=== dispatch_rules() - -Opaque type containing the compiled routes. - -=== routes() - -[source,erlang] ----- -routes() = [ - {Host, PathList} | - {Host, Fields, PathList} -] - -PathList :: [ - {Path, Handler, InitialState} | - {Path, Fields, Handler, InitialState} -] - -Host :: '_' | iodata() -Path :: '_' | iodata() -Fields :: cowboy:fields() -Handler :: module() -InitialState :: any() ----- - -Human readable list of routes to handlers. - -Cowboy uses this list to map hosts and paths, optionally -augmented with constraints applied to the bindings, to -handler modules. - -The syntax for routes is currently defined in the user guide. - -// @todo The syntax should probably be in this module, -// and the user guide show more practical examples. - -=== tokens() - -[source,erlang] ----- -tokens() :: [binary()] ----- - -List of `host_info` and `path_info` tokens that were found -using the `...` syntax. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_req:binding(3)[cowboy_req:binding(3)], -link:man:cowboy_req:bindings(3)[cowboy_req:bindings(3)], -link:man:cowboy_req:host_info(3)[cowboy_req:host_info(3)], -link:man:cowboy_req:path_info(3)[cowboy_req:path_info(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_router.compile.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_router.compile.asciidoc deleted file mode 100644 index 187d790a74..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_router.compile.asciidoc +++ /dev/null @@ -1,53 +0,0 @@ -= cowboy_router:compile(3) - -== Name - -cowboy_router:compile - Compile routes to the resources - -== Description - -[source,erlang] ----- -compile(cowboy_router:routes()) -> cowboy_router:dispatch_rules() ----- - -Compile routes to the resources. - -Takes a human readable list of routes and transforms it -into a form more efficient to process. - -== Arguments - -Routes:: - -Human readable list of routes. - -== Return value - -An opaque dispatch rules value is returned. This value -must be given to Cowboy as a middleware environment value. - -== Changelog - -* *1.0*: Function introduced. - -== Examples - -.Compile routes and start a listener -[source,erlang] ----- -Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []}, - {"/[...]", cowboy_static, {priv_dir, my_example_app, ""}} - ]} -]), - -{ok, _} = cowboy:start_clear(example, [{port, 8080}], #{ - env => #{dispatch => Dispatch} -}). ----- - -== See also - -link:man:cowboy_router(3)[cowboy_router(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_static.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_static.asciidoc deleted file mode 100644 index 0e131dd1e0..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_static.asciidoc +++ /dev/null @@ -1,158 +0,0 @@ -= cowboy_static(3) - -== Name - -cowboy_static - Static file handler - -== Description - -The module `cowboy_static` implements file serving capabilities -using the REST semantics provided by `cowboy_rest`. - -The static file handler is a pre-written handler coming with -Cowboy. To serve files, use it in your routes. - -== Options - -[source,erlang] ----- -opts() :: {priv_file, App, Path} - | {priv_file, App, Path, Extra} - | {file, Path} - | {file, Path, Extra} - | {priv_dir, App, Path} - | {priv_dir, App, Path, Extra} - | {dir, Path} - | {dir, Path, Extra} - -App :: atom() -Path :: binary() | string() -Extra :: [Charset | Etag | Mimetypes] - -Charset :: {charset, module(), function()} - | {charset, binary()} - -Etag :: {etag, module(), function()} - | {etag, false} - -Mimetypes :: {mimetypes, module(), function()} - | {mimetypes, binary() | ParsedMime} - -ParsedMime :: {Type :: binary(), SubType :: binary(), Params} -Params :: [{Key :: binary(), Value :: binary()}] ----- - -Static handler configuration. - -priv_file:: - -Send a file. -+ -The path is relative to the given application's private -directory. - -file:: - -Send a file. -+ -The path is either absolute or relative to the Erlang node's -current directory. - -priv_dir:: - -Recursively serve files from a directory. -+ -The path is relative to the given application's private -directory. - -dir:: - -Recursively serve files from a directory. -+ -The path is either absolute or relative to the Erlang node's -current directory. - -The extra options allow you to define how the etag should be -calculated and how the MIME type of files should be detected. - -By default the static handler will not send a charset with -the response. You can provide a specific charset that will -be used for all files using the text media type, or provide -a module and function that will be called when needed: - -[source,erlang] ----- -detect_charset(Path :: binary()) -> Charset :: binary() ----- - -A charset must always be returned even if it doesn't make -sense considering the media type of the file. A good default -is `<<"utf-8">>`. - -By default the static handler will generate an etag based -on the size and modification time of the file. You may disable -the etag entirely with `{etag, false}` or provide a module -and function that will be called when needed: - -[source,erlang] ----- -generate_etag(Path, Size, Mtime) -> {strong | weak, binary()} - -Path :: binary() -Size :: non_neg_integer() -Mtime :: file:date_time() ----- - -By default the static handler will detect Web-related MIME types -by looking at the file extension. You can provide a specific -MIME type that will always be used, or a module and function that -will be called when needed: - -[source,erlang] ----- -detect_mimetype(Path) -> ParsedMime - -Path :: binary() -ParsedMime :: {Type :: binary(), SubType :: binary(), Params} -Params :: [{Key :: binary(), Value :: binary()}] ----- - -// @todo Case sensitivity of parsed mime content? - -Cowboy comes with two such functions; the default function -`cow_mimetypes:web/1`, and a second function generated from -the Apache 'mime.types' file, `cow_mimetypes:all/1`. - -The MIME type function should return -`{<<"application">>, <<"octet-stream">>, []}` -when it fails to detect a file's MIME type. - -== Changelog - -* *2.6*: The `charset` extra option was added. -* *1.0*: Handler introduced. - -== Examples - -.Custom etag function -[source,erlang] ----- -generate_etag(Path, Size, Mtime) -> - {strong, integer_to_binary( - erlang:phash2({Path, Size, Mtime}, 16#ffffffff))}. ----- - -.Custom MIME type function -[source,erlang] ----- -always_octet_stream(_Path) -> - case filename:extension(Path) of - <<".erl">> -> {<<"text">>, <<"plain">>, []}; - _ -> {<<"application">>, <<"octet-stream">>, []} - end. ----- - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_router(3)[cowboy_router(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_stream.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_stream.asciidoc deleted file mode 100644 index 65bd06ecd7..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_stream.asciidoc +++ /dev/null @@ -1,414 +0,0 @@ -= cowboy_stream(3) - -== Name - -cowboy_stream - Stream handlers - -== Description - -The module `cowboy_stream` defines a callback interface -and a protocol for handling HTTP streams. - -An HTTP request and its associated response is called -a stream. A connection may have many streams. In HTTP/1.1 -they are executed sequentially, while in HTTP/2 they are -executed concurrently. - -Cowboy calls the stream handler for nearly all events -related to a stream. Exceptions vary depending on the -protocol. - -Extra care must be taken when implementing stream handlers -to ensure compatibility. While some modification of the -events and commands is allowed, it is generally not a good -idea to completely discard them. - -== Callbacks - -Stream handlers must implement the following interface: - -[source,erlang] ----- -init(StreamID, Req, Opts) -> {Commands, State} -data(StreamID, IsFin, Data, State) -> {Commands, State} -info(StreamID, Info, State) -> {Commands, State} -terminate(StreamID, Reason, State) -> any() -early_error(StreamID, Reason, PartialReq, Resp, Opts) -> Resp - -StreamID :: cowboy_stream:streamid() -Req :: cowboy_req:req() -Opts :: cowboy:opts() -Commands :: cowboy_stream:commands() -State :: any() -IsFin :: cowboy_stream:fin() -Data :: binary() -Info :: any() -Reason :: cowboy_stream:reason() -PartialReq - cowboy_req:req(), except all fields are optional -Resp :: cowboy_stream:resp_command() ----- - -HTTP/1.1 will initialize a stream only when the request-line -and all headers have been received. When errors occur before -that point Cowboy will call the callback `early_error/5` -with a partial request, the error reason and the response -Cowboy intends to send. All other events go throuh the -stream handler using the normal callbacks. - -HTTP/2 will initialize the stream when the `HEADERS` block has -been fully received and decoded. Any protocol error occuring -before that will not result in a response being sent and -will therefore not go through the stream handler. In addition -Cowboy may terminate streams without sending an HTTP response -back. - -The stream is initialized by calling `init/3`. All streams -that are initialized will eventually be terminated by calling -`terminate/3`. - -When Cowboy receives data for the stream it will call `data/4`. -The data given is the request body after any transfer decoding -has been applied. - -When Cowboy receives a message addressed to a stream, or when -Cowboy needs to inform the stream handler that an internal -event has occurred, it will call `info/3`. - -[[commands]] -== Commands - -Stream handlers can return a list of commands to be executed -from the `init/3`, `data/4` and `info/3` callbacks. In addition, -the `early_error/5` callback must return a response command. - -// @todo The logger option and the {log, Level, Format, Args} -// options need to be documented and tested. - -The following commands are defined: - -[[inform_command]] -=== inform - -Send an informational response to the client. - -[source,erlang] ----- -{inform, cowboy:http_status(), cowboy:http_headers()} ----- - -Any number of informational responses may be sent, -but only until the final response is sent. - -[[response_command]] -=== response - -Send a response to the client. - -[source,erlang] ----- -{response, cowboy:http_status(), cowboy:http_headers(), - cowboy_req:resp_body()} ----- - -No more data can be sent after this command. - -Note that in Cowboy it is the `cowboy_req` module that -sets the date and server headers. When using the command -directly those headers will not be added. - -[[headers_command]] -=== headers - -Initiate a response to the client. - -[source,erlang] ----- -{headers, cowboy:http_status(), cowboy:http_headers()} ----- - -This initiates a response to the client. The stream -will end when a data command with the `fin` flag or -a trailer command is returned. - -Note that in Cowboy it is the `cowboy_req` module that -sets the date and server headers. When using the command -directly those headers will not be added. - -[[data_command]] -=== data - -Send data to the client. - -[source,erlang] ----- -{data, fin(), cowboy_req:resp_body()} ----- - -[[trailers_command]] -=== trailers - -Send response trailers to the client. - -[source,erlang] ----- -{trailers, cowboy:http_headers()} ----- - -[[push_command]] -=== push - -Push a resource to the client. - -[source,erlang] ----- -{push, Method, Scheme, Host, inet:port_number(), - Path, Qs, cowboy:http_headers()} - -Method = Scheme = Host = Path = Qs = binary() ----- - -The command will be ignored if the protocol does not provide -any server push mechanism. - -=== flow - -[source,erlang] ----- -{flow, pos_integer()} ----- - -Request more data to be read from the request body. The -exact behavior depends on the protocol. - -=== spawn - -Inform Cowboy that a process was spawned and should be -supervised. - -[source,erlang] ----- -{spawn, pid(), timeout()} ----- - -=== error_response - -Send an error response if no response was sent previously. - -[source,erlang] ----- -{error_response, cowboy:http_status(), cowboy:http_headers(), iodata()} ----- - -[[switch_protocol_command]] -=== switch_protocol - -Switch to a different protocol. - -[source,erlang] ----- -{switch_protocol, cowboy:http_headers(), module(), state()} ----- - -Contains the headers that will be sent in the 101 response, -along with the module implementing the protocol we are -switching to and its initial state. - -Note that the 101 informational response will not be sent -after a final response. - -=== stop - -Stop the stream. - -[source,erlang] ----- -stop ----- - -While no more data can be sent after the `fin` flag was set, -the stream is still tracked by Cowboy until it is stopped by -the handler. - -The behavior when stopping a stream for which no response -has been sent will vary depending on the protocol. The stream -will end successfully as far as the client is concerned. - -To indicate that an error occurred, either use `error_response` -before stopping, or use `internal_error`. - -=== internal_error - -Stop the stream with an error. - -[source,erlang] ----- -{internal_error, Reason, HumanReadable} - -Reason = any() -HumanReadable = atom() ----- - -This command should be used when the stream cannot continue -because of an internal error. An `error_response` command -may be sent before that to advertise to the client why the -stream is dropped. - -=== log - -Log a message. - -[source,erlang] ----- -{log, logger:level(), io:format(), list()} ----- - -This command can be used to log a message using the -configured `logger` module. - -=== set_options - -Set protocol options. - -[source,erlang] ----- -{set_options, map()} ----- - -This can also be used to override stream handler -options. For example this is supported by -link:man:cowboy_compress_h(3)[cowboy_compress_h(3)]. - -Not all options can be overriden. Please consult the -relevant option's documentation for details. - -== Predefined events - -Cowboy will forward all messages sent to the stream to -the `info/3` callback. To send a message to a stream, -the function link:man:cowboy_req:cast(3)[cowboy_req:cast(3)] -can be used. - -Cowboy will also forward the exit signals for the -processes that the stream spawned. - -When Cowboy needs to send a response it will trigger -an event that looks exactly like the corresponding -command. This event must be returned to be processed -by Cowboy (which is done automatically when using -link:man:cowboy_stream_h(3)[cowboy_stream_h(3)]). - -Cowboy may trigger the following events on its own, -regardless of the stream handlers configured: -xref:inform_command[inform] (to send a 101 -informational response when upgrading to HTTP/2 or -Websocket), xref:response_command[response], -xref:headers_command[headers], xref:data_command[data] -and xref:switch_protocol_command[switch_protocol]. - -== Exports - -The following function should be called by modules implementing -stream handlers to execute the next stream handler in the list: - -* link:man:cowboy_stream:init(3)[cowboy_stream:init(3)] - Initialize a stream -* link:man:cowboy_stream:data(3)[cowboy_stream:data(3)] - Handle data for a stream -* link:man:cowboy_stream:info(3)[cowboy_stream:info(3)] - Handle a message for a stream -* link:man:cowboy_stream:terminate(3)[cowboy_stream:terminate(3)] - Terminate a stream -* link:man:cowboy_stream:early_error(3)[cowboy_stream:early_error(3)] - Handle an early error for a stream - -== Types - -=== commands() - -[source,erlang] ----- -commands() :: [Command] ----- - -See the xref:commands[list of commands] for details. - -=== fin() - -[source,erlang] ----- -fin() :: fin | nofin ----- - -Used in commands and events to indicate that this is -the end of the stream. - -=== partial_req() - -[source,erlang] ----- -req() :: #{ - method => binary(), %% case sensitive - version => cowboy:http_version() | atom(), - scheme => binary(), %% lowercase; case insensitive - host => binary(), %% lowercase; case insensitive - port => inet:port_number(), - path => binary(), %% case sensitive - qs => binary(), %% case sensitive - headers => cowboy:http_headers(), - peer => {inet:ip_address(), inet:port_number()} -} ----- - -Partial request information received when an early error is -detected. - -=== reason() - -[source,erlang] ----- -reason() :: normal | switch_protocol - | {internal_error, timeout | {error | exit | throw, any()}, HumanReadable} - | {socket_error, closed | atom(), HumanReadable} - | {stream_error, Error, HumanReadable} - | {connection_error, Error, HumanReadable} - | {stop, cow_http2:frame() | {exit, any()}, HumanReadable} - -Error = atom() -HumanReadable = atom() ----- - -Reason for the stream termination. - -=== resp_command() - -[source,erlang] ----- -resp_command() :: {response, cowboy:http_status(), - cowboy:http_headers(), cowboy_req:resp_body()} ----- - -See the xref:response_command[response command] for details. - -=== streamid() - -[source,erlang] ----- -streamid() :: any() ----- - -The identifier for this stream. - -The identifier is unique over the connection process. -It is possible to form a unique identifier node-wide and -cluster-wide by wrapping it in a `{self(), StreamID}` -tuple. - -== Changelog - -* *2.7*: The `log` and `set_options` commands were introduced. -* *2.6*: The `data` command can now contain a sendfile tuple. -* *2.6*: The `{stop, {exit, any()}, HumanReadable}` terminate reason was added. -* *2.2*: The `trailers` command was introduced. -* *2.0*: Module introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_http(3)[cowboy_http(3)], -link:man:cowboy_http2(3)[cowboy_http2(3)], -link:man:cowboy_req:cast(3)[cowboy_req:cast(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_stream_h.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_stream_h.asciidoc deleted file mode 100644 index c25aa3d0a7..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_stream_h.asciidoc +++ /dev/null @@ -1,73 +0,0 @@ -= cowboy_stream_h(3) - -== Name - -cowboy_stream_h - Default stream handler - -== Description - -The module `cowboy_stream_h` is Cowboy's default stream -handler and defines much of its behavior. It is responsible -for managing the request process, sending it the request -body and translating its messages into commands that -Cowboy understands. - -== Options - -[source,erlang] ----- -opts() :: #{ - env => cowboy_middleware:env(), - middlewares => [module()], - shutdown_timeout => timeout() -} ----- - -Configuration for the default stream handler. - -The default value is given next to the option name: - -env (#{}):: - -Middleware environment. - -middlewares ([cowboy_router, cowboy_handler]):: - -Middlewares to run for every request. - -shutdown_timeout (5000):: - -Time in ms Cowboy will wait for child processes to shut down before killing them. - -== Events - -The default stream handler spawns the request process -and receives its exit signal when it terminates. It -will stop the stream once its receives it. - -// @todo It also implements the read_body mechanism. -// Note that cowboy_stream_h sends the 100-continue automatically. - -In addition it returns a command for any event message -looking like one of the following commands: `inform`, -`response`, `headers`, `data`, `trailers`, `push`, -`switch_protocol`. This is what allows the request -process to send a response. - -// @todo Add set_options, which updates options dynamically. - -Because this stream handler converts events from the -request process into commands, other stream handlers -may not work properly if they are executed - -== Changelog - -* *2.0*: Module introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_stream(3)[cowboy_stream(3)], -link:man:cowboy_compress_h(3)[cowboy_compress_h(3)], -link:man:cowboy_metrics_h(3)[cowboy_metrics_h(3)], -link:man:cowboy_tracer_h(3)[cowboy_tracer_h(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_tracer_h.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_tracer_h.asciidoc deleted file mode 100644 index e3592e464f..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_tracer_h.asciidoc +++ /dev/null @@ -1,88 +0,0 @@ -= cowboy_tracer_h(3) - -== Name - -cowboy_tracer_h - Tracer stream handler - -== Description - -The module `cowboy_tracer_h` can be used to conditionally -trace streams based on information found in the request. -Trace messages are given to the configured callback. - -== Options - -[source,erlang] ----- -opts() :: #{ - tracer_callback => Callback, - tracer_flags => [atom()], - tracer_match_specs => [MatchSpec] -} - -Callback :: fun((init | terminate | tuple(), State) -> State) - -MatchSpec :: MatchPredicate - | {method, binary()} - | {host, binary()} - | {path, binary()} - | {path_start, binary()} - | {header, binary()} - | {header, binary(), binary()} - | {peer_ip, inet:ip_address()} - -MatchPredicate :: fun((cowboy_stream:streamid(), - cowboy_req:req(), - cowboy:opts()) -> boolean()) -} ----- - -Configuration for the tracer stream handler. - -This module will not set trace patterns. Those must be -set by the user directly, either from the callback's -`init` or, preferably, in advance. - -tracer_callback:: - -The function that will be called for each trace -events. It will also be called before any trace -event with an argument `init`, and when the -stream is terminated with an argument `terminate`. -+ -This option is required for tracing to be enabled. -The tracer stream handler does nothing otherwise. - -tracer_flags:: - -Trace flags to enable. See the documentation -of `erlang:trace/3` for details. Note that all -trace flags are allowed except for the `tracer` -flag. - -tracer_match_specs:: - -A list of match conditions that must all be -fulfilled for the stream to be traced. Cowboy -will compare these with the information found -in the request and only enable tracing if all -matches succeed. -+ -This option is required for tracing to be enabled. -The tracer stream handler does nothing otherwise. - -== Events - -The tracer stream handler does not produce any event. - -== Changelog - -* *2.7*: Module introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_stream(3)[cowboy_stream(3)], -link:man:cowboy_compress_h(3)[cowboy_compress_h(3)], -link:man:cowboy_metrics_h(3)[cowboy_metrics_h(3)], -link:man:cowboy_stream_h(3)[cowboy_stream_h(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_websocket.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/cowboy_websocket.asciidoc deleted file mode 100644 index 59d412dfc4..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/cowboy_websocket.asciidoc +++ /dev/null @@ -1,293 +0,0 @@ -= cowboy_websocket(3) - -== Name - -cowboy_websocket - Websocket - -== Description - -The module `cowboy_websocket` implements Websocket -as a Ranch protocol. It also defines a callback interface -for handling Websocket connections. - -== Callbacks - -Websocket handlers must implement the following callback -interface: - -[source,erlang] ----- -init(Req, State) - -> {cowboy_websocket, Req, State} - | {cowboy_websocket, Req, State, Opts} - -websocket_init(State) -> CallResult %% optional -websocket_handle(InFrame, State) -> CallResult -websocket_info(Info, State) -> CallResult - -terminate(Reason, PartialReq, State) -> ok %% optional - -Req :: cowboy_req:req() -PartialReq :: map() -State :: any() -Opts :: cowboy_websocket:opts() -InFrame :: ping | pong | {text | binary | ping | pong, binary()} -Info :: any() - -CallResult :: {commands(), State} - | {commands(), State, hibernate} - | Deprecated - -Deprecated :: {ok, State} - | {ok, State, hibernate} - | {reply, OutFrame | [OutFrame], State} - | {reply, OutFrame | [OutFrame], State, hibernate} - | {stop, State} -OutFrame :: cow_ws:frame() %% see types below - -Reason :: normal | stop | timeout - | remote | {remote, cow_ws:close_code(), binary()} - | {error, badencoding | badframe | closed | atom()} - | {crash, error | exit | throw, any()} ----- - -The `init/2` callback is common to all handlers. To upgrade -the connection to Websocket, it must return `cowboy_websocket` -as the first element of the tuple. - -Any operation requiring the HTTP request must be done in the -`init/2` function, as the Req object will not be available -after it returns. Websocket sub-protocol selection should -therefore be done in this function. - -The optional `websocket_init/1` callback will be called once -the connection has been upgraded to Websocket. It can be used -to perform any required initialization of the handler. - -Note that the `init/2` function does not run in the same -process as the Websocket callbacks. Any Websocket-specific -initialization must be done in `websocket_init/1`. - -The `websocket_handle/2` callback will be called for every -frame received. The `websocket_info/2` callback will be -called for every Erlang message received. - -All three Websocket callbacks may send one or more frames -back to the client, including close frames to terminate -the connection; enable/disable active mode; enable/disable -compression for subsequent frames; or change Websocket options. - -The optional `terminate/3` callback will ultimately be called -with the reason for the termination of the connection. This -callback is common to all handlers. Note that Websocket will -not provide the full Req object by default, to save memory. - -Cowboy will terminate the process right after closing the -Websocket connection. This means that there is no need to -perform any cleanup in the `terminate/3` callback. - -The following terminate reasons are defined for Websocket -connections: - -normal:: - The connection was closed normally before establishing a Websocket - connection. This typically happens if an `ok` tuple is returned - from the `init/2` callback. - -remote:: - The remote endpoint closed the connection without giving any - further details. - -{remote, Code, Payload}:: - The remote endpoint closed the connection with the given - `Code` and `Payload` as the reason. - -stop:: - The handler requested to close the connection, either by returning - a `stop` tuple or by sending a `close` frame. - -timeout:: - The connection has been closed due to inactivity. The timeout - value can be configured from `init/2`. - -{crash, Class, Reason}:: - A crash occurred in the handler. `Class` and `Reason` can be - used to obtain more information about the crash. The function - `erlang:get_stacktrace/0` can also be called to obtain the - stacktrace of the process when the crash occurred. - -{error, badencoding}:: - A text frame was sent by the client with invalid encoding. All - text frames must be valid UTF-8. - -{error, badframe}:: - A protocol error has been detected. - -{error, closed}:: - The socket has been closed brutally without a close frame being - received first. - -{error, Reason}:: - A socket error ocurred. - -== Types - -=== commands() - -[source,erlang] ----- -commands() :: [Command] - -Command :: {active, boolean()} - | {deflate, boolean()} - | {set_options, #{idle_timeout => timeout()}} - | {shutdown_reason, any()} - | Frame :: cow_ws:frame() ----- - -Commands that may be returned from Websocket callbacks. - -The following commands are defined: - -active:: - -Whether to disable or enable reading from the socket. This -can be used to apply flow control to a Websocket connection. - -deflate:: - -Whether the subsequent frames should be compressed. Has no -effect on connections that did not negotiate compression. - -set_options:: - -Set Websocket options. Currently only the option `idle_timeout` -may be updated from a Websocket handler. - -shutdown_reason:: - -Change the shutdown reason. The Websocket process will exit -with reason `normal` by default. This command can be used to -exit with reason `{shutdown, ShutdownReason}` under normal -conditions. This command has no effect when the Websocket -process exits abnormally, for example following a crash in a -handler callback. - -Frame:: - -Send the corresponding Websocket frame. - -=== cow_ws:frame() - -[source,erlang] ----- -frame() :: {text, iodata()} - | {binary, iodata()} - | ping | {ping, iodata()} - | pong | {pong, iodata()} - | close | {close, iodata()} | {close, close_code(), iodata()} - -close_code() :: 1000..1003 | 1006..1011 | 3000..4999 ----- - -Websocket frames that can be sent as a response. - -Note that there is no need to send pong frames back as -Cowboy does it automatically for you. - -=== opts() - -[source,erlang] ----- -opts() :: #{ - compress => boolean(), - deflate_opts => cow_ws:deflate_opts() - idle_timeout => timeout(), - max_frame_size => non_neg_integer() | infinity, - req_filter => fun((cowboy_req:req()) -> map()), - validate_utf8 => boolean() -} ----- - -Websocket handler options. - -This configuration is passed to Cowboy from the `init/2` -function: - -[source,erlang] ----- -init(Req, State) -> - Opts = #{compress => true}, - {cowboy_websocket, Req, State, Opts}. ----- - -The default value is given next to the option name: - -compress (false):: - -Whether to enable the Websocket frame compression -extension. Frames will only be compressed for the -clients that support this extension. - -deflate_opts (#{}):: - -Configuration for the permessage-deflate Websocket -extension. Allows configuring both the negotiated -options and the zlib compression options. The -defaults optimize the compression at the expense -of some memory and CPU. - -idle_timeout (60000):: - -Time in milliseconds that Cowboy will keep the -connection open without receiving anything from -the client. -+ -This option can be updated at any time using the -`set_options` command. - -max_frame_size (infinity):: - -Maximum frame size in bytes allowed by this Websocket -handler. Cowboy will close the connection when -a client attempts to send a frame that goes over -this limit. For fragmented frames this applies -to the size of the reconstituted frame. - -req_filter:: - -A function applied to the Req to compact it and -only keep required information. The Req is only -given back in the `terminate/3` callback. By default -it keeps the method, version, URI components and peer -information. - -validate_utf8 (true):: - -Whether Cowboy should verify that the payload of -`text` and `close` frames is valid UTF-8. This is -required by the protocol specification but in some -cases it may be more interesting to disable it in -order to save resources. -+ -Note that `binary` frames do not have this UTF-8 -requirement and are what should be used under -normal circumstances if necessary. - -== Changelog - -* *2.7*: The commands based interface has been documented. - The old interface is now deprecated. -* *2.7*: The command `shutdown_reason` was introduced. -* *2.7*: The option `validate_utf8` has been added. -* *2.6*: Deflate options can now be configured via `deflate_opts`. -* *2.0*: The Req object is no longer passed to Websocket callbacks. -* *2.0*: The callback `websocket_terminate/3` was removed in favor of `terminate/3`. -* *1.0*: Protocol introduced. - -== See also - -link:man:cowboy(7)[cowboy(7)], -link:man:cowboy_handler(3)[cowboy_handler(3)], -link:man:cowboy_http(3)[cowboy_http(3)], -link:man:cowboy_http2(3)[cowboy_http2(3)] diff --git a/_build/emqx/lib/cowboy/doc/src/manual/http_status_codes.asciidoc b/_build/emqx/lib/cowboy/doc/src/manual/http_status_codes.asciidoc deleted file mode 100644 index 172272a2b7..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/manual/http_status_codes.asciidoc +++ /dev/null @@ -1,157 +0,0 @@ -= HTTP status codes(7) - -== Name - -HTTP status codes - status codes used by Cowboy - -== Description - -This chapter aims to list all HTTP status codes that Cowboy -may return, with details on the reasons why. The list given -here only includes the replies that Cowboy sends, not user -replies. - -== 100 Continue - -When the client sends an `expect: 100-continue` header, -Cowboy automatically sends a this status code before -trying to read the request body. This behavior can be -disabled using the appropriate body option. - -== 101 Switching Protocols - -This is the status code sent when switching to the -Websocket protocol. - -== 200 OK - -This status code is sent by `cowboy_rest`. - -== 201 Created - -This status code is sent by `cowboy_rest`. - -== 202 Accepted - -This status code is sent by `cowboy_rest`. - -== 204 No Content - -This status code is sent when the processing of a request -ends without any reply having been sent. It may also be -sent by `cowboy_rest` under normal conditions. - -== 300 Multiple Choices - -This status code is sent by `cowboy_rest`. - -== 301 Moved Permanently - -This status code is sent by `cowboy_rest`. - -== 303 See Other - -This status code is sent by `cowboy_rest`. - -== 304 Not Modified - -This status code is sent by `cowboy_rest`. - -== 307 Temporary Redirect - -This status code is sent by `cowboy_rest`. - -== 400 Bad Request - -Cowboy will send this status code for any of the -following reasons: - -* Too many empty lines were sent before the request. -* The request-line could not be parsed. -* Too many headers were sent. -* A header name was too long. -* A header value was too long. -* The host header was missing from an HTTP/1.1 request. -* The host header could not be parsed. -* The requested host was not found. -* The requested path could not be parsed. -* The accept header could not be parsed when using REST. -* REST under normal conditions. -* A Websocket upgrade failed. - -== 401 Unauthorized - -This status code is sent by `cowboy_rest`. - -== 403 Forbidden - -This status code is sent by `cowboy_rest`. - -== 404 Not Found - -This status code is sent when the router successfully -resolved the host but didn't find a matching path for -the request. It may also be sent by `cowboy_rest` under -normal conditions. - -== 405 Method Not Allowed - -This status code is sent by `cowboy_rest`. - -== 406 Not Acceptable - -This status code is sent by `cowboy_rest`. - -== 408 Request Timeout - -Cowboy will send this status code to the client if the -client started to send a request, indicated by the -request-line being received fully, but failed to send -all headers in a reasonable time. - -== 409 Conflict - -This status code is sent by `cowboy_rest`. - -== 410 Gone - -This status code is sent by `cowboy_rest`. - -== 412 Precondition Failed - -This status code is sent by `cowboy_rest`. - -== 413 Request Entity Too Large - -This status code is sent by `cowboy_rest`. - -== 414 Request-URI Too Long - -Cowboy will send this status code to the client if the -request-line is too long. It may also be sent by -`cowboy_rest` under normal conditions. - -== 415 Unsupported Media Type - -This status code is sent by `cowboy_rest`. - -== 500 Internal Server Error - -This status code is sent when a crash occurs in HTTP, loop -or REST handlers, or when an invalid return value is -returned. It may also be sent by `cowboy_rest` under -normal conditions. - -== 501 Not Implemented - -This status code is sent by `cowboy_rest`. - -== 503 Service Unavailable - -This status code is sent by `cowboy_rest`. - -== 505 HTTP Version Not Supported - -Cowboy only supports the versions 1.0 and 1.1 of HTTP. -In all other cases this status code is sent back to the -client and the connection is closed. diff --git a/_build/emqx/lib/cowboy/doc/src/specs/index.ezdoc b/_build/emqx/lib/cowboy/doc/src/specs/index.ezdoc deleted file mode 100644 index 847780be24..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/specs/index.ezdoc +++ /dev/null @@ -1,7 +0,0 @@ -::: Cowboy Implementation Reference - -The implementation reference documents the behavior of Cowboy -with regards to various standards and specifications. - -* ^"RFC6585 status codes^rfc6585 -* ^"RFC7230 HTTP/1.1 server^rfc7230_server diff --git a/_build/emqx/lib/cowboy/doc/src/specs/rfc6585.ezdoc b/_build/emqx/lib/cowboy/doc/src/specs/rfc6585.ezdoc deleted file mode 100644 index 7b19aa0a70..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/specs/rfc6585.ezdoc +++ /dev/null @@ -1,44 +0,0 @@ -::: RFC6585 - -This document lists status codes that Cowboy implements as -defined in the RFC6585 specifications. - -:: Status codes - -: 428 Precondition Required (RFC6585 3) - -The server requires the request to this resource to be conditional. - -The response should explain how to resubmit the request successfully. - -: 429 Too Many Requests (RFC6585 4, RFC6585 7.2) - -The user has sent too many requests in a given amount of time. - -The response should detail the rates allowed. - -The retry-after header can be used to indicate how long the -user has to wait before making a new request. - -When an attack is detected it is recommended to drop the -connection directly instead of sending this response. - -: 431 Request Header Fields Too Large (RFC6585 5, RFC6585 7.3) - -The request's header fields are too large. - -When rejecting a single header, the response should detail -which header was at fault. - -When an attack is detected it is recommended to drop the -connection directly instead of sending this response. - -: 511 Network Authentication Required (RFC6585 6) - -The user needs to authenticate into the network to gain access. - -This status code is meant to be used by proxies only, not by -origin servers. - -The response should contain a link to the resource allowing -the user to log in. diff --git a/_build/emqx/lib/cowboy/doc/src/specs/rfc7230_server.ezdoc b/_build/emqx/lib/cowboy/doc/src/specs/rfc7230_server.ezdoc deleted file mode 100644 index 2497f5652f..0000000000 --- a/_build/emqx/lib/cowboy/doc/src/specs/rfc7230_server.ezdoc +++ /dev/null @@ -1,887 +0,0 @@ -::: RFC7230 HTTP/1.1 server - -This document lists the rules the Cowboy server follows based -on the RFC7230 HTTP specifications. - -:: Listener - -The default port for "http" connections is 80. The connection -uses plain TCP. (RFC7230 2.7.1) - -The default port for "https" connections is 443. The connection -uses TLS. (RFC7230 2.7.2) - -Any other port may be used for either of them. - -:: Before the request - -A configurable number of empty lines (CRLF) preceding the request -must be ignored. At least 1 empty line must be ignored. (RFC7230 3.5) - -When receiving a response instead of a request, identified by the -status-line which starts with the HTTP version, the server must -reject the message with a 501 status code and close the connection. (RFC7230 3.1) - -:: Request - -It is only necessary to parse elements required to process the -request. (RFC7230 2.5) - -Parsed elements are subject to configurable limits. A server must -be able to parse elements at least as long as it generates. (RFC7230 2.5) - -The request must be parsed as a sequence of octets in an encoding -that is a superset of US-ASCII. (RFC7230 2.5) - -``` -HTTP-request = request-line *( header-field CRLF ) CRLF [ message-body ] -``` - -The general format of HTTP requests is strict. No empty line is -allowed in-between components except for the empty line -indicating the end of the list of headers. - -It is not necessary to read the message-body before processing -the request as the message-body may be dropped depending on the -outcome of the processing. - -The time the request (request line and headers) takes to be -received by the server must be limited and subject to configuration. -A server must wait at least 5 seconds before dropping the connection. -A 408 status code must be sent if the request line was received -fully when the timeout is triggered. - -An HTTP/1.1 server must understand any valid HTTP/1.0 request, -and respond to those with an HTTP/1.1 message that only use -features understood or safely ignored by HTTP/1.0 clients. (RFC7230 A) - -:: Request line - -It is recommended to limit the request-line length to a configurable -limit of at least 8000 octets. However, as the possible line length is -highly dependent on what form the request-target takes, it is preferrable -to limit each individual components of the request-target. (RFC7230 3.1.1) - -A request line too long must be rejected with a 414 status code -and the closing of the connection. (RFC7230 3.1.1) - -``` -method SP request-target SP version CRLF -``` - -:: Method - -``` -method = token ; case sensitive -token = 1*tchar -tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA -``` - -The request method is defined as 1+ token characters. An invalid -or empty method must be rejected with a 400 status code and the -closing of the connection. (RFC7230 3.1.1, RFC7230 3.2.6) - -In practice the only characters in use by registered methods are -uppercase letters [A-Z] and the dash "-". (IANA HTTP Method Registry) - -The length of the method must be subject to a configurable limit. -A method too long must be rejected with a 501 status code and the -closing of the connection. (RFC7230 3.1.1) - -A good default for the method length limit is the longest method -length the server implements. (RFC7230 3.1.1) - -:: Between method and request-target - -A request that uses anything other than SP as separator between -the method and the request-target must be rejected with a 400 -status code and the closing of the connection. (RFC7230 3.1.1, RFC7230 3.5) - -:: Request target - -There are four request-target forms. A server must be able to -handle at least origin-form and absolute-form. The other two -forms are specific to the CONNECT and site-wide OPTIONS method, -respectively. (RFC7230 5.3.2) - -The fragment part of the target URI is not sent. It must be -ignored by a server receiving it. (RFC7230 5.1) - -``` -request-target = origin-form / absolute-form / authority-form / asterisk-form -``` - -Any other form is invalid and must be rejected with a 400 -status code and the closing of the connection. - -: origin-form - -origin-form is used when the client does not connect to a proxy, -does not use the CONNECT method and does not issue a site-wide -OPTIONS request. (RFC7230 5.3.1) - -``` -origin-form = absolute-path [ "?" query ] -absolute-path = 1*( "/" segment ) -segment = *pchar -query = *( pchar / "/" / "?" ) - -pchar = unreserved / pct-encoded / sub-delims / ":" / "@" -unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -pct-encoded = "%" HEXDIG HEXDIG -sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" -``` - -The scheme is either resolved from configuration or is "https" -when on a TLS connection and "http" otherwise. (RFC7230 5.5) - -The authority is sent in the host header. (RFC7230 5.3.1, RFC7230 5.5) - -The absolute-path always starts with "/" and ends with either "?", "#" -or the end of the URI. (RFC3986 3.3) - -The query starts with "?" and ends with "#" or the end of the URI. (RFC3986 3.4) - -The path and query must be subject to a configurable limit. -This limit must be at least as high as what the server generates. -A good default would be 8000 characters. (RFC7230 2.5, RFC7230 3.1.1) - -A request with a too long origin-form must be rejected with -a 414 status code and the closing of the connection. (RFC7230 3.1.1) - -: absolute-form - -absolute-form is used when the client connects to a proxy, though -its usage is also allowed when connecting to the server directly. (RFC7230 5.3.2) - -In practice the scheme will be "http" or "https". - -The "http" and "https" schemes based URI take the following form. (RFC7230 2.7.1, RFC7230 2.7.2) - -``` -http-URI = "http:" "//" authority path-abempty [ "?" query ] [ "#" fragment ] -https-URI = "https:" "//" authority path-abempty [ "?" query ] [ "#" fragment ] -``` - -The target URI excludes the fragment component. (RFC7230 5.1) - -This means that the absolute-form uses a subset of absolute-URI. - -``` -absolute-form = ( "http" / "https" ) "://" authority path-abempty [ "?" query ] -authority = host [ ":" port ] -path-abempty = *( "/" segment ) -query = *( pchar / "/" / "?" ) - -host = IP-literal / IPv4address / reg-name -port = *DIGIT - -IP-literal = "[" ( IPv6address / IPvFuture ) "]" - -IPv6address = 6( h16 ":" ) ls32 - / "::" 5( h16 ":" ) ls32 - / [ h16 ] "::" 4( h16 ":" ) ls32 - / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - / [ *4( h16 ":" ) h16 ] "::" ls32 - / [ *5( h16 ":" ) h16 ] "::" h16 - / [ *6( h16 ":" ) h16 ] "::" - -ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address -h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal - -IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - -dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35 - -IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - -reg-name = *( unreserved / pct-encoded / sub-delims ) - -segment = *pchar -segment-nz = 1*pchar - -pchar = unreserved / pct-encoded / sub-delims / ":" / "@" -unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -pct-encoded = "%" HEXDIG HEXDIG -sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" -``` - -The scheme and host are case insensitive and normally provided in lowercase. -All other components are case sensitive. (RFC7230 2.7.3) - -Unknown schemes must be rejected with a 400 status code and the -closing of the connection. Because only a fixed number of schemes -are allowed, it is not necessary to limit its length. - -The scheme provided with the request must be dropped. The effective -scheme is either resolved from configuration or is "https" when on -a TLS connection and "http" otherwise. (RFC7230 5.5) - -An authority component with a userinfo component (and its -"@" delimiter) is invalid. The request must be rejected with -a 400 status code and the closing of the connection. (RFC7230 2.7.1) - -A URI with a missing host identifier is invalid. The request must -be rejected with a 400 status code and the closing of the connection. (RFC7230 2.7.1) - -The maximum length for an IPv4address is 15 characters. No -configurable limit is necessary. - -The maximum length for an IPv6address is 47 characters. No -configurable limit is necessary. - -The maximum length for the reg-name component must be subject -to a configurable limit. A good default is 255 characters. (RFC3986 3.2.2, RFC1034 3.1) - -It is not possible to distinguish between an IPv4address and -a reg-name before reaching the end of the string, therefore -the length limit for IPv4address must be ignored until that -point. - -The maximum length for the port component is 5. No configurable -limit is necessary. - -The authority is sent both in the URI and in the host header. -The authority from the URI must be dropped, and the host header -must be used instead. (RFC7230 5.5) - -The path always starts with "/" and ends with either "?", "#" -or the end of the URI. (RFC3986 3.3) - -An empty path component is equivalent to "/". (RFC7230 2.7.3) - -The query starts with "?" and ends with "#" or the end of the URI. (RFC3986 3.4) - -The path and query must be subject to a configurable limit. -This limit must be at least as high as what the server generates. -A good default would be 8000 characters. (RFC7230 2.5, RFC7230 3.1.1) - -A request with a too long component of absolute-form must be rejected with -a 414 status code and the closing of the connection. (RFC7230 3.1.1) - -: authority-form - -When the method is CONNECT, authority-form must be used. This -form does not apply to any other methods which must reject the -request with a 400 status code and the closing of the connection. (RFC7230 5.3.3) - -``` -authority-form = authority -authority = host [ ":" port ] -host = IP-literal / IPv4address / reg-name -port = *DIGIT - -IP-literal = "[" ( IPv6address / IPvFuture ) "]" - -IPv6address = 6( h16 ":" ) ls32 - / "::" 5( h16 ":" ) ls32 - / [ h16 ] "::" 4( h16 ":" ) ls32 - / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - / [ *4( h16 ":" ) h16 ] "::" ls32 - / [ *5( h16 ":" ) h16 ] "::" h16 - / [ *6( h16 ":" ) h16 ] "::" - -ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address -h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal - -IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - -dec-octet = DIGIT / %x31-39 DIGIT / "1" 2DIGIT / "2" %x30-34 DIGIT / "25" %x30-35 - -IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - -reg-name = *( unreserved / pct-encoded / sub-delims ) - -unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -pct-encoded = "%" HEXDIG HEXDIG -sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" -``` - -An authority component with a userinfo component (and its -"@" delimiter) is invalid. The request must be rejected with -a 400 status code and the closing of the connection. (RFC7230 2.7.1) - -The maximum length for an IPv4address is 15 characters. No -configurable limit is necessary. - -The maximum length for an IPv6address is 47 characters. No -configurable limit is necessary. - -The maximum length for the reg-name component must be subject -to a configurable limit. A good default is 255 characters. (RFC3986 3.2.2, RFC1034 3.1) - -It is not possible to distinguish between an IPv4address and -a reg-name before reaching the end of the string, therefore -the length limit for IPv4address must be ignored until that -point. - -The maximum length for the port component is 5. No configurable -limit is necessary. - -A request with a too long component of authority-form must be rejected with -a 414 status code and the closing of the connection. (RFC7230 3.1.1) - -The authority is either resolved from configuration or is taken -directly from authority-form. (RFC7230 5.5) - -The path and query are empty when using authority-form. (RFC7230 5.5) - -: asterisk-form - -asterisk-form is used for server-wide OPTIONS requests. -It is invalid with any other methods which must reject the -request with a 400 status code and the closing of the connection. (RFC7230 5.3.4) - -``` -asterisk-form = "*" -``` - -The asterisk-form always has a length of 1. No configurable limit -is necessary. - -The authority is empty when using asterisk-form. - -The path and query are empty when using asterisk-form. (RFC7230 5.5) - -:: Between request-target and version - -A request that uses anything other than SP as separator between -the request-target and the version must be rejected with a 400 -status code and the closing of the connection. (RFC7230 3.1.1, RFC7230 3.5) - -:: Request version - -``` -version = "HTTP/1.0" / "HTTP/1.1" -``` - -Any version number other than HTTP/1.0 or HTTP/1.1 must be -rejected by a server or intermediary with a 505 status code. (RFC7230 2.6, RFC7230 A.2) - -A request that has any whitespace or characters different than -CRLF following the version must be rejected with a 400 status -code and the closing of the connection. (RFC7230 3.1.1) - -:: Request headers - -``` -headers = *( header-field CRLF ) CRLF -header-field = field-name ":" OWS field-value OWS - -field-name = token -field-value = *( SP / HTAB / %21-7E / %80-FF ) - -OWS = *( SP / HTAB ) -``` - -The header field name is case insensitive. (RFC7230 3.2) - -HTTP/2 requires header field names to be lowercase. It is -perfectly acceptable for a server supporting both to convert -HTTP/1.1 header names to lowercase when they are received. (draft-ietf-httpbis-http2-15 8.1.2.1) - -Messages that contain whitespace before the header name must -be rejected with a 400 status code and the closing of the -connection. (RFC7230 3.2.4) - -Messages that contain whitespace between the header name and -colon must be rejected with a 400 status code and the closing -of the connection. (RFC7230 3.2.4) - -The header name must be subject to a configurable limit. A -good default is 50 characters, well above the longest registered -header. Such a request must be rejected with a 431 status code -and the closing of the connection. (RFC7230 3.2.5, RFC6585 5, IANA Message Headers registry) - -The header value and the optional whitespace around it must be -subject to a configurable limit. There is no recommendations -for the default. 4096 characters is known to work well. Such -a request must be rejected with a 431 status code and the closing -of the connection. (RFC7230 3.2.5, RFC6585 5) - -Optional whitespace before and after the header value is not -part of the value and must be dropped. - -The order of header fields with differing names is not significant. (RFC7230 3.2.2) - -The normal procedure for parsing headers is to read each header -field into a hash table by field name until the empty line. (RFC7230 3) - -Requests with duplicate content-length or host headers must be rejected -with a 400 status code and the closing of the connection. (RFC7230 3.3.2) - -Other duplicate header fields must be combined by inserting a comma -between the values in the order they were received. (RFC7230 3.2.2) - -Duplicate header field names are only allowed when their value is -a comma-separated list. In practice there is no need to perform -a check while reading the headers as the value will become invalid -and the error can be handled while parsing the header later on. (RFC7230 3.2.2) - -The request must not be processed until all headers have arrived. (RFC7230 3.2.2) - -The number of headers allowed in a request must be subject to -a configurable limit. There is no recommendations for the default. -100 headers is known to work well. Such a request must be rejected -with a 431 status code and the closing of the connection. (RFC7230 3.2.5, RFC6585 5) - -When parsing header field values, the server must ignore empty -list elements, and not count those as the count of elements present. (RFC7230 7) - -The information in the via header is largely unreliable. (RFC7230 5.7.1) - -:: Request body - -``` -message-body = *OCTET -``` - -The message body is the octets after decoding any transfer -codings. (RFC7230 3.3) - -A request has a message body only if it includes a transfer-encoding -header or a non-zero content-length header. (RFC7230 3.3) - -``` -Transfer-Encoding = 1#transfer-coding - -transfer-coding = "chunked" / "compress" / "deflate" / "gzip" / transfer-extension -transfer-extension = token *( OWS ";" OWS transfer-parameter ) -transfer-parameter = token BWS "=" BWS ( token / quoted-string ) -``` - -The transfer-coding is case insensitive. (RFC7230 4) - -There are no known other transfer-extension with the exception of -deprecated aliases "x-compress" and "x-gzip". (IANA HTTP Transfer Coding Registry, -RFC7230 4.2.1, RFC7230 4.2.3, RFC7230 8.4.2) - -A server must be able to handle at least chunked transfer-encoding. -This is also the only coding that sees widespread use. (RFC7230 3.3.1, RFC7230 4.1) - -Messages encoded more than once with chunked transfer-encoding -must be rejected with a 400 status code and the closing of the -connection. (RFC7230 3.3.1) - -Messages where chunked, when present, is not the last -transfer-encoding must be rejected with a 400 status code -and the closing of the connection. (RFC7230 3.3.3) - -Some non-conformant implementations send the "deflate" compressed -data without the zlib wrapper. (RFC7230 4.2.2) - -Messages encoded with a transfer-encoding the server does not -understand must be rejected with a 501 status code and the -closing of the connection. (RFC7230 3.3.1) - -A server can reject requests with a body and no content-length -header with a 411 status code. (RFC7230 3.3.3) - -``` -Content-Length = 1*DIGIT -``` - -A request with an invalid content-length header must be rejected -with a 400 status code and the closing of the connection. (RFC7230 3.3.3) - -The content-length header ranges from 0 to infinity. Requests -with a message body too large must be rejected with a 413 status -code and the closing of the connection. (RFC7230 3.3.2) - -When a message includes both transfer-encoding and content-length -headers, the content-length header must be removed before processing -the request. (RFC7230 3.3.3) - -If a socket error occurs while reading the body the server -must send a 400 status code response and close the connection. (RFC7230 3.3.3, RFC7230 3.4) - -If a timeout occurs while reading the body the server must -send a 408 status code response and close the connection. (RFC7230 3.3.3, RFC7230 3.4) - -: Body length - -The length of a message with a transfer-encoding header can -only be determined on decoding completion. (RFC7230 3.3.3) - -The length of a message with a content-length header is -the numeric value in octets found in the header. (RFC7230 3.3.3) - -A message with no transfer-encoding or content-length header -has a body length of 0. (RFC7230 3.3.3) - -: Chunked transfer-encoding - -``` -chunked-body = *chunk last-chunk trailer-part CRLF - -chunk = chunk-size [ chunk-ext ] CRLF chunk-data CRLF -chunk-size = 1*HEXDIG -chunk-data = 1*OCTET ; a sequence of chunk-size octets - -last-chunk = 1*("0") [ chunk-ext ] CRLF -``` - -The chunk-size field is a string of hex digits indicating the size of -the chunk-data in octets. - -``` -chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) -chunk-ext-name = token -chunk-ext-val = token / quoted-string -``` - -Unknown chunk extensions must be ignored. (RFC7230 4.1.1) - -The chunk-size line length must be subject to configuration. -There are no recommended defaults, although 100 octets should work. -Requests with a too long line must be rejected with a 400 status -code and the closing of the connection. - -``` -trailer-part = *( header-field CRLF ) -``` - -Trailing headers must not include transfer-encoding, content-length, -host, cache-control, expect, max-forwards, pragma, range, te, -if-match, if-none-match, if-modified-since, if-unmodified-since, -if-range, www-authenticate, authorization, proxy-authenticate, -proxy-authorization, age, cache-control, expires, date, location, -retry-after, vary, warning, content-encoding, content-type, -content-range, or trailer. (RFC7230 4.1.2) - -Trailer headers can be ignored safely. (RFC7230 4.1.2) - -When trailer headers are processed, invalid headers must be ignored. -Valid headers must be added to the list of headers of the request. (RFC7230 4.1.2) - -The number of trailer headers must be subject to configuration. -There is no known recommendations for the default. A value of 10 -should cover most cases. Requests with too many trailer headers -must be rejected with a 431 status code and the closing of the -connection. (RFC6585 5) - -Upon completion of chunk decoding the server must add a content-length -header with the value set to the total length of data read. (RFC7230 4.1.3) - -Upon completion of chunk decoding the server must remove "chunked" -from the transfer-encoding header. This header must be removed if -it becomes empty following this removal. (RFC7230 4.1.3) - -Upon completion of chunk decoding the server must remove the trailer -header from the list of headers. (RFC7230 4.1.3) - -``` -Trailer = 1#field-name -``` - -The trailer header can be used to list the headers found in the -trailer. A server must have the option of ignoring trailer headers -that were not listed in the trailer header. (RFC7230 4.4) - -The trailer header must be listed in the connection header field. -Trailers must be ignored otherwise. - -:: Connection management - -Never assume any two requests on a single connection come -from the same user agent. (RFC7230 2.3) - -``` -Connection = 1#token ; case-insensitive -``` - -The connection token is either case insensitive "close", "keep-alive" -or a header field name. - -There are no corresponding "close" or "keep-alive" headers. (RFC7230 8.1, RFC7230 A.2) - -The connection header is valid only for the immediate connection, -alongside any header field it lists. (RFC7230 6.1) - -The server must determine if the connection is persistent for -every message received by looking at the connection header and -HTTP version. (RFC7230 6.3) - -HTTP/1.1 requests with no "close" option and HTTP/1.0 with the -"keep-alive" option indicate the connection will persist. (RFC7230 6.1, RFC7230 6.3) - -HTTP/1.1 requests with the "close" option and HTTP/1.0 with no -"keep-alive" option indicate the connection will be closed -upon reception of the response by the client. (RFC7230 6.1, RFC7230 6.3) - -The maximum number of requests sent using a persistent connection -must be subject to configuration. The connection must be closed -when the limit is reached. (RFC7230 6.3) - -A server that doesn't want to read the entire body of a message -must close the connection, if possible after sending the "close" -connection option in the response. (RFC7230 6.3) - -A server can receive more than one request before any response -is sent. This is called pipelining. The requests can be processed -in parallel if they all have safe methods. Responses must be sent -in the same order as the requests. (RFC7230 6.3.2) - -The server must reject abusive traffic by closing the connection. -Abusive traffic can come from the form of too many requests in a -given amount of time, or too many concurrent connections. Limits -must be subject to configuration. (RFC7230 6.4) - -The server must close inactive connections. The timeout -must be subject to configuration. (RFC7230 6.5) - -The server must monitor connections for the close signal -and close the socket on its end accordingly. (RFC7230 6.5) - -A connection close may occur at any time. (RFC7230 6.5) - -The server must not process any request after sending or -receiving the "close" connection option. (RFC7230 6.6) - -The server must close the connection in stages to avoid the -TCP reset problem. The server starts by closing the write -side of the socket. The server then reads until it detects -the socket has been closed, until it can be certain its -last response has been received by the client, or until -a close or timeout occurs. The server then fully close the -connection. (6.6) - -:: Routing - -``` -Host = authority ; same as authority-form -``` - -An HTTP/1.1 request that lack a host header must be rejected with -a 400 status code and the closing of the connection. (RFC7230 5.4) - -An HTTP/1.0 request that lack a host header is valid. Behavior -for these requests is configuration dependent. (RFC7230 5.5) - -A request with an invalid host header must be rejected with a -400 status code and the closing of the connection. (RFC7230 5.4) - -An authority component with a userinfo component (and its -"@" delimiter) is invalid. The request must be rejected with -a 400 status code and the closing of the connection. (RFC7230 2.7.1) - -When using absolute-form the URI authority component must be -identical to the host header. Invalid requests must be rejected -with a 400 status code and the closing of the connection. (RFC7230 5.4) - -When using authority-form the URI authority component must be -identical to the host header. Invalid requests must be rejected -with a 400 status code and the closing of the connection. - -The host header is empty when the authority component is undefined. (RFC7230 5.4) - -The effective request URI can be rebuilt by concatenating scheme, -"://", authority, path and query components. (RFC7230 5.5) - -Resources with identical URI except for the scheme component -must be treated as different. (RFC7230 2.7.2) - -:: Response - -A server can send more than one response per request only when a -1xx response is sent preceding the final response. (RFC7230 5.6) - -A server that does parallel pipelining must send responses in the -same order as the requests came in. (RFC7230 5.6) - -``` -HTTP-response = status-line *( header-field CRLF ) CRLF [ message-body ] -``` - -The response format must be followed strictly. - -``` -status-line = HTTP-version SP status-code SP reason-phrase CRLF -status-code = 3DIGIT -reason-phrase = *( HTAB / SP / VCHAR / obs-text ) -``` - -A server must send its own version. (RFC7230 2.6) - -An HTTP/1.1 server may send an HTTP/1.0 version for compatibility purposes. (RFC7230 2.6) - -RFC6585 defines additional status code a server can use to reject -messages. (RFC7230 9.3, RFC6585) - -:: Response headers - -In responses, OWS must be generated as SP or not generated -at all. RWS must be generated as SP. BWS must not be -generated. (RFC7230 3.2.3) - -``` -header-field = field-name ":" SP field-value - -field-name = token ; case-insensitive -field-value = *( SP / %21-7E / %80-FF ) -``` - -In quoted-string found in field-value, quoted-pair must only be -used for DQUOTE and backslash. (RFC7230 3.2.6) - -The server must not generate comments in header values. - -HTTP header values must use US-ASCII encoding and must only send -printable characters or SP. (RFC7230 3.2.4, RFC7230 9.4) - -The server must not generate empty list elements in headers. (RFC7230 7) - -When encoding an URI as part of a response, only characters that -are reserved need to be percent-encoded. (RFC7230 2.7.3) - -The set-cookie header must be handled as a special case. There -must be exactly one set-cookie header field per cookie. (RFC7230 3.2.2) - -The server must list headers for or about the immediate connection -in the connection header field. (RFC7230 6.1) - -A server that does not support persistent connections must -send "close" in every non-1xx response. (RFC7230 6.1) - -A server must not send a "close" connection option -in 1xx responses. (RFC7230 6.1) - -The "close" connection must be sent in a message when the -sender knows it will close the connection after fully sending -the response. (RFC7230 6.6) - -A server must close the connection after sending or -receiving a "close" once the response has been sent. (RFC7230 6.6) - -A server must send a "close" in a response to a request -containing a "close". (RFC7230 6.6) - -:: Response body - -Responses to HEAD requests never include a message body. (RFC7230 3.3) - -2xx responses to CONNECT requests never include a message -body. (RFC7230 3.3) - -1xx, 204 and 304 responses never include a message body. (RFC7230 3.3) - -Responses to HEAD requests and 304 responses can include a -content-length or transfer-encoding header. Their value must -be the same as if the request was an unconditional GET. (RFC7230 3.3, RFC7230 3.3.1, RFC7230 3.3.2) - -1xx, 204 responses and 2xx responses to CONNECT requests must -not include a content-length or transfer-encoding header. (RFC7230 3.3.1, RFC7230 3.3.2) - -``` -message-body = *OCTET -``` - -The message body is the octets after decoding any transfer -codings. (RFC7230 3.3) - -When the length is known in advance, the server must send a -content-length header, including if the length is 0. (RFC7230 3.3.2, RFC7230 3.3.3) - -When the length is not known in advance, the chunked transfer-encoding -must be used. (RFC7230 3.3.2, RFC7230 3.3.3) - -For compatibility purposes a server can send no content-length or -transfer-encoding header. In this case the connection must be -closed after the response has been sent fully. (RFC7230 3.3.2, RFC7230 3.3.3) - -The content-length header must not be sent when a transfer-encoding -header already exists. (RFC7230 3.3.2) - -The server must not apply the chunked transfer-encoding more than -once. (RFC7230 3.3.1) - -The server must apply the chunked transfer-encoding last. (RFC7230 3.3.1) - -The transfer-encoding header must not be sent in responses to -HTTP/1.0 requests, or in responses that use the HTTP/1.0 version. -No transfer codings must be applied in these cases. (RFC7230 3.3.1) - -``` -TE = #t-codings - -t-codings = "trailers" / ( transfer-coding [ t-ranking ] ) -t-ranking = OWS ";" OWS "q=" rank -rank = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) -``` - -Trailers can only be sent if the request includes a TE header -containing "trailers". (RFC7230 4.1.2) - -The presence of "chunked" in a TE header must be ignored as it -is always acceptable with HTTP/1.1. (RFC7230 4.3) - -A qvalue of 0 in the TE header means "not acceptable". (RFC7230 4.3) - -The lack of a TE header or an empty TE header means only "chunked" -(with no trailers) or no transfer-encoding is acceptable. (RFC7230 4.3) - -The TE header must be listed in the connection header field, -or must be ignored otherwise. - -Trailer headers must be listed in the trailer header field value. (RFC7230 4.4) - -When defined, the trailer header must also be listed in the connection header. (RFC7230 4.4) - -:: Upgrade - -``` -Upgrade = 1#protocol - -protocol = protocol-name ["/" protocol-version] -protocol-name = token -protocol-version = token -``` - -The upgrade header contains the list of protocols the -client wishes to upgrade to, in order of preference. (RFC7230 6.7) - -The upgrade header can be safely ignored. (RFC7230 6.7) - -The upgrade header must be listed under the connection header, -or must be ignored otherwise. (RFC7230 6.7) - -A server accepting an upgrade request must send a 101 status -code with a upgrade header listing the protocol(s) it upgrades -to, in layer-ascending order. In addition the upgrade header -must be listed in the connection header. (RFC7230 6.7) - -A server must not switch to a protocol not listed in the -request's upgrade header. (RFC7230 6.7) - -A server that sends a 426 status code must include a upgrade -header listing acceptable protocols in order of preference. (RFC7230 6.7) - -A server can send a upgrade header to any response to advertise -its support for other protocols listed in order of preference. (RFC7230 6.7) - -Immediately after a server responds with a 101 status code -it must respond to the original request using the new protocol. (RFC7230 6.7) - -A server must not switch protocols unless the original message's -semantics can be honored by the new protocol. OPTIONS requests -can be honored by any protocol. (RFC7230 6.7) - -A server must ignore an upgrade header received by an HTTP/1.0 -request. (RFC7230 6.7) - -A server receiving both an upgrade header and an expect header -containing "100-continue" must send a 100 response before the -101 response. (RFC7230 6.7) - -The upgrade header field cannot be used for switching the -connection protocol (e.g. TCP) or switching connections. (RFC7230 6.7) - -:: Compatibility - -A server can choose to be non-conformant to the specifications -for the sake of compatibility. Such behavior can be enabled -through configuration and/or software identification. (RFC7230 2.5) diff --git a/_build/emqx/lib/cowboy/examples/README.asciidoc b/_build/emqx/lib/cowboy/examples/README.asciidoc deleted file mode 100644 index 8b09c9b630..0000000000 --- a/_build/emqx/lib/cowboy/examples/README.asciidoc +++ /dev/null @@ -1,51 +0,0 @@ -= Cowboy examples - -* link:chunked_hello_world[]: - demonstrate chunked data transfer with two one-second delays - -* link:compress_response[]: - send a response body compressed if the client supports it - -* link:cookie[]: - set cookies from server and client side - -* link:echo_get[]: - parse and echo a GET query string - -* link:echo_post[]: - parse and echo a POST parameter - -* link:eventsource[]: - eventsource emitter and consumer - -* link:file_server[]: - file server with directory listing - -* link:hello_world[]: - simplest example application - -* link:markdown_middleware[]: - static file handler with markdown preprocessor - -* link:rest_basic_auth[]: - basic HTTP authorization with REST - -* link:rest_hello_world[]: - return the data type that matches the request type (ex: html, text, json) - -* link:rest_pastebin[]: - create text objects and return the data type that matches the request type (html, text) - -* link:ssl_hello_world[]: - simplest SSL application - -* link:upload[]: - multipart/form-data upload - -* link:websocket[]: - websocket example - -== Other languages - -* https://hub.fastgit.org/joshrotenberg/elixir_cowboy_examples[Elixir] -* https://hub.fastgit.org/quasiquoting/lfe-cowboy-examples[LFE] diff --git a/_build/emqx/lib/cowboy/examples/chunked_hello_world/Makefile b/_build/emqx/lib/cowboy/examples/chunked_hello_world/Makefile deleted file mode 100644 index 7e14a8257a..0000000000 --- a/_build/emqx/lib/cowboy/examples/chunked_hello_world/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = chunked_hello_world -PROJECT_DESCRIPTION = Cowboy chunked Hello World example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/chunked_hello_world/README.asciidoc b/_build/emqx/lib/cowboy/examples/chunked_hello_world/README.asciidoc deleted file mode 100644 index f3e4c2ad72..0000000000 --- a/_build/emqx/lib/cowboy/examples/chunked_hello_world/README.asciidoc +++ /dev/null @@ -1,86 +0,0 @@ -= Chunked hello world example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 -or use `curl` to see the chunks arriving one at a time every second. - -== HTTP/1.1 example output - -[source,bash] ----- -$ time curl -i http://localhost:8080 -HTTP/1.1 200 OK -transfer-encoding: chunked -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:24:16 GMT - -Hello -World -Chunked! -curl -i http://localhost:8080 0.01s user 0.00s system 0% cpu 2.015 total ----- - -== HTTP/2 example output - -[source,bash] ----- -$ nghttp -v http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.006] recv SETTINGS frame - (niv=0) -[ 0.006] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.006] send SETTINGS frame - ; ACK - (niv=0) -[ 0.010] recv (stream_id=13) :status: 200 -[ 0.010] recv (stream_id=13) date: Mon, 13 Jun 2016 14:16:26 GMT -[ 0.010] recv (stream_id=13) server: Cowboy -[ 0.010] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -Hello -[ 0.010] recv DATA frame -World -[ 1.012] recv DATA frame -Chunked! -[ 2.013] recv DATA frame -[ 2.013] recv DATA frame - ; END_STREAM -[ 2.013] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/chunked_hello_world/relx.config b/_build/emqx/lib/cowboy/examples/chunked_hello_world/relx.config deleted file mode 100644 index 88e7b5223f..0000000000 --- a/_build/emqx/lib/cowboy/examples/chunked_hello_world/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {chunked_hello_world_example, "1"}, [chunked_hello_world]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/chunked_hello_world_app.erl b/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/chunked_hello_world_app.erl deleted file mode 100644 index 70d63f55fb..0000000000 --- a/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/chunked_hello_world_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(chunked_hello_world_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - chunked_hello_world_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/chunked_hello_world_sup.erl b/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/chunked_hello_world_sup.erl deleted file mode 100644 index 08bdb717fc..0000000000 --- a/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/chunked_hello_world_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(chunked_hello_world_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/toppage_h.erl deleted file mode 100644 index 7ed2964825..0000000000 --- a/_build/emqx/lib/cowboy/examples/chunked_hello_world/src/toppage_h.erl +++ /dev/null @@ -1,15 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Chunked hello world handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - Req = cowboy_req:stream_reply(200, Req0), - cowboy_req:stream_body("Hello\r\n", nofin, Req), - timer:sleep(1000), - cowboy_req:stream_body("World\r\n", nofin, Req), - timer:sleep(1000), - cowboy_req:stream_body("Chunked!\r\n", fin, Req), - {ok, Req, Opts}. diff --git a/_build/emqx/lib/cowboy/examples/compress_response/Makefile b/_build/emqx/lib/cowboy/examples/compress_response/Makefile deleted file mode 100644 index 8eab60429a..0000000000 --- a/_build/emqx/lib/cowboy/examples/compress_response/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = compress_response -PROJECT_DESCRIPTION = Cowboy compressed response example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/compress_response/README.asciidoc b/_build/emqx/lib/cowboy/examples/compress_response/README.asciidoc deleted file mode 100644 index a16ea3c5b6..0000000000 --- a/_build/emqx/lib/cowboy/examples/compress_response/README.asciidoc +++ /dev/null @@ -1,198 +0,0 @@ -= Compressed response example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -== HTTP/1.1 example output - -Without compression: - -[source,bash] ----- -$ curl -i http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Mon, 07 Jan 2013 18:42:29 GMT -content-length: 909 - -A cowboy is an animal herder who tends cattle on ranches in North America, -traditionally on horseback, and often performs a multitude of other ranch- -related tasks. The historic American cowboy of the late 19th century arose -from the vaquero traditions of northern Mexico and became a figure of special -significance and legend. A subtype, called a wrangler, specifically tends the -horses used to work cattle. In addition to ranch work, some cowboys work for -or participate in rodeos. Cowgirls, first defined as such in the late 19th -century, had a less-well documented historical role, but in the modern world -have established the ability to work at virtually identical tasks and obtained -considerable respect for their achievements. There are also cattle handlers -in many other parts of the world, particularly South America and Australia, -who perform work similar to the cowboy in their respective nations. ----- - -With compression: - -[source,bash] ----- -$ curl -i --compressed http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Mon, 07 Jan 2013 18:42:30 GMT -content-encoding: gzip -content-length: 510 - -A cowboy is an animal herder who tends cattle on ranches in North America, -traditionally on horseback, and often performs a multitude of other ranch- -related tasks. The historic American cowboy of the late 19th century arose -from the vaquero traditions of northern Mexico and became a figure of special -significance and legend. A subtype, called a wrangler, specifically tends the -horses used to work cattle. In addition to ranch work, some cowboys work for -or participate in rodeos. Cowgirls, first defined as such in the late 19th -century, had a less-well documented historical role, but in the modern world -have established the ability to work at virtually identical tasks and obtained -considerable respect for their achievements. There are also cattle handlers -in many other parts of the world, particularly South America and Australia, -who perform work similar to the cowboy in their respective nations. ----- - -== HTTP/2 example output - -Without compression: - -[source,bash] ----- -$ nghttp -v -H 'accept-encoding: compress' http://localhost:8080 -[ 0.001] Connected -[ 0.001] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.001] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.002] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: compress - user-agent: nghttp2/1.18.1 -[ 0.002] recv SETTINGS frame - (niv=0) -[ 0.002] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.002] send SETTINGS frame - ; ACK - (niv=0) -[ 0.003] recv (stream_id=13) :status: 200 -[ 0.003] recv (stream_id=13) content-length: 909 -[ 0.003] recv (stream_id=13) date: Sun, 22 Jan 2017 19:13:47 GMT -[ 0.003] recv (stream_id=13) server: Cowboy -[ 0.003] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -A cowboy is an animal herder who tends cattle on ranches in North America, -traditionally on horseback, and often performs a multitude of other ranch- -related tasks. The historic American cowboy of the late 19th century arose -from the vaquero traditions of northern Mexico and became a figure of special -significance and legend. A subtype, called a wrangler, specifically tends the -horses used to work cattle. In addition to ranch work, some cowboys work for -or participate in rodeos. Cowgirls, first defined as such in the late 19th -century, had a less-well documented historical role, but in the modern world -have established the ability to work at virtually identical tasks and obtained -considerable respect for their achievements. There are also cattle handlers -in many other parts of the world, particularly South America and Australia, -who perform work similar to the cowboy in their respective nations. -[ 0.003] recv DATA frame - ; END_STREAM -[ 0.003] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- - -With compression: - -[source,bash] ----- -$ nghttp -v http://localhost:8080 -[ERROR] Could not connect to the address ::1 -Trying next address 127.0.0.1 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.18.1 -[ 0.000] recv SETTINGS frame - (niv=0) -[ 0.000] send SETTINGS frame - ; ACK - (niv=0) -[ 0.000] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.000] recv (stream_id=13) :status: 200 -[ 0.000] recv (stream_id=13) content-encoding: gzip -[ 0.000] recv (stream_id=13) content-length: 510 -[ 0.000] recv (stream_id=13) date: Sun, 22 Jan 2017 19:15:16 GMT -[ 0.000] recv (stream_id=13) server: Cowboy -[ 0.000] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -A cowboy is an animal herder who tends cattle on ranches in North America, -traditionally on horseback, and often performs a multitude of other ranch- -related tasks. The historic American cowboy of the late 19th century arose -from the vaquero traditions of northern Mexico and became a figure of special -significance and legend. A subtype, called a wrangler, specifically tends the -horses used to work cattle. In addition to ranch work, some cowboys work for -or participate in rodeos. Cowgirls, first defined as such in the late 19th -century, had a less-well documented historical role, but in the modern world -have established the ability to work at virtually identical tasks and obtained -considerable respect for their achievements. There are also cattle handlers -in many other parts of the world, particularly South America and Australia, -who perform work similar to the cowboy in their respective nations. -[ 0.000] recv DATA frame - ; END_STREAM -[ 0.000] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/compress_response/relx.config b/_build/emqx/lib/cowboy/examples/compress_response/relx.config deleted file mode 100644 index 154434933f..0000000000 --- a/_build/emqx/lib/cowboy/examples/compress_response/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {compress_response_example, "1"}, [compress_response]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/compress_response/src/compress_response_app.erl b/_build/emqx/lib/cowboy/examples/compress_response/src/compress_response_app.erl deleted file mode 100644 index b35fd6f96a..0000000000 --- a/_build/emqx/lib/cowboy/examples/compress_response/src/compress_response_app.erl +++ /dev/null @@ -1,26 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(compress_response_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch}, - stream_handlers => [cowboy_compress_h, cowboy_stream_h] - }), - compress_response_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/compress_response/src/compress_response_sup.erl b/_build/emqx/lib/cowboy/examples/compress_response/src/compress_response_sup.erl deleted file mode 100644 index d1bc31209c..0000000000 --- a/_build/emqx/lib/cowboy/examples/compress_response/src/compress_response_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(compress_response_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/compress_response/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/compress_response/src/toppage_h.erl deleted file mode 100644 index 477cfcf225..0000000000 --- a/_build/emqx/lib/cowboy/examples/compress_response/src/toppage_h.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Compress response handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - BigBody = -<<"A cowboy is an animal herder who tends cattle on ranches in North America, -traditionally on horseback, and often performs a multitude of other ranch- -related tasks. The historic American cowboy of the late 19th century arose -from the vaquero traditions of northern Mexico and became a figure of special -significance and legend. A subtype, called a wrangler, specifically tends the -horses used to work cattle. In addition to ranch work, some cowboys work for -or participate in rodeos. Cowgirls, first defined as such in the late 19th -century, had a less-well documented historical role, but in the modern world -have established the ability to work at virtually identical tasks and obtained -considerable respect for their achievements. There are also cattle handlers -in many other parts of the world, particularly South America and Australia, -who perform work similar to the cowboy in their respective nations.\n">>, - Req = cowboy_req:reply(200, #{}, BigBody, Req0), - {ok, Req, Opts}. diff --git a/_build/emqx/lib/cowboy/examples/cookie/Makefile b/_build/emqx/lib/cowboy/examples/cookie/Makefile deleted file mode 100644 index 563cd87fe8..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = cookie -PROJECT_DESCRIPTION = Cowboy Cookie example -PROJECT_VERSION = 1 - -DEPS = cowboy erlydtl -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/cookie/README.asciidoc b/_build/emqx/lib/cowboy/examples/cookie/README.asciidoc deleted file mode 100644 index 20294f53df..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/README.asciidoc +++ /dev/null @@ -1,13 +0,0 @@ -= Cookie example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -This example allows you to use any path to show that the cookies -are defined site-wide. Try it! diff --git a/_build/emqx/lib/cowboy/examples/cookie/relx.config b/_build/emqx/lib/cowboy/examples/cookie/relx.config deleted file mode 100644 index 26dc875c5f..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {cookie_example, "1"}, [cookie]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/cookie/src/cookie_app.erl b/_build/emqx/lib/cowboy/examples/cookie/src/cookie_app.erl deleted file mode 100644 index 358d882311..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/src/cookie_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(cookie_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {'_', toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - cookie_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/cookie/src/cookie_sup.erl b/_build/emqx/lib/cowboy/examples/cookie/src/cookie_sup.erl deleted file mode 100644 index 5ba4e53e07..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/src/cookie_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(cookie_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/cookie/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/cookie/src/toppage_h.erl deleted file mode 100644 index 308899b0fa..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/src/toppage_h.erl +++ /dev/null @@ -1,21 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Cookie handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - NewValue = integer_to_list(rand:uniform(1000000)), - Req1 = cowboy_req:set_resp_cookie(<<"server">>, NewValue, - Req0, #{path => <<"/">>}), - #{client := ClientCookie, server := ServerCookie} - = cowboy_req:match_cookies([{client, [], <<>>}, {server, [], <<>>}], Req1), - {ok, Body} = toppage_dtl:render([ - {client, ClientCookie}, - {server, ServerCookie} - ]), - Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/html">> - }, Body, Req1), - {ok, Req, Opts}. diff --git a/_build/emqx/lib/cowboy/examples/cookie/templates/toppage.dtl b/_build/emqx/lib/cowboy/examples/cookie/templates/toppage.dtl deleted file mode 100644 index e6faa2b655..0000000000 --- a/_build/emqx/lib/cowboy/examples/cookie/templates/toppage.dtl +++ /dev/null @@ -1,24 +0,0 @@ - - - - - Cowboy Cookie Example - - - -

Cowboy Cookie Example

-

Refresh the page to see the next cookie.

- -

Cookie Set Server-Side

-

{{ server }}

- -

Cookie Set Client-Side

-

{{ client }}

- - - - diff --git a/_build/emqx/lib/cowboy/examples/echo_get/Makefile b/_build/emqx/lib/cowboy/examples/echo_get/Makefile deleted file mode 100644 index 6332d4b9af..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_get/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = echo_get -PROJECT_DESCRIPTION = Cowboy GET echo example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/echo_get/README.asciidoc b/_build/emqx/lib/cowboy/examples/echo_get/README.asciidoc deleted file mode 100644 index 06badecdf3..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_get/README.asciidoc +++ /dev/null @@ -1,82 +0,0 @@ -= GET parameter echo example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080/?echo=hello - -You can replace the `echo` parameter with another to check -that the handler is echoing it back properly. - -== HTTP/1.1 example output - -[source,bash] ----- -$ curl -i "http://localhost:8080/?echo=saymyname" -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:09:04 GMT -content-length: 9 -content-type: text/plain; charset=utf-8 - -saymyname ----- - -== HTTP/2 example output - -[source,bash] ----- -$ nghttp -v "http://localhost:8080/?echo=saymyname" -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: /?echo=saymyname - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.000] recv SETTINGS frame - (niv=0) -[ 0.000] send SETTINGS frame - ; ACK - (niv=0) -[ 0.000] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.001] recv (stream_id=13) :status: 200 -[ 0.001] recv (stream_id=13) content-length: 9 -[ 0.001] recv (stream_id=13) content-type: text/plain; charset=utf-8 -[ 0.001] recv (stream_id=13) date: Thu, 09 Jun 2016 09:06:05 GMT -[ 0.001] recv (stream_id=13) server: Cowboy -[ 0.001] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -saymyname[ 0.001] recv DATA frame - ; END_STREAM -[ 0.001] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/echo_get/relx.config b/_build/emqx/lib/cowboy/examples/echo_get/relx.config deleted file mode 100644 index fdf41448a6..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_get/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {echo_get_example, "1"}, [echo_get]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/echo_get/src/echo_get_app.erl b/_build/emqx/lib/cowboy/examples/echo_get/src/echo_get_app.erl deleted file mode 100644 index 5b15fb331d..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_get/src/echo_get_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(echo_get_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - echo_get_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/echo_get/src/echo_get_sup.erl b/_build/emqx/lib/cowboy/examples/echo_get/src/echo_get_sup.erl deleted file mode 100644 index 455af0459c..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_get/src/echo_get_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(echo_get_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/echo_get/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/echo_get/src/toppage_h.erl deleted file mode 100644 index 419b4d472a..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_get/src/toppage_h.erl +++ /dev/null @@ -1,22 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc GET echo handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - Method = cowboy_req:method(Req0), - #{echo := Echo} = cowboy_req:match_qs([{echo, [], undefined}], Req0), - Req = echo(Method, Echo, Req0), - {ok, Req, Opts}. - -echo(<<"GET">>, undefined, Req) -> - cowboy_req:reply(400, #{}, <<"Missing echo parameter.">>, Req); -echo(<<"GET">>, Echo, Req) -> - cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain; charset=utf-8">> - }, Echo, Req); -echo(_, _, Req) -> - %% Method not allowed. - cowboy_req:reply(405, Req). diff --git a/_build/emqx/lib/cowboy/examples/echo_post/Makefile b/_build/emqx/lib/cowboy/examples/echo_post/Makefile deleted file mode 100644 index c1d64fea7d..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_post/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = echo_post -PROJECT_DESCRIPTION = Cowboy POST echo example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/echo_post/README.asciidoc b/_build/emqx/lib/cowboy/examples/echo_post/README.asciidoc deleted file mode 100644 index 81b4cfc8d0..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_post/README.asciidoc +++ /dev/null @@ -1,87 +0,0 @@ -= POST parameter echo example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -As this example echoes a POST parameter, it is a little more -complex to test. Some browsers feature tools that allow you -to perform one such request, or you can use the command line -tool `curl` as we will demonstrate. - -== HTTP/1.1 example output - -[source,bash] ----- -$ curl -i -d echo=echomeplz http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:12:36 GMT -content-length: 9 -content-type: text/plain; charset=utf-8 - -echomeplz ----- - -== HTTP/2 example output - -[source,bash] ----- -$ echo echo=echomeplz | nghttp -v -d - http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.001] send HEADERS frame - ; END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: POST - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 - content-length: 15 -[ 0.001] send DATA frame -[ 0.001] send DATA frame - ; END_STREAM -[ 0.012] recv SETTINGS frame - (niv=0) -[ 0.012] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.012] send SETTINGS frame - ; ACK - (niv=0) -[ 0.020] recv (stream_id=13) :status: 200 -[ 0.020] recv (stream_id=13) content-length: 10 -[ 0.020] recv (stream_id=13) content-type: text/plain; charset=utf-8 -[ 0.020] recv (stream_id=13) date: Thu, 09 Jun 2016 09:19:35 GMT -[ 0.020] recv (stream_id=13) server: Cowboy -[ 0.020] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -echomeplz -[ 0.020] recv DATA frame - ; END_STREAM -[ 0.020] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/echo_post/relx.config b/_build/emqx/lib/cowboy/examples/echo_post/relx.config deleted file mode 100644 index a1abbf0aea..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_post/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {echo_post_example, "1"}, [echo_post]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/echo_post/src/echo_post_app.erl b/_build/emqx/lib/cowboy/examples/echo_post/src/echo_post_app.erl deleted file mode 100644 index 4a057bbc03..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_post/src/echo_post_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(echo_post_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - echo_post_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/echo_post/src/echo_post_sup.erl b/_build/emqx/lib/cowboy/examples/echo_post/src/echo_post_sup.erl deleted file mode 100644 index 6f973c05aa..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_post/src/echo_post_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(echo_post_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/echo_post/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/echo_post/src/toppage_h.erl deleted file mode 100644 index 1c6446a039..0000000000 --- a/_build/emqx/lib/cowboy/examples/echo_post/src/toppage_h.erl +++ /dev/null @@ -1,29 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc POST echo handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - Method = cowboy_req:method(Req0), - HasBody = cowboy_req:has_body(Req0), - Req = maybe_echo(Method, HasBody, Req0), - {ok, Req, Opts}. - -maybe_echo(<<"POST">>, true, Req0) -> - {ok, PostVals, Req} = cowboy_req:read_urlencoded_body(Req0), - Echo = proplists:get_value(<<"echo">>, PostVals), - echo(Echo, Req); -maybe_echo(<<"POST">>, false, Req) -> - cowboy_req:reply(400, [], <<"Missing body.">>, Req); -maybe_echo(_, _, Req) -> - %% Method not allowed. - cowboy_req:reply(405, Req). - -echo(undefined, Req) -> - cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req); -echo(Echo, Req) -> - cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain; charset=utf-8">> - }, Echo, Req). diff --git a/_build/emqx/lib/cowboy/examples/eventsource/Makefile b/_build/emqx/lib/cowboy/examples/eventsource/Makefile deleted file mode 100644 index 1b67b8e53b..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = eventsource -PROJECT_DESCRIPTION = Cowboy EventSource example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/eventsource/README.asciidoc b/_build/emqx/lib/cowboy/examples/eventsource/README.asciidoc deleted file mode 100644 index 9461b77693..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/README.asciidoc +++ /dev/null @@ -1,10 +0,0 @@ -= EventSource example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 diff --git a/_build/emqx/lib/cowboy/examples/eventsource/priv/index.html b/_build/emqx/lib/cowboy/examples/eventsource/priv/index.html deleted file mode 100644 index f057195767..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/priv/index.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - Hi! -
- - diff --git a/_build/emqx/lib/cowboy/examples/eventsource/relx.config b/_build/emqx/lib/cowboy/examples/eventsource/relx.config deleted file mode 100644 index efd854874f..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {eventsource_example, "1"}, [eventsource]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_app.erl b/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_app.erl deleted file mode 100644 index 825f434f9b..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_app.erl +++ /dev/null @@ -1,26 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(eventsource_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/eventsource", eventsource_h, []}, - {"/", cowboy_static, {priv_file, eventsource, "index.html"}} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - eventsource_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_h.erl b/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_h.erl deleted file mode 100644 index ba5d866271..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_h.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc EventSource emitter. --module(eventsource_h). - --export([init/2]). --export([info/3]). - -init(Req0, Opts) -> - Req = cowboy_req:stream_reply(200, #{ - <<"content-type">> => <<"text/event-stream">> - }, Req0), - erlang:send_after(1000, self(), {message, "Tick"}), - {cowboy_loop, Req, Opts}. - -info({message, Msg}, Req, State) -> - cowboy_req:stream_events(#{ - id => id(), - data => Msg - }, nofin, Req), - erlang:send_after(1000, self(), {message, "Tick"}), - {ok, Req, State}. - -id() -> - integer_to_list(erlang:unique_integer([positive, monotonic]), 16). diff --git a/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_sup.erl b/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_sup.erl deleted file mode 100644 index 611b0158a6..0000000000 --- a/_build/emqx/lib/cowboy/examples/eventsource/src/eventsource_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(eventsource_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/file_server/Makefile b/_build/emqx/lib/cowboy/examples/file_server/Makefile deleted file mode 100644 index 7efa6efc67..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = file_server -PROJECT_DESCRIPTION = Cowboy file server example with directory listing -PROJECT_VERSION = 1 - -DEPS = cowboy jsx -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/file_server/README.asciidoc b/_build/emqx/lib/cowboy/examples/file_server/README.asciidoc deleted file mode 100644 index f6bc61cc0e..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/README.asciidoc +++ /dev/null @@ -1,89 +0,0 @@ -= File server example with directory listing - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 -to browse the contents of the `priv` directory. - -Interesting examples include: - -* http://localhost:8080/test.txt[Plain text file] -* http://localhost:8080/video.html[HTML5 video demo] - -== HTTP/1.1 example output - -[source,bash] ----- -$ curl -i http://localhost:8080/test.txt -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Mon, 09 Sep 2013 13:49:50 GMT -content-length: 52 -content-type: text/plain -last-modified: Fri, 18 Jan 2013 16:33:31 GMT - -If you read this then the static file server works! ----- - -== HTTP/2 example output - -[source,bash] ----- -$ nghttp -v http://localhost:8080/test.txt -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: /test.txt - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.001] recv SETTINGS frame - (niv=0) -[ 0.001] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.001] send SETTINGS frame - ; ACK - (niv=0) -[ 0.007] recv (stream_id=13) :status: 200 -[ 0.007] recv (stream_id=13) content-length: 52 -[ 0.007] recv (stream_id=13) content-type: text/plain -[ 0.007] recv (stream_id=13) date: Mon, 13 Jun 2016 11:25:20 GMT -[ 0.007] recv (stream_id=13) etag: "1371478245" -[ 0.007] recv (stream_id=13) last-modified: Tue, 12 Aug 2014 17:00:17 GMT -[ 0.007] recv (stream_id=13) server: Cowboy -[ 0.007] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -If you read this then the static file server works! -[ 0.007] recv DATA frame - ; END_STREAM -[ 0.007] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/file_server/priv/small.mp4 b/_build/emqx/lib/cowboy/examples/file_server/priv/small.mp4 deleted file mode 100644 index 1fc478842f..0000000000 Binary files a/_build/emqx/lib/cowboy/examples/file_server/priv/small.mp4 and /dev/null differ diff --git a/_build/emqx/lib/cowboy/examples/file_server/priv/small.ogv b/_build/emqx/lib/cowboy/examples/file_server/priv/small.ogv deleted file mode 100644 index 6409d6e615..0000000000 Binary files a/_build/emqx/lib/cowboy/examples/file_server/priv/small.ogv and /dev/null differ diff --git a/_build/emqx/lib/cowboy/examples/file_server/priv/test.txt b/_build/emqx/lib/cowboy/examples/file_server/priv/test.txt deleted file mode 100644 index 760cddb0a1..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/priv/test.txt +++ /dev/null @@ -1 +0,0 @@ -If you read this then the static file server works! diff --git a/_build/emqx/lib/cowboy/examples/file_server/priv/video.html b/_build/emqx/lib/cowboy/examples/file_server/priv/video.html deleted file mode 100644 index 0830ae028f..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/priv/video.html +++ /dev/null @@ -1,11 +0,0 @@ - - - -

HTML5 Video Example

- -

Videos taken from TechSlides

- - diff --git a/_build/emqx/lib/cowboy/examples/file_server/relx.config b/_build/emqx/lib/cowboy/examples/file_server/relx.config deleted file mode 100644 index 9e365e9c93..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {file_server_example, "1"}, [file_server]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/file_server/src/directory_h.erl b/_build/emqx/lib/cowboy/examples/file_server/src/directory_h.erl deleted file mode 100644 index 66e1466bd1..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/src/directory_h.erl +++ /dev/null @@ -1,53 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Directory handler. --module(directory_h). - -%% REST Callbacks --export([init/2]). --export([allowed_methods/2]). --export([resource_exists/2]). --export([content_types_provided/2]). - -%% Callback Callbacks --export([list_json/2]). --export([list_html/2]). - -init(Req, Paths) -> - {cowboy_rest, Req, Paths}. - -allowed_methods(Req, State) -> - {[<<"GET">>], Req, State}. - -resource_exists(Req, {ReqPath, FilePath}) -> - case file:list_dir(FilePath) of - {ok, Fs} -> {true, Req, {ReqPath, lists:sort(Fs)}}; - _Err -> {false, Req, {ReqPath, FilePath}} - end. - -content_types_provided(Req, State) -> - {[ - {{<<"text">>, <<"html">>, []}, list_html}, - {{<<"application">>, <<"json">>, []}, list_json} - ], Req, State}. - -list_json(Req, {Path, Fs}) -> - Files = [ <<(list_to_binary(F))/binary>> || F <- Fs ], - {jsx:encode(Files), Req, Path}. - -list_html(Req, {Path, Fs}) -> - Body = [[ links(Path, F) || F <- [".."|Fs] ]], - HTML = [<<"Index", - "">>, Body, <<"\n">>], - {HTML, Req, Path}. - -links(<<>>, "..") -> - "..
\n"; -links(Prefix, "..") -> - Tokens = string:tokens(binary_to_list(Prefix), "/"), - Back = lists:join("/", lists:reverse(tl(lists:reverse(Tokens)))), - ["..
\n"]; -links(<<>>, File) -> - ["", File, "
\n"]; -links(Prefix, File) -> - ["", File, "
\n"]. diff --git a/_build/emqx/lib/cowboy/examples/file_server/src/directory_lister.erl b/_build/emqx/lib/cowboy/examples/file_server/src/directory_lister.erl deleted file mode 100644 index 2ca9d303b2..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/src/directory_lister.erl +++ /dev/null @@ -1,32 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - --module(directory_lister). --behaviour(cowboy_middleware). - --export([execute/2]). - -execute(Req, Env=#{handler := cowboy_static}) -> - redirect_directory(Req, Env); -execute(Req, Env) -> - {ok, Req, Env}. - -redirect_directory(Req, Env=#{handler_opts := {_, _, _, Extra}}) -> - Path = cowboy_req:path_info(Req), - Path1 = << <> || S <- Path >>, - {dir_handler, DirHandler} = lists:keyfind(dir_handler, 1, Extra), - FullPath = resource_path(Path1), - case valid_path(Path) and filelib:is_dir(FullPath) of - true -> handle_directory(Req, Env, Path1, FullPath, DirHandler); - false -> {ok, Req, Env} - end. - -handle_directory(Req, Env, Prefix, Path, DirHandler) -> - {ok, Req, Env#{handler => DirHandler, handler_opts => {Prefix, Path}}}. - -valid_path([]) -> true; -valid_path([<<"..">> | _T]) -> false; -valid_path([<<"/", _/binary>> | _T]) -> false; -valid_path([_H | Rest]) -> valid_path(Rest). - -resource_path(Path) -> - filename:join([code:priv_dir(file_server), Path]). diff --git a/_build/emqx/lib/cowboy/examples/file_server/src/file_server_app.erl b/_build/emqx/lib/cowboy/examples/file_server/src/file_server_app.erl deleted file mode 100644 index 17e73b296b..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/src/file_server_app.erl +++ /dev/null @@ -1,29 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(file_server_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/[...]", cowboy_static, {priv_dir, file_server, "", [ - {mimetypes, cow_mimetypes, all}, - {dir_handler, directory_h} - ]}} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch}, - middlewares => [cowboy_router, directory_lister, cowboy_handler] - }), - file_server_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/file_server/src/file_server_sup.erl b/_build/emqx/lib/cowboy/examples/file_server/src/file_server_sup.erl deleted file mode 100644 index 961eb5ec4b..0000000000 --- a/_build/emqx/lib/cowboy/examples/file_server/src/file_server_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(file_server_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/hello_world/Makefile b/_build/emqx/lib/cowboy/examples/hello_world/Makefile deleted file mode 100644 index c410b09db3..0000000000 --- a/_build/emqx/lib/cowboy/examples/hello_world/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = hello_world -PROJECT_DESCRIPTION = Cowboy Hello World example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/hello_world/README.asciidoc b/_build/emqx/lib/cowboy/examples/hello_world/README.asciidoc deleted file mode 100644 index 96c1a60db0..0000000000 --- a/_build/emqx/lib/cowboy/examples/hello_world/README.asciidoc +++ /dev/null @@ -1,79 +0,0 @@ -= Hello world example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -== HTTP/1.1 example output - -[source,bash] ----- -$ curl -i http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:10:25 GMT -content-length: 12 -content-type: text/plain - -Hello world! ----- - -== HTTP/2 example output - -[source,bash] ----- -$ nghttp -v http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.008] recv SETTINGS frame - (niv=0) -[ 0.008] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.008] send SETTINGS frame - ; ACK - (niv=0) -[ 0.013] recv (stream_id=13) :status: 200 -[ 0.013] recv (stream_id=13) content-length: 12 -[ 0.013] recv (stream_id=13) content-type: text/plain -[ 0.013] recv (stream_id=13) date: Thu, 09 Jun 2016 08:56:56 GMT -[ 0.013] recv (stream_id=13) server: Cowboy -[ 0.013] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -Hello world![ 0.013] recv DATA frame - ; END_STREAM -[ 0.013] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/hello_world/relx.config b/_build/emqx/lib/cowboy/examples/hello_world/relx.config deleted file mode 100644 index b282ad9f2a..0000000000 --- a/_build/emqx/lib/cowboy/examples/hello_world/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {hello_world_example, "1"}, [hello_world]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/hello_world/src/hello_world_app.erl b/_build/emqx/lib/cowboy/examples/hello_world/src/hello_world_app.erl deleted file mode 100644 index daa7d19487..0000000000 --- a/_build/emqx/lib/cowboy/examples/hello_world/src/hello_world_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(hello_world_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - hello_world_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/hello_world/src/hello_world_sup.erl b/_build/emqx/lib/cowboy/examples/hello_world/src/hello_world_sup.erl deleted file mode 100644 index 01fbe3bcc8..0000000000 --- a/_build/emqx/lib/cowboy/examples/hello_world/src/hello_world_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(hello_world_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/hello_world/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/hello_world/src/toppage_h.erl deleted file mode 100644 index ee62a2fac3..0000000000 --- a/_build/emqx/lib/cowboy/examples/hello_world/src/toppage_h.erl +++ /dev/null @@ -1,12 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Hello world handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> - }, <<"Hello world!">>, Req0), - {ok, Req, Opts}. diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/Makefile b/_build/emqx/lib/cowboy/examples/markdown_middleware/Makefile deleted file mode 100644 index ccbd3c22a4..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = markdown_middleware -PROJECT_DESCRIPTION = Cowboy static file handler example with middleware component -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/README.asciidoc b/_build/emqx/lib/cowboy/examples/markdown_middleware/README.asciidoc deleted file mode 100644 index 3881bfb9f2..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/README.asciidoc +++ /dev/null @@ -1,15 +0,0 @@ -= Middleware example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080/video.html - -Cowboy will serve all the files you put in the `priv` directory. -If you request a `.html` file that has a corresponding `.md` file -that has been modified more recently than the `.html` file, the -Markdown file will be converted to HTML and served by Cowboy. diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/small.mp4 b/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/small.mp4 deleted file mode 100644 index 1fc478842f..0000000000 Binary files a/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/small.mp4 and /dev/null differ diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/small.ogv b/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/small.ogv deleted file mode 100644 index 6409d6e615..0000000000 Binary files a/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/small.ogv and /dev/null differ diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/video.md b/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/video.md deleted file mode 100644 index 422bd3218a..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/priv/video.md +++ /dev/null @@ -1,9 +0,0 @@ -HTML5 Video With Markdown -========================= - - - -Videos taken from [TechSlides](http://techslides.com/sample-webm-ogg-and-mp4-video-files-for-html5/) diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/relx.config b/_build/emqx/lib/cowboy/examples/markdown_middleware/relx.config deleted file mode 100644 index 9c622b9294..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {markdown_middleware_example, "1"}, [markdown_middleware]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/erlmarkdown.erl b/_build/emqx/lib/cowboy/examples/markdown_middleware/src/erlmarkdown.erl deleted file mode 100644 index 6cab50d70b..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/erlmarkdown.erl +++ /dev/null @@ -1,1581 +0,0 @@ -%%% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- -%%% Copyright 2012 Erlware, LLC. All Rights Reserved. -%%% -%%% This file is provided to you under the Apache License, -%%% Version 2.0 (the "License"); you may not use this file -%%% except in compliance with the License. You may obtain -%%% a copy of the License at -%%% -%%% http://www.apache.org/licenses/LICENSE-2.0 -%%% -%%% Unless required by applicable law or agreed to in writing, -%%% software distributed under the License is distributed on an -%%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%%% KIND, either express or implied. See the License for the -%%% specific language governing permissions and limitations -%%% under the License. -%%%--------------------------------------------------------------------------- -%%% @copyright (C) Erlware, LLC. -%%% @copyright (C) 2009, Gordon Guthrie -%%% @doc --module(erlmarkdown). - --export([conv/1, - conv_utf8/1, - conv_file/2]). - --define(SPACE, 32). --define(TAB, 9). --define(LF, 10). --define(CR, 13). --define(NBSP, 160). --define(AMP, $&, $a, $m, $p, $;). --define(COPY, $&, $c, $o, $p, $y, $;). - -%%============================================================================ -%% API -%%============================================================================ - -%% the lexer first lexes the input -%% make_lines does 2 passes: -%% * it chops the lexed strings into lines which it represents as a -%% list of lists -%% * it then types the lines into the following: -%% * normal lines -%% * reference style links -%% * reference style images -%% * special line types -%% - blank -%% - SETEXT header lines -%% - ATX header lines -%% - blockquote -%% - unordered lists -%% - ordered lists -%% - code blocks -%% - horizontal rules -%% the parser then does its magic interpolating the references as appropriate -conv(String) -> - Lex = lex(String), - UntypedLines = make_lines(Lex), - {TypedLines, Refs} = type_lines(UntypedLines), - parse(TypedLines, Refs). - --spec conv_utf8(list()) -> list(). -conv_utf8(Utf8) -> - Str = xmerl_ucs:from_utf8(Utf8), - Res = conv(Str), - xmerl_ucs:to_utf8(Res). - -conv_file(FileIn, FileOut) -> - case file:open(FileIn, [read]) of - {ok, Device} -> - Input = get_all_lines(Device,[]), - Output = conv(Input), - write(FileOut, Output); - _ -> - error - end. - -%%============================================================================ -%% Internal Functions -%%============================================================================ - -get_all_lines(Device, Accum) -> - case io:get_line(Device,"") of - eof -> - file:close(Device), - Accum; - Line -> - get_all_lines(Device,Accum ++ Line) - end. - -write(File, Text) -> - _Return=filelib:ensure_dir(File), - case file:open(File, [write]) of - {ok, Id} -> - io:fwrite(Id, "~s~n", [Text]), - file:close(Id); - _ -> - error - end. - - -%% -%% Parse the lines interpolating the references as appropriate -%% - -parse(TypedLines, Refs) -> - string:strip(p1(TypedLines, Refs, 0, []), both, $\n). - -%% goes through the lines -%% Variable 'R' contains the References and 'I' is the indent level - -%% Terminal clause -p1([], _R, _I, Acc) -> - lists:flatten(lists:reverse(Acc)); - -%% Tags have the highest precedence... -p1([{tag, Tag} | T], R, I, Acc) -> - case T of - [] -> - p1([], R, I, ["

", make_tag_str(Tag, R), "

" | Acc]); - [{blank, _} | T2] -> - p1(T2, R, I, [make_tag_str(Tag, R) | Acc]); - _Other -> - p1(T, R, I, [pad(I) ++ make_tag_str(Tag, R) | Acc]) - end; - -p1([{blocktag, [{{{tag, open}, Type}, Tg}] = _Tag} | T], R, I, Acc) -> - {Block, Rest} = grab_for_blockhtml(T, Type, []), - Str = lists:flatten([Tg, "\n" | Block]), - p1(Rest, R, I, [Str | Acc]); - -%% blank lines/linefeeds are gobbled down -p1([{Type, _} | T], R, I, Acc) - when Type == blank orelse Type == linefeed -> - Rest = grab_empties(T), - p1(Rest, R, I, [pad(I) ++ "\n" | Acc]); - -%% two consecutive normal lines should be concatenated... -%% remembering the pad the second line with the indent... -p1([{normal, P1}, {normal, P2} | T], R, I, Acc) -> - p1([{normal, merge(P1, pad(I), P2)} | T], R, I, Acc); -%% as should a normal and linefeed - -%% setext h1 is a look behind and it overrides blockquote and code... -p1([{normal, P}, {setext_h1, _} | T], R, I, Acc) -> - p1(T, R, I, [pad(I) ++ "

" ++ make_string(snip(P), R) - ++ "

\n\n" | Acc]); -p1([{blockquote, P}, {setext_h1, _} | T], R, I, Acc) -> - p1(T, R, I, [pad(I) ++ "

" ++ make_string(snip(P), R) - ++ "

\n\n" | Acc]); -p1([{{codeblock, P}, _}, {setext_h1, _} | T], R, I, Acc) -> - p1(T, R, I, [pad(I) ++ "

" ++ make_string(snip(P), R) - ++ "

\n\n" | Acc]); -p1([{blockquote, P}, {h2_or_hr, _} | T], R, I, Acc) -> - p1(T, R, I, [pad(I) ++ "

" ++ make_string(snip(P), R) - ++ "

\n\n" | Acc]); -p1([{{codeblock, P}, _}, {h2_or_hr, _} | T], R, I, Acc) -> - p1(T, R, I, [pad(I) ++ "

" ++ make_string(snip(P), R) - ++ "

\n\n" | Acc]); - -%% but a setext with no lookbehind is just rendered as a normal line, -%% so change its type and rethrow it -p1([{setext_h1, P} | T], R, I, Acc) -> - p1([{normal, P} | T], R, I, Acc); - -%% setext h2 might be a look behind -p1([{normal, P}, {h2_or_hr, _} | T], R, I, Acc) -> - P2 = string:strip(make_string(snip(P), R), both, ?SPACE), - p1(T, R, I, [pad(I) ++ "

" ++ P2 ++ "

\n\n" | Acc]); - -%% blockquotes swallow each other -%% replace the first blockquote mark with a space... -p1([{blockquote, P1}, {blockquote, [_ | P2]} | T], R, I, Acc) -> - p1([{blockquote, merge(P1, pad(I), [{{ws, sp}, " "} | P2])} | T], R, I, Acc); -%% blockquotes swallow normal -p1([{blockquote, P1}, {normal, P2} | T], R, I, Acc) -> - p1([{blockquote, merge(P1, pad(I + 1), P2)} | T], R, I, Acc); -%% blockquote -p1([{blockquote, P} | T], R, I, Acc) -> - [{{md, gt}, _} | T1] = P, - T2 = string:strip(make_string(T1, R)), - p1(T, R, I, - ["\n
\n" ++ pad(I + 1) ++ "

" ++ T2 ++ "

\n
" | Acc]); - -%% one normal is just normal... -p1([{normal, P} | T], R, I, Acc) -> - P2 = string:strip(make_string(snip(P), R), both, ?SPACE), - p1(T, R, I, [pad(I) ++ "

" ++ P2 ++ "

\n" | Acc]); - -%% atx headings -p1([{{h1, P}, _} | T], R, I, Acc) -> - NewP = string:strip(make_string(snip(P), R), right), - p1(T, R, I, [pad(I) ++ "

" ++ NewP ++ "

\n\n" | Acc]); -p1([{{h2, P}, _} | T], R, I, Acc) -> - NewP = string:strip(make_string(snip(P), R), right), - p1(T, R, I, [pad(I) ++ "

" ++ NewP ++ "

\n\n" | Acc]); -p1([{{h3, P}, _} | T], R, I, Acc) -> - NewP = string:strip(make_string(snip(P), R), right), - p1(T, R, I, [pad(I) ++ "

" ++ NewP ++ "

\n\n" | Acc]); -p1([{{h4, P}, _} | T], R, I, Acc) -> - NewP = string:strip(make_string(snip(P), R), right), - p1(T, R, I, [pad(I) ++ "

" ++ NewP ++ "

\n\n" | Acc]); -p1([{{h5, P}, _} | T], R, I, Acc) -> - NewP = string:strip(make_string(snip(P), R), right), - p1(T, R, I, [pad(I) ++ "
" ++ NewP ++ "
\n\n" | Acc]); -p1([{{h6, P}, _} | T], R, I, Acc) -> - NewP = string:strip(make_string(snip(P), R), right), - p1(T, R, I, [pad(I) ++ "
" ++ NewP ++ "
\n\n" | Acc]); - -%% unordered lists swallow normal and codeblock lines -p1([{{ul, P1}, S1}, {{normal, P2}, S2} | T], R, I , Acc) -> - p1([{{ul, merge(P1, pad(I), P2)}, S1 ++ S2} | T], R, I, Acc); -p1([{{ul, P1}, S1}, {{codeblock, P2}, S2} | T], R, I , Acc) -> - p1([{{ul, merge(P1, pad(I), P2)}, S1 ++ S2} | T], R, I, Acc); -p1([{{ul, _P}, _} | _T] = List, R, I, Acc) -> - {Rest, NewAcc} = parse_list(ul, List, R, I, [], false), - p1(Rest, R, I, [pad(I) ++ "
    \n" ++ NewAcc - ++ pad(I) ++ "
\n" | Acc]); - -%% ordered lists swallow normal and codeblock lines -p1([{{ol, P1}, S1}, {{normal, P2}, S2} | T], R, I , Acc) -> - p1([{{ol, merge(P1, pad(I), P2)}, S1 ++ S2} | T], R, I, Acc); -p1([{{ol, P1}, S1}, {{codeblock, P2}, S2} | T], R, I , Acc) -> - p1([{{ol, merge(P1, pad(I), P2)}, S1 ++ S2} | T], R, I, Acc); -p1([{{ol, _P}, _} | _T] = List, R, I, Acc) -> - {Rest, NewAcc} = parse_list(ol, List, R, I, [], false), - p1(Rest, R, I, [pad(I) ++ "
    \n" ++ NewAcc - ++ pad(I) ++ "
\n" | Acc]); - -%% codeblock consumes any following empty lines -%% and other codeblocks -p1([{{codeblock, P1}, S1}, {{codeblock, P2}, S2} | T], R, I, Acc) -> - p1([{{codeblock, merge(P1, pad(I), P2)}, S1 ++ S2} | T], R, I, Acc); -p1([{{codeblock, P}, _} | T], R, I, Acc) -> - Rest = grab_empties(T), - p1(Rest, R, I, ["
" ++ make_string(snip(P), R)
-                     ++ "\n
\n\n" | Acc]); - -%% horizontal rules -p1([{hr, _} | T], R, I, Acc) -> - p1(T, R, I, ["
" | Acc]); -%% h2_or_hr is greedy for normal lines -p1([{h2_or_hr, P1}, {normal, P2} | T], R, I, Acc) -> - p1([{normal, lists:flatten([P1 | P2])} | T], R, I, Acc); -%% the clause with a normal before an 'h2_or_hr' has already been -%% handled further up the tree, so this is a bona fide 'hr'... -p1([{h2_or_hr, _} | T], R, I, Acc) -> - p1(T, R, I, ["
" | Acc]); - -%% Now start pulling out inline refs etc, etc -p1([{inlineref, _P} | T], R, I, Acc) -> - p1(T, R, I, Acc). - -grab_for_blockhtml([], Type, Acc) -> - {lists:reverse(["" | Acc]), []}; -grab_for_blockhtml([{blocktag, [{{{tag, close}, Type}, Tg}]} - | T], Type, Acc) -> - {lists:reverse([Tg | Acc]), T}; -grab_for_blockhtml([{blocktag, [{{{tag, _}, GrabType}, Tg}]} - | T], Type, Acc) when GrabType =/= Type -> - %% blocktags grabbed in a blocktag need a line ending pushed - grab_for_blockhtml(T, Type, ["\n", Tg | Acc]); -grab_for_blockhtml([{tag, {{{tag, self_closing}, _Ty}, Tg}} - | T], Type, Acc) -> - grab_for_blockhtml(T, Type, [Tg | Acc]); -grab_for_blockhtml([H | T], Type, Acc) -> - {_Type, Content} = H, - Str = make_plain_string(Content), - grab_for_blockhtml(T, Type, [Str | Acc]). - -grab_empties([{linefeed, _} | T]) -> grab_empties(T); -grab_empties([{blank, _} | T]) -> grab_empties(T); -grab_empties(List) -> List. - -merge(P1, Pad, P2) -> - NewP1 = make_br(P1), - lists:flatten([NewP1, {string, Pad} | P2]). - -make_br(List) -> make_br1(lists:reverse(List)). - -make_br1([{{lf, _}, _}, - {{ws, comp}, _} | T]) -> lists:reverse([{tags, "
\n"} | T]); -make_br1([{{lf, _}, _}, - {{ws, tab}, _} | T]) -> lists:reverse([{tags, "
\n"} | T]); -make_br1(List) -> lists:reverse(List). - -pad(N) -> - pad1(N, []). - -pad1(0, Acc) -> - Acc; -pad1(N, Acc) - when N > 0 -> - pad1(N - 1, [" " | Acc]). - -%% this is a bit messy because of the way that hard lines are treated... -%% If your li's have a blank line between them the item gets wrapped in a para, -%% if not, they don't -%% BUT if one item is

wrapped then the next is too -parse_list(_Type, [], _R, _I, A, _) -> - {[], lists:reverse(A)}; -parse_list(Type, [{{Type, P}, _} | T], R, I, A, Wrap) -> - {Rest, NewP, NewWrap} = grab(T, R, [], Wrap), - Li = - case NewWrap of - false -> - Ret = parse([{normal, P}], R), - %% need to strip off the extra

's - Ret2 = string:left(Ret, length(Ret) - 4), - Ret3 = string:right(Ret2, length(Ret2) -3), - Ret3 ++ "\n" ++ NewP ++ pad(I); - true -> - string:strip(parse([{normal, P}], R), right, ?LF) - ++ NewP ++ pad(I) - end, - NewWrap2 = - case T of - [] -> - false; % doesnt matter - [H2 | _T2] -> - case H2 of - {linefeed, _} -> - true; - _ -> - false - end - end, - parse_list(Type, Rest, R, I, [pad(I) ++ "
  • " - ++ string:strip(Li, right, ?LF) - ++ "
  • \n" | A], NewWrap2); -parse_list(_Type, List, _R, _I, A, _) -> - {List, lists:reverse(A)}. - -%% grab grabs normals, double codeblocks, linefeeds and blanks -%% BUT stop grabbing if a normal if preceeded by a linefeed or blank -%% UNLESS the normal starts with white space :( -%% the third return parameter is 'true' if the 'li' should be -%% wrapped in '

    ' and false if it shouldn't -grab([{{codeblock, _}, S} | T] = List, R, Acc, W) -> - case is_blockquote(S, T) of - {{true, R1}, T2} -> - grab(T2, R, ["", - make_escape_string(R1, R), - "
    " | Acc], W); - {{esc_false, R1}, _T2} -> - {R1, lists:reverse(Acc), false}; - {false, T2} -> - case is_double_indent(S) of - false -> - {List, lists:reverse(Acc), false}; - {true, R2} -> - %% if it is a double indent - delete 4 spaces - %% no it makes not sense to me neither :( - grab(T2, R, [" " ++ make_escape_string(R2, R) | Acc], W) - end - end; -grab([{linefeed, _} | T], R, Acc, false) -> - grab2(T, R, Acc, T, Acc, true); -grab([{linefeed, _} | T], R, Acc, true) -> - grab2(T, R, ["\n" | Acc], T, Acc, true); -grab([{blank, _} | T], R, Acc, false) -> - grab2(T, R, Acc, T, Acc, true); -grab([{blank, _} | T], R, Acc, true) -> - grab2(T, R, ["\n" | Acc], T, Acc, true); -grab([{normal, P} | T], R, Acc, W) -> - Li = case W of - false -> - make_escape_string(P, R); - true -> - "

    "++ string:strip(make_escape_string(P, R), right, ?LF) - ++ "

    " - end, - grab(T, R, [Li | Acc], W); -grab(List, _R, Acc, W) -> - {List, lists:reverse(Acc), W}. - -%% the problem is knowing when to grab, if the list is followed by a long -%% string of blank lines and linefeeds and a normal then the linefeeds aren't -%% grabbed -%% if the list if followed by blank lines and linefeeds and a normal with an -%% initial whitespace it is grabbed... -grab2([{normal, P2} | T], R, Acc, LO, AO, W) -> - case P2 of - [{{ws, _}, _} | T2] -> - Li = case W of - false -> - make_escape_string(T2, R); - true -> - "

    " ++ - string:strip(make_escape_string(T2, R), right, ?LF) - ++ "

    " - end, - grab(T, R, [Li | Acc], W); - _ -> - {LO, AO, false} - end; -grab2([{linefeed, _} | T], R, Acc, LO, AO, _W) -> - grab2(T, R, ["\n" | Acc], LO, AO, true); -grab2([{blank, _} | T], R, Acc, LO, AO, _W) -> - grab2(T, R, ["\n" | Acc], LO, AO, true); -%% We dont want to grab this stuff so return the old list and the old acc -grab2(_List, _R, _Acc, LO, AO, _W) -> - {LO, AO, true}. - -is_double_indent(List) -> - is_double_indent1(List, 0). - -%% double indent is any combination of tabs and spaces that add -%% up to 8 -is_double_indent1([], _N) -> - false; -is_double_indent1(Rest, N) - when N > 7 -> - {true, Rest}; -is_double_indent1([{{ws, sp}, _} | T], N) -> - is_double_indent1(T, N + 1); -is_double_indent1([{{ws, tab}, _} | T], N) -> - is_double_indent1(T, N + 4); -is_double_indent1(_List, _N) -> - false. - -is_blockquote(List, T) -> - case is_bq1(List, 0) of - false -> - {false, T}; - {esc_false, R} -> - {{esc_false, R}, T}; - {true, R} -> - {NewT, NewR} = grab2(T, R), - {{true, NewR}, NewT} - end. - -is_bq1([], _N) -> - false; -is_bq1([{{ws, sp}, _} | T], N) -> - is_bq1(T, N + 1); -is_bq1([{{ws, tab}, _} | T], N) -> - is_bq1(T, N + 4); -is_bq1([{{md, gt}, _}, {{ws, _}, _} | T], N) - when N > 3 -> - {true, T}; -is_bq1([{{punc, bslash}, _}, {{md, gt}, GT}, {{ws, _}, WS} | T], N) - when N > 3 -> - {esc_false, [GT, WS | T]}; -is_bq1(_List, _N) -> - false. - -grab2(List, R) -> - gb2(List, lists:reverse(R)). - -gb2([], Acc) -> - {[], lists:flatten(lists:reverse(Acc))}; -gb2([{blank, _} | T], Acc) -> - {T, lists:flatten(lists:reverse(Acc))}; -gb2([{_Type, P} | T], Acc) -> - gb2(T, [P | Acc]). - -%% -%% Make the lines from the raw tokens -%% -make_lines(Tokens) -> - ml1(Tokens, [], []). - -ml1([], [], A2) -> - lists:reverse(A2); -ml1([], A1, A2) -> - ml1([], [], [lists:reverse(A1) | A2]); -ml1([{{lf, _}, _} = H | T], A1, A2) -> - ml1(T, [], [ml2(H, A1) | A2]); -ml1([H | T], A1, A2) -> - ml1(T, [H | A1], A2). - -ml2(H, List) -> - lists:reverse([H | List]). - -%%% -%%% Process the lines and give each line a type. The valid types are: -%%% * normal line -%%% * reference style links -%%% * reference style images -%%% * special line types -%%% - blank -%%% - SETEXT header lines -%%% - ATX header lines -%%% - unordered lists (including code blocks) -%%% - ordered lists (including code blocks) -%%% - blockquotes -%%% - code blocks -%%% - horizontal rules -%%% -type_lines(Lines) -> - {Refs, TypedLines} = type_lines1(Lines, [], []), - {strip_lines(TypedLines), Refs}. - -type_lines1([], A1, A2) -> - {A1, lists:reverse(A2)}; -type_lines1([[{{ws, sp}, _}, {{inline, open}, _} | T1] = H | T2], A1, A2) -> - %% this clause extracts URL and Image refs - %% (it is the only one that uses A1 and A2... - %% inlines can have up to 3 spaces before it - t_inline(H, T1, T2, A1, A2); -type_lines1([[{{ws, tab}, _}, {{inline, open}, _} | T1] = H | T2], A1, A2) -> - t_inline(H, T1, T2, A1, A2); -type_lines1([[{{ws, comp}, W}, {{inline, open}, _} | T1] = H | T2], A1, A2) -> - case gt(W, 3) of - {true, _R} -> - t_inline(H, T1, T2, A1, A2); - false -> - type_lines1(T1, A1, [{normal , H} | A2]) % same exit at the final clause! - end, - t_inline(H, T1, T2, A1, A2); -type_lines1([[{{inline, open}, _} | T1] = H | T2], A1, A2) -> - t_inline(H, T1, T2, A1, A2); -type_lines1([[{{md, eq}, _} | _T] = H | T], A1, A2) -> - %% types setext lines - type_lines1(T, A1, [type_setext_h1(H) | A2]); -type_lines1([[{{md, dash}, _} | _T] = H | T], A1, A2) -> - %% NOTE 1: generates a ul as the default not a normal line - %% NOTE 2: depending on the context this might generate an

    header - %% or an
    - %% NOTE 3: space - is typed to a bullet down in
      land... - type_lines1(T, A1, [type_setext_h2(H) | A2]); -type_lines1([[{{md, atx}, _} | _T] = H | T], A1, A2) -> - %% types atx lines - type_lines1(T, A1, [type_atx(H) | A2]); -type_lines1([[{{md, gt}, _} | []] = H | T], A1, A2) -> - %% types blockquotes - %% a blockquote on its own or followed by a linefeed is - %% displayed 'as is' by showdown - type_lines1(T, A1, [{normal, H} | A2]); -type_lines1([[{{md, gt}, _}, {{lf, _}, _} | []] = H | T], A1, A2) -> - type_lines1(T, A1, [{normal, H} | A2]); -%% one with anything after it starts a blockquote -type_lines1([[{{md, gt}, _} | _T1] = H | T], A1, A2) -> - type_lines1(T, A1, [{blockquote, H} | A2]); -type_lines1([[{{ws, _}, _}, {{md, star}, _} = ST1, {{ws, _}, _} = WS1 | T1] = H | T], A1, A2) -> - %% types unordered lists lines - %% NOTE 1: the dashed version is generated in type_setext_h2 - %% NOTE 2: the asterix version also might generate a horizontal rule - %% which is why it jumps to type_star2 <-- note the 2!! - type_lines1(T, A1, [{type_star2([ST1, WS1 | T1]), H} | A2]); -type_lines1([[{{md, star}, _}, {{ws, _}, _} | _T1] = H | T], A1, A2) -> - type_lines1(T, A1, [{type_star2(H), H} | A2]); -type_lines1([[{{ws, _}, _}, {{md, plus}, _}, {{ws, _}, _} = W | T1] = H | T], A1, A2) -> - type_lines1(T, A1, [{{ul, make_list_str([W | T1])}, H} | A2]); -type_lines1([[{{md, plus}, _}, {{ws, _}, _} = W | T1] = H | T], A1, A2) -> - type_lines1(T, A1, [{{ul, make_list_str([W | T1])}, H} | A2]); -%% UL based on dashes -type_lines1([[{{ws, _}, _}, {{md, dash}, _}, {{ws, _}, _} = W | T1] = H | T], A1, A2) -> - type_lines1(T, A1, [{{ul, make_list_str([W | T1])}, H} | A2]); -type_lines1([[{{ws, _}, _}, {num, _} = N1| T1] | T], A1, A2) -> - %% types ordered lists... - type_lines1(T, A1, [type_ol([N1 | T1]) | A2]); -type_lines1([[{num, _} | _T] = H | T], A1, A2) -> - type_lines1(T, A1, [type_ol(H) | A2]); -type_lines1([[{{md, underscore}, _} | _T1] = H | T], A1, A2) -> - %% types horizontal rules for stars and underscores - %% dashes and some stars are done elsewhere... - type_lines1(T, A1, [type_underscore(H) | A2]); -type_lines1([[{{md, star}, _} | _T1] = H | T], A1, A2) -> - type_lines1(T, A1, [type_star(H) | A2]); -type_lines1([[{{{tag, _Type}, Tag}, _ } = H | T1] = List | T], A1, A2) -> - %% Block level tags - these are look ahead they must be - %% on a single line (ie directly followed by a lf and nothing else - case is_blank(T1) of - false -> - type_lines1(T, A1, [{normal , List} | A2]); - true -> - case is_block_tag(Tag) of - true -> - type_lines1(T, A1, [{blocktag , [H]} | A2]); - false -> - type_lines1(T, A1, [{tag, [H | T1]} | A2]) - end - end; -type_lines1([[{{lf, _}, _}| []] = H | T], A1, A2) -> - %% types a blank line or a code block - type_lines1(T, A1, [{linefeed, H} | A2]); -type_lines1([[{{ws, _}, _} | _T1] = H | T], A1, A2) -> - type_lines1(T, A1, [type_ws(H) | A2]); - -%% Final clause... -type_lines1([H | T], A1, A2) -> - type_lines1(T, A1, [{normal , H} | A2]). - -t_inline(H, T1, T2, A1, A2) -> - case snip_ref(T1) of - {Type, {Id, {Url, Title}}} -> - type_lines1(T2, lists:flatten([{Id, {Url, Title}} | A1]), - [{Type, H} | A2]); - normal -> - type_lines1(T2, A1, [{normal, H} | A2]) - end. - -%% strips blanks from the beginning and end -strip_lines(List) -> - lists:reverse(strip_lines1(lists:reverse(strip_lines1(List)))). - -strip_lines1([{linefeed, _} | T]) -> - strip_lines1(T); -strip_lines1([{blank, _} | T]) -> - strip_lines1(T); -strip_lines1(List) -> - List. - -%% -%% Loads of type rules... -%% -is_blank([]) -> - true; -is_blank([{{lf, _}, _} | []]) -> - true; -is_blank([{{ws, _}, _} | T]) -> - is_blank(T); -is_blank(_List) -> - false. - -is_block_tag("address") -> - true; -is_block_tag("blockquote") -> - true; -is_block_tag("center") -> - true; -is_block_tag("dir") -> - true; -is_block_tag("div") -> - true; -is_block_tag("dl") -> - true; -is_block_tag("fieldset") -> - true; -is_block_tag("form") -> - true; -is_block_tag("h1") -> - true; -is_block_tag("h2") -> - true; -is_block_tag("h3") -> - true; -is_block_tag("h4") -> - true; -is_block_tag("h5") -> - true; -is_block_tag("h6") -> - true; -is_block_tag("hr") -> - true; -is_block_tag("isindex") -> - true; -is_block_tag("menu") -> - true; -is_block_tag("noframes") -> - true; -is_block_tag("noscript") -> - true; -is_block_tag("ol") -> - true; -is_block_tag("p") -> - true; -is_block_tag("pre") -> - true; -is_block_tag("table") -> - true; -is_block_tag("thead") -> - true; -is_block_tag("tbody") -> - true; -is_block_tag("tr") -> - true; -is_block_tag("td") -> - true; -is_block_tag("ul") -> - true; -is_block_tag(_Other) -> - false. - -type_underscore(List) -> - case type_underscore1(trim_right(List)) of - hr -> - {hr, List}; - maybe -> - {type_underscore2(List), List} - end. - -type_underscore1([]) -> - hr; -type_underscore1([{{md, underscore}, _} | T]) -> - type_underscore1(T); -type_underscore1(_List) -> - maybe. - -type_underscore2(List) -> - case trim_right(List) of % be permissive of trailing spaces - [{{md, underscore}, _}, {{ws, _}, _}, - {{md, underscore}, _}, {{ws, _}, _}, - {{md, underscore}, _}] -> - hr; - _Other -> - normal - end. - -type_star(List) -> - Trim = trim_right(List), - case type_star1(Trim) of % be permssive of trailing spaces - hr -> - {hr, trim_right(Trim)}; - maybe -> - Type = type_star2(List), - %% if it is a normal line we prepend it with a special - %% non-space filling white space character - case Type of - normal -> - {normal, [{{ws, none}, none} | List]}; - _ -> - {Type, List} - end - end. - -type_star1([]) -> - hr; -type_star1([{{md, star}, _} | T]) -> - type_star1(T); -type_star1(_List) -> - maybe. - -type_star2(List) -> - case trim_right(List) of - [{{md, star}, _}, {{ws, _}, _}, - {{md, star}, _}, {{ws, _}, _}, - {{md, star}, _}] -> - hr; - _Other -> - case List of - [{{md, star}, _}, - {{ws, _}, _}= WS | T] -> - {ul, make_list_str([WS | T])}; - _Other2 -> - normal - end - end. - -type_ol(List) -> - case type_ol1(List, []) of - normal -> - {normal, List}; - {ol, Str} -> - {{ol, Str}, List}; - {esc_normal, Str} -> - {normal, Str} - end. - -%% this line terminates on an escaped fullstop after a number -%% (but you need to drop the bslash...) -type_ol1([{num, _} = N, - {{punc, bslash}, _}, - {{punc, fullstop}, _} = P | T], Acc) -> - {esc_normal, lists:flatten([lists:reverse(Acc), N, P | T])}; -type_ol1([{num, _} = H | T], Acc) -> - %% we accumulate the digits in case we need to escape a full stop in a normal line - type_ol1(T, [H | Acc]); -type_ol1([{{punc, fullstop}, _}, {{ws, _}, _} | T], _Acc) -> - {ol, T}; -type_ol1(_List, _Acc) -> - normal. - -%% You need to understand what this function is trying to d... -%% '### blah' is fine -%% '### blah ###' is reduced to '### blah' because trailing #'s are -%% just for show but... -%% '##' is like appling '#' to '#' <-- applying 1 less styling to a single # -%% and '###' is like appling '##' to '#' etc, etc -%% but after you hit 6#'s you just get this for a single hash -%% ie '#############' is like applying '######' to a single '#' -%% but/and '######## blah' is like apply '######' to '## blah' -%% strip trailing #'s as they are decorative only... -type_atx(List) -> - {Sz, R} = get_atx_size(List), - A = [{{md, atx}, "#"}], - Type = - case is_all_hashes(R) of - true -> - if - Sz == 1 -> - normal; - ((Sz > 1) andalso (Sz < 6)) -> - Ns = integer_to_list(Sz - 1), - Hn = list_to_atom("h" ++ Ns), - {Hn, A}; - ((Sz == 6) andalso (R == [])) -> - {h5, A}; - ((Sz == 6) andalso (R == [{{lf, lf}, "\n"}])) -> - {h5, A}; - ((Sz == 6) andalso (R == [{{lf, crlf}, "\r\n"}])) -> - {h5, A}; - ((Sz == 6) andalso (R =/= [])) -> - {h6, A} - end; - false -> - Ns = integer_to_list(Sz), - Hn = list_to_atom("h" ++ Ns), - {Hn, strip_atx(R)} - end, - {Type, List}. - -is_all_hashes([]) -> - true; -is_all_hashes([{{md, atx}, _} | T]) -> - is_all_hashes(T); -is_all_hashes([{{lf, _}, _} | []]) -> - true; -is_all_hashes(_List) -> - false. - -get_atx_size(List) -> - g_atx_size1(List, 0). - - % this function also strips whitespace to the left... -g_atx_size1([{{md, atx}, _} = A | T], N) when N == 6 -> - {6, [A | T]}; -g_atx_size1([{{md, atx}, _} | T], N) -> - g_atx_size1(T, N + 1); -g_atx_size1([{{ws, _}, _} | T], N) -> - g_atx_size1(T, N); -g_atx_size1(List, N) -> - {N, List}. - -strip_atx(List) -> - lists:reverse(s_atx1(lists:reverse(List))). - -s_atx1([{{lf, _}, _}, {{md, atx}, _} | T]) -> - s_atx1(T); -s_atx1([{{md, atx}, _} | T]) -> - s_atx1(T); -s_atx1(List) -> - List. - -type_setext_h1(List) -> - type_s_h1_1(List, []). - -%% terminates on running out or new line -type_s_h1_1([{{lf, _}, _} = L | []], Acc) -> - {setext_h1, lists:reverse([L | Acc])}; -type_s_h1_1([], Acc)-> - {setext_h1, lists:reverse(Acc)}; -type_s_h1_1([[] | T], Acc) -> - type_s_h1_1(T, Acc); -type_s_h1_1([{{md, eq}, _} = H | T], Acc) -> - type_s_h1_1(T, [H | Acc]); -type_s_h1_1(L, Acc) -> - {normal, lists:flatten([Acc | L])}. - -type_setext_h2(List) -> - case type_s_h2_1(List) of - h2_or_hr -> - {h2_or_hr, List}; - not_h2 -> - {type_s_h2_2(trim_right(List)), List} - end. -%% terminates on running out or new line -type_s_h2_1([{{lf, _}, _} | []]) -> - h2_or_hr; -type_s_h2_1([]) -> - h2_or_hr; -type_s_h2_1([[] | T]) -> - type_s_h2_1(T); -type_s_h2_1([{{md, dash}, _} | T]) -> - type_s_h2_1(T); -type_s_h2_1(_L) -> - not_h2. - -type_s_h2_2([{{md, dash}, _}, {{ws,_}, _}, - {{md, dash}, _}, {{ws, _}, _}, - {{md, dash}, _}]) -> - hr; -type_s_h2_2([{{md, dash}, _}, - {{ws, _}, _} = WS | T]) -> - {ul, make_list_str([WS | T])}; -type_s_h2_2(_List) -> - normal. - -type_ws(List) -> - case type_ws1(List) of - blank -> - {blank, List}; - try_codeblock -> - case type_ws2(List) of - normal -> - {normal, List}; - {codeblock, Ret} -> - {{codeblock, Ret}, List} - end - end. - -type_ws1([]) -> - blank; -type_ws1([{{lf, _}, _} | []]) -> - blank; -type_ws1([[] | T]) -> - type_ws1(T); -type_ws1([{{ws, _}, _} | T]) -> - type_ws1(T); -type_ws1(_L) -> - try_codeblock. - -%% 4 or more spaces takes you over the limit -%% (a tab is 4...) -type_ws2([{{ws, tab}, _} | T]) -> - {codeblock, T}; -type_ws2([{{ws, comp}, W} | T]) -> - case gt(W, 4) of - {true, R} -> - {codeblock, [R| T]}; - false -> - normal - end; -type_ws2([{{ws, sp}, _} | _T]) -> - normal. - -gt(String, Len) -> - ExpString = re:replace(String, "\t", " ", [{return, list}]), - ExpStringLen = length(ExpString), - if - ExpStringLen >= Len -> - WS = string:substr(ExpString, Len + 1, - ExpStringLen), - {true, {{ws, sp}, WS}}; - ExpStringLen < Len -> - false - end. - -%% make a tag into a string -make_tag_str(L, R) -> - make_tag1(L, R, []). - -make_tag1([], _R, Acc) -> - lists:reverse(Acc); -make_tag1([{{{tag, _Type}, _Tag}, B} | T], R, Acc) -> - make_tag1(T, R, [B | Acc]); -make_tag1([H | T], R, Acc) -> - make_tag1(T, R, [make_string([H], R) | Acc]). - -esc_tag(String) -> - esc_tag1(String, []). - -esc_tag1([], Acc) -> - lists:reverse(Acc); -esc_tag1([?NBSP | T], Acc) -> - esc_tag1(T, [?SPACE | Acc]); % non-breaking space to space -esc_tag1([H | T], Acc) -> - esc_tag1(T, [H | Acc]). - -%% if it is a list we need to discard the initial white space... -make_list_str([{{ws, _}, _} | T] = List) -> - case is_double_indent(List) of - false -> - T; - {true, R} -> - lists:flatten([{tags, "
      "} ,R ,
      -                           {tags, "
      \n\n"} | []]) - end. - -%% All ref processing can ignore the original values 'cos those -%% have already been captured at a higher level -snip_ref(List) -> - case get_id(List) of - {[{_, Id}], Rest} -> - {_Rest2, Ref, Title} = parse_inline(Rest), - Ref2 = trim(Ref), - Rs = htmlencode(make_plain_string(Ref2)), - Ts = make_plain_string(Title), - {inlineref, {Id, {Rs, Ts}}}; - normal -> - normal - end. - -get_id(List) -> - g_id1(List, []). - -g_id1([], _Acc) -> - normal; -g_id1([{{inline, close}, _}, {{punc, colon}, _}, {{ws, _}, _} | T], Acc) -> - {lists:reverse(Acc), T}; -g_id1([H | T], Acc) -> - g_id1(T, [H | Acc]). - -parse_inline(List) -> - parse_inline1(List, []). - -%% snip off the terminal linefeed (if there is one...) -parse_inline1([{{lf, _}, _} | []], A) -> - {[], lists:reverse(A), []}; -parse_inline1([], A) -> - {[], lists:reverse(A), []}; -parse_inline1([{{punc, bslash}, _}, {bra, _} = B | T], A) -> - %% brackets can be escaped - parse_inline1(T, [B | A]); -parse_inline1([{{punc, bslash}, _}, {ket, _} = B | T], A) -> - parse_inline1(T, [B | A]); -parse_inline1([{{punc, bslash}, _}, {{punc, doubleq}, _} = Q | T], A) -> - parse_inline1(T, [Q | A]); -parse_inline1([{{punc, bslash}, _}, {{punc, singleq}, _} = Q | T], A) -> - parse_inline1(T, [Q | A]); -parse_inline1([{{punc, doubleq}, _} | T], A) -> - %% these clauses capture the start of the title... - parse_inline2(T, lists:reverse(A), doubleq, []); -parse_inline1([{{punc, singleq}, _} | T], A) -> - parse_inline2(T, lists:reverse(A), singleq, []); -parse_inline1([{bra, _} | T], A) -> - parse_inline2(T, lists:reverse(A), brackets, []); -parse_inline1([{ket, _} | T], A) -> - {T, lists:reverse(A), []}; -parse_inline1([H | T], A) -> - parse_inline1(T, [H | A]). - -%% this gets titles in single and double quotes -%% the delimiter type is passed in as 'D' -parse_inline2([], Url, _D, A) -> - {[], Url, lists:flatten(lists:reverse(A))}; - -parse_inline2([{{punc, bslash}, _}, {bra, _} = B | T], Url, D, A) -> - %% brackets can be escaped - parse_inline2(T, Url, D, [B | A]); -parse_inline2([{{punc, bslash}, _}, {ket, _} = B | T], Url, D, A) -> - parse_inline2(T, Url, D, [B | A]); -parse_inline2([{{punc, bslash}, _}, - {{punc, doubleq}, _}= Q | T], Url, D, A) -> - %% quotes can be escaped - parse_inline2(T, Url, D, [Q | A]); -parse_inline2([{{punc, bslash}, _}, {{punc, singleq}, _} = Q | T], Url, D, A) -> - parse_inline2(T, Url, D, [Q | A]); -parse_inline2([{{punc, doubleq}, _} | T], Url, doubleq, A) -> - %% these clauses capture the end of the title and drop the delimiter... - parse_inline2(T, Url, none, A); -parse_inline2([{{punc, singleq}, _} | T], Url, singleq, A) -> - parse_inline2(T, Url, none, A); -parse_inline2([{ket, _} | T], Url, brackets, A) -> - parse_inline2(T, Url, none, A); -parse_inline2([{ket, _} | T], Url, none, A) -> - %% terminator clause - {T, Url, lists:flatten(lists:reverse(A))}; -parse_inline2([_H | T], Url, none, A) -> - %% this clause silently discards stuff after the delimiter... - parse_inline2(T, Url, none, [A]); -parse_inline2([H | T], Url, D, A) -> - parse_inline2(T, Url, D, [H | A]). - -trim(String) -> - trim_left(trim_right(String)). - -trim_right(String) -> - lists:reverse(trim_left(lists:reverse(String))). - -trim_left([{{ws, _}, _} | T]) -> - trim_left(T); -trim_left([[] | T]) -> - trim_left(T); -trim_left(List) -> - List. - -snip(List) -> - List2 = lists:reverse(List), - case List2 of - [{{lf, _}, _} | T] -> - lists:reverse(T); - _ -> - List - end. - -%% end of ref processing - -%% -%% Build the Lexed Token List -%% This is a two part lexer, first it chunks the input and then on the second -%% pass it gathers it into lines and types the lines -%% -%% NOTE that there are two different styles of processing lines: -%% * markdown transformed -%% * block -%% inside block processing the whole text is dumped and just url encoded -%% and the original text is always maintained during the lexing/parsing -%% so that it can be recreated if the context requires it... -%% - -lex(String) -> - merge_ws(lex1(String, [], [])). - -merge_ws(List) -> - merge_ws1(List, []). - -merge_ws1([], Acc) -> - lists:reverse(Acc); -merge_ws1([{{ws, _}, W1}, {{ws, _}, W2} | T], Acc) -> - merge_ws1([{{ws, comp}, W1 ++ W2} | T], Acc); -merge_ws1([H | T], Acc) -> - merge_ws1(T, [H | Acc]). - -%% this is the terminal head which ends the parsing... -lex1([], [], A2) -> - lists:flatten(lists:reverse(A2)); -lex1([], A1, A2) -> - lex1([], [], [lex2(A1) | A2]); -%% these two heads capture opening and closing tags -lex1([$<, $/|T], A1, A2) -> - {Tag, NewT} = closingdiv(T, []), - lex1(NewT, [], [Tag, lex2(A1) | A2]); -lex1([$< | T], A1, A2) -> - {Tag, NewT} = openingdiv(T), - lex1(NewT, [], [Tag , lex2(A1) | A2]); -%% these clauses are the normal lexer clauses -lex1([$= | T], A1, A2) -> - lex1(T, [], [{{md, eq}, "="}, lex2(A1) | A2]); -lex1([$- | T], A1, A2) -> - lex1(T, [], [{{md, dash}, "-"}, lex2(A1) | A2]); -lex1([$# | T], A1, A2) -> - lex1(T, [], [{{md, atx}, "#"}, lex2(A1) | A2]); -lex1([$> | T], A1, A2) -> - lex1(T, [], [{{md, gt}, ">"}, lex2(A1) | A2]); -lex1([$+ | T], A1, A2) -> - lex1(T, [], [{{md, plus}, "+"}, lex2(A1) | A2]); -lex1([$* | T], A1, A2) -> - lex1(T, [], [{{md, star}, "*"}, lex2(A1) | A2]); -lex1([$_ | T], A1, A2) -> - lex1(T, [], [{{md, underscore}, "_"}, lex2(A1) | A2]); -lex1([$1 | T], A1, A2) -> - lex1(T, [], [{num, "1"}, lex2(A1) | A2]); -lex1([$2 | T], A1, A2) -> - lex1(T, [], [{num, "2"}, lex2(A1) | A2]); -lex1([$3 | T], A1, A2) -> - lex1(T, [], [{num, "3"}, lex2(A1) | A2]); -lex1([$4 | T], A1, A2) -> - lex1(T, [], [{num, "4"}, lex2(A1) | A2]); -lex1([$5 | T], A1, A2) -> - lex1(T, [], [{num, "5"}, lex2(A1) | A2]); -lex1([$6 | T], A1, A2) -> - lex1(T, [], [{num, "6"}, lex2(A1) | A2]); -lex1([$7 | T], A1, A2) -> - lex1(T, [], [{num, "7"}, lex2(A1) | A2]); -lex1([$8 | T], A1, A2) -> - lex1(T, [], [{num, "8"}, lex2(A1) | A2]); -lex1([$9 | T], A1, A2) -> - lex1(T, [], [{num, "9"}, lex2(A1) | A2]); -lex1([$0 | T], A1, A2) -> - lex1(T, [], [{num, "0"}, lex2(A1) | A2]); -lex1([$. | T], A1, A2) -> - lex1(T, [], [{{punc, fullstop}, "."}, lex2(A1) | A2]); -lex1([$: | T], A1, A2) -> - lex1(T, [], [{{punc, colon}, ":"}, lex2(A1) | A2]); -lex1([$' | T], A1, A2) -> - lex1(T, [], [{{punc, singleq}, "'"}, lex2(A1) | A2]); %' -lex1([$" | T], A1, A2) -> - lex1(T, [], [{{punc, doubleq}, "\""}, lex2(A1) | A2]); %" -lex1([$` | T], A1, A2) -> - lex1(T, [], [{{punc, backtick}, "`"}, lex2(A1) | A2]); %" -lex1([$! | T], A1, A2) -> - lex1(T, [], [{{punc, bang}, "!"}, lex2(A1) | A2]); %" -lex1([$\\ | T], A1, A2)-> - lex1(T, [], [{{punc, bslash}, "\\"}, lex2(A1) | A2]); %" -lex1([$/ | T], A1, A2) -> - lex1(T, [], [{{punc, fslash}, "/"}, lex2(A1) | A2]); %" -lex1([$( | T], A1, A2) -> - lex1(T, [], [{bra, "("}, lex2(A1) | A2]); -lex1([$) | T], A1, A2) -> - lex1(T, [], [{ket, ")"}, lex2(A1) | A2]); -lex1([$[ | T], A1, A2) -> - lex1(T, [], [{{inline, open}, "["}, lex2(A1) | A2]); -lex1([$] | T], A1, A2) -> - lex1(T, [], [{{inline, close}, "]"}, lex2(A1) | A2]); -lex1([?SPACE | T], A1, A2) -> - %% note there is a special 'whitespace' {{ws, none}, ""} which is used to generate non-space - %% filling whitespace for cases like '*bob* is great' which needs a non-space filling - %% whitespace prepended to trigger emphasis so it renders as "bob is great... - %% that 'character' doesn't exist so isn't in the lexer but appears in the parser - lex1(T, [], [{{ws, sp}, " "}, lex2(A1) | A2]); -lex1([?TAB | T], A1, A2) -> - lex1(T, [], [{{ws, tab}, "\t"}, lex2(A1) | A2]); -lex1([?NBSP | T], A1, A2) -> - lex1(T, [], [{{ws, sp}, " "}, lex2(A1) | A2]); -lex1([?CR, ?LF | T], A1, A2) -> - lex1(T, [], [{{lf, crlf}, [?CR , ?LF]}, lex2(A1) | A2]); -lex1([?LF | T], A1, A2) -> - lex1(T, [], [{{lf, lf}, [?LF]}, lex2(A1) | A2]); -lex1([H|T], A1, A2) -> - %% this final clause accumulates line fragments - lex1(T, [H |A1] , A2). - -lex2([]) -> - []; -lex2(List) -> - {string, lists:flatten(lists:reverse(List))}. - -%% need to put in regexes for urls and e-mail addies -openingdiv(String) -> - case get_url(String) of - {{url, URL}, R1} -> - {{url, URL}, R1}; - not_url -> - case get_email_addie(String) of - {{email, EM}, R2} -> - {{email, EM}, R2}; - not_email -> - openingdiv1(String, []) - end - end. - - % dumps out a list if it is not an opening div -openingdiv1([], Acc) -> - {lists:flatten([{{punc, bra}, "<"} | lex(lists:reverse(Acc))]), []}; -openingdiv1([$/,$>| T], Acc) -> - Acc2 = lists:flatten(lists:reverse(Acc)), - Acc3 = string:to_lower(Acc2), - [Tag | _T] = string:tokens(Acc3, " "), - {{{{tag, self_closing}, Tag}, "<" - ++ Acc2 ++ "/>"}, T}; -openingdiv1([$>| T], []) -> - %% special for non-tags - {[{{punc, bra}, "<"}, - {{punc, ket}, ">"}], T}; -openingdiv1([$>| T], Acc) -> - Acc2 = lists:flatten(lists:reverse(Acc)), - Acc3 = string:to_lower(Acc2), - [Tag | _T] = string:tokens(Acc3, " "), - {{{{tag, open}, Tag}, "<" - ++ Acc2 ++ ">"}, T}; -openingdiv1([H|T], Acc) -> - openingdiv1(T, [H | Acc]). - - % dumps out a list if it is not an closing div -closingdiv([], Acc) -> - {lists:flatten([{{punc, bra}, "<"}, {{punc, fslash}, "/"} - | lex(lists:reverse(Acc))]), []}; -closingdiv([$>| T], Acc) -> - Acc2 = lists:flatten(lists:reverse(Acc)), - Acc3 = string:to_lower(Acc2), - [Tag | _T] = string:tokens(Acc3, " "), - {{{{tag, close}, Tag}, ""}, T}; -closingdiv([H|T], Acc) -> - closingdiv(T, [H | Acc]). - -get_url(String) -> - HTTP_regex = "^(H|h)(T|t)(T|t)(P|p)(S|s)*://", - case re:run(String, HTTP_regex) of - nomatch -> - not_url; - {match, _} -> - get_url1(String, []) - end. - -get_url1([], Acc) -> - URL = lists:flatten(lists:reverse(Acc)), - {{url, URL}, []}; -get_url1([$\\, $> | T], Acc) -> - %% allow escaped kets - get_url1(T, [$>, $\\ | Acc]); -get_url1([$> | T], Acc) -> - URL = lists:flatten(lists:reverse(Acc)), - {{url, URL}, T}; -get_url1([H | T], Acc) -> - get_url1(T, [H | Acc]). - -get_email_addie(String) -> - Snip_regex = ">", - case re:run(String, Snip_regex) of - nomatch -> - not_email; - {match, [{N, _} | _T]} -> - {Possible, [$> | T]} = lists:split(N, String), - EMail_regex = "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+" - ++ "(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*" - ++ "@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+" - ++ "(?:[a-zA-Z]{2}|com|org|net|gov|mil" - ++ "|biz|info|mobi|name|aero|jobs|museum)", - case re:run(Possible, EMail_regex) of - nomatch -> - not_email; - {match, _} -> - {{email, Possible}, T} - end - end. - -make_plain_string(List) -> - make_plain_string(List, []). - -make_plain_string([], Acc) -> - lists:flatten(lists:reverse(Acc)); -make_plain_string([{{ws, none}, none} | T], Acc) -> - make_plain_string(T, [" " | Acc]); -make_plain_string([{_, Str} | T], Acc) -> - make_plain_string(T, [Str | Acc]). - -make_escape_string(List, Refs) -> - make_escape_string(List, Refs, []). - -make_escape_string([], _R, A) -> - lists:flatten(lists:reverse(A)); -make_escape_string([{tags, Tag} | T], R, A) -> - make_escape_string(T, R, [{tags, Tag} | A]); -make_escape_string([H | T], R, A) -> - make_escape_string(T, R, [make_string([H], R) | A]). - - -make_string(List, Refs) -> - make_string(List, Refs, []). - -make_string([], _R, A) -> - Flat = lists:flatten(lists:reverse(A)), - htmlchars(Flat); -make_string([{{punc, bang}, B}, {{inline, open}, O} | T], R, A) -> - case get_inline(T, R, [], img) of - {Rest, {Url, Title, Acc}} -> - Tag = [make_img_tag(Url, Acc, Title)], - make_string(Rest, R, [Tag | A]); - {Rest, Tag} -> - make_string(Rest, R, [Tag, O, B | A]) - end; -%% escape inline open's... -make_string([{{punc, bslash}, _}, {{inline, open}, O} | T], R, A) -> - make_string(T, R, [O | A]); -make_string([{{inline, open}, O} | T], R, A) -> - case get_inline(T, R, [], url) of - {Rest, {Url, Title, Acc}} -> - Tit = case Title of - [] -> - []; - _ -> - " title=\"" ++ Title ++ "\"" - end, - Tag = [{tags, ""}, Acc, - {tags, ""} | []], - make_string(Rest, R, [Tag | A]); - {Rest, Tag} -> - make_string(Rest, R, [Tag, O | A]) - end; -make_string([{email, Addie} | T], R, A) -> - make_string(T, R, [{tags, "\" />"}, Addie, {tags, " - make_string(T, R, [ {tags, ""}, Url, {tags, "\">"}, Url, - {tags, " - make_string(T, R, [Tag | A]); -make_string([{{{tag, Type}, Tag}, _} | T], R, A) -> - Tag2 = esc_tag(Tag), - TagStr = case Type of - open -> - {tags, "<" ++ Tag2 ++ ">"}; - close -> - {tags, "</" ++ Tag2 ++ ">"}; - self_closing -> - {tags, "<" ++ Tag2 ++ " />"} - end, - make_string(T, R, [TagStr | A]); -make_string([{_, Orig} | T], R, A) -> - make_string(T, R, [Orig | A]). - -get_inline([], _R, A, _) -> - %% if the inline doesn't terminate its not an inline... - {[], make_plain_string(lists:reverse(A))}; -get_inline([{{punc, bang}, _B}, {{inline, open}, _O} | T], R, A, url) -> - %% a url can contain an image inline - {Rest, {Url, Title, Acc}} = get_inline(T, R, A, img), - Tag = make_img_tag(Url, Acc, Title), - %% We double tag the tag so that it can get through the lists:flatteners.. - get_inline(Rest, R, [{tags, Tag} | A], url); -get_inline([{{inline, close}, _}, {bra, _} | T], _R, A, _) -> - {Rest, Url, Title} = parse_inline(T), - Tag = {string:strip(make_plain_string(Url)), - make_plain_string(Title), - make_plain_string(lists:reverse(A))}, - {Rest, Tag}; -get_inline([{{inline, close}, _}, {{ws, sp}, _}, {bra, _} | T], _R, A, img) -> - %% for img's but not url's you need to allow a single space between them - %% to be compatible with showdown :( - {Rest, Url, Title} = parse_inline(T), - Tag = {string:strip(make_plain_string(Url)), - make_plain_string(Title), - make_plain_string(lists:reverse(A))}, - {Rest, Tag}; -get_inline([{{inline, close}, _}, {{inline, open}, _} | T], R, A, _) -> - %% this clause detects references to images/links... - Text = make_plain_string(lists:reverse(A)), - case get_id_diff(T) of - normal -> - {[], make_plain_string(lists:reverse(A))}; - {[{_, Id}], Rest} -> - {Url, Title} = case lists:keyfind(Id, 1, R) of - false -> - {"", ""}; - {Id, {U, Tit}} -> - {U, Tit} - end, - Tag = {Url, Title, Text}, - {Rest, Tag}; - _Other -> - {[], make_plain_string(lists:reverse(A))} % random failing id's - end; -get_inline([{{inline, close}, _} = C , {{ws, _}, _}, - {{inline, open}, _} = O | T], R, A, Type) -> - %% so does this one - just delete the space and rethrow it - get_inline([C, O | T], R, A, Type); -get_inline([{{inline, close}, _} | T], R, A, _) -> - %% this is the markdown extension clause that takes an id in square brackets without - %% any additional stuff as a valid id marker - Id = make_plain_string(lists:reverse(A)), - case lists:keyfind(Id, 1, R) of - false -> - {T, lists:flatten([Id , $]])}; - {Id, {Url, Title}} -> - Tag = {Url, Title, Id}, - {T, Tag} - end; -get_inline([H | T], R, A, Type) -> - get_inline(T, R, [H | A], Type). - -get_id_diff(List) -> - g_id_diff1(List, []). - -g_id_diff1([], _Acc) -> - normal; -g_id_diff1([{{inline, close}, _}| T], Acc) -> - {lists:reverse(Acc), T}; -g_id_diff1([H | T], Acc) -> - g_id_diff1(T, [H | Acc]). - -%% convert ascii into html characters -htmlencode(List) -> - htmlencode(List, []). - -htmlencode([], Acc) -> - lists:flatten(lists:reverse(Acc)); - -htmlencode([$& | Rest], Acc) -> - htmlencode(Rest, ["&" | Acc]); -htmlencode([$< | Rest], Acc) -> - htmlencode(Rest, ["<" | Acc]); -htmlencode([$> | Rest], Acc) -> - htmlencode(Rest, [">" | Acc]); -htmlencode([160 | Rest], Acc) -> - htmlencode(Rest, [" " | Acc]); -htmlencode([Else | Rest], Acc) -> - htmlencode(Rest, [Else | Acc]). - -htmlchars(List) -> - htmlchars1(List, []). - -htmlchars1([], Acc) -> - lists:flatten(lists:reverse(Acc)); -htmlchars1([{tags, Tag} | T], Acc) -> - %% tags are just wheeched out unescaped - htmlchars1(T, [Tag | Acc]); -htmlchars1([?CR, ?LF | T], Acc) -> - %% line ends are pushed to a space.. - htmlchars1(T, ["\n" | Acc]); -htmlchars1([?LF | T], Acc) -> - %% line ends are pushed to a space.. - htmlchars1(T, ["\n" | Acc]); -htmlchars1([?CR | T], Acc) -> - htmlchars1(T, ["\r" | Acc]); -htmlchars1([$\\, $*, $*, $* | T], A) -> - %% there is a non-space filling white space represented by the atom 'none' - %% which is created in the parser (NOT IN THE LEXER!) and which triggers - %% emphasis or strong tags being turned on... - htmlchars1(T, [$*, $*, $* | A]); -htmlchars1([$*, $*, $* | T], A) -> - {T2, NewA} = superstrong(T, $*), - htmlchars1(T2, [NewA | A]); -htmlchars1([$\\, $*, $* | T], A) -> - %% repeat for strong - htmlchars1(T, [$*, $* | A]); -htmlchars1([$*, $* | T], A) -> - {T2, NewA} = strong(T, $*), - htmlchars1(T2, [NewA | A]); -htmlchars1([$\\, $* | T], A) -> - %% likewise for strong - htmlchars1(T, [$* | A]); -htmlchars1([$* | T], A) -> - {T2, NewA} = emphasis(T, $*), - htmlchars1(T2, [NewA | A]); -htmlchars1([$\\, $_, $_, $_ | T], A) -> - %% and again for underscores - htmlchars1(T, [$_, $_, $_ | A]); -htmlchars1([$_, $_, $_ | T], A) -> - %% the none atom is the non-space filling whitespace - {T2, NewA} = superstrong(T, $_), - htmlchars1(T2, [NewA | A]); -htmlchars1([$\\, $_, $_ | T], A) -> - %% and strong - %% and again for underscores - htmlchars1(T, [$_, $_ | A]); -htmlchars1([$_, $_ | T], A) -> - {T2, NewA} = strong(T, $_), - htmlchars1(T2, [NewA | A]); -htmlchars1([$\\, $_ | T], A) -> - %% likewise for strong - htmlchars1(T, [$_ | A]); -htmlchars1([$_ | T], A) -> - {T2, NewA} = emphasis(T, $_), - htmlchars1(T2, [NewA | A]); -htmlchars1([$\\, $` | T], A) -> - %% handle backtick escaping - htmlchars1(T, [$` | A]); -htmlchars1([$`, $` | T], A) -> - {T2, NewA} = dblcode(T), - htmlchars1(T2, [NewA | A]); -htmlchars1([$` | T], A) -> - {T2, NewA} = code(T), - htmlchars1(T2, [NewA | A]); -htmlchars1([?COPY | T], A) -> - htmlchars1(T, ["©" | A]); -htmlchars1([?AMP | T], A) -> - htmlchars1(T, ["&" | A]); -htmlchars1([$& | T], A) -> - htmlchars1(T, ["&" | A]); -htmlchars1([$< | T], A) -> - htmlchars1(T, ["<" | A]); -htmlchars1([?NBSP | T], A) -> - htmlchars1(T, [" " | A]); -htmlchars1([?TAB | T], A) -> - htmlchars1(T, [" " | A]); -htmlchars1([none | T], A) -> - htmlchars1(T, A); -htmlchars1([H | T], A) -> - htmlchars1(T, [H | A]). - -emphasis(List, Delim) -> - interpolate(List, Delim, "em", "" ,[]). -strong(List, Delim) -> - interpolate2(List, Delim, "strong", "", []). -superstrong(List, Delim) -> - interpolate3(List, Delim, "strong", "em", "", []). -dblcode(List) -> - {T, Tag} = interpolate2(List, $`, "code", "" ,[]), - {T, "
      " ++ Tag ++ "
      "}. -code(List) -> - interpolateX(List, $`, "code", "", []). - -%% pain in the arse - sometimes the closing tag should be preceded by -%% a "\n" and sometimes not in showdown.js -%% interpolate is for single delimiters... -interpolateX([], Delim, _Tag, _X, Acc) -> - {[], [Delim] ++ htmlchars(lists:reverse(Acc))}; -interpolateX([Delim | T], Delim, Tag, X, Acc) -> - {T, "<" ++ Tag ++ ">" ++ htmlchars(lists:reverse(Acc)) ++ X ++ - ""}; -interpolateX([H | T], Delim, Tag, X, Acc) -> - interpolateX(T, Delim, Tag, X, [H | Acc]). - -interpolate([], Delim, _Tag, _X, Acc) -> - {[], [Delim] ++ htmlchars(lists:reverse(Acc))}; -interpolate([Delim | T], Delim, Tag, X, Acc) -> - {T, "<" ++ Tag ++ ">" ++ htmlchars(lists:reverse(Acc)) ++ X ++ - ""}; -interpolate([H | T], Delim, Tag, X, Acc) -> - interpolate(T, Delim, Tag, X, [H | Acc]). - -%% interpolate two is for double delimiters... -interpolate2([], Delim, _Tag, _X, Acc) -> - {[], [Delim] ++ [Delim] ++ htmlchars(lists:reverse(Acc))}; -interpolate2([Delim, Delim | T], Delim, Tag, X, Acc) -> - {T, "<" ++ Tag ++ ">" ++ htmlchars(lists:reverse(Acc)) ++ X ++ - ""}; -interpolate2([H | T], Delim, Tag, X, Acc) -> - interpolate2(T, Delim, Tag, X, [H | Acc]). - -%% interpolate three is for double delimiters... -interpolate3([], D, _Tag1, Tag2, _X, Acc) -> - {[], "<" ++ Tag2 ++ ">" ++ [D] ++ "" - ++ htmlchars(lists:reverse(Acc))}; -interpolate3([D, D, D | T], D, Tag1, Tag2, _X, Acc) -> - {T, "<" ++ Tag1 ++ ">" ++ "<" ++ Tag2 ++ ">" - ++ htmlchars(lists:reverse(Acc)) ++ "" - ++ ""}; -interpolate3([H | T], D, Tag1, Tag2, X, Acc) -> - interpolate3(T, D, Tag1, Tag2, X, [H | Acc]). - -make_img_tag(Url, Acc, Title) -> - {tags, "\"""}. diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_converter.erl b/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_converter.erl deleted file mode 100644 index 988de9d435..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_converter.erl +++ /dev/null @@ -1,29 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - --module(markdown_converter). --behaviour(cowboy_middleware). - --export([execute/2]). - -execute(Req, Env) -> - [Path] = cowboy_req:path_info(Req), - case filename:extension(Path) of - <<".html">> -> maybe_generate_markdown(resource_path(Path)); - _Ext -> ok - end, - {ok, Req, Env}. - -maybe_generate_markdown(Path) -> - ModifiedAt = filelib:last_modified(source_path(Path)), - GeneratedAt = filelib:last_modified(Path), - case ModifiedAt > GeneratedAt of - true -> erlmarkdown:conv_file(source_path(Path), Path); - false -> ok - end. - -resource_path(Path) -> - PrivDir = code:priv_dir(markdown_middleware), - filename:join([PrivDir, Path]). - -source_path(Path) -> - << (filename:rootname(Path))/binary, ".md" >>. diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_middleware_app.erl b/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_middleware_app.erl deleted file mode 100644 index 75b3bc7c5a..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_middleware_app.erl +++ /dev/null @@ -1,26 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(markdown_middleware_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/[...]", cowboy_static, {priv_dir, markdown_middleware, ""}} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch}, - middlewares => [cowboy_router, markdown_converter, cowboy_handler] - }), - markdown_middleware_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_middleware_sup.erl b/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_middleware_sup.erl deleted file mode 100644 index 4bf71d1b56..0000000000 --- a/_build/emqx/lib/cowboy/examples/markdown_middleware/src/markdown_middleware_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(markdown_middleware_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/rest_basic_auth/Makefile b/_build/emqx/lib/cowboy/examples/rest_basic_auth/Makefile deleted file mode 100644 index dc7bd5cace..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_basic_auth/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = rest_basic_auth -PROJECT_DESCRIPTION = Cowboy Basic HTTP Authorization example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/rest_basic_auth/README.asciidoc b/_build/emqx/lib/cowboy/examples/rest_basic_auth/README.asciidoc deleted file mode 100644 index ce7ef26847..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_basic_auth/README.asciidoc +++ /dev/null @@ -1,152 +0,0 @@ -= Basic authorization example using REST - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -== HTTP/1.1 example output - -Request with no authentication: - -[source,bash] ----- -$ curl -i http://localhost:8080 -HTTP/1.1 401 Unauthorized -connection: keep-alive -server: Cowboy -date: Sun, 20 Jan 2013 14:10:27 GMT -content-length: 0 -www-authenticate: Basic realm="cowboy" ----- - -Request with authentication: - -[source,bash] ----- -$ curl -i -u "Alladin:open sesame" http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Sun, 20 Jan 2013 14:11:12 GMT -content-length: 16 -content-type: text/plain - -Hello, Alladin! ----- - -== HTTP/2 example output - -Request with no authentication: - -[source,bash] ----- -$ nghttp -v http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.004] recv SETTINGS frame - (niv=0) -[ 0.004] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.004] send SETTINGS frame - ; ACK - (niv=0) -[ 0.004] recv (stream_id=13) :status: 401 -[ 0.004] recv (stream_id=13) content-length: 0 -[ 0.004] recv (stream_id=13) date: Tue, 14 Jun 2016 09:15:56 GMT -[ 0.004] recv (stream_id=13) server: Cowboy -[ 0.004] recv (stream_id=13) www-authenticate: Basic realm="cowboy" -[ 0.004] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -[ 0.004] recv DATA frame - ; END_STREAM -[ 0.004] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- - -Request with authentication: - -[source,bash] ----- -$ nghttp -v -H "Authorization: Basic `echo -n Alladin:open sesame | base64`" http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.001] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 - authorization: Basic QWxsYWRpbjpvcGVuIHNlc2FtZQ== -[ 0.002] recv SETTINGS frame - (niv=0) -[ 0.002] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.002] send SETTINGS frame - ; ACK - (niv=0) -[ 0.004] recv (stream_id=13) :status: 200 -[ 0.004] recv (stream_id=13) content-length: 16 -[ 0.004] recv (stream_id=13) content-type: text/plain -[ 0.004] recv (stream_id=13) date: Tue, 14 Jun 2016 09:15:48 GMT -[ 0.004] recv (stream_id=13) server: Cowboy -[ 0.004] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -Hello, Alladin! -[ 0.004] recv DATA frame - ; END_STREAM -[ 0.004] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/rest_basic_auth/relx.config b/_build/emqx/lib/cowboy/examples/rest_basic_auth/relx.config deleted file mode 100644 index 1f75b28aa5..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_basic_auth/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {rest_basic_auth_example, "1"}, [rest_basic_auth]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/rest_basic_auth_app.erl b/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/rest_basic_auth_app.erl deleted file mode 100644 index f95dc36bb2..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/rest_basic_auth_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(rest_basic_auth_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - rest_basic_auth_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/rest_basic_auth_sup.erl b/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/rest_basic_auth_sup.erl deleted file mode 100644 index f6ce67cbb5..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/rest_basic_auth_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(rest_basic_auth_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/toppage_h.erl deleted file mode 100644 index 21b66ab34a..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_basic_auth/src/toppage_h.erl +++ /dev/null @@ -1,28 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Handler with basic HTTP authorization. --module(toppage_h). - --export([init/2]). --export([content_types_provided/2]). --export([is_authorized/2]). --export([to_text/2]). - -init(Req, Opts) -> - {cowboy_rest, Req, Opts}. - -is_authorized(Req, State) -> - case cowboy_req:parse_header(<<"authorization">>, Req) of - {basic, User = <<"Alladin">>, <<"open sesame">>} -> - {true, Req, User}; - _ -> - {{false, <<"Basic realm=\"cowboy\"">>}, Req, State} - end. - -content_types_provided(Req, State) -> - {[ - {<<"text/plain">>, to_text} - ], Req, State}. - -to_text(Req, User) -> - {<< "Hello, ", User/binary, "!\n" >>, Req, User}. diff --git a/_build/emqx/lib/cowboy/examples/rest_hello_world/Makefile b/_build/emqx/lib/cowboy/examples/rest_hello_world/Makefile deleted file mode 100644 index 3452a444fc..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_hello_world/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = rest_hello_world -PROJECT_DESCRIPTION = Cowboy REST Hello World example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/rest_hello_world/README.asciidoc b/_build/emqx/lib/cowboy/examples/rest_hello_world/README.asciidoc deleted file mode 100644 index a9362f1cb5..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_hello_world/README.asciidoc +++ /dev/null @@ -1,309 +0,0 @@ -= REST hello world example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -== HTTP/1.1 example output - -Request HTML: - -[source,bash] ----- -$ curl -i http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:15:52 GMT -content-length: 136 -content-type: text/html -vary: Accept - - - - - REST Hello World! - - -

      REST Hello World as HTML!

      - - ----- - -Request JSON: - -[source,bash] ----- -$ curl -i -H "Accept: application/json" http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:16:46 GMT -content-length: 24 -content-type: application/json -vary: Accept - -{"rest": "Hello World!"} ----- - -Request plain text: - -[source,bash] ----- -$ curl -i -H "Accept: text/plain" http://localhost:8080 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:18:35 GMT -content-length: 25 -content-type: text/plain -vary: Accept - -REST Hello World as text! ----- - -Request a non acceptable content-type: - -[source,bash] ----- -$ curl -i -H "Accept: text/css" http://localhost:8080 -HTTP/1.1 406 Not Acceptable -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:18:51 GMT -content-length: 0 - ----- - -== HTTP/2 example output - -Request HTML: - -[source,bash] ----- -$ nghttp -v http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.000] recv SETTINGS frame - (niv=0) -[ 0.000] send SETTINGS frame - ; ACK - (niv=0) -[ 0.000] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.001] recv (stream_id=13) :status: 200 -[ 0.001] recv (stream_id=13) content-length: 136 -[ 0.001] recv (stream_id=13) content-type: text/html -[ 0.001] recv (stream_id=13) date: Thu, 09 Jun 2016 14:28:50 GMT -[ 0.001] recv (stream_id=13) server: Cowboy -[ 0.001] recv (stream_id=13) vary: accept -[ 0.001] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header - - - - REST Hello World! - - -

      REST Hello World as HTML!

      - -[ 0.001] recv DATA frame - ; END_STREAM -[ 0.001] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- - -Request JSON: - -[source,bash] ----- -$ nghttp -v -H "accept: application/json" http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.001] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.001] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: application/json - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.001] recv SETTINGS frame - (niv=0) -[ 0.001] send SETTINGS frame - ; ACK - (niv=0) -[ 0.001] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.001] recv (stream_id=13) :status: 200 -[ 0.001] recv (stream_id=13) content-length: 24 -[ 0.001] recv (stream_id=13) content-type: application/json -[ 0.001] recv (stream_id=13) date: Thu, 09 Jun 2016 14:29:00 GMT -[ 0.001] recv (stream_id=13) server: Cowboy -[ 0.001] recv (stream_id=13) vary: accept -[ 0.001] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -{"rest": "Hello World!"}[ 0.002] recv DATA frame - ; END_STREAM -[ 0.002] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- - -Request plain text: - -[source,bash] ----- -$ nghttp -v -H "accept: text/plain" http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: text/plain - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.000] recv SETTINGS frame - (niv=0) -[ 0.000] send SETTINGS frame - ; ACK - (niv=0) -[ 0.000] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.000] recv (stream_id=13) :status: 200 -[ 0.000] recv (stream_id=13) content-length: 25 -[ 0.000] recv (stream_id=13) content-type: text/plain -[ 0.000] recv (stream_id=13) date: Thu, 09 Jun 2016 14:28:25 GMT -[ 0.000] recv (stream_id=13) server: Cowboy -[ 0.000] recv (stream_id=13) vary: accept -[ 0.000] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -REST Hello World as text![ 0.000] recv DATA frame - ; END_STREAM -[ 0.000] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- - -Request a non acceptable content-type: - -[source,bash] ----- -$ nghttp -v -H "accept: text/css" http://localhost:8080 -[ 0.000] Connected -[ 0.000] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.000] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.000] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: http - :authority: localhost:8080 - accept: text/css - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.007] recv SETTINGS frame - (niv=0) -[ 0.007] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.007] send SETTINGS frame - ; ACK - (niv=0) -[ 0.021] recv (stream_id=13) :status: 406 -[ 0.021] recv (stream_id=13) content-length: 0 -[ 0.021] recv (stream_id=13) date: Thu, 09 Jun 2016 14:29:15 GMT -[ 0.021] recv (stream_id=13) server: Cowboy -[ 0.021] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -[ 0.021] recv DATA frame - ; END_STREAM -[ 0.021] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/rest_hello_world/relx.config b/_build/emqx/lib/cowboy/examples/rest_hello_world/relx.config deleted file mode 100644 index a6152d4e46..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_hello_world/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {rest_hello_world_example, "1"}, [rest_hello_world]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/rest_hello_world/src/rest_hello_world_app.erl b/_build/emqx/lib/cowboy/examples/rest_hello_world/src/rest_hello_world_app.erl deleted file mode 100644 index 40dd890c9a..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_hello_world/src/rest_hello_world_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(rest_hello_world_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - rest_hello_world_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/rest_hello_world/src/rest_hello_world_sup.erl b/_build/emqx/lib/cowboy/examples/rest_hello_world/src/rest_hello_world_sup.erl deleted file mode 100644 index 3c0cecc09a..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_hello_world/src/rest_hello_world_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(rest_hello_world_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/rest_hello_world/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/rest_hello_world/src/toppage_h.erl deleted file mode 100644 index bbff6f7710..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_hello_world/src/toppage_h.erl +++ /dev/null @@ -1,39 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Hello world handler. --module(toppage_h). - --export([init/2]). --export([content_types_provided/2]). --export([hello_to_html/2]). --export([hello_to_json/2]). --export([hello_to_text/2]). - -init(Req, Opts) -> - {cowboy_rest, Req, Opts}. - -content_types_provided(Req, State) -> - {[ - {<<"text/html">>, hello_to_html}, - {<<"application/json">>, hello_to_json}, - {<<"text/plain">>, hello_to_text} - ], Req, State}. - -hello_to_html(Req, State) -> - Body = <<" - - - REST Hello World! - - -

      REST Hello World as HTML!

      - -">>, - {Body, Req, State}. - -hello_to_json(Req, State) -> - Body = <<"{\"rest\": \"Hello World!\"}">>, - {Body, Req, State}. - -hello_to_text(Req, State) -> - {<<"REST Hello World as text!">>, Req, State}. diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/Makefile b/_build/emqx/lib/cowboy/examples/rest_pastebin/Makefile deleted file mode 100644 index 994f4a4beb..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = rest_pastebin -PROJECT_DESCRIPTION = Cowboy REST Pastebin example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/README.asciidoc b/_build/emqx/lib/cowboy/examples/rest_pastebin/README.asciidoc deleted file mode 100644 index d0cabc139d..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/README.asciidoc +++ /dev/null @@ -1,47 +0,0 @@ -= REST pastebin example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -== Usage - -To upload something to the paste application, you can use `curl`: - -[source,bash] -$ | curl -i --data-urlencode paste@- localhost:8080 - -Or, to upload the file `my_file`: - -[source,bash] -curl -i --data-urlencode paste@my_file localhost:8080 - -The URL of your data will be in the location header. Alternately, you can visit -http://localhost:8080 with your favorite web browser and submit your paste via -the form. - -Code that has been pasted can be highlighted with ?lang= option if -you have http://www.andre-simon.de/doku/highlight/en/highlight.html[highlight] -installed (although `pygments` or any other should work just fine). - -This will show the contents of the HTML file: - -[source,bash] -curl -i --data-urlencode paste@priv/index.html localhost:8080 -curl - -If your terminal supports color sequences and `highlight` is installed, -the following command will show the same contents but with HTML syntax -highlighting. - -[source,bash] -curl ?lang=html - -If you open the same URL in your web browser and your web browser tells -Cowboy that it prefers HTML files, you will see the file highlighted -with special HTML markup and CSS. Firefox is known to work. diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/priv/index.html b/_build/emqx/lib/cowboy/examples/rest_pastebin/priv/index.html deleted file mode 100644 index 1c7e2eba1f..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/priv/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - Simple Pastebin - - -

      Simple Pastebin

      -

      - You can paste your text into the text field to submit, or you can - capture the output of a command with: -

      - - command | curl -i --data-urlencode paste@- localhost:8080 - -
      - -
      - -
      -
      - - diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/priv/index.txt b/_build/emqx/lib/cowboy/examples/rest_pastebin/priv/index.txt deleted file mode 100644 index 0135fb0064..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/priv/index.txt +++ /dev/null @@ -1,7 +0,0 @@ -Simple Pastebin ---------------- - -You can paste your text into the text field to submit, or you can capture the -output of a command with: - - | curl -i --data-urlencode paste@- localhost:8080 diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/relx.config b/_build/emqx/lib/cowboy/examples/rest_pastebin/relx.config deleted file mode 100644 index 6b8a67cb26..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {rest_pastebin_example, "1"}, [rest_pastebin]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/src/rest_pastebin_app.erl b/_build/emqx/lib/cowboy/examples/rest_pastebin/src/rest_pastebin_app.erl deleted file mode 100644 index a5e7ebc56f..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/src/rest_pastebin_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(rest_pastebin_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/[:paste_id]", toppage_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - rest_pastebin_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/src/rest_pastebin_sup.erl b/_build/emqx/lib/cowboy/examples/rest_pastebin/src/rest_pastebin_sup.erl deleted file mode 100644 index b5f08d702c..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/src/rest_pastebin_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(rest_pastebin_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/rest_pastebin/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/rest_pastebin/src/toppage_h.erl deleted file mode 100644 index 784cad070d..0000000000 --- a/_build/emqx/lib/cowboy/examples/rest_pastebin/src/toppage_h.erl +++ /dev/null @@ -1,134 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Pastebin handler. --module(toppage_h). - -%% Standard callbacks. --export([init/2]). --export([allowed_methods/2]). --export([content_types_provided/2]). --export([content_types_accepted/2]). --export([resource_exists/2]). - -%% Custom callbacks. --export([create_paste/2]). --export([paste_html/2]). --export([paste_text/2]). - -init(Req, Opts) -> - {cowboy_rest, Req, Opts}. - -allowed_methods(Req, State) -> - {[<<"GET">>, <<"POST">>], Req, State}. - -content_types_provided(Req, State) -> - {[ - {{<<"text">>, <<"plain">>, []}, paste_text}, - {{<<"text">>, <<"html">>, []}, paste_html} - ], Req, State}. - -content_types_accepted(Req, State) -> - {[{{<<"application">>, <<"x-www-form-urlencoded">>, '*'}, create_paste}], - Req, State}. - -resource_exists(Req, _State) -> - case cowboy_req:binding(paste_id, Req) of - undefined -> - {true, Req, index}; - PasteID -> - case valid_path(PasteID) and file_exists(PasteID) of - true -> {true, Req, PasteID}; - false -> {false, Req, PasteID} - end - end. - -create_paste(Req, State) -> - PasteID = new_paste_id(), - {ok, [{<<"paste">>, Paste}], Req2} = cowboy_req:read_urlencoded_body(Req), - ok = file:write_file(full_path(PasteID), Paste), - case cowboy_req:method(Req2) of - <<"POST">> -> - {{true, <<$/, PasteID/binary>>}, Req2, State}; - _ -> - {true, Req2, State} - end. - -paste_html(Req, index) -> - {read_file("index.html"), Req, index}; -paste_html(Req, Paste) -> - #{lang := Lang} = cowboy_req:match_qs([{lang, [fun lang_constraint/2], plain}], Req), - {format_html(Paste, Lang), Req, Paste}. - -paste_text(Req, index) -> - {read_file("index.txt"), Req, index}; -paste_text(Req, Paste) -> - #{lang := Lang} = cowboy_req:match_qs([{lang, [fun lang_constraint/2], plain}], Req), - {format_text(Paste, Lang), Req, Paste}. - -% Private - -lang_constraint(forward, Bin) -> - case re:run(Bin, "^[a-z0-9_]+$", [{capture, none}]) of - match -> {ok, Bin}; - nomatch -> {error, bad_lang} - end; -lang_constraint(format_error, {bad_lang, _}) -> - "Invalid lang parameter.". - -read_file(Name) -> - {ok, Binary} = file:read_file(full_path(Name)), - Binary. - -full_path(Name) -> - filename:join([code:priv_dir(rest_pastebin), Name]). - -file_exists(Name) -> - case file:read_file_info(full_path(Name)) of - {ok, _Info} -> true; - {error, _Reason} -> false - end. - -valid_path(<<>>) -> true; -valid_path(<<$., _T/binary>>) -> false; -valid_path(<<$/, _T/binary>>) -> false; -valid_path(<<_Char, T/binary>>) -> valid_path(T). - -new_paste_id() -> - Initial = rand:uniform(62) - 1, - new_paste_id(<>, 7). -new_paste_id(Bin, 0) -> - Chars = <<"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890">>, - << <<(binary_part(Chars, B, 1))/binary>> || <> <= Bin >>; -new_paste_id(Bin, Rem) -> - Next = rand:uniform(62) - 1, - new_paste_id(<>, Rem - 1). - -format_html(Paste, plain) -> - Text = escape_html_chars(read_file(Paste)), - <<"", - "paste", - "
      ", Text/binary, "
      \n">>; -format_html(Paste, Lang) -> - highlight(full_path(Paste), Lang, "html"). - -format_text(Paste, plain) -> - read_file(Paste); -format_text(Paste, Lang) -> - highlight(full_path(Paste), Lang, "ansi"). - -highlight(Path, Lang, Type) -> - Path1 = binary_to_list(Path), - Lang1 = binary_to_list(Lang), - os:cmd(["highlight --syntax=", Lang1, - " --doc-title=paste ", - " --out-format=", Type, - " --include-style ", Path1]). - -% Escape some HTML characters that might make a fuss -escape_html_chars(Bin) -> - << <<(escape_html_char(B))/binary>> || <> <= Bin >>. - -escape_html_char($<) -> <<"<">>; -escape_html_char($>) -> <<">">>; -escape_html_char($&) -> <<"&">>; -escape_html_char(C) -> <>. diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/Makefile b/_build/emqx/lib/cowboy/examples/ssl_hello_world/Makefile deleted file mode 100644 index 47676a973e..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -PROJECT = ssl_hello_world -PROJECT_DESCRIPTION = Cowboy SSL Hello World example -PROJECT_VERSION = 1 - -DEPS = cowboy -LOCAL_DEPS = ssl -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/README.asciidoc b/_build/emqx/lib/cowboy/examples/ssl_hello_world/README.asciidoc deleted file mode 100644 index 70ee7f8cff..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/README.asciidoc +++ /dev/null @@ -1,85 +0,0 @@ -= Secure hello world example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to https://localhost:8443 - -You will need to temporarily trust the root certificate authority, -which can also be found in `priv/ssl/cowboy-ca.crt`. - -Recent browsers will communicate using HTTP/2. Older browsers -will use HTTP/1.1. - -== HTTP/1.1 example output - -[source,bash] ----- -$ curl --cacert priv/ssl/cowboy-ca.crt -i https://localhost:8443 -HTTP/1.1 200 OK -connection: keep-alive -server: Cowboy -date: Fri, 28 Sep 2012 04:10:25 GMT -content-length: 12 - -Hello world! ----- - -== HTTP/2 example output - -[source,bash] ----- -$ nghttp -v https://localhost:8443 -[ 0.001] Connected -The negotiated protocol: h2 -[ 0.009] recv SETTINGS frame - (niv=0) -[ 0.009] send SETTINGS frame - (niv=2) - [SETTINGS_MAX_CONCURRENT_STREAMS(0x03):100] - [SETTINGS_INITIAL_WINDOW_SIZE(0x04):65535] -[ 0.009] send SETTINGS frame - ; ACK - (niv=0) -[ 0.009] send PRIORITY frame - (dep_stream_id=0, weight=201, exclusive=0) -[ 0.009] send PRIORITY frame - (dep_stream_id=0, weight=101, exclusive=0) -[ 0.009] send PRIORITY frame - (dep_stream_id=0, weight=1, exclusive=0) -[ 0.009] send PRIORITY frame - (dep_stream_id=7, weight=1, exclusive=0) -[ 0.009] send PRIORITY frame - (dep_stream_id=3, weight=1, exclusive=0) -[ 0.009] send HEADERS frame - ; END_STREAM | END_HEADERS | PRIORITY - (padlen=0, dep_stream_id=11, weight=16, exclusive=0) - ; Open new stream - :method: GET - :path: / - :scheme: https - :authority: localhost:8443 - accept: */* - accept-encoding: gzip, deflate - user-agent: nghttp2/1.7.1 -[ 0.010] recv SETTINGS frame - ; ACK - (niv=0) -[ 0.010] recv (stream_id=13) :status: 200 -[ 0.010] recv (stream_id=13) content-length: 12 -[ 0.010] recv (stream_id=13) content-type: text/plain -[ 0.010] recv (stream_id=13) date: Sat, 30 Apr 2016 12:54:32 GMT -[ 0.010] recv (stream_id=13) server: Cowboy -[ 0.010] recv HEADERS frame - ; END_HEADERS - (padlen=0) - ; First response header -Hello world![ 0.010] recv DATA frame - ; END_STREAM -[ 0.010] send GOAWAY frame - (last_stream_id=0, error_code=NO_ERROR(0x00), opaque_data(0)=[]) ----- diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/cowboy-ca.crt b/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/cowboy-ca.crt deleted file mode 100644 index a35ac390a0..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/cowboy-ca.crt +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICeDCCAeGgAwIBAgIJAOvpU0y2e5J4MA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV -BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczETMBEGA1UECgwKTmluZSBOaW5lczEPMA0G -A1UECwwGQ293Ym95MRAwDgYDVQQDDAdST09UIENBMB4XDTEzMDIyODA1MTAwMVoX -DTMzMDIyMzA1MTAwMVowVTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMRMw -EQYDVQQKDApOaW5lIE5pbmVzMQ8wDQYDVQQLDAZDb3dib3kxEDAOBgNVBAMMB1JP -T1QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMzmY7Us06yjyUbpqwPx -Iv+xh/g3V7we07ClC9GEYnvr3OQvdA1jFEHccMBUUjRoQ8DPd6uSyK5UkixABs08 -Tt5B3VsnGKr0DIN+IO4SN2PkmBqIU/BN3KdcwN65YNr3iM0KsKWeFtAZdYx4CakX -7REbO0wjK20AH3xSBn3uFGiBAgMBAAGjUDBOMB0GA1UdDgQWBBRKfZ8KF2jlLBDm -NL6IuEuGY0pdbzAfBgNVHSMEGDAWgBRKfZ8KF2jlLBDmNL6IuEuGY0pdbzAMBgNV -HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAG1I0kBxXiLkM1b7rl2zPLizREYg -1m+ajb6rWzPOBg6TXjv58Be+H4tqoHIL/M/crixew5emftBkuAGjiKMhbIokjvan -aPTCV8U6HHvNvz9c68HpESWbd+56cHqfsS5XCKp1OpW5tbL2UQYpFKMP4qmbv3Ea -pBfPPmSFMBb1i2AI ------END CERTIFICATE----- diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/server.crt b/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/server.crt deleted file mode 100644 index 0bdfaed01c..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/server.crt +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICpTCCAg6gAwIBAgIJAOvpU0y2e5J5MA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV -BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczETMBEGA1UECgwKTmluZSBOaW5lczEPMA0G -A1UECwwGQ293Ym95MRAwDgYDVQQDDAdST09UIENBMB4XDTEzMDIyODA1MjMzNFoX -DTMzMDIyMzA1MjMzNFowVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMRMw -EQYDVQQKDApOaW5lIE5pbmVzMQ8wDQYDVQQLDAZDb3dib3kxEjAQBgNVBAMMCWxv -Y2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAzbW1GjECzHUc/WST -qLiAGqjCNccR5saVS+yoz2SPRhpoyf0/qBrX5BY0tzmgozoTiRfE4wCiVD99Cc+D -rp/FM49r4EpZdocIovprmOmv/gwkoj95zaA6PKNn1OdmDp2hwJsX2Zm3kpbGUZTx -jDkkccmgUb4EjL7qNHq7saQtivUCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB -hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE -FB6jTEIWI8T1ckORA4GezbyYxtbvMB8GA1UdIwQYMBaAFEp9nwoXaOUsEOY0voi4 -S4ZjSl1vMA0GCSqGSIb3DQEBBQUAA4GBACMboVQjrx8u/fk3gl/sR0tbA0Wf/NcS -2Dzsy2czndgVUAG4Sqb+hfgn0dqAyUKghRrj3JDcYxYksGPIklDfPzZb7yJ39l16 -6x5ZiIzhp8CAVdPvRxRznw5rZwaXesryXu1jVSZxTr3MYZdkG6KaAM0t90+YlGLZ -UG8fAicx0Bf+ ------END CERTIFICATE----- diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/server.key b/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/server.key deleted file mode 100644 index b6f7374211..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/priv/ssl/server.key +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXQIBAAKBgQDNtbUaMQLMdRz9ZJOouIAaqMI1xxHmxpVL7KjPZI9GGmjJ/T+o -GtfkFjS3OaCjOhOJF8TjAKJUP30Jz4Oun8Uzj2vgSll2hwii+muY6a/+DCSiP3nN -oDo8o2fU52YOnaHAmxfZmbeSlsZRlPGMOSRxyaBRvgSMvuo0eruxpC2K9QIDAQAB -AoGAaD85c/h6bpq7Aj7CBbLaWKhFI3OqwsTITB22vsM7SE+B4zsP02UnG1OVi3UM -zytTUxpUkKV1njQ+bYZYOVqGWF4Up8tTqUglHn0FTPok1AIemELWtz3sXvdSHC1T -lqvFBAZ9kibn13qGyVOiyCFaMwfOM/05RvV7p3jfUMTWnNECQQDs7yCJZ8Ol8MyH -TGZzvkjoN2zg1KwmTbSD1hkP6QAJtPdRuqFbjlEru0/PefgOXsWLRIa3/3v0qw2G -xGkV6AXTAkEA3kNbFisqUydjPnZIYv/P6SvPdUimHJEjXbAbfNfzS9dzszrOVJd2 -XqGH7z5yzjoH3IyaIMW8GnubVzGDSjrHFwJAKSU5vELlygpwKkrNO+pelN0TLlQg -dSJnZ8GlZorq88SWcn37iX/EftivenNO7YftvEqxLoDSkOGnnrC7Iw/A+wJBAIEe -L/QY72WPJCBNJpAce/PA96vyoE1II3txqwZDjZspdpVQPDz4IFOpEwbxCFC1dYuy -Qnd3Z2cbF4r3wIWGz9ECQQCJGNhUNtY+Om1ELdqPcquxE2VRV/pucnvJSTKwyo2C -Rvm6H7kFDwPDuN23YnTOlTiho0zzCkclcIukhIVJ+dKz ------END RSA PRIVATE KEY----- diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/relx.config b/_build/emqx/lib/cowboy/examples/ssl_hello_world/relx.config deleted file mode 100644 index d40e07b607..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {ssl_hello_world_example, "1"}, [ssl_hello_world]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/ssl_hello_world_app.erl b/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/ssl_hello_world_app.erl deleted file mode 100644 index 959dc7790c..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/ssl_hello_world_app.erl +++ /dev/null @@ -1,29 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(ssl_hello_world_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. - -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", toppage_h, []} - ]} - ]), - PrivDir = code:priv_dir(ssl_hello_world), - {ok, _} = cowboy:start_tls(https, [ - {port, 8443}, - {cacertfile, PrivDir ++ "/ssl/cowboy-ca.crt"}, - {certfile, PrivDir ++ "/ssl/server.crt"}, - {keyfile, PrivDir ++ "/ssl/server.key"} - ], #{env => #{dispatch => Dispatch}}), - ssl_hello_world_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(https). diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/ssl_hello_world_sup.erl b/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/ssl_hello_world_sup.erl deleted file mode 100644 index 27b63f888b..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/ssl_hello_world_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(ssl_hello_world_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/toppage_h.erl b/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/toppage_h.erl deleted file mode 100644 index ee62a2fac3..0000000000 --- a/_build/emqx/lib/cowboy/examples/ssl_hello_world/src/toppage_h.erl +++ /dev/null @@ -1,12 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Hello world handler. --module(toppage_h). - --export([init/2]). - -init(Req0, Opts) -> - Req = cowboy_req:reply(200, #{ - <<"content-type">> => <<"text/plain">> - }, <<"Hello world!">>, Req0), - {ok, Req, Opts}. diff --git a/_build/emqx/lib/cowboy/examples/upload/Makefile b/_build/emqx/lib/cowboy/examples/upload/Makefile deleted file mode 100644 index af39f92965..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = upload -PROJECT_DESCRIPTION = Cowboy multipart upload example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/upload/README.asciidoc b/_build/emqx/lib/cowboy/examples/upload/README.asciidoc deleted file mode 100644 index 96f6ec79c3..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/README.asciidoc +++ /dev/null @@ -1,12 +0,0 @@ -= Multipart upload example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 - -The uploaded file will be displayed in the shell directly. diff --git a/_build/emqx/lib/cowboy/examples/upload/priv/index.html b/_build/emqx/lib/cowboy/examples/upload/priv/index.html deleted file mode 100644 index 031420df49..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/priv/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - Multipart upload example - - - -
      - - -
      - - diff --git a/_build/emqx/lib/cowboy/examples/upload/relx.config b/_build/emqx/lib/cowboy/examples/upload/relx.config deleted file mode 100644 index e51e5c2a0f..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {upload_example, "1"}, [upload]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/upload/src/upload_app.erl b/_build/emqx/lib/cowboy/examples/upload/src/upload_app.erl deleted file mode 100644 index 6fb829ff61..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/src/upload_app.erl +++ /dev/null @@ -1,25 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(upload_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", cowboy_static, {priv_file, upload, "index.html"}}, - {"/upload", upload_h, []} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - upload_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/upload/src/upload_h.erl b/_build/emqx/lib/cowboy/examples/upload/src/upload_h.erl deleted file mode 100644 index 45db8e1baf..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/src/upload_h.erl +++ /dev/null @@ -1,15 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @doc Upload handler. --module(upload_h). - --export([init/2]). - -init(Req, Opts) -> - {ok, Headers, Req2} = cowboy_req:read_part(Req), - {ok, Data, Req3} = cowboy_req:read_part_body(Req2), - {file, <<"inputfile">>, Filename, ContentType} - = cow_multipart:form_data(Headers), - io:format("Received file ~p of content-type ~p as follow:~n~p~n~n", - [Filename, ContentType, Data]), - {ok, Req3, Opts}. diff --git a/_build/emqx/lib/cowboy/examples/upload/src/upload_sup.erl b/_build/emqx/lib/cowboy/examples/upload/src/upload_sup.erl deleted file mode 100644 index 0d0350322c..0000000000 --- a/_build/emqx/lib/cowboy/examples/upload/src/upload_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(upload_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/websocket/Makefile b/_build/emqx/lib/cowboy/examples/websocket/Makefile deleted file mode 100644 index 955cd527d5..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -PROJECT = websocket -PROJECT_DESCRIPTION = Cowboy Websocket example -PROJECT_VERSION = 1 - -DEPS = cowboy -dep_cowboy_commit = master - -include ../../erlang.mk diff --git a/_build/emqx/lib/cowboy/examples/websocket/README.asciidoc b/_build/emqx/lib/cowboy/examples/websocket/README.asciidoc deleted file mode 100644 index 0b2260743b..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/README.asciidoc +++ /dev/null @@ -1,10 +0,0 @@ -= Websocket example - -To try this example, you need GNU `make` and `git` in your PATH. - -To build and run the example, use the following command: - -[source,bash] -$ make run - -Then point your browser to http://localhost:8080 diff --git a/_build/emqx/lib/cowboy/examples/websocket/priv/index.html b/_build/emqx/lib/cowboy/examples/websocket/priv/index.html deleted file mode 100644 index 56f36b248c..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/priv/index.html +++ /dev/null @@ -1,113 +0,0 @@ - - - - Websocket client - - - - - - - - - - - diff --git a/_build/emqx/lib/cowboy/examples/websocket/priv/static/jquery.min.js b/_build/emqx/lib/cowboy/examples/websocket/priv/static/jquery.min.js deleted file mode 100644 index f121291c4c..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/priv/static/jquery.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v@1.8.0 jquery.com | jquery.org/license */ -(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write(""),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b
      a",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="
      t
      ",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="
      ",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;jq&&u.push({elem:this,matches:o.slice(q)});for(d=0;d0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;ai){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="
      ",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="

      ",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b0)for(e=d;e=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*\s*$/g,bz={option:[1,""],legend:[1,"
      ","
      "],thead:[1,"","
      "],tr:[2,"","
      "],td:[3,"","
      "],col:[2,"","
      "],area:[1,"",""],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X
      ","
      "]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1>");try{for(;d1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]===""&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("
      ").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); \ No newline at end of file diff --git a/_build/emqx/lib/cowboy/examples/websocket/relx.config b/_build/emqx/lib/cowboy/examples/websocket/relx.config deleted file mode 100644 index 227589b76f..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/relx.config +++ /dev/null @@ -1,2 +0,0 @@ -{release, {websocket_example, "1"}, [websocket]}. -{extended_start_script, true}. diff --git a/_build/emqx/lib/cowboy/examples/websocket/src/websocket_app.erl b/_build/emqx/lib/cowboy/examples/websocket/src/websocket_app.erl deleted file mode 100644 index babb39ea58..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/src/websocket_app.erl +++ /dev/null @@ -1,26 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(websocket_app). --behaviour(application). - -%% API. --export([start/2]). --export([stop/1]). - -%% API. -start(_Type, _Args) -> - Dispatch = cowboy_router:compile([ - {'_', [ - {"/", cowboy_static, {priv_file, websocket, "index.html"}}, - {"/websocket", ws_h, []}, - {"/static/[...]", cowboy_static, {priv_dir, websocket, "static"}} - ]} - ]), - {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{ - env => #{dispatch => Dispatch} - }), - websocket_sup:start_link(). - -stop(_State) -> - ok = cowboy:stop_listener(http). diff --git a/_build/emqx/lib/cowboy/examples/websocket/src/websocket_sup.erl b/_build/emqx/lib/cowboy/examples/websocket/src/websocket_sup.erl deleted file mode 100644 index 40ef8e0792..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/src/websocket_sup.erl +++ /dev/null @@ -1,23 +0,0 @@ -%% Feel free to use, reuse and abuse the code in this file. - -%% @private --module(websocket_sup). --behaviour(supervisor). - -%% API. --export([start_link/0]). - -%% supervisor. --export([init/1]). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%% supervisor. - -init([]) -> - Procs = [], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/examples/websocket/src/ws_h.erl b/_build/emqx/lib/cowboy/examples/websocket/src/ws_h.erl deleted file mode 100644 index ba2b844033..0000000000 --- a/_build/emqx/lib/cowboy/examples/websocket/src/ws_h.erl +++ /dev/null @@ -1,24 +0,0 @@ --module(ws_h). - --export([init/2]). --export([websocket_init/1]). --export([websocket_handle/2]). --export([websocket_info/2]). - -init(Req, Opts) -> - {cowboy_websocket, Req, Opts}. - -websocket_init(State) -> - erlang:start_timer(1000, self(), <<"Hello!">>), - {[], State}. - -websocket_handle({text, Msg}, State) -> - {[{text, << "That's what she said! ", Msg/binary >>}], State}; -websocket_handle(_Data, State) -> - {[], State}. - -websocket_info({timeout, _Ref, Msg}, State) -> - erlang:start_timer(1000, self(), <<"How' you doin'?">>), - {[{text, Msg}], State}; -websocket_info(_Info, State) -> - {[], State}. diff --git a/_build/emqx/lib/cowboy/plugins.mk b/_build/emqx/lib/cowboy/plugins.mk deleted file mode 100644 index 3fb2f7e88c..0000000000 --- a/_build/emqx/lib/cowboy/plugins.mk +++ /dev/null @@ -1,75 +0,0 @@ -# See LICENSE for licensing information. - -# Plain HTTP handlers. -define tpl_cowboy.http --module($(n)). --behavior(cowboy_handler). - --export([init/2]). - -init(Req, State) -> - {ok, Req, State}. -endef - -# Loop handlers. -define tpl_cowboy.loop --module($(n)). --behavior(cowboy_loop). - --export([init/2]). --export([info/3]). - -init(Req, State) -> - {cowboy_loop, Req, State, hibernate}. - -info(_Info, Req, State) -> - {ok, Req, State, hibernate}. -endef - -# REST handlers. -define tpl_cowboy.rest --module($(n)). --behavior(cowboy_rest). - --export([init/2]). --export([content_types_provided/2]). --export([to_html/2]). - -init(Req, State) -> - {cowboy_rest, Req, State}. - -content_types_provided(Req, State) -> - {[ - {{<<"text">>, <<"html">>, '*'}, to_html} - ], Req, State}. - -to_html(Req, State) -> - {<<"This is REST!">>, Req, State}. -endef - -# Websocket handlers. -define tpl_cowboy.ws --module($(n)). --behavior(cowboy_websocket). - --export([init/2]). --export([websocket_init/1]). --export([websocket_handle/2]). --export([websocket_info/2]). - -init(Req, State) -> - {cowboy_websocket, Req, State}. - -websocket_init(State) -> - {[], State}. - -websocket_handle({text, Data}, State) -> - {[{text, Data}], State}; -websocket_handle({binary, Data}, State) -> - {[{binary, Data}], State}; -websocket_handle(_Frame, State) -> - {[], State}. - -websocket_info(_Info, State) -> - {[], State}. -endef diff --git a/_build/emqx/lib/cowboy/rebar.config b/_build/emqx/lib/cowboy/rebar.config deleted file mode 100644 index aab2493793..0000000000 --- a/_build/emqx/lib/cowboy/rebar.config +++ /dev/null @@ -1,36 +0,0 @@ -{minimum_otp_vsn, "21.0"}. - -{deps, - [{ranch, {git, "https://hub.fastgit.org/ninenines/ranch", {tag, "1.7.1"}}}, - {cowlib, {git, "https://hub.fastgit.org/ninenines/cowlib", {tag, "2.8.0"}}} - ]}. - -{erl_opts, [warn_unused_vars, - warn_shadow_vars, - warn_unused_import, - warn_obsolete_guard, - warn_untyped_record, - debug_info - ]}. - -{xref_checks, [undefined_function_calls, undefined_functions, - locals_not_used, deprecated_function_calls, - warnings_as_errors, deprecated_functions - ]}. - -{cover_enabled, true}. -{cover_opts, [verbose]}. -{cover_export_enabled, true}. - -{ct_opts, [{ct_hooks, [cowboy_ct_hook]}]}. - -{profiles, - [{test, - [{deps, - [{proper, "1.3.0"}, % hex - {gun, {git, "https://hub.fastgit.org/ninenines/gun", {branch, "master"}}}, - {ct_helper, {git, "https://hub.fastgit.org/extend/ct_helper", {branch, "master"}}} - ]}, - {erl_opts, [{parse_transform, eunit_autoexport}]} - ]} - ]}. diff --git a/_build/emqx/lib/cowboy/src/cowboy.app.src b/_build/emqx/lib/cowboy/src/cowboy.app.src deleted file mode 100644 index 8aeee5b1c0..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy.app.src +++ /dev/null @@ -1,9 +0,0 @@ -{application, cowboy, - [{description, "Small, fast, modern HTTP server."}, - {vsn, "2.8.1"}, - {modules, []}, - {registered, [cowboy_sup,cowboy_clock]}, - {applications, [kernel,stdlib,crypto,cowlib,ranch]}, - {mod, {cowboy_app, []}}, - {env, []} - ]}. diff --git a/_build/emqx/lib/cowboy/src/cowboy.erl b/_build/emqx/lib/cowboy/src/cowboy.erl deleted file mode 100644 index c4be25bf9b..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy.erl +++ /dev/null @@ -1,105 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy). - --export([start_clear/3]). --export([start_tls/3]). --export([stop_listener/1]). --export([set_env/3]). - -%% Internal. --export([log/2]). --export([log/4]). - --type opts() :: cowboy_http:opts() | cowboy_http2:opts(). --export_type([opts/0]). - --type fields() :: [atom() - | {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()]} - | {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()], any()}]. --export_type([fields/0]). - --type http_headers() :: #{binary() => iodata()}. --export_type([http_headers/0]). - --type http_status() :: non_neg_integer() | binary(). --export_type([http_status/0]). - --type http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'. --export_type([http_version/0]). - --spec start_clear(ranch:ref(), ranch:opts(), opts()) - -> {ok, pid()} | {error, any()}. -start_clear(Ref, TransOpts0, ProtoOpts0) -> - TransOpts1 = ranch:normalize_opts(TransOpts0), - {TransOpts, ConnectionType} = ensure_connection_type(TransOpts1), - ProtoOpts = ProtoOpts0#{connection_type => ConnectionType}, - ranch:start_listener(Ref, ranch_tcp, TransOpts, cowboy_clear, ProtoOpts). - --spec start_tls(ranch:ref(), ranch:opts(), opts()) - -> {ok, pid()} | {error, any()}. -start_tls(Ref, TransOpts0, ProtoOpts0) -> - TransOpts1 = ranch:normalize_opts(TransOpts0), - SocketOpts = maps:get(socket_opts, TransOpts1, []), - TransOpts2 = TransOpts1#{socket_opts => [ - {next_protocols_advertised, [<<"h2">>, <<"http/1.1">>]}, - {alpn_preferred_protocols, [<<"h2">>, <<"http/1.1">>]} - |SocketOpts]}, - {TransOpts, ConnectionType} = ensure_connection_type(TransOpts2), - ProtoOpts = ProtoOpts0#{connection_type => ConnectionType}, - ranch:start_listener(Ref, ranch_ssl, TransOpts, cowboy_tls, ProtoOpts). - -ensure_connection_type(TransOpts=#{connection_type := ConnectionType}) -> - {TransOpts, ConnectionType}; -ensure_connection_type(TransOpts) -> - {TransOpts#{connection_type => supervisor}, supervisor}. - --spec stop_listener(ranch:ref()) -> ok | {error, not_found}. -stop_listener(Ref) -> - ranch:stop_listener(Ref). - --spec set_env(ranch:ref(), atom(), any()) -> ok. -set_env(Ref, Name, Value) -> - Opts = ranch:get_protocol_options(Ref), - Env = maps:get(env, Opts, #{}), - Opts2 = maps:put(env, maps:put(Name, Value, Env), Opts), - ok = ranch:set_protocol_options(Ref, Opts2). - -%% Internal. - --spec log({log, logger:level(), io:format(), list()}, opts()) -> ok. -log({log, Level, Format, Args}, Opts) -> - log(Level, Format, Args, Opts). - --spec log(logger:level(), io:format(), list(), opts()) -> ok. -log(Level, Format, Args, #{logger := Logger}) - when Logger =/= error_logger -> - _ = Logger:Level(Format, Args), - ok; -%% We use error_logger by default. Because error_logger does -%% not have all the levels we accept we have to do some -%% mapping to error_logger functions. -log(Level, Format, Args, _) -> - Function = case Level of - emergency -> error_msg; - alert -> error_msg; - critical -> error_msg; - error -> error_msg; - warning -> warning_msg; - notice -> warning_msg; - info -> info_msg; - debug -> info_msg - end, - error_logger:Function(Format, Args). diff --git a/_build/emqx/lib/cowboy/src/cowboy_app.erl b/_build/emqx/lib/cowboy/src/cowboy_app.erl deleted file mode 100644 index 74cba415fd..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_app.erl +++ /dev/null @@ -1,27 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_app). --behaviour(application). - --export([start/2]). --export([stop/1]). - --spec start(_, _) -> {ok, pid()}. -start(_, _) -> - cowboy_sup:start_link(). - --spec stop(_) -> ok. -stop(_) -> - ok. diff --git a/_build/emqx/lib/cowboy/src/cowboy_bstr.erl b/_build/emqx/lib/cowboy/src/cowboy_bstr.erl deleted file mode 100644 index d8041e49c8..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_bstr.erl +++ /dev/null @@ -1,123 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_bstr). - -%% Binary strings. --export([capitalize_token/1]). --export([to_lower/1]). --export([to_upper/1]). - -%% Characters. --export([char_to_lower/1]). --export([char_to_upper/1]). - -%% The first letter and all letters after a dash are capitalized. -%% This is the form seen for header names in the HTTP/1.1 RFC and -%% others. Note that using this form isn't required, as header names -%% are case insensitive, and it is only provided for use with eventual -%% badly implemented clients. --spec capitalize_token(B) -> B when B::binary(). -capitalize_token(B) -> - capitalize_token(B, true, <<>>). -capitalize_token(<<>>, _, Acc) -> - Acc; -capitalize_token(<< $-, Rest/bits >>, _, Acc) -> - capitalize_token(Rest, true, << Acc/binary, $- >>); -capitalize_token(<< C, Rest/bits >>, true, Acc) -> - capitalize_token(Rest, false, << Acc/binary, (char_to_upper(C)) >>); -capitalize_token(<< C, Rest/bits >>, false, Acc) -> - capitalize_token(Rest, false, << Acc/binary, (char_to_lower(C)) >>). - --spec to_lower(B) -> B when B::binary(). -to_lower(B) -> - << << (char_to_lower(C)) >> || << C >> <= B >>. - --spec to_upper(B) -> B when B::binary(). -to_upper(B) -> - << << (char_to_upper(C)) >> || << C >> <= B >>. - --spec char_to_lower(char()) -> char(). -char_to_lower($A) -> $a; -char_to_lower($B) -> $b; -char_to_lower($C) -> $c; -char_to_lower($D) -> $d; -char_to_lower($E) -> $e; -char_to_lower($F) -> $f; -char_to_lower($G) -> $g; -char_to_lower($H) -> $h; -char_to_lower($I) -> $i; -char_to_lower($J) -> $j; -char_to_lower($K) -> $k; -char_to_lower($L) -> $l; -char_to_lower($M) -> $m; -char_to_lower($N) -> $n; -char_to_lower($O) -> $o; -char_to_lower($P) -> $p; -char_to_lower($Q) -> $q; -char_to_lower($R) -> $r; -char_to_lower($S) -> $s; -char_to_lower($T) -> $t; -char_to_lower($U) -> $u; -char_to_lower($V) -> $v; -char_to_lower($W) -> $w; -char_to_lower($X) -> $x; -char_to_lower($Y) -> $y; -char_to_lower($Z) -> $z; -char_to_lower(Ch) -> Ch. - --spec char_to_upper(char()) -> char(). -char_to_upper($a) -> $A; -char_to_upper($b) -> $B; -char_to_upper($c) -> $C; -char_to_upper($d) -> $D; -char_to_upper($e) -> $E; -char_to_upper($f) -> $F; -char_to_upper($g) -> $G; -char_to_upper($h) -> $H; -char_to_upper($i) -> $I; -char_to_upper($j) -> $J; -char_to_upper($k) -> $K; -char_to_upper($l) -> $L; -char_to_upper($m) -> $M; -char_to_upper($n) -> $N; -char_to_upper($o) -> $O; -char_to_upper($p) -> $P; -char_to_upper($q) -> $Q; -char_to_upper($r) -> $R; -char_to_upper($s) -> $S; -char_to_upper($t) -> $T; -char_to_upper($u) -> $U; -char_to_upper($v) -> $V; -char_to_upper($w) -> $W; -char_to_upper($x) -> $X; -char_to_upper($y) -> $Y; -char_to_upper($z) -> $Z; -char_to_upper(Ch) -> Ch. - -%% Tests. - --ifdef(TEST). -capitalize_token_test_() -> - Tests = [ - {<<"heLLo-woRld">>, <<"Hello-World">>}, - {<<"Sec-Websocket-Version">>, <<"Sec-Websocket-Version">>}, - {<<"Sec-WebSocket-Version">>, <<"Sec-Websocket-Version">>}, - {<<"sec-websocket-version">>, <<"Sec-Websocket-Version">>}, - {<<"SEC-WEBSOCKET-VERSION">>, <<"Sec-Websocket-Version">>}, - {<<"Sec-WebSocket--Version">>, <<"Sec-Websocket--Version">>}, - {<<"Sec-WebSocket---Version">>, <<"Sec-Websocket---Version">>} - ], - [{H, fun() -> R = capitalize_token(H) end} || {H, R} <- Tests]. --endif. diff --git a/_build/emqx/lib/cowboy/src/cowboy_children.erl b/_build/emqx/lib/cowboy/src/cowboy_children.erl deleted file mode 100644 index 05d39fb86a..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_children.erl +++ /dev/null @@ -1,192 +0,0 @@ -%% Copyright (c) 2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_children). - --export([init/0]). --export([up/4]). --export([down/2]). --export([shutdown/2]). --export([shutdown_timeout/3]). --export([terminate/1]). --export([handle_supervisor_call/4]). - --record(child, { - pid :: pid(), - streamid :: cowboy_stream:streamid() | undefined, - shutdown :: timeout(), - timer = undefined :: undefined | reference() -}). - --type children() :: [#child{}]. --export_type([children/0]). - --spec init() -> []. -init() -> - []. - --spec up(Children, pid(), cowboy_stream:streamid(), timeout()) - -> Children when Children::children(). -up(Children, Pid, StreamID, Shutdown) -> - [#child{ - pid=Pid, - streamid=StreamID, - shutdown=Shutdown - }|Children]. - --spec down(Children, pid()) - -> {ok, cowboy_stream:streamid() | undefined, Children} | error - when Children::children(). -down(Children0, Pid) -> - case lists:keytake(Pid, #child.pid, Children0) of - {value, #child{streamid=StreamID, timer=Ref}, Children} -> - _ = case Ref of - undefined -> ok; - _ -> erlang:cancel_timer(Ref, [{async, true}, {info, false}]) - end, - {ok, StreamID, Children}; - false -> - error - end. - -%% We ask the processes to shutdown first. This gives -%% a chance to processes that are trapping exits to -%% shut down gracefully. Others will exit immediately. -%% -%% @todo We currently fire one timer per process being -%% shut down. This is probably not the most efficient. -%% A more efficient solution could be to maintain a -%% single timer and decrease the shutdown time of all -%% processes when it fires. This is however much more -%% complex, and there aren't that many processes that -%% will need to be shutdown through this function, so -%% this is left for later. --spec shutdown(Children, cowboy_stream:streamid()) - -> Children when Children::children(). -shutdown(Children0, StreamID) -> - [ - case Child of - #child{pid=Pid, streamid=StreamID, shutdown=Shutdown} -> - exit(Pid, shutdown), - Ref = erlang:start_timer(Shutdown, self(), {shutdown, Pid}), - Child#child{streamid=undefined, timer=Ref}; - _ -> - Child - end - || Child <- Children0]. - --spec shutdown_timeout(children(), reference(), pid()) -> ok. -shutdown_timeout(Children, Ref, Pid) -> - case lists:keyfind(Pid, #child.pid, Children) of - #child{timer=Ref} -> - exit(Pid, kill), - ok; - _ -> - ok - end. - --spec terminate(children()) -> ok. -terminate(Children) -> - %% For each child, either ask for it to shut down, - %% or cancel its shutdown timer if it already is. - %% - %% We do not need to flush stray timeout messages out because - %% we are either terminating or switching protocols, - %% and in the latter case we flush all messages. - _ = [case TRef of - undefined -> exit(Pid, shutdown); - _ -> erlang:cancel_timer(TRef, [{async, true}, {info, false}]) - end || #child{pid=Pid, timer=TRef} <- Children], - before_terminate_loop(Children). - -before_terminate_loop([]) -> - ok; -before_terminate_loop(Children) -> - %% Find the longest shutdown time. - Time = longest_shutdown_time(Children, 0), - %% We delay the creation of the timer if one of the - %% processes has an infinity shutdown value. - TRef = case Time of - infinity -> undefined; - _ -> erlang:start_timer(Time, self(), terminate) - end, - %% Loop until that time or until all children are dead. - terminate_loop(Children, TRef). - -terminate_loop([], TRef) -> - %% Don't forget to cancel the timer, if any! - case TRef of - undefined -> - ok; - _ -> - _ = erlang:cancel_timer(TRef, [{async, true}, {info, false}]), - ok - end; -terminate_loop(Children, TRef) -> - receive - {'EXIT', Pid, _} when TRef =:= undefined -> - {value, #child{shutdown=Shutdown}, Children1} - = lists:keytake(Pid, #child.pid, Children), - %% We delayed the creation of the timer. If a process with - %% infinity shutdown just ended, we might have to start that timer. - case Shutdown of - infinity -> before_terminate_loop(Children1); - _ -> terminate_loop(Children1, TRef) - end; - {'EXIT', Pid, _} -> - terminate_loop(lists:keydelete(Pid, #child.pid, Children), TRef); - {timeout, TRef, terminate} -> - %% Brutally kill any remaining children. - _ = [exit(Pid, kill) || #child{pid=Pid} <- Children], - ok - end. - -longest_shutdown_time([], Time) -> - Time; -longest_shutdown_time([#child{shutdown=ChildTime}|Tail], Time) when ChildTime > Time -> - longest_shutdown_time(Tail, ChildTime); -longest_shutdown_time([_|Tail], Time) -> - longest_shutdown_time(Tail, Time). - --spec handle_supervisor_call(any(), {pid(), any()}, children(), module()) -> ok. -handle_supervisor_call(which_children, {From, Tag}, Children, Module) -> - From ! {Tag, which_children(Children, Module)}, - ok; -handle_supervisor_call(count_children, {From, Tag}, Children, _) -> - From ! {Tag, count_children(Children)}, - ok; -%% We disable start_child since only incoming requests -%% end up creating a new process. -handle_supervisor_call({start_child, _}, {From, Tag}, _, _) -> - From ! {Tag, {error, start_child_disabled}}, - ok; -%% All other calls refer to children. We act in a similar way -%% to a simple_one_for_one so we never find those. -handle_supervisor_call(_, {From, Tag}, _, _) -> - From ! {Tag, {error, not_found}}, - ok. - --spec which_children(children(), module()) -> [{module(), pid(), worker, [module()]}]. -which_children(Children, Module) -> - [{Module, Pid, worker, [Module]} || #child{pid=Pid} <- Children]. - --spec count_children(children()) -> [{atom(), non_neg_integer()}]. -count_children(Children) -> - Count = length(Children), - [ - {specs, 1}, - {active, Count}, - {supervisors, 0}, - {workers, Count} - ]. diff --git a/_build/emqx/lib/cowboy/src/cowboy_clear.erl b/_build/emqx/lib/cowboy/src/cowboy_clear.erl deleted file mode 100644 index 0af734f9de..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_clear.erl +++ /dev/null @@ -1,51 +0,0 @@ -%% Copyright (c) 2016-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_clear). --behavior(ranch_protocol). - --export([start_link/3]). --export([start_link/4]). --export([connection_process/4]). - -%% Ranch 1. --spec start_link(ranch:ref(), inet:socket(), module(), cowboy:opts()) -> {ok, pid()}. -start_link(Ref, _Socket, Transport, Opts) -> - start_link(Ref, Transport, Opts). - -%% Ranch 2. --spec start_link(ranch:ref(), module(), cowboy:opts()) -> {ok, pid()}. -start_link(Ref, Transport, Opts) -> - Pid = proc_lib:spawn_link(?MODULE, connection_process, - [self(), Ref, Transport, Opts]), - {ok, Pid}. - --spec connection_process(pid(), ranch:ref(), module(), cowboy:opts()) -> ok. -connection_process(Parent, Ref, Transport, Opts) -> - ProxyInfo = case maps:get(proxy_header, Opts, false) of - true -> - {ok, ProxyInfo0} = ranch:recv_proxy_header(Ref, 1000), - ProxyInfo0; - false -> - undefined - end, - {ok, Socket} = ranch:handshake(Ref), - init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, cowboy_http). - -init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol) -> - _ = case maps:get(connection_type, Opts, supervisor) of - worker -> ok; - supervisor -> process_flag(trap_exit, true) - end, - Protocol:init(Parent, Ref, Socket, Transport, ProxyInfo, Opts). diff --git a/_build/emqx/lib/cowboy/src/cowboy_clock.erl b/_build/emqx/lib/cowboy/src/cowboy_clock.erl deleted file mode 100644 index 28f8a1b2b7..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_clock.erl +++ /dev/null @@ -1,221 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -%% While a gen_server process runs in the background to update -%% the cache of formatted dates every second, all API calls are -%% local and directly read from the ETS cache table, providing -%% fast time and date computations. --module(cowboy_clock). --behaviour(gen_server). - -%% API. --export([start_link/0]). --export([stop/0]). --export([rfc1123/0]). --export([rfc1123/1]). - -%% gen_server. --export([init/1]). --export([handle_call/3]). --export([handle_cast/2]). --export([handle_info/2]). --export([terminate/2]). --export([code_change/3]). - --record(state, { - universaltime = undefined :: undefined | calendar:datetime(), - rfc1123 = <<>> :: binary(), - tref = undefined :: undefined | reference() -}). - -%% API. - --spec start_link() -> {ok, pid()}. -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - --spec stop() -> stopped. -stop() -> - gen_server:call(?MODULE, stop). - -%% When the ets table doesn't exist, either because of a bug -%% or because Cowboy is being restarted, we perform in a -%% slightly degraded state and build a new timestamp for -%% every request. --spec rfc1123() -> binary(). -rfc1123() -> - try - ets:lookup_element(?MODULE, rfc1123, 2) - catch error:badarg -> - rfc1123(erlang:universaltime()) - end. - --spec rfc1123(calendar:datetime()) -> binary(). -rfc1123(DateTime) -> - update_rfc1123(<<>>, undefined, DateTime). - -%% gen_server. - --spec init([]) -> {ok, #state{}}. -init([]) -> - ?MODULE = ets:new(?MODULE, [set, protected, - named_table, {read_concurrency, true}]), - T = erlang:universaltime(), - B = update_rfc1123(<<>>, undefined, T), - TRef = erlang:send_after(1000, self(), update), - ets:insert(?MODULE, {rfc1123, B}), - {ok, #state{universaltime=T, rfc1123=B, tref=TRef}}. - --type from() :: {pid(), term()}. --spec handle_call - (stop, from(), State) -> {stop, normal, stopped, State} - when State::#state{}. -handle_call(stop, _From, State) -> - {stop, normal, stopped, State}; -handle_call(_Request, _From, State) -> - {reply, ignored, State}. - --spec handle_cast(_, State) -> {noreply, State} when State::#state{}. -handle_cast(_Msg, State) -> - {noreply, State}. - --spec handle_info(any(), State) -> {noreply, State} when State::#state{}. -handle_info(update, #state{universaltime=Prev, rfc1123=B1, tref=TRef0}) -> - %% Cancel the timer in case an external process sent an update message. - _ = erlang:cancel_timer(TRef0), - T = erlang:universaltime(), - B2 = update_rfc1123(B1, Prev, T), - ets:insert(?MODULE, {rfc1123, B2}), - TRef = erlang:send_after(1000, self(), update), - {noreply, #state{universaltime=T, rfc1123=B2, tref=TRef}}; -handle_info(_Info, State) -> - {noreply, State}. - --spec terminate(_, _) -> ok. -terminate(_Reason, _State) -> - ok. - --spec code_change(_, State, _) -> {ok, State} when State::#state{}. -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%% Internal. - --spec update_rfc1123(binary(), undefined | calendar:datetime(), - calendar:datetime()) -> binary(). -update_rfc1123(Bin, Now, Now) -> - Bin; -update_rfc1123(<< Keep:23/binary, _/bits >>, - {Date, {H, M, _}}, {Date, {H, M, S}}) -> - << Keep/binary, (pad_int(S))/binary, " GMT" >>; -update_rfc1123(<< Keep:20/binary, _/bits >>, - {Date, {H, _, _}}, {Date, {H, M, S}}) -> - << Keep/binary, (pad_int(M))/binary, $:, (pad_int(S))/binary, " GMT" >>; -update_rfc1123(<< Keep:17/binary, _/bits >>, {Date, _}, {Date, {H, M, S}}) -> - << Keep/binary, (pad_int(H))/binary, $:, (pad_int(M))/binary, - $:, (pad_int(S))/binary, " GMT" >>; -update_rfc1123(<< _:7/binary, Keep:10/binary, _/bits >>, - {{Y, Mo, _}, _}, {Date = {Y, Mo, D}, {H, M, S}}) -> - Wday = calendar:day_of_the_week(Date), - << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, Keep/binary, - (pad_int(H))/binary, $:, (pad_int(M))/binary, - $:, (pad_int(S))/binary, " GMT" >>; -update_rfc1123(<< _:11/binary, Keep:6/binary, _/bits >>, - {{Y, _, _}, _}, {Date = {Y, Mo, D}, {H, M, S}}) -> - Wday = calendar:day_of_the_week(Date), - << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, " ", - (month(Mo))/binary, Keep/binary, - (pad_int(H))/binary, $:, (pad_int(M))/binary, - $:, (pad_int(S))/binary, " GMT" >>; -update_rfc1123(_, _, {Date = {Y, Mo, D}, {H, M, S}}) -> - Wday = calendar:day_of_the_week(Date), - << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, " ", - (month(Mo))/binary, " ", (integer_to_binary(Y))/binary, - " ", (pad_int(H))/binary, $:, (pad_int(M))/binary, - $:, (pad_int(S))/binary, " GMT" >>. - -%% Following suggestion by MononcQc on #erlounge. --spec pad_int(0..59) -> binary(). -pad_int(X) when X < 10 -> - << $0, ($0 + X) >>; -pad_int(X) -> - integer_to_binary(X). - --spec weekday(1..7) -> <<_:24>>. -weekday(1) -> <<"Mon">>; -weekday(2) -> <<"Tue">>; -weekday(3) -> <<"Wed">>; -weekday(4) -> <<"Thu">>; -weekday(5) -> <<"Fri">>; -weekday(6) -> <<"Sat">>; -weekday(7) -> <<"Sun">>. - --spec month(1..12) -> <<_:24>>. -month( 1) -> <<"Jan">>; -month( 2) -> <<"Feb">>; -month( 3) -> <<"Mar">>; -month( 4) -> <<"Apr">>; -month( 5) -> <<"May">>; -month( 6) -> <<"Jun">>; -month( 7) -> <<"Jul">>; -month( 8) -> <<"Aug">>; -month( 9) -> <<"Sep">>; -month(10) -> <<"Oct">>; -month(11) -> <<"Nov">>; -month(12) -> <<"Dec">>. - -%% Tests. - --ifdef(TEST). -update_rfc1123_test_() -> - Tests = [ - {<<"Sat, 14 May 2011 14:25:33 GMT">>, undefined, - {{2011, 5, 14}, {14, 25, 33}}, <<>>}, - {<<"Sat, 14 May 2011 14:25:33 GMT">>, {{2011, 5, 14}, {14, 25, 33}}, - {{2011, 5, 14}, {14, 25, 33}}, <<"Sat, 14 May 2011 14:25:33 GMT">>}, - {<<"Sat, 14 May 2011 14:25:34 GMT">>, {{2011, 5, 14}, {14, 25, 33}}, - {{2011, 5, 14}, {14, 25, 34}}, <<"Sat, 14 May 2011 14:25:33 GMT">>}, - {<<"Sat, 14 May 2011 14:26:00 GMT">>, {{2011, 5, 14}, {14, 25, 59}}, - {{2011, 5, 14}, {14, 26, 0}}, <<"Sat, 14 May 2011 14:25:59 GMT">>}, - {<<"Sat, 14 May 2011 15:00:00 GMT">>, {{2011, 5, 14}, {14, 59, 59}}, - {{2011, 5, 14}, {15, 0, 0}}, <<"Sat, 14 May 2011 14:59:59 GMT">>}, - {<<"Sun, 15 May 2011 00:00:00 GMT">>, {{2011, 5, 14}, {23, 59, 59}}, - {{2011, 5, 15}, { 0, 0, 0}}, <<"Sat, 14 May 2011 23:59:59 GMT">>}, - {<<"Wed, 01 Jun 2011 00:00:00 GMT">>, {{2011, 5, 31}, {23, 59, 59}}, - {{2011, 6, 1}, { 0, 0, 0}}, <<"Tue, 31 May 2011 23:59:59 GMT">>}, - {<<"Sun, 01 Jan 2012 00:00:00 GMT">>, {{2011, 5, 31}, {23, 59, 59}}, - {{2012, 1, 1}, { 0, 0, 0}}, <<"Sat, 31 Dec 2011 23:59:59 GMT">>} - ], - [{R, fun() -> R = update_rfc1123(B, P, N) end} || {R, P, N, B} <- Tests]. - -pad_int_test_() -> - Tests = [ - { 0, <<"00">>}, { 1, <<"01">>}, { 2, <<"02">>}, { 3, <<"03">>}, - { 4, <<"04">>}, { 5, <<"05">>}, { 6, <<"06">>}, { 7, <<"07">>}, - { 8, <<"08">>}, { 9, <<"09">>}, {10, <<"10">>}, {11, <<"11">>}, - {12, <<"12">>}, {13, <<"13">>}, {14, <<"14">>}, {15, <<"15">>}, - {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">>}, {30, <<"30">>}, {31, <<"31">>}, - {32, <<"32">>}, {33, <<"33">>}, {34, <<"34">>}, {35, <<"35">>}, - {36, <<"36">>}, {37, <<"37">>}, {38, <<"38">>}, {39, <<"39">>}, - {40, <<"40">>}, {41, <<"41">>}, {42, <<"42">>}, {43, <<"43">>}, - {44, <<"44">>}, {45, <<"45">>}, {46, <<"46">>}, {47, <<"47">>}, - {48, <<"48">>}, {49, <<"49">>}, {50, <<"50">>}, {51, <<"51">>}, - {52, <<"52">>}, {53, <<"53">>}, {54, <<"54">>}, {55, <<"55">>}, - {56, <<"56">>}, {57, <<"57">>}, {58, <<"58">>}, {59, <<"59">>} - ], - [{I, fun() -> O = pad_int(I) end} || {I, O} <- Tests]. --endif. diff --git a/_build/emqx/lib/cowboy/src/cowboy_compress_h.erl b/_build/emqx/lib/cowboy/src/cowboy_compress_h.erl deleted file mode 100644 index e9824ba178..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_compress_h.erl +++ /dev/null @@ -1,245 +0,0 @@ -%% Copyright (c) 2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_compress_h). --behavior(cowboy_stream). - --export([init/3]). --export([data/4]). --export([info/3]). --export([terminate/3]). --export([early_error/5]). - --record(state, { - next :: any(), - threshold :: non_neg_integer() | undefined, - compress = undefined :: undefined | gzip, - deflate = undefined :: undefined | zlib:zstream(), - deflate_flush = sync :: none | sync -}). - --spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) - -> {cowboy_stream:commands(), #state{}}. -init(StreamID, Req, Opts) -> - State0 = check_req(Req), - CompressThreshold = maps:get(compress_threshold, Opts, 300), - DeflateFlush = buffering_to_zflush(maps:get(compress_buffering, Opts, false)), - {Commands0, Next} = cowboy_stream:init(StreamID, Req, Opts), - fold(Commands0, State0#state{next=Next, - threshold=CompressThreshold, - deflate_flush=DeflateFlush}). - --spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State) - -> {cowboy_stream:commands(), State} when State::#state{}. -data(StreamID, IsFin, Data, State0=#state{next=Next0}) -> - {Commands0, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0), - fold(Commands0, State0#state{next=Next}). - --spec info(cowboy_stream:streamid(), any(), State) - -> {cowboy_stream:commands(), State} when State::#state{}. -info(StreamID, Info, State0=#state{next=Next0}) -> - {Commands0, Next} = cowboy_stream:info(StreamID, Info, Next0), - fold(Commands0, State0#state{next=Next}). - --spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> any(). -terminate(StreamID, Reason, #state{next=Next, deflate=Z}) -> - %% Clean the zlib:stream() in case something went wrong. - %% In the normal scenario the stream is already closed. - case Z of - undefined -> ok; - _ -> zlib:close(Z) - end, - cowboy_stream:terminate(StreamID, Reason, Next). - --spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(), - cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp - when Resp::cowboy_stream:resp_command(). -early_error(StreamID, Reason, PartialReq, Resp, Opts) -> - cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts). - -%% Internal. - -%% Check if the client supports decoding of gzip responses. -check_req(Req) -> - %% @todo Probably shouldn't unconditionally crash on failure. - case cowboy_req:parse_header(<<"accept-encoding">>, Req) of - %% Client doesn't support any compression algorithm. - undefined -> - #state{compress=undefined}; - Encodings -> - %% We only support gzip so look for it specifically. - %% @todo A recipient SHOULD consider "x-gzip" to be - %% equivalent to "gzip". (RFC7230 4.2.3) - case [E || E={<<"gzip">>, Q} <- Encodings, Q =/= 0] of - [] -> - #state{compress=undefined}; - _ -> - #state{compress=gzip} - end - end. - -%% Do not compress responses that contain the content-encoding header. -check_resp_headers(#{<<"content-encoding">> := _}, State) -> - State#state{compress=undefined}; -check_resp_headers(_, State) -> - State. - -fold(Commands, State=#state{compress=undefined}) -> - {Commands, State}; -fold(Commands, State) -> - fold(Commands, State, []). - -fold([], State, Acc) -> - {lists:reverse(Acc), State}; -%% We do not compress full sendfile bodies. -fold([Response={response, _, _, {sendfile, _, _, _}}|Tail], State, Acc) -> - fold(Tail, State, [Response|Acc]); -%% We compress full responses directly, unless they are lower than -%% the configured threshold or we find we are not able to by looking at the headers. -fold([Response0={response, _, Headers, Body}|Tail], - State0=#state{threshold=CompressThreshold}, Acc) -> - case check_resp_headers(Headers, State0) of - State=#state{compress=undefined} -> - fold(Tail, State, [Response0|Acc]); - State1 -> - BodyLength = iolist_size(Body), - if - BodyLength =< CompressThreshold -> - fold(Tail, State1, [Response0|Acc]); - true -> - {Response, State} = gzip_response(Response0, State1), - fold(Tail, State, [Response|Acc]) - end - end; -%% Check headers and initiate compression... -fold([Response0={headers, _, Headers}|Tail], State0, Acc) -> - case check_resp_headers(Headers, State0) of - State=#state{compress=undefined} -> - fold(Tail, State, [Response0|Acc]); - State1 -> - {Response, State} = gzip_headers(Response0, State1), - fold(Tail, State, [Response|Acc]) - end; -%% then compress each data commands individually. -fold([Data0={data, _, _}|Tail], State0=#state{compress=gzip}, Acc) -> - {Data, State} = gzip_data(Data0, State0), - fold(Tail, State, [Data|Acc]); -%% When trailers are sent we need to end the compression. -%% This results in an extra data command being sent. -fold([Trailers={trailers, _}|Tail], State0=#state{compress=gzip}, Acc) -> - {{data, fin, Data}, State} = gzip_data({data, fin, <<>>}, State0), - fold(Tail, State, [Trailers, {data, nofin, Data}|Acc]); -%% All the options from this handler can be updated for the current stream. -%% The set_options command must be propagated as-is regardless. -fold([SetOptions={set_options, Opts}|Tail], State=#state{ - threshold=CompressThreshold0, deflate_flush=DeflateFlush0}, Acc) -> - CompressThreshold = maps:get(compress_threshold, Opts, CompressThreshold0), - DeflateFlush = case Opts of - #{compress_buffering := CompressBuffering} -> - buffering_to_zflush(CompressBuffering); - _ -> - DeflateFlush0 - end, - fold(Tail, State#state{threshold=CompressThreshold, deflate_flush=DeflateFlush}, - [SetOptions|Acc]); -%% Otherwise, we have an unrelated command or compression is disabled. -fold([Command|Tail], State, Acc) -> - fold(Tail, State, [Command|Acc]). - -buffering_to_zflush(true) -> none; -buffering_to_zflush(false) -> sync. - -gzip_response({response, Status, Headers, Body}, State) -> - %% We can't call zlib:gzip/1 because it does an - %% iolist_to_binary(GzBody) at the end to return - %% a binary(). Therefore the code here is largely - %% a duplicate of the code of that function. - Z = zlib:open(), - GzBody = try - %% 31 = 16+?MAX_WBITS from zlib.erl - %% @todo It might be good to allow them to be configured? - zlib:deflateInit(Z, default, deflated, 31, 8, default), - Gz = zlib:deflate(Z, Body, finish), - zlib:deflateEnd(Z), - Gz - after - zlib:close(Z) - end, - {{response, Status, vary(Headers#{ - <<"content-length">> => integer_to_binary(iolist_size(GzBody)), - <<"content-encoding">> => <<"gzip">> - }), GzBody}, State}. - -gzip_headers({headers, Status, Headers0}, State) -> - Z = zlib:open(), - %% We use the same arguments as when compressing the body fully. - %% @todo It might be good to allow them to be configured? - zlib:deflateInit(Z, default, deflated, 31, 8, default), - Headers = maps:remove(<<"content-length">>, Headers0), - {{headers, Status, vary(Headers#{ - <<"content-encoding">> => <<"gzip">> - })}, State#state{deflate=Z}}. - -%% We must add content-encoding to vary if it's not already there. -vary(Headers=#{<<"vary">> := Vary}) -> - try cow_http_hd:parse_vary(iolist_to_binary(Vary)) of - '*' -> Headers; - List -> - case lists:member(<<"accept-encoding">>, List) of - true -> Headers; - false -> Headers#{<<"vary">> => [Vary, <<", accept-encoding">>]} - end - catch _:_ -> - %% The vary header is invalid. Probably empty. We replace it with ours. - Headers#{<<"vary">> => <<"accept-encoding">>} - end; -vary(Headers) -> - Headers#{<<"vary">> => <<"accept-encoding">>}. - -%% It is not possible to combine zlib and the sendfile -%% syscall as far as I can tell, because the zlib format -%% includes a checksum at the end of the stream. We have -%% to read the file in memory, making this not suitable for -%% large files. -gzip_data({data, nofin, Sendfile={sendfile, _, _, _}}, - State=#state{deflate=Z, deflate_flush=Flush}) -> - {ok, Data0} = read_file(Sendfile), - Data = zlib:deflate(Z, Data0, Flush), - {{data, nofin, Data}, State}; -gzip_data({data, fin, Sendfile={sendfile, _, _, _}}, State=#state{deflate=Z}) -> - {ok, Data0} = read_file(Sendfile), - Data = zlib:deflate(Z, Data0, finish), - zlib:deflateEnd(Z), - zlib:close(Z), - {{data, fin, Data}, State#state{deflate=undefined}}; -gzip_data({data, nofin, Data0}, State=#state{deflate=Z, deflate_flush=Flush}) -> - Data = zlib:deflate(Z, Data0, Flush), - {{data, nofin, Data}, State}; -gzip_data({data, fin, Data0}, State=#state{deflate=Z}) -> - Data = zlib:deflate(Z, Data0, finish), - zlib:deflateEnd(Z), - zlib:close(Z), - {{data, fin, Data}, State#state{deflate=undefined}}. - -read_file({sendfile, Offset, Bytes, Path}) -> - {ok, IoDevice} = file:open(Path, [read, raw, binary]), - try - _ = case Offset of - 0 -> ok; - _ -> file:position(IoDevice, {bof, Offset}) - end, - file:read(IoDevice, Bytes) - after - file:close(IoDevice) - end. diff --git a/_build/emqx/lib/cowboy/src/cowboy_constraints.erl b/_build/emqx/lib/cowboy/src/cowboy_constraints.erl deleted file mode 100644 index 6509c4b233..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_constraints.erl +++ /dev/null @@ -1,174 +0,0 @@ -%% Copyright (c) 2014-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_constraints). - --export([validate/2]). --export([reverse/2]). --export([format_error/1]). - --type constraint() :: int | nonempty | fun(). --export_type([constraint/0]). - --type reason() :: {constraint(), any(), any()}. --export_type([reason/0]). - --spec validate(binary(), constraint() | [constraint()]) - -> {ok, any()} | {error, reason()}. -validate(Value, Constraints) when is_list(Constraints) -> - apply_list(forward, Value, Constraints); -validate(Value, Constraint) -> - apply_list(forward, Value, [Constraint]). - --spec reverse(any(), constraint() | [constraint()]) - -> {ok, binary()} | {error, reason()}. -reverse(Value, Constraints) when is_list(Constraints) -> - apply_list(reverse, Value, Constraints); -reverse(Value, Constraint) -> - apply_list(reverse, Value, [Constraint]). - --spec format_error(reason()) -> iodata(). -format_error({Constraint, Reason, Value}) -> - apply_constraint(format_error, {Reason, Value}, Constraint). - -apply_list(_, Value, []) -> - {ok, Value}; -apply_list(Type, Value0, [Constraint|Tail]) -> - case apply_constraint(Type, Value0, Constraint) of - {ok, Value} -> - apply_list(Type, Value, Tail); - {error, Reason} -> - {error, {Constraint, Reason, Value0}} - end. - -%% @todo {int, From, To}, etc. -apply_constraint(Type, Value, int) -> - int(Type, Value); -apply_constraint(Type, Value, nonempty) -> - nonempty(Type, Value); -apply_constraint(Type, Value, F) when is_function(F) -> - F(Type, Value). - -%% Constraint functions. - -int(forward, Value) -> - try - {ok, binary_to_integer(Value)} - catch _:_ -> - {error, not_an_integer} - end; -int(reverse, Value) -> - try - {ok, integer_to_binary(Value)} - catch _:_ -> - {error, not_an_integer} - end; -int(format_error, {not_an_integer, Value}) -> - io_lib:format("The value ~p is not an integer.", [Value]). - -nonempty(Type, <<>>) when Type =/= format_error -> - {error, empty}; -nonempty(Type, Value) when Type =/= format_error, is_binary(Value) -> - {ok, Value}; -nonempty(format_error, {empty, Value}) -> - io_lib:format("The value ~p is empty.", [Value]). - --ifdef(TEST). - -validate_test() -> - F = fun(_, Value) -> - try - {ok, binary_to_atom(Value, latin1)} - catch _:_ -> - {error, not_a_binary} - end - end, - %% Value, Constraints, Result. - Tests = [ - {<<>>, [], <<>>}, - {<<"123">>, int, 123}, - {<<"123">>, [int], 123}, - {<<"123">>, [nonempty, int], 123}, - {<<"123">>, [int, nonempty], 123}, - {<<>>, nonempty, error}, - {<<>>, [nonempty], error}, - {<<"hello">>, F, hello}, - {<<"hello">>, [F], hello}, - {<<"123">>, [F, int], error}, - {<<"123">>, [int, F], error}, - {<<"hello">>, [nonempty, F], hello}, - {<<"hello">>, [F, nonempty], hello} - ], - [{lists:flatten(io_lib:format("~p, ~p", [V, C])), fun() -> - case R of - error -> {error, _} = validate(V, C); - _ -> {ok, R} = validate(V, C) - end - end} || {V, C, R} <- Tests]. - -reverse_test() -> - F = fun(_, Value) -> - try - {ok, atom_to_binary(Value, latin1)} - catch _:_ -> - {error, not_an_atom} - end - end, - %% Value, Constraints, Result. - Tests = [ - {<<>>, [], <<>>}, - {123, int, <<"123">>}, - {123, [int], <<"123">>}, - {123, [nonempty, int], <<"123">>}, - {123, [int, nonempty], <<"123">>}, - {<<>>, nonempty, error}, - {<<>>, [nonempty], error}, - {hello, F, <<"hello">>}, - {hello, [F], <<"hello">>}, - {123, [F, int], error}, - {123, [int, F], error}, - {hello, [nonempty, F], <<"hello">>}, - {hello, [F, nonempty], <<"hello">>} - ], - [{lists:flatten(io_lib:format("~p, ~p", [V, C])), fun() -> - case R of - error -> {error, _} = reverse(V, C); - _ -> {ok, R} = reverse(V, C) - end - end} || {V, C, R} <- Tests]. - -int_format_error_test() -> - {error, Reason} = validate(<<"string">>, int), - Bin = iolist_to_binary(format_error(Reason)), - true = is_binary(Bin), - ok. - -nonempty_format_error_test() -> - {error, Reason} = validate(<<>>, nonempty), - Bin = iolist_to_binary(format_error(Reason)), - true = is_binary(Bin), - ok. - -fun_format_error_test() -> - F = fun - (format_error, {test, <<"value">>}) -> - formatted; - (_, _) -> - {error, test} - end, - {error, Reason} = validate(<<"value">>, F), - formatted = format_error(Reason), - ok. - --endif. diff --git a/_build/emqx/lib/cowboy/src/cowboy_handler.erl b/_build/emqx/lib/cowboy/src/cowboy_handler.erl deleted file mode 100644 index bf42b77dc2..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_handler.erl +++ /dev/null @@ -1,62 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -%% Handler middleware. -%% -%% Execute the handler given by the handler and handler_opts -%% environment values. The result of this execution is added to the -%% environment under the result value. --module(cowboy_handler). --behaviour(cowboy_middleware). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([execute/2]). --export([terminate/4]). - --callback init(Req, any()) - -> {ok | module(), Req, any()} - | {module(), Req, any(), any()} - when Req::cowboy_req:req(). - --callback terminate(any(), map(), any()) -> ok. --optional_callbacks([terminate/3]). - --spec execute(Req, Env) -> {ok, Req, Env} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -execute(Req, Env=#{handler := Handler, handler_opts := HandlerOpts}) -> - try Handler:init(Req, HandlerOpts) of - {ok, Req2, State} -> - Result = terminate(normal, Req2, State, Handler), - {ok, Req2, Env#{result => Result}}; - {Mod, Req2, State} -> - Mod:upgrade(Req2, Env, Handler, State); - {Mod, Req2, State, Opts} -> - Mod:upgrade(Req2, Env, Handler, State, Opts) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - terminate({crash, Class, Reason}, Req, HandlerOpts, Handler), - erlang:raise(Class, Reason, StackTrace) - end. - --spec terminate(any(), Req | undefined, any(), module()) -> ok when Req::cowboy_req:req(). -terminate(Reason, Req, State, Handler) -> - case erlang:function_exported(Handler, terminate, 3) of - true -> - Handler:terminate(Reason, Req, State); - false -> - ok - end. diff --git a/_build/emqx/lib/cowboy/src/cowboy_http.erl b/_build/emqx/lib/cowboy/src/cowboy_http.erl deleted file mode 100644 index f128a443dc..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_http.erl +++ /dev/null @@ -1,1465 +0,0 @@ -%% Copyright (c) 2016-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_http). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([init/6]). - --export([system_continue/3]). --export([system_terminate/4]). --export([system_code_change/4]). - --type opts() :: #{ - chunked => boolean(), - compress_buffering => boolean(), - compress_threshold => non_neg_integer(), - connection_type => worker | supervisor, - env => cowboy_middleware:env(), - http10_keepalive => boolean(), - idle_timeout => timeout(), - inactivity_timeout => timeout(), - initial_stream_flow_size => non_neg_integer(), - linger_timeout => timeout(), - logger => module(), - max_authority_length => non_neg_integer(), - max_empty_lines => non_neg_integer(), - max_header_name_length => non_neg_integer(), - max_header_value_length => non_neg_integer(), - max_headers => non_neg_integer(), - max_keepalive => non_neg_integer(), - max_method_length => non_neg_integer(), - max_request_line_length => non_neg_integer(), - metrics_callback => cowboy_metrics_h:metrics_callback(), - metrics_req_filter => fun((cowboy_req:req()) -> map()), - metrics_resp_headers_filter => fun((cowboy:http_headers()) -> cowboy:http_headers()), - middlewares => [module()], - proxy_header => boolean(), - request_timeout => timeout(), - sendfile => boolean(), - shutdown_timeout => timeout(), - stream_handlers => [module()], - tracer_callback => cowboy_tracer_h:tracer_callback(), - tracer_flags => [atom()], - tracer_match_specs => cowboy_tracer_h:tracer_match_specs(), - %% Open ended because configured stream handlers might add options. - _ => _ -}. --export_type([opts/0]). - --record(ps_request_line, { - empty_lines = 0 :: non_neg_integer() -}). - --record(ps_header, { - method = undefined :: binary(), - authority = undefined :: binary() | undefined, - path = undefined :: binary(), - qs = undefined :: binary(), - version = undefined :: cowboy:http_version(), - headers = undefined :: cowboy:http_headers() | undefined, - name = undefined :: binary() | undefined -}). - --record(ps_body, { - length :: non_neg_integer() | undefined, - received = 0 :: non_neg_integer(), - transfer_decode_fun :: fun((binary(), cow_http_te:state()) -> cow_http_te:decode_ret()), - transfer_decode_state :: cow_http_te:state() -}). - --record(stream, { - id = undefined :: cowboy_stream:streamid(), - %% Stream handlers and their state. - state = undefined :: {module(), any()}, - %% Request method. - method = undefined :: binary(), - %% Client HTTP version for this stream. - version = undefined :: cowboy:http_version(), - %% Unparsed te header. Used to know if we can send trailers. - te :: undefined | binary(), - %% Expected body size. - local_expected_size = undefined :: undefined | non_neg_integer(), - %% Sent body size. - local_sent_size = 0 :: non_neg_integer(), - %% Commands queued. - queue = [] :: cowboy_stream:commands() -}). - --type stream() :: #stream{}. - --record(state, { - parent :: pid(), - ref :: ranch:ref(), - socket :: inet:socket(), - transport :: module(), - proxy_header :: undefined | ranch_proxy_header:proxy_info(), - opts = #{} :: cowboy:opts(), - buffer = <<>> :: binary(), - - %% Some options may be overriden for the current stream. - overriden_opts = #{} :: cowboy:opts(), - - %% Remote address and port for the connection. - peer = undefined :: {inet:ip_address(), inet:port_number()}, - - %% Local address and port for the connection. - sock = undefined :: {inet:ip_address(), inet:port_number()}, - - %% Client certificate (TLS only). - cert :: undefined | binary(), - - timer = undefined :: undefined | reference(), - - %% Identifier for the stream currently being read (or waiting to be received). - in_streamid = 1 :: pos_integer(), - - %% Parsing state for the current stream or stream-to-be. - in_state = #ps_request_line{} :: #ps_request_line{} | #ps_header{} | #ps_body{}, - - %% Flow requested for the current stream. - flow = infinity :: non_neg_integer() | infinity, - - %% Identifier for the stream currently being written. - %% Note that out_streamid =< in_streamid. - out_streamid = 1 :: pos_integer(), - - %% Whether we finished writing data for the current stream. - out_state = wait :: wait | chunked | streaming | done, - - %% The connection will be closed after this stream. - last_streamid = undefined :: pos_integer(), - - %% Currently active HTTP/1.1 streams. - streams = [] :: [stream()], - - %% Children processes created by streams. - children = cowboy_children:init() :: cowboy_children:children() -}). - --include_lib("cowlib/include/cow_inline.hrl"). --include_lib("cowlib/include/cow_parse.hrl"). - --spec init(pid(), ranch:ref(), inet:socket(), module(), - ranch_proxy_header:proxy_info(), cowboy:opts()) -> ok. -init(Parent, Ref, Socket, Transport, ProxyHeader, Opts) -> - Peer0 = Transport:peername(Socket), - Sock0 = Transport:sockname(Socket), - Cert1 = case Transport:name() of - ssl -> - case ssl:peercert(Socket) of - {error, no_peercert} -> - {ok, undefined}; - Cert0 -> - Cert0 - end; - _ -> - {ok, undefined} - end, - case {Peer0, Sock0, Cert1} of - {{ok, Peer}, {ok, Sock}, {ok, Cert}} -> - State = #state{ - parent=Parent, ref=Ref, socket=Socket, - transport=Transport, proxy_header=ProxyHeader, opts=Opts, - peer=Peer, sock=Sock, cert=Cert, - last_streamid=maps:get(max_keepalive, Opts, 100)}, - before_loop(set_timeout(State, request_timeout)); - {{error, Reason}, _, _} -> - terminate(undefined, {socket_error, Reason, - 'A socket error occurred when retrieving the peer name.'}); - {_, {error, Reason}, _} -> - terminate(undefined, {socket_error, Reason, - 'A socket error occurred when retrieving the sock name.'}); - {_, _, {error, Reason}} -> - terminate(undefined, {socket_error, Reason, - 'A socket error occurred when retrieving the client TLS certificate.'}) - end. - -%% Do not read from the socket unless flow is large enough. -before_loop(State=#state{flow=Flow}) when Flow =< 0 -> - loop(State); -before_loop(State=#state{socket=Socket, transport=Transport}) -> - Transport:setopts(Socket, [{active, once}]), - loop(State). - -loop(State=#state{parent=Parent, socket=Socket, transport=Transport, opts=Opts, - buffer=Buffer, timer=TimerRef, children=Children, in_streamid=InStreamID, - last_streamid=LastStreamID}) -> - Messages = Transport:messages(), - InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000), - receive - %% Discard data coming in after the last request - %% we want to process was received fully. - {OK, Socket, _} when OK =:= element(1, Messages), InStreamID > LastStreamID -> - before_loop(State); - %% Socket messages. - {OK, Socket, Data} when OK =:= element(1, Messages) -> - parse(<< Buffer/binary, Data/binary >>, State); - {Closed, Socket} when Closed =:= element(2, Messages) -> - terminate(State, {socket_error, closed, 'The socket has been closed.'}); - {Error, Socket, Reason} when Error =:= element(3, Messages) -> - terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'}); - %% Timeouts. - {timeout, Ref, {shutdown, Pid}} -> - cowboy_children:shutdown_timeout(Children, Ref, Pid), - loop(State); - {timeout, TimerRef, Reason} -> - timeout(State, Reason); - {timeout, _, _} -> - loop(State); - %% System messages. - {'EXIT', Parent, Reason} -> - terminate(State, {stop, {exit, Reason}, 'Parent process terminated.'}); - {system, From, Request} -> - sys:handle_system_msg(Request, From, Parent, ?MODULE, [], State); - %% Messages pertaining to a stream. - {{Pid, StreamID}, Msg} when Pid =:= self() -> - loop(info(State, StreamID, Msg)); - %% Exit signal from children. - Msg = {'EXIT', Pid, _} -> - loop(down(State, Pid, Msg)); - %% Calls from supervisor module. - {'$gen_call', From, Call} -> - cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE), - loop(State); - %% Unknown messages. - Msg -> - cowboy:log(warning, "Received stray message ~p.~n", [Msg], Opts), - loop(State) - after InactivityTimeout -> - terminate(State, {internal_error, timeout, 'No message or data received before timeout.'}) - end. - -%% We do not set request_timeout if there are active streams. -set_timeout(State=#state{streams=[_|_]}, request_timeout) -> - State; -%% We do not set request_timeout if we are skipping a body. -set_timeout(State=#state{in_state=#ps_body{}}, request_timeout) -> - State; -%% We do not set idle_timeout if there are no active streams, -%% unless when we are skipping a body. -set_timeout(State=#state{streams=[], in_state=InState}, idle_timeout) - when element(1, InState) =/= ps_body -> - State; -%% Otherwise we can set the timeout. -set_timeout(State0=#state{opts=Opts, overriden_opts=Override}, Name) -> - State = cancel_timeout(State0), - Default = case Name of - request_timeout -> 5000; - idle_timeout -> 60000 - end, - Timeout = case Override of - %% The timeout may have been overriden for the current stream. - #{Name := Timeout0} -> Timeout0; - _ -> maps:get(Name, Opts, Default) - end, - TimerRef = case Timeout of - infinity -> undefined; - Timeout -> erlang:start_timer(Timeout, self(), Name) - end, - State#state{timer=TimerRef}. - -cancel_timeout(State=#state{timer=TimerRef}) -> - ok = case TimerRef of - undefined -> - ok; - _ -> - %% Do a synchronous cancel and remove the message if any - %% to avoid receiving stray messages. - _ = erlang:cancel_timer(TimerRef), - receive - {timeout, TimerRef, _} -> ok - after 0 -> - ok - end - end, - State#state{timer=undefined}. - --spec timeout(_, _) -> no_return(). -timeout(State=#state{in_state=#ps_request_line{}}, request_timeout) -> - terminate(State, {connection_error, timeout, - 'No request-line received before timeout.'}); -timeout(State=#state{in_state=#ps_header{}}, request_timeout) -> - error_terminate(408, State, {connection_error, timeout, - 'Request headers not received before timeout.'}); -timeout(State, idle_timeout) -> - terminate(State, {connection_error, timeout, - 'Connection idle longer than configuration allows.'}). - -parse(<<>>, State) -> - before_loop(State#state{buffer= <<>>}); -%% Do not process requests that come in after the last request -%% and discard the buffer if any to save memory. -parse(_, State=#state{in_streamid=InStreamID, in_state=#ps_request_line{}, - last_streamid=LastStreamID}) when InStreamID > LastStreamID -> - before_loop(State#state{buffer= <<>>}); -parse(Buffer, State=#state{in_state=#ps_request_line{empty_lines=EmptyLines}}) -> - after_parse(parse_request(Buffer, State, EmptyLines)); -parse(Buffer, State=#state{in_state=PS=#ps_header{headers=Headers, name=undefined}}) -> - after_parse(parse_header(Buffer, - State#state{in_state=PS#ps_header{headers=undefined}}, - Headers)); -parse(Buffer, State=#state{in_state=PS=#ps_header{headers=Headers, name=Name}}) -> - after_parse(parse_hd_before_value(Buffer, - State#state{in_state=PS#ps_header{headers=undefined, name=undefined}}, - Headers, Name)); -parse(Buffer, State=#state{in_state=#ps_body{}}) -> - after_parse(parse_body(Buffer, State)). - -after_parse({request, Req=#{streamid := StreamID, method := Method, - headers := Headers, version := Version}, - State0=#state{opts=Opts, buffer=Buffer, streams=Streams0}}) -> - try cowboy_stream:init(StreamID, Req, Opts) of - {Commands, StreamState} -> - Flow = maps:get(initial_stream_flow_size, Opts, 65535), - TE = maps:get(<<"te">>, Headers, undefined), - Streams = [#stream{id=StreamID, state=StreamState, - method=Method, version=Version, te=TE}|Streams0], - State1 = case maybe_req_close(State0, Headers, Version) of - close -> State0#state{streams=Streams, last_streamid=StreamID, flow=Flow}; - keepalive -> State0#state{streams=Streams, flow=Flow} - end, - State = set_timeout(State1, idle_timeout), - parse(Buffer, commands(State, StreamID, Commands)) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(init, - [StreamID, Req, Opts], - Class, Exception, erlang:get_stacktrace()), Opts), - early_error(500, State0, {internal_error, {Class, Exception}, - 'Unhandled exception in cowboy_stream:init/3.'}, Req), - parse(Buffer, State0) - end; -%% Streams are sequential so the body is always about the last stream created -%% unless that stream has terminated. -after_parse({data, StreamID, IsFin, Data, State0=#state{opts=Opts, buffer=Buffer, - streams=Streams0=[Stream=#stream{id=StreamID, state=StreamState0}|_]}}) -> - try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of - {Commands, StreamState} -> - Streams = lists:keyreplace(StreamID, #stream.id, Streams0, - Stream#stream{state=StreamState}), - State1 = set_timeout(State0, case IsFin of - fin -> request_timeout; - nofin -> idle_timeout - end), - State = update_flow(IsFin, Data, State1#state{streams=Streams}), - parse(Buffer, commands(State, StreamID, Commands)) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(data, - [StreamID, IsFin, Data, StreamState0], - Class, Exception, erlang:get_stacktrace()), Opts), - %% @todo Should call parse after this. - stream_terminate(State0, StreamID, {internal_error, {Class, Exception}, - 'Unhandled exception in cowboy_stream:data/4.'}) - end; -%% No corresponding stream. We must skip the body of the previous request -%% in order to process the next one. -after_parse({data, _, IsFin, _, State}) -> - before_loop(set_timeout(State, case IsFin of - fin -> request_timeout; - nofin -> idle_timeout - end)); -after_parse({more, State}) -> - before_loop(set_timeout(State, idle_timeout)). - -update_flow(fin, _, State) -> - State#state{flow=infinity}; -update_flow(nofin, Data, State=#state{flow=Flow0}) -> - State#state{flow=Flow0 - byte_size(Data)}. - -%% Request-line. - --spec parse_request(Buffer, State, non_neg_integer()) - -> {request, cowboy_req:req(), State} - | {data, cowboy_stream:streamid(), cowboy_stream:fin(), binary(), State} - | {more, State} - when Buffer::binary(), State::#state{}. -%% Empty lines must be using \r\n. -parse_request(<< $\n, _/bits >>, State, _) -> - error_terminate(400, State, {connection_error, protocol_error, - 'Empty lines between requests must use the CRLF line terminator. (RFC7230 3.5)'}); -parse_request(<< $\s, _/bits >>, State, _) -> - error_terminate(400, State, {connection_error, protocol_error, - 'The request-line must not begin with a space. (RFC7230 3.1.1, RFC7230 3.5)'}); -%% We limit the length of the Request-line to MaxLength to avoid endlessly -%% reading from the socket and eventually crashing. -parse_request(Buffer, State=#state{opts=Opts, in_streamid=InStreamID}, EmptyLines) -> - MaxLength = maps:get(max_request_line_length, Opts, 8000), - MaxEmptyLines = maps:get(max_empty_lines, Opts, 5), - case match_eol(Buffer, 0) of - nomatch when byte_size(Buffer) > MaxLength -> - error_terminate(414, State, {connection_error, limit_reached, - 'The request-line length is larger than configuration allows. (RFC7230 3.1.1)'}); - nomatch -> - {more, State#state{buffer=Buffer, in_state=#ps_request_line{empty_lines=EmptyLines}}}; - 1 when EmptyLines =:= MaxEmptyLines -> - error_terminate(400, State, {connection_error, limit_reached, - 'More empty lines were received than configuration allows. (RFC7230 3.5)'}); - 1 -> - << _:16, Rest/bits >> = Buffer, - parse_request(Rest, State, EmptyLines + 1); - _ -> - case Buffer of - %% @todo * is only for server-wide OPTIONS request (RFC7230 5.3.4); tests - << "OPTIONS * ", Rest/bits >> -> - parse_version(Rest, State, <<"OPTIONS">>, undefined, <<"*">>, <<>>); - <<"CONNECT ", _/bits>> -> - error_terminate(501, State, {connection_error, no_error, - 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)'}); - <<"TRACE ", _/bits>> -> - error_terminate(501, State, {connection_error, no_error, - 'The TRACE method is currently not implemented. (RFC7231 4.3.8)'}); - %% Accept direct HTTP/2 only at the beginning of the connection. - << "PRI * HTTP/2.0\r\n", _/bits >> when InStreamID =:= 1 -> - %% @todo Might be worth throwing to get a clean stacktrace. - http2_upgrade(State, Buffer); - _ -> - parse_method(Buffer, State, <<>>, - maps:get(max_method_length, Opts, 32)) - end - end. - -match_eol(<< $\n, _/bits >>, N) -> - N; -match_eol(<< _, Rest/bits >>, N) -> - match_eol(Rest, N + 1); -match_eol(_, _) -> - nomatch. - -parse_method(_, State, _, 0) -> - error_terminate(501, State, {connection_error, limit_reached, - 'The method name is longer than configuration allows. (RFC7230 3.1.1)'}); -parse_method(<< C, Rest/bits >>, State, SoFar, Remaining) -> - case C of - $\r -> error_terminate(400, State, {connection_error, protocol_error, - 'The method name must not be followed with a line break. (RFC7230 3.1.1)'}); - $\s -> parse_uri(Rest, State, SoFar); - _ when ?IS_TOKEN(C) -> parse_method(Rest, State, << SoFar/binary, C >>, Remaining - 1); - _ -> error_terminate(400, State, {connection_error, protocol_error, - 'The method name must contain only valid token characters. (RFC7230 3.1.1)'}) - end. - -parse_uri(<< H, T, T, P, "://", Rest/bits >>, State, Method) - when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T; - P =:= $p orelse P =:= $P -> - parse_uri_authority(Rest, State, Method); -parse_uri(<< H, T, T, P, S, "://", Rest/bits >>, State, Method) - when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T; - P =:= $p orelse P =:= $P; S =:= $s orelse S =:= $S -> - parse_uri_authority(Rest, State, Method); -parse_uri(<< $/, Rest/bits >>, State, Method) -> - parse_uri_path(Rest, State, Method, undefined, <<$/>>); -parse_uri(_, State, _) -> - error_terminate(400, State, {connection_error, protocol_error, - 'Invalid request-line or request-target. (RFC7230 3.1.1, RFC7230 5.3)'}). - -%% @todo We probably want to apply max_authority_length also -%% to the host header and to document this option. It might -%% also be useful for HTTP/2 requests. -parse_uri_authority(Rest, State=#state{opts=Opts}, Method) -> - parse_uri_authority(Rest, State, Method, <<>>, - maps:get(max_authority_length, Opts, 255)). - -parse_uri_authority(_, State, _, _, 0) -> - error_terminate(414, State, {connection_error, limit_reached, - 'The authority component of the absolute URI is longer than configuration allows. (RFC7230 2.7.1)'}); -parse_uri_authority(<>, State, Method, SoFar, Remaining) -> - case C of - $\r -> - error_terminate(400, State, {connection_error, protocol_error, - 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'}); - $@ -> - error_terminate(400, State, {connection_error, protocol_error, - 'Absolute URIs must not include a userinfo component. (RFC7230 2.7.1)'}); - C when SoFar =:= <<>> andalso - ((C =:= $/) orelse (C =:= $\s) orelse (C =:= $?) orelse (C =:= $#)) -> - error_terminate(400, State, {connection_error, protocol_error, - 'Absolute URIs must include a non-empty host component. (RFC7230 2.7.1)'}); - $: when SoFar =:= <<>> -> - error_terminate(400, State, {connection_error, protocol_error, - 'Absolute URIs must include a non-empty host component. (RFC7230 2.7.1)'}); - $/ -> parse_uri_path(Rest, State, Method, SoFar, <<"/">>); - $\s -> parse_version(Rest, State, Method, SoFar, <<"/">>, <<>>); - $? -> parse_uri_query(Rest, State, Method, SoFar, <<"/">>, <<>>); - $# -> skip_uri_fragment(Rest, State, Method, SoFar, <<"/">>, <<>>); - C -> parse_uri_authority(Rest, State, Method, <>, Remaining - 1) - end. - -parse_uri_path(<>, State, Method, Authority, SoFar) -> - case C of - $\r -> error_terminate(400, State, {connection_error, protocol_error, - 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'}); - $\s -> parse_version(Rest, State, Method, Authority, SoFar, <<>>); - $? -> parse_uri_query(Rest, State, Method, Authority, SoFar, <<>>); - $# -> skip_uri_fragment(Rest, State, Method, Authority, SoFar, <<>>); - _ -> parse_uri_path(Rest, State, Method, Authority, <>) - end. - -parse_uri_query(<>, State, M, A, P, SoFar) -> - case C of - $\r -> error_terminate(400, State, {connection_error, protocol_error, - 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'}); - $\s -> parse_version(Rest, State, M, A, P, SoFar); - $# -> skip_uri_fragment(Rest, State, M, A, P, SoFar); - _ -> parse_uri_query(Rest, State, M, A, P, <>) - end. - -skip_uri_fragment(<>, State, M, A, P, Q) -> - case C of - $\r -> error_terminate(400, State, {connection_error, protocol_error, - 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'}); - $\s -> parse_version(Rest, State, M, A, P, Q); - _ -> skip_uri_fragment(Rest, State, M, A, P, Q) - end. - -parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, State, M, A, P, Q) -> - before_parse_headers(Rest, State, M, A, P, Q, 'HTTP/1.1'); -parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, State, M, A, P, Q) -> - before_parse_headers(Rest, State, M, A, P, Q, 'HTTP/1.0'); -parse_version(<< "HTTP/1.", _, C, _/bits >>, State, _, _, _, _) when C =:= $\s; C =:= $\t -> - error_terminate(400, State, {connection_error, protocol_error, - 'Whitespace is not allowed after the HTTP version. (RFC7230 3.1.1)'}); -parse_version(<< C, _/bits >>, State, _, _, _, _) when C =:= $\s; C =:= $\t -> - error_terminate(400, State, {connection_error, protocol_error, - 'The separator between request target and version must be a single SP. (RFC7230 3.1.1)'}); -parse_version(_, State, _, _, _, _) -> - error_terminate(505, State, {connection_error, protocol_error, - 'Unsupported HTTP version. (RFC7230 2.6)'}). - -before_parse_headers(Rest, State, M, A, P, Q, V) -> - parse_header(Rest, State#state{in_state=#ps_header{ - method=M, authority=A, path=P, qs=Q, version=V}}, #{}). - -%% Headers. - -%% We need two or more bytes in the buffer to continue. -parse_header(Rest, State=#state{in_state=PS}, Headers) when byte_size(Rest) < 2 -> - {more, State#state{buffer=Rest, in_state=PS#ps_header{headers=Headers}}}; -parse_header(<< $\r, $\n, Rest/bits >>, S, Headers) -> - request(Rest, S, Headers); -parse_header(Buffer, State=#state{opts=Opts, in_state=PS}, Headers) -> - MaxHeaders = maps:get(max_headers, Opts, 100), - NumHeaders = maps:size(Headers), - if - NumHeaders >= MaxHeaders -> - error_terminate(431, State#state{in_state=PS#ps_header{headers=Headers}}, - {connection_error, limit_reached, - 'The number of headers is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'}); - true -> - parse_header_colon(Buffer, State, Headers) - end. - -parse_header_colon(Buffer, State=#state{opts=Opts, in_state=PS}, Headers) -> - MaxLength = maps:get(max_header_name_length, Opts, 64), - case match_colon(Buffer, 0) of - nomatch when byte_size(Buffer) > MaxLength -> - error_terminate(431, State#state{in_state=PS#ps_header{headers=Headers}}, - {connection_error, limit_reached, - 'A header name is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'}); - nomatch -> - %% We don't have a colon but we might have an invalid header line, - %% so check if we have an LF and abort with an error if we do. - case match_eol(Buffer, 0) of - nomatch -> - {more, State#state{buffer=Buffer, in_state=PS#ps_header{headers=Headers}}}; - _ -> - error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}}, - {connection_error, protocol_error, - 'A header line is missing a colon separator. (RFC7230 3.2.4)'}) - end; - _ -> - parse_hd_name(Buffer, State, Headers, <<>>) - end. - -match_colon(<< $:, _/bits >>, N) -> - N; -match_colon(<< _, Rest/bits >>, N) -> - match_colon(Rest, N + 1); -match_colon(_, _) -> - nomatch. - -parse_hd_name(<< $:, Rest/bits >>, State, H, SoFar) -> - parse_hd_before_value(Rest, State, H, SoFar); -parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, <<>>) when ?IS_WS(C) -> - error_terminate(400, State#state{in_state=PS#ps_header{headers=H}}, - {connection_error, protocol_error, - 'Whitespace is not allowed before the header name. (RFC7230 3.2)'}); -parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, _) when ?IS_WS(C) -> - error_terminate(400, State#state{in_state=PS#ps_header{headers=H}}, - {connection_error, protocol_error, - 'Whitespace is not allowed between the header name and the colon. (RFC7230 3.2.4)'}); -parse_hd_name(<< C, Rest/bits >>, State, H, SoFar) -> - ?LOWER(parse_hd_name, Rest, State, H, SoFar). - -parse_hd_before_value(<< $\s, Rest/bits >>, S, H, N) -> - parse_hd_before_value(Rest, S, H, N); -parse_hd_before_value(<< $\t, Rest/bits >>, S, H, N) -> - parse_hd_before_value(Rest, S, H, N); -parse_hd_before_value(Buffer, State=#state{opts=Opts, in_state=PS}, H, N) -> - MaxLength = maps:get(max_header_value_length, Opts, 4096), - case match_eol(Buffer, 0) of - nomatch when byte_size(Buffer) > MaxLength -> - error_terminate(431, State#state{in_state=PS#ps_header{headers=H}}, - {connection_error, limit_reached, - 'A header value is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'}); - nomatch -> - {more, State#state{buffer=Buffer, in_state=PS#ps_header{headers=H, name=N}}}; - _ -> - parse_hd_value(Buffer, State, H, N, <<>>) - end. - -parse_hd_value(<< $\r, $\n, Rest/bits >>, S, Headers0, Name, SoFar) -> - Value = clean_value_ws_end(SoFar, byte_size(SoFar) - 1), - Headers = case maps:get(Name, Headers0, undefined) of - undefined -> Headers0#{Name => Value}; - %% The cookie header does not use proper HTTP header lists. - Value0 when Name =:= <<"cookie">> -> Headers0#{Name => << Value0/binary, "; ", Value/binary >>}; - Value0 -> Headers0#{Name => << Value0/binary, ", ", Value/binary >>} - end, - parse_header(Rest, S, Headers); -parse_hd_value(<< C, Rest/bits >>, S, H, N, SoFar) -> - parse_hd_value(Rest, S, H, N, << SoFar/binary, C >>). - -clean_value_ws_end(_, -1) -> - <<>>; -clean_value_ws_end(Value, N) -> - case binary:at(Value, N) of - $\s -> clean_value_ws_end(Value, N - 1); - $\t -> clean_value_ws_end(Value, N - 1); - _ -> - S = N + 1, - << Value2:S/binary, _/bits >> = Value, - Value2 - end. - --ifdef(TEST). -clean_value_ws_end_test_() -> - Tests = [ - {<<>>, <<>>}, - {<<" ">>, <<>>}, - {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, " - "text/html;level=2;q=0.4, */*;q=0.5 \t \t ">>, - <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, " - "text/html;level=2;q=0.4, */*;q=0.5">>} - ], - [{V, fun() -> R = clean_value_ws_end(V, byte_size(V) - 1) end} || {V, R} <- Tests]. - -horse_clean_value_ws_end() -> - horse:repeat(200000, - clean_value_ws_end( - <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, " - "text/html;level=2;q=0.4, */*;q=0.5 ">>, - byte_size(<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, " - "text/html;level=2;q=0.4, */*;q=0.5 ">>) - 1) - ). --endif. - -request(Buffer, State=#state{transport=Transport, - in_state=PS=#ps_header{authority=Authority, version=Version}}, Headers) -> - case maps:get(<<"host">>, Headers, undefined) of - undefined when Version =:= 'HTTP/1.1' -> - %% @todo Might want to not close the connection on this and next one. - error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}}, - {stream_error, protocol_error, - 'HTTP/1.1 requests must include a host header. (RFC7230 5.4)'}); - undefined -> - request(Buffer, State, Headers, <<>>, default_port(Transport:secure())); - %% @todo When CONNECT requests come in we need to ignore the RawHost - %% and instead use the Authority as the source of host. - RawHost when Authority =:= undefined; Authority =:= RawHost -> - request_parse_host(Buffer, State, Headers, RawHost); - %% RFC7230 does not explicitly ask us to reject requests - %% that have a different authority component and host header. - %% However it DOES ask clients to set them to the same value, - %% so we enforce that. - _ -> - error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}}, - {stream_error, protocol_error, - 'The host header is different than the absolute-form authority component. (RFC7230 5.4)'}) - end. - -request_parse_host(Buffer, State=#state{transport=Transport, in_state=PS}, Headers, RawHost) -> - try cow_http_hd:parse_host(RawHost) of - {Host, undefined} -> - request(Buffer, State, Headers, Host, default_port(Transport:secure())); - {Host, Port} when Port > 0, Port =< 65535 -> - request(Buffer, State, Headers, Host, Port); - _ -> - error_terminate(400, State, {stream_error, protocol_error, - 'The port component of the absolute-form is not in the range 0..65535. (RFC7230 2.7.1)'}) - catch _:_ -> - error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}}, - {stream_error, protocol_error, - 'The host header is invalid. (RFC7230 5.4)'}) - end. - --spec default_port(boolean()) -> 80 | 443. -default_port(true) -> 443; -default_port(_) -> 80. - -%% End of request parsing. - -request(Buffer, State0=#state{ref=Ref, transport=Transport, peer=Peer, sock=Sock, cert=Cert, - proxy_header=ProxyHeader, in_streamid=StreamID, in_state= - PS=#ps_header{method=Method, path=Path, qs=Qs, version=Version}}, - Headers0, Host, Port) -> - Scheme = case Transport:secure() of - true -> <<"https">>; - false -> <<"http">> - end, - {Headers, HasBody, BodyLength, TDecodeFun, TDecodeState} = case Headers0 of - #{<<"transfer-encoding">> := TransferEncoding0} -> - try cow_http_hd:parse_transfer_encoding(TransferEncoding0) of - [<<"chunked">>] -> - {maps:remove(<<"content-length">>, Headers0), - true, undefined, fun cow_http_te:stream_chunked/2, {0, 0}}; - _ -> - error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers0}}, - {stream_error, protocol_error, - 'Cowboy only supports transfer-encoding: chunked. (RFC7230 3.3.1)'}) - catch _:_ -> - error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers0}}, - {stream_error, protocol_error, - 'The transfer-encoding header is invalid. (RFC7230 3.3.1)'}) - end; - #{<<"content-length">> := <<"0">>} -> - {Headers0, false, 0, undefined, undefined}; - #{<<"content-length">> := BinLength} -> - Length = try - cow_http_hd:parse_content_length(BinLength) - catch _:_ -> - error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers0}}, - {stream_error, protocol_error, - 'The content-length header is invalid. (RFC7230 3.3.2)'}) - end, - {Headers0, true, Length, fun cow_http_te:stream_identity/2, {0, Length}}; - _ -> - {Headers0, false, 0, undefined, undefined} - end, - Req0 = #{ - ref => Ref, - pid => self(), - streamid => StreamID, - peer => Peer, - sock => Sock, - cert => Cert, - method => Method, - scheme => Scheme, - host => Host, - port => Port, - path => Path, - qs => Qs, - version => Version, - %% We are transparently taking care of transfer-encodings so - %% the user code has no need to know about it. - headers => maps:remove(<<"transfer-encoding">>, Headers), - has_body => HasBody, - body_length => BodyLength - }, - %% We add the PROXY header information if any. - Req = case ProxyHeader of - undefined -> Req0; - _ -> Req0#{proxy_header => ProxyHeader} - end, - case is_http2_upgrade(Headers, Version) of - false -> - State = case HasBody of - true -> - State0#state{in_state=#ps_body{ - length = BodyLength, - transfer_decode_fun = TDecodeFun, - transfer_decode_state = TDecodeState - }}; - false -> - State0#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}} - end, - {request, Req, State#state{buffer=Buffer}}; - {true, HTTP2Settings} -> - %% We save the headers in case the upgrade will fail - %% and we need to pass them to cowboy_stream:early_error. - http2_upgrade(State0#state{in_state=PS#ps_header{headers=Headers}}, - Buffer, HTTP2Settings, Req) - end. - -%% HTTP/2 upgrade. - -%% @todo We must not upgrade to h2c over a TLS connection. -is_http2_upgrade(#{<<"connection">> := Conn, <<"upgrade">> := Upgrade, - <<"http2-settings">> := HTTP2Settings}, 'HTTP/1.1') -> - Conns = cow_http_hd:parse_connection(Conn), - case {lists:member(<<"upgrade">>, Conns), lists:member(<<"http2-settings">>, Conns)} of - {true, true} -> - Protocols = cow_http_hd:parse_upgrade(Upgrade), - case lists:member(<<"h2c">>, Protocols) of - true -> - {true, HTTP2Settings}; - false -> - false - end; - _ -> - false - end; -is_http2_upgrade(_, _) -> - false. - -%% Prior knowledge upgrade, without an HTTP/1.1 request. -http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport, - proxy_header=ProxyHeader, opts=Opts, peer=Peer, sock=Sock, cert=Cert}, Buffer) -> - case Transport:secure() of - false -> - _ = cancel_timeout(State), - cowboy_http2:init(Parent, Ref, Socket, Transport, - ProxyHeader, Opts, Peer, Sock, Cert, Buffer); - true -> - error_terminate(400, State, {connection_error, protocol_error, - 'Clients that support HTTP/2 over TLS MUST use ALPN. (RFC7540 3.4)'}) - end. - -%% Upgrade via an HTTP/1.1 request. -http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport, - proxy_header=ProxyHeader, opts=Opts, peer=Peer, sock=Sock, cert=Cert}, - Buffer, HTTP2Settings, Req) -> - %% @todo - %% However if the client sent a body, we need to read the body in full - %% and if we can't do that, return a 413 response. Some options are in order. - %% Always half-closed stream coming from this side. - try cow_http_hd:parse_http2_settings(HTTP2Settings) of - Settings -> - _ = cancel_timeout(State), - cowboy_http2:init(Parent, Ref, Socket, Transport, - ProxyHeader, Opts, Peer, Sock, Cert, Buffer, Settings, Req) - catch _:_ -> - error_terminate(400, State, {connection_error, protocol_error, - 'The HTTP2-Settings header must contain a base64 SETTINGS payload. (RFC7540 3.2, RFC7540 3.2.1)'}) - end. - -%% Request body parsing. - -parse_body(Buffer, State=#state{in_streamid=StreamID, in_state= - PS=#ps_body{received=Received, transfer_decode_fun=TDecode, - transfer_decode_state=TState0}}) -> - %% @todo Proper trailers. - try TDecode(Buffer, TState0) of - more -> - {more, State#state{buffer=Buffer}}; - {more, Data, TState} -> - {data, StreamID, nofin, Data, State#state{buffer= <<>>, - in_state=PS#ps_body{received=Received + byte_size(Data), - transfer_decode_state=TState}}}; - {more, Data, _Length, TState} when is_integer(_Length) -> - {data, StreamID, nofin, Data, State#state{buffer= <<>>, - in_state=PS#ps_body{received=Received + byte_size(Data), - transfer_decode_state=TState}}}; - {more, Data, Rest, TState} -> - {data, StreamID, nofin, Data, State#state{buffer=Rest, - in_state=PS#ps_body{received=Received + byte_size(Data), - transfer_decode_state=TState}}}; - {done, _HasTrailers, Rest} -> - {data, StreamID, fin, <<>>, - State#state{buffer=Rest, in_streamid=StreamID + 1, in_state=#ps_request_line{}}}; - {done, Data, _HasTrailers, Rest} -> - {data, StreamID, fin, Data, - State#state{buffer=Rest, in_streamid=StreamID + 1, in_state=#ps_request_line{}}} - catch _:_ -> - Reason = {connection_error, protocol_error, - 'Failure to decode the content. (RFC7230 4)'}, - terminate(stream_terminate(State, StreamID, Reason), Reason) - end. - -%% Message handling. - -down(State=#state{opts=Opts, children=Children0}, Pid, Msg) -> - case cowboy_children:down(Children0, Pid) of - %% The stream was terminated already. - {ok, undefined, Children} -> - State#state{children=Children}; - %% The stream is still running. - {ok, StreamID, Children} -> - info(State#state{children=Children}, StreamID, Msg); - %% The process was unknown. - error -> - cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n", - [Msg, Pid], Opts), - State - end. - -info(State=#state{opts=Opts, streams=Streams0}, StreamID, Msg) -> - case lists:keyfind(StreamID, #stream.id, Streams0) of - Stream = #stream{state=StreamState0} -> - try cowboy_stream:info(StreamID, Msg, StreamState0) of - {Commands, StreamState} -> - Streams = lists:keyreplace(StreamID, #stream.id, Streams0, - Stream#stream{state=StreamState}), - commands(State#state{streams=Streams}, StreamID, Commands) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(info, - [StreamID, Msg, StreamState0], - Class, Exception, erlang:get_stacktrace()), Opts), - stream_terminate(State, StreamID, {internal_error, {Class, Exception}, - 'Unhandled exception in cowboy_stream:info/3.'}) - end; - false -> - cowboy:log(warning, "Received message ~p for unknown stream ~p.~n", - [Msg, StreamID], Opts), - State - end. - -%% Commands. - -commands(State, _, []) -> - State; -%% Supervise a child process. -commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) -> - commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)}, - StreamID, Tail); -%% Error handling. -commands(State, StreamID, [Error = {internal_error, _, _}|Tail]) -> - commands(stream_terminate(State, StreamID, Error), StreamID, Tail); -%% Commands for a stream currently inactive. -commands(State=#state{out_streamid=Current, streams=Streams0}, StreamID, Commands) - when Current =/= StreamID -> - - %% @todo We still want to handle some commands... - - Stream = #stream{queue=Queue} = lists:keyfind(StreamID, #stream.id, Streams0), - Streams = lists:keyreplace(StreamID, #stream.id, Streams0, - Stream#stream{queue=Queue ++ Commands}), - State#state{streams=Streams}; -%% Read the request body. -commands(State=#state{socket=Socket, transport=Transport, flow=Flow0}, StreamID, - [{flow, Size}|Tail]) -> - %% We must read *at least* Size of data otherwise functions - %% like cowboy_req:read_body/1,2 will wait indefinitely. - Flow = if - Flow0 < 0 -> Size; - true -> Flow0 + Size - end, - %% Reenable active mode if necessary. - _ = if - Flow0 =< 0, Flow > 0 -> - Transport:setopts(Socket, [{active, once}]); - true -> - ok - end, - commands(State#state{flow=Flow}, StreamID, Tail); -%% Error responses are sent only if a response wasn't sent already. -commands(State=#state{out_state=wait, out_streamid=StreamID}, StreamID, - [{error_response, Status, Headers0, Body}|Tail]) -> - %% We close the connection when the error response is 408, as it - %% indicates a timeout and the RFC recommends that we stop here. (RFC7231 6.5.7) - Headers = case Status of - 408 -> Headers0#{<<"connection">> => <<"close">>}; - <<"408", _/bits>> -> Headers0#{<<"connection">> => <<"close">>}; - _ -> Headers0 - end, - commands(State, StreamID, [{response, Status, Headers, Body}|Tail]); -commands(State, StreamID, [{error_response, _, _, _}|Tail]) -> - commands(State, StreamID, Tail); -%% Send an informational response. -commands(State=#state{socket=Socket, transport=Transport, out_state=wait, streams=Streams}, - StreamID, [{inform, StatusCode, Headers}|Tail]) -> - %% @todo I'm pretty sure the last stream in the list is the one we want - %% considering all others are queued. - #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams), - _ = case Version of - 'HTTP/1.1' -> - Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', - headers_to_list(Headers))); - %% Do not send informational responses to HTTP/1.0 clients. (RFC7231 6.2) - 'HTTP/1.0' -> - ok - end, - commands(State, StreamID, Tail); -%% Send a full response. -%% -%% @todo Kill the stream if it sent a response when one has already been sent. -%% @todo Keep IsFin in the state. -%% @todo Same two things above apply to DATA, possibly promise too. -commands(State0=#state{socket=Socket, transport=Transport, out_state=wait, streams=Streams}, StreamID, - [{response, StatusCode, Headers0, Body}|Tail]) -> - %% @todo I'm pretty sure the last stream in the list is the one we want - %% considering all others are queued. - #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams), - {State1, Headers} = connection(State0, Headers0, StreamID, Version), - State = State1#state{out_state=done}, - %% @todo Ensure content-length is set. - Response = cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers)), - case Body of - {sendfile, _, _, _} -> - Transport:send(Socket, Response), - sendfile(State, Body); - _ -> - Transport:send(Socket, [Response, Body]) - end, - commands(State, StreamID, Tail); -%% Send response headers and initiate chunked encoding or streaming. -commands(State0=#state{socket=Socket, transport=Transport, - opts=Opts, overriden_opts=Override, streams=Streams0, out_state=OutState}, - StreamID, [{headers, StatusCode, Headers0}|Tail]) -> - %% @todo Same as above (about the last stream in the list). - Stream = #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams0), - Status = cow_http:status_to_integer(StatusCode), - ContentLength = maps:get(<<"content-length">>, Headers0, undefined), - %% Chunked transfer-encoding can be disabled on a per-request basis. - Chunked = case Override of - #{chunked := Chunked0} -> Chunked0; - _ -> maps:get(chunked, Opts, true) - end, - {State1, Headers1} = case {Status, ContentLength, Version} of - {204, _, 'HTTP/1.1'} -> - {State0#state{out_state=done}, Headers0}; - {304, _, 'HTTP/1.1'} -> - {State0#state{out_state=done}, Headers0}; - {_, undefined, 'HTTP/1.1'} when Chunked -> - {State0#state{out_state=chunked}, Headers0#{<<"transfer-encoding">> => <<"chunked">>}}; - %% Close the connection after streaming without content-length - %% to all HTTP/1.0 clients and to HTTP/1.1 clients when chunked is disabled. - {_, undefined, _} -> - {State0#state{out_state=streaming, last_streamid=StreamID}, Headers0}; - %% Stream the response body without chunked transfer-encoding. - _ -> - ExpectedSize = cow_http_hd:parse_content_length(ContentLength), - Streams = lists:keyreplace(StreamID, #stream.id, Streams0, - Stream#stream{local_expected_size=ExpectedSize}), - {State0#state{out_state=streaming, streams=Streams}, Headers0} - end, - Headers2 = case stream_te(OutState, Stream) of - trailers -> Headers1; - _ -> maps:remove(<<"trailer">>, Headers1) - end, - {State, Headers} = connection(State1, Headers2, StreamID, Version), - Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers))), - commands(State, StreamID, Tail); -%% Send a response body chunk. -%% @todo We need to kill the stream if it tries to send data before headers. -commands(State0=#state{socket=Socket, transport=Transport, streams=Streams0, out_state=OutState}, - StreamID, [{data, IsFin, Data}|Tail]) -> - %% Do not send anything when the user asks to send an empty - %% data frame, as that would break the protocol. - Size = case Data of - {sendfile, _, B, _} -> B; - _ -> iolist_size(Data) - end, - %% Depending on the current state we may need to send nothing, - %% the last chunk, chunked data with/without the last chunk, - %% or just the data as-is. - Stream = case lists:keyfind(StreamID, #stream.id, Streams0) of - Stream0=#stream{method= <<"HEAD">>} -> - Stream0; - Stream0 when Size =:= 0, IsFin =:= fin, OutState =:= chunked -> - Transport:send(Socket, <<"0\r\n\r\n">>), - Stream0; - Stream0 when Size =:= 0 -> - Stream0; - Stream0 when is_tuple(Data), OutState =:= chunked -> - Transport:send(Socket, [integer_to_binary(Size, 16), <<"\r\n">>]), - sendfile(State0, Data), - Transport:send(Socket, - case IsFin of - fin -> <<"\r\n0\r\n\r\n">>; - nofin -> <<"\r\n">> - end), - Stream0; - Stream0 when OutState =:= chunked -> - Transport:send(Socket, [ - integer_to_binary(Size, 16), <<"\r\n">>, Data, - case IsFin of - fin -> <<"\r\n0\r\n\r\n">>; - nofin -> <<"\r\n">> - end - ]), - Stream0; - Stream0 when OutState =:= streaming -> - #stream{local_sent_size=SentSize0, local_expected_size=ExpectedSize} = Stream0, - SentSize = SentSize0 + Size, - if - %% ExpectedSize may be undefined, which is > any integer value. - SentSize > ExpectedSize -> - terminate(State0, response_body_too_large); - is_tuple(Data) -> - sendfile(State0, Data); - true -> - Transport:send(Socket, Data) - end, - Stream0#stream{local_sent_size=SentSize} - end, - State = case IsFin of - fin -> State0#state{out_state=done}; - nofin -> State0 - end, - Streams = lists:keyreplace(StreamID, #stream.id, Streams0, Stream), - commands(State#state{streams=Streams}, StreamID, Tail); -commands(State=#state{socket=Socket, transport=Transport, streams=Streams, out_state=OutState}, - StreamID, [{trailers, Trailers}|Tail]) -> - case stream_te(OutState, lists:keyfind(StreamID, #stream.id, Streams)) of - trailers -> - Transport:send(Socket, [ - <<"0\r\n">>, - cow_http:headers(maps:to_list(Trailers)), - <<"\r\n">> - ]); - no_trailers -> - Transport:send(Socket, <<"0\r\n\r\n">>); - not_chunked -> - ok - end, - commands(State#state{out_state=done}, StreamID, Tail); -%% Protocol takeover. -commands(State0=#state{ref=Ref, parent=Parent, socket=Socket, transport=Transport, - out_state=OutState, opts=Opts, buffer=Buffer, children=Children}, StreamID, - [{switch_protocol, Headers, Protocol, InitialState}|_Tail]) -> - %% @todo If there's streams opened after this one, fail instead of 101. - State = cancel_timeout(State0), - %% Before we send the 101 response we need to stop receiving data - %% from the socket, otherwise the data might be receive before the - %% call to flush/0 and we end up inadvertently dropping a packet. - %% - %% @todo Handle cases where the request came with a body. We need - %% to process or skip the body before the upgrade can be completed. - Transport:setopts(Socket, [{active, false}]), - %% Send a 101 response if necessary, then terminate the stream. - #state{streams=Streams} = case OutState of - wait -> info(State, StreamID, {inform, 101, Headers}); - _ -> State - end, - #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams), - %% @todo We need to shutdown processes here first. - stream_call_terminate(StreamID, switch_protocol, StreamState, State), - %% Terminate children processes and flush any remaining messages from the mailbox. - cowboy_children:terminate(Children), - flush(Parent), - Protocol:takeover(Parent, Ref, Socket, Transport, Opts, Buffer, InitialState); -%% Set options dynamically. -commands(State0=#state{overriden_opts=Opts}, - StreamID, [{set_options, SetOpts}|Tail]) -> - State1 = case SetOpts of - #{idle_timeout := IdleTimeout} -> - set_timeout(State0#state{overriden_opts=Opts#{idle_timeout => IdleTimeout}}, - idle_timeout); - _ -> - State0 - end, - State = case SetOpts of - #{chunked := Chunked} -> - State1#state{overriden_opts=Opts#{chunked => Chunked}}; - _ -> - State1 - end, - commands(State, StreamID, Tail); -%% Stream shutdown. -commands(State, StreamID, [stop|Tail]) -> - %% @todo Do we want to run the commands after a stop? - %% @todo We currently wait for the stop command before we - %% continue with the next request/response. In theory, if - %% the request body was read fully and the response body - %% was sent fully we should be able to start working on - %% the next request concurrently. This can be done as a - %% future optimization. - maybe_terminate(State, StreamID, Tail); -%% Log event. -commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) -> - cowboy:log(Log, Opts), - commands(State, StreamID, Tail); -%% HTTP/1.1 does not support push; ignore. -commands(State, StreamID, [{push, _, _, _, _, _, _, _}|Tail]) -> - commands(State, StreamID, Tail). - -%% The set-cookie header is special; we can only send one cookie per header. -headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) -> - Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)), - Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies]; -headers_to_list(Headers) -> - maps:to_list(Headers). - -%% We wrap the sendfile call into a try/catch because on OTP-20 -%% and earlier a few different crashes could occur for sockets -%% that were closing or closed. For example a badarg in -%% erlang:port_get_data(#Port<...>) or a badmatch like -%% {{badmatch,{error,einval}},[{prim_file,sendfile,8,[]}... -%% -%% OTP-21 uses a NIF instead of a port so the implementation -%% and behavior has dramatically changed and it is unclear -%% whether it will be necessary in the future. -%% -%% This try/catch prevents some noisy logs to be written -%% when these errors occur. -sendfile(State=#state{socket=Socket, transport=Transport, opts=Opts}, - {sendfile, Offset, Bytes, Path}) -> - try - %% When sendfile is disabled we explicitly use the fallback. - _ = case maps:get(sendfile, Opts, true) of - true -> Transport:sendfile(Socket, Path, Offset, Bytes); - false -> ranch_transport:sendfile(Transport, Socket, Path, Offset, Bytes, []) - end, - ok - catch _:_ -> - terminate(State, {socket_error, sendfile_crash, - 'An error occurred when using the sendfile function.'}) - end. - -%% Flush messages specific to cowboy_http before handing over the -%% connection to another protocol. -flush(Parent) -> - receive - {timeout, _, _} -> - flush(Parent); - {{Pid, _}, _} when Pid =:= self() -> - flush(Parent); - {'EXIT', Pid, _} when Pid =/= Parent -> - flush(Parent) - after 0 -> - ok - end. - -%% @todo In these cases I'm not sure if we should continue processing commands. -maybe_terminate(State=#state{last_streamid=StreamID}, StreamID, _Tail) -> - terminate(stream_terminate(State, StreamID, normal), normal); %% @todo Reason ok? -maybe_terminate(State, StreamID, _Tail) -> - stream_terminate(State, StreamID, normal). - -stream_terminate(State0=#state{opts=Opts, in_streamid=InStreamID, in_state=InState, - out_streamid=OutStreamID, out_state=OutState, streams=Streams0, - children=Children0}, StreamID, Reason) -> - #stream{version=Version, local_expected_size=ExpectedSize, local_sent_size=SentSize} - = lists:keyfind(StreamID, #stream.id, Streams0), - State1 = #state{streams=Streams1} = case OutState of - wait when element(1, Reason) =:= internal_error -> - info(State0, StreamID, {response, 500, #{<<"content-length">> => <<"0">>}, <<>>}); - wait when element(1, Reason) =:= connection_error -> - info(State0, StreamID, {response, 400, #{<<"content-length">> => <<"0">>}, <<>>}); - wait -> - info(State0, StreamID, {response, 204, #{}, <<>>}); - chunked when Version =:= 'HTTP/1.1' -> - info(State0, StreamID, {data, fin, <<>>}); - streaming when SentSize < ExpectedSize -> - terminate(State0, response_body_too_small); - _ -> %% done or Version =:= 'HTTP/1.0' - State0 - end, - %% Remove the stream from the state and reset the overriden options. - {value, #stream{state=StreamState}, Streams} - = lists:keytake(StreamID, #stream.id, Streams1), - State2 = State1#state{streams=Streams, overriden_opts=#{}, flow=infinity}, - %% Stop the stream. - stream_call_terminate(StreamID, Reason, StreamState, State2), - Children = cowboy_children:shutdown(Children0, StreamID), - %% We reset the timeout if there are no active streams anymore. - State = set_timeout(State2#state{streams=Streams, children=Children}, request_timeout), - %% We want to drop the connection if the body was not read fully - %% and we don't know its length or more remains to be read than - %% configuration allows. - %% @todo Only do this if Current =:= StreamID. - MaxSkipBodyLength = maps:get(max_skip_body_length, Opts, 1000000), - case InState of - #ps_body{length=undefined} - when InStreamID =:= OutStreamID -> - terminate(State, skip_body_unknown_length); - #ps_body{length=Len, received=Received} - when InStreamID =:= OutStreamID, Received + MaxSkipBodyLength < Len -> - terminate(State, skip_body_too_large); - _ -> - %% Move on to the next stream. - NextOutStreamID = OutStreamID + 1, - case lists:keyfind(NextOutStreamID, #stream.id, Streams) of - false -> - State#state{out_streamid=NextOutStreamID, out_state=wait}; - #stream{queue=Commands} -> - %% @todo Remove queue from the stream. - commands(State#state{out_streamid=NextOutStreamID, out_state=wait}, - NextOutStreamID, Commands) - end - end. - -stream_call_terminate(StreamID, Reason, StreamState, #state{opts=Opts}) -> - try - cowboy_stream:terminate(StreamID, Reason, StreamState) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(terminate, - [StreamID, Reason, StreamState], - Class, Exception, erlang:get_stacktrace()), Opts) - end. - -maybe_req_close(#state{opts=#{http10_keepalive := false}}, _, 'HTTP/1.0') -> - close; -maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.0') -> - Conns = cow_http_hd:parse_connection(Conn), - case lists:member(<<"keep-alive">>, Conns) of - true -> keepalive; - false -> close - end; -maybe_req_close(_, _, 'HTTP/1.0') -> - close; -maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.1') -> - case connection_hd_is_close(Conn) of - true -> close; - false -> keepalive - end; -maybe_req_close(_, _, _) -> - keepalive. - -connection(State=#state{last_streamid=StreamID}, Headers=#{<<"connection">> := Conn}, StreamID, _) -> - case connection_hd_is_close(Conn) of - true -> {State, Headers}; - %% @todo Here we need to remove keep-alive and add close, not just add close. - false -> {State, Headers#{<<"connection">> => [<<"close, ">>, Conn]}} - end; -connection(State=#state{last_streamid=StreamID}, Headers, StreamID, _) -> - {State, Headers#{<<"connection">> => <<"close">>}}; -connection(State, Headers=#{<<"connection">> := Conn}, StreamID, _) -> - case connection_hd_is_close(Conn) of - true -> {State#state{last_streamid=StreamID}, Headers}; - %% @todo Here we need to set keep-alive only if it wasn't set before. - false -> {State, Headers} - end; -connection(State, Headers, _, 'HTTP/1.0') -> - {State, Headers#{<<"connection">> => <<"keep-alive">>}}; -connection(State, Headers, _, _) -> - {State, Headers}. - -connection_hd_is_close(Conn) -> - Conns = cow_http_hd:parse_connection(iolist_to_binary(Conn)), - lists:member(<<"close">>, Conns). - -stream_te(streaming, _) -> - not_chunked; -%% No TE header was sent. -stream_te(_, #stream{te=undefined}) -> - no_trailers; -stream_te(_, #stream{te=TE0}) -> - try cow_http_hd:parse_te(TE0) of - {TE1, _} -> TE1 - catch _:_ -> - %% If we can't parse the TE header, assume we can't send trailers. - no_trailers - end. - -%% This function is only called when an error occurs on a new stream. --spec error_terminate(cowboy:http_status(), #state{}, _) -> no_return(). -error_terminate(StatusCode, State=#state{ref=Ref, peer=Peer, in_state=StreamState}, Reason) -> - PartialReq = case StreamState of - #ps_request_line{} -> #{ - ref => Ref, - peer => Peer - }; - #ps_header{method=Method, path=Path, qs=Qs, - version=Version, headers=ReqHeaders} -> #{ - ref => Ref, - peer => Peer, - method => Method, - path => Path, - qs => Qs, - version => Version, - headers => case ReqHeaders of - undefined -> #{}; - _ -> ReqHeaders - end - } - end, - early_error(StatusCode, State, Reason, PartialReq, #{<<"connection">> => <<"close">>}), - terminate(State, Reason). - -early_error(StatusCode, State, Reason, PartialReq) -> - early_error(StatusCode, State, Reason, PartialReq, #{}). - -early_error(StatusCode0, #state{socket=Socket, transport=Transport, - opts=Opts, in_streamid=StreamID}, Reason, PartialReq, RespHeaders0) -> - RespHeaders1 = RespHeaders0#{<<"content-length">> => <<"0">>}, - Resp = {response, StatusCode0, RespHeaders1, <<>>}, - try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of - {response, StatusCode, RespHeaders, RespBody} -> - Transport:send(Socket, [ - cow_http:response(StatusCode, 'HTTP/1.1', maps:to_list(RespHeaders)), - %% @todo We shouldn't send the body when the method is HEAD. - %% @todo Technically we allow the sendfile tuple. - RespBody - ]) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(early_error, - [StreamID, Reason, PartialReq, Resp, Opts], - Class, Exception, erlang:get_stacktrace()), Opts), - %% We still need to send an error response, so send what we initially - %% wanted to send. It's better than nothing. - Transport:send(Socket, cow_http:response(StatusCode0, - 'HTTP/1.1', maps:to_list(RespHeaders1))) - end, - ok. - --spec terminate(_, _) -> no_return(). -terminate(undefined, Reason) -> - exit({shutdown, Reason}); -terminate(State=#state{streams=Streams, children=Children}, Reason) -> - terminate_all_streams(State, Streams, Reason), - cowboy_children:terminate(Children), - terminate_linger(State), - exit({shutdown, Reason}). - -terminate_all_streams(_, [], _) -> - ok; -terminate_all_streams(State, [#stream{id=StreamID, state=StreamState}|Tail], Reason) -> - stream_call_terminate(StreamID, Reason, StreamState, State), - terminate_all_streams(State, Tail, Reason). - -terminate_linger(State=#state{socket=Socket, transport=Transport, opts=Opts}) -> - case Transport:shutdown(Socket, write) of - ok -> - case maps:get(linger_timeout, Opts, 1000) of - 0 -> - ok; - infinity -> - terminate_linger_loop(State, undefined); - Timeout -> - TimerRef = erlang:start_timer(Timeout, self(), linger_timeout), - terminate_linger_loop(State, TimerRef) - end; - {error, _} -> - ok - end. - -terminate_linger_loop(State=#state{socket=Socket, transport=Transport}, TimerRef) -> - Messages = Transport:messages(), - %% We may already have a message in the mailbox when we do this - %% but it's OK because we are shutting down anyway. - case Transport:setopts(Socket, [{active, once}]) of - ok -> - receive - {OK, Socket, _} when OK =:= element(1, Messages) -> - terminate_linger_loop(State, TimerRef); - {Closed, Socket} when Closed =:= element(2, Messages) -> - ok; - {Error, Socket, _} when Error =:= element(3, Messages) -> - ok; - {timeout, TimerRef, linger_timeout} -> - ok; - _ -> - terminate_linger_loop(State, TimerRef) - end; - {error, _} -> - ok - end. - -%% System callbacks. - --spec system_continue(_, _, #state{}) -> ok. -system_continue(_, _, State) -> - loop(State). - --spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return(). -system_terminate(Reason, _, _, State) -> - terminate(State, {stop, {exit, Reason}, 'sys:terminate/2,3 was called.'}). - --spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}. -system_code_change(Misc, _, _, _) -> - {ok, Misc}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_http2.erl b/_build/emqx/lib/cowboy/src/cowboy_http2.erl deleted file mode 100644 index 2754e9cab3..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_http2.erl +++ /dev/null @@ -1,1052 +0,0 @@ -%% Copyright (c) 2015-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_http2). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([init/6]). --export([init/10]). --export([init/12]). - --export([system_continue/3]). --export([system_terminate/4]). --export([system_code_change/4]). - --type opts() :: #{ - compress_buffering => boolean(), - compress_threshold => non_neg_integer(), - connection_type => worker | supervisor, - connection_window_margin_size => 0..16#7fffffff, - connection_window_update_threshold => 0..16#7fffffff, - enable_connect_protocol => boolean(), - env => cowboy_middleware:env(), - idle_timeout => timeout(), - inactivity_timeout => timeout(), - initial_connection_window_size => 65535..16#7fffffff, - initial_stream_window_size => 0..16#7fffffff, - logger => module(), - max_concurrent_streams => non_neg_integer() | infinity, - max_connection_buffer_size => non_neg_integer(), - max_connection_window_size => 0..16#7fffffff, - max_decode_table_size => non_neg_integer(), - max_encode_table_size => non_neg_integer(), - max_frame_size_received => 16384..16777215, - max_frame_size_sent => 16384..16777215 | infinity, - max_received_frame_rate => {pos_integer(), timeout()}, - max_reset_stream_rate => {pos_integer(), timeout()}, - max_stream_buffer_size => non_neg_integer(), - max_stream_window_size => 0..16#7fffffff, - metrics_callback => cowboy_metrics_h:metrics_callback(), - metrics_req_filter => fun((cowboy_req:req()) -> map()), - metrics_resp_headers_filter => fun((cowboy:http_headers()) -> cowboy:http_headers()), - middlewares => [module()], - preface_timeout => timeout(), - proxy_header => boolean(), - sendfile => boolean(), - settings_timeout => timeout(), - shutdown_timeout => timeout(), - stream_handlers => [module()], - stream_window_data_threshold => 0..16#7fffffff, - stream_window_margin_size => 0..16#7fffffff, - stream_window_update_threshold => 0..16#7fffffff, - tracer_callback => cowboy_tracer_h:tracer_callback(), - tracer_flags => [atom()], - tracer_match_specs => cowboy_tracer_h:tracer_match_specs(), - %% Open ended because configured stream handlers might add options. - _ => _ -}. --export_type([opts/0]). - --record(stream, { - %% Whether the stream is currently stopping. - status = running :: running | stopping, - - %% Flow requested for this stream. - flow = 0 :: non_neg_integer(), - - %% Stream state. - state :: {module, any()} -}). - --record(state, { - parent = undefined :: pid(), - ref :: ranch:ref(), - socket = undefined :: inet:socket(), - transport :: module(), - proxy_header :: undefined | ranch_proxy_header:proxy_info(), - opts = #{} :: opts(), - - %% Timer for idle_timeout. - timer = undefined :: undefined | reference(), - - %% Remote address and port for the connection. - peer = undefined :: {inet:ip_address(), inet:port_number()}, - - %% Local address and port for the connection. - sock = undefined :: {inet:ip_address(), inet:port_number()}, - - %% Client certificate (TLS only). - cert :: undefined | binary(), - - %% HTTP/2 state machine. - http2_status :: sequence | settings | upgrade | connected | closing, - http2_machine :: cow_http2_machine:http2_machine(), - - %% HTTP/2 frame rate flood protection. - frame_rate_num :: undefined | pos_integer(), - frame_rate_time :: undefined | integer(), - - %% HTTP/2 reset stream flood protection. - reset_rate_num :: undefined | pos_integer(), - reset_rate_time :: undefined | integer(), - - %% Flow requested for all streams. - flow = 0 :: non_neg_integer(), - - %% Currently active HTTP/2 streams. Streams may be initiated either - %% by the client or by the server through PUSH_PROMISE frames. - streams = #{} :: #{cow_http2:streamid() => #stream{}}, - - %% Streams can spawn zero or more children which are then managed - %% by this module if operating as a supervisor. - children = cowboy_children:init() :: cowboy_children:children() -}). - --spec init(pid(), ranch:ref(), inet:socket(), module(), - ranch_proxy_header:proxy_info() | undefined, cowboy:opts()) -> ok. -init(Parent, Ref, Socket, Transport, ProxyHeader, Opts) -> - Peer0 = Transport:peername(Socket), - Sock0 = Transport:sockname(Socket), - Cert1 = case Transport:name() of - ssl -> - case ssl:peercert(Socket) of - {error, no_peercert} -> - {ok, undefined}; - Cert0 -> - Cert0 - end; - _ -> - {ok, undefined} - end, - case {Peer0, Sock0, Cert1} of - {{ok, Peer}, {ok, Sock}, {ok, Cert}} -> - init(Parent, Ref, Socket, Transport, ProxyHeader, Opts, Peer, Sock, Cert, <<>>); - {{error, Reason}, _, _} -> - terminate(undefined, {socket_error, Reason, - 'A socket error occurred when retrieving the peer name.'}); - {_, {error, Reason}, _} -> - terminate(undefined, {socket_error, Reason, - 'A socket error occurred when retrieving the sock name.'}); - {_, _, {error, Reason}} -> - terminate(undefined, {socket_error, Reason, - 'A socket error occurred when retrieving the client TLS certificate.'}) - end. - --spec init(pid(), ranch:ref(), inet:socket(), module(), - ranch_proxy_header:proxy_info() | undefined, cowboy:opts(), - {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()}, - binary() | undefined, binary()) -> ok. -init(Parent, Ref, Socket, Transport, ProxyHeader, Opts, Peer, Sock, Cert, Buffer) -> - {ok, Preface, HTTP2Machine} = cow_http2_machine:init(server, Opts), - State = set_timeout(init_rate_limiting(#state{parent=Parent, ref=Ref, socket=Socket, - transport=Transport, proxy_header=ProxyHeader, - opts=Opts, peer=Peer, sock=Sock, cert=Cert, - http2_status=sequence, http2_machine=HTTP2Machine})), - Transport:send(Socket, Preface), - case Buffer of - <<>> -> loop(State, Buffer); - _ -> parse(State, Buffer) - end. - -init_rate_limiting(State=#state{opts=Opts}) -> - {FrameRateNum, FrameRatePeriod} = maps:get(max_received_frame_rate, Opts, {1000, 10000}), - {ResetRateNum, ResetRatePeriod} = maps:get(max_reset_stream_rate, Opts, {10, 10000}), - CurrentTime = erlang:monotonic_time(millisecond), - State#state{ - frame_rate_num=FrameRateNum, frame_rate_time=add_period(CurrentTime, FrameRatePeriod), - reset_rate_num=ResetRateNum, reset_rate_time=add_period(CurrentTime, ResetRatePeriod) - }. - -add_period(_, infinity) -> infinity; -add_period(Time, Period) -> Time + Period. - -%% @todo Add an argument for the request body. --spec init(pid(), ranch:ref(), inet:socket(), module(), - ranch_proxy_header:proxy_info() | undefined, cowboy:opts(), - {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()}, - binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> ok. -init(Parent, Ref, Socket, Transport, ProxyHeader, Opts, Peer, Sock, Cert, Buffer, - _Settings, Req=#{method := Method}) -> - {ok, Preface, HTTP2Machine0} = cow_http2_machine:init(server, Opts), - {ok, StreamID, HTTP2Machine} - = cow_http2_machine:init_upgrade_stream(Method, HTTP2Machine0), - State0 = #state{parent=Parent, ref=Ref, socket=Socket, - transport=Transport, proxy_header=ProxyHeader, - opts=Opts, peer=Peer, sock=Sock, cert=Cert, - http2_status=upgrade, http2_machine=HTTP2Machine}, - State1 = headers_frame(State0#state{ - http2_machine=HTTP2Machine}, StreamID, Req), - %% We assume that the upgrade will be applied. A stream handler - %% must not prevent the normal operations of the server. - State2 = info(State1, 1, {switch_protocol, #{ - <<"connection">> => <<"Upgrade">>, - <<"upgrade">> => <<"h2c">> - }, ?MODULE, undefined}), %% @todo undefined or #{}? - State = set_timeout(init_rate_limiting(State2#state{http2_status=sequence})), - Transport:send(Socket, Preface), - case Buffer of - <<>> -> loop(State, Buffer); - _ -> parse(State, Buffer) - end. - -loop(State=#state{parent=Parent, socket=Socket, transport=Transport, - opts=Opts, timer=TimerRef, children=Children}, Buffer) -> - %% @todo This should only be called when data was read. - Transport:setopts(Socket, [{active, once}]), - Messages = Transport:messages(), - InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000), - receive - %% Socket messages. - {OK, Socket, Data} when OK =:= element(1, Messages) -> - parse(set_timeout(State), << Buffer/binary, Data/binary >>); - {Closed, Socket} when Closed =:= element(2, Messages) -> - terminate(State, {socket_error, closed, 'The socket has been closed.'}); - {Error, Socket, Reason} when Error =:= element(3, Messages) -> - terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'}); - %% System messages. - {'EXIT', Parent, Reason} -> - %% @todo Graceful shutdown here as well? - terminate(State, {stop, {exit, Reason}, 'Parent process terminated.'}); - {system, From, Request} -> - sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer}); - %% Timeouts. - {timeout, TimerRef, idle_timeout} -> - terminate(State, {stop, timeout, - 'Connection idle longer than configuration allows.'}); - {timeout, Ref, {shutdown, Pid}} -> - cowboy_children:shutdown_timeout(Children, Ref, Pid), - loop(State, Buffer); - {timeout, TRef, {cow_http2_machine, Name}} -> - loop(timeout(State, Name, TRef), Buffer); - %% Messages pertaining to a stream. - {{Pid, StreamID}, Msg} when Pid =:= self() -> - loop(info(State, StreamID, Msg), Buffer); - %% Exit signal from children. - Msg = {'EXIT', Pid, _} -> - loop(down(State, Pid, Msg), Buffer); - %% Calls from supervisor module. - {'$gen_call', From, Call} -> - cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE), - loop(State, Buffer); - Msg -> - cowboy:log(warning, "Received stray message ~p.", [Msg], Opts), - loop(State, Buffer) - after InactivityTimeout -> - terminate(State, {internal_error, timeout, 'No message or data received before timeout.'}) - end. - -set_timeout(State=#state{opts=Opts, timer=TimerRef0}) -> - ok = case TimerRef0 of - undefined -> ok; - _ -> erlang:cancel_timer(TimerRef0, [{async, true}, {info, false}]) - end, - TimerRef = case maps:get(idle_timeout, Opts, 60000) of - infinity -> undefined; - Timeout -> erlang:start_timer(Timeout, self(), idle_timeout) - end, - State#state{timer=TimerRef}. - -%% HTTP/2 protocol parsing. - -parse(State=#state{http2_status=sequence}, Data) -> - case cow_http2:parse_sequence(Data) of - {ok, Rest} -> - parse(State#state{http2_status=settings}, Rest); - more -> - loop(State, Data); - Error = {connection_error, _, _} -> - terminate(State, Error) - end; -parse(State=#state{http2_status=Status, http2_machine=HTTP2Machine, streams=Streams}, Data) -> - MaxFrameSize = cow_http2_machine:get_local_setting(max_frame_size, HTTP2Machine), - case cow_http2:parse(Data, MaxFrameSize) of - {ok, Frame, Rest} -> - parse(frame_rate(State, Frame), Rest); - {ignore, Rest} -> - parse(frame_rate(State, ignore), Rest); - {stream_error, StreamID, Reason, Human, Rest} -> - parse(reset_stream(State, StreamID, {stream_error, Reason, Human}), Rest); - Error = {connection_error, _, _} -> - terminate(State, Error); - %% Terminate the connection if we are closing and all streams have completed. - more when Status =:= closing, Streams =:= #{} -> - terminate(State, {stop, normal, 'The connection is going away.'}); - more -> - loop(State, Data) - end. - -%% Frame rate flood protection. - -frame_rate(State0=#state{opts=Opts, frame_rate_num=Num0, frame_rate_time=Time}, Frame) -> - {Result, State} = case Num0 - 1 of - 0 -> - CurrentTime = erlang:monotonic_time(millisecond), - if - CurrentTime < Time -> - {error, State0}; - true -> - %% When the option has a period of infinity we cannot reach this clause. - {Num, Period} = maps:get(max_received_frame_rate, Opts, {1000, 10000}), - {ok, State0#state{frame_rate_num=Num, frame_rate_time=CurrentTime + Period}} - end; - Num -> - {ok, State0#state{frame_rate_num=Num}} - end, - case {Result, Frame} of - {ok, ignore} -> ignored_frame(State); - {ok, _} -> frame(State, Frame); - {error, _} -> terminate(State, {connection_error, enhance_your_calm, - 'Frame rate larger than configuration allows. Flood? (CVE-2019-9512, CVE-2019-9515, CVE-2019-9518)'}) - end. - -%% Frames received. - -%% We do nothing when receiving a lingering DATA frame. -%% We already removed the stream flow from the connection -%% flow and are therefore already accounting for the window -%% being reduced by these frames. -frame(State=#state{http2_machine=HTTP2Machine0}, Frame) -> - case cow_http2_machine:frame(Frame, HTTP2Machine0) of - {ok, HTTP2Machine} -> - maybe_ack(State#state{http2_machine=HTTP2Machine}, Frame); - {ok, {data, StreamID, IsFin, Data}, HTTP2Machine} -> - data_frame(State#state{http2_machine=HTTP2Machine}, StreamID, IsFin, Data); - {ok, {headers, StreamID, IsFin, Headers, PseudoHeaders, BodyLen}, HTTP2Machine} -> - headers_frame(State#state{http2_machine=HTTP2Machine}, - StreamID, IsFin, Headers, PseudoHeaders, BodyLen); - {ok, {trailers, _StreamID, _Trailers}, HTTP2Machine} -> - %% @todo Propagate trailers. - State#state{http2_machine=HTTP2Machine}; - {ok, {rst_stream, StreamID, Reason}, HTTP2Machine} -> - rst_stream_frame(State#state{http2_machine=HTTP2Machine}, StreamID, Reason); - {ok, GoAway={goaway, _, _, _}, HTTP2Machine} -> - goaway(State#state{http2_machine=HTTP2Machine}, GoAway); - {send, SendData, HTTP2Machine} -> - %% We may need to send an alarm for each of the streams sending data. - lists:foldl( - fun({StreamID, _, _}, S) -> maybe_send_data_alarm(S, HTTP2Machine0, StreamID) end, - send_data(maybe_ack(State#state{http2_machine=HTTP2Machine}, Frame), SendData), - SendData); - {error, {stream_error, StreamID, Reason, Human}, HTTP2Machine} -> - reset_stream(State#state{http2_machine=HTTP2Machine}, - StreamID, {stream_error, Reason, Human}); - {error, Error={connection_error, _, _}, HTTP2Machine} -> - terminate(State#state{http2_machine=HTTP2Machine}, Error) - end. - -%% We use this opportunity to mark the HTTP/2 status as connected -%% if we were still waiting for a SETTINGS frame. -maybe_ack(State=#state{http2_status=settings}, Frame) -> - maybe_ack(State#state{http2_status=connected}, Frame); -maybe_ack(State=#state{socket=Socket, transport=Transport}, Frame) -> - case Frame of - {settings, _} -> Transport:send(Socket, cow_http2:settings_ack()); - {ping, Opaque} -> Transport:send(Socket, cow_http2:ping_ack(Opaque)); - _ -> ok - end, - State. - -data_frame(State0=#state{opts=Opts, flow=Flow, streams=Streams}, StreamID, IsFin, Data) -> - case Streams of - #{StreamID := Stream=#stream{status=running, flow=StreamFlow, state=StreamState0}} -> - try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of - {Commands, StreamState} -> - %% Remove the amount of data received from the flow. - %% We may receive more data than we requested. We ensure - %% that the flow value doesn't go lower than 0. - Size = byte_size(Data), - State = update_window(State0#state{flow=max(0, Flow - Size), - streams=Streams#{StreamID => Stream#stream{ - flow=max(0, StreamFlow - Size), state=StreamState}}}, - StreamID), - commands(State, StreamID, Commands) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(data, - [StreamID, IsFin, Data, StreamState0], - Class, Exception, erlang:get_stacktrace()), Opts), - reset_stream(State0, StreamID, {internal_error, {Class, Exception}, - 'Unhandled exception in cowboy_stream:data/4.'}) - end; - %% We ignore DATA frames for streams that are stopping. - #{} -> - State0 - end. - -headers_frame(State, StreamID, IsFin, Headers, - PseudoHeaders=#{method := <<"CONNECT">>}, _) - when map_size(PseudoHeaders) =:= 2 -> - early_error(State, StreamID, IsFin, Headers, PseudoHeaders, 501, - 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)'); -headers_frame(State, StreamID, IsFin, Headers, - PseudoHeaders=#{method := <<"TRACE">>}, _) -> - early_error(State, StreamID, IsFin, Headers, PseudoHeaders, 501, - 'The TRACE method is currently not implemented. (RFC7231 4.3.8)'); -headers_frame(State, StreamID, IsFin, Headers, PseudoHeaders=#{authority := Authority}, BodyLen) -> - headers_frame_parse_host(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority); -headers_frame(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen) -> - case lists:keyfind(<<"host">>, 1, Headers) of - {_, Authority} -> - headers_frame_parse_host(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority); - _ -> - reset_stream(State, StreamID, {stream_error, protocol_error, - 'Requests translated from HTTP/1.1 must include a host header. (RFC7540 8.1.2.3, RFC7230 5.4)'}) - end. - -headers_frame_parse_host(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert, proxy_header=ProxyHeader}, - StreamID, IsFin, Headers, PseudoHeaders=#{method := Method, scheme := Scheme, path := PathWithQs}, - BodyLen, Authority) -> - try cow_http_hd:parse_host(Authority) of - {Host, Port0} -> - Port = ensure_port(Scheme, Port0), - try cow_http:parse_fullpath(PathWithQs) of - {<<>>, _} -> - reset_stream(State, StreamID, {stream_error, protocol_error, - 'The path component must not be empty. (RFC7540 8.1.2.3)'}); - {Path, Qs} -> - Req0 = #{ - ref => Ref, - pid => self(), - streamid => StreamID, - peer => Peer, - sock => Sock, - cert => Cert, - method => Method, - scheme => Scheme, - host => Host, - port => Port, - path => Path, - qs => Qs, - version => 'HTTP/2', - headers => headers_to_map(Headers, #{}), - has_body => IsFin =:= nofin, - body_length => BodyLen - }, - %% We add the PROXY header information if any. - Req1 = case ProxyHeader of - undefined -> Req0; - _ -> Req0#{proxy_header => ProxyHeader} - end, - %% We add the protocol information for extended CONNECTs. - Req = case PseudoHeaders of - #{protocol := Protocol} -> Req1#{protocol => Protocol}; - _ -> Req1 - end, - headers_frame(State, StreamID, Req) - catch _:_ -> - reset_stream(State, StreamID, {stream_error, protocol_error, - 'The :path pseudo-header is invalid. (RFC7540 8.1.2.3)'}) - end - catch _:_ -> - reset_stream(State, StreamID, {stream_error, protocol_error, - 'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)'}) - end. - -ensure_port(<<"http">>, undefined) -> 80; -ensure_port(<<"https">>, undefined) -> 443; -ensure_port(_, Port) -> Port. - -%% This function is necessary to properly handle duplicate headers -%% and the special-case cookie header. -headers_to_map([], Acc) -> - Acc; -headers_to_map([{Name, Value}|Tail], Acc0) -> - Acc = case Acc0 of - %% The cookie header does not use proper HTTP header lists. - #{Name := Value0} when Name =:= <<"cookie">> -> - Acc0#{Name => << Value0/binary, "; ", Value/binary >>}; - #{Name := Value0} -> - Acc0#{Name => << Value0/binary, ", ", Value/binary >>}; - _ -> - Acc0#{Name => Value} - end, - headers_to_map(Tail, Acc). - -headers_frame(State=#state{opts=Opts, streams=Streams}, StreamID, Req) -> - try cowboy_stream:init(StreamID, Req, Opts) of - {Commands, StreamState} -> - commands(State#state{ - streams=Streams#{StreamID => #stream{state=StreamState}}}, - StreamID, Commands) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(init, - [StreamID, Req, Opts], - Class, Exception, erlang:get_stacktrace()), Opts), - reset_stream(State, StreamID, {internal_error, {Class, Exception}, - 'Unhandled exception in cowboy_stream:init/3.'}) - end. - -early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer}, - StreamID, _IsFin, Headers, #{method := Method}, - StatusCode0, HumanReadable) -> - %% We automatically terminate the stream but it is not an error - %% per se (at least not in the first implementation). - Reason = {stream_error, no_error, HumanReadable}, - %% The partial Req is minimal for now. We only have one case - %% where it can be called (when a method is completely disabled). - %% @todo Fill in the other elements. - PartialReq = #{ - ref => Ref, - peer => Peer, - method => Method, - headers => headers_to_map(Headers, #{}) - }, - Resp = {response, StatusCode0, RespHeaders0=#{<<"content-length">> => <<"0">>}, <<>>}, - try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of - {response, StatusCode, RespHeaders, RespBody} -> - send_response(State0, StreamID, StatusCode, RespHeaders, RespBody) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(early_error, - [StreamID, Reason, PartialReq, Resp, Opts], - Class, Exception, erlang:get_stacktrace()), Opts), - %% We still need to send an error response, so send what we initially - %% wanted to send. It's better than nothing. - send_headers(State0, StreamID, fin, StatusCode0, RespHeaders0) - end. - -rst_stream_frame(State=#state{streams=Streams0, children=Children0}, StreamID, Reason) -> - case maps:take(StreamID, Streams0) of - {#stream{state=StreamState}, Streams} -> - terminate_stream_handler(State, StreamID, Reason, StreamState), - Children = cowboy_children:shutdown(Children0, StreamID), - State#state{streams=Streams, children=Children}; - error -> - State - end. - -ignored_frame(State=#state{http2_machine=HTTP2Machine0}) -> - case cow_http2_machine:ignored_frame(HTTP2Machine0) of - {ok, HTTP2Machine} -> - State#state{http2_machine=HTTP2Machine}; - {error, Error={connection_error, _, _}, HTTP2Machine} -> - terminate(State#state{http2_machine=HTTP2Machine}, Error) - end. - -%% HTTP/2 timeouts. - -timeout(State=#state{http2_machine=HTTP2Machine0}, Name, TRef) -> - case cow_http2_machine:timeout(Name, TRef, HTTP2Machine0) of - {ok, HTTP2Machine} -> - State#state{http2_machine=HTTP2Machine}; - {error, Error={connection_error, _, _}, HTTP2Machine} -> - terminate(State#state{http2_machine=HTTP2Machine}, Error) - end. - -%% Erlang messages. - -down(State=#state{opts=Opts, children=Children0}, Pid, Msg) -> - case cowboy_children:down(Children0, Pid) of - %% The stream was terminated already. - {ok, undefined, Children} -> - State#state{children=Children}; - %% The stream is still running. - {ok, StreamID, Children} -> - info(State#state{children=Children}, StreamID, Msg); - %% The process was unknown. - error -> - cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n", - [Msg, Pid], Opts), - State - end. - -info(State=#state{opts=Opts, http2_machine=HTTP2Machine, streams=Streams}, StreamID, Msg) -> - case Streams of - #{StreamID := Stream=#stream{state=StreamState0}} -> - try cowboy_stream:info(StreamID, Msg, StreamState0) of - {Commands, StreamState} -> - commands(State#state{streams=Streams#{StreamID => Stream#stream{state=StreamState}}}, - StreamID, Commands) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(info, - [StreamID, Msg, StreamState0], - Class, Exception, erlang:get_stacktrace()), Opts), - reset_stream(State, StreamID, {internal_error, {Class, Exception}, - 'Unhandled exception in cowboy_stream:info/3.'}) - end; - _ -> - case cow_http2_machine:is_lingering_stream(StreamID, HTTP2Machine) of - true -> - ok; - false -> - cowboy:log(warning, "Received message ~p for unknown stream ~p.", - [Msg, StreamID], Opts) - end, - State - end. - -%% Stream handler commands. -%% -%% @todo Kill the stream if it tries to send a response, headers, -%% data or push promise when the stream is closed or half-closed. - -commands(State, _, []) -> - State; -%% Error responses are sent only if a response wasn't sent already. -commands(State=#state{http2_machine=HTTP2Machine}, StreamID, - [{error_response, StatusCode, Headers, Body}|Tail]) -> - case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine) of - {ok, idle, _} -> - commands(State, StreamID, [{response, StatusCode, Headers, Body}|Tail]); - _ -> - commands(State, StreamID, Tail) - end; -%% Send an informational response. -commands(State0, StreamID, [{inform, StatusCode, Headers}|Tail]) -> - State = send_headers(State0, StreamID, idle, StatusCode, Headers), - commands(State, StreamID, Tail); -%% Send response headers. -commands(State0, StreamID, [{response, StatusCode, Headers, Body}|Tail]) -> - State = send_response(State0, StreamID, StatusCode, Headers, Body), - commands(State, StreamID, Tail); -%% Send response headers. -commands(State0, StreamID, [{headers, StatusCode, Headers}|Tail]) -> - State = send_headers(State0, StreamID, nofin, StatusCode, Headers), - commands(State, StreamID, Tail); -%% Send a response body chunk. -commands(State0, StreamID, [{data, IsFin, Data}|Tail]) -> - State = maybe_send_data(State0, StreamID, IsFin, Data), - commands(State, StreamID, Tail); -%% Send trailers. -commands(State0, StreamID, [{trailers, Trailers}|Tail]) -> - State = maybe_send_data(State0, StreamID, fin, {trailers, maps:to_list(Trailers)}), - commands(State, StreamID, Tail); -%% Send a push promise. -%% -%% @todo Responses sent as a result of a push_promise request -%% must not send push_promise frames themselves. -%% -%% @todo We should not send push_promise frames when we are -%% in the closing http2_status. -commands(State0=#state{socket=Socket, transport=Transport, http2_machine=HTTP2Machine0}, - StreamID, [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) -> - Authority = case {Scheme, Port} of - {<<"http">>, 80} -> Host; - {<<"https">>, 443} -> Host; - _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)]) - end, - PathWithQs = iolist_to_binary(case Qs of - <<>> -> Path; - _ -> [Path, $?, Qs] - end), - PseudoHeaders = #{ - method => Method, - scheme => Scheme, - authority => Authority, - path => PathWithQs - }, - %% We need to make sure the header value is binary before we can - %% create the Req object, as it expects them to be flat. - Headers = maps:to_list(maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0)), - State = case cow_http2_machine:prepare_push_promise(StreamID, HTTP2Machine0, - PseudoHeaders, Headers) of - {ok, PromisedStreamID, HeaderBlock, HTTP2Machine} -> - Transport:send(Socket, cow_http2:push_promise( - StreamID, PromisedStreamID, HeaderBlock)), - headers_frame(State0#state{http2_machine=HTTP2Machine}, - PromisedStreamID, fin, Headers, PseudoHeaders, 0); - {error, no_push} -> - State0 - end, - commands(State, StreamID, Tail); -%% Read the request body. -commands(State0=#state{flow=Flow, streams=Streams}, StreamID, [{flow, Size}|Tail]) -> - #{StreamID := Stream=#stream{flow=StreamFlow}} = Streams, - State = update_window(State0#state{flow=Flow + Size, - streams=Streams#{StreamID => Stream#stream{flow=StreamFlow + Size}}}, - StreamID), - commands(State, StreamID, Tail); -%% Supervise a child process. -commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) -> - commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)}, - StreamID, Tail); -%% Error handling. -commands(State, StreamID, [Error = {internal_error, _, _}|_Tail]) -> - %% @todo Do we want to run the commands after an internal_error? - %% @todo Do we even allow commands after? - %% @todo Only reset when the stream still exists. - reset_stream(State, StreamID, Error); -%% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself. -commands(State=#state{socket=Socket, transport=Transport, http2_status=upgrade}, - StreamID, [{switch_protocol, Headers, ?MODULE, _}|Tail]) -> - %% @todo This 101 response needs to be passed through stream handlers. - Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))), - commands(State, StreamID, Tail); -%% Use a different protocol within the stream (CONNECT :protocol). -%% @todo Make sure we error out when the feature is disabled. -commands(State0, StreamID, [{switch_protocol, Headers, _Mod, _ModState}|Tail]) -> - State = info(State0, StreamID, {headers, 200, Headers}), - commands(State, StreamID, Tail); -%% Set options dynamically. -commands(State, StreamID, [{set_options, _Opts}|Tail]) -> - commands(State, StreamID, Tail); -commands(State, StreamID, [stop|_Tail]) -> - %% @todo Do we want to run the commands after a stop? - %% @todo Do we even allow commands after? - stop_stream(State, StreamID); -%% Log event. -commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) -> - cowboy:log(Log, Opts), - commands(State, StreamID, Tail). - -%% Tentatively update the window after the flow was updated. - -update_window(State=#state{socket=Socket, transport=Transport, - http2_machine=HTTP2Machine0, flow=Flow, streams=Streams}, StreamID) -> - #{StreamID := #stream{flow=StreamFlow}} = Streams, - {Data1, HTTP2Machine2} = case cow_http2_machine:ensure_window(Flow, HTTP2Machine0) of - ok -> {<<>>, HTTP2Machine0}; - {ok, Increment1, HTTP2Machine1} -> {cow_http2:window_update(Increment1), HTTP2Machine1} - end, - {Data2, HTTP2Machine} = case cow_http2_machine:ensure_window(StreamID, StreamFlow, HTTP2Machine2) of - ok -> {<<>>, HTTP2Machine2}; - {ok, Increment2, HTTP2Machine3} -> {cow_http2:window_update(StreamID, Increment2), HTTP2Machine3} - end, - case {Data1, Data2} of - {<<>>, <<>>} -> ok; - _ -> Transport:send(Socket, [Data1, Data2]) - end, - State#state{http2_machine=HTTP2Machine}. - -%% Send the response, trailers or data. - -send_response(State0, StreamID, StatusCode, Headers, Body) -> - Size = case Body of - {sendfile, _, Bytes, _} -> Bytes; - _ -> iolist_size(Body) - end, - case Size of - 0 -> - State = send_headers(State0, StreamID, fin, StatusCode, Headers), - maybe_terminate_stream(State, StreamID, fin); - _ -> - State = send_headers(State0, StreamID, nofin, StatusCode, Headers), - maybe_send_data(State, StreamID, fin, Body) - end. - -send_headers(State=#state{socket=Socket, transport=Transport, - http2_machine=HTTP2Machine0}, StreamID, IsFin0, StatusCode, Headers) -> - {ok, IsFin, HeaderBlock, HTTP2Machine} - = cow_http2_machine:prepare_headers(StreamID, HTTP2Machine0, IsFin0, - #{status => cow_http:status_to_integer(StatusCode)}, - headers_to_list(Headers)), - Transport:send(Socket, cow_http2:headers(StreamID, IsFin, HeaderBlock)), - State#state{http2_machine=HTTP2Machine}. - -%% The set-cookie header is special; we can only send one cookie per header. -headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) -> - Headers = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)), - Headers ++ [{<<"set-cookie">>, Value} || Value <- SetCookies]; -headers_to_list(Headers) -> - maps:to_list(Headers). - -maybe_send_data(State0=#state{http2_machine=HTTP2Machine0}, StreamID, IsFin, Data0) -> - Data = case is_tuple(Data0) of - false -> {data, Data0}; - true -> Data0 - end, - case cow_http2_machine:send_or_queue_data(StreamID, HTTP2Machine0, IsFin, Data) of - {ok, HTTP2Machine} -> - maybe_send_data_alarm(State0#state{http2_machine=HTTP2Machine}, HTTP2Machine0, StreamID); - {send, SendData, HTTP2Machine} -> - State = #state{http2_status=Status, streams=Streams} - = send_data(State0#state{http2_machine=HTTP2Machine}, SendData), - %% Terminate the connection if we are closing and all streams have completed. - if - Status =:= closing, Streams =:= #{} -> - terminate(State, {stop, normal, 'The connection is going away.'}); - true -> - maybe_send_data_alarm(State, HTTP2Machine0, StreamID) - end - end. - -send_data(State, []) -> - State; -send_data(State0, [{StreamID, IsFin, SendData}|Tail]) -> - State = send_data(State0, StreamID, IsFin, SendData), - send_data(State, Tail). - -send_data(State0, StreamID, IsFin, [Data]) -> - State = send_data_frame(State0, StreamID, IsFin, Data), - maybe_terminate_stream(State, StreamID, IsFin); -send_data(State0, StreamID, IsFin, [Data|Tail]) -> - State = send_data_frame(State0, StreamID, nofin, Data), - send_data(State, StreamID, IsFin, Tail). - -send_data_frame(State=#state{socket=Socket, transport=Transport}, - StreamID, IsFin, {data, Data}) -> - Transport:send(Socket, cow_http2:data(StreamID, IsFin, Data)), - State; -send_data_frame(State=#state{socket=Socket, transport=Transport, opts=Opts}, - StreamID, IsFin, {sendfile, Offset, Bytes, Path}) -> - Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)), - %% When sendfile is disabled we explicitly use the fallback. - _ = case maps:get(sendfile, Opts, true) of - true -> Transport:sendfile(Socket, Path, Offset, Bytes); - false -> ranch_transport:sendfile(Transport, Socket, Path, Offset, Bytes, []) - end, - State; -%% The stream is terminated in cow_http2_machine:prepare_trailers. -send_data_frame(State=#state{socket=Socket, transport=Transport, - http2_machine=HTTP2Machine0}, StreamID, nofin, {trailers, Trailers}) -> - {ok, HeaderBlock, HTTP2Machine} - = cow_http2_machine:prepare_trailers(StreamID, HTTP2Machine0, Trailers), - Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)), - State#state{http2_machine=HTTP2Machine}. - -%% After we have sent or queued data we may need to set or clear an alarm. -%% We do this by comparing the HTTP2Machine buffer state before/after for -%% the relevant streams. -maybe_send_data_alarm(State=#state{opts=Opts, http2_machine=HTTP2Machine}, HTTP2Machine0, StreamID) -> - ConnBufferSizeBefore = cow_http2_machine:get_connection_local_buffer_size(HTTP2Machine0), - ConnBufferSizeAfter = cow_http2_machine:get_connection_local_buffer_size(HTTP2Machine), - {ok, StreamBufferSizeBefore} = cow_http2_machine:get_stream_local_buffer_size(StreamID, HTTP2Machine0), - %% When the stream ends up closed after it finished sending data, - %% we do not want to trigger an alarm. We act as if the buffer - %% size did not change. - StreamBufferSizeAfter = case cow_http2_machine:get_stream_local_buffer_size(StreamID, HTTP2Machine) of - {ok, BSA} -> BSA; - {error, closed} -> StreamBufferSizeBefore - end, - MaxConnBufferSize = maps:get(max_connection_buffer_size, Opts, 16000000), - MaxStreamBufferSize = maps:get(max_stream_buffer_size, Opts, 8000000), - %% I do not want to document these internal events yet. I am not yet - %% convinced it should be {alarm, Name, on|off} and not {internal_event, E} - %% or something else entirely. Though alarms are probably right. - if - ConnBufferSizeBefore >= MaxConnBufferSize, ConnBufferSizeAfter < MaxConnBufferSize -> - connection_alarm(State, connection_buffer_full, off); - ConnBufferSizeBefore < MaxConnBufferSize, ConnBufferSizeAfter >= MaxConnBufferSize -> - connection_alarm(State, connection_buffer_full, on); - StreamBufferSizeBefore >= MaxStreamBufferSize, StreamBufferSizeAfter < MaxStreamBufferSize -> - stream_alarm(State, StreamID, stream_buffer_full, off); - StreamBufferSizeBefore < MaxStreamBufferSize, StreamBufferSizeAfter >= MaxStreamBufferSize -> - stream_alarm(State, StreamID, stream_buffer_full, on); - true -> - State - end. - -connection_alarm(State0=#state{streams=Streams}, Name, Value) -> - lists:foldl(fun(StreamID, State) -> - stream_alarm(State, StreamID, Name, Value) - end, State0, maps:keys(Streams)). - -stream_alarm(State, StreamID, Name, Value) -> - info(State, StreamID, {alarm, Name, Value}). - -%% Terminate a stream or the connection. - -%% We may have to cancel streams even if we receive multiple -%% GOAWAY frames as the LastStreamID value may be lower than -%% the one previously received. -goaway(State0=#state{socket=Socket, transport=Transport, http2_machine=HTTP2Machine, - http2_status=Status, streams=Streams0}, {goaway, LastStreamID, Reason, _}) - when Status =:= connected; Status =:= closing -> - Streams = goaway_streams(State0, maps:to_list(Streams0), LastStreamID, - {stop, {goaway, Reason}, 'The connection is going away.'}, []), - State = State0#state{streams=maps:from_list(Streams)}, - case Status of - connected -> - Transport:send(Socket, cow_http2:goaway( - cow_http2_machine:get_last_streamid(HTTP2Machine), - no_error, <<>>)), - State#state{http2_status=closing}; - _ -> - State - end; -%% We terminate the connection immediately if it hasn't fully been initialized. -goaway(State, {goaway, _, Reason, _}) -> - terminate(State, {stop, {goaway, Reason}, 'The connection is going away.'}). - -%% Cancel client-initiated streams that are above LastStreamID. -goaway_streams(_, [], _, _, Acc) -> - Acc; -goaway_streams(State, [{StreamID, #stream{state=StreamState}}|Tail], LastStreamID, Reason, Acc) - when StreamID > LastStreamID, (StreamID rem 2) =:= 0 -> - terminate_stream_handler(State, StreamID, Reason, StreamState), - goaway_streams(State, Tail, LastStreamID, Reason, Acc); -goaway_streams(State, [Stream|Tail], LastStreamID, Reason, Acc) -> - goaway_streams(State, Tail, LastStreamID, Reason, [Stream|Acc]). - --spec terminate(#state{}, _) -> no_return(). -terminate(undefined, Reason) -> - exit({shutdown, Reason}); -terminate(State=#state{socket=Socket, transport=Transport, http2_status=Status, - http2_machine=HTTP2Machine, streams=Streams, children=Children}, Reason) - when Status =:= connected; Status =:= closing -> - %% @todo We might want to optionally send the Reason value - %% as debug data in the GOAWAY frame here. Perhaps more. - case Status of - connected -> - Transport:send(Socket, cow_http2:goaway( - cow_http2_machine:get_last_streamid(HTTP2Machine), - terminate_reason(Reason), <<>>)); - %% We already sent the GOAWAY frame. - closing -> - ok - end, - terminate_all_streams(State, maps:to_list(Streams), Reason), - cowboy_children:terminate(Children), - Transport:close(Socket), - exit({shutdown, Reason}); -terminate(#state{socket=Socket, transport=Transport}, Reason) -> - Transport:close(Socket), - exit({shutdown, Reason}). - -terminate_reason({connection_error, Reason, _}) -> Reason; -terminate_reason({stop, _, _}) -> no_error; -terminate_reason({socket_error, _, _}) -> internal_error; -terminate_reason({internal_error, _, _}) -> internal_error. - -terminate_all_streams(_, [], _) -> - ok; -terminate_all_streams(State, [{StreamID, #stream{state=StreamState}}|Tail], Reason) -> - terminate_stream_handler(State, StreamID, Reason, StreamState), - terminate_all_streams(State, Tail, Reason). - -%% @todo Don't send an RST_STREAM if one was already sent. -reset_stream(State0=#state{socket=Socket, transport=Transport, - http2_machine=HTTP2Machine0}, StreamID, Error) -> - Reason = case Error of - {internal_error, _, _} -> internal_error; - {stream_error, Reason0, _} -> Reason0 - end, - Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)), - State1 = case cow_http2_machine:reset_stream(StreamID, HTTP2Machine0) of - {ok, HTTP2Machine} -> - terminate_stream(State0#state{http2_machine=HTTP2Machine}, StreamID, Error); - {error, not_found} -> - terminate_stream(State0, StreamID, Error) - end, - case reset_rate(State1) of - {ok, State} -> - State; - error -> - terminate(State1, {connection_error, enhance_your_calm, - 'Stream reset rate larger than configuration allows. Flood? (CVE-2019-9514)'}) - end. - -reset_rate(State0=#state{opts=Opts, reset_rate_num=Num0, reset_rate_time=Time}) -> - case Num0 - 1 of - 0 -> - CurrentTime = erlang:monotonic_time(millisecond), - if - CurrentTime < Time -> - error; - true -> - %% When the option has a period of infinity we cannot reach this clause. - {Num, Period} = maps:get(max_reset_stream_rate, Opts, {10, 10000}), - {ok, State0#state{reset_rate_num=Num, reset_rate_time=CurrentTime + Period}} - end; - Num -> - {ok, State0#state{reset_rate_num=Num}} - end. - -stop_stream(State=#state{http2_machine=HTTP2Machine}, StreamID) -> - case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine) of - %% When the stream terminates normally (without sending RST_STREAM) - %% and no response was sent, we need to send a proper response back to the client. - %% We delay the termination of the stream until the response is fully sent. - {ok, idle, _} -> - info(stopping(State, StreamID), StreamID, {response, 204, #{}, <<>>}); - %% When a response was sent but not terminated, we need to close the stream. - %% We delay the termination of the stream until the response is fully sent. - {ok, nofin, fin} -> - stopping(State, StreamID); - %% We only send a final DATA frame if there isn't one queued yet. - {ok, nofin, _} -> - info(stopping(State, StreamID), StreamID, {data, fin, <<>>}); - %% When a response was sent fully we can terminate the stream, - %% regardless of the stream being in half-closed or closed state. - _ -> - terminate_stream(State, StreamID) - end. - -stopping(State=#state{streams=Streams}, StreamID) -> - #{StreamID := Stream} = Streams, - State#state{streams=Streams#{StreamID => Stream#stream{status=stopping}}}. - -%% If we finished sending data and the stream is stopping, terminate it. -maybe_terminate_stream(State=#state{streams=Streams}, StreamID, fin) -> - case Streams of - #{StreamID := #stream{status=stopping}} -> - terminate_stream(State, StreamID); - _ -> - State - end; -maybe_terminate_stream(State, _, _) -> - State. - -%% When the stream stops normally without reading the request -%% body fully we need to tell the client to stop sending it. -%% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0) -terminate_stream(State0=#state{socket=Socket, transport=Transport, - http2_machine=HTTP2Machine0}, StreamID) -> - State = case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine0) of - {ok, fin, _} -> - Transport:send(Socket, cow_http2:rst_stream(StreamID, no_error)), - {ok, HTTP2Machine} = cow_http2_machine:reset_stream(StreamID, HTTP2Machine0), - State0#state{http2_machine=HTTP2Machine}; - {error, closed} -> - State0 - end, - terminate_stream(State, StreamID, normal). - -%% We remove the stream flow from the connection flow. Any further -%% data received for this stream is therefore fully contained within -%% the extra window we allocated for this stream. -terminate_stream(State=#state{flow=Flow, streams=Streams0, children=Children0}, StreamID, Reason) -> - case maps:take(StreamID, Streams0) of - {#stream{flow=StreamFlow, state=StreamState}, Streams} -> - terminate_stream_handler(State, StreamID, Reason, StreamState), - Children = cowboy_children:shutdown(Children0, StreamID), - State#state{flow=Flow - StreamFlow, streams=Streams, children=Children}; - error -> - State - end. - -terminate_stream_handler(#state{opts=Opts}, StreamID, Reason, StreamState) -> - try - cowboy_stream:terminate(StreamID, Reason, StreamState) - catch Class:Exception -> - cowboy:log(cowboy_stream:make_error_log(terminate, - [StreamID, Reason, StreamState], - Class, Exception, erlang:get_stacktrace()), Opts) - end. - -%% System callbacks. - --spec system_continue(_, _, {#state{}, binary()}) -> ok. -system_continue(_, _, {State, Buffer}) -> - loop(State, Buffer). - --spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return(). -system_terminate(Reason, _, _, {State, _}) -> - %% @todo Graceful shutdown here as well? - terminate(State, {stop, {exit, Reason}, 'sys:terminate/2,3 was called.'}). - --spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}. -system_code_change(Misc, _, _, _) -> - {ok, Misc}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_loop.erl b/_build/emqx/lib/cowboy/src/cowboy_loop.erl deleted file mode 100644 index 603c9395ab..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_loop.erl +++ /dev/null @@ -1,113 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_loop). --behaviour(cowboy_sub_protocol). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([upgrade/4]). --export([upgrade/5]). --export([loop/4]). - --export([system_continue/3]). --export([system_terminate/4]). --export([system_code_change/4]). - --callback init(Req, any()) - -> {ok | module(), Req, any()} - | {module(), Req, any(), any()} - when Req::cowboy_req:req(). - --callback info(any(), Req, State) - -> {ok, Req, State} - | {ok, Req, State, hibernate} - | {stop, Req, State} - when Req::cowboy_req:req(), State::any(). - --callback terminate(any(), cowboy_req:req(), any()) -> ok. --optional_callbacks([terminate/3]). - --spec upgrade(Req, Env, module(), any()) - -> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -upgrade(Req, Env, Handler, HandlerState) -> - loop(Req, Env, Handler, HandlerState). - --spec upgrade(Req, Env, module(), any(), hibernate) - -> {suspend, ?MODULE, loop, [any()]} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -upgrade(Req, Env, Handler, HandlerState, hibernate) -> - suspend(Req, Env, Handler, HandlerState). - --spec loop(Req, Env, module(), any()) - -> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -%% @todo Handle system messages. -loop(Req=#{pid := Parent}, Env, Handler, HandlerState) -> - receive - %% System messages. - {'EXIT', Parent, Reason} -> - terminate(Req, Env, Handler, HandlerState, Reason); - {system, From, Request} -> - sys:handle_system_msg(Request, From, Parent, ?MODULE, [], - {Req, Env, Handler, HandlerState}); - %% Calls from supervisor module. - {'$gen_call', From, Call} -> - cowboy_children:handle_supervisor_call(Call, From, [], ?MODULE), - loop(Req, Env, Handler, HandlerState); - Message -> - call(Req, Env, Handler, HandlerState, Message) - end. - -call(Req0, Env, Handler, HandlerState0, Message) -> - try Handler:info(Message, Req0, HandlerState0) of - {ok, Req, HandlerState} -> - loop(Req, Env, Handler, HandlerState); - {ok, Req, HandlerState, hibernate} -> - suspend(Req, Env, Handler, HandlerState); - {stop, Req, HandlerState} -> - terminate(Req, Env, Handler, HandlerState, stop) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - cowboy_handler:terminate({crash, Class, Reason}, Req0, HandlerState0, Handler), - erlang:raise(Class, Reason, StackTrace) - end. - -suspend(Req, Env, Handler, HandlerState) -> - {suspend, ?MODULE, loop, [Req, Env, Handler, HandlerState]}. - -terminate(Req, Env, Handler, HandlerState, Reason) -> - Result = cowboy_handler:terminate(Reason, Req, HandlerState, Handler), - {ok, Req, Env#{result => Result}}. - -%% System callbacks. - --spec system_continue(_, _, {Req, Env, module(), any()}) - -> {ok, Req, Env} | {suspend, ?MODULE, loop, [any()]} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -system_continue(_, _, {Req, Env, Handler, HandlerState}) -> - loop(Req, Env, Handler, HandlerState). - --spec system_terminate(any(), _, _, {Req, Env, module(), any()}) - -> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -system_terminate(Reason, _, _, {Req, Env, Handler, HandlerState}) -> - terminate(Req, Env, Handler, HandlerState, Reason). - --spec system_code_change(Misc, _, _, _) -> {ok, Misc} - when Misc::{cowboy_req:req(), cowboy_middleware:env(), module(), any()}. -system_code_change(Misc, _, _, _) -> - {ok, Misc}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_metrics_h.erl b/_build/emqx/lib/cowboy/src/cowboy_metrics_h.erl deleted file mode 100644 index 4107aac0a4..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_metrics_h.erl +++ /dev/null @@ -1,331 +0,0 @@ -%% Copyright (c) 2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_metrics_h). --behavior(cowboy_stream). - --export([init/3]). --export([data/4]). --export([info/3]). --export([terminate/3]). --export([early_error/5]). - --type proc_metrics() :: #{pid() => #{ - %% Time at which the process spawned. - spawn := integer(), - - %% Time at which the process exited. - exit => integer(), - - %% Reason for the process exit. - reason => any() -}}. - --type informational_metrics() :: #{ - %% Informational response status. - status := cowboy:http_status(), - - %% Headers sent with the informational response. - headers := cowboy:http_headers(), - - %% Time when the informational response was sent. - time := integer() -}. - --type metrics() :: #{ - %% The identifier for this listener. - ref := ranch:ref(), - - %% The pid for this connection. - pid := pid(), - - %% The streamid also indicates the total number of requests on - %% this connection (StreamID div 2 + 1). - streamid := cowboy_stream:streamid(), - - %% The terminate reason is always useful. - reason := cowboy_stream:reason(), - - %% A filtered Req object or a partial Req object - %% depending on how far the request got to. - req => cowboy_req:req(), - partial_req => cowboy_stream:partial_req(), - - %% Response status. - resp_status := cowboy:http_status(), - - %% Filtered response headers. - resp_headers := cowboy:http_headers(), - - %% Start/end of the processing of the request. - %% - %% This represents the time from this stream handler's init - %% to terminate. - req_start => integer(), - req_end => integer(), - - %% Start/end of the receiving of the request body. - %% Begins when the first packet has been received. - req_body_start => integer(), - req_body_end => integer(), - - %% Start/end of the sending of the response. - %% Begins when we send the headers and ends on the final - %% packet of the response body. If everything is sent at - %% once these values are identical. - resp_start => integer(), - resp_end => integer(), - - %% For early errors all we get is the time we received it. - early_error_time => integer(), - - %% Start/end of spawned processes. This is where most of - %% the user code lies, excluding stream handlers. On a - %% default Cowboy configuration there should be only one - %% process: the request process. - procs => proc_metrics(), - - %% Informational responses sent before the final response. - informational => [informational_metrics()], - - %% Length of the request and response bodies. This does - %% not include the framing. - req_body_length => non_neg_integer(), - resp_body_length => non_neg_integer(), - - %% Additional metadata set by the user. - user_data => map() -}. --export_type([metrics/0]). - --type metrics_callback() :: fun((metrics()) -> any()). --export_type([metrics_callback/0]). - --record(state, { - next :: any(), - callback :: fun((metrics()) -> any()), - resp_headers_filter :: undefined | fun((cowboy:http_headers()) -> cowboy:http_headers()), - req :: map(), - resp_status :: undefined | cowboy:http_status(), - resp_headers :: undefined | cowboy:http_headers(), - ref :: ranch:ref(), - req_start :: integer(), - req_end :: undefined | integer(), - req_body_start :: undefined | integer(), - req_body_end :: undefined | integer(), - resp_start :: undefined | integer(), - resp_end :: undefined | integer(), - procs = #{} :: proc_metrics(), - informational = [] :: [informational_metrics()], - req_body_length = 0 :: non_neg_integer(), - resp_body_length = 0 :: non_neg_integer(), - user_data = #{} :: map() -}). - --spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) - -> {[{spawn, pid(), timeout()}], #state{}}. -init(StreamID, Req=#{ref := Ref}, Opts=#{metrics_callback := Fun}) -> - ReqStart = erlang:monotonic_time(), - {Commands, Next} = cowboy_stream:init(StreamID, Req, Opts), - FilteredReq = case maps:get(metrics_req_filter, Opts, undefined) of - undefined -> Req; - ReqFilter -> ReqFilter(Req) - end, - RespHeadersFilter = maps:get(metrics_resp_headers_filter, Opts, undefined), - {Commands, fold(Commands, #state{ - next=Next, - callback=Fun, - resp_headers_filter=RespHeadersFilter, - req=FilteredReq, - ref=Ref, - req_start=ReqStart - })}. - --spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State) - -> {cowboy_stream:commands(), State} when State::#state{}. -data(StreamID, IsFin=fin, Data, State=#state{req_body_start=undefined}) -> - ReqBody = erlang:monotonic_time(), - do_data(StreamID, IsFin, Data, State#state{ - req_body_start=ReqBody, - req_body_end=ReqBody, - req_body_length=byte_size(Data) - }); -data(StreamID, IsFin=fin, Data, State=#state{req_body_length=ReqBodyLen}) -> - ReqBodyEnd = erlang:monotonic_time(), - do_data(StreamID, IsFin, Data, State#state{ - req_body_end=ReqBodyEnd, - req_body_length=ReqBodyLen + byte_size(Data) - }); -data(StreamID, IsFin, Data, State=#state{req_body_start=undefined}) -> - ReqBodyStart = erlang:monotonic_time(), - do_data(StreamID, IsFin, Data, State#state{ - req_body_start=ReqBodyStart, - req_body_length=byte_size(Data) - }); -data(StreamID, IsFin, Data, State=#state{req_body_length=ReqBodyLen}) -> - do_data(StreamID, IsFin, Data, State#state{ - req_body_length=ReqBodyLen + byte_size(Data) - }). - -do_data(StreamID, IsFin, Data, State0=#state{next=Next0}) -> - {Commands, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0), - {Commands, fold(Commands, State0#state{next=Next})}. - --spec info(cowboy_stream:streamid(), any(), State) - -> {cowboy_stream:commands(), State} when State::#state{}. -info(StreamID, Info={'EXIT', Pid, Reason}, State0=#state{procs=Procs}) -> - ProcEnd = erlang:monotonic_time(), - P = maps:get(Pid, Procs), - State = State0#state{procs=Procs#{Pid => P#{ - exit => ProcEnd, - reason => Reason - }}}, - do_info(StreamID, Info, State); -info(StreamID, Info, State) -> - do_info(StreamID, Info, State). - -do_info(StreamID, Info, State0=#state{next=Next0}) -> - {Commands, Next} = cowboy_stream:info(StreamID, Info, Next0), - {Commands, fold(Commands, State0#state{next=Next})}. - -fold([], State) -> - State; -fold([{spawn, Pid, _}|Tail], State0=#state{procs=Procs}) -> - ProcStart = erlang:monotonic_time(), - State = State0#state{procs=Procs#{Pid => #{spawn => ProcStart}}}, - fold(Tail, State); -fold([{inform, Status, Headers}|Tail], - State=#state{informational=Infos}) -> - Time = erlang:monotonic_time(), - fold(Tail, State#state{informational=[#{ - status => Status, - headers => Headers, - time => Time - }|Infos]}); -fold([{response, Status, Headers, Body}|Tail], - State=#state{resp_headers_filter=RespHeadersFilter}) -> - Resp = erlang:monotonic_time(), - fold(Tail, State#state{ - resp_status=Status, - resp_headers=case RespHeadersFilter of - undefined -> Headers; - _ -> RespHeadersFilter(Headers) - end, - resp_start=Resp, - resp_end=Resp, - resp_body_length=resp_body_length(Body) - }); -fold([{error_response, Status, Headers, Body}|Tail], - State=#state{resp_status=RespStatus}) -> - %% The error_response command only results in a response - %% if no response was sent before. - case RespStatus of - undefined -> - fold([{response, Status, Headers, Body}|Tail], State); - _ -> - fold(Tail, State) - end; -fold([{headers, Status, Headers}|Tail], - State=#state{resp_headers_filter=RespHeadersFilter}) -> - RespStart = erlang:monotonic_time(), - fold(Tail, State#state{ - resp_status=Status, - resp_headers=case RespHeadersFilter of - undefined -> Headers; - _ -> RespHeadersFilter(Headers) - end, - resp_start=RespStart - }); -%% @todo It might be worthwhile to keep the sendfile information around, -%% especially if these frames ultimately result in a sendfile syscall. -fold([{data, nofin, Data}|Tail], State=#state{resp_body_length=RespBodyLen}) -> - fold(Tail, State#state{ - resp_body_length=RespBodyLen + resp_body_length(Data) - }); -fold([{data, fin, Data}|Tail], State=#state{resp_body_length=RespBodyLen}) -> - RespEnd = erlang:monotonic_time(), - fold(Tail, State#state{ - resp_end=RespEnd, - resp_body_length=RespBodyLen + resp_body_length(Data) - }); -fold([{set_options, SetOpts}|Tail], State0=#state{user_data=OldUserData}) -> - State = case SetOpts of - #{metrics_user_data := NewUserData} -> - State0#state{user_data=maps:merge(OldUserData, NewUserData)}; - _ -> - State0 - end, - fold(Tail, State); -fold([_|Tail], State) -> - fold(Tail, State). - --spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> any(). -terminate(StreamID, Reason, #state{next=Next, callback=Fun, - req=Req, resp_status=RespStatus, resp_headers=RespHeaders, ref=Ref, - req_start=ReqStart, req_body_start=ReqBodyStart, - req_body_end=ReqBodyEnd, resp_start=RespStart, resp_end=RespEnd, - procs=Procs, informational=Infos, user_data=UserData, - req_body_length=ReqBodyLen, resp_body_length=RespBodyLen}) -> - Res = cowboy_stream:terminate(StreamID, Reason, Next), - ReqEnd = erlang:monotonic_time(), - Metrics = #{ - ref => Ref, - pid => self(), - streamid => StreamID, - reason => Reason, - req => Req, - resp_status => RespStatus, - resp_headers => RespHeaders, - req_start => ReqStart, - req_end => ReqEnd, - req_body_start => ReqBodyStart, - req_body_end => ReqBodyEnd, - resp_start => RespStart, - resp_end => RespEnd, - procs => Procs, - informational => lists:reverse(Infos), - req_body_length => ReqBodyLen, - resp_body_length => RespBodyLen, - user_data => UserData - }, - Fun(Metrics), - Res. - --spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(), - cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp - when Resp::cowboy_stream:resp_command(). -early_error(StreamID, Reason, PartialReq=#{ref := Ref}, Resp0, Opts=#{metrics_callback := Fun}) -> - Time = erlang:monotonic_time(), - Resp = {response, RespStatus, RespHeaders, RespBody} - = cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp0, Opts), - %% As far as metrics go we are limited in what we can provide - %% in this case. - Metrics = #{ - ref => Ref, - pid => self(), - streamid => StreamID, - reason => Reason, - partial_req => PartialReq, - resp_status => RespStatus, - resp_headers => RespHeaders, - early_error_time => Time, - resp_body_length => resp_body_length(RespBody) - }, - Fun(Metrics), - Resp. - -resp_body_length({sendfile, _, Len, _}) -> - Len; -resp_body_length(Data) -> - iolist_size(Data). diff --git a/_build/emqx/lib/cowboy/src/cowboy_middleware.erl b/_build/emqx/lib/cowboy/src/cowboy_middleware.erl deleted file mode 100644 index 9a739f1f43..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_middleware.erl +++ /dev/null @@ -1,24 +0,0 @@ -%% Copyright (c) 2013-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_middleware). - --type env() :: #{atom() => any()}. --export_type([env/0]). - --callback execute(Req, Env) - -> {ok, Req, Env} - | {suspend, module(), atom(), [any()]} - | {stop, Req} - when Req::cowboy_req:req(), Env::env(). diff --git a/_build/emqx/lib/cowboy/src/cowboy_req.erl b/_build/emqx/lib/cowboy/src/cowboy_req.erl deleted file mode 100644 index ea61194e16..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_req.erl +++ /dev/null @@ -1,997 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% Copyright (c) 2011, Anthony Ramine -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_req). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - -%% Request. --export([method/1]). --export([version/1]). --export([peer/1]). --export([sock/1]). --export([cert/1]). --export([scheme/1]). --export([host/1]). --export([host_info/1]). --export([port/1]). --export([path/1]). --export([path_info/1]). --export([qs/1]). --export([parse_qs/1]). --export([match_qs/2]). --export([uri/1]). --export([uri/2]). --export([binding/2]). --export([binding/3]). --export([bindings/1]). --export([header/2]). --export([header/3]). --export([headers/1]). --export([parse_header/2]). --export([parse_header/3]). --export([filter_cookies/2]). --export([parse_cookies/1]). --export([match_cookies/2]). - -%% Request body. --export([has_body/1]). --export([body_length/1]). --export([read_body/1]). --export([read_body/2]). --export([read_urlencoded_body/1]). --export([read_urlencoded_body/2]). --export([read_and_match_urlencoded_body/2]). --export([read_and_match_urlencoded_body/3]). - -%% Multipart. --export([read_part/1]). --export([read_part/2]). --export([read_part_body/1]). --export([read_part_body/2]). - -%% Response. --export([set_resp_cookie/3]). --export([set_resp_cookie/4]). --export([resp_header/2]). --export([resp_header/3]). --export([resp_headers/1]). --export([set_resp_header/3]). --export([set_resp_headers/2]). --export([has_resp_header/2]). --export([delete_resp_header/2]). --export([set_resp_body/2]). -%% @todo set_resp_body/3 with a ContentType or even Headers argument, to set content headers. --export([has_resp_body/1]). --export([inform/2]). --export([inform/3]). --export([reply/2]). --export([reply/3]). --export([reply/4]). --export([stream_reply/2]). --export([stream_reply/3]). -%% @todo stream_body/2 (nofin) --export([stream_body/3]). -%% @todo stream_events/2 (nofin) --export([stream_events/3]). --export([stream_trailers/2]). --export([push/3]). --export([push/4]). - -%% Stream handlers. --export([cast/2]). - -%% Internal. --export([response_headers/2]). - --type read_body_opts() :: #{ - length => non_neg_integer() | infinity, - period => non_neg_integer(), - timeout => timeout() -}. --export_type([read_body_opts/0]). - -%% While sendfile allows a Len of 0 that means "everything past Offset", -%% Cowboy expects the real length as it is used as metadata. --type resp_body() :: iodata() - | {sendfile, non_neg_integer(), non_neg_integer(), file:name_all()}. --export_type([resp_body/0]). - --type push_opts() :: #{ - method => binary(), - scheme => binary(), - host => binary(), - port => inet:port_number(), - qs => binary() -}. --export_type([push_opts/0]). - --type req() :: #{ - %% Public interface. - method := binary(), - version := cowboy:http_version() | atom(), - scheme := binary(), - host := binary(), - port := inet:port_number(), - path := binary(), - qs := binary(), - headers := cowboy:http_headers(), - peer := {inet:ip_address(), inet:port_number()}, - sock := {inet:ip_address(), inet:port_number()}, - cert := binary() | undefined, - - %% Private interface. - ref := ranch:ref(), - pid := pid(), - streamid := cowboy_stream:streamid(), - - host_info => cowboy_router:tokens(), - path_info => cowboy_router:tokens(), - bindings => cowboy_router:bindings(), - - has_body := boolean(), - body_length := non_neg_integer() | undefined, - has_read_body => true, - multipart => {binary(), binary()} | done, - - has_sent_resp => headers | true, - resp_cookies => #{iodata() => iodata()}, - resp_headers => #{binary() => iodata()}, - resp_body => resp_body(), - - proxy_header => ranch_proxy_header:proxy_info(), - media_type => {binary(), binary(), [{binary(), binary()}]}, - language => binary() | undefined, - charset => binary() | undefined, - range => {binary(), binary() - | [{non_neg_integer(), non_neg_integer() | infinity} | neg_integer()]}, - websocket_version => 7 | 8 | 13, - - %% The user is encouraged to use the Req to store information - %% when no better solution is available. - _ => _ -}. --export_type([req/0]). - -%% Request. - --spec method(req()) -> binary(). -method(#{method := Method}) -> - Method. - --spec version(req()) -> cowboy:http_version(). -version(#{version := Version}) -> - Version. - --spec peer(req()) -> {inet:ip_address(), inet:port_number()}. -peer(#{peer := Peer}) -> - Peer. - --spec sock(req()) -> {inet:ip_address(), inet:port_number()}. -sock(#{sock := Sock}) -> - Sock. - --spec cert(req()) -> binary() | undefined. -cert(#{cert := Cert}) -> - Cert. - --spec scheme(req()) -> binary(). -scheme(#{scheme := Scheme}) -> - Scheme. - --spec host(req()) -> binary(). -host(#{host := Host}) -> - Host. - -%% @todo The host_info is undefined if cowboy_router isn't used. Do we want to crash? --spec host_info(req()) -> cowboy_router:tokens() | undefined. -host_info(#{host_info := HostInfo}) -> - HostInfo. - --spec port(req()) -> inet:port_number(). -port(#{port := Port}) -> - Port. - --spec path(req()) -> binary(). -path(#{path := Path}) -> - Path. - -%% @todo The path_info is undefined if cowboy_router isn't used. Do we want to crash? --spec path_info(req()) -> cowboy_router:tokens() | undefined. -path_info(#{path_info := PathInfo}) -> - PathInfo. - --spec qs(req()) -> binary(). -qs(#{qs := Qs}) -> - Qs. - -%% @todo Might be useful to limit the number of keys. --spec parse_qs(req()) -> [{binary(), binary() | true}]. -parse_qs(#{qs := Qs}) -> - try - cow_qs:parse_qs(Qs) - catch _:_ -> - erlang:raise(exit, {request_error, qs, - 'Malformed query string; application/x-www-form-urlencoded expected.' - }, erlang:get_stacktrace()) - end. - --spec match_qs(cowboy:fields(), req()) -> map(). -match_qs(Fields, Req) -> - case filter(Fields, kvlist_to_map(Fields, parse_qs(Req))) of - {ok, Map} -> - Map; - {error, Errors} -> - exit({request_error, {match_qs, Errors}, - 'Query string validation constraints failed for the reasons provided.'}) - end. - --spec uri(req()) -> iodata(). -uri(Req) -> - uri(Req, #{}). - --spec uri(req(), map()) -> iodata(). -uri(#{scheme := Scheme0, host := Host0, port := Port0, - path := Path0, qs := Qs0}, Opts) -> - Scheme = case maps:get(scheme, Opts, Scheme0) of - S = undefined -> S; - S -> iolist_to_binary(S) - end, - Host = maps:get(host, Opts, Host0), - Port = maps:get(port, Opts, Port0), - {Path, Qs} = case maps:get(path, Opts, Path0) of - <<"*">> -> {<<>>, <<>>}; - P -> {P, maps:get(qs, Opts, Qs0)} - end, - Fragment = maps:get(fragment, Opts, undefined), - [uri_host(Scheme, Scheme0, Port, Host), uri_path(Path), uri_qs(Qs), uri_fragment(Fragment)]. - -uri_host(_, _, _, undefined) -> <<>>; -uri_host(Scheme, Scheme0, Port, Host) -> - case iolist_size(Host) of - 0 -> <<>>; - _ -> [uri_scheme(Scheme), <<"//">>, Host, uri_port(Scheme, Scheme0, Port)] - end. - -uri_scheme(undefined) -> <<>>; -uri_scheme(Scheme) -> - case iolist_size(Scheme) of - 0 -> Scheme; - _ -> [Scheme, $:] - end. - -uri_port(_, _, undefined) -> <<>>; -uri_port(undefined, <<"http">>, 80) -> <<>>; -uri_port(undefined, <<"https">>, 443) -> <<>>; -uri_port(<<"http">>, _, 80) -> <<>>; -uri_port(<<"https">>, _, 443) -> <<>>; -uri_port(_, _, Port) -> - [$:, integer_to_binary(Port)]. - -uri_path(undefined) -> <<>>; -uri_path(Path) -> Path. - -uri_qs(undefined) -> <<>>; -uri_qs(Qs) -> - case iolist_size(Qs) of - 0 -> Qs; - _ -> [$?, Qs] - end. - -uri_fragment(undefined) -> <<>>; -uri_fragment(Fragment) -> - case iolist_size(Fragment) of - 0 -> Fragment; - _ -> [$#, Fragment] - end. - --ifdef(TEST). -uri1_test() -> - <<"http://localhost/path">> = iolist_to_binary(uri(#{ - scheme => <<"http">>, host => <<"localhost">>, port => 80, - path => <<"/path">>, qs => <<>>})), - <<"http://localhost:443/path">> = iolist_to_binary(uri(#{ - scheme => <<"http">>, host => <<"localhost">>, port => 443, - path => <<"/path">>, qs => <<>>})), - <<"http://localhost:8080/path">> = iolist_to_binary(uri(#{ - scheme => <<"http">>, host => <<"localhost">>, port => 8080, - path => <<"/path">>, qs => <<>>})), - <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(#{ - scheme => <<"http">>, host => <<"localhost">>, port => 8080, - path => <<"/path">>, qs => <<"dummy=2785">>})), - <<"https://localhost/path">> = iolist_to_binary(uri(#{ - scheme => <<"https">>, host => <<"localhost">>, port => 443, - path => <<"/path">>, qs => <<>>})), - <<"https://localhost:8443/path">> = iolist_to_binary(uri(#{ - scheme => <<"https">>, host => <<"localhost">>, port => 8443, - path => <<"/path">>, qs => <<>>})), - <<"https://localhost:8443/path?dummy=2785">> = iolist_to_binary(uri(#{ - scheme => <<"https">>, host => <<"localhost">>, port => 8443, - path => <<"/path">>, qs => <<"dummy=2785">>})), - ok. - -uri2_test() -> - Req = #{ - scheme => <<"http">>, host => <<"localhost">>, port => 8080, - path => <<"/path">>, qs => <<"dummy=2785">> - }, - <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{})), - %% Disable individual components. - <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => undefined})), - <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => undefined})), - <<"http://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => undefined})), - <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => undefined})), - <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => undefined})), - <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => undefined})), - <<"http://localhost:8080">> = iolist_to_binary(uri(Req, #{path => undefined, qs => undefined})), - <<>> = iolist_to_binary(uri(Req, #{host => undefined, path => undefined, qs => undefined})), - %% Empty values. - <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => <<>>})), - <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => ""})), - <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => [<<>>]})), - <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => <<>>})), - <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => ""})), - <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => [<<>>]})), - <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => <<>>})), - <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => ""})), - <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => [<<>>]})), - <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => <<>>})), - <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => ""})), - <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => [<<>>]})), - <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => <<>>})), - <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => ""})), - <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => [<<>>]})), - %% Port is integer() | undefined. - {'EXIT', _} = (catch iolist_to_binary(uri(Req, #{port => <<>>}))), - {'EXIT', _} = (catch iolist_to_binary(uri(Req, #{port => ""}))), - {'EXIT', _} = (catch iolist_to_binary(uri(Req, #{port => [<<>>]}))), - %% Update components. - <<"https://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => "https"})), - <<"http://example.org:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => "example.org"})), - <<"http://localhost:123/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => 123})), - <<"http://localhost:8080/custom?dummy=2785">> = iolist_to_binary(uri(Req, #{path => "/custom"})), - <<"http://localhost:8080/path?smart=42">> = iolist_to_binary(uri(Req, #{qs => "smart=42"})), - <<"http://localhost:8080/path?dummy=2785#intro">> = iolist_to_binary(uri(Req, #{fragment => "intro"})), - %% Interesting combinations. - <<"http://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => 80})), - <<"https://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => "https", port => 443})), - ok. --endif. - --spec binding(atom(), req()) -> any() | undefined. -binding(Name, Req) -> - binding(Name, Req, undefined). - --spec binding(atom(), req(), Default) -> any() | Default when Default::any(). -binding(Name, #{bindings := Bindings}, Default) when is_atom(Name) -> - case Bindings of - #{Name := Value} -> Value; - _ -> Default - end; -binding(Name, _, Default) when is_atom(Name) -> - Default. - --spec bindings(req()) -> cowboy_router:bindings(). -bindings(#{bindings := Bindings}) -> - Bindings; -bindings(_) -> - #{}. - --spec header(binary(), req()) -> binary() | undefined. -header(Name, Req) -> - header(Name, Req, undefined). - --spec header(binary(), req(), Default) -> binary() | Default when Default::any(). -header(Name, #{headers := Headers}, Default) -> - maps:get(Name, Headers, Default). - --spec headers(req()) -> cowboy:http_headers(). -headers(#{headers := Headers}) -> - Headers. - --spec parse_header(binary(), Req) -> any() when Req::req(). -parse_header(Name = <<"content-length">>, Req) -> - parse_header(Name, Req, 0); -parse_header(Name = <<"cookie">>, Req) -> - parse_header(Name, Req, []); -parse_header(Name, Req) -> - parse_header(Name, Req, undefined). - --spec parse_header(binary(), Req, any()) -> any() when Req::req(). -parse_header(Name, Req, Default) -> - try - parse_header(Name, Req, Default, parse_header_fun(Name)) - catch _:_ -> - erlang:raise(exit, {request_error, {header, Name}, - 'Malformed header. Please consult the relevant specification.' - }, erlang:get_stacktrace()) - end. - -parse_header_fun(<<"accept">>) -> fun cow_http_hd:parse_accept/1; -parse_header_fun(<<"accept-charset">>) -> fun cow_http_hd:parse_accept_charset/1; -parse_header_fun(<<"accept-encoding">>) -> fun cow_http_hd:parse_accept_encoding/1; -parse_header_fun(<<"accept-language">>) -> fun cow_http_hd:parse_accept_language/1; -parse_header_fun(<<"authorization">>) -> fun cow_http_hd:parse_authorization/1; -parse_header_fun(<<"connection">>) -> fun cow_http_hd:parse_connection/1; -parse_header_fun(<<"content-length">>) -> fun cow_http_hd:parse_content_length/1; -parse_header_fun(<<"content-type">>) -> fun cow_http_hd:parse_content_type/1; -parse_header_fun(<<"cookie">>) -> fun cow_cookie:parse_cookie/1; -parse_header_fun(<<"expect">>) -> fun cow_http_hd:parse_expect/1; -parse_header_fun(<<"if-match">>) -> fun cow_http_hd:parse_if_match/1; -parse_header_fun(<<"if-modified-since">>) -> fun cow_http_hd:parse_if_modified_since/1; -parse_header_fun(<<"if-none-match">>) -> fun cow_http_hd:parse_if_none_match/1; -parse_header_fun(<<"if-range">>) -> fun cow_http_hd:parse_if_range/1; -parse_header_fun(<<"if-unmodified-since">>) -> fun cow_http_hd:parse_if_unmodified_since/1; -parse_header_fun(<<"range">>) -> fun cow_http_hd:parse_range/1; -parse_header_fun(<<"sec-websocket-extensions">>) -> fun cow_http_hd:parse_sec_websocket_extensions/1; -parse_header_fun(<<"sec-websocket-protocol">>) -> fun cow_http_hd:parse_sec_websocket_protocol_req/1; -parse_header_fun(<<"sec-websocket-version">>) -> fun cow_http_hd:parse_sec_websocket_version_req/1; -parse_header_fun(<<"upgrade">>) -> fun cow_http_hd:parse_upgrade/1; -parse_header_fun(<<"x-forwarded-for">>) -> fun cow_http_hd:parse_x_forwarded_for/1. - -parse_header(Name, Req, Default, ParseFun) -> - case header(Name, Req) of - undefined -> Default; - Value -> ParseFun(Value) - end. - --spec filter_cookies([atom() | binary()], Req) -> Req when Req::req(). -filter_cookies(Names0, Req=#{headers := Headers}) -> - Names = [if - is_atom(N) -> atom_to_binary(N, utf8); - true -> N - end || N <- Names0], - case header(<<"cookie">>, Req) of - undefined -> Req; - Value0 -> - Cookies0 = binary:split(Value0, <<$;>>), - Cookies = lists:filter(fun(Cookie) -> - lists:member(cookie_name(Cookie), Names) - end, Cookies0), - Value = iolist_to_binary(lists:join($;, Cookies)), - Req#{headers => Headers#{<<"cookie">> => Value}} - end. - -%% This is a specialized function to extract a cookie name -%% regardless of whether the name is valid or not. We skip -%% whitespace at the beginning and take whatever's left to -%% be the cookie name, up to the = sign. -cookie_name(<<$\s, Rest/binary>>) -> cookie_name(Rest); -cookie_name(<<$\t, Rest/binary>>) -> cookie_name(Rest); -cookie_name(Name) -> cookie_name(Name, <<>>). - -cookie_name(<<>>, Name) -> Name; -cookie_name(<<$=, _/bits>>, Name) -> Name; -cookie_name(<>, Acc) -> cookie_name(Rest, <>). - --spec parse_cookies(req()) -> [{binary(), binary()}]. -parse_cookies(Req) -> - parse_header(<<"cookie">>, Req). - --spec match_cookies(cowboy:fields(), req()) -> map(). -match_cookies(Fields, Req) -> - case filter(Fields, kvlist_to_map(Fields, parse_cookies(Req))) of - {ok, Map} -> - Map; - {error, Errors} -> - exit({request_error, {match_cookies, Errors}, - 'Cookie validation constraints failed for the reasons provided.'}) - end. - -%% Request body. - --spec has_body(req()) -> boolean(). -has_body(#{has_body := HasBody}) -> - HasBody. - -%% The length may not be known if HTTP/1.1 with a transfer-encoding; -%% or HTTP/2 with no content-length header. The length is always -%% known once the body has been completely read. --spec body_length(req()) -> undefined | non_neg_integer(). -body_length(#{body_length := Length}) -> - Length. - --spec read_body(Req) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req(). -read_body(Req) -> - read_body(Req, #{}). - --spec read_body(Req, read_body_opts()) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req(). -read_body(Req=#{has_body := false}, _) -> - {ok, <<>>, Req}; -read_body(Req=#{has_read_body := true}, _) -> - {ok, <<>>, Req}; -read_body(Req, Opts) -> - Length = maps:get(length, Opts, 8000000), - Period = maps:get(period, Opts, 15000), - Timeout = maps:get(timeout, Opts, Period + 1000), - Ref = make_ref(), - cast({read_body, self(), Ref, Length, Period}, Req), - receive - {request_body, Ref, nofin, Body} -> - {more, Body, Req}; - {request_body, Ref, fin, BodyLength, Body} -> - {ok, Body, set_body_length(Req, BodyLength)} - after Timeout -> - exit(timeout) - end. - -set_body_length(Req=#{headers := Headers}, BodyLength) -> - Req#{ - headers => Headers#{<<"content-length">> => integer_to_binary(BodyLength)}, - body_length => BodyLength, - has_read_body => true - }. - --spec read_urlencoded_body(Req) -> {ok, [{binary(), binary() | true}], Req} when Req::req(). -read_urlencoded_body(Req) -> - read_urlencoded_body(Req, #{length => 64000, period => 5000}). - --spec read_urlencoded_body(Req, read_body_opts()) -> {ok, [{binary(), binary() | true}], Req} when Req::req(). -read_urlencoded_body(Req0, Opts) -> - case read_body(Req0, Opts) of - {ok, Body, Req} -> - try - {ok, cow_qs:parse_qs(Body), Req} - catch _:_ -> - erlang:raise(exit, {request_error, urlencoded_body, - 'Malformed body; application/x-www-form-urlencoded expected.' - }, erlang:get_stacktrace()) - end; - {more, Body, _} -> - Length = maps:get(length, Opts, 64000), - if - byte_size(Body) < Length -> - exit({request_error, timeout, - 'The request body was not received within the configured time.'}); - true -> - exit({request_error, payload_too_large, - 'The request body is larger than allowed by configuration.'}) - end - end. - --spec read_and_match_urlencoded_body(cowboy:fields(), Req) - -> {ok, map(), Req} when Req::req(). -read_and_match_urlencoded_body(Fields, Req) -> - read_and_match_urlencoded_body(Fields, Req, #{length => 64000, period => 5000}). - --spec read_and_match_urlencoded_body(cowboy:fields(), Req, read_body_opts()) - -> {ok, map(), Req} when Req::req(). -read_and_match_urlencoded_body(Fields, Req0, Opts) -> - {ok, Qs, Req} = read_urlencoded_body(Req0, Opts), - case filter(Fields, kvlist_to_map(Fields, Qs)) of - {ok, Map} -> - {ok, Map, Req}; - {error, Errors} -> - exit({request_error, {read_and_match_urlencoded_body, Errors}, - 'Urlencoded request body validation constraints failed for the reasons provided.'}) - end. - -%% Multipart. - --spec read_part(Req) - -> {ok, cowboy:http_headers(), Req} | {done, Req} - when Req::req(). -read_part(Req) -> - read_part(Req, #{length => 64000, period => 5000}). - --spec read_part(Req, read_body_opts()) - -> {ok, cowboy:http_headers(), Req} | {done, Req} - when Req::req(). -read_part(Req, Opts) -> - case maps:is_key(multipart, Req) of - true -> - {Data, Req2} = stream_multipart(Req, Opts, headers), - read_part(Data, Opts, Req2); - false -> - read_part(init_multipart(Req), Opts) - end. - -read_part(Buffer, Opts, Req=#{multipart := {Boundary, _}}) -> - try cow_multipart:parse_headers(Buffer, Boundary) of - more -> - {Data, Req2} = stream_multipart(Req, Opts, headers), - read_part(<< Buffer/binary, Data/binary >>, Opts, Req2); - {more, Buffer2} -> - {Data, Req2} = stream_multipart(Req, Opts, headers), - read_part(<< Buffer2/binary, Data/binary >>, Opts, Req2); - {ok, Headers0, Rest} -> - Headers = maps:from_list(Headers0), - %% Reject multipart content containing duplicate headers. - true = map_size(Headers) =:= length(Headers0), - {ok, Headers, Req#{multipart => {Boundary, Rest}}}; - %% Ignore epilogue. - {done, _} -> - {done, Req#{multipart => done}} - catch _:_ -> - erlang:raise(exit, {request_error, {multipart, headers}, - 'Malformed body; multipart expected.' - }, erlang:get_stacktrace()) - end. - --spec read_part_body(Req) - -> {ok, binary(), Req} | {more, binary(), Req} - when Req::req(). -read_part_body(Req) -> - read_part_body(Req, #{}). - --spec read_part_body(Req, read_body_opts()) - -> {ok, binary(), Req} | {more, binary(), Req} - when Req::req(). -read_part_body(Req, Opts) -> - case maps:is_key(multipart, Req) of - true -> - read_part_body(<<>>, Opts, Req, <<>>); - false -> - read_part_body(init_multipart(Req), Opts) - end. - -read_part_body(Buffer, Opts, Req=#{multipart := {Boundary, _}}, Acc) -> - Length = maps:get(length, Opts, 8000000), - case byte_size(Acc) > Length of - true -> - {more, Acc, Req#{multipart => {Boundary, Buffer}}}; - false -> - {Data, Req2} = stream_multipart(Req, Opts, body), - case cow_multipart:parse_body(<< Buffer/binary, Data/binary >>, Boundary) of - {ok, Body} -> - read_part_body(<<>>, Opts, Req2, << Acc/binary, Body/binary >>); - {ok, Body, Rest} -> - read_part_body(Rest, Opts, Req2, << Acc/binary, Body/binary >>); - done -> - {ok, Acc, Req2}; - {done, Body} -> - {ok, << Acc/binary, Body/binary >>, Req2}; - {done, Body, Rest} -> - {ok, << Acc/binary, Body/binary >>, - Req2#{multipart => {Boundary, Rest}}} - end - end. - -init_multipart(Req) -> - {<<"multipart">>, _, Params} = parse_header(<<"content-type">>, Req), - case lists:keyfind(<<"boundary">>, 1, Params) of - {_, Boundary} -> - Req#{multipart => {Boundary, <<>>}}; - false -> - exit({request_error, {multipart, boundary}, - 'Missing boundary parameter for multipart media type.'}) - end. - -stream_multipart(Req=#{multipart := done}, _, _) -> - {<<>>, Req}; -stream_multipart(Req=#{multipart := {_, <<>>}}, Opts, Type) -> - case read_body(Req, Opts) of - {more, Data, Req2} -> - {Data, Req2}; - %% We crash when the data ends unexpectedly. - {ok, <<>>, _} -> - exit({request_error, {multipart, Type}, - 'Malformed body; multipart expected.'}); - {ok, Data, Req2} -> - {Data, Req2} - end; -stream_multipart(Req=#{multipart := {Boundary, Buffer}}, _, _) -> - {Buffer, Req#{multipart => {Boundary, <<>>}}}. - -%% Response. - --spec set_resp_cookie(iodata(), iodata(), Req) - -> Req when Req::req(). -set_resp_cookie(Name, Value, Req) -> - set_resp_cookie(Name, Value, Req, #{}). - -%% The cookie name cannot contain any of the following characters: -%% =,;\s\t\r\n\013\014 -%% -%% The cookie value cannot contain any of the following characters: -%% ,; \t\r\n\013\014 --spec set_resp_cookie(binary(), iodata(), Req, cow_cookie:cookie_opts()) - -> Req when Req::req(). -set_resp_cookie(Name, Value, Req, Opts) -> - Cookie = cow_cookie:setcookie(Name, Value, Opts), - RespCookies = maps:get(resp_cookies, Req, #{}), - Req#{resp_cookies => RespCookies#{Name => Cookie}}. - -%% @todo We could add has_resp_cookie and delete_resp_cookie now. - --spec set_resp_header(binary(), iodata(), Req) - -> Req when Req::req(). -set_resp_header(Name, Value, Req=#{resp_headers := RespHeaders}) -> - Req#{resp_headers => RespHeaders#{Name => Value}}; -set_resp_header(Name,Value, Req) -> - Req#{resp_headers => #{Name => Value}}. - --spec set_resp_headers(cowboy:http_headers(), Req) - -> Req when Req::req(). -set_resp_headers(Headers, Req=#{resp_headers := RespHeaders}) -> - Req#{resp_headers => maps:merge(RespHeaders, Headers)}; -set_resp_headers(Headers, Req) -> - Req#{resp_headers => Headers}. - --spec resp_header(binary(), req()) -> binary() | undefined. -resp_header(Name, Req) -> - resp_header(Name, Req, undefined). - --spec resp_header(binary(), req(), Default) - -> binary() | Default when Default::any(). -resp_header(Name, #{resp_headers := Headers}, Default) -> - maps:get(Name, Headers, Default); -resp_header(_, #{}, Default) -> - Default. - --spec resp_headers(req()) -> cowboy:http_headers(). -resp_headers(#{resp_headers := RespHeaders}) -> - RespHeaders; -resp_headers(#{}) -> - #{}. - --spec set_resp_body(resp_body(), Req) -> Req when Req::req(). -set_resp_body(Body, Req) -> - Req#{resp_body => Body}. - --spec has_resp_header(binary(), req()) -> boolean(). -has_resp_header(Name, #{resp_headers := RespHeaders}) -> - maps:is_key(Name, RespHeaders); -has_resp_header(_, _) -> - false. - --spec has_resp_body(req()) -> boolean(). -has_resp_body(#{resp_body := {sendfile, _, _, _}}) -> - true; -has_resp_body(#{resp_body := RespBody}) -> - iolist_size(RespBody) > 0; -has_resp_body(_) -> - false. - --spec delete_resp_header(binary(), Req) - -> Req when Req::req(). -delete_resp_header(Name, Req=#{resp_headers := RespHeaders}) -> - Req#{resp_headers => maps:remove(Name, RespHeaders)}; -%% There are no resp headers so we have nothing to delete. -delete_resp_header(_, Req) -> - Req. - --spec inform(cowboy:http_status(), req()) -> ok. -inform(Status, Req) -> - inform(Status, #{}, Req). - --spec inform(cowboy:http_status(), cowboy:http_headers(), req()) -> ok. -inform(_, _, #{has_sent_resp := _}) -> - error(function_clause); %% @todo Better error message. -inform(Status, Headers, Req) when is_integer(Status); is_binary(Status) -> - cast({inform, Status, Headers}, Req). - --spec reply(cowboy:http_status(), Req) -> Req when Req::req(). -reply(Status, Req) -> - reply(Status, #{}, Req). - --spec reply(cowboy:http_status(), cowboy:http_headers(), Req) - -> Req when Req::req(). -reply(Status, Headers, Req=#{resp_body := Body}) -> - reply(Status, Headers, Body, Req); -reply(Status, Headers, Req) -> - reply(Status, Headers, <<>>, Req). - --spec reply(cowboy:http_status(), cowboy:http_headers(), resp_body(), Req) - -> Req when Req::req(). -reply(_, _, _, #{has_sent_resp := _}) -> - error(function_clause); %% @todo Better error message. -reply(Status, Headers, {sendfile, _, 0, _}, Req) - when is_integer(Status); is_binary(Status) -> - do_reply(Status, Headers#{ - <<"content-length">> => <<"0">> - }, <<>>, Req); -reply(Status, Headers, SendFile = {sendfile, _, Len, _}, Req) - when is_integer(Status); is_binary(Status) -> - do_reply(Status, Headers#{ - <<"content-length">> => integer_to_binary(Len) - }, SendFile, Req); -%% 204 responses must not include content-length. 304 responses may -%% but only when set explicitly. (RFC7230 3.3.1, RFC7230 3.3.2) -reply(Status, Headers, Body, Req) - when Status =:= 204; Status =:= 304 -> - do_reply(Status, Headers, Body, Req); -reply(Status= <<"204",_/bits>>, Headers, Body, Req) -> - do_reply(Status, Headers, Body, Req); -reply(Status= <<"304",_/bits>>, Headers, Body, Req) -> - do_reply(Status, Headers, Body, Req); -reply(Status, Headers, Body, Req) - when is_integer(Status); is_binary(Status) -> - do_reply(Status, Headers#{ - <<"content-length">> => integer_to_binary(iolist_size(Body)) - }, Body, Req). - -%% Don't send any body for HEAD responses. While the protocol code is -%% supposed to enforce this rule, we prefer to avoid copying too much -%% data around if we can avoid it. -do_reply(Status, Headers, _, Req=#{method := <<"HEAD">>}) -> - cast({response, Status, response_headers(Headers, Req), <<>>}, Req), - done_replying(Req, true); -do_reply(Status, Headers, Body, Req) -> - cast({response, Status, response_headers(Headers, Req), Body}, Req), - done_replying(Req, true). - -done_replying(Req, HasSentResp) -> - maps:without([resp_cookies, resp_headers, resp_body], Req#{has_sent_resp => HasSentResp}). - --spec stream_reply(cowboy:http_status(), Req) -> Req when Req::req(). -stream_reply(Status, Req) -> - stream_reply(Status, #{}, Req). - --spec stream_reply(cowboy:http_status(), cowboy:http_headers(), Req) - -> Req when Req::req(). -stream_reply(_, _, #{has_sent_resp := _}) -> - error(function_clause); -stream_reply(Status, Headers=#{}, Req) when is_integer(Status); is_binary(Status) -> - cast({headers, Status, response_headers(Headers, Req)}, Req), - done_replying(Req, headers). - --spec stream_body(resp_body(), fin | nofin, req()) -> ok. -%% Error out if headers were not sent. -%% Don't send any body for HEAD responses. -stream_body(_, _, #{method := <<"HEAD">>, has_sent_resp := headers}) -> - ok; -%% Don't send a message if the data is empty, except for the -%% very last message with IsFin=fin. When using sendfile this -%% is converted to a data tuple, however. -stream_body({sendfile, _, 0, _}, nofin, _) -> - ok; -stream_body({sendfile, _, 0, _}, IsFin=fin, Req=#{has_sent_resp := headers}) -> - stream_body({data, self(), IsFin, <<>>}, Req); -stream_body({sendfile, O, B, P}, IsFin, Req=#{has_sent_resp := headers}) - when is_integer(O), O >= 0, is_integer(B), B > 0 -> - stream_body({data, self(), IsFin, {sendfile, O, B, P}}, Req); -stream_body(Data, IsFin=nofin, Req=#{has_sent_resp := headers}) - when not is_tuple(Data) -> - case iolist_size(Data) of - 0 -> ok; - _ -> stream_body({data, self(), IsFin, Data}, Req) - end; -stream_body(Data, IsFin, Req=#{has_sent_resp := headers}) - when not is_tuple(Data) -> - stream_body({data, self(), IsFin, Data}, Req). - -%% @todo Do we need a timeout? -stream_body(Msg, Req=#{pid := Pid}) -> - cast(Msg, Req), - receive {data_ack, Pid} -> ok end. - --spec stream_events(cow_sse:event() | [cow_sse:event()], fin | nofin, req()) -> ok. -stream_events(Event, IsFin, Req) when is_map(Event) -> - stream_events([Event], IsFin, Req); -stream_events(Events, IsFin, Req=#{has_sent_resp := headers}) -> - stream_body({data, self(), IsFin, cow_sse:events(Events)}, Req). - --spec stream_trailers(cowboy:http_headers(), req()) -> ok. -stream_trailers(Trailers, Req=#{has_sent_resp := headers}) -> - cast({trailers, Trailers}, Req). - --spec push(iodata(), cowboy:http_headers(), req()) -> ok. -push(Path, Headers, Req) -> - push(Path, Headers, Req, #{}). - -%% @todo Optimization: don't send anything at all for HTTP/1.0 and HTTP/1.1. -%% @todo Path, Headers, Opts, everything should be in proper binary, -%% or normalized when creating the Req object. --spec push(iodata(), cowboy:http_headers(), req(), push_opts()) -> ok. -push(Path, Headers, Req=#{scheme := Scheme0, host := Host0, port := Port0}, Opts) -> - Method = maps:get(method, Opts, <<"GET">>), - Scheme = maps:get(scheme, Opts, Scheme0), - Host = maps:get(host, Opts, Host0), - Port = maps:get(port, Opts, Port0), - Qs = maps:get(qs, Opts, <<>>), - cast({push, Method, Scheme, Host, Port, Path, Qs, Headers}, Req). - -%% Stream handlers. - --spec cast(any(), req()) -> ok. -cast(Msg, #{pid := Pid, streamid := StreamID}) -> - Pid ! {{Pid, StreamID}, Msg}, - ok. - -%% Internal. - -%% @todo What about set-cookie headers set through set_resp_header or reply? --spec response_headers(Headers, req()) -> Headers when Headers::cowboy:http_headers(). -response_headers(Headers0, Req) -> - RespHeaders = maps:get(resp_headers, Req, #{}), - Headers = maps:merge(#{ - <<"date">> => cowboy_clock:rfc1123(), - <<"server">> => <<"Cowboy">> - }, maps:merge(RespHeaders, Headers0)), - %% The set-cookie header is special; we can only send one cookie per header. - %% We send the list of values for many cookies in one key of the map, - %% and let the protocols deal with it directly. - case maps:get(resp_cookies, Req, undefined) of - undefined -> Headers; - RespCookies -> Headers#{<<"set-cookie">> => maps:values(RespCookies)} - end. - -%% Create map, convert keys to atoms and group duplicate keys into lists. -%% Keys that are not found in the user provided list are entirely skipped. -%% @todo Can probably be done directly while parsing. -kvlist_to_map(Fields, KvList) -> - Keys = [case K of - {Key, _} -> Key; - {Key, _, _} -> Key; - Key -> Key - end || K <- Fields], - kvlist_to_map(Keys, KvList, #{}). - -kvlist_to_map(_, [], Map) -> - Map; -kvlist_to_map(Keys, [{Key, Value}|Tail], Map) -> - try binary_to_existing_atom(Key, utf8) of - Atom -> - case lists:member(Atom, Keys) of - true -> - case maps:find(Atom, Map) of - {ok, MapValue} when is_list(MapValue) -> - kvlist_to_map(Keys, Tail, - Map#{Atom => [Value|MapValue]}); - {ok, MapValue} -> - kvlist_to_map(Keys, Tail, - Map#{Atom => [Value, MapValue]}); - error -> - kvlist_to_map(Keys, Tail, - Map#{Atom => Value}) - end; - false -> - kvlist_to_map(Keys, Tail, Map) - end - catch error:badarg -> - kvlist_to_map(Keys, Tail, Map) - end. - -filter(Fields, Map0) -> - filter(Fields, Map0, #{}). - -%% Loop through fields, if value is missing and no default, -%% record the error; else if value is missing and has a -%% default, set default; otherwise apply constraints. If -%% constraint fails, record the error. -%% -%% When there is an error at the end, crash. -filter([], Map, Errors) -> - case maps:size(Errors) of - 0 -> {ok, Map}; - _ -> {error, Errors} - end; -filter([{Key, Constraints}|Tail], Map, Errors) -> - filter_constraints(Tail, Map, Errors, Key, maps:get(Key, Map), Constraints); -filter([{Key, Constraints, Default}|Tail], Map, Errors) -> - case maps:find(Key, Map) of - {ok, Value} -> - filter_constraints(Tail, Map, Errors, Key, Value, Constraints); - error -> - filter(Tail, Map#{Key => Default}, Errors) - end; -filter([Key|Tail], Map, Errors) -> - case maps:is_key(Key, Map) of - true -> - filter(Tail, Map, Errors); - false -> - filter(Tail, Map, Errors#{Key => required}) - end. - -filter_constraints(Tail, Map, Errors, Key, Value0, Constraints) -> - case cowboy_constraints:validate(Value0, Constraints) of - {ok, Value} -> - filter(Tail, Map#{Key => Value}, Errors); - {error, Reason} -> - filter(Tail, Map, Errors#{Key => Reason}) - end. diff --git a/_build/emqx/lib/cowboy/src/cowboy_rest.erl b/_build/emqx/lib/cowboy/src/cowboy_rest.erl deleted file mode 100644 index 9a73374e07..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_rest.erl +++ /dev/null @@ -1,1631 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -%% Originally based on the Webmachine Diagram from Alan Dean and -%% Justin Sheehy. --module(cowboy_rest). --behaviour(cowboy_sub_protocol). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([upgrade/4]). --export([upgrade/5]). - --type switch_handler() :: {switch_handler, module()} - | {switch_handler, module(), any()}. - -%% Common handler callbacks. - --callback init(Req, any()) - -> {ok | module(), Req, any()} - | {module(), Req, any(), any()} - when Req::cowboy_req:req(). - --callback terminate(any(), cowboy_req:req(), any()) -> ok. --optional_callbacks([terminate/3]). - -%% REST handler callbacks. - --callback allowed_methods(Req, State) - -> {[binary()], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([allowed_methods/2]). - --callback allow_missing_post(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([allow_missing_post/2]). - --callback charsets_provided(Req, State) - -> {[binary()], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([charsets_provided/2]). - --callback content_types_accepted(Req, State) - -> {[{'*' | binary() | {binary(), binary(), '*' | [{binary(), binary()}]}, atom()}], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([content_types_accepted/2]). - --callback content_types_provided(Req, State) - -> {[{binary() | {binary(), binary(), '*' | [{binary(), binary()}]}, atom()}], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([content_types_provided/2]). - --callback delete_completed(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([delete_completed/2]). - --callback delete_resource(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([delete_resource/2]). - --callback expires(Req, State) - -> {calendar:datetime() | binary() | undefined, Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([expires/2]). - --callback forbidden(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([forbidden/2]). - --callback generate_etag(Req, State) - -> {binary() | {weak | strong, binary()}, Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([generate_etag/2]). - --callback is_authorized(Req, State) - -> {true | {false, iodata()}, Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([is_authorized/2]). - --callback is_conflict(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([is_conflict/2]). - --callback known_methods(Req, State) - -> {[binary()], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([known_methods/2]). - --callback languages_provided(Req, State) - -> {[binary()], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([languages_provided/2]). - --callback last_modified(Req, State) - -> {calendar:datetime(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([last_modified/2]). - --callback malformed_request(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([malformed_request/2]). - --callback moved_permanently(Req, State) - -> {{true, iodata()} | false, Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([moved_permanently/2]). - --callback moved_temporarily(Req, State) - -> {{true, iodata()} | false, Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([moved_temporarily/2]). - --callback multiple_choices(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([multiple_choices/2]). - --callback options(Req, State) - -> {ok, Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([options/2]). - --callback previously_existed(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([previously_existed/2]). - --callback range_satisfiable(Req, State) - -> {boolean() | {false, non_neg_integer() | iodata()}, Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([range_satisfiable/2]). - --callback ranges_provided(Req, State) - -> {[{binary(), atom()}], Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([ranges_provided/2]). - --callback rate_limited(Req, State) - -> {{true, non_neg_integer() | calendar:datetime()} | false, Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([rate_limited/2]). - --callback resource_exists(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([resource_exists/2]). - --callback service_available(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([service_available/2]). - --callback uri_too_long(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([uri_too_long/2]). - --callback valid_content_headers(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([valid_content_headers/2]). - --callback valid_entity_length(Req, State) - -> {boolean(), Req, State} - | {stop, Req, State} - | {switch_handler(), Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([valid_entity_length/2]). - --callback variances(Req, State) - -> {[binary()], Req, State} - when Req::cowboy_req:req(), State::any(). --optional_callbacks([variances/2]). - -%% End of REST callbacks. Whew! - --record(state, { - method = undefined :: binary(), - - %% Handler. - handler :: atom(), - handler_state :: any(), - - %% Allowed methods. Only used for OPTIONS requests. - allowed_methods :: [binary()] | undefined, - - %% Media type. - content_types_p = [] :: - [{binary() | {binary(), binary(), [{binary(), binary()}] | '*'}, - atom()}], - content_type_a :: undefined - | {binary() | {binary(), binary(), [{binary(), binary()}] | '*'}, - atom()}, - - %% Language. - languages_p = [] :: [binary()], - language_a :: undefined | binary(), - - %% Charset. - charsets_p = undefined :: undefined | [binary()], - charset_a :: undefined | binary(), - - %% Range units. - ranges_a = [] :: [{binary(), atom()}], - - %% Whether the resource exists. - exists = false :: boolean(), - - %% Cached resource calls. - etag :: undefined | no_call | {strong | weak, binary()}, - last_modified :: undefined | no_call | calendar:datetime(), - expires :: undefined | no_call | calendar:datetime() | binary() -}). - --spec upgrade(Req, Env, module(), any()) - -> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -upgrade(Req0, Env, Handler, HandlerState0) -> - Method = cowboy_req:method(Req0), - case service_available(Req0, #state{method=Method, - handler=Handler, handler_state=HandlerState0}) of - {ok, Req, Result} -> - {ok, Req, Env#{result => Result}}; - {Mod, Req, HandlerState} -> - Mod:upgrade(Req, Env, Handler, HandlerState); - {Mod, Req, HandlerState, Opts} -> - Mod:upgrade(Req, Env, Handler, HandlerState, Opts) - end. - --spec upgrade(Req, Env, module(), any(), any()) - -> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -%% cowboy_rest takes no options. -upgrade(Req, Env, Handler, HandlerState, _Opts) -> - upgrade(Req, Env, Handler, HandlerState). - -service_available(Req, State) -> - expect(Req, State, service_available, true, fun known_methods/2, 503). - -%% known_methods/2 should return a list of binary methods. -known_methods(Req, State=#state{method=Method}) -> - case call(Req, State, known_methods) of - no_call when Method =:= <<"HEAD">>; Method =:= <<"GET">>; - Method =:= <<"POST">>; Method =:= <<"PUT">>; - Method =:= <<"PATCH">>; Method =:= <<"DELETE">>; - Method =:= <<"OPTIONS">> -> - next(Req, State, fun uri_too_long/2); - no_call -> - next(Req, State, 501); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {List, Req2, State2} -> - case lists:member(Method, List) of - true -> next(Req2, State2, fun uri_too_long/2); - false -> next(Req2, State2, 501) - end - end. - -uri_too_long(Req, State) -> - expect(Req, State, uri_too_long, false, fun allowed_methods/2, 414). - -%% allowed_methods/2 should return a list of binary methods. -allowed_methods(Req, State=#state{method=Method}) -> - case call(Req, State, allowed_methods) of - no_call when Method =:= <<"HEAD">>; Method =:= <<"GET">> -> - next(Req, State, fun malformed_request/2); - no_call when Method =:= <<"OPTIONS">> -> - next(Req, State#state{allowed_methods= - [<<"HEAD">>, <<"GET">>, <<"OPTIONS">>]}, - fun malformed_request/2); - no_call -> - method_not_allowed(Req, State, - [<<"HEAD">>, <<"GET">>, <<"OPTIONS">>]); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {List, Req2, State2} -> - case lists:member(Method, List) of - true when Method =:= <<"OPTIONS">> -> - next(Req2, State2#state{allowed_methods=List}, - fun malformed_request/2); - true -> - next(Req2, State2, fun malformed_request/2); - false -> - method_not_allowed(Req2, State2, List) - end - end. - -method_not_allowed(Req, State, []) -> - Req2 = cowboy_req:set_resp_header(<<"allow">>, <<>>, Req), - respond(Req2, State, 405); -method_not_allowed(Req, State, Methods) -> - << ", ", Allow/binary >> = << << ", ", M/binary >> || M <- Methods >>, - Req2 = cowboy_req:set_resp_header(<<"allow">>, Allow, Req), - respond(Req2, State, 405). - -malformed_request(Req, State) -> - expect(Req, State, malformed_request, false, fun is_authorized/2, 400). - -%% is_authorized/2 should return true or {false, WwwAuthenticateHeader}. -is_authorized(Req, State) -> - case call(Req, State, is_authorized) of - no_call -> - forbidden(Req, State); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {true, Req2, State2} -> - forbidden(Req2, State2); - {{false, AuthHead}, Req2, State2} -> - Req3 = cowboy_req:set_resp_header( - <<"www-authenticate">>, AuthHead, Req2), - respond(Req3, State2, 401) - end. - -forbidden(Req, State) -> - expect(Req, State, forbidden, false, fun rate_limited/2, 403). - -rate_limited(Req, State) -> - case call(Req, State, rate_limited) of - no_call -> - valid_content_headers(Req, State); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {false, Req2, State2} -> - valid_content_headers(Req2, State2); - {{true, RetryAfter0}, Req2, State2} -> - RetryAfter = if - is_integer(RetryAfter0), RetryAfter0 >= 0 -> - integer_to_binary(RetryAfter0); - is_tuple(RetryAfter0) -> - cowboy_clock:rfc1123(RetryAfter0) - end, - Req3 = cowboy_req:set_resp_header(<<"retry-after">>, RetryAfter, Req2), - respond(Req3, State2, 429) - end. - -valid_content_headers(Req, State) -> - expect(Req, State, valid_content_headers, true, - fun valid_entity_length/2, 501). - -valid_entity_length(Req, State) -> - expect(Req, State, valid_entity_length, true, fun options/2, 413). - -%% If you need to add additional headers to the response at this point, -%% you should do it directly in the options/2 call using set_resp_headers. -options(Req, State=#state{allowed_methods=Methods, method= <<"OPTIONS">>}) -> - case call(Req, State, options) of - no_call when Methods =:= [] -> - Req2 = cowboy_req:set_resp_header(<<"allow">>, <<>>, Req), - respond(Req2, State, 200); - no_call -> - << ", ", Allow/binary >> - = << << ", ", M/binary >> || M <- Methods >>, - Req2 = cowboy_req:set_resp_header(<<"allow">>, Allow, Req), - respond(Req2, State, 200); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {ok, Req2, State2} -> - respond(Req2, State2, 200) - end; -options(Req, State) -> - content_types_provided(Req, State). - -%% content_types_provided/2 should return a list of content types and their -%% associated callback function as a tuple: {{Type, SubType, Params}, Fun}. -%% Type and SubType are the media type as binary. Params is a list of -%% Key/Value tuple, with Key and Value a binary. Fun is the name of the -%% callback that will be used to return the content of the response. It is -%% given as an atom. -%% -%% An example of such return value would be: -%% {{<<"text">>, <<"html">>, []}, to_html} -%% -%% Note that it is also possible to return a binary content type that will -%% then be parsed by Cowboy. However note that while this may make your -%% resources a little more readable, this is a lot less efficient. -%% -%% An example of such return value would be: -%% {<<"text/html">>, to_html} -content_types_provided(Req, State) -> - case call(Req, State, content_types_provided) of - no_call -> - State2 = State#state{ - content_types_p=[{{<<"text">>, <<"html">>, '*'}, to_html}]}, - try cowboy_req:parse_header(<<"accept">>, Req) of - undefined -> - languages_provided( - Req#{media_type => {<<"text">>, <<"html">>, []}}, - State2#state{content_type_a={{<<"text">>, <<"html">>, []}, to_html}}); - Accept -> - choose_media_type(Req, State2, prioritize_accept(Accept)) - catch _:_ -> - respond(Req, State2, 400) - end; - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {[], Req2, State2} -> - not_acceptable(Req2, State2); - {CTP, Req2, State2} -> - CTP2 = [normalize_content_types(P) || P <- CTP], - State3 = State2#state{content_types_p=CTP2}, - try cowboy_req:parse_header(<<"accept">>, Req2) of - undefined -> - {PMT0, _Fun} = HeadCTP = hd(CTP2), - %% We replace the wildcard by an empty list of parameters. - PMT = case PMT0 of - {Type, SubType, '*'} -> {Type, SubType, []}; - _ -> PMT0 - end, - languages_provided( - Req2#{media_type => PMT}, - State3#state{content_type_a=HeadCTP}); - Accept -> - choose_media_type(Req2, State3, prioritize_accept(Accept)) - catch _:_ -> - respond(Req2, State3, 400) - end - end. - -normalize_content_types({ContentType, Callback}) - when is_binary(ContentType) -> - {cow_http_hd:parse_content_type(ContentType), Callback}; -normalize_content_types(Normalized) -> - Normalized. - -prioritize_accept(Accept) -> - lists:sort( - fun ({MediaTypeA, Quality, _AcceptParamsA}, - {MediaTypeB, Quality, _AcceptParamsB}) -> - %% Same quality, check precedence in more details. - prioritize_mediatype(MediaTypeA, MediaTypeB); - ({_MediaTypeA, QualityA, _AcceptParamsA}, - {_MediaTypeB, QualityB, _AcceptParamsB}) -> - %% Just compare the quality. - QualityA > QualityB - end, Accept). - -%% Media ranges can be overridden by more specific media ranges or -%% specific media types. If more than one media range applies to a given -%% type, the most specific reference has precedence. -%% -%% We always choose B over A when we can't decide between the two. -prioritize_mediatype({TypeA, SubTypeA, ParamsA}, {TypeB, SubTypeB, ParamsB}) -> - case TypeB of - TypeA -> - case SubTypeB of - SubTypeA -> length(ParamsA) > length(ParamsB); - <<"*">> -> true; - _Any -> false - end; - <<"*">> -> true; - _Any -> false - end. - -%% Ignoring the rare AcceptParams. Not sure what should be done about them. -choose_media_type(Req, State, []) -> - not_acceptable(Req, State); -choose_media_type(Req, State=#state{content_types_p=CTP}, - [MediaType|Tail]) -> - match_media_type(Req, State, Tail, CTP, MediaType). - -match_media_type(Req, State, Accept, [], _MediaType) -> - choose_media_type(Req, State, Accept); -match_media_type(Req, State, Accept, CTP, - MediaType = {{<<"*">>, <<"*">>, _Params_A}, _QA, _APA}) -> - match_media_type_params(Req, State, Accept, CTP, MediaType); -match_media_type(Req, State, Accept, - CTP = [{{Type, SubType_P, _PP}, _Fun}|_Tail], - MediaType = {{Type, SubType_A, _PA}, _QA, _APA}) - when SubType_P =:= SubType_A; SubType_A =:= <<"*">> -> - match_media_type_params(Req, State, Accept, CTP, MediaType); -match_media_type(Req, State, Accept, [_Any|Tail], MediaType) -> - match_media_type(Req, State, Accept, Tail, MediaType). - -match_media_type_params(Req, State, Accept, - [Provided = {{TP, STP, '*'}, _Fun}|Tail], - MediaType = {{TA, _STA, Params_A0}, _QA, _APA}) -> - case lists:keytake(<<"charset">>, 1, Params_A0) of - {value, {_, Charset}, Params_A} when TA =:= <<"text">> -> - %% When we match against a wildcard, the media type is text - %% and has a charset parameter, we call charsets_provided - %% and check that the charset is provided. If the callback - %% is not exported, we accept inconditionally but ignore - %% the given charset so as to not send a wrong value back. - case call(Req, State, charsets_provided) of - no_call -> - languages_provided(Req#{media_type => {TP, STP, Params_A0}}, - State#state{content_type_a=Provided}); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {CP, Req2, State2} -> - State3 = State2#state{charsets_p=CP}, - case lists:member(Charset, CP) of - false -> - match_media_type(Req2, State3, Accept, Tail, MediaType); - true -> - languages_provided(Req2#{media_type => {TP, STP, Params_A}}, - State3#state{content_type_a=Provided, - charset_a=Charset}) - end - end; - _ -> - languages_provided(Req#{media_type => {TP, STP, Params_A0}}, - State#state{content_type_a=Provided}) - end; -match_media_type_params(Req, State, Accept, - [Provided = {PMT = {TP, STP, Params_P0}, Fun}|Tail], - MediaType = {{_TA, _STA, Params_A}, _QA, _APA}) -> - case lists:sort(Params_P0) =:= lists:sort(Params_A) of - true when TP =:= <<"text">> -> - %% When a charset was provided explicitly in both the charset header - %% and the media types provided and the negotiation is successful, - %% we keep the charset and don't call charsets_provided. This only - %% applies to text media types, however. - {Charset, Params_P} = case lists:keytake(<<"charset">>, 1, Params_P0) of - false -> {undefined, Params_P0}; - {value, {_, Charset0}, Params_P1} -> {Charset0, Params_P1} - end, - languages_provided(Req#{media_type => {TP, STP, Params_P}}, - State#state{content_type_a={{TP, STP, Params_P}, Fun}, - charset_a=Charset}); - true -> - languages_provided(Req#{media_type => PMT}, - State#state{content_type_a=Provided}); - false -> - match_media_type(Req, State, Accept, Tail, MediaType) - end. - -%% languages_provided should return a list of binary values indicating -%% which languages are accepted by the resource. -%% -%% @todo I suppose we should also ask the resource if it wants to -%% set a language itself or if it wants it to be automatically chosen. -languages_provided(Req, State) -> - case call(Req, State, languages_provided) of - no_call -> - charsets_provided(Req, State); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {[], Req2, State2} -> - not_acceptable(Req2, State2); - {LP, Req2, State2} -> - State3 = State2#state{languages_p=LP}, - case cowboy_req:parse_header(<<"accept-language">>, Req2) of - undefined -> - set_language(Req2, State3#state{language_a=hd(LP)}); - AcceptLanguage -> - AcceptLanguage2 = prioritize_languages(AcceptLanguage), - choose_language(Req2, State3, AcceptLanguage2) - end - end. - -%% A language-range matches a language-tag if it exactly equals the tag, -%% or if it exactly equals a prefix of the tag such that the first tag -%% character following the prefix is "-". The special range "*", if -%% present in the Accept-Language field, matches every tag not matched -%% by any other range present in the Accept-Language field. -%% -%% @todo The last sentence probably means we should always put '*' -%% at the end of the list. -prioritize_languages(AcceptLanguages) -> - lists:sort( - fun ({_TagA, QualityA}, {_TagB, QualityB}) -> - QualityA > QualityB - end, AcceptLanguages). - -choose_language(Req, State, []) -> - not_acceptable(Req, State); -choose_language(Req, State=#state{languages_p=LP}, [Language|Tail]) -> - match_language(Req, State, Tail, LP, Language). - -match_language(Req, State, Accept, [], _Language) -> - choose_language(Req, State, Accept); -match_language(Req, State, _Accept, [Provided|_Tail], {'*', _Quality}) -> - set_language(Req, State#state{language_a=Provided}); -match_language(Req, State, _Accept, [Provided|_Tail], {Provided, _Quality}) -> - set_language(Req, State#state{language_a=Provided}); -match_language(Req, State, Accept, [Provided|Tail], - Language = {Tag, _Quality}) -> - Length = byte_size(Tag), - case Provided of - << Tag:Length/binary, $-, _Any/bits >> -> - set_language(Req, State#state{language_a=Provided}); - _Any -> - match_language(Req, State, Accept, Tail, Language) - end. - -set_language(Req, State=#state{language_a=Language}) -> - Req2 = cowboy_req:set_resp_header(<<"content-language">>, Language, Req), - charsets_provided(Req2#{language => Language}, State). - -%% charsets_provided should return a list of binary values indicating -%% which charsets are accepted by the resource. -%% -%% A charset may have been selected while negotiating the accept header. -%% There's no need to select one again. -charsets_provided(Req, State=#state{charset_a=Charset}) - when Charset =/= undefined -> - set_content_type(Req, State); -%% If charsets_p is defined, use it instead of calling charsets_provided -%% again. We also call this clause during normal execution to avoid -%% duplicating code. -charsets_provided(Req, State=#state{charsets_p=[]}) -> - not_acceptable(Req, State); -charsets_provided(Req, State=#state{charsets_p=CP}) - when CP =/= undefined -> - case cowboy_req:parse_header(<<"accept-charset">>, Req) of - undefined -> - set_content_type(Req, State#state{charset_a=hd(CP)}); - AcceptCharset0 -> - AcceptCharset = prioritize_charsets(AcceptCharset0), - choose_charset(Req, State, AcceptCharset) - end; -charsets_provided(Req, State) -> - case call(Req, State, charsets_provided) of - no_call -> - set_content_type(Req, State); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {CP, Req2, State2} -> - charsets_provided(Req2, State2#state{charsets_p=CP}) - end. - -prioritize_charsets(AcceptCharsets) -> - lists:sort( - fun ({_CharsetA, QualityA}, {_CharsetB, QualityB}) -> - QualityA > QualityB - end, AcceptCharsets). - -choose_charset(Req, State, []) -> - not_acceptable(Req, State); -%% A q-value of 0 means not acceptable. -choose_charset(Req, State, [{_, 0}|Tail]) -> - choose_charset(Req, State, Tail); -choose_charset(Req, State=#state{charsets_p=CP}, [Charset|Tail]) -> - match_charset(Req, State, Tail, CP, Charset). - -match_charset(Req, State, Accept, [], _Charset) -> - choose_charset(Req, State, Accept); -match_charset(Req, State, _Accept, [Provided|_], {<<"*">>, _}) -> - set_content_type(Req, State#state{charset_a=Provided}); -match_charset(Req, State, _Accept, [Provided|_], {Provided, _}) -> - set_content_type(Req, State#state{charset_a=Provided}); -match_charset(Req, State, Accept, [_|Tail], Charset) -> - match_charset(Req, State, Accept, Tail, Charset). - -set_content_type(Req, State=#state{ - content_type_a={{Type, SubType, Params}, _Fun}, - charset_a=Charset}) -> - ParamsBin = set_content_type_build_params(Params, []), - ContentType = [Type, <<"/">>, SubType, ParamsBin], - ContentType2 = case {Type, Charset} of - {<<"text">>, Charset} when Charset =/= undefined -> - [ContentType, <<"; charset=">>, Charset]; - _ -> - ContentType - end, - Req2 = cowboy_req:set_resp_header(<<"content-type">>, ContentType2, Req), - encodings_provided(Req2#{charset => Charset}, State). - -set_content_type_build_params('*', []) -> - <<>>; -set_content_type_build_params([], []) -> - <<>>; -set_content_type_build_params([], Acc) -> - lists:reverse(Acc); -set_content_type_build_params([{Attr, Value}|Tail], Acc) -> - set_content_type_build_params(Tail, [[Attr, <<"=">>, Value], <<";">>|Acc]). - -%% @todo Match for identity as we provide nothing else for now. -%% @todo Don't forget to set the Content-Encoding header when we reply a body -%% and the found encoding is something other than identity. -encodings_provided(Req, State) -> - ranges_provided(Req, State). - -not_acceptable(Req, State) -> - respond(Req, State, 406). - -ranges_provided(Req, State) -> - case call(Req, State, ranges_provided) of - no_call -> - variances(Req, State); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {[], Req2, State2} -> - Req3 = cowboy_req:set_resp_header(<<"accept-ranges">>, <<"none">>, Req2), - variances(Req3, State2#state{ranges_a=[]}); - {RP, Req2, State2} -> - <<", ", AcceptRanges/binary>> = <<<<", ", R/binary>> || {R, _} <- RP>>, - Req3 = cowboy_req:set_resp_header(<<"accept-ranges">>, AcceptRanges, Req2), - variances(Req3, State2#state{ranges_a=RP}) - end. - -%% variances/2 should return a list of headers that will be added -%% to the Vary response header. The Accept, Accept-Language, -%% Accept-Charset and Accept-Encoding headers do not need to be -%% specified. -%% -%% @todo Do Accept-Encoding too when we handle it. -%% @todo Does the order matter? -variances(Req, State=#state{content_types_p=CTP, - languages_p=LP, charsets_p=CP}) -> - Variances = case CTP of - [] -> []; - [_] -> []; - [_|_] -> [<<"accept">>] - end, - Variances2 = case LP of - [] -> Variances; - [_] -> Variances; - [_|_] -> [<<"accept-language">>|Variances] - end, - Variances3 = case CP of - undefined -> Variances2; - [] -> Variances2; - [_] -> Variances2; - [_|_] -> [<<"accept-charset">>|Variances2] - end, - try variances(Req, State, Variances3) of - {Variances4, Req2, State2} -> - case [[<<", ">>, V] || V <- Variances4] of - [] -> - resource_exists(Req2, State2); - [[<<", ">>, H]|Variances5] -> - Req3 = cowboy_req:set_resp_header( - <<"vary">>, [H|Variances5], Req2), - resource_exists(Req3, State2) - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -variances(Req, State, Variances) -> - case unsafe_call(Req, State, variances) of - no_call -> - {Variances, Req, State}; - {HandlerVariances, Req2, State2} -> - {Variances ++ HandlerVariances, Req2, State2} - end. - -resource_exists(Req, State) -> - expect(Req, State, resource_exists, true, - fun if_match_exists/2, fun if_match_must_not_exist/2). - -if_match_exists(Req, State) -> - State2 = State#state{exists=true}, - case cowboy_req:parse_header(<<"if-match">>, Req) of - undefined -> - if_unmodified_since_exists(Req, State2); - '*' -> - if_unmodified_since_exists(Req, State2); - ETagsList -> - if_match(Req, State2, ETagsList) - end. - -if_match(Req, State, EtagsList) -> - try generate_etag(Req, State) of - %% Strong Etag comparison: weak Etag never matches. - {{weak, _}, Req2, State2} -> - precondition_failed(Req2, State2); - {Etag, Req2, State2} -> - case lists:member(Etag, EtagsList) of - true -> if_none_match_exists(Req2, State2); - %% Etag may be `undefined' which cannot be a member. - false -> precondition_failed(Req2, State2) - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -if_match_must_not_exist(Req, State) -> - case cowboy_req:header(<<"if-match">>, Req) of - undefined -> is_put_to_missing_resource(Req, State); - _ -> precondition_failed(Req, State) - end. - -if_unmodified_since_exists(Req, State) -> - try cowboy_req:parse_header(<<"if-unmodified-since">>, Req) of - undefined -> - if_none_match_exists(Req, State); - IfUnmodifiedSince -> - if_unmodified_since(Req, State, IfUnmodifiedSince) - catch _:_ -> - if_none_match_exists(Req, State) - end. - -%% If LastModified is the atom 'no_call', we continue. -if_unmodified_since(Req, State, IfUnmodifiedSince) -> - try last_modified(Req, State) of - {LastModified, Req2, State2} -> - case LastModified > IfUnmodifiedSince of - true -> precondition_failed(Req2, State2); - false -> if_none_match_exists(Req2, State2) - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -if_none_match_exists(Req, State) -> - case cowboy_req:parse_header(<<"if-none-match">>, Req) of - undefined -> - if_modified_since_exists(Req, State); - '*' -> - precondition_is_head_get(Req, State); - EtagsList -> - if_none_match(Req, State, EtagsList) - end. - -if_none_match(Req, State, EtagsList) -> - try generate_etag(Req, State) of - {Etag, Req2, State2} -> - case Etag of - undefined -> - precondition_failed(Req2, State2); - Etag -> - case is_weak_match(Etag, EtagsList) of - true -> precondition_is_head_get(Req2, State2); - false -> method(Req2, State2) - end - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -%% Weak Etag comparison: only check the opaque tag. -is_weak_match(_, []) -> - false; -is_weak_match({_, Tag}, [{_, Tag}|_]) -> - true; -is_weak_match(Etag, [_|Tail]) -> - is_weak_match(Etag, Tail). - -precondition_is_head_get(Req, State=#state{method=Method}) - when Method =:= <<"HEAD">>; Method =:= <<"GET">> -> - not_modified(Req, State); -precondition_is_head_get(Req, State) -> - precondition_failed(Req, State). - -if_modified_since_exists(Req, State) -> - try cowboy_req:parse_header(<<"if-modified-since">>, Req) of - undefined -> - method(Req, State); - IfModifiedSince -> - if_modified_since_now(Req, State, IfModifiedSince) - catch _:_ -> - method(Req, State) - end. - -if_modified_since_now(Req, State, IfModifiedSince) -> - case IfModifiedSince > erlang:universaltime() of - true -> method(Req, State); - false -> if_modified_since(Req, State, IfModifiedSince) - end. - -if_modified_since(Req, State, IfModifiedSince) -> - try last_modified(Req, State) of - {undefined, Req2, State2} -> - method(Req2, State2); - {LastModified, Req2, State2} -> - case LastModified > IfModifiedSince of - true -> method(Req2, State2); - false -> not_modified(Req2, State2) - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -not_modified(Req, State) -> - Req2 = cowboy_req:delete_resp_header(<<"content-type">>, Req), - try set_resp_etag(Req2, State) of - {Req3, State2} -> - try set_resp_expires(Req3, State2) of - {Req4, State3} -> - respond(Req4, State3, 304) - catch Class:Reason -> - error_terminate(Req, State2, Class, Reason) - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -precondition_failed(Req, State) -> - respond(Req, State, 412). - -is_put_to_missing_resource(Req, State=#state{method= <<"PUT">>}) -> - moved_permanently(Req, State, fun is_conflict/2); -is_put_to_missing_resource(Req, State) -> - previously_existed(Req, State). - -%% moved_permanently/2 should return either false or {true, Location} -%% with Location the full new URI of the resource. -moved_permanently(Req, State, OnFalse) -> - case call(Req, State, moved_permanently) of - {{true, Location}, Req2, State2} -> - Req3 = cowboy_req:set_resp_header( - <<"location">>, Location, Req2), - respond(Req3, State2, 301); - {false, Req2, State2} -> - OnFalse(Req2, State2); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - no_call -> - OnFalse(Req, State) - end. - -previously_existed(Req, State) -> - expect(Req, State, previously_existed, false, - fun (R, S) -> is_post_to_missing_resource(R, S, 404) end, - fun (R, S) -> moved_permanently(R, S, fun moved_temporarily/2) end). - -%% moved_temporarily/2 should return either false or {true, Location} -%% with Location the full new URI of the resource. -moved_temporarily(Req, State) -> - case call(Req, State, moved_temporarily) of - {{true, Location}, Req2, State2} -> - Req3 = cowboy_req:set_resp_header( - <<"location">>, Location, Req2), - respond(Req3, State2, 307); - {false, Req2, State2} -> - is_post_to_missing_resource(Req2, State2, 410); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - no_call -> - is_post_to_missing_resource(Req, State, 410) - end. - -is_post_to_missing_resource(Req, State=#state{method= <<"POST">>}, OnFalse) -> - allow_missing_post(Req, State, OnFalse); -is_post_to_missing_resource(Req, State, OnFalse) -> - respond(Req, State, OnFalse). - -allow_missing_post(Req, State, OnFalse) -> - expect(Req, State, allow_missing_post, true, fun accept_resource/2, OnFalse). - -method(Req, State=#state{method= <<"DELETE">>}) -> - delete_resource(Req, State); -method(Req, State=#state{method= <<"PUT">>}) -> - is_conflict(Req, State); -method(Req, State=#state{method=Method}) - when Method =:= <<"POST">>; Method =:= <<"PATCH">> -> - accept_resource(Req, State); -method(Req, State=#state{method=Method}) - when Method =:= <<"GET">>; Method =:= <<"HEAD">> -> - set_resp_body_etag(Req, State); -method(Req, State) -> - multiple_choices(Req, State). - -%% delete_resource/2 should start deleting the resource and return. -delete_resource(Req, State) -> - expect(Req, State, delete_resource, false, 500, fun delete_completed/2). - -%% delete_completed/2 indicates whether the resource has been deleted yet. -delete_completed(Req, State) -> - expect(Req, State, delete_completed, true, fun has_resp_body/2, 202). - -is_conflict(Req, State) -> - expect(Req, State, is_conflict, false, fun accept_resource/2, 409). - -%% content_types_accepted should return a list of media types and their -%% associated callback functions in the same format as content_types_provided. -%% -%% The callback will then be called and is expected to process the content -%% pushed to the resource in the request body. -%% -%% content_types_accepted SHOULD return a different list -%% for each HTTP method. -accept_resource(Req, State) -> - case call(Req, State, content_types_accepted) of - no_call -> - respond(Req, State, 415); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {CTA, Req2, State2} -> - CTA2 = [normalize_content_types(P) || P <- CTA], - try cowboy_req:parse_header(<<"content-type">>, Req2) of - %% We do not match against the boundary parameter for multipart. - {Type = <<"multipart">>, SubType, Params} -> - ContentType = {Type, SubType, lists:keydelete(<<"boundary">>, 1, Params)}, - choose_content_type(Req2, State2, ContentType, CTA2); - ContentType -> - choose_content_type(Req2, State2, ContentType, CTA2) - catch _:_ -> - respond(Req2, State2, 415) - end - end. - -%% The special content type '*' will always match. It can be used as a -%% catch-all content type for accepting any kind of request content. -%% Note that because it will always match, it should be the last of the -%% list of content types, otherwise it'll shadow the ones following. -choose_content_type(Req, State, _ContentType, []) -> - respond(Req, State, 415); -choose_content_type(Req, State, ContentType, [{Accepted, Fun}|_Tail]) - when Accepted =:= '*'; Accepted =:= ContentType -> - process_content_type(Req, State, Fun); -%% The special parameter '*' will always match any kind of content type -%% parameters. -%% Note that because it will always match, it should be the last of the -%% list for specific content type, otherwise it'll shadow the ones following. -choose_content_type(Req, State, {Type, SubType, Param}, - [{{Type, SubType, AcceptedParam}, Fun}|_Tail]) - when AcceptedParam =:= '*'; AcceptedParam =:= Param -> - process_content_type(Req, State, Fun); -choose_content_type(Req, State, ContentType, [_Any|Tail]) -> - choose_content_type(Req, State, ContentType, Tail). - -process_content_type(Req, State=#state{method=Method, exists=Exists}, Fun) -> - try case call(Req, State, Fun) of - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {true, Req2, State2} when Exists -> - next(Req2, State2, fun has_resp_body/2); - {true, Req2, State2} -> - next(Req2, State2, fun maybe_created/2); - {false, Req2, State2} -> - respond(Req2, State2, 400); - {{true, ResURL}, Req2, State2} when Method =:= <<"POST">> -> - Req3 = cowboy_req:set_resp_header( - <<"location">>, ResURL, Req2), - if - Exists -> respond(Req3, State2, 303); - true -> respond(Req3, State2, 201) - end - end catch Class:Reason = {case_clause, no_call} -> - error_terminate(Req, State, Class, Reason) - end. - -%% If PUT was used then the resource has been created at the current URL. -%% Otherwise, if a location header has been set then the resource has been -%% created at a new URL. If not, send a 200 or 204 as expected from a -%% POST or PATCH request. -maybe_created(Req, State=#state{method= <<"PUT">>}) -> - respond(Req, State, 201); -maybe_created(Req, State) -> - case cowboy_req:has_resp_header(<<"location">>, Req) of - true -> respond(Req, State, 201); - false -> has_resp_body(Req, State) - end. - -has_resp_body(Req, State) -> - case cowboy_req:has_resp_body(Req) of - true -> multiple_choices(Req, State); - false -> respond(Req, State, 204) - end. - -%% Set the Etag header if any for the response provided. -set_resp_body_etag(Req, State) -> - try set_resp_etag(Req, State) of - {Req2, State2} -> - set_resp_body_last_modified(Req2, State2) - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -%% Set the Last-Modified header if any for the response provided. -set_resp_body_last_modified(Req, State) -> - try last_modified(Req, State) of - {LastModified, Req2, State2} -> - case LastModified of - LastModified when is_atom(LastModified) -> - set_resp_body_expires(Req2, State2); - LastModified -> - LastModifiedBin = cowboy_clock:rfc1123(LastModified), - Req3 = cowboy_req:set_resp_header( - <<"last-modified">>, LastModifiedBin, Req2), - set_resp_body_expires(Req3, State2) - end - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -%% Set the Expires header if any for the response provided. -set_resp_body_expires(Req, State) -> - try set_resp_expires(Req, State) of - {Req2, State2} -> - if_range(Req2, State2) - catch Class:Reason -> - error_terminate(Req, State, Class, Reason) - end. - -%% When both the if-range and range headers are set, we perform -%% a strong comparison. If it fails, we send a full response. -if_range(Req=#{headers := #{<<"if-range">> := _, <<"range">> := _}}, - State=#state{etag=Etag}) -> - try cowboy_req:parse_header(<<"if-range">>, Req) of - %% Strong etag comparison is an exact match with the generate_etag result. - Etag={strong, _} -> - range(Req, State); - %% We cannot do a strong date comparison because we have - %% no way of knowing whether the representation changed - %% twice during the second covered by the presented - %% validator. (RFC7232 2.2.2) - _ -> - set_resp_body(Req, State) - catch _:_ -> - set_resp_body(Req, State) - end; -if_range(Req, State) -> - range(Req, State). - -range(Req, State=#state{ranges_a=[]}) -> - set_resp_body(Req, State); -range(Req, State) -> - try cowboy_req:parse_header(<<"range">>, Req) of - undefined -> - set_resp_body(Req, State); - %% @todo Maybe change parse_header to return <<"bytes">> in 3.0. - {bytes, BytesRange} -> - choose_range(Req, State, {<<"bytes">>, BytesRange}); - Range -> - choose_range(Req, State, Range) - catch _:_ -> - %% We send a 416 response back when we can't parse the - %% range header at all. I'm not sure this is the right - %% way to go but at least this can help clients identify - %% what went wrong when their range requests never work. - range_not_satisfiable(Req, State, undefined) - end. - -choose_range(Req, State=#state{ranges_a=RangesAccepted}, Range={RangeUnit, _}) -> - case lists:keyfind(RangeUnit, 1, RangesAccepted) of - {_, Callback} -> - %% We pass the selected range onward in the Req. - range_satisfiable(Req#{range => Range}, State, Callback); - false -> - set_resp_body(Req, State) - end. - -range_satisfiable(Req, State, Callback) -> - case call(Req, State, range_satisfiable) of - no_call -> - set_ranged_body(Req, State, Callback); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {true, Req2, State2} -> - set_ranged_body(Req2, State2, Callback); - {false, Req2, State2} -> - range_not_satisfiable(Req2, State2, undefined); - {{false, Int}, Req2, State2} when is_integer(Int) -> - range_not_satisfiable(Req2, State2, [<<"*/">>, integer_to_binary(Int)]); - {{false, Iodata}, Req2, State2} when is_binary(Iodata); is_list(Iodata) -> - range_not_satisfiable(Req2, State2, Iodata) - end. - -%% When the callback selected is 'auto' and the range unit -%% is bytes, we call the normal provide callback and split -%% the content automatically. -set_ranged_body(Req=#{range := {<<"bytes">>, _}}, State, auto) -> - set_ranged_body_auto(Req, State); -set_ranged_body(Req, State, Callback) -> - set_ranged_body_callback(Req, State, Callback). - -set_ranged_body_auto(Req, State=#state{handler=Handler, content_type_a={_, Callback}}) -> - try case call(Req, State, Callback) of - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {Body, Req2, State2} -> - maybe_set_ranged_body_auto(Req2, State2, Body) - end catch Class:{case_clause, no_call} -> - error_terminate(Req, State, Class, {error, {missing_callback, {Handler, Callback, 2}}, - 'A callback specified in content_types_provided/2 is not exported.'}) - end. - -maybe_set_ranged_body_auto(Req=#{range := {_, Ranges}}, State, Body) -> - Size = case Body of - {sendfile, _, Bytes, _} -> Bytes; - _ -> iolist_size(Body) - end, - Checks = [case Range of - {From, infinity} -> From < Size; - {From, To} -> (From < Size) andalso (From =< To) andalso (To =< Size); - Neg -> (Neg =/= 0) andalso (-Neg < Size) - end || Range <- Ranges], - case lists:usort(Checks) of - [true] -> set_ranged_body_auto(Req, State, Body); - _ -> range_not_satisfiable(Req, State, [<<"*/">>, integer_to_binary(Size)]) - end. - -%% We might also want to have some checks about range order, -%% number of ranges, and perhaps also join ranges that are -%% too close into one contiguous range. Some of these can -%% be done before calling the ProvideCallback. - -set_ranged_body_auto(Req=#{range := {_, Ranges}}, State, Body) -> - Parts = [ranged_partition(Range, Body) || Range <- Ranges], - case Parts of - [OnePart] -> set_one_ranged_body(Req, State, OnePart); - _ when is_tuple(Body) -> send_multipart_ranged_body(Req, State, Parts); - _ -> set_multipart_ranged_body(Req, State, Parts) - end. - -ranged_partition(Range, {sendfile, Offset0, Bytes0, Path}) -> - {From, To, Offset, Bytes} = case Range of - {From0, infinity} -> {From0, Bytes0 - 1, Offset0 + From0, Bytes0 - From0}; - {From0, To0} -> {From0, To0, Offset0 + From0, 1 + To0 - From0}; - Neg -> {Bytes0 + Neg, Bytes0 - 1, Offset0 + Bytes0 + Neg, -Neg} - end, - {{From, To, Bytes0}, {sendfile, Offset, Bytes, Path}}; -ranged_partition(Range, Data0) -> - Total = iolist_size(Data0), - {From, To, Data} = case Range of - {From0, infinity} -> - {_, Data1} = cow_iolists:split(From0, Data0), - {From0, Total - 1, Data1}; - {From0, To0} -> - {_, Data1} = cow_iolists:split(From0, Data0), - {Data2, _} = cow_iolists:split(To0 - From0 + 1, Data1), - {From0, To0, Data2}; - Neg -> - {_, Data1} = cow_iolists:split(Total + Neg, Data0), - {Total + Neg, Total - 1, Data1} - end, - {{From, To, Total}, Data}. - --ifdef(TEST). -ranged_partition_test_() -> - Tests = [ - %% Sendfile with open-ended range. - {{0, infinity}, {sendfile, 0, 12, "t"}, {{0, 11, 12}, {sendfile, 0, 12, "t"}}}, - {{6, infinity}, {sendfile, 0, 12, "t"}, {{6, 11, 12}, {sendfile, 6, 6, "t"}}}, - {{11, infinity}, {sendfile, 0, 12, "t"}, {{11, 11, 12}, {sendfile, 11, 1, "t"}}}, - %% Sendfile with open-ended range. Sendfile tuple has an offset originally. - {{0, infinity}, {sendfile, 3, 12, "t"}, {{0, 11, 12}, {sendfile, 3, 12, "t"}}}, - {{6, infinity}, {sendfile, 3, 12, "t"}, {{6, 11, 12}, {sendfile, 9, 6, "t"}}}, - {{11, infinity}, {sendfile, 3, 12, "t"}, {{11, 11, 12}, {sendfile, 14, 1, "t"}}}, - %% Sendfile with a specific range. - {{0, 11}, {sendfile, 0, 12, "t"}, {{0, 11, 12}, {sendfile, 0, 12, "t"}}}, - {{6, 11}, {sendfile, 0, 12, "t"}, {{6, 11, 12}, {sendfile, 6, 6, "t"}}}, - {{11, 11}, {sendfile, 0, 12, "t"}, {{11, 11, 12}, {sendfile, 11, 1, "t"}}}, - {{1, 10}, {sendfile, 0, 12, "t"}, {{1, 10, 12}, {sendfile, 1, 10, "t"}}}, - %% Sendfile with a specific range. Sendfile tuple has an offset originally. - {{0, 11}, {sendfile, 3, 12, "t"}, {{0, 11, 12}, {sendfile, 3, 12, "t"}}}, - {{6, 11}, {sendfile, 3, 12, "t"}, {{6, 11, 12}, {sendfile, 9, 6, "t"}}}, - {{11, 11}, {sendfile, 3, 12, "t"}, {{11, 11, 12}, {sendfile, 14, 1, "t"}}}, - {{1, 10}, {sendfile, 3, 12, "t"}, {{1, 10, 12}, {sendfile, 4, 10, "t"}}}, - %% Sendfile with negative range. - {-12, {sendfile, 0, 12, "t"}, {{0, 11, 12}, {sendfile, 0, 12, "t"}}}, - {-6, {sendfile, 0, 12, "t"}, {{6, 11, 12}, {sendfile, 6, 6, "t"}}}, - {-1, {sendfile, 0, 12, "t"}, {{11, 11, 12}, {sendfile, 11, 1, "t"}}}, - %% Sendfile with negative range. Sendfile tuple has an offset originally. - {-12, {sendfile, 3, 12, "t"}, {{0, 11, 12}, {sendfile, 3, 12, "t"}}}, - {-6, {sendfile, 3, 12, "t"}, {{6, 11, 12}, {sendfile, 9, 6, "t"}}}, - {-1, {sendfile, 3, 12, "t"}, {{11, 11, 12}, {sendfile, 14, 1, "t"}}}, - %% Iodata with open-ended range. - {{0, infinity}, <<"Hello world!">>, {{0, 11, 12}, <<"Hello world!">>}}, - {{6, infinity}, <<"Hello world!">>, {{6, 11, 12}, <<"world!">>}}, - {{11, infinity}, <<"Hello world!">>, {{11, 11, 12}, <<"!">>}}, - %% Iodata with a specific range. The resulting data is - %% wrapped in a list because of how cow_iolists:split/2 works. - {{0, 11}, <<"Hello world!">>, {{0, 11, 12}, [<<"Hello world!">>]}}, - {{6, 11}, <<"Hello world!">>, {{6, 11, 12}, [<<"world!">>]}}, - {{11, 11}, <<"Hello world!">>, {{11, 11, 12}, [<<"!">>]}}, - {{1, 10}, <<"Hello world!">>, {{1, 10, 12}, [<<"ello world">>]}}, - %% Iodata with negative range. - {-12, <<"Hello world!">>, {{0, 11, 12}, <<"Hello world!">>}}, - {-6, <<"Hello world!">>, {{6, 11, 12}, <<"world!">>}}, - {-1, <<"Hello world!">>, {{11, 11, 12}, <<"!">>}} - ], - [{iolist_to_binary(io_lib:format("range ~p data ~p", [VR, VD])), - fun() -> R = ranged_partition(VR, VD) end} || {VR, VD, R} <- Tests]. --endif. - -set_ranged_body_callback(Req, State=#state{handler=Handler}, Callback) -> - try case call(Req, State, Callback) of - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - %% When we receive a single range, we send it directly. - {[OneRange], Req2, State2} -> - set_one_ranged_body(Req2, State2, OneRange); - %% When we receive multiple ranges we have to send them as multipart/byteranges. - %% This also applies to non-bytes units. (RFC7233 A) If users don't want to use - %% this for non-bytes units they can always return a single range with a binary - %% content-range information. - {Ranges, Req2, State2} when length(Ranges) > 1 -> - %% We have to check whether there are sendfile tuples in the - %% ranges to be sent. If there are we must use stream_reply. - HasSendfile = [] =/= [true || {_, {sendfile, _, _, _}} <- Ranges], - case HasSendfile of - true -> send_multipart_ranged_body(Req2, State2, Ranges); - false -> set_multipart_ranged_body(Req2, State2, Ranges) - end - end catch Class:{case_clause, no_call} -> - error_terminate(Req, State, Class, {error, {missing_callback, {Handler, Callback, 2}}, - 'A callback specified in ranges_provided/2 is not exported.'}) - end. - -set_one_ranged_body(Req0, State, OneRange) -> - {ContentRange, Body} = prepare_range(Req0, OneRange), - Req1 = cowboy_req:set_resp_header(<<"content-range">>, ContentRange, Req0), - Req = cowboy_req:set_resp_body(Body, Req1), - respond(Req, State, 206). - -set_multipart_ranged_body(Req, State, [FirstRange|MoreRanges]) -> - Boundary = cow_multipart:boundary(), - ContentType = cowboy_req:resp_header(<<"content-type">>, Req), - {FirstContentRange, FirstPartBody} = prepare_range(Req, FirstRange), - FirstPartHead = cow_multipart:first_part(Boundary, [ - {<<"content-type">>, ContentType}, - {<<"content-range">>, FirstContentRange} - ]), - MoreParts = [begin - {NextContentRange, NextPartBody} = prepare_range(Req, NextRange), - NextPartHead = cow_multipart:part(Boundary, [ - {<<"content-type">>, ContentType}, - {<<"content-range">>, NextContentRange} - ]), - [NextPartHead, NextPartBody] - end || NextRange <- MoreRanges], - Body = [FirstPartHead, FirstPartBody, MoreParts, cow_multipart:close(Boundary)], - Req2 = cowboy_req:set_resp_header(<<"content-type">>, - [<<"multipart/byteranges; boundary=">>, Boundary], Req), - Req3 = cowboy_req:set_resp_body(Body, Req2), - respond(Req3, State, 206). - -%% Similar to set_multipart_ranged_body except we have to stream -%% the data because the parts contain sendfile tuples. -send_multipart_ranged_body(Req, State, [FirstRange|MoreRanges]) -> - Boundary = cow_multipart:boundary(), - ContentType = cowboy_req:resp_header(<<"content-type">>, Req), - Req2 = cowboy_req:set_resp_header(<<"content-type">>, - [<<"multipart/byteranges; boundary=">>, Boundary], Req), - Req3 = cowboy_req:stream_reply(206, Req2), - {FirstContentRange, FirstPartBody} = prepare_range(Req, FirstRange), - FirstPartHead = cow_multipart:first_part(Boundary, [ - {<<"content-type">>, ContentType}, - {<<"content-range">>, FirstContentRange} - ]), - cowboy_req:stream_body(FirstPartHead, nofin, Req3), - cowboy_req:stream_body(FirstPartBody, nofin, Req3), - _ = [begin - {NextContentRange, NextPartBody} = prepare_range(Req, NextRange), - NextPartHead = cow_multipart:part(Boundary, [ - {<<"content-type">>, ContentType}, - {<<"content-range">>, NextContentRange} - ]), - cowboy_req:stream_body(NextPartHead, nofin, Req3), - cowboy_req:stream_body(NextPartBody, nofin, Req3), - [NextPartHead, NextPartBody] - end || NextRange <- MoreRanges], - cowboy_req:stream_body(cow_multipart:close(Boundary), fin, Req3), - terminate(Req3, State). - -prepare_range(#{range := {RangeUnit, _}}, {{From, To, Total0}, Body}) -> - Total = case Total0 of - '*' -> <<"*">>; - _ -> integer_to_binary(Total0) - end, - ContentRange = [RangeUnit, $\s, integer_to_binary(From), - $-, integer_to_binary(To), $/, Total], - {ContentRange, Body}; -prepare_range(#{range := {RangeUnit, _}}, {RangeData, Body}) -> - {[RangeUnit, $\s, RangeData], Body}. - -%% We send the content-range header when we can on error. -range_not_satisfiable(Req, State, undefined) -> - respond(Req, State, 416); -range_not_satisfiable(Req0=#{range := {RangeUnit, _}}, State, RangeData) -> - Req = cowboy_req:set_resp_header(<<"content-range">>, - [RangeUnit, $\s, RangeData], Req0), - respond(Req, State, 416). - -%% Set the response headers and call the callback found using -%% content_types_provided/2 to obtain the request body and add -%% it to the response. -set_resp_body(Req, State=#state{handler=Handler, content_type_a={_, Callback}}) -> - try case call(Req, State, Callback) of - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {Body, Req2, State2} -> - Req3 = cowboy_req:set_resp_body(Body, Req2), - multiple_choices(Req3, State2) - end catch Class:{case_clause, no_call} -> - error_terminate(Req, State, Class, {error, {missing_callback, {Handler, Callback, 2}}, - 'A callback specified in content_types_provided/2 is not exported.'}) - end. - -multiple_choices(Req, State) -> - expect(Req, State, multiple_choices, false, 200, 300). - -%% Response utility functions. - -set_resp_etag(Req, State) -> - {Etag, Req2, State2} = generate_etag(Req, State), - case Etag of - undefined -> - {Req2, State2}; - Etag -> - Req3 = cowboy_req:set_resp_header( - <<"etag">>, encode_etag(Etag), Req2), - {Req3, State2} - end. - --spec encode_etag({strong | weak, binary()}) -> iolist(). -encode_etag({strong, Etag}) -> [$",Etag,$"]; -encode_etag({weak, Etag}) -> ["W/\"",Etag,$"]. - -set_resp_expires(Req, State) -> - {Expires, Req2, State2} = expires(Req, State), - case Expires of - Expires when is_atom(Expires) -> - {Req2, State2}; - Expires when is_binary(Expires) -> - Req3 = cowboy_req:set_resp_header( - <<"expires">>, Expires, Req2), - {Req3, State2}; - Expires -> - ExpiresBin = cowboy_clock:rfc1123(Expires), - Req3 = cowboy_req:set_resp_header( - <<"expires">>, ExpiresBin, Req2), - {Req3, State2} - end. - -%% Info retrieval. No logic. - -generate_etag(Req, State=#state{etag=no_call}) -> - {undefined, Req, State}; -generate_etag(Req, State=#state{etag=undefined}) -> - case unsafe_call(Req, State, generate_etag) of - no_call -> - {undefined, Req, State#state{etag=no_call}}; - {Etag, Req2, State2} when is_binary(Etag) -> - Etag2 = cow_http_hd:parse_etag(Etag), - {Etag2, Req2, State2#state{etag=Etag2}}; - {Etag, Req2, State2} -> - {Etag, Req2, State2#state{etag=Etag}} - end; -generate_etag(Req, State=#state{etag=Etag}) -> - {Etag, Req, State}. - -last_modified(Req, State=#state{last_modified=no_call}) -> - {undefined, Req, State}; -last_modified(Req, State=#state{last_modified=undefined}) -> - case unsafe_call(Req, State, last_modified) of - no_call -> - {undefined, Req, State#state{last_modified=no_call}}; - {LastModified, Req2, State2} -> - {LastModified, Req2, State2#state{last_modified=LastModified}} - end; -last_modified(Req, State=#state{last_modified=LastModified}) -> - {LastModified, Req, State}. - -expires(Req, State=#state{expires=no_call}) -> - {undefined, Req, State}; -expires(Req, State=#state{expires=undefined}) -> - case unsafe_call(Req, State, expires) of - no_call -> - {undefined, Req, State#state{expires=no_call}}; - {Expires, Req2, State2} -> - {Expires, Req2, State2#state{expires=Expires}} - end; -expires(Req, State=#state{expires=Expires}) -> - {Expires, Req, State}. - -%% REST primitives. - -expect(Req, State, Callback, Expected, OnTrue, OnFalse) -> - case call(Req, State, Callback) of - no_call -> - next(Req, State, OnTrue); - {stop, Req2, State2} -> - terminate(Req2, State2); - {Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> - switch_handler(Switch, Req2, State2); - {Expected, Req2, State2} -> - next(Req2, State2, OnTrue); - {_Unexpected, Req2, State2} -> - next(Req2, State2, OnFalse) - end. - -call(Req0, State=#state{handler=Handler, - handler_state=HandlerState0}, Callback) -> - case erlang:function_exported(Handler, Callback, 2) of - true -> - try Handler:Callback(Req0, HandlerState0) of - no_call -> - no_call; - {Result, Req, HandlerState} -> - {Result, Req, State#state{handler_state=HandlerState}} - catch Class:Reason -> - error_terminate(Req0, State, Class, Reason) - end; - false -> - no_call - end. - -unsafe_call(Req0, State=#state{handler=Handler, - handler_state=HandlerState0}, Callback) -> - case erlang:function_exported(Handler, Callback, 2) of - false -> - no_call; - true -> - case Handler:Callback(Req0, HandlerState0) of - no_call -> - no_call; - {Result, Req, HandlerState} -> - {Result, Req, State#state{handler_state=HandlerState}} - end - end. - -next(Req, State, Next) when is_function(Next) -> - Next(Req, State); -next(Req, State, StatusCode) when is_integer(StatusCode) -> - respond(Req, State, StatusCode). - -respond(Req0, State, StatusCode) -> - %% We remove the content-type header when there is no body, - %% except when the status code is 200 because it might have - %% been intended (for example sending an empty file). - Req = case cowboy_req:has_resp_body(Req0) of - true when StatusCode =:= 200 -> Req0; - true -> Req0; - false -> cowboy_req:delete_resp_header(<<"content-type">>, Req0) - end, - terminate(cowboy_req:reply(StatusCode, Req), State). - -switch_handler({switch_handler, Mod}, Req, #state{handler_state=HandlerState}) -> - {Mod, Req, HandlerState}; -switch_handler({switch_handler, Mod, Opts}, Req, #state{handler_state=HandlerState}) -> - {Mod, Req, HandlerState, Opts}. - --spec error_terminate(cowboy_req:req(), #state{}, atom(), any()) -> no_return(). -error_terminate(Req, #state{handler=Handler, handler_state=HandlerState}, Class, Reason) -> - StackTrace = erlang:get_stacktrace(), - cowboy_handler:terminate({crash, Class, Reason}, Req, HandlerState, Handler), - erlang:raise(Class, Reason, StackTrace). - -terminate(Req, #state{handler=Handler, handler_state=HandlerState}) -> - Result = cowboy_handler:terminate(normal, Req, HandlerState, Handler), - {ok, Req, Result}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_router.erl b/_build/emqx/lib/cowboy/src/cowboy_router.erl deleted file mode 100644 index 0eb4bdd34c..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_router.erl +++ /dev/null @@ -1,593 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -%% Routing middleware. -%% -%% Resolve the handler to be used for the request based on the -%% routing information found in the dispatch environment value. -%% When found, the handler module and associated data are added to -%% the environment as the handler and handler_opts values -%% respectively. -%% -%% If the route cannot be found, processing stops with either -%% a 400 or a 404 reply. --module(cowboy_router). --behaviour(cowboy_middleware). - --export([compile/1]). --export([execute/2]). - --type bindings() :: #{atom() => any()}. --type tokens() :: [binary()]. --export_type([bindings/0]). --export_type([tokens/0]). - --type route_match() :: '_' | iodata(). --type route_path() :: {Path::route_match(), Handler::module(), Opts::any()} - | {Path::route_match(), cowboy:fields(), Handler::module(), Opts::any()}. --type route_rule() :: {Host::route_match(), Paths::[route_path()]} - | {Host::route_match(), cowboy:fields(), Paths::[route_path()]}. --type routes() :: [route_rule()]. --export_type([routes/0]). - --type dispatch_match() :: '_' | <<_:8>> | [binary() | '_' | '...' | atom()]. --type dispatch_path() :: {dispatch_match(), cowboy:fields(), module(), any()}. --type dispatch_rule() :: {Host::dispatch_match(), cowboy:fields(), Paths::[dispatch_path()]}. --opaque dispatch_rules() :: [dispatch_rule()]. --export_type([dispatch_rules/0]). - --spec compile(routes()) -> dispatch_rules(). -compile(Routes) -> - compile(Routes, []). - -compile([], Acc) -> - lists:reverse(Acc); -compile([{Host, Paths}|Tail], Acc) -> - compile([{Host, [], Paths}|Tail], Acc); -compile([{HostMatch, Fields, Paths}|Tail], Acc) -> - HostRules = case HostMatch of - '_' -> '_'; - _ -> compile_host(HostMatch) - end, - PathRules = compile_paths(Paths, []), - Hosts = case HostRules of - '_' -> [{'_', Fields, PathRules}]; - _ -> [{R, Fields, PathRules} || R <- HostRules] - end, - compile(Tail, Hosts ++ Acc). - -compile_host(HostMatch) when is_list(HostMatch) -> - compile_host(list_to_binary(HostMatch)); -compile_host(HostMatch) when is_binary(HostMatch) -> - compile_rules(HostMatch, $., [], [], <<>>). - -compile_paths([], Acc) -> - lists:reverse(Acc); -compile_paths([{PathMatch, Handler, Opts}|Tail], Acc) -> - compile_paths([{PathMatch, [], Handler, Opts}|Tail], Acc); -compile_paths([{PathMatch, Fields, Handler, Opts}|Tail], Acc) - when is_list(PathMatch) -> - compile_paths([{iolist_to_binary(PathMatch), - Fields, Handler, Opts}|Tail], Acc); -compile_paths([{'_', Fields, Handler, Opts}|Tail], Acc) -> - compile_paths(Tail, [{'_', Fields, Handler, Opts}] ++ Acc); -compile_paths([{<<"*">>, Fields, Handler, Opts}|Tail], Acc) -> - compile_paths(Tail, [{<<"*">>, Fields, Handler, Opts}|Acc]); -compile_paths([{<< $/, PathMatch/bits >>, Fields, Handler, Opts}|Tail], - Acc) -> - PathRules = compile_rules(PathMatch, $/, [], [], <<>>), - Paths = [{lists:reverse(R), Fields, Handler, Opts} || R <- PathRules], - compile_paths(Tail, Paths ++ Acc); -compile_paths([{PathMatch, _, _, _}|_], _) -> - error({badarg, "The following route MUST begin with a slash: " - ++ binary_to_list(PathMatch)}). - -compile_rules(<<>>, _, Segments, Rules, <<>>) -> - [Segments|Rules]; -compile_rules(<<>>, _, Segments, Rules, Acc) -> - [[Acc|Segments]|Rules]; -compile_rules(<< S, Rest/bits >>, S, Segments, Rules, <<>>) -> - compile_rules(Rest, S, Segments, Rules, <<>>); -compile_rules(<< S, Rest/bits >>, S, Segments, Rules, Acc) -> - compile_rules(Rest, S, [Acc|Segments], Rules, <<>>); -%% Colon on path segment start is special, otherwise allow. -compile_rules(<< $:, Rest/bits >>, S, Segments, Rules, <<>>) -> - {NameBin, Rest2} = compile_binding(Rest, S, <<>>), - Name = binary_to_atom(NameBin, utf8), - compile_rules(Rest2, S, Segments, Rules, Name); -compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) - when Acc =:= <<>> -> - compile_rules(Rest, S, ['...'|Segments], Rules, Acc); -compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) -> - compile_rules(Rest, S, ['...', Acc|Segments], Rules, Acc); -compile_rules(<< $[, S, Rest/bits >>, S, Segments, Rules, Acc) -> - compile_brackets(Rest, S, [Acc|Segments], Rules); -compile_rules(<< $[, Rest/bits >>, S, Segments, Rules, <<>>) -> - compile_brackets(Rest, S, Segments, Rules); -%% Open bracket in the middle of a segment. -compile_rules(<< $[, _/bits >>, _, _, _, _) -> - error(badarg); -%% Missing an open bracket. -compile_rules(<< $], _/bits >>, _, _, _, _) -> - error(badarg); -compile_rules(<< C, Rest/bits >>, S, Segments, Rules, Acc) -> - compile_rules(Rest, S, Segments, Rules, << Acc/binary, C >>). - -%% Everything past $: until the segment separator ($. for hosts, -%% $/ for paths) or $[ or $] or end of binary is the binding name. -compile_binding(<<>>, _, <<>>) -> - error(badarg); -compile_binding(Rest = <<>>, _, Acc) -> - {Acc, Rest}; -compile_binding(Rest = << C, _/bits >>, S, Acc) - when C =:= S; C =:= $[; C =:= $] -> - {Acc, Rest}; -compile_binding(<< C, Rest/bits >>, S, Acc) -> - compile_binding(Rest, S, << Acc/binary, C >>). - -compile_brackets(Rest, S, Segments, Rules) -> - {Bracket, Rest2} = compile_brackets_split(Rest, <<>>, 0), - Rules1 = compile_rules(Rest2, S, Segments, [], <<>>), - Rules2 = compile_rules(<< Bracket/binary, Rest2/binary >>, - S, Segments, [], <<>>), - Rules ++ Rules2 ++ Rules1. - -%% Missing a close bracket. -compile_brackets_split(<<>>, _, _) -> - error(badarg); -%% Make sure we don't confuse the closing bracket we're looking for. -compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $[ -> - compile_brackets_split(Rest, << Acc/binary, C >>, N + 1); -compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $], N > 0 -> - compile_brackets_split(Rest, << Acc/binary, C >>, N - 1); -%% That's the right one. -compile_brackets_split(<< $], Rest/bits >>, Acc, 0) -> - {Acc, Rest}; -compile_brackets_split(<< C, Rest/bits >>, Acc, N) -> - compile_brackets_split(Rest, << Acc/binary, C >>, N). - --spec execute(Req, Env) - -> {ok, Req, Env} | {stop, Req} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -execute(Req=#{host := Host, path := Path}, Env=#{dispatch := Dispatch0}) -> - Dispatch = case Dispatch0 of - {persistent_term, Key} -> persistent_term:get(Key); - _ -> Dispatch0 - end, - case match(Dispatch, Host, Path) of - {ok, Handler, HandlerOpts, Bindings, HostInfo, PathInfo} -> - {ok, Req#{ - host_info => HostInfo, - path_info => PathInfo, - bindings => Bindings - }, Env#{ - handler => Handler, - handler_opts => HandlerOpts - }}; - {error, notfound, host} -> - {stop, cowboy_req:reply(400, Req)}; - {error, badrequest, path} -> - {stop, cowboy_req:reply(400, Req)}; - {error, notfound, path} -> - {stop, cowboy_req:reply(404, Req)} - end. - -%% Internal. - -%% Match hostname tokens and path tokens against dispatch rules. -%% -%% It is typically used for matching tokens for the hostname and path of -%% the request against a global dispatch rule for your listener. -%% -%% Dispatch rules are a list of {Hostname, PathRules} tuples, with -%% PathRules being a list of {Path, HandlerMod, HandlerOpts}. -%% -%% Hostname and Path are match rules and can be either the -%% atom '_', which matches everything, `<<"*">>', which match the -%% wildcard path, or a list of tokens. -%% -%% Each token can be either a binary, the atom '_', -%% the atom '...' or a named atom. A binary token must match exactly, -%% '_' matches everything for a single token, '...' matches -%% everything for the rest of the tokens and a named atom will bind the -%% corresponding token value and return it. -%% -%% The list of hostname tokens is reversed before matching. For example, if -%% we were to match "www.ninenines.eu", we would first match "eu", then -%% "ninenines", then "www". This means that in the context of hostnames, -%% the '...' atom matches properly the lower levels of the domain -%% as would be expected. -%% -%% When a result is found, this function will return the handler module and -%% options found in the dispatch list, a key-value list of bindings and -%% the tokens that were matched by the '...' atom for both the -%% hostname and path. --spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary()) - -> {ok, module(), any(), bindings(), - HostInfo::undefined | tokens(), - PathInfo::undefined | tokens()} - | {error, notfound, host} | {error, notfound, path} - | {error, badrequest, path}. -match([], _, _) -> - {error, notfound, host}; -%% If the host is '_' then there can be no constraints. -match([{'_', [], PathMatchs}|_Tail], _, Path) -> - match_path(PathMatchs, undefined, Path, #{}); -match([{HostMatch, Fields, PathMatchs}|Tail], Tokens, Path) - when is_list(Tokens) -> - case list_match(Tokens, HostMatch, #{}) of - false -> - match(Tail, Tokens, Path); - {true, Bindings, HostInfo} -> - HostInfo2 = case HostInfo of - undefined -> undefined; - _ -> lists:reverse(HostInfo) - end, - case check_constraints(Fields, Bindings) of - {ok, Bindings2} -> - match_path(PathMatchs, HostInfo2, Path, Bindings2); - nomatch -> - match(Tail, Tokens, Path) - end - end; -match(Dispatch, Host, Path) -> - match(Dispatch, split_host(Host), Path). - --spec match_path([dispatch_path()], - HostInfo::undefined | tokens(), binary() | tokens(), bindings()) - -> {ok, module(), any(), bindings(), - HostInfo::undefined | tokens(), - PathInfo::undefined | tokens()} - | {error, notfound, path} | {error, badrequest, path}. -match_path([], _, _, _) -> - {error, notfound, path}; -%% If the path is '_' then there can be no constraints. -match_path([{'_', [], Handler, Opts}|_Tail], HostInfo, _, Bindings) -> - {ok, Handler, Opts, Bindings, HostInfo, undefined}; -match_path([{<<"*">>, _, Handler, Opts}|_Tail], HostInfo, <<"*">>, Bindings) -> - {ok, Handler, Opts, Bindings, HostInfo, undefined}; -match_path([_|Tail], HostInfo, <<"*">>, Bindings) -> - match_path(Tail, HostInfo, <<"*">>, Bindings); -match_path([{PathMatch, Fields, Handler, Opts}|Tail], HostInfo, Tokens, - Bindings) when is_list(Tokens) -> - case list_match(Tokens, PathMatch, Bindings) of - false -> - match_path(Tail, HostInfo, Tokens, Bindings); - {true, PathBinds, PathInfo} -> - case check_constraints(Fields, PathBinds) of - {ok, PathBinds2} -> - {ok, Handler, Opts, PathBinds2, HostInfo, PathInfo}; - nomatch -> - match_path(Tail, HostInfo, Tokens, Bindings) - end - end; -match_path(_Dispatch, _HostInfo, badrequest, _Bindings) -> - {error, badrequest, path}; -match_path(Dispatch, HostInfo, Path, Bindings) -> - match_path(Dispatch, HostInfo, split_path(Path), Bindings). - -check_constraints([], Bindings) -> - {ok, Bindings}; -check_constraints([Field|Tail], Bindings) when is_atom(Field) -> - check_constraints(Tail, Bindings); -check_constraints([Field|Tail], Bindings) -> - Name = element(1, Field), - case Bindings of - #{Name := Value0} -> - Constraints = element(2, Field), - case cowboy_constraints:validate(Value0, Constraints) of - {ok, Value} -> - check_constraints(Tail, Bindings#{Name => Value}); - {error, _} -> - nomatch - end; - _ -> - check_constraints(Tail, Bindings) - end. - --spec split_host(binary()) -> tokens(). -split_host(Host) -> - split_host(Host, []). - -split_host(Host, Acc) -> - case binary:match(Host, <<".">>) of - nomatch when Host =:= <<>> -> - Acc; - nomatch -> - [Host|Acc]; - {Pos, _} -> - << Segment:Pos/binary, _:8, Rest/bits >> = Host, - false = byte_size(Segment) == 0, - split_host(Rest, [Segment|Acc]) - end. - -%% Following RFC2396, this function may return path segments containing any -%% character, including / if, and only if, a / was escaped -%% and part of a path segment. --spec split_path(binary()) -> tokens() | badrequest. -split_path(<< $/, Path/bits >>) -> - split_path(Path, []); -split_path(_) -> - badrequest. - -split_path(Path, Acc) -> - try - case binary:match(Path, <<"/">>) of - nomatch when Path =:= <<>> -> - remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- Acc]), []); - nomatch -> - remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- [Path|Acc]]), []); - {Pos, _} -> - << Segment:Pos/binary, _:8, Rest/bits >> = Path, - split_path(Rest, [Segment|Acc]) - end - catch error:_ -> - badrequest - end. - -remove_dot_segments([], Acc) -> - lists:reverse(Acc); -remove_dot_segments([<<".">>|Segments], Acc) -> - remove_dot_segments(Segments, Acc); -remove_dot_segments([<<"..">>|Segments], Acc=[]) -> - remove_dot_segments(Segments, Acc); -remove_dot_segments([<<"..">>|Segments], [_|Acc]) -> - remove_dot_segments(Segments, Acc); -remove_dot_segments([S|Segments], Acc) -> - remove_dot_segments(Segments, [S|Acc]). - --ifdef(TEST). -remove_dot_segments_test_() -> - Tests = [ - {[<<"a">>, <<"b">>, <<"c">>, <<".">>, <<"..">>, <<"..">>, <<"g">>], [<<"a">>, <<"g">>]}, - {[<<"mid">>, <<"content=5">>, <<"..">>, <<"6">>], [<<"mid">>, <<"6">>]}, - {[<<"..">>, <<"a">>], [<<"a">>]} - ], - [fun() -> R = remove_dot_segments(S, []) end || {S, R} <- Tests]. --endif. - --spec list_match(tokens(), dispatch_match(), bindings()) - -> {true, bindings(), undefined | tokens()} | false. -%% Atom '...' matches any trailing path, stop right now. -list_match(List, ['...'], Binds) -> - {true, Binds, List}; -%% Atom '_' matches anything, continue. -list_match([_E|Tail], ['_'|TailMatch], Binds) -> - list_match(Tail, TailMatch, Binds); -%% Both values match, continue. -list_match([E|Tail], [E|TailMatch], Binds) -> - list_match(Tail, TailMatch, Binds); -%% Bind E to the variable name V and continue, -%% unless V was already defined and E isn't identical to the previous value. -list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) -> - case Binds of - #{V := E} -> - list_match(Tail, TailMatch, Binds); - #{V := _} -> - false; - _ -> - list_match(Tail, TailMatch, Binds#{V => E}) - end; -%% Match complete. -list_match([], [], Binds) -> - {true, Binds, undefined}; -%% Values don't match, stop. -list_match(_List, _Match, _Binds) -> - false. - -%% Tests. - --ifdef(TEST). -compile_test_() -> - Tests = [ - %% Match any host and path. - {[{'_', [{'_', h, o}]}], - [{'_', [], [{'_', [], h, o}]}]}, - {[{"cowboy.example.org", - [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}], - [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [ - {[], [], ha, oa}, - {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]}, - {[{'_', [{"/path/to/resource/", h, o}]}], - [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]}, - % Cyrillic from a latin1 encoded file. - {[{'_', [{[47,208,191,209,131,209,130,209,140,47,208,186,47,209,128, - 208,181,209,129,209,131,209,128,209,129,209,131,47], h, o}]}], - [{'_', [], [{[<<208,191,209,131,209,130,209,140>>, <<208,186>>, - <<209,128,208,181,209,129,209,131,209,128,209,129,209,131>>], - [], h, o}]}]}, - {[{"cowboy.example.org.", [{'_', h, o}]}], - [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]}, - {[{".cowboy.example.org", [{'_', h, o}]}], - [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]}, - % Cyrillic from a latin1 encoded file. - {[{[208,189,208,181,208,186,208,184,208,185,46,209,129,208,176, - 208,185,209,130,46,209,128,209,132,46], [{'_', h, o}]}], - [{[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>, - <<208,189,208,181,208,186,208,184,208,185>>], - [], [{'_', [], h, o}]}]}, - {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}], - [{[<<"org">>, <<"example">>, subdomain], [], [ - {[<<"hats">>, name, <<"prices">>], [], h, o}]}]}, - {[{"ninenines.:_", [{"/hats/:_", h, o}]}], - [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]}, - {[{"[www.]ninenines.eu", - [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [ - {[<<"eu">>, <<"ninenines">>], [], [ - {[<<"horses">>], [], h, o}, - {[<<"hats">>], [], h, o}, - {[<<"hats">>, <<"page">>, number], [], h, o}]}, - {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [ - {[<<"horses">>], [], h, o}, - {[<<"hats">>], [], h, o}, - {[<<"hats">>, <<"page">>, number], [], h, o}]}]}, - {[{'_', [{"/hats/:page/:number", h, o}]}], [{'_', [], [ - {[<<"hats">>, page, number], [], h, o}]}]}, - {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [ - {[<<"hats">>], [], h, o}, - {[<<"hats">>, <<"page">>], [], h, o}, - {[<<"hats">>, <<"page">>, number], [], h, o}]}]}, - {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}], - [{[<<"eu">>, <<"ninenines">>, '...'], [], [ - {[<<"hats">>, '...'], [], h, o}]}]}, - %% Path segment containing a colon. - {[{'_', [{"/foo/bar:blah", h, o}]}], [{'_', [], [ - {[<<"foo">>, <<"bar:blah">>], [], h, o}]}]} - ], - [{lists:flatten(io_lib:format("~p", [Rt])), - fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests]. - -split_host_test_() -> - Tests = [ - {<<"">>, []}, - {<<"*">>, [<<"*">>]}, - {<<"cowboy.ninenines.eu">>, - [<<"eu">>, <<"ninenines">>, <<"cowboy">>]}, - {<<"ninenines.eu">>, - [<<"eu">>, <<"ninenines">>]}, - {<<"ninenines.eu.">>, - [<<"eu">>, <<"ninenines">>]}, - {<<"a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z">>, - [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>, - <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>, - <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>, - <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]} - ], - [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests]. - -split_path_test_() -> - Tests = [ - {<<"/">>, []}, - {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]}, - {<<"/users">>, [<<"users">>]}, - {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]}, - {<<"/users/a%20b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]} - ], - [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests]. - -match_test_() -> - Dispatch = [ - {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [ - {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []} - ]}, - {[<<"eu">>, <<"ninenines">>], [], [ - {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []}, - {'_', [], match_extend, []} - ]}, - {[var, <<"ninenines">>], [], [ - {[<<"threads">>, var], [], match_duplicate_vars, - [we, {expect, two}, var, here]} - ]}, - {[ext, <<"erlang">>], [], [ - {'_', [], match_erlang_ext, []} - ]}, - {'_', [], [ - {[<<"users">>, id, <<"friends">>], [], match_users_friends, []}, - {'_', [], match_any, []} - ]} - ], - Tests = [ - {<<"any">>, <<"/">>, {ok, match_any, [], #{}}}, - {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>, - {ok, match_any_subdomain_users, [], #{}}}, - {<<"www.ninenines.eu">>, <<"/users/42/mails">>, - {ok, match_any, [], #{}}}, - {<<"www.ninenines.eu">>, <<"/">>, - {ok, match_any, [], #{}}}, - {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>, - {error, notfound, path}}, - {<<"ninenines.eu">>, <<"/">>, - {ok, match_extend, [], #{}}}, - {<<"ninenines.eu">>, <<"/users/42/friends">>, - {ok, match_extend_users_friends, [], #{id => <<"42">>}}}, - {<<"erlang.fr">>, '_', - {ok, match_erlang_ext, [], #{ext => <<"fr">>}}}, - {<<"any">>, <<"/users/444/friends">>, - {ok, match_users_friends, [], #{id => <<"444">>}}} - ], - [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> - {ok, Handler, Opts, Binds, undefined, undefined} - = match(Dispatch, H, P) - end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests]. - -match_info_test_() -> - Dispatch = [ - {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [ - {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []} - ]}, - {[<<"eu">>, <<"ninenines">>, '...'], [], [ - {'_', [], match_any, []} - ]} - ], - Tests = [ - {<<"ninenines.eu">>, <<"/">>, - {ok, match_any, [], #{}, [], undefined}}, - {<<"bugs.ninenines.eu">>, <<"/">>, - {ok, match_any, [], #{}, [<<"bugs">>], undefined}}, - {<<"cowboy.bugs.ninenines.eu">>, <<"/">>, - {ok, match_any, [], #{}, [<<"cowboy">>, <<"bugs">>], undefined}}, - {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>, - {ok, match_path, [], #{}, undefined, []}}, - {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>, - {ok, match_path, [], #{}, undefined, [<<"path_info">>]}}, - {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>, - {ok, match_path, [], #{}, undefined, [<<"foo">>, <<"bar">>]}} - ], - [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> - R = match(Dispatch, H, P) - end} || {H, P, R} <- Tests]. - -match_constraints_test() -> - Dispatch = [{'_', [], - [{[<<"path">>, value], [{value, int}], match, []}]}], - {ok, _, [], #{value := 123}, _, _} = match(Dispatch, - <<"ninenines.eu">>, <<"/path/123">>), - {ok, _, [], #{value := 123}, _, _} = match(Dispatch, - <<"ninenines.eu">>, <<"/path/123/">>), - {error, notfound, path} = match(Dispatch, - <<"ninenines.eu">>, <<"/path/NaN/">>), - Dispatch2 = [{'_', [], [{[<<"path">>, username], - [{username, fun(_, Value) -> - case cowboy_bstr:to_lower(Value) of - Value -> {ok, Value}; - _ -> {error, not_lowercase} - end end}], - match, []}]}], - {ok, _, [], #{username := <<"essen">>}, _, _} = match(Dispatch2, - <<"ninenines.eu">>, <<"/path/essen">>), - {error, notfound, path} = match(Dispatch2, - <<"ninenines.eu">>, <<"/path/ESSEN">>), - ok. - -match_same_bindings_test() -> - Dispatch = [{[same, same], [], [{'_', [], match, []}]}], - {ok, _, [], #{same := <<"eu">>}, _, _} = match(Dispatch, - <<"eu.eu">>, <<"/">>), - {error, notfound, host} = match(Dispatch, - <<"ninenines.eu">>, <<"/">>), - Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [], - [{[<<"path">>, user], [], match, []}]}], - {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2, - <<"essen.ninenines.eu">>, <<"/path/essen">>), - {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2, - <<"essen.ninenines.eu">>, <<"/path/essen/">>), - {error, notfound, path} = match(Dispatch2, - <<"essen.ninenines.eu">>, <<"/path/notessen">>), - Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}], - {ok, _, [], #{same := <<"path">>}, _, _} = match(Dispatch3, - <<"ninenines.eu">>, <<"/path/path">>), - {error, notfound, path} = match(Dispatch3, - <<"ninenines.eu">>, <<"/path/to">>), - ok. --endif. diff --git a/_build/emqx/lib/cowboy/src/cowboy_static.erl b/_build/emqx/lib/cowboy/src/cowboy_static.erl deleted file mode 100644 index b0cf146326..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_static.erl +++ /dev/null @@ -1,418 +0,0 @@ -%% Copyright (c) 2013-2017, Loïc Hoguin -%% Copyright (c) 2011, Magnus Klaar -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_static). - --export([init/2]). --export([malformed_request/2]). --export([forbidden/2]). --export([content_types_provided/2]). --export([charsets_provided/2]). --export([ranges_provided/2]). --export([resource_exists/2]). --export([last_modified/2]). --export([generate_etag/2]). --export([get_file/2]). - --type extra_charset() :: {charset, module(), function()} | {charset, binary()}. --type extra_etag() :: {etag, module(), function()} | {etag, false}. --type extra_mimetypes() :: {mimetypes, module(), function()} - | {mimetypes, binary() | {binary(), binary(), [{binary(), binary()}]}}. --type extra() :: [extra_charset() | extra_etag() | extra_mimetypes()]. --type opts() :: {file | dir, string() | binary()} - | {file | dir, string() | binary(), extra()} - | {priv_file | priv_dir, atom(), string() | binary()} - | {priv_file | priv_dir, atom(), string() | binary(), extra()}. --export_type([opts/0]). - --include_lib("kernel/include/file.hrl"). - --type state() :: {binary(), {direct | archive, #file_info{}} - | {error, atom()}, extra()}. - -%% Resolve the file that will be sent and get its file information. -%% If the handler is configured to manage a directory, check that the -%% requested file is inside the configured directory. - --spec init(Req, opts()) -> {cowboy_rest, Req, error | state()} when Req::cowboy_req:req(). -init(Req, {Name, Path}) -> - init_opts(Req, {Name, Path, []}); -init(Req, {Name, App, Path}) - when Name =:= priv_file; Name =:= priv_dir -> - init_opts(Req, {Name, App, Path, []}); -init(Req, Opts) -> - init_opts(Req, Opts). - -init_opts(Req, {priv_file, App, Path, Extra}) -> - {PrivPath, HowToAccess} = priv_path(App, Path), - init_info(Req, absname(PrivPath), HowToAccess, Extra); -init_opts(Req, {file, Path, Extra}) -> - init_info(Req, absname(Path), direct, Extra); -init_opts(Req, {priv_dir, App, Path, Extra}) -> - {PrivPath, HowToAccess} = priv_path(App, Path), - init_dir(Req, PrivPath, HowToAccess, Extra); -init_opts(Req, {dir, Path, Extra}) -> - init_dir(Req, Path, direct, Extra). - -priv_path(App, Path) -> - case code:priv_dir(App) of - {error, bad_name} -> - error({badarg, "Can't resolve the priv_dir of application " - ++ atom_to_list(App)}); - PrivDir when is_list(Path) -> - { - PrivDir ++ "/" ++ Path, - how_to_access_app_priv(PrivDir) - }; - PrivDir when is_binary(Path) -> - { - << (list_to_binary(PrivDir))/binary, $/, Path/binary >>, - how_to_access_app_priv(PrivDir) - } - end. - -how_to_access_app_priv(PrivDir) -> - %% If the priv directory is not a directory, it must be - %% inside an Erlang application .ez archive. We call - %% how_to_access_app_priv1() to find the corresponding archive. - case filelib:is_dir(PrivDir) of - true -> direct; - false -> how_to_access_app_priv1(PrivDir) - end. - -how_to_access_app_priv1(Dir) -> - %% We go "up" by one path component at a time and look for a - %% regular file. - Archive = filename:dirname(Dir), - case Archive of - Dir -> - %% filename:dirname() returned its argument: - %% we reach the root directory. We found no - %% archive so we return 'direct': the given priv - %% directory doesn't exist. - direct; - _ -> - case filelib:is_regular(Archive) of - true -> {archive, Archive}; - false -> how_to_access_app_priv1(Archive) - end - end. - -absname(Path) when is_list(Path) -> - filename:absname(list_to_binary(Path)); -absname(Path) when is_binary(Path) -> - filename:absname(Path). - -init_dir(Req, Path, HowToAccess, Extra) when is_list(Path) -> - init_dir(Req, list_to_binary(Path), HowToAccess, Extra); -init_dir(Req, Path, HowToAccess, Extra) -> - Dir = fullpath(filename:absname(Path)), - case cowboy_req:path_info(Req) of - %% When dir/priv_dir are used and there is no path_info - %% this is a configuration error and we abort immediately. - undefined -> - {ok, cowboy_req:reply(500, Req), error}; - PathInfo -> - case validate_reserved(PathInfo) of - error -> - {cowboy_rest, Req, error}; - ok -> - Filepath = filename:join([Dir|PathInfo]), - Len = byte_size(Dir), - case fullpath(Filepath) of - << Dir:Len/binary, $/, _/binary >> -> - init_info(Req, Filepath, HowToAccess, Extra); - << Dir:Len/binary >> -> - init_info(Req, Filepath, HowToAccess, Extra); - _ -> - {cowboy_rest, Req, error} - end - end - end. - -validate_reserved([]) -> - ok; -validate_reserved([P|Tail]) -> - case validate_reserved1(P) of - ok -> validate_reserved(Tail); - error -> error - end. - -%% We always reject forward slash, backward slash and NUL as -%% those have special meanings across the supported platforms. -%% We could support the backward slash on some platforms but -%% for the sake of consistency and simplicity we don't. -validate_reserved1(<<>>) -> - ok; -validate_reserved1(<<$/, _/bits>>) -> - error; -validate_reserved1(<<$\\, _/bits>>) -> - error; -validate_reserved1(<<0, _/bits>>) -> - error; -validate_reserved1(<<_, Rest/bits>>) -> - validate_reserved1(Rest). - -fullpath(Path) -> - fullpath(filename:split(Path), []). -fullpath([], Acc) -> - filename:join(lists:reverse(Acc)); -fullpath([<<".">>|Tail], Acc) -> - fullpath(Tail, Acc); -fullpath([<<"..">>|Tail], Acc=[_]) -> - fullpath(Tail, Acc); -fullpath([<<"..">>|Tail], [_|Acc]) -> - fullpath(Tail, Acc); -fullpath([Segment|Tail], Acc) -> - fullpath(Tail, [Segment|Acc]). - -init_info(Req, Path, HowToAccess, Extra) -> - Info = read_file_info(Path, HowToAccess), - {cowboy_rest, Req, {Path, Info, Extra}}. - -read_file_info(Path, direct) -> - case file:read_file_info(Path, [{time, universal}]) of - {ok, Info} -> {direct, Info}; - Error -> Error - end; -read_file_info(Path, {archive, Archive}) -> - case file:read_file_info(Archive, [{time, universal}]) of - {ok, ArchiveInfo} -> - %% The Erlang application archive is fine. - %% Now check if the requested file is in that - %% archive. We also need the file_info to merge - %% them with the archive's one. - PathS = binary_to_list(Path), - case erl_prim_loader:read_file_info(PathS) of - {ok, ContainedFileInfo} -> - Info = fix_archived_file_info( - ArchiveInfo, - ContainedFileInfo), - {archive, Info}; - error -> - {error, enoent} - end; - Error -> - Error - end. - -fix_archived_file_info(ArchiveInfo, ContainedFileInfo) -> - %% We merge the archive and content #file_info because we are - %% interested by the timestamps of the archive, but the type and - %% size of the contained file/directory. - %% - %% We reset the access to 'read', because we won't rewrite the - %% archive. - ArchiveInfo#file_info{ - size = ContainedFileInfo#file_info.size, - type = ContainedFileInfo#file_info.type, - access = read - }. - --ifdef(TEST). -fullpath_test_() -> - Tests = [ - {<<"/home/cowboy">>, <<"/home/cowboy">>}, - {<<"/home/cowboy">>, <<"/home/cowboy/">>}, - {<<"/home/cowboy">>, <<"/home/cowboy/./">>}, - {<<"/home/cowboy">>, <<"/home/cowboy/./././././.">>}, - {<<"/home/cowboy">>, <<"/home/cowboy/abc/..">>}, - {<<"/home/cowboy">>, <<"/home/cowboy/abc/../">>}, - {<<"/home/cowboy">>, <<"/home/cowboy/abc/./../.">>}, - {<<"/">>, <<"/home/cowboy/../../../../../..">>}, - {<<"/etc/passwd">>, <<"/home/cowboy/../../etc/passwd">>} - ], - [{P, fun() -> R = fullpath(P) end} || {R, P} <- Tests]. - -good_path_check_test_() -> - Tests = [ - <<"/home/cowboy/file">>, - <<"/home/cowboy/file/">>, - <<"/home/cowboy/./file">>, - <<"/home/cowboy/././././././file">>, - <<"/home/cowboy/abc/../file">>, - <<"/home/cowboy/abc/../file">>, - <<"/home/cowboy/abc/./.././file">> - ], - [{P, fun() -> - case fullpath(P) of - << "/home/cowboy/", _/bits >> -> ok - end - end} || P <- Tests]. - -bad_path_check_test_() -> - Tests = [ - <<"/home/cowboy/../../../../../../file">>, - <<"/home/cowboy/../../etc/passwd">> - ], - [{P, fun() -> - error = case fullpath(P) of - << "/home/cowboy/", _/bits >> -> ok; - _ -> error - end - end} || P <- Tests]. - -good_path_win32_check_test_() -> - Tests = case os:type() of - {unix, _} -> - []; - {win32, _} -> - [ - <<"c:/home/cowboy/file">>, - <<"c:/home/cowboy/file/">>, - <<"c:/home/cowboy/./file">>, - <<"c:/home/cowboy/././././././file">>, - <<"c:/home/cowboy/abc/../file">>, - <<"c:/home/cowboy/abc/../file">>, - <<"c:/home/cowboy/abc/./.././file">> - ] - end, - [{P, fun() -> - case fullpath(P) of - << "c:/home/cowboy/", _/bits >> -> ok - end - end} || P <- Tests]. - -bad_path_win32_check_test_() -> - Tests = case os:type() of - {unix, _} -> - []; - {win32, _} -> - [ - <<"c:/home/cowboy/../../secretfile.bat">>, - <<"c:/home/cowboy/c:/secretfile.bat">>, - <<"c:/home/cowboy/..\\..\\secretfile.bat">>, - <<"c:/home/cowboy/c:\\secretfile.bat">> - ] - end, - [{P, fun() -> - error = case fullpath(P) of - << "c:/home/cowboy/", _/bits >> -> ok; - _ -> error - end - end} || P <- Tests]. --endif. - -%% Reject requests that tried to access a file outside -%% the target directory, or used reserved characters. - --spec malformed_request(Req, State) - -> {boolean(), Req, State}. -malformed_request(Req, State) -> - {State =:= error, Req, State}. - -%% Directories, files that can't be accessed at all and -%% files with no read flag are forbidden. - --spec forbidden(Req, State) - -> {boolean(), Req, State} - when State::state(). -forbidden(Req, State={_, {_, #file_info{type=directory}}, _}) -> - {true, Req, State}; -forbidden(Req, State={_, {error, eacces}, _}) -> - {true, Req, State}; -forbidden(Req, State={_, {_, #file_info{access=Access}}, _}) - when Access =:= write; Access =:= none -> - {true, Req, State}; -forbidden(Req, State) -> - {false, Req, State}. - -%% Detect the mimetype of the file. - --spec content_types_provided(Req, State) - -> {[{binary(), get_file}], Req, State} - when State::state(). -content_types_provided(Req, State={Path, _, Extra}) when is_list(Extra) -> - case lists:keyfind(mimetypes, 1, Extra) of - false -> - {[{cow_mimetypes:web(Path), get_file}], Req, State}; - {mimetypes, Module, Function} -> - {[{Module:Function(Path), get_file}], Req, State}; - {mimetypes, Type} -> - {[{Type, get_file}], Req, State} - end. - -%% Detect the charset of the file. - --spec charsets_provided(Req, State) - -> {[binary()], Req, State} - when State::state(). -charsets_provided(Req, State={Path, _, Extra}) -> - case lists:keyfind(charset, 1, Extra) of - %% We simulate the callback not being exported. - false -> - no_call; - {charset, Module, Function} -> - {[Module:Function(Path)], Req, State}; - {charset, Charset} when is_binary(Charset) -> - {[Charset], Req, State} - end. - -%% Enable support for range requests. - --spec ranges_provided(Req, State) - -> {[{binary(), auto}], Req, State} - when State::state(). -ranges_provided(Req, State) -> - {[{<<"bytes">>, auto}], Req, State}. - -%% Assume the resource doesn't exist if it's not a regular file. - --spec resource_exists(Req, State) - -> {boolean(), Req, State} - when State::state(). -resource_exists(Req, State={_, {_, #file_info{type=regular}}, _}) -> - {true, Req, State}; -resource_exists(Req, State) -> - {false, Req, State}. - -%% Generate an etag for the file. - --spec generate_etag(Req, State) - -> {{strong | weak, binary()}, Req, State} - when State::state(). -generate_etag(Req, State={Path, {_, #file_info{size=Size, mtime=Mtime}}, - Extra}) -> - case lists:keyfind(etag, 1, Extra) of - false -> - {generate_default_etag(Size, Mtime), Req, State}; - {etag, Module, Function} -> - {Module:Function(Path, Size, Mtime), Req, State}; - {etag, false} -> - {undefined, Req, State} - end. - -generate_default_etag(Size, Mtime) -> - {strong, integer_to_binary(erlang:phash2({Size, Mtime}, 16#ffffffff))}. - -%% Return the time of last modification of the file. - --spec last_modified(Req, State) - -> {calendar:datetime(), Req, State} - when State::state(). -last_modified(Req, State={_, {_, #file_info{mtime=Modified}}, _}) -> - {Modified, Req, State}. - -%% Stream the file. - --spec get_file(Req, State) - -> {{sendfile, 0, non_neg_integer(), binary()}, Req, State} - when State::state(). -get_file(Req, State={Path, {direct, #file_info{size=Size}}, _}) -> - {{sendfile, 0, Size, Path}, Req, State}; -get_file(Req, State={Path, {archive, _}, _}) -> - PathS = binary_to_list(Path), - {ok, Bin, _} = erl_prim_loader:get_file(PathS), - {Bin, Req, State}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_stream.erl b/_build/emqx/lib/cowboy/src/cowboy_stream.erl deleted file mode 100644 index 2dad6d0386..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_stream.erl +++ /dev/null @@ -1,193 +0,0 @@ -%% Copyright (c) 2015-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_stream). - --type state() :: any(). --type human_reason() :: atom(). - --type streamid() :: any(). --export_type([streamid/0]). - --type fin() :: fin | nofin. --export_type([fin/0]). - -%% @todo Perhaps it makes more sense to have resp_body in this module? - --type resp_command() - :: {response, cowboy:http_status(), cowboy:http_headers(), cowboy_req:resp_body()}. --export_type([resp_command/0]). - --type commands() :: [{inform, cowboy:http_status(), cowboy:http_headers()} - | resp_command() - | {headers, cowboy:http_status(), cowboy:http_headers()} - | {data, fin(), cowboy_req:resp_body()} - | {trailers, cowboy:http_headers()} - | {push, binary(), binary(), binary(), inet:port_number(), - binary(), binary(), cowboy:http_headers()} - | {flow, pos_integer()} - | {spawn, pid(), timeout()} - | {error_response, cowboy:http_status(), cowboy:http_headers(), iodata()} - | {switch_protocol, cowboy:http_headers(), module(), state()} - | {internal_error, any(), human_reason()} - | {set_options, map()} - | {log, logger:level(), io:format(), list()} - | stop]. --export_type([commands/0]). - --type reason() :: normal | switch_protocol - | {internal_error, timeout | {error | exit | throw, any()}, human_reason()} - | {socket_error, closed | atom(), human_reason()} - | {stream_error, cow_http2:error(), human_reason()} - | {connection_error, cow_http2:error(), human_reason()} - | {stop, cow_http2:frame() | {exit, any()}, human_reason()}. --export_type([reason/0]). - --type partial_req() :: map(). %% @todo Take what's in cowboy_req with everything? optional. --export_type([partial_req/0]). - --callback init(streamid(), cowboy_req:req(), cowboy:opts()) -> {commands(), state()}. --callback data(streamid(), fin(), binary(), State) -> {commands(), State} when State::state(). --callback info(streamid(), any(), State) -> {commands(), State} when State::state(). --callback terminate(streamid(), reason(), state()) -> any(). --callback early_error(streamid(), reason(), partial_req(), Resp, cowboy:opts()) - -> Resp when Resp::resp_command(). - -%% @todo To optimize the number of active timers we could have a command -%% that enables a timeout that is called in the absence of any other call, -%% similar to what gen_server does. However the nice thing about this is -%% that the connection process can keep a single timer around (the same -%% one that would be used to detect half-closed sockets) and use this -%% timer and other events to trigger the timeout in streams at their -%% intended time. -%% -%% This same timer can be used to try and send PING frames to help detect -%% that the connection is indeed unresponsive. - --export([init/3]). --export([data/4]). --export([info/3]). --export([terminate/3]). --export([early_error/5]). --export([make_error_log/5]). - -%% Note that this and other functions in this module do NOT catch -%% exceptions. We want the exception to go all the way down to the -%% protocol code. -%% -%% OK the failure scenario is not so clear. The problem is -%% that the failure at any point in init/3 will result in the -%% corresponding state being lost. I am unfortunately not -%% confident we can do anything about this. If the crashing -%% handler just created a process, we'll never know about it. -%% Therefore at this time I choose to leave all failure handling -%% to the protocol process. -%% -%% Note that a failure in init/3 will result in terminate/3 -%% NOT being called. This is because the state is not available. - --spec init(streamid(), cowboy_req:req(), cowboy:opts()) - -> {commands(), {module(), state()} | undefined}. -init(StreamID, Req, Opts) -> - case maps:get(stream_handlers, Opts, [cowboy_stream_h]) of - [] -> - {[], undefined}; - [Handler|Tail] -> - %% We call the next handler and remove it from the list of - %% stream handlers. This means that handlers that run after - %% it have no knowledge it exists. Should user require this - %% knowledge they can just define a separate option that will - %% be left untouched. - {Commands, State} = Handler:init(StreamID, Req, Opts#{stream_handlers => Tail}), - {Commands, {Handler, State}} - end. - --spec data(streamid(), fin(), binary(), {Handler, State} | undefined) - -> {commands(), {Handler, State} | undefined} - when Handler::module(), State::state(). -data(_, _, _, undefined) -> - {[], undefined}; -data(StreamID, IsFin, Data, {Handler, State0}) -> - {Commands, State} = Handler:data(StreamID, IsFin, Data, State0), - {Commands, {Handler, State}}. - --spec info(streamid(), any(), {Handler, State} | undefined) - -> {commands(), {Handler, State} | undefined} - when Handler::module(), State::state(). -info(_, _, undefined) -> - {[], undefined}; -info(StreamID, Info, {Handler, State0}) -> - {Commands, State} = Handler:info(StreamID, Info, State0), - {Commands, {Handler, State}}. - --spec terminate(streamid(), reason(), {module(), state()} | undefined) -> ok. -terminate(_, _, undefined) -> - ok; -terminate(StreamID, Reason, {Handler, State}) -> - _ = Handler:terminate(StreamID, Reason, State), - ok. - --spec early_error(streamid(), reason(), partial_req(), Resp, cowboy:opts()) - -> Resp when Resp::resp_command(). -early_error(StreamID, Reason, PartialReq, Resp, Opts) -> - case maps:get(stream_handlers, Opts, [cowboy_stream_h]) of - [] -> - Resp; - [Handler|Tail] -> - %% This is the same behavior as in init/3. - Handler:early_error(StreamID, Reason, - PartialReq, Resp, Opts#{stream_handlers => Tail}) - end. - --spec make_error_log(init | data | info | terminate | early_error, - list(), error | exit | throw, any(), list()) - -> {log, error, string(), list()}. -make_error_log(init, [StreamID, Req, Opts], Class, Exception, Stacktrace) -> - {log, error, - "Unhandled exception ~p:~p in cowboy_stream:init(~p, Req, Opts)~n" - "Stacktrace: ~p~n" - "Req: ~p~n" - "Opts: ~p~n", - [Class, Exception, StreamID, Stacktrace, Req, Opts]}; -make_error_log(data, [StreamID, IsFin, Data, State], Class, Exception, Stacktrace) -> - {log, error, - "Unhandled exception ~p:~p in cowboy_stream:data(~p, ~p, Data, State)~n" - "Stacktrace: ~p~n" - "Data: ~p~n" - "State: ~p~n", - [Class, Exception, StreamID, IsFin, Stacktrace, Data, State]}; -make_error_log(info, [StreamID, Msg, State], Class, Exception, Stacktrace) -> - {log, error, - "Unhandled exception ~p:~p in cowboy_stream:info(~p, Msg, State)~n" - "Stacktrace: ~p~n" - "Msg: ~p~n" - "State: ~p~n", - [Class, Exception, StreamID, Stacktrace, Msg, State]}; -make_error_log(terminate, [StreamID, Reason, State], Class, Exception, Stacktrace) -> - {log, error, - "Unhandled exception ~p:~p in cowboy_stream:terminate(~p, Reason, State)~n" - "Stacktrace: ~p~n" - "Reason: ~p~n" - "State: ~p~n", - [Class, Exception, StreamID, Stacktrace, Reason, State]}; -make_error_log(early_error, [StreamID, Reason, PartialReq, Resp, Opts], - Class, Exception, Stacktrace) -> - {log, error, - "Unhandled exception ~p:~p in cowboy_stream:early_error(~p, Reason, PartialReq, Resp, Opts)~n" - "Stacktrace: ~p~n" - "Reason: ~p~n" - "PartialReq: ~p~n" - "Resp: ~p~n" - "Opts: ~p~n", - [Class, Exception, StreamID, Stacktrace, Reason, PartialReq, Resp, Opts]}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_stream_h.erl b/_build/emqx/lib/cowboy/src/cowboy_stream_h.erl deleted file mode 100644 index 71b2948ebb..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_stream_h.erl +++ /dev/null @@ -1,338 +0,0 @@ -%% Copyright (c) 2016-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_stream_h). --behavior(cowboy_stream). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([init/3]). --export([data/4]). --export([info/3]). --export([terminate/3]). --export([early_error/5]). - --export([request_process/3]). --export([resume/5]). - --record(state, { - next :: any(), - ref = undefined :: ranch:ref(), - pid = undefined :: pid(), - expect = undefined :: undefined | continue, - read_body_pid = undefined :: pid() | undefined, - read_body_ref = undefined :: reference() | undefined, - read_body_timer_ref = undefined :: reference() | undefined, - read_body_length = 0 :: non_neg_integer() | infinity | auto, - read_body_is_fin = nofin :: nofin | {fin, non_neg_integer()}, - read_body_buffer = <<>> :: binary(), - body_length = 0 :: non_neg_integer(), - stream_body_pid = undefined :: pid() | undefined, - stream_body_status = normal :: normal | blocking | blocked -}). - --spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) - -> {[{spawn, pid(), timeout()}], #state{}}. -init(StreamID, Req=#{ref := Ref}, Opts) -> - Env = maps:get(env, Opts, #{}), - Middlewares = maps:get(middlewares, Opts, [cowboy_router, cowboy_handler]), - Shutdown = maps:get(shutdown_timeout, Opts, 5000), - Pid = proc_lib:spawn_link(?MODULE, request_process, [Req, Env, Middlewares]), - Expect = expect(Req), - {Commands, Next} = cowboy_stream:init(StreamID, Req, Opts), - {[{spawn, Pid, Shutdown}|Commands], - #state{next=Next, ref=Ref, pid=Pid, expect=Expect}}. - -%% Ignore the expect header in HTTP/1.0. -expect(#{version := 'HTTP/1.0'}) -> - undefined; -expect(Req) -> - try cowboy_req:parse_header(<<"expect">>, Req) of - Expect -> - Expect - catch _:_ -> - undefined - end. - -%% If we receive data and stream is waiting for data: -%% If we accumulated enough data or IsFin=fin, send it. -%% If we are in auto mode, send it and update flow control. -%% If not, buffer it. -%% If not, buffer it. -%% -%% We always reset the expect field when we receive data, -%% since the client started sending the request body before -%% we could send a 100 continue response. - --spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State) - -> {cowboy_stream:commands(), State} when State::#state{}. -%% Stream isn't waiting for data. -data(StreamID, IsFin, Data, State=#state{ - read_body_ref=undefined, read_body_buffer=Buffer, body_length=BodyLen}) -> - do_data(StreamID, IsFin, Data, [], State#state{ - expect=undefined, - read_body_is_fin=IsFin, - read_body_buffer= << Buffer/binary, Data/binary >>, - body_length=BodyLen + byte_size(Data) - }); -%% Stream is waiting for data using auto mode. -%% -%% There is no buffering done in auto mode. -data(StreamID, IsFin, Data, State=#state{read_body_pid=Pid, read_body_ref=Ref, - read_body_length=auto, body_length=BodyLen}) -> - send_request_body(Pid, Ref, IsFin, BodyLen, Data), - do_data(StreamID, IsFin, Data, [{flow, byte_size(Data)}], State#state{ - read_body_ref=undefined, - body_length=BodyLen - }); -%% Stream is waiting for data but we didn't receive enough to send yet. -data(StreamID, IsFin=nofin, Data, State=#state{ - read_body_length=ReadLen, read_body_buffer=Buffer, body_length=BodyLen}) - when byte_size(Data) + byte_size(Buffer) < ReadLen -> - do_data(StreamID, IsFin, Data, [], State#state{ - expect=undefined, - read_body_buffer= << Buffer/binary, Data/binary >>, - body_length=BodyLen + byte_size(Data) - }); -%% Stream is waiting for data and we received enough to send. -data(StreamID, IsFin, Data, State=#state{read_body_pid=Pid, read_body_ref=Ref, - read_body_timer_ref=TRef, read_body_buffer=Buffer, body_length=BodyLen0}) -> - BodyLen = BodyLen0 + byte_size(Data), - ok = erlang:cancel_timer(TRef, [{async, true}, {info, false}]), - send_request_body(Pid, Ref, IsFin, BodyLen, <>), - do_data(StreamID, IsFin, Data, [], State#state{ - expect=undefined, - read_body_ref=undefined, - read_body_timer_ref=undefined, - read_body_buffer= <<>>, - body_length=BodyLen - }). - -do_data(StreamID, IsFin, Data, Commands1, State=#state{next=Next0}) -> - {Commands2, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0), - {Commands1 ++ Commands2, State#state{next=Next}}. - --spec info(cowboy_stream:streamid(), any(), State) - -> {cowboy_stream:commands(), State} when State::#state{}. -info(StreamID, Info={'EXIT', Pid, normal}, State=#state{pid=Pid}) -> - do_info(StreamID, Info, [stop], State); -info(StreamID, Info={'EXIT', Pid, {{request_error, Reason, _HumanReadable}, _}}, - State=#state{pid=Pid}) -> - Status = case Reason of - timeout -> 408; - payload_too_large -> 413; - _ -> 400 - end, - %% @todo Headers? Details in body? Log the crash? More stuff in debug only? - do_info(StreamID, Info, [ - {error_response, Status, #{<<"content-length">> => <<"0">>}, <<>>}, - stop - ], State); -info(StreamID, Exit={'EXIT', Pid, {Reason, Stacktrace}}, State=#state{ref=Ref, pid=Pid}) -> - Commands0 = [{internal_error, Exit, 'Stream process crashed.'}], - Commands = case Reason of - normal -> Commands0; - shutdown -> Commands0; - {shutdown, _} -> Commands0; - _ -> [{log, error, - "Ranch listener ~p, connection process ~p, stream ~p " - "had its request process ~p exit with reason " - "~999999p and stacktrace ~999999p~n", - [Ref, self(), StreamID, Pid, Reason, Stacktrace]} - |Commands0] - end, - do_info(StreamID, Exit, [ - {error_response, 500, #{<<"content-length">> => <<"0">>}, <<>>} - |Commands], State); -%% Request body, auto mode, no body buffered. -info(StreamID, Info={read_body, Pid, Ref, auto, infinity}, State=#state{read_body_buffer= <<>>}) -> - do_info(StreamID, Info, [], State#state{ - read_body_pid=Pid, - read_body_ref=Ref, - read_body_length=auto - }); -%% Request body, auto mode, body buffered or complete. -info(StreamID, Info={read_body, Pid, Ref, auto, infinity}, State=#state{ - read_body_is_fin=IsFin, read_body_buffer=Buffer, body_length=BodyLen}) -> - send_request_body(Pid, Ref, IsFin, BodyLen, Buffer), - do_info(StreamID, Info, [{flow, byte_size(Buffer)}], - State#state{read_body_buffer= <<>>}); -%% Request body, body buffered large enough or complete. -%% -%% We do not send a 100 continue response if the client -%% already started sending the body. -info(StreamID, Info={read_body, Pid, Ref, Length, _}, State=#state{ - read_body_is_fin=IsFin, read_body_buffer=Buffer, body_length=BodyLen}) - when IsFin =:= fin; byte_size(Buffer) >= Length -> - send_request_body(Pid, Ref, IsFin, BodyLen, Buffer), - do_info(StreamID, Info, [], State#state{read_body_buffer= <<>>}); -%% Request body, not enough to send yet. -info(StreamID, Info={read_body, Pid, Ref, Length, Period}, State=#state{expect=Expect}) -> - Commands = case Expect of - continue -> [{inform, 100, #{}}, {flow, Length}]; - undefined -> [{flow, Length}] - end, - TRef = erlang:send_after(Period, self(), {{self(), StreamID}, {read_body_timeout, Ref}}), - do_info(StreamID, Info, Commands, State#state{ - read_body_pid=Pid, - read_body_ref=Ref, - read_body_timer_ref=TRef, - read_body_length=Length - }); -%% Request body reading timeout; send what we got. -info(StreamID, Info={read_body_timeout, Ref}, State=#state{read_body_pid=Pid, read_body_ref=Ref, - read_body_is_fin=IsFin, read_body_buffer=Buffer, body_length=BodyLen}) -> - send_request_body(Pid, Ref, IsFin, BodyLen, Buffer), - do_info(StreamID, Info, [], State#state{ - read_body_ref=undefined, - read_body_timer_ref=undefined, - read_body_buffer= <<>> - }); -info(StreamID, Info={read_body_timeout, _}, State) -> - do_info(StreamID, Info, [], State); -%% Response. -%% -%% We reset the expect field when a 100 continue response -%% is sent or when any final response is sent. -info(StreamID, Inform={inform, Status, _}, State0) -> - State = case cow_http:status_to_integer(Status) of - 100 -> State0#state{expect=undefined}; - _ -> State0 - end, - do_info(StreamID, Inform, [Inform], State); -info(StreamID, Response={response, _, _, _}, State) -> - do_info(StreamID, Response, [Response], State#state{expect=undefined}); -info(StreamID, Headers={headers, _, _}, State) -> - do_info(StreamID, Headers, [Headers], State#state{expect=undefined}); -%% Sending data involves the data message, the stream_buffer_full alarm -%% and the connection_buffer_full alarm. We stop sending acks when an alarm is on. -%% -%% We only apply backpressure when the message includes a pid. Otherwise -%% it is a message from Cowboy, or the user circumventing the backpressure. -%% -%% We currently do not support sending data from multiple processes concurrently. -info(StreamID, Data={data, _, _}, State) -> - do_info(StreamID, Data, [Data], State); -info(StreamID, Data0={data, Pid, _, _}, State0=#state{stream_body_status=Status}) -> - State = case Status of - normal -> - Pid ! {data_ack, self()}, - State0; - blocking -> - State0#state{stream_body_pid=Pid, stream_body_status=blocked}; - blocked -> - State0 - end, - Data = erlang:delete_element(2, Data0), - do_info(StreamID, Data, [Data], State); -info(StreamID, Alarm={alarm, Name, on}, State) - when Name =:= connection_buffer_full; Name =:= stream_buffer_full -> - do_info(StreamID, Alarm, [], State#state{stream_body_status=blocking}); -info(StreamID, Alarm={alarm, Name, off}, State=#state{stream_body_pid=Pid, stream_body_status=Status}) - when Name =:= connection_buffer_full; Name =:= stream_buffer_full -> - _ = case Status of - normal -> ok; - blocking -> ok; - blocked -> Pid ! {data_ack, self()} - end, - do_info(StreamID, Alarm, [], State#state{stream_body_pid=undefined, stream_body_status=normal}); -info(StreamID, Trailers={trailers, _}, State) -> - do_info(StreamID, Trailers, [Trailers], State); -info(StreamID, Push={push, _, _, _, _, _, _, _}, State) -> - do_info(StreamID, Push, [Push], State); -info(StreamID, SwitchProtocol={switch_protocol, _, _, _}, State) -> - do_info(StreamID, SwitchProtocol, [SwitchProtocol], State#state{expect=undefined}); -%% Convert the set_options message to a command. -info(StreamID, SetOptions={set_options, _}, State) -> - do_info(StreamID, SetOptions, [SetOptions], State); -%% Unknown message, either stray or meant for a handler down the line. -info(StreamID, Info, State) -> - do_info(StreamID, Info, [], State). - -do_info(StreamID, Info, Commands1, State0=#state{next=Next0}) -> - {Commands2, Next} = cowboy_stream:info(StreamID, Info, Next0), - {Commands1 ++ Commands2, State0#state{next=Next}}. - --spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> ok. -terminate(StreamID, Reason, #state{next=Next}) -> - cowboy_stream:terminate(StreamID, Reason, Next). - --spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(), - cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp - when Resp::cowboy_stream:resp_command(). -early_error(StreamID, Reason, PartialReq, Resp, Opts) -> - cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts). - -send_request_body(Pid, Ref, nofin, _, Data) -> - Pid ! {request_body, Ref, nofin, Data}, - ok; -send_request_body(Pid, Ref, fin, BodyLen, Data) -> - Pid ! {request_body, Ref, fin, BodyLen, Data}, - ok. - -%% Request process. - -%% We catch all exceptions in order to add the stacktrace to -%% the exit reason as it is not propagated by proc_lib otherwise -%% and therefore not present in the 'EXIT' message. We want -%% the stacktrace in order to simplify debugging of errors. -%% -%% This + the behavior in proc_lib means that we will get a -%% {Reason, Stacktrace} tuple for every exceptions, instead of -%% just for errors and throws. -%% -%% @todo Better spec. --spec request_process(cowboy_req:req(), cowboy_middleware:env(), [module()]) -> ok. -request_process(Req, Env, Middlewares) -> - OTP = erlang:system_info(otp_release), - try - execute(Req, Env, Middlewares) - catch - exit:Reason -> - Stacktrace = erlang:get_stacktrace(), - erlang:raise(exit, {Reason, Stacktrace}, Stacktrace); - %% OTP 19 does not propagate any exception stacktraces, - %% we therefore add it for every class of exception. - _:Reason when OTP =:= "19" -> - Stacktrace = erlang:get_stacktrace(), - erlang:raise(exit, {Reason, Stacktrace}, Stacktrace); - %% @todo I don't think this clause is necessary. - Class:Reason -> - erlang:raise(Class, Reason, erlang:get_stacktrace()) - end. - -execute(_, _, []) -> - ok; -execute(Req, Env, [Middleware|Tail]) -> - case Middleware:execute(Req, Env) of - {ok, Req2, Env2} -> - execute(Req2, Env2, Tail); - {suspend, Module, Function, Args} -> - proc_lib:hibernate(?MODULE, resume, [Env, Tail, Module, Function, Args]); - {stop, _Req2} -> - ok - end. - --spec resume(cowboy_middleware:env(), [module()], module(), atom(), [any()]) -> ok. -resume(Env, Tail, Module, Function, Args) -> - case apply(Module, Function, Args) of - {ok, Req2, Env2} -> - execute(Req2, Env2, Tail); - {suspend, Module2, Function2, Args2} -> - proc_lib:hibernate(?MODULE, resume, [Env, Tail, Module2, Function2, Args2]); - {stop, _Req2} -> - ok - end. diff --git a/_build/emqx/lib/cowboy/src/cowboy_sub_protocol.erl b/_build/emqx/lib/cowboy/src/cowboy_sub_protocol.erl deleted file mode 100644 index 6714289834..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_sub_protocol.erl +++ /dev/null @@ -1,24 +0,0 @@ -%% Copyright (c) 2013-2017, Loïc Hoguin -%% Copyright (c) 2013, James Fish -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_sub_protocol). - --callback upgrade(Req, Env, module(), any()) - -> {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). - --callback upgrade(Req, Env, module(), any(), any()) - -> {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). diff --git a/_build/emqx/lib/cowboy/src/cowboy_sup.erl b/_build/emqx/lib/cowboy/src/cowboy_sup.erl deleted file mode 100644 index d3ac3b0de4..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_sup.erl +++ /dev/null @@ -1,30 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_sup). --behaviour(supervisor). - --export([start_link/0]). --export([init/1]). - --spec start_link() -> {ok, pid()}. -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - --spec init([]) - -> {ok, {{supervisor:strategy(), 10, 10}, [supervisor:child_spec()]}}. -init([]) -> - Procs = [{cowboy_clock, {cowboy_clock, start_link, []}, - permanent, 5000, worker, [cowboy_clock]}], - {ok, {{one_for_one, 10, 10}, Procs}}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_tls.erl b/_build/emqx/lib/cowboy/src/cowboy_tls.erl deleted file mode 100644 index c049ecbeca..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_tls.erl +++ /dev/null @@ -1,56 +0,0 @@ -%% Copyright (c) 2015-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_tls). --behavior(ranch_protocol). - --export([start_link/3]). --export([start_link/4]). --export([connection_process/4]). - -%% Ranch 1. --spec start_link(ranch:ref(), ssl:sslsocket(), module(), cowboy:opts()) -> {ok, pid()}. -start_link(Ref, _Socket, Transport, Opts) -> - start_link(Ref, Transport, Opts). - -%% Ranch 2. --spec start_link(ranch:ref(), module(), cowboy:opts()) -> {ok, pid()}. -start_link(Ref, Transport, Opts) -> - Pid = proc_lib:spawn_link(?MODULE, connection_process, - [self(), Ref, Transport, Opts]), - {ok, Pid}. - --spec connection_process(pid(), ranch:ref(), module(), cowboy:opts()) -> ok. -connection_process(Parent, Ref, Transport, Opts) -> - ProxyInfo = case maps:get(proxy_header, Opts, false) of - true -> - {ok, ProxyInfo0} = ranch:recv_proxy_header(Ref, 1000), - ProxyInfo0; - false -> - undefined - end, - {ok, Socket} = ranch:handshake(Ref), - case ssl:negotiated_protocol(Socket) of - {ok, <<"h2">>} -> - init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, cowboy_http2); - _ -> %% http/1.1 or no protocol negotiated. - init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, cowboy_http) - end. - -init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol) -> - _ = case maps:get(connection_type, Opts, supervisor) of - worker -> ok; - supervisor -> process_flag(trap_exit, true) - end, - Protocol:init(Parent, Ref, Socket, Transport, ProxyInfo, Opts). diff --git a/_build/emqx/lib/cowboy/src/cowboy_tracer_h.erl b/_build/emqx/lib/cowboy/src/cowboy_tracer_h.erl deleted file mode 100644 index 750ff03753..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_tracer_h.erl +++ /dev/null @@ -1,192 +0,0 @@ -%% Copyright (c) 2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - --module(cowboy_tracer_h). --behavior(cowboy_stream). - --export([init/3]). --export([data/4]). --export([info/3]). --export([terminate/3]). --export([early_error/5]). - --export([set_trace_patterns/0]). - --export([tracer_process/3]). --export([system_continue/3]). --export([system_terminate/4]). --export([system_code_change/4]). - --type match_predicate() - :: fun((cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) -> boolean()). - --type tracer_match_specs() :: [match_predicate() - | {method, binary()} - | {host, binary()} - | {path, binary()} - | {path_start, binary()} - | {header, binary()} - | {header, binary(), binary()} - | {peer_ip, inet:ip_address()} -]. --export_type([tracer_match_specs/0]). - --type tracer_callback() :: fun((init | terminate | tuple(), any()) -> any()). --export_type([tracer_callback/0]). - --spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) - -> {cowboy_stream:commands(), any()}. -init(StreamID, Req, Opts) -> - init_tracer(StreamID, Req, Opts), - cowboy_stream:init(StreamID, Req, Opts). - --spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State) - -> {cowboy_stream:commands(), State} when State::any(). -data(StreamID, IsFin, Data, Next) -> - cowboy_stream:data(StreamID, IsFin, Data, Next). - --spec info(cowboy_stream:streamid(), any(), State) - -> {cowboy_stream:commands(), State} when State::any(). -info(StreamID, Info, Next) -> - cowboy_stream:info(StreamID, Info, Next). - --spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), any()) -> any(). -terminate(StreamID, Reason, Next) -> - cowboy_stream:terminate(StreamID, Reason, Next). - --spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(), - cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp - when Resp::cowboy_stream:resp_command(). -early_error(StreamID, Reason, PartialReq, Resp, Opts) -> - cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts). - -%% API. - -%% These trace patterns are most likely not suitable for production. --spec set_trace_patterns() -> ok. -set_trace_patterns() -> - erlang:trace_pattern({'_', '_', '_'}, [{'_', [], [{return_trace}]}], [local]), - erlang:trace_pattern(on_load, [{'_', [], [{return_trace}]}], [local]), - ok. - -%% Internal. - -init_tracer(StreamID, Req, Opts=#{tracer_match_specs := List, tracer_callback := _}) -> - case match(List, StreamID, Req, Opts) of - false -> - ok; - true -> - start_tracer(StreamID, Req, Opts) - end; -%% When the options tracer_match_specs or tracer_callback -%% are not provided we do not enable tracing. -init_tracer(_, _, _) -> - ok. - -match([], _, _, _) -> - true; -match([Predicate|Tail], StreamID, Req, Opts) when is_function(Predicate) -> - case Predicate(StreamID, Req, Opts) of - true -> match(Tail, StreamID, Req, Opts); - false -> false - end; -match([{method, Value}|Tail], StreamID, Req=#{method := Value}, Opts) -> - match(Tail, StreamID, Req, Opts); -match([{host, Value}|Tail], StreamID, Req=#{host := Value}, Opts) -> - match(Tail, StreamID, Req, Opts); -match([{path, Value}|Tail], StreamID, Req=#{path := Value}, Opts) -> - match(Tail, StreamID, Req, Opts); -match([{path_start, PathStart}|Tail], StreamID, Req=#{path := Path}, Opts) -> - Len = byte_size(PathStart), - case Path of - <> -> match(Tail, StreamID, Req, Opts); - _ -> false - end; -match([{header, Name}|Tail], StreamID, Req=#{headers := Headers}, Opts) -> - case Headers of - #{Name := _} -> match(Tail, StreamID, Req, Opts); - _ -> false - end; -match([{header, Name, Value}|Tail], StreamID, Req=#{headers := Headers}, Opts) -> - case Headers of - #{Name := Value} -> match(Tail, StreamID, Req, Opts); - _ -> false - end; -match([{peer_ip, IP}|Tail], StreamID, Req=#{peer := {IP, _}}, Opts) -> - match(Tail, StreamID, Req, Opts); -match(_, _, _, _) -> - false. - -%% We only start the tracer if one wasn't started before. -start_tracer(StreamID, Req, Opts) -> - case erlang:trace_info(self(), tracer) of - {tracer, []} -> - TracerPid = proc_lib:spawn_link(?MODULE, tracer_process, [StreamID, Req, Opts]), - %% The default flags are probably not suitable for production. - Flags = maps:get(tracer_flags, Opts, [ - send, 'receive', call, return_to, - procs, ports, monotonic_timestamp, - %% The set_on_spawn flag is necessary to catch events - %% from request processes. - set_on_spawn - ]), - erlang:trace(self(), true, [{tracer, TracerPid}|Flags]), - ok; - _ -> - ok - end. - -%% Tracer process. - --spec tracer_process(_, _, _) -> no_return(). -tracer_process(StreamID, Req=#{pid := Parent}, Opts=#{tracer_callback := Fun}) -> - %% This is necessary because otherwise the tracer could stop - %% before it has finished processing the events in its queue. - process_flag(trap_exit, true), - State = Fun(init, {StreamID, Req, Opts}), - tracer_loop(Parent, Opts, State). - -tracer_loop(Parent, Opts=#{tracer_callback := Fun}, State0) -> - receive - Msg when element(1, Msg) =:= trace_ts -> - State = Fun(Msg, State0), - tracer_loop(Parent, Opts, State); - {'EXIT', Parent, Reason} -> - tracer_terminate(Reason, Opts, State0); - {system, From, Request} -> - sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {Opts, State0}); - Msg -> - cowboy:log(warning, "~p: Tracer process received stray message ~9999p~n", - [?MODULE, Msg], Opts), - tracer_loop(Parent, Opts, State0) - end. - --spec tracer_terminate(_, _, _) -> no_return(). -tracer_terminate(Reason, #{tracer_callback := Fun}, State) -> - _ = Fun(terminate, State), - exit(Reason). - -%% System callbacks. - --spec system_continue(pid(), _, {cowboy:opts(), any()}) -> no_return(). -system_continue(Parent, _, {Opts, State}) -> - tracer_loop(Parent, Opts, State). - --spec system_terminate(any(), _, _, _) -> no_return(). -system_terminate(Reason, _, _, {Opts, State}) -> - tracer_terminate(Reason, Opts, State). - --spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::any(). -system_code_change(Misc, _, _, _) -> - {ok, Misc}. diff --git a/_build/emqx/lib/cowboy/src/cowboy_websocket.erl b/_build/emqx/lib/cowboy/src/cowboy_websocket.erl deleted file mode 100644 index 8165c29e48..0000000000 --- a/_build/emqx/lib/cowboy/src/cowboy_websocket.erl +++ /dev/null @@ -1,700 +0,0 @@ -%% Copyright (c) 2011-2017, Loïc Hoguin -%% -%% Permission to use, copy, modify, and/or distribute this software for any -%% purpose with or without fee is hereby granted, provided that the above -%% copyright notice and this permission notice appear in all copies. -%% -%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -%% Cowboy supports versions 7 through 17 of the Websocket drafts. -%% It also supports RFC6455, the proposed standard for Websocket. --module(cowboy_websocket). --behaviour(cowboy_sub_protocol). - --ifdef(OTP_RELEASE). --compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}). --endif. - --export([is_upgrade_request/1]). --export([upgrade/4]). --export([upgrade/5]). --export([takeover/7]). --export([loop/3]). - --export([system_continue/3]). --export([system_terminate/4]). --export([system_code_change/4]). - --type commands() :: [cow_ws:frame() - | {active, boolean()} - | {deflate, boolean()} - | {set_options, map()} - | {shutdown, Reason :: term()} -]. --export_type([commands/0]). - --type call_result(State) :: {commands(), State} | {commands(), State, hibernate}. - --type deprecated_call_result(State) :: {ok, State} - | {ok, State, hibernate} - | {reply, cow_ws:frame() | [cow_ws:frame()], State} - | {reply, cow_ws:frame() | [cow_ws:frame()], State, hibernate} - | {stop, State}. - --type terminate_reason() :: normal | stop | timeout - | remote | {remote, cow_ws:close_code(), binary()} - | {error, badencoding | badframe | closed | atom()} - | {crash, error | exit | throw, any()}. - --callback init(Req, any()) - -> {ok | module(), Req, any()} - | {module(), Req, any(), any()} - when Req::cowboy_req:req(). - --callback websocket_init(State) - -> call_result(State) | deprecated_call_result(State) when State::any(). --optional_callbacks([websocket_init/1]). - --callback websocket_handle(ping | pong | {text | binary | ping | pong, binary()}, State) - -> call_result(State) | deprecated_call_result(State) when State::any(). --callback websocket_info(any(), State) - -> call_result(State) | deprecated_call_result(State) when State::any(). - --callback terminate(any(), cowboy_req:req(), any()) -> ok. --optional_callbacks([terminate/3]). - --type opts() :: #{ - compress => boolean(), - deflate_opts => cow_ws:deflate_opts(), - idle_timeout => timeout(), - max_frame_size => non_neg_integer() | infinity, - req_filter => fun((cowboy_req:req()) -> map()), - validate_utf8 => boolean() -}. --export_type([opts/0]). - --record(state, { - parent :: undefined | pid(), - ref :: ranch:ref(), - socket = undefined :: inet:socket() | {pid(), cowboy_stream:streamid()} | undefined, - transport = undefined :: module() | undefined, - opts = #{} :: opts(), - active = true :: boolean(), - handler :: module(), - key = undefined :: undefined | binary(), - timeout_ref = undefined :: undefined | reference(), - messages = undefined :: undefined | {atom(), atom(), atom()}, - hibernate = false :: boolean(), - frag_state = undefined :: cow_ws:frag_state(), - frag_buffer = <<>> :: binary(), - utf8_state :: cow_ws:utf8_state(), - deflate = true :: boolean(), - extensions = #{} :: map(), - req = #{} :: map(), - closed = false :: boolean(), - shutdown_reason = normal :: any() -}). - -%% Because the HTTP/1.1 and HTTP/2 handshakes are so different, -%% this function is necessary to figure out whether a request -%% is trying to upgrade to the Websocket protocol. - --spec is_upgrade_request(cowboy_req:req()) -> boolean(). -is_upgrade_request(#{version := 'HTTP/2', method := <<"CONNECT">>, protocol := Protocol}) -> - <<"websocket">> =:= cowboy_bstr:to_lower(Protocol); -is_upgrade_request(Req=#{version := 'HTTP/1.1', method := <<"GET">>}) -> - ConnTokens = cowboy_req:parse_header(<<"connection">>, Req, []), - case lists:member(<<"upgrade">>, ConnTokens) of - false -> - false; - true -> - UpgradeTokens = cowboy_req:parse_header(<<"upgrade">>, Req), - lists:member(<<"websocket">>, UpgradeTokens) - end; -is_upgrade_request(_) -> - false. - -%% Stream process. - --spec upgrade(Req, Env, module(), any()) - -> {ok, Req, Env} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -upgrade(Req, Env, Handler, HandlerState) -> - upgrade(Req, Env, Handler, HandlerState, #{}). - --spec upgrade(Req, Env, module(), any(), opts()) - -> {ok, Req, Env} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -%% @todo Immediately crash if a response has already been sent. -upgrade(Req0=#{version := Version}, Env, Handler, HandlerState, Opts) -> - FilteredReq = case maps:get(req_filter, Opts, undefined) of - undefined -> maps:with([method, version, scheme, host, port, path, qs, peer], Req0); - FilterFun -> FilterFun(Req0) - end, - Utf8State = case maps:get(validate_utf8, Opts, true) of - true -> 0; - false -> undefined - end, - State0 = #state{opts=Opts, handler=Handler, utf8_state=Utf8State, req=FilteredReq}, - try websocket_upgrade(State0, Req0) of - {ok, State, Req} -> - websocket_handshake(State, Req, HandlerState, Env); - %% The status code 426 is specific to HTTP/1.1 connections. - {error, upgrade_required} when Version =:= 'HTTP/1.1' -> - {ok, cowboy_req:reply(426, #{ - <<"connection">> => <<"upgrade">>, - <<"upgrade">> => <<"websocket">> - }, Req0), Env}; - %% Use a generic 400 error for HTTP/2. - {error, upgrade_required} -> - {ok, cowboy_req:reply(400, Req0), Env} - catch _:_ -> - %% @todo Probably log something here? - %% @todo Test that we can have 2 /ws 400 status code in a row on the same connection. - %% @todo Does this even work? - {ok, cowboy_req:reply(400, Req0), Env} - end. - -websocket_upgrade(State, Req=#{version := Version}) -> - case is_upgrade_request(Req) of - false -> - {error, upgrade_required}; - true when Version =:= 'HTTP/1.1' -> - Key = cowboy_req:header(<<"sec-websocket-key">>, Req), - false = Key =:= undefined, - websocket_version(State#state{key=Key}, Req); - true -> - websocket_version(State, Req) - end. - -websocket_version(State, Req) -> - WsVersion = cowboy_req:parse_header(<<"sec-websocket-version">>, Req), - case WsVersion of - 7 -> ok; - 8 -> ok; - 13 -> ok - end, - websocket_extensions(State, Req#{websocket_version => WsVersion}). - -websocket_extensions(State=#state{opts=Opts}, Req) -> - %% @todo We want different options for this. For example - %% * compress everything auto - %% * compress only text auto - %% * compress only binary auto - %% * compress nothing auto (but still enabled it) - %% * disable compression - Compress = maps:get(compress, Opts, false), - case {Compress, cowboy_req:parse_header(<<"sec-websocket-extensions">>, Req)} of - {true, Extensions} when Extensions =/= undefined -> - websocket_extensions(State, Req, Extensions, []); - _ -> - {ok, State, Req} - end. - -websocket_extensions(State, Req, [], []) -> - {ok, State, Req}; -websocket_extensions(State, Req, [], [<<", ">>|RespHeader]) -> - {ok, State, cowboy_req:set_resp_header(<<"sec-websocket-extensions">>, lists:reverse(RespHeader), Req)}; -%% For HTTP/2 we ARE on the controlling process and do NOT want to update the owner. -websocket_extensions(State=#state{opts=Opts, extensions=Extensions}, - Req=#{pid := Pid, version := Version}, - [{<<"permessage-deflate">>, Params}|Tail], RespHeader) -> - DeflateOpts0 = maps:get(deflate_opts, Opts, #{}), - DeflateOpts = case Version of - 'HTTP/1.1' -> DeflateOpts0#{owner => Pid}; - _ -> DeflateOpts0 - end, - try cow_ws:negotiate_permessage_deflate(Params, Extensions, DeflateOpts) of - {ok, RespExt, Extensions2} -> - websocket_extensions(State#state{extensions=Extensions2}, - Req, Tail, [<<", ">>, RespExt|RespHeader]); - ignore -> - websocket_extensions(State, Req, Tail, RespHeader) - catch exit:{error, incompatible_zlib_version, _} -> - websocket_extensions(State, Req, Tail, RespHeader) - end; -websocket_extensions(State=#state{opts=Opts, extensions=Extensions}, - Req=#{pid := Pid, version := Version}, - [{<<"x-webkit-deflate-frame">>, Params}|Tail], RespHeader) -> - DeflateOpts0 = maps:get(deflate_opts, Opts, #{}), - DeflateOpts = case Version of - 'HTTP/1.1' -> DeflateOpts0#{owner => Pid}; - _ -> DeflateOpts0 - end, - try cow_ws:negotiate_x_webkit_deflate_frame(Params, Extensions, DeflateOpts) of - {ok, RespExt, Extensions2} -> - websocket_extensions(State#state{extensions=Extensions2}, - Req, Tail, [<<", ">>, RespExt|RespHeader]); - ignore -> - websocket_extensions(State, Req, Tail, RespHeader) - catch exit:{error, incompatible_zlib_version, _} -> - websocket_extensions(State, Req, Tail, RespHeader) - end; -websocket_extensions(State, Req, [_|Tail], RespHeader) -> - websocket_extensions(State, Req, Tail, RespHeader). - --spec websocket_handshake(#state{}, Req, any(), Env) - -> {ok, Req, Env} - when Req::cowboy_req:req(), Env::cowboy_middleware:env(). -websocket_handshake(State=#state{key=Key}, - Req=#{version := 'HTTP/1.1', pid := Pid, streamid := StreamID}, - HandlerState, Env) -> - Challenge = base64:encode(crypto:hash(sha, - << Key/binary, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" >>)), - %% @todo We don't want date and server headers. - Headers = cowboy_req:response_headers(#{ - <<"connection">> => <<"Upgrade">>, - <<"upgrade">> => <<"websocket">>, - <<"sec-websocket-accept">> => Challenge - }, Req), - Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, {State, HandlerState}}}, - {ok, Req, Env}; -%% For HTTP/2 we do not let the process die, we instead keep it -%% for the Websocket stream. This is because in HTTP/2 we only -%% have a stream, it doesn't take over the whole connection. -websocket_handshake(State, Req=#{ref := Ref, pid := Pid, streamid := StreamID}, - HandlerState, _Env) -> - %% @todo We don't want date and server headers. - Headers = cowboy_req:response_headers(#{}, Req), - Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, {State, HandlerState}}}, - takeover(Pid, Ref, {Pid, StreamID}, undefined, undefined, <<>>, - {State, HandlerState}). - -%% Connection process. - --record(ps_header, { - buffer = <<>> :: binary() -}). - --record(ps_payload, { - type :: cow_ws:frame_type(), - len :: non_neg_integer(), - mask_key :: cow_ws:mask_key(), - rsv :: cow_ws:rsv(), - close_code = undefined :: undefined | cow_ws:close_code(), - unmasked = <<>> :: binary(), - unmasked_len = 0 :: non_neg_integer(), - buffer = <<>> :: binary() -}). - --type parse_state() :: #ps_header{} | #ps_payload{}. - --spec takeover(pid(), ranch:ref(), inet:socket() | {pid(), cowboy_stream:streamid()}, - module() | undefined, any(), binary(), - {#state{}, any()}) -> no_return(). -takeover(Parent, Ref, Socket, Transport, _Opts, Buffer, - {State0=#state{handler=Handler}, HandlerState}) -> - %% @todo We should have an option to disable this behavior. - ranch:remove_connection(Ref), - Messages = case Transport of - undefined -> undefined; - _ -> Transport:messages() - end, - State = loop_timeout(State0#state{parent=Parent, - ref=Ref, socket=Socket, transport=Transport, - key=undefined, messages=Messages}), - %% We call parse_header/3 immediately because there might be - %% some data in the buffer that was sent along with the handshake. - %% While it is not allowed by the protocol to send frames immediately, - %% we still want to process that data if any. - case erlang:function_exported(Handler, websocket_init, 1) of - true -> handler_call(State, HandlerState, #ps_header{buffer=Buffer}, - websocket_init, undefined, fun parse_header/3); - false -> parse_header(State, HandlerState, #ps_header{buffer=Buffer}) - end. - -before_loop(State=#state{active=false}, HandlerState, ParseState) -> - loop(State, HandlerState, ParseState); -%% @todo We probably shouldn't do the setopts if we have not received a socket message. -%% @todo We need to hibernate when HTTP/2 is used too. -before_loop(State=#state{socket=Stream={Pid, _}, transport=undefined}, - HandlerState, ParseState) -> - %% @todo Keep Ref around. - ReadBodyRef = make_ref(), - Pid ! {Stream, {read_body, self(), ReadBodyRef, auto, infinity}}, - loop(State, HandlerState, ParseState); -before_loop(State=#state{socket=Socket, transport=Transport, hibernate=true}, - HandlerState, ParseState) -> - Transport:setopts(Socket, [{active, once}]), - proc_lib:hibernate(?MODULE, loop, - [State#state{hibernate=false}, HandlerState, ParseState]); -before_loop(State=#state{socket=Socket, transport=Transport}, - HandlerState, ParseState) -> - Transport:setopts(Socket, [{active, once}]), - loop(State, HandlerState, ParseState). - --spec loop_timeout(#state{}) -> #state{}. -loop_timeout(State=#state{opts=Opts, timeout_ref=PrevRef}) -> - _ = case PrevRef of - undefined -> ignore; - PrevRef -> erlang:cancel_timer(PrevRef) - end, - case maps:get(idle_timeout, Opts, 60000) of - infinity -> - State#state{timeout_ref=undefined}; - Timeout -> - TRef = erlang:start_timer(Timeout, self(), ?MODULE), - State#state{timeout_ref=TRef} - end. - --spec loop(#state{}, any(), parse_state()) -> no_return(). -loop(State=#state{parent=Parent, socket=Socket, messages=Messages, - timeout_ref=TRef}, HandlerState, ParseState) -> - receive - %% Socket messages. (HTTP/1.1) - {OK, Socket, Data} when OK =:= element(1, Messages) -> - State2 = loop_timeout(State), - parse(State2, HandlerState, ParseState, Data); - {Closed, Socket} when Closed =:= element(2, Messages) -> - websocket_close(State, HandlerState, {error, sock_closed}); - {Error, Socket, Reason} when Error =:= element(3, Messages) -> - websocket_close(State, HandlerState, {error, {sock_error, Reason}}); - %% Body reading messages. (HTTP/2) - {request_body, _Ref, nofin, Data} -> - State2 = loop_timeout(State), - parse(State2, HandlerState, ParseState, Data); - %% @todo We need to handle this case as if it was an {error, closed} - %% but not before we finish processing frames. We probably should have - %% a check in before_loop to let us stop looping if a flag is set. - {request_body, _Ref, fin, _, Data} -> - State2 = loop_timeout(State), - parse(State2, HandlerState, ParseState, Data); - %% Timeouts. - {timeout, TRef, ?MODULE} -> - websocket_close(State, HandlerState, timeout); - {timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) -> - %% @todo This should call before_loop. - loop(State, HandlerState, ParseState); - %% System messages. - {'EXIT', Parent, Reason} -> - %% @todo We should exit gracefully. - exit(Reason); - {system, From, Request} -> - sys:handle_system_msg(Request, From, Parent, ?MODULE, [], - {State, HandlerState, ParseState}); - %% Calls from supervisor module. - {'$gen_call', From, Call} -> - cowboy_children:handle_supervisor_call(Call, From, [], ?MODULE), - %% @todo This should call before_loop. - loop(State, HandlerState, ParseState); - Message -> - handler_call(State, HandlerState, ParseState, - websocket_info, Message, fun before_loop/3) - end. - -%% Ignore all the input data when the conn is in 'closed' state. -parse(State, HandlerState, undefined, _Data) -> - loop(State, HandlerState, undefined); - -parse(State, HandlerState, PS=#ps_header{buffer=Buffer}, Data) -> - parse_header(State, HandlerState, PS#ps_header{ - buffer= <>}); -parse(State, HandlerState, PS=#ps_payload{buffer=Buffer}, Data) -> - parse_payload(State, HandlerState, PS#ps_payload{buffer= <<>>}, - <>). - -parse_header(State=#state{opts=Opts, frag_state=FragState, extensions=Extensions}, - HandlerState, ParseState=#ps_header{buffer=Data}) -> - MaxFrameSize = maps:get(max_frame_size, Opts, infinity), - case cow_ws:parse_header(Data, Extensions, FragState) of - %% All frames sent from the client to the server are masked. - {_, _, _, _, undefined, _} -> - websocket_close(State, HandlerState, {error, badframe}); - {_, _, _, Len, _, _} when Len > MaxFrameSize -> - websocket_close(State, HandlerState, {error, badsize}); - {Type, FragState2, Rsv, Len, MaskKey, Rest} -> - parse_payload(State#state{frag_state=FragState2}, HandlerState, - #ps_payload{type=Type, len=Len, mask_key=MaskKey, rsv=Rsv}, Rest); - more -> - before_loop(State, HandlerState, ParseState); - error -> - websocket_close(State, HandlerState, {error, badframe}) - end. - -parse_payload(State=#state{frag_state=FragState, utf8_state=Incomplete, extensions=Extensions}, - HandlerState, ParseState=#ps_payload{ - type=Type, len=Len, mask_key=MaskKey, rsv=Rsv, - unmasked=Unmasked, unmasked_len=UnmaskedLen}, Data) -> - case cow_ws:parse_payload(Data, MaskKey, Incomplete, UnmaskedLen, - Type, Len, FragState, Extensions, Rsv) of - {ok, CloseCode, Payload, Utf8State, Rest} -> - dispatch_frame(State#state{utf8_state=Utf8State}, HandlerState, - ParseState#ps_payload{unmasked= <>, - close_code=CloseCode}, Rest); - {ok, Payload, Utf8State, Rest} -> - dispatch_frame(State#state{utf8_state=Utf8State}, HandlerState, - ParseState#ps_payload{unmasked= <>}, - Rest); - {more, CloseCode, Payload, Utf8State} -> - before_loop(State#state{utf8_state=Utf8State}, HandlerState, - ParseState#ps_payload{len=Len - byte_size(Data), close_code=CloseCode, - unmasked= <>, - unmasked_len=UnmaskedLen + byte_size(Data)}); - {more, Payload, Utf8State} -> - before_loop(State#state{utf8_state=Utf8State}, HandlerState, - ParseState#ps_payload{len=Len - byte_size(Data), - unmasked= <>, - unmasked_len=UnmaskedLen + byte_size(Data)}); - Error = {error, _Reason} -> - websocket_close(State, HandlerState, Error) - end. - -dispatch_frame(State=#state{opts=Opts, frag_state=FragState, frag_buffer=SoFar}, HandlerState, - #ps_payload{type=Type0, unmasked=Payload0, close_code=CloseCode0}, RemainingData) -> - MaxFrameSize = maps:get(max_frame_size, Opts, infinity), - case cow_ws:make_frame(Type0, Payload0, CloseCode0, FragState) of - %% @todo Allow receiving fragments. - {fragment, _, _, Payload} when byte_size(Payload) + byte_size(SoFar) > MaxFrameSize -> - websocket_close(State, HandlerState, {error, badsize}); - {fragment, nofin, _, Payload} -> - parse_header(State#state{frag_buffer= << SoFar/binary, Payload/binary >>}, - HandlerState, #ps_header{buffer=RemainingData}); - {fragment, fin, Type, Payload} -> - handler_call(State#state{frag_state=undefined, frag_buffer= <<>>}, HandlerState, - #ps_header{buffer=RemainingData}, - websocket_handle, {Type, << SoFar/binary, Payload/binary >>}, - fun parse_header/3); - close -> - websocket_close(State, HandlerState, remote); - {close, CloseCode, Payload} -> - websocket_close(State, HandlerState, {remote, CloseCode, Payload}); - Frame = ping -> - transport_send(State, nofin, frame(pong, State)), - handler_call(State, HandlerState, - #ps_header{buffer=RemainingData}, - websocket_handle, Frame, fun parse_header/3); - Frame = {ping, Payload} -> - transport_send(State, nofin, frame({pong, Payload}, State)), - handler_call(State, HandlerState, - #ps_header{buffer=RemainingData}, - websocket_handle, Frame, fun parse_header/3); - Frame -> - handler_call(State, HandlerState, - #ps_header{buffer=RemainingData}, - websocket_handle, Frame, fun parse_header/3) - end. - -handler_call(State=#state{handler=Handler}, HandlerState, - ParseState, Callback, Message, NextState) -> - try case Callback of - websocket_init -> Handler:websocket_init(HandlerState); - _ -> Handler:Callback(Message, HandlerState) - end of - {Commands, HandlerState2} when is_list(Commands) -> - handler_call_result(State, - HandlerState2, ParseState, NextState, Commands); - {Commands, HandlerState2, hibernate} when is_list(Commands) -> - handler_call_result(State#state{hibernate=true}, - HandlerState2, ParseState, NextState, Commands); - %% The following call results are deprecated. - {ok, HandlerState2} -> - NextState(State, HandlerState2, ParseState); - {ok, HandlerState2, hibernate} -> - NextState(State#state{hibernate=true}, HandlerState2, ParseState); - {reply, Payload, HandlerState2} -> - case websocket_send(Payload, State) of - ok -> - NextState(State, HandlerState2, ParseState); - close -> - websocket_close(State, HandlerState2, {error, close}); - {close, Reason} -> - websocket_close(State, HandlerState2, Reason); - Error = {error, _} -> - websocket_close(State, HandlerState2, Error) - end; - {reply, Payload, HandlerState2, hibernate} -> - case websocket_send(Payload, State) of - ok -> - NextState(State#state{hibernate=true}, - HandlerState2, ParseState); - close -> - websocket_close(State, HandlerState2, {error, close}); - {close, Reason} -> - websocket_close(State, HandlerState2, Reason); - Error = {error, _} -> - websocket_close(State, HandlerState2, Error) - end; - {stop, HandlerState2} -> - websocket_close(State, HandlerState2, stop) - catch Class:Reason -> - StackTrace = erlang:get_stacktrace(), - websocket_send_close(State, {crash, Class, Reason}), - handler_terminate(State, HandlerState, {crash, Class, Reason}), - erlang:raise(Class, Reason, StackTrace) - end. - --spec handler_call_result(#state{}, any(), parse_state(), fun(), commands()) -> no_return(). -handler_call_result(State0, HandlerState, ParseState, NextState, Commands) -> - case commands(Commands, State0, []) of - {ok, State} -> - NextState(State, HandlerState, ParseState); - {{close, Reason}, State} -> - websocket_close(State, HandlerState, Reason); - {stop, State} -> - websocket_close(State, HandlerState, stop); - {Error = {error, _}, State} -> - websocket_close(State, HandlerState, Error) - end. - -commands([], State, []) -> - {ok, State}; -commands([], State, Data) -> - Result = transport_send(State, nofin, lists:reverse(Data)), - {Result, State}; -commands([{active, Active}|Tail], State, Data) when is_boolean(Active) -> - commands(Tail, State#state{active=Active}, Data); -commands([{deflate, Deflate}|Tail], State, Data) when is_boolean(Deflate) -> - commands(Tail, State#state{deflate=Deflate}, Data); -commands([{set_options, SetOpts}|Tail], State0=#state{opts=Opts}, Data) -> - State = case SetOpts of - #{idle_timeout := IdleTimeout} -> - loop_timeout(State0#state{opts=Opts#{idle_timeout => IdleTimeout}}); - _ -> - State0 - end, - commands(Tail, State, Data); -commands([{shutdown, Reason}|_Tail], State, Data) -> - _ = transport_send(State, fin, lists:reverse(Data)), - {stop, State#state{shutdown_reason=Reason}}; -commands([Frame|Tail], State, Data0) -> - Data = [frame(Frame, State)|Data0], - case is_close_frame(Frame) of - true -> - _ = transport_send(State, fin, lists:reverse(Data)), - {Frame, State}; - false -> - commands(Tail, State, Data) - end. - -transport_send(#state{socket=Stream={Pid, _}, transport=undefined}, IsFin, Data) -> - Pid ! {Stream, {data, IsFin, Data}}, - ok; -transport_send(#state{socket=Socket, transport=Transport}, _, Data) -> - Transport:send(Socket, Data). - --spec websocket_send(cow_ws:frame(), #state{}) -> ok | close | {error, atom()}. -websocket_send(Frames, State) when is_list(Frames) -> - websocket_send_many(Frames, State, []); -websocket_send(Frame, State) -> - Data = frame(Frame, State), - case is_close_frame(Frame) of - true -> - _ = transport_send(State, fin, Data), - Frame; - false -> - transport_send(State, nofin, Data) - end. - -websocket_send_many([], State, Acc) -> - transport_send(State, nofin, lists:reverse(Acc)); -websocket_send_many([Frame|Tail], State, Acc0) -> - Acc = [frame(Frame, State)|Acc0], - case is_close_frame(Frame) of - true -> - _ = transport_send(State, fin, lists:reverse(Acc)), - Frame; - false -> - websocket_send_many(Tail, State, Acc) - end. - -is_close_frame(close) -> true; -is_close_frame({close, _}) -> true; -is_close_frame({close, _, _}) -> true; -is_close_frame(_) -> false. - --spec websocket_close(#state{}, any(), terminate_reason()) -> no_return(). - -websocket_close(State, HandlerState, stop) -> - websocket_send_close(State, stop), - terminate(State, HandlerState, stop); - -websocket_close(State = #state{closed=true}, HandlerState, _Reason) -> - loop(State, HandlerState, undefined); - -websocket_close(State = #state{socket=Socket, - transport=Transport, - handler=Handler}, HandlerState, Reason) -> - ok = websocket_send_close(State, Reason), - case erlang:function_exported(Handler, websocket_close, 2) - andalso Handler:websocket_close(Reason, HandlerState) of - false -> - terminate(State, HandlerState, Reason); - {ok, HandlerState1} -> - catch Transport:close(Socket), - loop(State#state{closed = true}, HandlerState1, undefined); - {_Cmds, HandlerState1} -> - terminate(State, HandlerState1, Reason) - end. - -websocket_send_close(_State, {error, sock_closed}) -> - ok; -websocket_send_close(_State, {error, {sock_error, _Reason}}) -> - ok; -websocket_send_close(State, Reason) -> - _ = case Reason of - Normal when is_atom(Normal) -> - transport_send(State, fin, frame({close, 1000, <<>>}, State)); - {error, close} -> - transport_send(State, fin, frame({close, 1000, <<>>}, State)); - {error, badframe} -> - transport_send(State, fin, frame({close, 1002, <<>>}, State)); - {error, badencoding} -> - transport_send(State, fin, frame({close, 1007, <<>>}, State)); - {error, badsize} -> - transport_send(State, fin, frame({close, 1009, <<>>}, State)); - {crash, _, _} -> - transport_send(State, fin, frame({close, 1011, <<>>}, State)); - remote -> - transport_send(State, fin, frame(close, State)); - {remote, Code, _} -> - transport_send(State, fin, frame({close, Code, <<>>}, State)) - end, - ok. - -%% Don't compress frames while deflate is disabled. -frame({close, _Reason}, State) -> - cow_ws:frame(close, State); -frame(Frame, #state{deflate=false, extensions=Extensions}) -> - cow_ws:frame(Frame, Extensions#{deflate => false}); -frame(Frame, #state{extensions=Extensions}) -> - cow_ws:frame(Frame, Extensions). - --spec terminate(#state{}, any(), terminate_reason()) -> no_return(). -terminate(State=#state{shutdown_reason=Shutdown}, HandlerState, Reason) -> - case Shutdown of - undefined -> - handler_terminate(State, HandlerState, Reason); - normal -> - handler_terminate(State, HandlerState, normal); - _ -> - handler_terminate(State, HandlerState, {shutdown, Shutdown}) - end, - case Shutdown of - normal -> exit(normal); - _ -> exit({shutdown, Shutdown}) - end. - -handler_terminate(#state{handler=Handler, req=Req}, HandlerState, Reason) -> - cowboy_handler:terminate(Reason, Req, HandlerState, Handler). - -%% System callbacks. - --spec system_continue(_, _, {#state{}, any(), parse_state()}) -> no_return(). -system_continue(_, _, {State, HandlerState, ParseState}) -> - loop(State, HandlerState, ParseState). - --spec system_terminate(any(), _, _, {#state{}, any(), parse_state()}) -> no_return(). -system_terminate(Reason, _, _, {State, HandlerState, _}) -> - %% @todo We should exit gracefully, if possible. - terminate(State, HandlerState, Reason). - --spec system_code_change(Misc, _, _, _) - -> {ok, Misc} when Misc::{#state{}, any(), parse_state()}. -system_code_change(Misc, _, _, _) -> - {ok, Misc}. diff --git a/_build/emqx/lib/cowlib b/_build/emqx/lib/cowlib deleted file mode 160000 index c6553f8308..0000000000 --- a/_build/emqx/lib/cowlib +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c6553f8308a2ca5dcd69d845f0a7d098c40c3363 diff --git a/_build/emqx/lib/cuttlefish/.gitignore b/_build/emqx/lib/cuttlefish/.gitignore deleted file mode 100644 index d3d3f3669d..0000000000 --- a/_build/emqx/lib/cuttlefish/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -.DS_Store -generated.config -generated.conf -ebin/* -.eunit -src/conf_parse.erl -deps -cuttlefish -*.sublime-project -*.sublime-workspace -log -.local_dialyzer_plt -src/cuttlefish_duration_parse.erl -erln8.config -test/fixtures/escript_prune_test/generated.config/ -_build/ -.rebar3/ -erl_crash.dump -rebar3.crashdump -reabr.lock diff --git a/_build/emqx/lib/cuttlefish/Makefile b/_build/emqx/lib/cuttlefish/Makefile deleted file mode 100644 index e9a4b6117c..0000000000 --- a/_build/emqx/lib/cuttlefish/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -DIALYZER_APPS = kernel stdlib sasl erts ssl tools os_mon runtime_tools crypto inets \ - public_key mnesia syntax_tools compiler -COMBO_PLT = $(HOME)/.cuttlefish_combo_dialyzer_plt - -REBAR := $(CURDIR)/rebar3 - -REBAR_URL := https://s3.amazonaws.com/rebar3/rebar3 - -.PHONY: all -all: $(REBAR) compile - echo $(REBAR) - -.PHONY: deps -deps: - $(REBAR) get-deps - -.PHONY: distclean -docsclean: - @rm -rf doc/*.png doc/*.html doc/*.css doc/edoc-info - -.PHONY: compile -compile: deps - $(REBAR) compile - -## Environment variable CUTTLEFISH_ESCRIPT is shared with rebar.config -.PHONY: escript -escript: export CUTTLEFISH_ESCRIPT = true -escript: $(REBAR) - $(REBAR) as escript escriptize - -.PHONY: clean -clean: distclean - -.PHONY: distclean -distclean: - @rm -rf _build cuttlefish erl_crash.dump rebar3.crashdump rebar.lock - -.PHONY: eunit -eunit: compile - $(REBAR) eunit verbose=true - -.PHONY: dialyzer -dialyzer: - $(REBAR) dialyzer - -.PHONY: $(REBAR) -$(REBAR): -ifneq ($(wildcard rebar3),rebar3) - @curl -Lo rebar3 $(REBAR_URL) || wget $(REBAR_URL) -endif - @chmod a+x rebar3 - -ifeq ($(OS),Windows_NT) - @$(CURDIR)/rebar3 update -endif \ No newline at end of file diff --git a/_build/emqx/lib/cuttlefish/README.md b/_build/emqx/lib/cuttlefish/README.md deleted file mode 100644 index 91e7419e97..0000000000 --- a/_build/emqx/lib/cuttlefish/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Cuttlefish - -Cuttlefish is a library for Erlang applications that wish to walk the -fine line between Erlang `app.config`s and a sysctl-like syntax. -The name is a pun on the pronunciation of 'sysctl' and jokes are -better explained. - -## Riak Disclaimer - -While this readme and test suite is Riak-heavy, the fact is that this -library can be used with any Erlang application that wants a more -universally accessible configuration syntax. Still, I built this for -Riak, and it's nice to have a concrete example to work with. - -## The Vision - -Currently, Riak's `app.config` is **the** definitive place for -configuring Riak. It's not odd for Erlang applications to be -configured this way, but it is a struggle for non-Erlang programmers -and automated deployment tools to manipulate these files. On the other -hand, the `app.config` is a useful construct for Erlang programmers, -and it is pretty coupled to OTP applications. - -Cuttlefish's goal is to put a layer of abstraction on top of the -`app.config` that is easier to work with outside of the Erlang world. -It will allow Erlang programmers to write a schema for their -application's configuration file, which is independent of the -applications included in the project. The schema is one of the more -important parts of Cuttlefish, so we'll go into more detail on it -below, but it is written in Erlang and defines how the non-Erlang -configuration file works. - -From this schema, you can generate a default `.conf` file for your -application. This will be the file that is packaged with your -application as the default configuration. - -The schema is also used to generate an `app.config` that will be used -to start your application. Using the schema alone will generate all -the proper defaults. Your users can make changes to the `.conf` file -and those changes will overwrite the schema's defaults. - -You an also have an `advanced.config` which looks like the old -`app.config` for anything that no schema mapping is created for. - -What does this look like for an application like Riak? - -Well, the authors of Riak maintain a schema for Riak's config. It -defines all sorts of things we'll get into later. When we build Riak, -Cuttlefish generates a `riak.conf` file that contains the default -shipping configuration of Riak. When a script to start Riak is run, a -Cuttlefish escript is spun up, reads the `riak.conf` file and combines -that with the Schema to generate an `app.config`. The script then -exits, and a new Erlang VM (destined to run Riak) is started with that -generated `app.config`. Down the line somewhere, you may be -troubleshooting some part of Riak, and the support organization at -Basho may need you to manipulate a configuration setting that is not -exposed by the schema because it is so infrequently used. In that -case, we can set that setting directly in an `advanced.config` which -sits in the same directory as `riak.conf`. - -I hope that gives you a good idea about how this works at a high -level. - -## What's it look like to Erlang Developers? - -You can learn more about the technical implementation of schemas at: -https://hub.fastgit.org/basho/cuttlefish/wiki/Cuttlefish-for-Erlang-Developers - -## What's it look like to users? - -Riak uses the semantic of `$conf_dir/app.config` for configuration. -We're going to replace that with a file called `riak.conf`, with a -syntax that looks like this: - -```ini -ring_size = 32 -anti_entropy = debug -log.error.file = /var/log/error.log -log.console.file = /var/log/console.log -log.syslog = on -``` - -More information for users here: -https://hub.fastgit.org/basho/cuttlefish/wiki/Cuttlefish-for-Application-Users - -## What's it look like to application packagers? - -* [node_package](https://hub.fastgit.org/basho/cuttlefish/wiki/Cuttlefish-for-node_package-users) -* [non node_package](https://hub.fastgit.org/basho/cuttlefish/wiki/Cuttlefish-for-non-node_package-users) - - -## Current Status - -Cuttlefish is ready for production deployments. diff --git a/_build/emqx/lib/cuttlefish/include/cuttlefish.hrl b/_build/emqx/lib/cuttlefish/include/cuttlefish.hrl deleted file mode 100644 index 20c2ca3b54..0000000000 --- a/_build/emqx/lib/cuttlefish/include/cuttlefish.hrl +++ /dev/null @@ -1,5 +0,0 @@ --ifdef(TEST). --define(logger, cuttlefish_test_logger). --else. --define(logger, logger). --endif. diff --git a/_build/emqx/lib/cuttlefish/rebar.config b/_build/emqx/lib/cuttlefish/rebar.config deleted file mode 100644 index 2c7e5240b7..0000000000 --- a/_build/emqx/lib/cuttlefish/rebar.config +++ /dev/null @@ -1,29 +0,0 @@ -{require_otp_vsn, "21"}. - -{erl_opts, [debug_info, warn_untyped_record, nowarn_export_all]}. - -{eunit_opts, [verbose]}. -{cover_enabled, true}. - -{escript_emu_args, "%%! -escript main cuttlefish_escript +A 0\n"}. -{escript_incl_apps, [getopt]}. - -{deps, [{getopt, {git, "https://hub.fastgit.org/emqx/getopt.git", {tag, "v1.0.2"}}}]}. - -{profiles, - [{test, [{deps, [bbmustache]}]}, - {escript, [{post_hooks, [ {"(linux|darwin|solaris|freebsd|netbsd|openbsd)", escriptize, "cp _build/escript/bin/cuttlefish ./"} - , {"win32", escriptize, "copy _build\\escript\\bin\\cuttlefish ."}]}]} - ]}. - -{provider_hooks, [ - {pre, [{compile, {neotoma, compile}}]} -]}. - -%% escriptize in another profile (not default) so escript can be built -%% even when cuttlefish is used as a dependency in a wrapper project -%% {post_hooks, [ {"(linux|darwin|solaris|win32)", app_compile, "make escript"} -%% , {"(freebsd|netbsd|openbsd)", app_compile, "gmake escript"}]}. - -{plugins, [rebar3_neotoma_plugin]}. - diff --git a/_build/emqx/lib/cuttlefish/rebar.config.script b/_build/emqx/lib/cuttlefish/rebar.config.script deleted file mode 100644 index 8c31d57a47..0000000000 --- a/_build/emqx/lib/cuttlefish/rebar.config.script +++ /dev/null @@ -1,10 +0,0 @@ -%%-*- mode: erlang -*- -case os:getenv("CUTTLEFISH_ESCRIPT") =:= "true" of - true -> - %% building escript, delete the post hook - lists:keydelete(post_hooks, 1, CONFIG); - false -> - PostHooks = {post_hooks, [ {"(linux|darwin|solaris|win32)", app_compile, "make escript"} - , {"(freebsd|netbsd|openbsd)", app_compile, "gmake escript"}]}, - [PostHooks | CONFIG] -end. diff --git a/_build/emqx/lib/cuttlefish/rebar3 b/_build/emqx/lib/cuttlefish/rebar3 deleted file mode 100644 index 640804d1be..0000000000 Binary files a/_build/emqx/lib/cuttlefish/rebar3 and /dev/null differ diff --git a/_build/emqx/lib/cuttlefish/rebar3.cmd b/_build/emqx/lib/cuttlefish/rebar3.cmd deleted file mode 100644 index 6c7a1caf2d..0000000000 --- a/_build/emqx/lib/cuttlefish/rebar3.cmd +++ /dev/null @@ -1,4 +0,0 @@ -@echo off -setlocal -set rebarscript=%~f0 -escript.exe "%rebarscript:.cmd=%" %* diff --git a/_build/emqx/lib/cuttlefish/src/conf_parse.peg b/_build/emqx/lib/cuttlefish/src/conf_parse.peg deleted file mode 100644 index 0ca03d074e..0000000000 --- a/_build/emqx/lib/cuttlefish/src/conf_parse.peg +++ /dev/null @@ -1,176 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% conf_parse: for all your .conf parsing needs. -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - -%% A configuration file may have zero-or-more lines. -config <- line* %{ - [ L || L <- Node, is_setting(L) ] -%}; - -%% Lines are actual settings, comments, or horizontal whitespace, -%% terminated by an end-of-line or end-of-file. -line <- ((setting / comment / include / ws+ / placeholder) (crlf / eof)) / crlf %{ - case Node of - [ Line, _EOL ] -> Line; - Line -> Line - end -%}; - -%% A setting is a key and a value, joined by =, with surrounding -%% whitespace ignored. -setting <- ws* key ws* "=" ws* value ws* %{ - [ _, Key, _, _Eq, _, Value, _] = Node, - {Key, Value} -%}; - -%% A key is a series of dot-separated identifiers. -key <- head:word tail:("." word)* %{ - [{head, H}, {tail, T}] = Node, - [unicode:characters_to_list(H)| [ unicode:characters_to_list(W) || [_, W] <- T]] -%}; - -%% A value is any character, with trailing whitespace stripped. -value <- (!(ws* crlf) .)+ %{ - case unicode:characters_to_binary(Node, utf8, latin1) of - {_Status, _Begining, _Rest} -> - {error, {conf_to_latin1, line(Idx)}}; - Bin -> - binary_to_list(Bin) - end -%}; - -%% A comment is any line that begins with a # sign, leading whitespace -%% allowed. -comment <- ws* "#" (!crlf .)* `comment`; - -include <- ws* "include" (ws)+ (value) ws* %{ - [_, _, _, Value, _] = Node, - {include_file, Value} -%}; - -%% A placeholder is any line that is surrounded with {{}} -placeholder <- ws* "{{" (!crlf !"}}" .)+ "}}" `placeholder`; - -%% A word is one or more of letters, numbers and dashes or -%% underscores. -word <- ("\\." / [@/:] / [A-Za-z0-9_-])+ %{ - unescape_dots(unicode:characters_to_list(Node)) -%}; - -%% An end-of-line is signified by a line-feed with an optional -%% preceding carriage-return. -crlf <- "\r"? "\n" `ws`; - -%% The end-of-file is where no character matches. -eof <- !. `ws`; - -%% Whitespace is either spaces or tabs. -ws <- [ \t] `ws`; - -% Erlang code -%{ - -%% ------------------------------------------------------------------- -%% -%% conf_parse: for all your .conf parsing needs. -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - -%% This module implements the parser for a sysctl-style -%% configuration format. Example: -%% -%% ``` -%% riak.local.node = riak@127.0.0.1 -%% riak.local.http = 127.0.0.1:8098 -%% riak.local.pb = 127.0.0.1:8087 -%% riak.local.storage.backend = bitcask''' -%% -%% This would parse into the following flat proplist: -%% -%% ``` -%% [{<<"riak.local.node">>,<<"riak@127.0.0.1">>}, -%% {<<"riak.local.http">>,<<"127.0.0.1:8098">>}, -%% {<<"riak.local.pb">>,<<"127.0.0.1:8087">>}, -%% {<<"riak.local.storage.backend">>,<<"bitcask">>}]''' -%% -%% Other modules in this application interpret and validate the -%% result of a successful parse. -%% @end --define(line, true). --define(FMT(F,A), lists:flatten(io_lib:format(F,A))). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - -%% @doc Only let through lines that are not comments, whitespace or placeholder. -is_setting(ws) -> false; -is_setting(comment) -> false; -is_setting(placeholder) -> false; -is_setting(_) -> true. - -%% @doc Removes escaped dots from keys -unescape_dots([$\\,$.|Rest]) -> - [$.|unescape_dots(Rest)]; -unescape_dots([]) -> []; -unescape_dots([C|Rest]) -> - [C|unescape_dots(Rest)]. - --ifdef(TEST). -file_test() -> - Path = filename:join([code:lib_dir(cuttlefish), "test", "riak.conf"]), - Conf = conf_parse:file(Path), - ?assertEqual([ - {["ring_size"],"32"}, - {["anti_entropy"],"debug"}, - {["log","error","file"],"/var/log/error.log"}, - {["log","console","file"],"/var/log/console.log"}, - {["log","syslog"],"on"}, - {["listener","http","internal"],"127.0.0.1:8098"}, - {["listener","http","external"],"10.0.0.1:80"} - ], Conf), - ok. - -utf8_test() -> - Conf = conf_parse:parse("setting = thing" ++ [338] ++ "\n"), - ?assertEqual([{["setting"], - {error, {conf_to_latin1, 1}} - }], Conf), - ok. --endif. -%} diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish.app.src b/_build/emqx/lib/cuttlefish/src/cuttlefish.app.src deleted file mode 100644 index 7cede4a72e..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish.app.src +++ /dev/null @@ -1,11 +0,0 @@ -{application, cuttlefish, - [ - {description, "cuttlefish configuration abstraction"}, - {vsn, git}, - {registered, []}, - {applications, [ - kernel, - stdlib - ]}, - {env, []} - ]}. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish.erl deleted file mode 100644 index a12d684960..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish.erl +++ /dev/null @@ -1,151 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% External functions for schema writers and cuttlefish invokers -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --module(cuttlefish). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([ - conf_get/2, - conf_get/3, - unset/0, - invalid/1, - otp/2, - otp/3, - warn/1 -]). - --include("cuttlefish.hrl"). - -% @doc If DesiredMinimum =< the OTP you're running, then return -% IfGreaterOrEqual, otherwise IfLessThan. --spec otp(string(), any(), any()) -> any(). -otp(DesiredMinimumOTPVersion, IfGreaterOrEqual, IfLessThan) -> - ActualOTPVersion = erlang:system_info(otp_release), - case otp(DesiredMinimumOTPVersion, ActualOTPVersion) of - true -> IfGreaterOrEqual; - _ -> IfLessThan - end. - -% @doc is ActualOTPVersion >= DesiredMinimumOTPVersion? --spec otp(string(), string()) -> boolean(). -otp([], []) -> - %% They're the same length AND all previous chars were matches - true; -otp([$R|TMin], Ver) -> - otp(TMin, Ver); -otp(Min, [$R|TVer]) -> - otp(Min, TVer); -otp([H|TMin], [H|TVer]) -> - %% The head chars are equal, test the tails - otp(TMin, TVer); -otp([HMin|_], [HVer|_]) -> - %% The heads are different, check which is greater - HVer >= HMin; -otp([], _Ver) -> - %% The actual OTP release is a longer string, but - %% everything matched up until this point - %% e.g. R16B02, R16B02-basho4 - true; -otp(_Min, []) -> - %% Our Min is a longer string - %% e.g. R16B02-basho4, R16B02 - false. - -% @doc conf_get/2 is a convenience wrapper for proplists:get_value/2 -% for schema writers. Keys to a Conf proplist are variable()s which -% are a list of strings. This function will look for those, but if -% you pass it a string() instead, it will be nice and split that -% string on "." since that's how cuttlefish do. Also, it will -% throw(not_found) if the key is not found in the list which is -% different that proplists:get_value/2's default behavior of returning -% 'undefined'. This makes it easy for cuttlefish translations to abort -% and on error, and not assume a value. If that's what you want, -% please use conf_get/3. formerly cuttlefish_util:conf_get_value/2 --spec conf_get( - string() | cuttlefish_variable:variable(), - cuttlefish_conf:conf()) -> any(). -conf_get([H|_T]=Variable, ConfigProplist) when is_list(H) -> - case proplists:is_defined(Variable, ConfigProplist) of - true -> - proplists:get_value(Variable, ConfigProplist); - false -> - throw({not_found, Variable}) - end; -conf_get(Variable, ConfigProplist) -> - conf_get( - cuttlefish_variable:tokenize(Variable), - ConfigProplist). - -% @doc conf_get/3 works just like proplists:get_value/3. It expects a -% variable() as the Key, but is nice enough to take a string() and -% split it on "." formerly cuttlefish_util:conf_get_value/3 --spec conf_get( - string() | cuttlefish_variable:variable(), - cuttlefish_conf:conf(), any()) -> any(). -conf_get([H|_T]=Variable, ConfigProplist, Default) when is_list(H) -> - proplists:get_value(Variable, ConfigProplist, Default); -conf_get(Variable, ConfigProplist, Default) -> - conf_get(cuttlefish_variable:tokenize(Variable), ConfigProplist, Default). - -%% @doc When called inside a translation, tells cuttlefish to omit the -%% Erlang setting from the generated configuration. --spec unset() -> no_return(). -unset() -> - throw(unset). - -%% @doc When called inside a translation, informs the user that input -%% configuration is invalid, using the supplied reason string. --spec invalid(string()) -> no_return(). -invalid(Reason) -> - throw({invalid, Reason}). - -%% @doc When called inside a translation, results in a warning message -%% being logged. --spec warn(iodata()) -> ok. -warn(Str) -> - ?logger:warning(Str, []). - --ifdef(TEST). - -otp_test() -> - ?assert(otp("R15B02", "R15B02-basho3")), - ?assert(not(otp("R15B02-basho3", "R15B02"))), - ?assert(otp("R16B02-basho3", "R16B03")), - ?assert(otp("R15B01", "R15B02")), - ?assert(otp("R15B01", "R15B02-basho3")), - ?assert(not(otp("R16B01", "R15B02"))), - ?assert(otp("R16", "R16B03")), - ?assert(otp("R16", "R16A")), - ?assert(not(otp("R16B01", "R16A"))), - ?assert(otp("R16A", "R16A")), - ?assert(otp("R16", "17")), - ?assert(otp("R16B03-1", "17")), - ?assert(not(otp("17", "R16"))), - ?assert(otp("R16A", "17")), - ?assert(not(otp("18", "17"))), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_advanced.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_advanced.erl deleted file mode 100644 index d089daa576..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_advanced.erl +++ /dev/null @@ -1,76 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_advanced: handles merging of advanced configs -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --module(cuttlefish_advanced). - --export([overlay/2]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - -%% @doc this function overlays the values in proplist 'AdvancedConfig' -%% on top of 'GeneratedConfig' -overlay(GeneratedConfig, AdvancedConfig) -> - lists:foldl( - fun({ApplicationName, ApplicationConfig}, OuterAcc) -> - GeneratedApplicationConfig = proplists:get_value(ApplicationName, GeneratedConfig, []), - Updated = lists:foldl( - fun({ConfigElementName, ConfigElement}, Acc) -> - cuttlefish_util:replace_proplist_value(ConfigElementName, ConfigElement, Acc) - end, - GeneratedApplicationConfig, - ApplicationConfig), - cuttlefish_util:replace_proplist_value(ApplicationName, Updated, OuterAcc) - end, - GeneratedConfig, - AdvancedConfig). - - --ifdef(TEST). - -overlay_test() -> - GeneratedConfig = [ - {app1, [{'setting1.1', "value1.1"}]}, - {app2, [{'setting2.1', "value2.1"}]}, - {app3, [{'setting3.1', [{"blah", "blah"}, {"blarg", "blarg"}]}]} - ], - - AdvancedConfig = [ - {app3, [{'setting3.1', i_dont_care}]}, - {app4, [{'some_unschemad_thing', 'like_a_penguin'}]} - ], - - Expected = [ - {app1, [{'setting1.1', "value1.1"}]}, - {app2, [{'setting2.1', "value2.1"}]}, - {app3, [{'setting3.1', i_dont_care}]}, - {app4, [{'some_unschemad_thing', 'like_a_penguin'}]} - ], - NewConfig = overlay(GeneratedConfig, AdvancedConfig), - - ?assertEqual(Expected, NewConfig), - - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_bytesize.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_bytesize.erl deleted file mode 100644 index 5262a526a4..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_bytesize.erl +++ /dev/null @@ -1,98 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_bytesize: complexity for parsing bytesizes -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --module(cuttlefish_bytesize). - --define(KILOBYTE, 1024). --define(MEGABYTE, 1048576). --define(GIGABYTE, 1073741824). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([parse/1, to_string/1]). - -%% @doc turns an integer of bytes into a string. -%% Will use the smallest unit to not lose precision. -%% e.g. 1024 -> 1kb, but 1025 = 1025. --spec to_string(integer()) -> string(). -to_string(Bytez) -> - case { Bytez rem ?GIGABYTE, Bytez rem ?MEGABYTE, Bytez rem ?KILOBYTE} of - {0, _, _} -> - integer_to_list(Bytez div ?GIGABYTE) ++ "GB"; - {_, 0, _} -> - integer_to_list(Bytez div ?MEGABYTE) ++ "MB"; - {_, _, 0} -> - integer_to_list(Bytez div ?KILOBYTE) ++ "KB"; - _ -> - integer_to_list(Bytez) - end. - -%% @doc the reverse of to_string/1. turns "1kb" or "1KB" into 1024. --spec parse(string()) -> integer()|cuttlefish_error:error(). -parse(String) -> - case lists:reverse(String) of - [$B,$K|BSize] -> bmult(cuttlefish_util:numerify(lists:reverse(BSize)), ?KILOBYTE); - [$b,$k|BSize] -> bmult(cuttlefish_util:numerify(lists:reverse(BSize)), ?KILOBYTE); - [$B,$M|BSize] -> bmult(cuttlefish_util:numerify(lists:reverse(BSize)), ?MEGABYTE); - [$b,$m|BSize] -> bmult(cuttlefish_util:numerify(lists:reverse(BSize)), ?MEGABYTE); - [$B,$G|BSize] -> bmult(cuttlefish_util:numerify(lists:reverse(BSize)), ?GIGABYTE); - [$b,$g|BSize] -> bmult(cuttlefish_util:numerify(lists:reverse(BSize)),?GIGABYTE); - BSize -> cuttlefish_util:numerify(lists:reverse(BSize)) - end. - --spec bmult(number()|cuttlefish_error:error(), integer()) -> - number()|cuttlefish_error:error(). -bmult({error, _ErrorTerm}=Error, _Mult) -> - Error; -bmult(Quantity, Multiplier) -> - Quantity * Multiplier. - --ifdef(TEST). -to_string_test() -> - ?assertEqual("1KB", to_string(1024)), - ?assertEqual("2KB", to_string(2048)), - - ?assertEqual("10MB", to_string(10485760)), - - ?assertEqual("1GB", to_string(1073741824)), - - ?assertEqual("20", to_string(20)), - ok. - -parse_test() -> - ?assertEqual(1024, parse("1kb")), - ?assertEqual(2048, parse("2KB")), - - ?assertEqual(10485760, parse("10mb")), - ?assertEqual(10485760, parse("10MB")), - - ?assertEqual(1073741824, parse("1GB")), - ?assertEqual(1073741824, parse("1gb")), - - ?assertEqual(20, parse("20")), - ?assertEqual({error, {number_parse, "10MB10"}}, parse("10MB10kb")), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_conf.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_conf.erl deleted file mode 100644 index bda58dd08b..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_conf.erl +++ /dev/null @@ -1,365 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_conf: handles the reading and generation of .conf files -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_conf). - --export([ - generate/1, - generate_file/2, - file/1, - files/1, - is_variable_defined/2, - pretty_datatype/1]). - --include("cuttlefish.hrl"). - --type conf_pair() :: {cuttlefish_variable:variable(), any()}. --type conf() :: [conf_pair()]. --export_type([conf_pair/0, conf/0]). - --define(FMT(F, Args), lists:flatten(io_lib:format(F, Args))). - -is_variable_defined(VariableDef, Conf) -> - lists:any(fun({X, _}) -> cuttlefish_variable:is_fuzzy_match(X, VariableDef) end, Conf). - --spec files([file:name()]) -> conf() | cuttlefish_error:errorlist(). -files(ListOfConfFiles) -> - {ValidConf, Errors} = lists:foldl( - fun(ConfFile, {ConfAcc, ErrorAcc}) -> - case cuttlefish_conf:file(ConfFile) of - {errorlist, ErrorList} -> - {ConfAcc, ErrorList ++ ErrorAcc}; - Conf -> - {lists:foldl( - fun({include_file,V}, MiniAcc)-> - [{include_file,V}|MiniAcc]; - ({K,V}, MiniAcc) -> - cuttlefish_util:replace_proplist_value(K, V, MiniAcc) - end, - ConfAcc, - Conf), ErrorAcc} - end - end, - {[], []}, - ListOfConfFiles), - case {ValidConf, Errors} of - {_, []} -> ValidConf; - _ -> {errorlist, Errors} - end. - --spec file(file:name()) -> conf() | cuttlefish_error:errorlist(). -file(Filename) -> - case conf_parse:file(Filename) of - {error, Reason} -> - %% Reason is an atom via file:open - {errorlist, [{error, {file_open, {Filename, Reason}}}]}; - {_Conf, Remainder, {{line, L}, {column, C}}} when is_binary(Remainder) -> - {errorlist, [{error, {conf_syntax, {Filename, {L, C}}}}]}; - Conf -> - %% Conf is a proplist, check if any of the values are cuttlefish_errors - {_, Values} = lists:unzip(Conf), - case cuttlefish_error:filter(Values) of - {errorlist, []} -> - remove_duplicates(Conf); - {errorlist, ErrorList} -> - NewErrorList = [ {error, {in_file, {Filename, E}}} || {error, E} <- ErrorList ], - {errorlist, NewErrorList} - end - end. - --spec generate([cuttlefish_mapping:mapping()]) -> [string()]. -generate(Mappings) -> - lists:foldl( - fun(Mapping, ConfFile) -> - ConfFile ++ generate_element(Mapping) - end, [], Mappings). - --spec generate_file([cuttlefish_mapping:mapping()], string()) -> ok. -generate_file(Mappings, Filename) -> - ConfFileLines = generate(Mappings), - - {ok, S} = file:open(Filename, [write]), - _ = [ begin - io:format(S, "~s~n", [lists:flatten(Line)]) - end || Line <- ConfFileLines], - _ = file:close(S), - ok. - --spec generate_element(cuttlefish_mapping:mapping()) -> [string()]. -generate_element(MappingRecord) -> - Default = get_default(MappingRecord), - Key = cuttlefish_mapping:variable(MappingRecord), - Commented = cuttlefish_mapping:commented(MappingRecord), - Level = cuttlefish_mapping:level(MappingRecord), - Hidden = cuttlefish_mapping:hidden(MappingRecord), - IncDef = cuttlefish_mapping:include_default(MappingRecord), - [Datatype|_] = cuttlefish_mapping:datatype(MappingRecord), - %% level != basic OR hidden == true: leave out of generated .conf file - %% commeneted $val: insert into .conf file, but commented out with $val - %% include_default $val: substitute '$name' or whatever in the key for $val - %% e.g. {include_default, "internal"} - %% listener.http.$name -> listener.http.internal - - Field = cuttlefish_variable:format(cuttlefish_variable:replace_match(Key, IncDef)), - - case Level of - basic -> ok; - Level -> - ?logger:warning("{level, ~p} has been deprecated. Use 'hidden' or '{hidden, true}'", [Level]) - end, - - case generate_element(Hidden, Level, Default, Commented) of - no -> - []; - commented -> - Comments = generate_comments(MappingRecord), - Comments ++ [lists:flatten([ "## ", Field, " = ", cuttlefish_datatypes:to_string(Commented, Datatype) ]), ""]; - default -> - Comments = generate_comments(MappingRecord), - Comments ++ [lists:flatten([ Field, " = ", cuttlefish_datatypes:to_string(Default, Datatype) ]), ""] - end. - -get_default(MappingRecord) -> - %% Normally we use `default` to determine what value to use when generating - %% a config file, but `new_conf_value` can override that. The reason we need - %% a separate attribute to override `default` (instead of just changing the - %% default directly) is that `default` also affects default values used for - %% config keys that haven't been set to any particular value in the .conf file. - %% (See `cuttlefish_generator:add_defaults` for the relevant bits of code.) - case cuttlefish_mapping:new_conf_value(MappingRecord) of - undefined -> - cuttlefish_mapping:default(MappingRecord); - Value -> - Value - end. - -generate_element(true, _, _, _) -> no; -generate_element(false, _, undefined, undefined) -> no; -generate_element(false, basic, _Default, undefined) -> default; -generate_element(false, basic, _, _Comment) -> commented; -generate_element(false, _Level, _Default, _Commented) -> no. - --spec generate_comments(cuttlefish_mapping:mapping()) -> [string()]. -generate_comments(M) -> - DocString = cuttlefish_mapping:doc(M), - - [DefaultDT|_] = cuttlefish_mapping:datatype(M), - Default = case cuttlefish_mapping:default(M) of - undefined -> []; - Other -> - [ "", ?FMT("Default: ~s", [cuttlefish_datatypes:to_string(Other, DefaultDT)]) ] - end, - - Datatypes = ["", "Acceptable values:" | - [ ?FMT(" - ~s", [pretty_datatype(DT)]) - || DT <- cuttlefish_mapping:datatype(M)]], - - Doc = DocString ++ Default ++ Datatypes, - [ "## " ++ D || D <- Doc]. - --spec pretty_datatype(cuttlefish_datatypes:datatype() | - cuttlefish_datatypes:extended()) -> string(). -pretty_datatype(integer) -> "an integer"; -pretty_datatype({enum, L}) -> - "one of: " ++ string:join([ atom_to_list(A) || A <- L], ", "); -pretty_datatype(ip) -> "an IP/port pair, e.g. 127.0.0.1:10011"; -pretty_datatype({duration, _}) -> "a time duration with units, e.g. '10s' for 10 seconds"; -pretty_datatype(bytesize) -> "a byte size with units, e.g. 10GB"; -pretty_datatype({integer, I}) -> "the integer " ++ integer_to_list(I); -pretty_datatype({string, S}) -> "the text \"" ++ S ++ "\""; -pretty_datatype({atom, A}) -> "the text \"" ++ atom_to_list(A) ++ "\""; -pretty_datatype({ip, {IP, Port}}) -> ?FMT("the address ~s:~p", [IP, Port]); -pretty_datatype({{duration,_}, D}) -> "the time duration " ++ D; -pretty_datatype({bytesize, B}) -> "the bytesize " ++ B; -pretty_datatype(file) -> "the path to a file"; -pretty_datatype(directory) -> "the path to a directory"; -pretty_datatype({file, F}) -> "the file " ++ F; -pretty_datatype({directory, D}) -> "the directory " ++ D; -pretty_datatype(flag) -> "on or off"; -pretty_datatype({flag, On, Off}) when is_atom(On), is_atom(Off) -> - ?FMT("~p or ~p", [On, Off]); -pretty_datatype({flag, {On,_}, {Off,_}}) -> - ?FMT("~p or ~p", [On, Off]); -pretty_datatype(_) -> "text". %% string and atom - -remove_duplicates(Conf) -> - lists:foldl( - fun({include_file,V}, MiniAcc) -> - [{include_file,V}|MiniAcc]; - ({K,V}, MiniAcc) -> - cuttlefish_util:replace_proplist_value(K, V, MiniAcc) - end, - [], - Conf). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --ifdef(TEST). - -generate_element_test() -> - - TestSchemaElement = - cuttlefish_mapping:parse({mapping, "ring_size", "riak_core.ring_creation_size", - [ - {datatype, integer}, - {commented, 64}, - {doc, ["Default ring creation size. Make sure it is a power of 2,", - "e.g. 16, 32, 64, 128, 256, 512 etc"]} - ] - }), - - - GeneratedConf = generate_element(TestSchemaElement), - - ?assertEqual(7, length(GeneratedConf)), - ?assertEqual( - "## Default ring creation size. Make sure it is a power of 2,", - lists:nth(1, GeneratedConf) - ), - ?assertEqual( - "## e.g. 16, 32, 64, 128, 256, 512 etc", - lists:nth(2, GeneratedConf) - ), - ?assertEqual( - "## ", - lists:nth(3, GeneratedConf) - ), - ?assertEqual( - "## Acceptable values:", - lists:nth(4, GeneratedConf) - ), - ?assertEqual( - "## - an integer", - lists:nth(5, GeneratedConf) - ), - ?assertEqual( - "## ring_size = 64", - lists:nth(6, GeneratedConf) - ), - ok. - -generate_conf_default_test() -> - TestMappings = [{mapping, "default.absent", "undefined", - [{datatype, integer}, - {new_conf_value, 42}]}, - {mapping, "default.present", "undefined", - [{datatype, integer}, - {default, -1}, - {new_conf_value, 9001}]}], - - TestSchema = lists:map(fun cuttlefish_mapping:parse/1, TestMappings), - GeneratedConf = generate(TestSchema), - - %% TODO Feels pretty fragile to rely on the number of comment lines not changing... - %% Would be nice if we had a good way to pinpoint the line we want to check without - %% having to hardcode the line numbers into the lists:nth calls. - ?assertEqual( - "default.absent = 42", - lists:nth(4, GeneratedConf) - ), - ?assertEqual( - "default.present = 9001", - lists:nth(11, GeneratedConf) - ), - ok. - -generate_dollar_test() -> - TestSchemaElement = - cuttlefish_mapping:parse({ mapping, "listener.http.$name", "riak_core.http", [ - {datatype, ip}, - {default, "127.0.0.1:8098"}, - {mapping, "riak_core.http"}, - {include_default,"internal"} - ]}), - _GeneratedConf = generate_element(TestSchemaElement), - - ok. - -generate_comments_test() -> - SchemaElement = cuttlefish_mapping:parse({ mapping, "dont.care", "undefined", [ - {doc, ["Hi!", "Bye!"]} - ]}), - Comments = generate_comments(SchemaElement), - ?assertEqual(["## Hi!", "## Bye!", "## ", "## Acceptable values:", "## - text"], Comments). - -duplicates_test() -> - Conf = file(tp("multi1.conf")), - ?assertEqual(2, length(Conf)), - ?assertEqual("3", proplists:get_value(["a","b","c"], Conf)), - ?assertEqual("1", proplists:get_value(["a","b","d"], Conf)), - ok. - -duplicates_multi_test() -> - Conf = files([tp("multi1.conf"), tp("multi2.conf")]), - ?assertEqual(2, length(Conf)), - ?assertEqual("4", proplists:get_value(["a","b","c"], Conf)), - ?assertEqual("1", proplists:get_value(["a","b","d"], Conf)), - ok. - -files_one_nonent_test() -> - Conf = files([tp("multi1.conf"), tp("nonent.conf")]), - ?assertEqual({errorlist,[{error, {file_open, {tp("nonent.conf"), enoent}}}]}, Conf), - ok. - -files_incomplete_parse_test() -> - Conf = file(tp("incomplete.conf")), - ?assertEqual({errorlist, [{error, {conf_syntax, {tp("incomplete.conf"), {3, 1}}}}]}, Conf), - ok. - -generate_element_level_advanced_test() -> - cuttlefish_test_logger:bounce(warning), - assert_no_output({level, advanced}), - [Log] = cuttlefish_test_logger:get_logs(), - ?assertMatch({match, _}, re:run(Log, "{level, advanced} has been deprecated. Use 'hidden' or '{hidden, true}'")), - ok. - -generate_element_level_intermediate_test() -> - cuttlefish_test_logger:bounce(warning), - assert_no_output({level, intermediate}), - [Log] = cuttlefish_test_logger:get_logs(), - ?assertMatch({match, _}, re:run(Log, "{level, intermediate} has been deprecated. Use 'hidden' or '{hidden, true}'")), - ok. - -generate_element_hidden_test() -> - cuttlefish_test_logger:bounce(warning), - assert_no_output(hidden), - assert_no_output({hidden, true}), - ?assertEqual([], cuttlefish_test_logger:get_logs()), - ok. - -assert_no_output(Setting) -> - Mapping = cuttlefish_mapping:parse( - {mapping, - "a", "b", [ - {doc, ["blah"]}, - Setting - ]}), - - ?assertEqual([], generate_element(Mapping)). - -%% test-path -tp(Name) -> - filename:join([code:lib_dir(cuttlefish), "test", Name]). - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_datatypes.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_datatypes.erl deleted file mode 100644 index f79779ea20..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_datatypes.erl +++ /dev/null @@ -1,519 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_datatypes: handles datatypes in cuttlefish schemas -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_datatypes). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --type datatype() :: integer | - string | - atom | - file | - directory | - flag | - {flag, atom(), atom()} | - {flag, {atom(), term()}, {atom(), term()}} | - {enum, [atom()]} | - ip | - {duration, cuttlefish_duration:time_unit() } | - bytesize | - {percent, integer} | - {percent, float} | - float. --type extended() :: { integer, integer() } | - { string, string() } | - { file, file:filename() } | - { directory, file:filename() } | - { atom, atom() } | - { ip, { string(), integer() } } | - { {duration, cuttlefish_duration:time_unit() }, string() } | - { bytesize, string() } | - { {percent, integer}, integer() } | - { {percent, float}, float() } | - { float, float() }. --type datatype_list() :: [ datatype() | extended() ]. - --export_type([datatype/0, extended/0, datatype_list/0]). - --export([ - is_supported/1, - is_extended/1, - is_valid_list/1, - from_string/2, - to_string/2, - extended_from/1 -]). - --spec is_supported(any()) -> boolean(). -is_supported(integer) -> true; -is_supported(string) -> true; -is_supported(file) -> true; -is_supported(directory) -> true; -is_supported(flag) -> true; -is_supported({flag, On, Off}) when is_atom(On), is_atom(Off) -> true; -is_supported({flag, {On, _}, {Off, _}}) when is_atom(On), is_atom(Off) -> true; -is_supported(atom) -> true; -is_supported({enum, E}) when is_list(E) -> true; -is_supported(ip) -> true; -is_supported({duration, f}) -> true; -is_supported({duration, w}) -> true; -is_supported({duration, d}) -> true; -is_supported({duration, h}) -> true; -is_supported({duration, m}) -> true; -is_supported({duration, s}) -> true; -is_supported({duration, ms}) -> true; -is_supported(bytesize) -> true; -is_supported({percent, integer}) -> true; -is_supported({percent, float}) -> true; -is_supported(float) -> true; -is_supported(_) -> false. - --spec is_extended(any()) -> boolean(). -is_extended({integer, I}) when is_integer(I) -> true; -is_extended({string, S}) when is_list(S) -> true; -is_extended({atom, A}) when is_atom(A) -> true; -is_extended({file, F}) when is_list(F) -> true; -is_extended({directory, D}) when is_list(D) -> true; -is_extended({ip, {IP, Port}}) when is_list(IP) andalso is_integer(Port) -> true; -is_extended({ip, StringIP}) when is_list(StringIP) -> true; -is_extended({{duration, f}, D}) when is_list(D) -> true; -is_extended({{duration, w}, D}) when is_list(D) -> true; -is_extended({{duration, d}, D}) when is_list(D) -> true; -is_extended({{duration, g}, D}) when is_list(D) -> true; -is_extended({{duration, m}, D}) when is_list(D) -> true; -is_extended({{duration, s}, D}) when is_list(D) -> true; -is_extended({{duration, ms}, D}) when is_list(D) -> true; -is_extended({bytesize, B}) when is_list(B) -> true; -is_extended({{percent, integer}, _Int}) -> true; -is_extended({{percent, float}, _Float}) -> true; -is_extended({float, F}) when is_float(F) -> true; -is_extended(_) -> false. - --spec extended_from(extended()) -> datatype(). -extended_from({integer, _}) -> integer; -extended_from({string, _}) -> string; -extended_from({atom, _}) -> atom; -extended_from({file, _}) -> file; -extended_from({directory, _}) -> directory; -extended_from({ip, _}) -> ip; -extended_from({{duration, Unit}, _}) -> {duration, Unit}; -extended_from({bytesize, _}) -> bytesize; -extended_from({{percent, integer}, _}) -> {percent, integer}; -extended_from({{percent, float}, _}) -> {percent, float}; -extended_from({float, _}) -> float; -extended_from(Other) -> - case is_supported(Other) of - true -> - Other; - _ -> error - end. - --spec is_valid_list(any()) -> boolean(). -is_valid_list(NotList) when not is_list(NotList) -> - false; -is_valid_list([]) -> false; -is_valid_list(List) -> - lists:all(fun(X) -> - is_supported(X) - orelse - is_extended(X) - end, List). - --spec to_string(term(), datatype()) -> string() | cuttlefish_error:error(). -to_string(Atom, atom) when is_list(Atom) -> Atom; -to_string(Atom, atom) when is_atom(Atom) -> atom_to_list(Atom); - -to_string(Integer, integer) when is_integer(Integer) -> integer_to_list(Integer); -to_string(Integer, integer) when is_list(Integer) -> Integer; - -to_string({IP, Port}, ip) when is_list(IP), is_integer(Port) -> IP ++ ":" ++ integer_to_list(Port); -to_string(IPString, ip) when is_list(IPString) -> IPString; - -to_string(Enum, {enum, _}) when is_list(Enum) -> Enum; -to_string(Enum, {enum, _}) when is_atom(Enum) -> atom_to_list(Enum); - -to_string(Duration, {duration, _}) when is_list(Duration) -> Duration; -to_string(Duration, {duration, Unit}) when is_integer(Duration) -> cuttlefish_duration:to_string(Duration, Unit); - -to_string(Bytesize, bytesize) when is_list(Bytesize) -> Bytesize; -to_string(Bytesize, bytesize) when is_integer(Bytesize) -> cuttlefish_bytesize:to_string(Bytesize); - -to_string(String, string) when is_list(String) -> String; - -to_string(File, file) when is_list(File) -> File; - -to_string(Directory, directory) when is_list(Directory) -> Directory; - -to_string(Flag, flag) when is_atom(Flag) -> cuttlefish_flag:to_string(Flag, flag); -to_string(Flag, flag) when is_list(Flag) -> cuttlefish_flag:to_string(Flag, flag); -to_string(Flag, {flag, _, _}=Type) when is_atom(Flag) -> cuttlefish_flag:to_string(Flag, Type); -to_string(Flag, {flag, _, _}=Type) when is_list(Flag) -> cuttlefish_flag:to_string(Flag, Type); - -to_string(Percent, {percent, integer}) when is_integer(Percent) -> - integer_to_list(Percent) ++ "%"; -to_string(Percent, {percent, integer}) when is_list(Percent) -> - Percent; -to_string(Percent, {percent, float}) when is_float(Percent) -> - P = list_to_float(float_to_list(Percent * 100, [{decimals, 6}, compact])), - integer_to_list(cuttlefish_util:ceiling(P)) ++ "%"; -to_string(Percent, {percent, float}) when is_list(Percent) -> - Percent; - -to_string(Float, float) when is_float(Float) -> - float_to_list(Float, [{decimals, 6}, compact]); -to_string(Float, float) when is_list(Float) -> Float; - -%% The Pokemon Clause: Gotta Catch 'em all! -to_string(Value, MaybeExtendedDatatype) -> - case is_extended(MaybeExtendedDatatype) of - true -> - to_string(Value, extended_from(MaybeExtendedDatatype)); - _ -> - {error, {type, {Value, MaybeExtendedDatatype}}} - end. - --spec from_string(term(), datatype()) -> term() | cuttlefish_error:error(). -from_string(Atom, atom) when is_atom(Atom) -> Atom; -from_string(String, atom) when is_list(String) -> list_to_atom(String); - -from_string(Value, {enum, Enum}) -> - cuttlefish_enum:parse(Value, {enum, Enum}); - -from_string(Integer, integer) when is_integer(Integer) -> Integer; -from_string(String, integer) when is_list(String) -> - try list_to_integer(String) of - X -> X - catch - _:_ -> {error, {conversion, {String, integer}}} - end; - -from_string({IP, Port}, ip) when is_list(IP), is_integer(Port) -> {IP, Port}; -from_string(String, ip) when is_list(String) -> - from_string_to_ip(String, lists:split(string:rchr(String, $:), String)); - -from_string(Duration, {duration, _}) when is_integer(Duration) -> Duration; -from_string(Duration, {duration, Unit}) when is_list(Duration) -> cuttlefish_duration:parse(Duration, Unit); - -from_string(Bytesize, bytesize) when is_integer(Bytesize) -> Bytesize; -from_string(Bytesize, bytesize) when is_list(Bytesize) -> cuttlefish_bytesize:parse(Bytesize); - -from_string(String, string) when is_list(String) -> String; - -from_string(File, file) when is_list(File) -> File; - -from_string(Directory, directory) when is_list(Directory) -> Directory; - -from_string(Flag, flag) when is_list(Flag) -> cuttlefish_flag:parse(Flag); -from_string(Flag, flag) when is_atom(Flag) -> cuttlefish_flag:parse(Flag); - -from_string(Flag, {flag, _, _}=Type) when is_list(Flag) -> cuttlefish_flag:parse(Flag, Type); -from_string(Flag, {flag, _, _}=Type) when is_atom(Flag) -> cuttlefish_flag:parse(Flag, Type); - -from_string(Percent, {percent, integer}) when is_integer(Percent), Percent >= 0, Percent =< 100 -> Percent; -from_string(Percent, {percent, integer}) when is_integer(Percent) -> - {error, {range, {{Percent, {percent, integer}}, "0 - 100%"}}}; -%% This clause ends with a percent sign! -from_string(Percent, {percent, integer}) when is_list(Percent) -> - from_string( - list_to_integer(string:sub_string(Percent, 1, length(Percent) - 1)), - {percent, integer}); - -from_string(Percent, {percent, float}) when is_float(Percent), Percent >= 0, Percent =< 1 -> Percent; -from_string(Percent, {percent, float}) when is_float(Percent) -> - {error, {range, {{Percent, {percent, float}}, "0 - 100%"}}}; -%% This clause ends with a percent sign! -from_string(Percent, {percent, float}) when is_list(Percent) -> - from_string( - list_to_integer(string:sub_string(Percent, 1, length(Percent) - 1)) / 100.0, - {percent, float}); - -from_string(Float, float) when is_float(Float) -> Float; -from_string(String, float) when is_list(String) -> - try list_to_float(String) of - X -> X - catch - _:_ -> {error, {conversion, {String, float}}} - end; - -from_string(Thing, InvalidDatatype) -> - {error, {type, {Thing, InvalidDatatype}}}. - - -%%% Utility functions for IP conversion - -port_to_integer(Str) -> - try - list_to_integer(Str) - of - X when X >= 0 -> - X; - %% Negative ports are nonsensical - _X -> - undefined - catch - _:_ -> - undefined - end. - -ip_conversions(String, _IPStr, {error, einval}, _Port) -> - {error, {conversion, {String, 'IP'}}}; -ip_conversions(String, _IPStr, _IP, undefined) -> - {error, {conversion, {String, 'IP'}}}; -ip_conversions(_String, IPStr, {ok, _}, Port) -> - {IPStr, Port}. - -droplast(List) -> - lists:sublist(List, length(List)-1). - -from_string_to_ip(String, {[], String}) -> - {error, {conversion, {String, 'IP'}}}; %% No port -from_string_to_ip(String, {IpPlusColon, PortString}) -> - %% Still need to drop last character from IP, the trailing - %% colon. Perfect use case for lists:droplast/1 but it's a recent - %% addition - IP = droplast(IpPlusColon), - ip_conversions(String, IP, inet:parse_address(IP), port_to_integer(PortString)). - - --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -to_string_atom_test() -> - ?assertEqual("split_the", to_string(split_the, atom)), - ?assertEqual("split_the", to_string("split_the", atom)). - -to_string_integer_test() -> - ?assertEqual("32", to_string(32, integer)), - ?assertEqual("32", to_string("32", integer)). - -to_string_ip_test() -> - ?assertEqual("127.0.0.1:8098", to_string("127.0.0.1:8098", ip)), - ?assertEqual("127.0.0.1:8098", to_string({"127.0.0.1", 8098}, ip)). - -to_string_enum_test() -> - ?assertEqual("true", to_string("true", {enum, [true, false]})), - ?assertEqual("true", to_string(true, {enum, [true, false]})). - -to_string_string_test() -> - ?assertEqual("string", to_string("string", string)). - -to_string_duration_test() -> - ?assertEqual("1w", to_string("1w", {duration, s})), - ?assertEqual("1w", to_string(604800000, {duration, ms})). - -to_string_bytesize_test() -> - ?assertEqual("1GB", to_string(1073741824, bytesize)), - ?assertEqual("1GB", to_string("1GB", bytesize)). - -to_string_percent_integer_test() -> - ?assertEqual("10%", to_string(10, {percent, integer})), - ?assertEqual("10%", to_string("10%", {percent, integer})), - ok. - -to_string_percent_float_test() -> - ?assertEqual("10%", to_string(0.1, {percent, float})), - ?assertEqual("10%", to_string("10%", {percent, float})), - ok. - -to_string_float_test() -> - ?assertEqual("0.1", to_string(0.1, float)), - ?assertEqual("0.1", to_string("0.1", float)), - ok. - -to_string_extended_type_test() -> - ?assertEqual("split_the", to_string(split_the, {atom, split_the})), - ?assertEqual("split_the", to_string("split_the", {atom, split_the})), - ?assertEqual("32", to_string(32, {integer, 32})), - ?assertEqual("32", to_string("32", {integer, 32})), - ?assertEqual("127.0.0.1:8098", to_string("127.0.0.1:8098", {ip, "127.0.0.1:8098"})), - ?assertEqual("127.0.0.1:8098", to_string({"127.0.0.1", 8098}, {ip, {"127.0.0.1", 8098}})), - ?assertEqual("string", to_string("string", {string, "string"})), - ?assertEqual("1w", to_string("1w", {{duration, s}, "1w"})), - ?assertEqual("1w", to_string(604800000, {{duration, ms}, "1w"})), - ?assertEqual("1GB", to_string(1073741824, {bytesize, "1GB"})), - ?assertEqual("1GB", to_string("1GB", {bytesize, "1GB"})), - ?assertEqual("10%", to_string(10, {{percent, integer}, "10%"})), - ?assertEqual("10%", to_string("10%", {{percent, integer}, "10%"})), - ?assertEqual("10%", to_string(0.1, {{percent, float}, "10%"})), - ?assertEqual("10%", to_string("10%", {{percent, float}, "10%"})), - ?assertEqual("0.1", to_string(0.1, {float, 0.1})), - ?assertEqual("0.1", to_string("0.1", {float, 0.1})), - ok. - -to_string_unsupported_datatype_test() -> - ?assertEqual("Tried to convert \"Something\" but invalid datatype: unsupported_datatype", ?XLATE(to_string("Something", unsupported_datatype))). - -from_string_atom_test() -> - ?assertEqual(split_the, from_string(split_the, atom)), - ?assertEqual(split_the, from_string("split_the", atom)). - -from_string_integer_test() -> - ?assertEqual(32, from_string(32, integer)), - ?assertEqual(32, from_string("32", integer)), - ?assertEqual("\"thirty_two\" cannot be converted to a(n) integer", ?XLATE(from_string("thirty_two", integer))), - ok. - -from_string_ip_test() -> - ?assertEqual({"127.0.0.1", 8098}, from_string("127.0.0.1:8098", ip)), - ?assertEqual( - {"2001:0db8:85a3:0042:1000:8a2e:0370:7334", 8098}, - from_string("2001:0db8:85a3:0042:1000:8a2e:0370:7334:8098", ip)), - ?assertEqual( - {"2001:0db8:85a3::0370:7334", 8098}, - from_string("2001:0db8:85a3::0370:7334:8098", ip)), - ?assertEqual( - {"::1", 1}, - from_string("::1:1", ip)), - - BadIPs = [ - "This is not an IP:80", - "2001:0db8:85a3:0042:1000:8a2e:0370:80", - "127.0.0.1.1:80", - "127.256.0.1:80", - "127.0.0.1", %% No port - "127.0.0.1:-5", - "0:127.0.0.1:80", - "127.0.0.1:80l", - ":1:1" - ], - - lists:foreach(fun(Bad) -> - ?assertEqual({error, {conversion, {Bad, 'IP'}}}, - from_string(Bad, ip)) - end, - BadIPs), - ok. - -from_string_enum_test() -> - ?assertEqual("\"a\" is not a valid enum value, acceptable values are: b, c", ?XLATE(from_string(a, {enum, [b, c]}))), - ?assertEqual(true, from_string("true", {enum, [true, false]})), - ?assertEqual(true, from_string(true, {enum, [true, false]})). - -from_string_duration_test() -> - %% more examples in the the cuttlefish_duration tests - ?assertEqual(1100, from_string("1s100ms", {duration, ms})), - ?assertEqual(1100, from_string(1100, {duration, ms})), - ok. - -from_string_duration_secs_test() -> - %% more examples in the the cuttlefish_duration tests - %% also rounds up for smaller units - ?assertEqual(2, from_string("1s100ms", {duration, s})), - ?assertEqual(2, from_string(2, {duration, s})), - ok. - -from_string_percent_integer_test() -> - ?assertEqual(10, from_string("10%", {percent, integer})), - ?assertEqual(10, from_string(10, {percent, integer})), - %% Range! - ?assertEqual(0, from_string("0%", {percent, integer})), - ?assertEqual(100, from_string("100%", {percent, integer})), - ?assertEqual("110% can't be outside the range 0 - 100%", ?XLATE(from_string("110%", {percent, integer}))), - ?assertEqual("-1% can't be outside the range 0 - 100%", ?XLATE(from_string("-1%", {percent, integer}))), - ok. - -from_string_percent_float_test() -> - ?assertEqual(0.10, from_string("10%", {percent, float})), - ?assertEqual(0.10, from_string(0.1, {percent, float})), - %% Range! - ?assertEqual(0.0, from_string("0%", {percent, float})), - ?assertEqual(1.0, from_string("100%", {percent, float})), - ?assertEqual("110% can't be outside the range 0 - 100%", ?XLATE(from_string("110%", {percent, float}))), - ?assertEqual("-1% can't be outside the range 0 - 100%", ?XLATE(from_string("-1%", {percent, float}))), - ok. - -from_string_float_test() -> - ?assertEqual(0.1, from_string("0.100", float)), - ?assertEqual(0.1, from_string(0.1, float)), - ok. - -from_string_string_test() -> - ?assertEqual("string", from_string("string", string)). - -from_string_unsupported_datatype_test() -> - ?assertEqual("Tried to convert \"string\" but invalid datatype: unsupported_datatype", ?XLATE(from_string("string", unsupported_datatype))). - -is_supported_test() -> - ?assert(is_supported(integer)), - ?assert(is_supported(string)), - ?assert(is_supported(atom)), - ?assert(is_supported(file)), - ?assert(is_supported(directory)), - ?assert(is_supported({enum, [one, two, three]})), - ?assert(not(is_supported({enum, not_a_list}))), - ?assert(is_supported(ip)), - ?assert(is_supported({duration, f})), - ?assert(is_supported({duration, w})), - ?assert(is_supported({duration, d})), - ?assert(is_supported({duration, h})), - ?assert(is_supported({duration, m})), - ?assert(is_supported({duration, s})), - ?assert(is_supported({duration, ms})), - ?assert(is_supported(bytesize)), - ?assert(not(is_supported(some_unsupported_type))), - ok. - -is_extended_test() -> - ?assertEqual(true, is_extended({integer, 10})), - ?assertEqual(true, is_extended({integer, -10})), - ?assertEqual(false, is_extended({integer, "ten"})), - - ?assertEqual(true, is_extended({string, "string"})), - ?assertEqual(false, is_extended({string, string})), - ?assertEqual(false, is_extended({string, 10})), - - ?assertEqual(true, is_extended({atom, atom})), - ?assertEqual(false, is_extended({atom, "atom"})), - ?assertEqual(false, is_extended({atom, 10})), - - ?assertEqual(true, is_extended({file, "/tmp/foo.txt"})), - ?assertEqual(true, is_extended({file, ""})), - ?assertEqual(false, is_extended({file, this})), - - ?assertEqual(true, is_extended({directory, "/tmp/foo.txt"})), - ?assertEqual(true, is_extended({directory, ""})), - ?assertEqual(false, is_extended({directory, this})), - - ?assertEqual(true, is_extended({ip, {"1.2.3.4", 1234}})), - ?assertEqual(false, is_extended({ip, {1234, 1234}})), - ?assertEqual(false, is_extended({ip, {"1.2.3.4", "1234"}})), - - ?assertEqual(true, is_extended({{duration, f}, "10f"})), - ?assertEqual(true, is_extended({{duration, w}, "10f"})), - ?assertEqual(true, is_extended({{duration, d}, "10f"})), - ?assertEqual(true, is_extended({{duration, g}, "10f"})), - ?assertEqual(true, is_extended({{duration, m}, "10f"})), - ?assertEqual(true, is_extended({{duration, s}, "10f"})), - ?assertEqual(true, is_extended({{duration, ms}, "10ms"})), - ?assertEqual(true, is_extended({bytesize, "10GB"})), - - ?assertEqual(true, is_extended({{percent, integer}, "10%"})), - ?assertEqual(true, is_extended({{percent, integer}, 10})), - ?assertEqual(true, is_extended({{percent, float}, "10%"})), - ?assertEqual(true, is_extended({{percent, float}, 0.1})), - ?assertEqual(true, is_extended({float, 0.1})), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_duration.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_duration.erl deleted file mode 100644 index 06ec15d97f..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_duration.erl +++ /dev/null @@ -1,171 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_duration: complexity for parsing durations -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_duration). - --opaque time_unit() :: f | w | d | h | m | s | ms. --export_type([time_unit/0]). - --include("cuttlefish_duration.hrl"). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([parse/1, parse/2, to_string/2]). - --spec to_string(integer(), time_unit()) -> string(). -to_string(Fortnights, f) -> milliseconds(Fortnights * ?FORTNIGHT); -to_string(Weeks, w) -> milliseconds(Weeks * ?WEEK); -to_string(Days, d) -> milliseconds(Days * ?DAY); -to_string(Hours, h) -> milliseconds(Hours * ?HOUR); -to_string(Minutes, m) -> milliseconds(Minutes * ?MINUTE); -to_string(Seconds, s) -> milliseconds(Seconds * ?SECOND); -to_string(Millis, ms) -> milliseconds(Millis). - -milliseconds(Millis) -> - Units = lists:filter(fun({N, _Unit}) -> N =/= 0 end, [ - { Millis div ?WEEK, "w"}, - {(Millis rem ?WEEK) div ?DAY, "d"}, - {(Millis rem ?DAY) div ?HOUR, "h"}, - {(Millis rem ?HOUR) div ?MINUTE, "m"}, - {(Millis rem ?MINUTE) div ?SECOND, "s"}, - { Millis rem ?SECOND, "ms"} - ]), - lists:flatten([ - integer_to_list(N) ++ Unit - || {N, Unit} <- Units]). - --spec parse(string(), time_unit()) -> integer(). -parse(DurationString, ms) -> parse(DurationString); -parse(DurationString, Unit) -> - case parse(DurationString) of - {error, _}=Err -> - Err; - Num when is_number(Num) -> - {Unit, Multiplier} = lists:keyfind(Unit, 1, ?MULTIPLIERS), - cuttlefish_util:ceiling(Num / Multiplier) - end. - - --spec parse(string()) -> integer() | cuttlefish_error:error(). -parse(InputDurationString) -> - DurationString = string:to_lower(InputDurationString), - case cuttlefish_duration_parse:parse(DurationString) of - Float when is_float(Float) -> - cuttlefish_util:ceiling(Float); - Int when is_integer(Int) -> - Int; - _ -> - {error, {duration, InputDurationString}} - end. - --ifdef(TEST). - -milliseconds_test() -> - ?assertEqual("500ms", milliseconds(500)), - ?assertEqual("1s500ms", milliseconds(1500)), - ?assertEqual("30m", milliseconds(1800000)), - ?assertEqual("1w1d1h1m1s1ms", milliseconds(694861001)), - ok. - -seconds_test() -> - ?assertEqual("50s", to_string(50, s)), - ?assertEqual("1m1s", to_string(61, s)), - ?assertEqual("30m", to_string(1800, s)), - ?assertEqual("1w1d1h1m1s", to_string(694861, s)), - ok. - -parse_test() -> - test_parse(500, "500ms"), - test_parse(500, ".5s"), - test_parse(1001, "1s1ms"), - test_parse(1599, "1s599ms"), - test_parse(1599, "1.599s"), - test_parse(1600, "1.5999s"), - test_parse(60000, "1m"), - test_parse(60000, "60s"), - test_parse(60000, "60000ms"), - test_parse(90000, "1.5m"), - test_parse(90000, "1m30s"), - test_parse(90000, "1m29s1000ms"), - test_parse(1800000, ".5h"), - test_parse(3600000, "1h"), - test_parse(3601000, "1h1s"), - test_parse(3660000, "1h1m"), - test_parse(3661000, "1h1m1s"), - test_parse(3661001, "1h1m1s1ms"), - test_parse(3600000, "60m"), - test_parse(5400000, "90m"), - test_parse(5401000, "90m1s"), - test_parse(5401001, "90m1s1ms"), - test_parse(5400000, "1h30m"), - test_parse(5401000, "1h30m1s"), - test_parse(3660000, "1h1m"), - test_parse(86400000, "1d"), - test_parse(86401000, "1d1s"), - test_parse(86401001, "1d1s1ms"), - test_parse(604800000, "1w"), - test_parse(691200000, "1w1d"), - test_parse(694800000, "1w1d1h"), - test_parse(694860000, "1w1d1h1m"), - test_parse(694861000, "1w1d1h1m1s"), - test_parse(694861001, "1w1d1h1m1s1ms"), - - %% Weird but ok? - test_parse(121001, "1m1s1ms1m"), - - %% Easter Egg - test_parse(1904461001, "1f1w1d1h1m1s1ms"), - ok. - -test_parse(ExpectedMillis, StringToParse) -> - ?assertEqual(ExpectedMillis, parse(StringToParse)). - -parse_2_test() -> - ?assertEqual(1, parse("1ms", ms)), - ?assertEqual(1, parse("1ms", s)), - ?assertEqual(1, parse("1ms", m)), - ?assertEqual(1, parse("1ms", h)), - ?assertEqual(1, parse("1ms", d)), - ?assertEqual(1, parse("1ms", w)), - ?assertEqual(1, parse("1ms", f)), - ok. - -to_string_test() -> - ?assertEqual("2w", to_string(1, f)), - ?assertEqual("2w", to_string(2, w)), - ?assertEqual("1w", to_string(1, w)), - ?assertEqual("1d", to_string(1, d)), - ?assertEqual("1w", to_string(7, d)), - ?assertEqual("1h", to_string(1, h)), - ?assertEqual("1m", to_string(1, m)), - ok. - -parse_error_test() -> - ?assertMatch({error, _}, parse("1q")), - %% This previously raised badarith because it did not check the - %% return value of parse/1. - ?assertMatch({error, _}, catch parse("1q", h)), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_duration.hrl b/_build/emqx/lib/cuttlefish/src/cuttlefish_duration.hrl deleted file mode 100644 index 2dfefc144d..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_duration.hrl +++ /dev/null @@ -1,16 +0,0 @@ --define(FMT(F,A), lists:flatten(io_lib:format(F,A))). --define(FORTNIGHT, 1209600000). --define(WEEK, 604800000). --define(DAY, 86400000). --define(HOUR, 3600000). --define(MINUTE, 60000). --define(SECOND, 1000). - --define(MULTIPLIERS, - [{f, ?FORTNIGHT}, - {w, ?WEEK}, - {d, ?DAY}, - {h, ?HOUR}, - {m, ?MINUTE}, - {s, ?SECOND}, - {ms, 1}]). diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_duration_parse.peg b/_build/emqx/lib/cuttlefish/src/cuttlefish_duration_parse.peg deleted file mode 100644 index 4deb2e7a87..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_duration_parse.peg +++ /dev/null @@ -1,51 +0,0 @@ -%% Duration string parser - -duration <- duration_segment+ `lists:sum(Node)`; - -duration_segment <- (float / integer) unit ` - [Amount, Span] = Node, - {Span, Multiplier} = lists:keyfind(Span, 1, ?MULTIPLIERS), - Amount * Multiplier -`; - -integer <- [1-9] [0-9]* `list_to_integer(?FLATTEN(Node))`; - -unit <- "f" / "w" / "d" / "h" / "ms" / "m" / "s" `binary_to_atom(Node, latin1)`; - -float <- ( [0-9]+ "." [0-9]+ ) / ( "." [0-9]+ ) ` - case Node of - [<<".">>, Mantissa] -> - list_to_float(?FLATTEN(["0.", Mantissa])); - _ -> - list_to_float(?FLATTEN(Node)) - end -`; - -` - -%% ------------------------------------------------------------------- -%% -%% cuttlefish_duration_parse: parses duration strings -%% -%% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --include("cuttlefish_duration.hrl"). - --define(FLATTEN(S), binary_to_list(iolist_to_binary(S))). -` diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_effective.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_effective.erl deleted file mode 100644 index c992734fc3..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_effective.erl +++ /dev/null @@ -1,283 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_effective: handles generating the effective configuration -%% -%% Copyright (c) 2014 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_effective). - --define(FMT(F,A), lists:flatten(io_lib:format(F,A))). - --export([build/3]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --spec build(cuttlefish_conf:conf(), cuttlefish_schema:schema(), [proplists:property()]) -> [string()]. -build(Conf, {_Translations, Mappings, _Validators} = _Schema, AdvConfig) -> - EffectiveConfig = lists:reverse(lists:sort(cuttlefish_generator:add_defaults(Conf, Mappings))), - %% EffectiveConfig is a list of { [string()], term() } - - %% Returns the list of cuttlefish variables that have been overridden in advanced.config - KeysToHateOn = process_advanced(Mappings, AdvConfig), - - EffectiveOutput = lists:foldl( - fun({Var, Value}, Acc) -> - Variable = string:join(Var, "."), - - IsHater = - lists:any( - fun(X) -> - cuttlefish_variable:is_fuzzy_match(Var, X) - end, - KeysToHateOn - ), - - Line = try ?FMT("~s = ~s", [Variable, Value]) of - X -> X - catch - _:_ -> - %% I hate that I had to do this, 'cause you know... - %% Erlang and Strings, but actually this is ok because - %% sometimes there are going to be weird tuply things - %% in here, so always good to fall back on ~p. - %% honestly, I think this try should be built into io:format - ?FMT("~s = ~p", [Variable, Value]) - end, - case IsHater of - true -> - [?FMT("## ~s was overridden in advanced.config", [Variable]), - "## " ++ Line] ++ Acc; - _ -> [Line | Acc] - end - end, - [], - EffectiveConfig - ), - - case AdvConfig of - [] -> EffectiveOutput; - _ -> - EffectiveOutput ++ - [ - "## The following advanced.config was used in generating the ", - "## configuration and may have overridden some options that were ", - "## commented out above." - ] - ++ advanced_as_comment(AdvConfig) - end. - -advanced_as_comment(AdvConfig) -> - Str = lists:flatten(io_lib:format("~p", [AdvConfig])), - [ "## " ++ L || L <- string:tokens(Str, "$\n")]. - -%% @doc checks a mapping's "mapping" is in the set of kvc paths in -%% the provided advanced.config --spec process_advanced( - [cuttlefish_mapping:mapping()], - [proplists:property()]) -> [cuttlefish_variable:variable()]. -process_advanced(Mappings, AdvancedConfig) -> - AdvKeys = proplist_to_kvcpaths(AdvancedConfig), - lists:foldl( - fun(M, Acc) -> - case lists:member(cuttlefish_mapping:mapping(M), AdvKeys) of - true -> - [cuttlefish_mapping:variable(M)|Acc]; - _ -> Acc - end - end, - [], - Mappings). - -%% @doc returns a list of kvcesque paths that represent the structure -%% of a proplist of proplists of proplists etc... -%% e.g. [{parent, [{child1, [{grandchild1, _}]}, {child2, _}]}] -> -%% ["parent.child1.grandchild1", "parent.child2"] --spec proplist_to_kvcpaths([proplists:property()]) -> [string()]. -proplist_to_kvcpaths(Proplist) -> - proplist_to_kvcpaths("", Proplist). --spec proplist_to_kvcpaths(string(), [proplists:property()]) -> [string()]. -proplist_to_kvcpaths(Prefix, Proplist) -> - %% Handles the base case, without this, all keys would start with "." - NewPrefix = case Prefix of - "" -> ""; - _ -> Prefix ++ "." - end, - lists:foldl(fun(K, Acc) -> - KeyedPrefix = NewPrefix ++ canonicalize_key(K), - R = proplist_to_kvcpaths( - KeyedPrefix, - proplists:get_value(K, Proplist)), - case R of - [] -> - [KeyedPrefix|Acc]; - _ -> - Acc ++ R - end - end, - [], - keys_if_you_got_em(Proplist) - ). - -%% So this is gross, but is the simplest scheme for determining the -%% type of data coming into this function. It doesn't really -%% matter how we handle non-atoms because cuttlefish only creates -%% proplists with atoms as the keynames. --spec canonicalize_key(atom() | list() | binary()) -> string(). -canonicalize_key(K) when is_atom(K) -> - atom_to_list(K); -canonicalize_key(K) when is_list(K) -> - "\"" ++ K ++ "\""; -canonicalize_key(K) when is_binary(K) -> - "<<\""++binary_to_list(K)++"\">>". - - --spec keys_if_you_got_em([proplists:property()]) -> [term()]. -keys_if_you_got_em(Proplist) when is_list(Proplist) -> - proplists:get_keys(Proplist); -keys_if_you_got_em(_) -> []. - --ifdef(TEST). - -%% This is the comprehensive test of all functionality of this module -%% working together in perfect harmony -probably_the_most_important_test() -> - Mappings = [ - cuttlefish_mapping:parse( - {mapping, "namespace.var1", "app.setting1", []} - ), - cuttlefish_mapping:parse( - {mapping, "namespace.2.$sub", "app.setting2", []} - ), - cuttlefish_mapping:parse( - {mapping, "namespace.var3", "app.setting3", []} - ), - cuttlefish_mapping:parse( - {mapping, "namespace.4.$sub", "app.setting4", []} - ) - ], - Conf = [ - {["namespace", "var1"], "x"}, - {["namespace", "2", "1"], "x"}, - {["namespace", "2", "2"], "x"}, - {["namespace", "2", "3"], "x"}, - {["namespace", "var3"], "y"}, - {["namespace", "4", "1"], "y"}, - {["namespace", "4", "2"], "y"}, - {["namespace", "4", "3"], "y"} - ], - AdvConfig = [{app, [{setting3, "z"}, {setting4, "zz"}]}], - - Effective = build(Conf, {[], Mappings, []}, AdvConfig), - ?assertEqual(16, length(Effective)), - - %% Remember, this output is sorted by variable, even if there's a comment - - ?assertEqual("namespace.2.1 = x", lists:nth(1, Effective)), - ?assertEqual("namespace.2.2 = x", lists:nth(2, Effective)), - ?assertEqual("namespace.2.3 = x", lists:nth(3, Effective)), - ?assertEqual("## namespace.4.1 was overridden in advanced.config", lists:nth(4, Effective)), - ?assertEqual("## namespace.4.1 = y", lists:nth(5, Effective)), - ?assertEqual("## namespace.4.2 was overridden in advanced.config", lists:nth(6, Effective)), - ?assertEqual("## namespace.4.2 = y", lists:nth(7, Effective)), - ?assertEqual("## namespace.4.3 was overridden in advanced.config", lists:nth(8, Effective)), - ?assertEqual("## namespace.4.3 = y", lists:nth(9, Effective)), - ?assertEqual("namespace.var1 = x", lists:nth(10, Effective)), - ?assertEqual("## namespace.var3 was overridden in advanced.config", lists:nth(11, Effective)), - ?assertEqual("## namespace.var3 = y", lists:nth(12, Effective)), - ?assertEqual("## The following advanced.config was used in generating the ", lists:nth(13, Effective)), - ?assertEqual("## configuration and may have overridden some options that were ", lists:nth(14, Effective)), - ?assertEqual("## commented out above.", lists:nth(15, Effective)), - ?assertEqual("## [{app,[{setting3,\"z\"},{setting4,\"zz\"}]}]", lists:nth(16, Effective)), - ok. - -process_advanced_test() -> - Mappings = [ - cuttlefish_mapping:parse( - {mapping, "thing.1", "a.b.c", []} - ) - ], - AdvConfig = [{a, [{b, [{c, ""}, {d, ""}]}]}], - KeysToWatch = process_advanced(Mappings, AdvConfig), - ?assertEqual([["thing", "1"]], KeysToWatch), - ok. - -build_with_sub_test() -> - Mappings = [ - cuttlefish_mapping:parse( - {mapping, "a.$whatev.thing", "a.b.c", []} - ) - ], - AdvConfig = [{a, [{b, [{c, ""}, {d, ""}]}]}], - Conf = [ - {["a", "1", "thing"], "x"}, - {["a", "2", "thing"], "x"}, - {["a", "3", "thing"], "x"} - ], - - Effective = build(Conf, {[], Mappings, []}, AdvConfig), - - ?assertEqual(10, length(Effective)), - ?assertEqual("## a.1.thing was overridden in advanced.config", lists:nth(1, Effective)), - ?assertEqual("## a.1.thing = x", lists:nth(2, Effective)), - ?assertEqual("## a.2.thing was overridden in advanced.config", lists:nth(3, Effective)), - ?assertEqual("## a.2.thing = x", lists:nth(4, Effective)), - ?assertEqual("## a.3.thing was overridden in advanced.config", lists:nth(5, Effective)), - ?assertEqual("## a.3.thing = x", lists:nth(6, Effective)), - ?assertEqual("## The following advanced.config was used in generating the ", lists:nth(7, Effective)), - ?assertEqual("## configuration and may have overridden some options that were ", lists:nth(8, Effective)), - ?assertEqual("## commented out above.", lists:nth(9, Effective)), - ?assertEqual("## [{a,[{b,[{c,[]},{d,[]}]}]}]", lists:nth(10, Effective)), - ok. - -proplist_to_kvcpath_test() -> - Proplist = [{a, [ - {b, [ - {c, "x"} - ]}, - {d, [ - {e, "y"} - ]}, - {f , "z"} - ] - }, - {g, "q"}], - Paths = proplist_to_kvcpaths(Proplist), - ?assertEqual(sets:from_list([ - "a.b.c", - "a.d.e", - "a.f", - "g" - ]), sets:from_list(Paths)), - ok. - -proplists_to_kvcpath_riak_core_test() -> - Proplist = [{riak_core,[ - {ring_creation_size,128}, - {cluster_mgr, {"127.0.0.1", 9080 } } - ]}], - Paths = proplist_to_kvcpaths(Proplist), - ?assertEqual([ - "riak_core.ring_creation_size", - "riak_core.cluster_mgr" - ], Paths), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_enum.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_enum.erl deleted file mode 100644 index 0b5eb18ccc..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_enum.erl +++ /dev/null @@ -1,163 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_enum: datatype for simple enum settings with -%% customizable names and values -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_enum). - --type enum_list() :: [{atom()|string(), term()}]. --type enum() :: {enum, enum_list()}. --type strict_enum_list() :: [{string(), term()}]. --type strict_enum() :: {enum, strict_enum_list()}. --export_type([enum/0, strict_enum/0]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([ - to_string/2, - parse/2 -]). - --define(FMT(F, A), lists:flatten(io_lib:format(F, A))). - --spec to_string(string() | atom(), enum() - ) -> string() | cuttlefish_error:error(). -to_string(Value, {enum, _Raw} = Enum) -> - FriendlEnum = assuage_enum(Enum), - case to_string_by_value(Value, FriendlEnum) of - {K, _} -> - atom_to_list_maybe(K); - false -> - to_string_by_key(atom_to_list_maybe(Value), FriendlEnum) - end. - --spec to_string_by_value(term(), strict_enum()) -> term(). -to_string_by_value(Value, {enum, FriendlEnum}) -> - lists:keyfind(Value, 2, FriendlEnum). - --spec to_string_by_key(atom() | string(), strict_enum()) -> string(). -to_string_by_key(Key, {enum, FriendlEnum}) -> - case lists:keyfind(Key, 1, FriendlEnum) of - {K, _} -> K; - false -> - to_error(Key, FriendlEnum) - end. - --spec parse(term(), enum()) -> term() | cuttlefish_error:error(). -parse(Value, {enum, _Raw} = Enum) -> - FriendlEnum = assuage_enum(Enum), - case parse_by_key(atom_to_list_maybe(Value), FriendlEnum) of - {_Key, Val} -> - Val; - false -> - parse_by_value(Value, FriendlEnum) - end. - --spec parse_by_key(atom() | string() | term(), strict_enum()) -> - {string(), term()} | false. -parse_by_key(Key, {enum, FriendlEnum}) -> - lists:keyfind(Key, 1, FriendlEnum). - --spec parse_by_value(term(), strict_enum()) -> term() | cuttlefish_error:error(). -parse_by_value(Value, {enum, FriendlEnum}) -> - case lists:keyfind(Value, 2, FriendlEnum) of - false -> - to_error(Value, FriendlEnum); - {_Key, Value} -> - Value - end. - --spec to_error(atom() | string()| term(), strict_enum_list()) -> cuttlefish_error:error(). -to_error(Value, FriendlEnum) -> - Acceptable = [Key || {Key, _} <- FriendlEnum], - {error, {enum_name, {atom_to_list_maybe(Value), Acceptable}}}. - --spec atom_to_list_maybe(term()) -> term(). -atom_to_list_maybe(Atom) when is_atom(Atom) -> - atom_to_list(Atom); -atom_to_list_maybe(Other) -> Other. - --spec assuage_enum(enum()) -> strict_enum() | cuttlefish_error:error(). -assuage_enum({enum, Enum}) -> - FriendlEnum = assuage_enum(Enum, []), - case cuttlefish_error:is_error(FriendlEnum) of - true -> - FriendlEnum; - _ -> - {enum, FriendlEnum} - end. - --spec assuage_enum(enum_list(), strict_enum_list()) - -> strict_enum_list() | cuttlefish_error:error(). -assuage_enum([], FriendlEnum) -> - lists:reverse(FriendlEnum); -%% If the head is a 2-tuple; yay! -assuage_enum([{Key, Value}|EnumTail], FriendlEnum) when is_atom(Key) -> - assuage_enum(EnumTail, [ { cuttlefish_datatypes:to_string(Key, atom), Value } | FriendlEnum ]); -assuage_enum([{Key, Value}|EnumTail], FriendlEnum) when is_list(Key) -> - assuage_enum(EnumTail, [ { Key, Value } | FriendlEnum ]); -%% If the head is just a string or atom, fall here. -assuage_enum([Key|EnumTail], FriendlEnum) when is_atom(Key) -> - assuage_enum(EnumTail, [ - { cuttlefish_datatypes:to_string(Key, atom), Key } | FriendlEnum]); -assuage_enum([Key|EnumTail], FriendlEnum) when is_list(Key) -> - assuage_enum(EnumTail, [{Key, Key} | FriendlEnum]); -assuage_enum([BadTuple|_], _) when is_tuple(BadTuple) -> - {error, {enum_format, BadTuple}}; -assuage_enum([ErroneousItem|_], _) -> - {error, {enum_format, ErroneousItem}}. - --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -parse_test() -> - ?assertEqual(1, parse("one", {enum, [{"one", 1}, two]})), - ?assertEqual(two, parse("two", {enum, [{"one", 1}, two]})), - ok. - -assuage_enum_test() -> - ?assertEqual({enum, [{"true", true}, {"false", false}]}, - assuage_enum({enum, [true, false]})), - ?assertEqual({enum, [{"true", "true"}, {"false", "false"}]}, - assuage_enum({enum, ["true", "false"]})), - ?assertEqual({enum, [{"one", 1}, {"two", 2}]}, - assuage_enum({enum, [{one, 1}, {"two", 2}]})), - ?assertEqual({enum, [{"off", off}, {"on", "On"}]}, - assuage_enum({enum, [off, {on, "On"}]})), - ok. - -assuage_enum_error_test() -> - ?assertEqual( - "Enum elements must be atoms, strings, or 2-tuples with " - "atom or string as first element. Bad value: {one,two,three}", - ?XLATE(assuage_enum({enum, [{one, two, three}, oops]})) - ), - ?assertEqual( - "Enum elements must be atoms, strings, or 2-tuples with " - "atom or string as first element. Bad value: 7", - ?XLATE(assuage_enum({enum, [oops, 7]})) - ), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_error.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_error.erl deleted file mode 100644 index a44ac88656..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_error.erl +++ /dev/null @@ -1,217 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_generator: this is where the action is -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_error). - --type error() :: {'error', {atom(), term()}}. --type errorlist() :: {'errorlist', [error()]}. --export_type([error/0, errorlist/0]). - --export([ - contains_error/1, - is_error/1, - filter/1, - errorlist_maybe/1, - print/1, - print/2, - xlate/1 -]). - --include("cuttlefish.hrl"). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - -%% We'll be calling this a lot from `xlate' --define(STR(X, Y), xlate(cuttlefish_datatypes:to_string(X, Y))). - --spec xlate({atom(), term()}|string()) -> iolist(). -xlate(Message) when is_list(Message) -> - %% We allow for strings so that we can safely call - %% `cuttlefish_datatypes:to_string` when creating these messages - Message; -xlate({error, Details}) -> - xlate(Details); -xlate({_Error, {error, NestedError}}) -> - xlate(NestedError); -xlate({type, {Value, Type}}) -> - io_lib:format("Tried to convert ~p but invalid datatype: ~p", - [Value, Type]); -xlate({range, {{Value, Type}, Range}}) -> - [?STR(Value, Type), " can't be outside the range ", Range]; -xlate({conversion, {Value, Type}}) -> - io_lib:format("~p cannot be converted to a(n) ~s", [Value, Type]); -xlate({duration, Value}) -> - io_lib:format("Invalid duration value: ~ts", [Value]); -xlate({enum_name, {Value, EnumNames}}) -> - io_lib:format("~p is not a valid enum value, acceptable values are: ~ts", - [Value, string:join(EnumNames, ", ")]); -xlate({enum_format, Value}) -> - %% This collapses two different type of formatting errors into one - %% error message - io_lib:format("Enum elements must be atoms, strings, or 2-tuples with " - "atom or string as first element. Bad value: ~w", [Value]); -xlate({mapping_types, List}) -> - io_lib:format("Invalid datatype list for mapping: ~ts", - [string:join(List, ", ")]); -xlate({mapping_parse, Term}) -> - io_lib:format( - "Poorly formatted input to cuttlefish_mapping:parse/1 : ~p", - [Term] - ); -xlate({translation_parse, Term}) -> - io_lib:format( - "Poorly formatted input to cuttlefish_translation:parse/1 : ~p", - [Term] - ); -xlate({validator_parse, Term}) -> - io_lib:format( - "Poorly formatted input to cuttlefish_validator:parse/1 : ~p", - [Term] - ); -xlate({conf_to_latin1, LineNum}) -> - io_lib:format("Error converting value on line #~p to latin1", [LineNum]); -xlate({bytesize_parse, Value}) -> - io_lib:format("Error converting value ~p to a number of bytes", [Value]); -xlate({file_open, {File, Reason}}) -> - io_lib:format("Could not open file (~s) for Reason ~s", [File, Reason]); -xlate({conf_syntax, {File, {Line, Col}}}) -> - io_lib:format("Syntax error in ~s after line ~p column ~p, " - "parsing incomplete", [File, Line, Col]); -xlate({in_file, {File, Error}}) -> - [File, ": ", xlate(Error)]; -xlate({translation_missing_setting, {Translation, Setting}}) -> - io_lib:format("Translation for '~s' expected to find setting '~s' but was missing", - [Translation, Setting]); -xlate({translation_invalid_configuration, {Translation, Invalid}}) -> - io_lib:format("Translation for '~s' found invalid configuration: ~s", - [Translation, Invalid]); -xlate({translation_unknown_error, {Translation, {Class, Error}}}) -> - io_lib:format("Error running translation for ~s, [~p, ~p]", - [Translation, Class, Error]); -xlate({translation_arity, {Translation, Arity}}) -> - io_lib:format("~p is not a valid arity for translation fun() ~s." - " Try 1 or 2", [Arity, Translation]); -xlate({map_multiple_match, VariableDefinition}) -> - io_lib:format("~p has both a fuzzy and strict match", [VariableDefinition]); -xlate({unknown_variable, Variable}) -> - ["Conf file attempted to set unknown variable: ", Variable]; -xlate({unsupported_type, Type}) -> - io_lib:format("~p is not a supported datatype", [Type]); -xlate({transform_type, Type}) -> - ["Error transforming datatype for: ", Type]; -xlate({transform_type_exception, {Type, {Class, Error}}}) -> - io_lib:format("Caught exception converting to ~p: ~p:~p", - [Type, Class, Error]); -xlate({transform_type_unacceptable, {Value, BadValue}}) -> - io_lib:format("~p is not accepted value: ~p", [Value, BadValue]); -xlate({circular_rhs, History}) -> - io_lib:format("Circular RHS substitutions: ~p", [History]); -xlate({substitution_missing_config, {Substitution, Variable}}) -> - io_lib:format("'~s' substitution requires a config variable '~s' to be set", - [Substitution, Variable]); -xlate({mapping_not_found, Variable}) -> - [Variable, " not_found"]; -xlate({mapping_multiple, {Variable, {Hard, Fuzzy}}}) -> - io_lib:format("~p hard mappings and ~p fuzzy mappings found " - "for ~s", [Hard, Fuzzy, Variable]); -xlate({validation, {Variable, Description}}) -> - [Variable, " invalid, ", Description]; -xlate({erl_parse, {Reason, LineNo}}) -> - ["Schema parse error near line number ", integer_to_list(LineNo), - ": ", Reason]; -xlate({erl_parse, Reason}) -> - io_lib:format("Schema parse error: ~p", [Reason]); -xlate({erl_parse_unexpected, Error}) -> - io_lib:format("Unexpected return from erl_parse:parse_exprs/1: ~p", - [Error]); -xlate({parse_schema, Value}) -> - io_lib:format("Unknown parse return: ~p", [Value]); -xlate({erl_scan, LineNo}) -> - ["Error scanning erlang near line ", integer_to_list(LineNo)]. - --spec contains_error(list()) -> boolean(). -contains_error(List) -> - lists:any(fun is_error/1, List). - --spec is_error(any()) -> boolean(). -is_error({error, _}) -> true; -is_error(_) -> false. - --spec filter(list()) -> errorlist(). -filter(List) -> - {errorlist, lists:filter(fun is_error/1, List)}. - --spec errorlist_maybe(any()) -> any(). -errorlist_maybe(List) when is_list(List) -> - case filter(List) of - {errorlist, []} -> - List; - Errorlist -> - Errorlist - end; -errorlist_maybe(AnythingElse) -> AnythingElse. - --spec print(string(), [any()]) -> ok. -print(FormatString, Args) -> - print(io_lib:format(FormatString, Args)). - --spec print(string() | error()) -> ok. -print({error, ErrorTerm}) -> - print(lists:flatten(xlate(ErrorTerm))); -print(String) -> - ok = ?logger:error("~s", [String]). - --ifdef(TEST). - -is_error_test() -> - ?assert(is_error({error, "oh no!"})), - ?assert(not(is_error("just an innocent string... I mean a list... I mean... argh, erlang"))), - ok. - -contains_error_test() -> - ?assert(contains_error(["hi", {error, "hi!"}, "bye"])), - ?assert(not(contains_error(["hi", "I'm not an error", "bye"]))), - ok. - -filter_test() -> - ?assertEqual({errorlist, []}, filter(["hi", "what even is an error?", "bye"])), - ?assertEqual({errorlist, [{error, "etoomanythings"}]}, - filter(["hi", {error, "etoomanythings"}, "bye"])), - ok. - -errorlist_maybe_test() -> - ?assertEqual(atom, errorlist_maybe(atom)), - ?assertEqual(12, errorlist_maybe(12)), - %% Fool you! "string" is a list!, but doesn't contain an error() - ?assertEqual("string", errorlist_maybe("string")), - - ?assertEqual( - {errorlist, [{error, "etoomanythings"}]}, - errorlist_maybe(["hi", {error, "etoomanythings"}, "bye"])), - ?assertEqual( - ["hi", "what even is an error?", "bye"], - errorlist_maybe(["hi", "what even is an error?", "bye"])), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_escript.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_escript.erl deleted file mode 100644 index b38471c7ab..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_escript.erl +++ /dev/null @@ -1,571 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_escript: used by sh scripts to parse configs -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_escript). - --define(STDOUT(Str, Args), io:format(Str ++ "~n", Args)). --define(FORMAT(Str, Args), io_lib:format(Str, Args)). --define(FORMAT_TEMPLATE, [time," [",level,"] ",msg,"\n"]). --export([main/1]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --include("cuttlefish.hrl"). --define(ENVS, [{"EMQX_NODE_NAME", "node.name"}, - {"EMQX_NODE_COOKIE", "node.cookie"}, - {"EMQX_MAX_PORTS", "node.max_ports"}, - {"EMQX_MAX_PACKET_SIZE", "mqtt.max_packet_size"}, - {"EMQX_TCP_PORT", "listener.tcp.external"}, - {"EMQX_SSL_PORT", "listener.ssl.external"}, - {"EMQX_WS_PORT", "listener.ws.external"}, - {"EMQX_WSS_PORT", "listener.wss.external"}]). - -cli_options() -> -%% Option Name, Short Code, Long Code, Argument Spec, Help Message -[ - {help, $h, "help", undefined, "Print this usage page"}, - {etc_dir, $e, "etc_dir", {string, "/etc"}, "etc dir"}, - {dest_dir, $d, "dest_dir", string, "specifies the directory to write the config file to"}, - {dest_file, $f, "dest_file", {string, "app"}, "the file name to write"}, - {schema_dir, $s, "schema_dir", string, "a directory containing .schema files"}, - {schema_file, $i, "schema_file", string, "individual schema file, will be processed in command line order, after -s"}, - {conf_file, $c, "conf_file", string, "a cuttlefish conf file, multiple files allowed"}, - {app_config, $a, "app_config", string, "the advanced erlangy app.config"}, - {log_level, $l, "log_level", {string, "notice"}, "log level for cuttlefish output"}, - {print_schema, $p, "print", undefined, "prints schema mappings on stderr"}, - {max_history, $m, "max_history", {integer, 3}, "the maximum number of generated config files to keep"} -]. - -%% LOL! I wanted this to be halt 0, but honestly, if this escript does anything -%% except return the path to a generated config file, it should return a non-zero -%% return code -print_help() -> - getopt:usage(cli_options(), - escript:script_name()), - stop_deactivate(). - -parse_and_command(Args) -> - {ParsedArgs, Extra} = case getopt:parse(cli_options(), Args) of - {ok, {P, H}} -> {P, H}; - _ -> {[help], []} - end, - {Command, ExtraArgs} = case {lists:member(help, ParsedArgs), Extra} of - {false, []} -> {generate, []}; - {false, [Cmd|E]} -> {list_to_atom(Cmd), E}; - _ -> {help, []} - end, - {Command, ParsedArgs, ExtraArgs}. - -%% @doc main method for generating erlang term config files -main(Args) -> - {Command, ParsedArgs, Extra} = parse_and_command(Args), - - SuggestedLogLevel = list_to_atom(proplists:get_value(log_level, ParsedArgs)), - LogLevel = case lists:member(SuggestedLogLevel, [debug, info, notice, warning, - error, critical, alert, emergency]) of - true -> SuggestedLogLevel; - _ -> notice - end, - logger:remove_handler(default), - logger:add_handler(cuttlefish, logger_std_h, - #{config => #{type =>standard_error}, - formatter => {logger_formatter, - #{legacy_header => false, - single_line => true, - template => ?FORMAT_TEMPLATE}}, - filter_default => log, - filters => [], - level => all - }), - - logger:set_primary_config(level, LogLevel), - case Command of - help -> - print_help(); - generate -> - generate(ParsedArgs); - effective -> - effective(ParsedArgs); - describe -> - describe(ParsedArgs, Extra); - _Other -> - print_help() - end. - -%% This shows the effective configuration, including defaults -effective(ParsedArgs) -> - ?logger:debug("cuttlefish `effective`", []), - EtcDir = proplists:get_value(etc_dir, ParsedArgs), - - %% Should we even show this? - {AppConfigExists, ExistingAppConfigName} = check_existence(EtcDir, "app.config"), - {VMArgsExists, ExistingVMArgsName} = check_existence(EtcDir, "vm.args"), - - case {AppConfigExists, VMArgsExists} of - {false, false} -> - AdvancedConfigFile = filename:join(EtcDir, "advanced.config"), - AdvConfig = case filelib:is_file(AdvancedConfigFile) of - true -> - ?logger:debug("~s/advanced.config detected, overlaying proplists", [EtcDir]), - case file:consult(AdvancedConfigFile) of - {ok, [AdvancedConfig]} -> - AdvancedConfig; - {error, Error} -> - ?logger:error("Error parsing advanced.config: ~s", [file:format_error(Error)]), - stop_deactivate() - end; - _ -> - [] - end, - - EffectiveConfig = cuttlefish_effective:build( - load_conf(ParsedArgs), - load_schema(ParsedArgs), - AdvConfig), - _ = [ ?STDOUT(Line, []) || Line <- EffectiveConfig], - ok; - _ -> - ?STDOUT("Disabling cuttlefish, legacy configuration files found:", []), - case AppConfigExists of - true -> - ?STDOUT(" ~s", [ExistingAppConfigName]); - _ -> - ok - end, - case VMArgsExists of - true -> - ?STDOUT(" ~s", [ExistingVMArgsName]); - _ -> - ok - end, - ?STDOUT("Effective config is only visible for cuttlefish conf files.", []) - end, - ok. - -%% This is the function that dumps the docs for a single setting -describe(_ParsedArgs, []) -> - %% No query, you get nothing. - ?STDOUT("cuttlefish's describe command required a variable to query.", []), - ?STDOUT("Try `describe setting.name`", []), - stop_deactivate(); -describe(ParsedArgs, [Query|_]) when is_list(Query) -> - QDef = cuttlefish_variable:tokenize(Query), - - ?logger:debug("cuttlefish describe '~s'", [Query]), - {_, Mappings, _} = load_schema(ParsedArgs), - - FindResults = fun(QueryVar) -> - lists:filter( - fun(X) -> - cuttlefish_variable:is_fuzzy_match(QueryVar, cuttlefish_mapping:variable(X)) - end, - Mappings) - end, - - case FindResults(QDef) of - [] -> - ?STDOUT("Variable '~s' not found", [Query]); - [Match|_] -> - ?STDOUT("Documentation for ~s", [cuttlefish_variable:format(cuttlefish_mapping:variable(Match))]), - _ = case {cuttlefish_mapping:doc(Match), cuttlefish_mapping:see(Match)} of - {[], []} -> - ok; - {[], See} -> - _ = [ begin - M = hd(FindResults(S)), - [ ?STDOUT("~s", [Line]) || Line <- cuttlefish_mapping:doc(M)] - end || S <- See], - ok; - {Docs, []} -> - [ ?STDOUT("~s", [Line]) || Line <- Docs]; - {Docs, See} -> - _ = [ ?STDOUT("~s", [Line]) || Line <- Docs], - ?STDOUT("See also:", []), - [?STDOUT(" ~s", [cuttlefish_variable:format(S)]) || S <- See] - end, - ?STDOUT("", []), - ValidValues = [ - ?FORMAT("~n - ~s", [cuttlefish_conf:pretty_datatype(Type)]) || - Type <- lists:flatten([cuttlefish_mapping:datatype(Match)]) ], - ?STDOUT(" Valid Values: ~s", [ValidValues]), - case cuttlefish_mapping:has_default(Match) of - true -> - ?STDOUT(" Default Value : ~s", - [format_datatype(cuttlefish_mapping:default(Match), - cuttlefish_mapping:datatype(Match))]); - false -> - ?STDOUT(" No default set", []) - end, - Conf = load_conf(ParsedArgs), - case lists:keyfind(QDef, 1, Conf) of - false -> - ConfFile = proplists:get_value(conf_file, ParsedArgs), - ?STDOUT(" Value not set in ~s", [ConfFile]); - {_, CValue} -> - ConfiguredValue = format_datatype(CValue, cuttlefish_mapping:datatype(Match)), - ?STDOUT(" Set Value : ~s", [ConfiguredValue]) - end, - ?STDOUT(" Internal key : ~s", [cuttlefish_mapping:mapping(Match)]) - end, - stop_deactivate(). - --ifndef(TEST). -stop_deactivate() -> - init:stop(1), - timer:sleep(250), - stop_deactivate(). - -stop_ok() -> - init:stop(0). --endif. - --ifdef(TEST). -%% In test mode we don't want to kill the test VM prematurely. -stop_deactivate() -> - throw(stop_deactivate). - -stop_ok() -> - ok. --endif. - -generate(ParsedArgs) -> - EtcDir = proplists:get_value(etc_dir, ParsedArgs), - - {AppConfigExists, ExistingAppConfigName} = check_existence(EtcDir, "app.config"), - {VMArgsExists, ExistingVMArgsName} = check_existence(EtcDir, "vm.args"), - - %% If /etc/app.config exists, use it and disable cuttlefish - %% even though cuttlefish is awesome - FilesToUse = case {AppConfigExists, VMArgsExists} of - {true, true} -> - ?logger:info("~s and ~s exists, disabling cuttlefish.", [ExistingAppConfigName, ExistingVMArgsName]), - ?logger:info("If you'd like to know more about cuttlefish, check your local library!", []), - ?logger:info(" or see http://github.com/basho/cuttlefish", []), - {ExistingAppConfigName, ExistingVMArgsName}; - {true, false} -> - ?logger:info("~s exists, generating vm.args", [ExistingAppConfigName]), - {_, NewVMArgs} = engage_cuttlefish(ParsedArgs), - {ExistingAppConfigName, NewVMArgs}; - {false, true} -> - ?logger:info("~s exists, generating app.config", [ExistingVMArgsName]), - {NewAppConfig, _} = engage_cuttlefish(ParsedArgs), - {NewAppConfig, ExistingVMArgsName}; - _ -> - ?logger:info("No app.config or vm.args detected in ~s, activating cuttlefish", [EtcDir]), - engage_cuttlefish(ParsedArgs) - end, - - case FilesToUse of - %% this is nice and all, but currently all error paths of engage_cuttlefish end with - %% stop_deactivate() hopefully factor that to be cleaner. - error -> - stop_deactivate(); - {AppConf, VMArgs} -> - %% Note: we have added a parameter '-vm_args' to this. It appears redundant - %% but it is not! the erlang vm allows us to access all arguments to the erl - %% command EXCEPT '-args_file', so in order to get access to this file location - %% from within the vm, we need to pass it in twice. - ?STDOUT(" -config ~s -args_file ~s -vm_args ~s ", [AppConf, VMArgs, VMArgs]), - stop_ok() - end. - -load_schema(ParsedArgs) -> - SchemaDir = proplists:get_value(schema_dir, ParsedArgs), - - SchemaDirFiles = case SchemaDir of - undefined -> []; - _ -> [ filename:join(SchemaDir, Filename) || Filename <- filelib:wildcard("*.schema", SchemaDir)] - end, - IndividualSchemaFiles = proplists:get_all_values(schema_file, ParsedArgs), - SchemaFiles = SchemaDirFiles ++ IndividualSchemaFiles, - - SortedSchemaFiles = lists:sort(fun(A,B) -> A < B end, SchemaFiles), - case length(SortedSchemaFiles) of - 0 -> - ?logger:debug("No Schema files found in specified", []), - stop_deactivate(); - _ -> - ?logger:debug("SchemaFiles: ~p", [SortedSchemaFiles]) - end, - - Schema = cuttlefish_schema:files(SortedSchemaFiles), - case proplists:is_defined(print_schema, ParsedArgs) of - true -> - _ = print_schema(Schema), - Schema; - _ -> - Schema - end. - -load_conf(ParsedArgs) -> - ConfFiles = proplists:get_all_values(conf_file, ParsedArgs), - ?logger:debug("ConfFiles: ~p", [ConfFiles]), - case cuttlefish_conf:files(ConfFiles) of - {errorlist, Errors} -> - _ = [ ?logger:error(cuttlefish_error:xlate(E)) || - {error, E} <- Errors], - stop_deactivate(), - {errorlist, Errors}; - GoodConf -> - GoodConf - end. - -change_conf(Conf) -> - change_conf(Conf, ?ENVS). - -change_conf(Conf, []) -> - Conf; -change_conf(Conf, [{Env, Key} | Envs]) -> - case os:getenv(Env) of - false -> change_conf(Conf, Envs); - Value -> - NKey = cuttlefish_variable:tokenize(Key), - NConf = case lists:keyfind(NKey, 1, Conf) of - false -> Conf ++ [{NKey, Value}]; - _ -> lists:keyreplace(NKey, 1, Conf, {NKey, Value}) - end, - change_conf(NConf, Envs) - end. - - - --spec writable_destination_path([proplists:property()]) -> file:filename() | error. -writable_destination_path(ParsedArgs) -> - EtcDir = proplists:get_value(etc_dir, ParsedArgs), - DestinationPath = proplists:get_value(dest_dir, ParsedArgs, filename:join(EtcDir, "generated")), - AbsoluteDestPath = case DestinationPath of - [$/|_] -> DestinationPath; - _ -> filename:join(element(2,file:get_cwd()), DestinationPath) - end, - %% Check Permissions - case filelib:ensure_dir(filename:join(AbsoluteDestPath, "weaksauce.dummy")) of - %% filelib:ensure_dir/1 requires a dummy filename in the argument, - %% I think that is weaksauce, hence "weaksauce.dummy" - ok -> - AbsoluteDestPath; - {error, E} -> - ?logger:error( - "Error creating ~s: ~s", - [AbsoluteDestPath, file:format_error(E)]), - error - end. - --spec engage_cuttlefish([proplists:property()]) -> {string(), string()} | error. -engage_cuttlefish(ParsedArgs) -> - EtcDir = proplists:get_value(etc_dir, ParsedArgs), - - AbsPath = case writable_destination_path(ParsedArgs) of - error -> - stop_deactivate(), - error; - Path -> Path - end, - - Date = calendar:local_time(), - - DestinationFilename = filename_maker(proplists:get_value(dest_file, ParsedArgs), Date, "config"), - Destination = filename:join(AbsPath, DestinationFilename), - - DestinationVMArgsFilename = filename_maker("vm", Date, "args"), - DestinationVMArgs = filename:join(AbsPath, DestinationVMArgsFilename), - - ?logger:debug("Generating config in: ~p", [Destination]), - - Schema = load_schema(ParsedArgs), - ConfFile = proplists:get_value(conf_file, ParsedArgs), - Conf = change_conf(load_conf(ParsedArgs)), - NewConfig = case cuttlefish_generator:map(Schema, Conf, ConfFile) of - {error, Phase, {errorlist, Errors}} -> - ?logger:error("Error generating configuration in phase ~s", [Phase]), - _ = [ cuttlefish_error:print(E) || E <- Errors], - stop_deactivate(); - ValidConfig -> ValidConfig - end, - - AdvancedConfigFile = filename:join(EtcDir, "advanced.config"), - FinalConfig = case filelib:is_file(AdvancedConfigFile) of - true -> - ?logger:info("~s/advanced.config detected, overlaying proplists", [EtcDir]), - case file:consult(AdvancedConfigFile) of - {ok, [AdvancedConfig]} -> - cuttlefish_advanced:overlay(NewConfig, AdvancedConfig); - {ok, OtherTerms} -> - ?logger:error("Error parsing ~s, incorrect format: ~p", [AdvancedConfigFile, OtherTerms]), - stop_deactivate(); - {error, Error} -> - ?logger:error("Error parsing ~s: ~s", [AdvancedConfigFile, file:format_error(Error)]), - stop_deactivate() - end; - _ -> - %% Nothing to see here, these aren't the droids you're looking for. - NewConfig - end, - - case FinalConfig of - {error, _X} -> - error; - _ -> - FinalAppConfig = proplists:delete(vm_args, FinalConfig), - FinalVMArgs = cuttlefish_vmargs:stringify(proplists:get_value(vm_args, FinalConfig)), - - %% Prune excess files - MaxHistory = proplists:get_value(max_history, ParsedArgs, 3) - 1, - prune(Destination, MaxHistory), - prune(DestinationVMArgs, MaxHistory), - - case { file:write_file(Destination, io_lib:fwrite("~p.\n",[FinalAppConfig])), - file:write_file(DestinationVMArgs, string:join(FinalVMArgs, "\n"))} of - {ok, ok} -> - {Destination, DestinationVMArgs}; - {Err1, Err2} -> - maybe_log_file_error(Destination, Err1), - maybe_log_file_error(DestinationVMArgs, Err2), - error - end - - end. - --spec prune(file:name_all(), integer()) -> ok. -prune(Filename, MaxHistory) -> - %% A Filename comes in /Abs/Path/To/something.YYYY.MM.DD.HH.mm.SS.ext - %% We want `ls /Abs/Path/To/something.*.ext and delete all but the most - %% recent MaxHistory - Path = filename:dirname(Filename), - Ext = filename:extension(Filename), - Base = hd(string:tokens(filename:basename(Filename, Ext), ".")), - Files = - lists:sort(filelib:wildcard(Base ++ ".*" ++ Ext, Path)), - - delete([ filename:join([Path, F]) || F <- Files], MaxHistory), - ok. - --spec delete(file:name_all(), integer()) -> ok. -delete(Files, MaxHistory) when length(Files) =< MaxHistory -> - ok; -delete([File|Files], MaxHistory) -> - case file:delete(File) of - ok -> ok; - {error, Reason} -> - ?logger:error("Could not delete ~s, ~p", [File, Reason]) - end, - delete(Files, MaxHistory). - --spec maybe_log_file_error( - file:filename(), ok | - {error, file:posix() %% copied from file:format_error/1 - | badarg - | terminated - | system_limit - | { integer(), module(), term() }}) -> ok. -maybe_log_file_error(_, ok) -> - ok; -maybe_log_file_error(Filename, {error, Reason}) -> - ?logger:error("Error writing ~s: ~s", [Filename, file:format_error(Reason)]), - ok. - --spec check_existence(string(), string()) -> {boolean(), string()}. -check_existence(EtcDir, Filename) -> - FullName = filename:join(EtcDir, Filename), %% Barfolomew - Exists = filelib:is_file(FullName), - ?logger:info("Checking ~s exists... ~p", [FullName, Exists]), - {Exists, FullName}. - -filename_maker(Filename, Date, Extension) -> - {{Y, M, D}, {HH, MM, SS}} = Date, - _DestinationFilename = - io_lib:format("~s.~p.~s.~s.~s.~s.~s.~s", - [Filename, - Y, - zero_pad(M), - zero_pad(D), - zero_pad(HH), - zero_pad(MM), - zero_pad(SS), - Extension - ]). - -zero_pad(Integer) -> - S = integer_to_list(Integer), - case Integer > 9 of - true -> S; - _ -> [$0|S] - end. - -print_schema(Schema) -> - ?logger:info("Printing Schema Mappings"), - {_, Mappings, _} = Schema, - - {Max, ListOfMappings} = lists:foldr( - fun(M, {OldMax, List}) -> - CandidateMax = length(cuttlefish_mapping:mapping(M)), - NewMax = case CandidateMax > OldMax of - true -> CandidateMax; - _ -> OldMax - end, - {NewMax, [{cuttlefish_mapping:mapping(M), cuttlefish_variable:format(cuttlefish_mapping:variable(M))}|List]} - end, - {0, []}, - Mappings - ), - [ - io:format(standard_error, "~s ~s~n", - [string:left(M, Max+2, $\s), V]) - || {M, V} <- ListOfMappings]. - -format_datatype(Value, Datatypes) when is_list(Datatypes) -> - %% We're not sure which datatype the default or set value is going - %% to match, so let's find one that does. - [H|_] = lists:dropwhile( - fun(D0) -> - D = cuttlefish_datatypes:extended_from(D0), - case cuttlefish_datatypes:from_string(Value, D) of - {error, _} -> true; - _ -> false - end - end, Datatypes), - format_datatype(Value, cuttlefish_datatypes:extended_from(H)); -format_datatype(Value, Datatype) -> - cuttlefish_datatypes:to_string(cuttlefish_datatypes:from_string(Value, Datatype), Datatype). - - --ifdef(TEST). - -zero_pad_test() -> - ?assertEqual("00", zero_pad(0)), - ?assertEqual("01", zero_pad(1)), - ?assertEqual("02", zero_pad(2)), - ?assertEqual("03", zero_pad(3)), - ?assertEqual("04", zero_pad(4)), - ?assertEqual("05", zero_pad(5)), - ?assertEqual("06", zero_pad(6)), - ?assertEqual("07", zero_pad(7)), - ?assertEqual("08", zero_pad(8)), - ?assertEqual("09", zero_pad(9)), - ?assertEqual("10", zero_pad(10)), - ?assertEqual("11", zero_pad(11)), - ?assertEqual("12", zero_pad(12)), - ok. - - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_flag.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_flag.erl deleted file mode 100644 index b0f60450de..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_flag.erl +++ /dev/null @@ -1,94 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_flag: datatype for simple boolean settings with -%% customizable names and values -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --module(cuttlefish_flag). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([ - parse/1, - parse/2, - to_string/2 - ]). - --define(FMT(F, A), lists:flatten(io_lib:format(F, A))). - -parse(Value) -> - cuttlefish_enum:parse(Value, to_enum(flag)). -parse(Value, Flag) -> - cuttlefish_enum:parse(Value, to_enum(Flag)). - -to_string(Value, Flag) -> - cuttlefish_enum:to_string(Value, to_enum(Flag)). - -to_enum({flag, {On, OnValue}, {Off, OffValue}}) -> - {enum, [{On, OnValue}, {Off, OffValue}]}; -to_enum({flag, On, Off}) -> - {enum, [{On, true}, {Off, false}]}; -to_enum(flag) -> - {enum, [{on, true}, {off, false}]}. - --ifdef(TEST). -parse_test() -> - ?assertEqual(true, parse("on")), - ?assertEqual(false, parse("off")), - ?assertEqual(true, parse("enabled", {flag, enabled, disabled})), - ?assertEqual(false, parse("disabled", {flag, enabled, disabled})), - ?assertEqual(tyk, parse("on", {flag, {on, tyk}, {off, torp}})), - ?assertEqual(torp, parse("off", {flag, {on, tyk}, {off, torp}})), - ?assertEqual({long, tuple, value}, - parse("foo", {flag, {simple, ok}, - {foo, {long, tuple, value}}})), - ?assertEqual(ok, - parse("simple", {flag, {simple, ok}, - {foo, {long, tuple, value}}})). - -to_string_test() -> - ?assertEqual(to_string(true, flag), "on"), - ?assertEqual(to_string(on, flag), "on"), - ?assertEqual(to_string(false, flag), "off"), - ?assertEqual(to_string(off, flag), "off"), - ?assertEqual(to_string(true, {flag, enabled, disabled}), "enabled"), - ?assertEqual(to_string(enabled, {flag, enabled, disabled}), "enabled"), - ?assertEqual(to_string(false, {flag, enabled, disabled}), "disabled"), - ?assertEqual(to_string(disabled, {flag, enabled, disabled}), "disabled"), - ?assertEqual(to_string(tyk, {flag, {on, tyk}, {off, torp}}), "on"), - ?assertEqual(to_string(on, {flag, {on, tyk}, {off, torp}}), "on"), - ?assertEqual(to_string(torp, {flag, {on, tyk}, {off, torp}}), "off"), - ?assertEqual(to_string(off, {flag, {on, tyk}, {off, torp}}), "off"), - ?assertEqual(to_string({long, tuple, value}, {flag, {simple, ok}, - {foo, {long, tuple, value}}}), - "foo"), - ?assertEqual(to_string(foo, {flag, {simple, ok}, - {foo, {long, tuple, value}}}), - "foo"), - ?assertEqual(to_string(ok, {flag, {simple, ok}, - {foo, {long, tuple, value}}}), - "simple"), - ?assertEqual(to_string(simple, {flag, {simple, ok}, - {foo, {long, tuple, value}}}), - "simple"). --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_generator.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_generator.erl deleted file mode 100644 index 1bb97b3df6..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_generator.erl +++ /dev/null @@ -1,1265 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_generator: this is where the action is -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_generator). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --define(FMT(F,A), lists:flatten(io_lib:format(F,A))). - --define(LSUB, "$("). --define(RSUB, ")"). --define(LSUBLEN, 2). --define(RSUBLEN, 1). - --export([map/2, map/3, find_mapping/2, add_defaults/2, minimal_map/2]). - --include("cuttlefish.hrl"). - --spec map(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - [proplists:property()] | - {error, atom(), cuttlefish_error:errorlist()}. -map(Schema, Config) -> - map(Schema, Config, undefined). - -map(Schema, Config, ConfFile) -> - IncludeFile = lists:filter(fun({K, _}) -> K =:= include_file end, Config), - AllConfig = merge_include_conf(Config -- IncludeFile, IncludeFile, ConfFile), - map_add_defaults(Schema, AllConfig). - -merge_include_conf(Config, [], _ConfFile) -> - Config; -merge_include_conf(Config, [{_, File0} | IncludeFiles], ConfFile) -> - File = case os:type() of - {win32, _} -> - case string:split(ConfFile, "etc", trailing) of - [Head| _] -> filename:join([Head, File0]); - _ -> File0 - end; - _ -> - File0 - end, - IncludeConfig = cuttlefish_conf:file(File), - MergeConfigs = lists:ukeymerge(1, lists:sort(Config), lists:sort(IncludeConfig)), - merge_include_conf(MergeConfigs, IncludeFiles, ConfFile). - -%% @doc Generates an Erlang config that only includes the settings -%% encompassed by the passed Config, excluding defaults from the -%% schema for unspecified settings. --spec minimal_map(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - [proplists:property()] | {error, atom(), cuttlefish_error:errorlist()}. -minimal_map({AllTranslations,AllMappings,V}, Config) -> - ConfigKeys = sets:from_list([K || {K, _} <- Config]), - {RestrictedMappings, MappingKeys} = lists:foldr(fun(M,Acc) -> - restrict_mappings(M, Acc, ConfigKeys) - end, {[], sets:new()}, AllMappings), - RestrictedTranslations = [ T || T <- AllTranslations, - sets:is_element(cuttlefish_translation:mapping(T), MappingKeys)], - map({RestrictedTranslations,RestrictedMappings,V}, Config). - -restrict_mappings(M, {Mappings, Keys}, ConfigKeys) -> - case sets:is_element(cuttlefish_mapping:variable(M), ConfigKeys) of - true -> - {[M|Mappings], sets:add_element(cuttlefish_mapping:mapping(M), Keys)}; - false -> - {Mappings, Keys} - end. - --spec map_add_defaults(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - [proplists:property()] | - {error, atom(), cuttlefish_error:errorlist()}. -map_add_defaults({_, Mappings, _} = Schema, Config) -> - - %% Config at this point is just what's in the .conf file. - %% add_defaults/2 rolls the default values in from the schema - ?logger:debug("Adding Defaults"), - DConfig = add_defaults(Config, Mappings), - case cuttlefish_error:errorlist_maybe(DConfig) of - {errorlist, EList} -> - {error, add_defaults, {errorlist, EList}}; - _ -> - map_value_sub(Schema, DConfig) - end. - --spec map_value_sub(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - [proplists:property()] | - {error, atom(), cuttlefish_error:errorlist()}. -map_value_sub(Schema, Config) -> - ?logger:debug("Right Hand Side Substitutions"), - case value_sub(Config) of - {SubbedConfig, []} -> - map_transform_datatypes(Schema, SubbedConfig); - {_, EList} -> - {error, rhs_subs, {errorlist, EList}} - end. - --spec map_transform_datatypes(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - [proplists:property()] | - {error, atom(), cuttlefish_error:errorlist()}. -map_transform_datatypes({_, Mappings, _} = Schema, DConfig) -> - %% Everything in DConfig is of datatype "string", - %% transform_datatypes turns them into other erlang terms - %% based on the schema - ?logger:debug("Applying Datatypes"), - case transform_datatypes(DConfig, Mappings) of - {NewConf, []} -> - map_validate(Schema, NewConf); - {_, EList} -> - {error, transform_datatypes, {errorlist, EList}} - end. - --spec map_validate(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - [proplists:property()] | - {error, atom(), cuttlefish_error:errorlist()}. -map_validate(Schema, Conf) -> - %% Any more advanced validators - ?logger:debug("Validation"), - case cuttlefish_error:errorlist_maybe(run_validations(Schema, Conf)) of - {errorlist, EList} -> - {error, validation, {errorlist, EList}}; - true -> - {DirectMappings, TranslationsToDrop} = apply_mappings(Schema, Conf), - apply_translations(Schema, Conf, DirectMappings, TranslationsToDrop) - end. - --spec apply_mappings(cuttlefish_schema:schema(), cuttlefish_conf:conf()) -> - {[proplists:property()], [string()]}. -apply_mappings({Translations, Mappings, _Validators}, Conf) -> - %% This fold handles 1:1 mappings, that have no cooresponding translations - %% The accumlator is the app.config proplist that we start building from - %% these 1:1 mappings, hence the return "DirectMappings". - %% It also builds a list of "TranslationsToDrop". It's basically saying that - %% if a user didn't actually configure this setting in the .conf file and - %% there's no default in the schema, then there won't be enough information - %% during the translation phase to succeed, so we'll earmark it to be skipped - {DirectMappings, {TranslationsToMaybeDrop, TranslationsToKeep}} = lists:foldr( - fun(MappingRecord, {ConfAcc, {MaybeDrop, Keep}}) -> - Mapping = cuttlefish_mapping:mapping(MappingRecord), - Default = cuttlefish_mapping:default(MappingRecord), - Variable = cuttlefish_mapping:variable(MappingRecord), - case { - Default =/= undefined orelse cuttlefish_conf:is_variable_defined(Variable, Conf), - lists:any( - fun(T) -> - cuttlefish_translation:mapping(T) =:= Mapping - end, - Translations) - } of - {true, false} -> - Tokens = cuttlefish_variable:tokenize(Mapping), - NewValue = proplists:get_value(Variable, Conf), - {set_value(Tokens, ConfAcc, NewValue), - {MaybeDrop, ordsets:add_element(Mapping,Keep)}}; - {true, true} -> - {ConfAcc, {MaybeDrop, ordsets:add_element(Mapping,Keep)}}; - _ -> - {ConfAcc, {ordsets:add_element(Mapping,MaybeDrop), Keep}} - end - end, - {[], {ordsets:new(),ordsets:new()}}, - Mappings), - ?logger:debug("Applied 1:1 Mappings"), - - TranslationsToDrop = TranslationsToMaybeDrop -- TranslationsToKeep, - {DirectMappings, TranslationsToDrop}. - --spec apply_translations(cuttlefish_schema:schema(), cuttlefish_conf:conf(), [proplists:property()], [string()]) -> - [proplists:property()] | - {error, atom(), cuttlefish_error:errorlist()}. -apply_translations({Translations, _, _} = Schema, Conf, DirectMappings, TranslationsToDrop) -> - %% The fold handles the translations. After we've build the DirectMappings, - %% we use that to seed this fold's accumulator. As we go through each translation - %% we write that to the `app.config` that lives in the accumutator. - {Proplist, Errorlist} = lists:foldl(fold_apply_translation(Conf, Schema, TranslationsToDrop), - {DirectMappings, []}, Translations), - case Errorlist of - [] -> - ?logger:debug("Applied Translations"), - Proplist; - Es -> - {error, apply_translations, {errorlist, Es}} - end. - - -fold_apply_translation(Conf, Schema, TranslationsToDrop) -> - fun(TranslationRecord, {Acc, Errors}) -> - Mapping = cuttlefish_translation:mapping(TranslationRecord), - Xlat = cuttlefish_translation:func(TranslationRecord), - case lists:member(Mapping, TranslationsToDrop) of - false -> - {XlatFun, XlatArgs} = prepare_translation_fun(Conf, Schema, - Mapping, Xlat), - ?logger:debug("Running translation for ~s", [Mapping]), - case try_apply_translation(Mapping, XlatFun, XlatArgs) of - unset -> - {Acc, Errors}; - {set, NewValue} -> - {set_value(cuttlefish_variable:tokenize(Mapping), Acc, NewValue), Errors}; - {error, Term} -> - {Acc, [{error, Term}|Errors]} - end; - _ -> - ?logger:debug("~p in Translations to drop...", [Mapping]), - {Acc, Errors} - end - end. - -prepare_translation_fun(Conf, Schema, Mapping, Xlat) -> - case proplists:get_value(arity, erlang:fun_info(Xlat)) of - 1 -> - {_, Mappings, _} = Schema, - Mappings0 = lists:foldl(fun(M, Acc1) -> - case cuttlefish_mapping:mapping(M) == Mapping of - true -> [cuttlefish_mapping:variable(M) | Acc1]; - false -> Acc1 - end - end, [], Mappings), - Conf1 = lists:filter(fun({Key, _}) -> - lists:any(fun(I) -> cuttlefish_variable:is_fuzzy_match(Key, I) end, Mappings0) - end, Conf), - {Xlat, [Conf1]}; - 2 -> - {Xlat, [Conf, Schema]}; - 3 -> - {_, Mappings, _} = Schema, - Mappings0 = lists:foldl(fun(M, Acc1) -> - case cuttlefish_mapping:mapping(M) == Mapping of - true -> [cuttlefish_mapping:variable(M) | Acc1]; - false -> Acc1 - end - end, [], Mappings), - Conf1 = lists:filter(fun({Key, _}) -> - lists:any(fun(I) -> cuttlefish_variable:is_fuzzy_match(Key, I) end, Mappings0) - end, Conf), - {Xlat, [Conf1, Schema, Conf]}; - _OtherArity -> - {fun() -> cuttlefish:invalid("translation fun can only have 1-3 arties") end, []} - end. - -try_apply_translation(Mapping, XlatFun, XlatArgs) -> - try erlang:apply(XlatFun, XlatArgs) of - {ok, Value} -> - {set, Value}; - X -> - {set, X} - catch - %% cuttlefish:conf_get/2 threw not_found - throw:{not_found, NotFound} -> - {error, {translation_missing_setting, - {Mapping, cuttlefish_variable:format(NotFound)}}}; - %% For explicitly omitting an output setting. - %% See cuttlefish:unset/0 - throw:unset -> - unset; - %% For translations that found invalid - %% settings, even after mapping. See - %% cuttlefish:invalid/1. - throw:{invalid, Invalid} -> - {error, {translation_invalid_configuration, - {Mapping, Invalid}}}; - %% Any unknown error, perhaps caused by stdlib - %% stuff. - E:R -> - {error, {translation_unknown_error, - {Mapping, {E, R}}}} - end. - -%for each token, is it special? -% -%if yes, special processing -%if no, recurse into this with the value from the proplist and tail of tokens -% -%unless the tail of tokens is [] - -%% This is the last token, so things ends with replacing the proplist value. -set_value([LastToken], Acc, NewValue) -> - cuttlefish_util:replace_proplist_value(list_to_atom(LastToken), NewValue, Acc); -%% This is the case of all but the last token. -%% recurse until you hit a leaf. -set_value([HeadToken|MoreTokens], PList, NewValue) -> - Token = list_to_atom(HeadToken), - OldValue = proplists:get_value(Token, PList, []), - cuttlefish_util:replace_proplist_value( - Token, - set_value(MoreTokens, OldValue, NewValue), - PList). - -%% @doc adds default values from the schema when something's not -%% defined in the Conf, to give a complete app.config -add_defaults(Conf, Mappings) -> - Prefixes = get_possible_values_for_fuzzy_matches(Conf, Mappings), - - lists:foldl( - fun(MappingRecord, Acc) -> - case cuttlefish_mapping:has_default(MappingRecord) of - false -> Acc; - true -> add_default(Conf, Prefixes, MappingRecord, Acc) - end - end, - Conf, Mappings). - -add_default(Conf, Prefixes, MappingRecord, Acc) -> - Default = cuttlefish_mapping:default(MappingRecord), - VariableDef = cuttlefish_mapping:variable(MappingRecord), - IsFuzzyMatch = cuttlefish_mapping:is_fuzzy_variable(MappingRecord), - IsStrictMatch = lists:keymember(VariableDef, 1, Conf), - - %% No, then plug in the default - case {IsStrictMatch, IsFuzzyMatch} of - %% Strict match means we have the setting already - {true, false} -> Acc; - - %% If IsStrictMatch =:= false, IsFuzzyMatch =:= true, we've got a setting, but - %% it's part of a complex data structure. - {false, true} -> - add_fuzzy_default(Prefixes, Acc, Default, VariableDef); - - %% If Match =:= FuzzyMatch =:= false, use the default, key not set in .conf - {false, false} -> [{VariableDef, Default}|Acc]; - - %% If Match =:= true, do nothing, the value is set in the .conf file - _ -> - %% TODO: Handle with more style and grace - ?logger:error("Both fuzzy and strict match! should not happen"), - [{error, {map_multiple_match, VariableDef}}|Acc] - end. - -is_strict_prefix([H|T1], [H|T2]) -> - is_strict_prefix(T1, T2); -is_strict_prefix([], [H2|_]) when hd(H2) =:= $$ -> - true; -is_strict_prefix(_, _) -> - false. - -add_fuzzy_default(Prefixes, Conf, Default, VariableDef) -> - PotentialMatch = lists:dropwhile(fun({Prefix, _}) -> - not is_strict_prefix(Prefix, VariableDef) - end, Prefixes), - case PotentialMatch of - %% None of the prefixes match, so we don't generate a default. - [] -> Conf; - [{_Prefix, Substitutions}|_] -> - %% This means that we found the key. - %% ToAdd will be the list of all the things we're adding to the defaults. - %% So, let's say you have the following mappings defined: - %% namespace.$named_thing.a - %% namespace.$named_thing.b - %% namespace.$named_thing.c - - %% and in your conf, you defined the following: - %% namespace.strong_bad.a = 10 - %% namespace.senor_cardgage.b = percent_sign - %% namespace.trogdor.c = burninate - - %% Well, Prefixes would look like this: - %% [{"namespace", ["strong_bad", "senor_cardgage", "trogdor"]}] - - %% The ToAdd list comp is going through and saying: ok, I know there are - %% defaults for namespace.$named_thing.a, b, and c. And I know the possible - %% values of $named_thing are strong_bad, senor_cardgage, and trogdor. - %% so I want to ensure that there are values for the following: - %% - %% namespace.strong_bad.a - %% namespace.strong_bad.b - %% namespace.strong_bad.c - %% namespace.senor_cardgage.a - %% namespace.senor_cardgage.b - %% namespace.senor_cardgage.c - %% namespace.trogdor.a - %% namespace.trogdor.b - %% namespace.trogdor.c - - %% So, we go through the List of possible substitutions - %% and apply the substitution to the variable. If it - %% already exists in the Conf, then we skip it, otherwise - %% we include the Default value. - ToAdd = [ {VariableToAdd, Default} - || Subst <- Substitutions, - VariableToAdd <- [cuttlefish_variable:replace_match(VariableDef, Subst)], - not lists:keymember(VariableToAdd, 1, Conf)], - Conf ++ ToAdd - end. - -%%%%%%%%%%%%%%%%%%%%%%%% -%% Prefixes is the thing we need for defaults of named keys -%% it looks like this: -%% -%% Prefixes: [{"riak_control.user",["user"]}, -%% {"listener.https",["internal"]}, -%% {"listener.protobuf",["internal"]}, -%% {"listener.http",["internal"]}, -%% {"multi_backend", -%% ["bitcask_mult","leveldb_mult","leveldb_mult2","memory_mult"}] -%%%%%%%%%%%%%%%%%%%%%%%% --spec get_possible_values_for_fuzzy_matches(cuttlefish_conf:conf(), [cuttlefish_mapping:mapping()]) -> [{string(), [string()]}]. -get_possible_values_for_fuzzy_matches(Conf, Mappings) -> - %% Now, get all the variables that could match, i.e. all the names - %% it found referenced in the Conf proplist. It may look something - %% like this: [{"n",["ck","ak","bk"]}] - lists:foldl( - fun(Mapping, FuzzyMatches) -> - case cuttlefish_mapping:is_fuzzy_variable(Mapping) of - false -> FuzzyMatches; %% Strict match - true -> - %% Fuzzy match, extract the matching settings from the conf - VD = cuttlefish_mapping:variable(Mapping), - ListOfVars = [Var || {_, Var} <- cuttlefish_variable:fuzzy_matches(VD, Conf)], - {Prefix, _, _} = cuttlefish_variable:split_on_match(VD), - orddict:append_list(Prefix, ListOfVars, FuzzyMatches) - end - end, - orddict:new(), - Mappings). - --spec transform_datatypes( - cuttlefish_conf:conf(), - [cuttlefish_mapping:mapping()] - ) -> {cuttlefish_conf:conf(), [cuttlefish_error:error()]}. -transform_datatypes(Conf, Mappings) -> - lists:foldl( - fun({Variable, Value}, {Acc, ErrorAcc}) -> - %% Look up mapping from schema - case find_mapping(Variable, Mappings) of - {error, _} -> - %% So, this error message isn't so performant (s/o @argv0) - %% but it shouldn't happen too often, and I think it's important - %% to give users this feedback. - - %% It will prevent anything from starting, and will let you know - %% that you're trying to set something that has no effect - VarName = cuttlefish_variable:format(Variable), - ?logger:error("You've tried to set ~s, but there is no setting with that name.", [VarName]), - ?logger:error(" Did you mean one of these?"), - - Possibilities = [ begin - MapVarName = cuttlefish_variable:format(cuttlefish_mapping:variable(M)), - {cuttlefish_util:levenshtein(VarName, MapVarName), MapVarName} - end || M <- Mappings], - Sorted = lists:sort(Possibilities), - _ = [ ?logger:error(" ~s", [T]) || {_, T} <- lists:sublist(Sorted, 3) ], - {Acc, [ {error, {unknown_variable, VarName}} | ErrorAcc ]}; - MappingRecord -> - DTs = cuttlefish_mapping:datatype(MappingRecord), - - %% DTs is a list now, which means we'll receive an - %% errorlist, not a single error - case transform_type(DTs, Value) of - {ok, NewValue} -> - {[{Variable, NewValue}|Acc], ErrorAcc}; - {errorlist, EList} -> - NewError = {transform_type, - cuttlefish_variable:format(Variable)}, - {Acc, [{error, NewError}] ++ EList ++ ErrorAcc} - end - end - end, - {[], []}, - Conf). - --spec value_sub(cuttlefish_conf:conf()) -> {cuttlefish_conf:conf(), [cuttlefish_error:error()]}. -value_sub(Conf) -> - lists:foldr( - fun({Var, Val}, {Acc, ErrorAcc}) -> - case value_sub(Var, Val, Conf) of - {error1, E} -> {Acc, [{error, E}|ErrorAcc]}; - {NewVal, _NewConf} -> {[{Var, NewVal}|Acc], ErrorAcc} - end - end, - {[],[]}, - Conf). - --spec value_sub(cuttlefish_variable:variable(), - string(), - cuttlefish_conf:conf()) -> - {string(), cuttlefish_conf:conf()} | cuttlefish_error:error(). -value_sub(Var, Value, Conf) -> - value_sub(Var, Value, Conf, []). - --spec value_sub(cuttlefish_variable:variable(), - string(), - cuttlefish_conf:conf(), - [string()]) -> - {string(), cuttlefish_conf:conf()} | cuttlefish_error:error(). -value_sub(Var, Value, Conf, History) when is_list(Value) -> - %% Check if history contains duplicates. if so error - case erlang:length(History) == sets:size(sets:from_list(History)) of - false -> - {error1, {circular_rhs, History}}; - _ -> - case head_sub(Value) of - none -> {Value, Conf}; - {sub, NextVar, {SubFront, SubBack}} -> - case proplists:get_value(NextVar, Conf) of - undefined -> - {error1, {substitution_missing_config, - {cuttlefish_variable:format(Var), - cuttlefish_variable:format(NextVar)}}}; - SubVal -> - %% Do a sub-subsitution, in case the substituted - %% value contains substitutions itself. Do this as - %% its own seperate recursion so that circular - %% subtitutions can be detected. - case value_sub(NextVar, SubVal, Conf, [Var|History]) of - {error1, _} = Error -> - Error; - {NewSubVal, NewConf} -> - NewValue = SubFront ++ NewSubVal ++ SubBack, - value_sub(Var, NewValue, NewConf, History) - end - end - end - end; -value_sub(_Var, Value, Conf, _History) -> - {Value, Conf}. - --spec head_sub(string()) -> none | {sub, cuttlefish_variable:variable(), {string(), string()}}. -head_sub(Value) -> - L = string:str(Value, ?LSUB), - case L > 0 of - false -> - none; - _ -> - R = string:str(string:substr(Value, L + ?RSUBLEN), ?RSUB) + L, - case L < R of - false -> - none; - _ -> - Var = cuttlefish_variable:tokenize(string:strip(string:substr(Value, L+?LSUBLEN, R-L-?LSUBLEN))), - Front = string:substr(Value, 1, L-1), - Back = string:substr(Value, R+?RSUBLEN), - {sub, Var, {Front, Back}} - end - end. - -%% If transform_type takes a list as first argument, foldm_either will -%% give us back an errorlist for a single error --spec transform_type(cuttlefish_datatypes:datatype_list() | cuttlefish_datatypes:datatype(), term()) -> - {ok, term()} | cuttlefish_error:error() | cuttlefish_error:errorlist(). -transform_type(DTs, Value) when is_list(DTs) -> - foldm_either(fun(DT) -> transform_type(DT, Value) end, DTs); - -transform_type(DT, Value) -> - Supported = cuttlefish_datatypes:is_supported(DT), - Extended = cuttlefish_datatypes:is_extended(DT), - if - Supported -> transform_supported_type(DT, Value); - Extended -> transform_extended_type(DT, Value); - true -> - {error, {unsupported_type, DT}} - end. - --spec transform_supported_type(cuttlefish_datatypes:datatype(), any()) -> - {ok, term()} | cuttlefish_error:error(). -transform_supported_type(DT, Value) -> - try cuttlefish_datatypes:from_string(Value, DT) of - {error, Message} -> {error, Message}; - NewValue -> {ok, NewValue} - catch - Class:Error -> - {error, {transform_type_exception, {DT, {Class, Error}}}} - end. - --spec transform_extended_type(cuttlefish_datatypes:extended(), any()) -> - {ok, term()} | cuttlefish_error:error(). -transform_extended_type({DT, AcceptableValue}, Value) -> - case transform_supported_type(DT, Value) of - {ok, AcceptableValue} -> - {ok, AcceptableValue}; - {ok, _NewValue} -> - {error, {transform_type_unacceptable, {Value, AcceptableValue}}}; - {error, Term} -> - {error, Term} - end. -%% Ok, this is tricky -%% There are three scenarios we have to deal with: -%% 1. The mapping is there! -> return mapping -%% 2. The mapping is not there -> error -%% 3. The mapping is there, but the key in the schema contains a $. -%% (fuzzy match) -find_mapping([H|_]=Variable, Mappings) when is_list(H) -> - {HardMappings, FuzzyMappings} = lists:foldl( - fun(Mapping, {HM, FM}) -> - VariableDef = cuttlefish_mapping:variable(Mapping), - case {Variable =:= VariableDef, cuttlefish_variable:is_fuzzy_match(Variable, VariableDef)} of - {true, _} -> {[Mapping|HM], FM}; - {_, true} -> {HM, [Mapping|FM]}; - _ -> {HM, FM} - end - end, - {[], []}, - Mappings), - - %% The input to this function is massaged enough that you'll never see a hard mapping count > 1 - %% You might see more than one fuzzy match, there's really nothing to stop that. - FVariable = cuttlefish_variable:format(Variable), - case {length(HardMappings), length(FuzzyMappings)} of - {1, _} -> hd(HardMappings); - {0, 1} -> hd(FuzzyMappings); - {0, 0} -> {error, {mapping_not_found, FVariable}}; - {X, Y} -> {error, {mapping_multiple, {FVariable, {X, Y}}}} - end; -find_mapping(Variable, Mappings) -> - find_mapping(cuttlefish_variable:tokenize(Variable), Mappings). - --spec run_validations(cuttlefish_schema:schema(), cuttlefish_conf:conf()) - -> boolean()|list(cuttlefish_error:error()). -run_validations({_, Mappings, Validators}, Conf) -> - Validations = lists:flatten([ begin - Vs = cuttlefish_mapping:validators(M, Validators), - Value = proplists:get_value(cuttlefish_mapping:variable(M), Conf), - [ begin - Validator = cuttlefish_validator:func(V), - case {Value, Validator(Value)} of - {undefined, _} -> true; - {_, true} -> - true; - _ -> - Error = {validation, { cuttlefish_variable:format( - cuttlefish_mapping:variable(M)), - cuttlefish_validator:description(V) - }}, - ?logger:error(cuttlefish_error:xlate(Error)), - {error, Error} - end - end || V <- Vs] - - end || M <- Mappings, - cuttlefish_mapping:validators(M) =/= [], - cuttlefish_mapping:default(M) =/= undefined orelse proplists:is_defined(cuttlefish_mapping:variable(M), Conf) - ]), - case lists:all(fun(X) -> X =:= true end, Validations) of - true -> true; - _ -> Validations - end. - - -%% @doc Calls Fun on each element of the list until it returns {ok, -%% term()}, otherwise accumulates {error, term()} into a list, -%% wrapping in {error, _} at the end. --spec foldm_either(fun((term()) -> - {ok, term()} | cuttlefish_error:errorlist()), - list()) -> - {ok, term()} | cuttlefish_error:errorlist(). -foldm_either(Fun, List) -> - foldm_either(Fun, List, []). - -%% @doc Calls Fun on each element of the list until it returns {ok, -%% term()}, otherwise accumulates {error, term()} into a list, -%% wrapping in {errorlist, _} at the end. --spec foldm_either(fun((term()) -> - {ok, term()} | cuttlefish_error:error()), - list(), list()) -> - {ok, term()} | cuttlefish_error:errorlist(). -foldm_either(_Fun, [], Acc) -> {errorlist, lists:reverse(Acc)}; -foldm_either(Fun, [H|T], Acc) -> - case Fun(H) of - {ok, Result} -> {ok, Result}; - {error, _}=Error -> - foldm_either(Fun, T, [Error|Acc]) - end. - --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -bad_conf_test() -> - Conf = [ - {["integer_thing"], "thirty_two"}, - {["enum_thing"], bad_enum_value}, - {["ip_thing"], "not an IP address"} - ], - - Mappings = [ - cuttlefish_mapping:parse({mapping, "integer_thing", "to.int", [ - {datatype, integer} - ]}), - cuttlefish_mapping:parse({mapping, "enum_thing", "to.enum", [ - {datatype, {enum, [on, off]}} - ]}), - cuttlefish_mapping:parse({mapping, "ip_thing", "to.ip", [ - {datatype, ip} - ]}) - ], - - Translations = [ - cuttlefish_translation:parse({translation, "to.enum", fun(_ConfConf) -> whatev end}) - ], - - NewConfig = map({Translations, Mappings, []}, Conf), - io:format("NewConf: ~p~n", [NewConfig]), - - ?assertMatch({error, transform_datatypes, _}, NewConfig), - ok. - -add_defaults_test() -> - Conf = [ - %%{["a","b","c"], "override"}, %% Specifically left out. Uncomment line to break test, - {["a","c","d"], "override"}, - {["no","match"], "unchanged"}, - %%{"m.rk.x", "defined"}, %% since this is undefined no defaults should be created for "m", - - %% two matches on a name "ak" and "bk" - {["n","ak","x"], "set_n_name_x"}, - {["n","bk","x"], "set_n_name_x2"}, - {["n","ck","y"], "set_n_name_y3"} - ], - - Mappings = [ - %% First mapping, direct, not in .conf, will be default - cuttlefish_mapping:parse({mapping, "a.b.c", "b.c", [ - {default, "q"} - ]}), - %% default is "l", but since "a.c.d" is in Conf, it will be "override" - cuttlefish_mapping:parse({mapping, "a.c.d", "c.d", [ - {default, "l"} - ]}), - cuttlefish_mapping:parse({mapping, "m.$name.x", "some.proplist", [ - {default, "m_name_x"} - ]}), - cuttlefish_mapping:parse({mapping, "n.$name.x", "some.proplist", [ - {default, "n_name_x"} - ]}), - cuttlefish_mapping:parse({mapping, "n.$name.y", "some.proplist", [ - {default, "n_name_y"} - ]}), - cuttlefish_mapping:parse({mapping, "o.$name.z", "some.proplist", [ - {default, "o_name_z"}, - {include_default, "blue"} - ]}) - ], - - DConf = add_defaults(Conf, Mappings), - io:format("DConf: ~p~n", [DConf]), - ?assertEqual(9, length(DConf)), - ?assertEqual("q", proplists:get_value(["a","b","c"], DConf)), - ?assertNotEqual("l", proplists:get_value(["a","c","d"], DConf)), - ?assertEqual("override", proplists:get_value(["a","c","d"], DConf)), - ?assertEqual("unchanged", proplists:get_value(["no","match"], DConf)), - ?assertEqual("set_n_name_x", proplists:get_value(["n","ak","x"], DConf)), - ?assertEqual("set_n_name_x2", proplists:get_value(["n","bk","x"], DConf)), - ?assertEqual("n_name_x", proplists:get_value(["n","ck","x"], DConf)), - ?assertEqual("n_name_y", proplists:get_value(["n","ak","y"], DConf)), - ?assertEqual("n_name_y", proplists:get_value(["n","bk","y"], DConf)), - ?assertEqual("set_n_name_y3", proplists:get_value(["n","ck","y"], DConf)), - ?assertEqual(undefined, proplists:get_value(["o","blue","z"], DConf)), - ok. - -map_test() -> - Schema = cuttlefish_schema:file(tp("riak.schema")), - - Conf = conf_parse:file(tp("riak.conf")), - - NewConfig = map(Schema, Conf), - - NewRingSize = proplists:get_value(ring_creation_size, proplists:get_value(riak_core, NewConfig)), - ?assertEqual(32, NewRingSize), - - NewAAE = proplists:get_value(anti_entropy, proplists:get_value(riak_kv, NewConfig)), - ?assertEqual({on,[debug]}, NewAAE), - - NewSASL = proplists:get_value(sasl_error_logger, proplists:get_value(sasl, NewConfig)), - ?assertEqual(false, NewSASL), - - NewHTTP = proplists:get_value(http, proplists:get_value(riak_core, NewConfig)), - ?assertEqual([{"10.0.0.1", 80}, {"127.0.0.1", 8098}], NewHTTP), - - NewPB = proplists:get_value(pb, proplists:get_value(riak_api, NewConfig)), - ?assertEqual([], NewPB), - - NewHTTPS = proplists:get_value(https, proplists:get_value(riak_core, NewConfig)), - ?assertEqual(undefined, NewHTTPS), - ok. - -minimal_map_test() -> - Schema = cuttlefish_schema:file(tp("riak.schema")), - Conf = [{["ring_size"], "32"}, - {["anti_entropy"], "debug"}], - NewConfig = minimal_map(Schema, Conf), - ?assertEqual([{riak_core, [{ring_creation_size, 32}]},{riak_kv,[{anti_entropy, {on, [debug]}}]}], - lists:sort(NewConfig)). - - -apply_mappings_test() -> - %% Two mappings, both alike in dignity, - %% In fair unit test, where we lay our scene, - %% From ancient failure break to new mutiny, - %% Where civil overrides makes civil priority unclean. - %% From forth the fatal loins of these two foes - %% A pair of star-cross'd mappings write one app var; - %% Whose misadventured piteous overthrows - %% Do with their merge behave unexpectedly. - - %% Assume add_defaults has already run - Conf = [ - {["conf", "key1"], "1"}, - {["conf", "key2"], "2"} - ], - Mappings = [ - cuttlefish_mapping:parse({ - mapping, - "conf.key1", - "erlang.key", - [ - {default, "1"} - ] - }), - cuttlefish_mapping:parse({ - mapping, - "conf.key2", - "erlang.key", - [ - {default, "2"} - ] - }) - ], - - {DirectMappings, []} = apply_mappings({[], Mappings, []}, Conf), - cuttlefish_unit:assert_config(DirectMappings, "erlang.key", "1"), - ok. - -find_mapping_test() -> - Mappings = [ - cuttlefish_mapping:parse({mapping, "variable.with.fixed.name", "", [{ default, 0}]}), - cuttlefish_mapping:parse({mapping, "variable.with.$matched.name", "", [{ default, 1}]}) - ], - io:format("Mappings: ~p~n", [Mappings]), - - ?assertEqual( - ["variable","with","fixed","name"], - cuttlefish_mapping:variable(find_mapping(["variable","with","fixed","name"], Mappings)) - ), - - ?assertEqual( - ["variable","with","fixed","name"], - cuttlefish_mapping:variable(find_mapping("variable.with.fixed.name", Mappings)) - ), - - ?assertEqual( - 0, - cuttlefish_mapping:default(find_mapping(["variable","with","fixed","name"], Mappings)) - ), - - ?assertEqual( - ["variable","with","$matched","name"], - cuttlefish_mapping:variable(find_mapping(["variable","with","A","name"], Mappings)) - ), - - ?assertEqual( - 1, - cuttlefish_mapping:default(find_mapping(["variable","with","A","name"], Mappings)) - ), - - ?assertEqual( - ["variable","with","$matched","name"], - cuttlefish_mapping:variable(find_mapping(["variable","with","B","name"], Mappings)) - ), - - ?assertEqual( - 1, - cuttlefish_mapping:default(find_mapping(["variable","with","B","name"], Mappings)) - ), - - ?assertEqual( - ["variable","with","$matched","name"], - cuttlefish_mapping:variable(find_mapping(["variable","with","C","name"], Mappings)) - ), - - ?assertEqual( - 1, - cuttlefish_mapping:default(find_mapping(["variable","with","C","name"], Mappings)) - ), - - ?assertEqual( - ["variable","with","$matched","name"], - cuttlefish_mapping:variable(find_mapping(["variable","with","D","name"], Mappings)) - ), - - ?assertEqual( - 1, - cuttlefish_mapping:default(find_mapping(["variable","with","D","name"], Mappings)) - ), - - ?assertEqual( - ["variable","with","$matched","name"], - cuttlefish_mapping:variable(find_mapping(["variable","with","E","name"], Mappings)) - ), - - ?assertEqual( - 1, - cuttlefish_mapping:default(find_mapping(["variable","with","E","name"], Mappings)) - ), - - %% Test variable name with dot - ?assertEqual( - "variable.with.E.F.name not_found", - ?XLATE(find_mapping(["variable","with","E","F","name"], Mappings)) - ), - %% Test variable name with escaped dot - ?assertEqual( - 1, - cuttlefish_mapping:default(find_mapping(["variable","with","E.F","name"], Mappings)) - ), - ok. - -multiple_hard_match_test() -> - %% In real life this should never happen, but if it does, I'd love a log message - Mappings = [ - cuttlefish_mapping:parse({mapping, "variable.with.fixed.name", "", [{ default, 0}]}), - cuttlefish_mapping:parse({mapping, "variable.with.fixed.name", "", [{ default, 1}]}) - ], - ?assertEqual( - "2 hard mappings and 0 fuzzy mappings found for variable.with.fixed.name", - ?XLATE(find_mapping(["variable","with","fixed","name"], Mappings)) - ), - ok. - -apply_mappings_translations_dropped_correctly_test() -> - Fun = fun(X) -> X end, - ?assertEqual(1, Fun(1)), %% coverage kludge - - Translations = [ - cuttlefish_translation:parse({ - translation, - "mapping.name", - Fun - }) - ], - Mappings = [ - cuttlefish_mapping:parse({ - mapping, - "conf.key", - "mapping.name", - [{default, 6}] - }) - ], - %% So, we have a translation for the corresponding mapping, but that mapping has no default - {_DirectMappings, TranslationsToDrop} = apply_mappings({Translations, Mappings, []}, []), - ?assertEqual([], TranslationsToDrop), - ok. - -apply_mappings_translations_dropped_correctly_mixed_test() -> - Fun = fun(X) -> X end, - ?assertEqual(1, Fun(1)), %% coverage kludge - - Translations = [ - cuttlefish_translation:parse({ - translation, - "mapping.name", - Fun - }) - ], - Mappings = [ - cuttlefish_mapping:parse({ - mapping, - "conf.key", - "mapping.name", - [{default, 6}] - }), - cuttlefish_mapping:parse({ - mapping, - "conf.key2", - "mapping.name", - [] - }) - ], - %% One valid mapping, and one that should be dropped (no default) - {_DirectMappings, TranslationsToDrop} = apply_mappings({Translations, Mappings, []}, []), - ?assertEqual([], TranslationsToDrop), - ok. -apply_mappings_translations_dropped_correctly_mixed2_test() -> - Fun = fun(X) -> X end, - ?assertEqual(1, Fun(1)), %% coverage kludge - - Translations = [ - cuttlefish_translation:parse({ - translation, - "mapping.name", - Fun - }) - ], - Mappings = [ - cuttlefish_mapping:parse({ - mapping, - "conf.key", - "mapping.name", - [{default, 6}] - }), - cuttlefish_mapping:parse({ - mapping, - "conf.key2", - "mapping.name", - [] - }), - cuttlefish_mapping:parse({ - mapping, - "conf.key3", - "mapping.name", - [] - }) - ], - %% One valid mapping and two that should be dropped (no default) - {_DirectMappings, TranslationsToDrop} = apply_mappings({Translations, Mappings, []}, []), - ?assertEqual([], TranslationsToDrop), - ok. - -transform_datatypes_not_found_test() -> - Mappings = [ - cuttlefish_mapping:parse({ - mapping, - "conf.key", - "erlang.key", - [] - }) - ], - - Conf = [ - {["conf", "other"], "string"} - ], - NewConf = transform_datatypes(Conf, Mappings), - ?assertEqual({[], [{error, {unknown_variable, "conf.other"}}]}, NewConf), - ok. - -validation_test() -> - - Pid = self(), - - Mappings = [cuttlefish_mapping:parse( - {mapping, "a", "b.c", [{validators, ["a"]}, {datatype, {enum, [true, false]}}]} - ) - ], - - Validators = [cuttlefish_validator:parse( - {validator, "a", "error msg", fun(X) -> Pid ! X, true end} - ) - ], - - Conf = [ - {["a"], true} - ], - - AppConf = map({[], Mappings, Validators}, Conf), - - receive - X -> - ?assert(X) - after - 1000 -> - ?assert(false) - end, - - ?assertEqual([{b, [{c, true}]}], AppConf), - ok. - -throw_unset_test() -> - Mappings = [cuttlefish_mapping:parse({mapping, "a", "b.c", []})], - Translations = [cuttlefish_translation:parse( - {translation, "b.c", - fun(_X) -> cuttlefish:unset() end}) - ], - AppConf = map({Translations, Mappings, []}, []), - ?assertEqual([], AppConf), - ok. - -bad_prefix_match_test() -> - Prefixes = [ - {["prefix", "one"], ["one", "two"]}, - {["prefix", "two"], ["one", "two"]} - ], - Conf = [], - Default = 8, - VariableDef = ["prefix", "one", "other_thing", "$name"], - - ?assertEqual([], add_fuzzy_default(Prefixes, Conf, Default, VariableDef)), - ok. - -assert_extended_datatype( - Datatype, - Setting, - Expected) -> - Mappings = [ - cuttlefish_mapping:parse({mapping, "a.b", "e.k", [ - {datatype, Datatype} - ]}) - ], - Conf = [ - {["a","b"], Setting} - ], - - Actual = map({[], Mappings, []}, Conf), - - case Expected of - {error, Phase, EMsg} -> - ?assertMatch({error, Phase, _}, Actual), - ?assertEqual(EMsg, ?XLATE(hd(element(2, element(3, Actual))))); - _ -> - ?assertEqual([{e, [{k, Expected}]}], map({[], Mappings, []}, Conf)) - end, - ok. - -extended_datatypes_test() -> - assert_extended_datatype([integer, {atom, never}], "1", 1), - assert_extended_datatype([integer, {atom, never}], "never", never), - assert_extended_datatype([integer, {atom, never}], "always", {error, transform_datatypes, "Error transforming datatype for: a.b"}), - assert_extended_datatype([{duration, s}, {atom, never}], "never", never), - assert_extended_datatype([{atom, never}, integer], "1", 1), - assert_extended_datatype([{enum, [never, always]}, {duration, s}], "1s", 1), - assert_extended_datatype([{atom, never}, {atom, always}], "foo", {error, transform_datatypes, "Error transforming datatype for: a.b"}), - ok. - -not_found_test() -> - Mappings = [cuttlefish_mapping:parse({mapping, "a", "b.c", []})], - Translations = [cuttlefish_translation:parse( - {translation, "b.c", - fun(Conf) -> cuttlefish:conf_get("d", Conf) end}) - ], - AppConf = map({Translations, Mappings, []}, [{["a"], "foo"}]), - ?assertEqual({error, apply_translations, - {errorlist, - [{error, {translation_missing_setting, - {"b.c", "d"}}}]}}, - AppConf). - -invalid_test() -> - Mappings = [cuttlefish_mapping:parse({mapping, "a", "b.c", []})], - Translations = [cuttlefish_translation:parse( - {translation, "b.c", - fun(_Conf) -> cuttlefish:invalid("review all files") end}) - ], - AppConf = map({Translations, Mappings, []}, [{["a"], "foo"}]), - ?assertEqual({error, apply_translations, - {errorlist, - [{error, {translation_invalid_configuration, - {"b.c", "review all files"}}}]}}, - AppConf). - -value_sub_test() -> - Conf = [ - {["a","b","c"], "$(a.b)/c"}, - {["a","b"], "/a/b"} - ], - {NewConf, Errors} = value_sub(Conf), - ?assertEqual([], Errors), - ABC = proplists:get_value(["a","b","c"], NewConf), - ?assertEqual("/a/b/c", ABC), - ok. - -value_sub_infinite_loop_test() -> - Conf = [ - {["a"], "$(c)/d"}, - {["b"], "$(a)/d"}, - {["c"], "$(b)/d"} - ], - {_NewConf, Errors} = value_sub(Conf), - ?assertEqual( - "Circular RHS substitutions: [[\"a\"],[\"b\"],[\"c\"],[\"a\"]]", - ?XLATE(hd(Errors)) - ), - ?assertEqual( - "Circular RHS substitutions: [[\"b\"],[\"c\"],[\"a\"],[\"b\"]]", - ?XLATE(hd(tl(Errors))) - ), - ?assertEqual( - "Circular RHS substitutions: [[\"c\"],[\"a\"],[\"b\"],[\"c\"]]", - ?XLATE(hd(tl(tl(Errors)))) - ), - ok. - -value_sub_not_found_test() -> - Conf = [ - {["a"], "$(b)/c"} - ], - {_NewConf, Errors} = value_sub(Conf), - ?assertEqual( - "'a' substitution requires a config variable 'b' to be set", - ?XLATE(hd(Errors)) - ), - ok. - -value_sub_whitespace_test() -> - Conf = [ - {["a", "b", "c"], "/tyktorp"}, - {["a"], "$(a.b.c)/svagen"}, - {["b"], "$( a.b.c)/svagen"}, - {["c"], "$(a.b.c )/svagen"}, - {["d"], "$( a.b.c )/svagen"} - ], - {NewConf, []} = value_sub(Conf), - ?assertEqual("/tyktorp/svagen", proplists:get_value(["a"], NewConf)), - ?assertEqual("/tyktorp/svagen", proplists:get_value(["b"], NewConf)), - ?assertEqual("/tyktorp/svagen", proplists:get_value(["c"], NewConf)), - ?assertEqual("/tyktorp/svagen", proplists:get_value(["d"], NewConf)), - ok. - -value_sub_multiple_sub_test() -> - Conf = [ - {["a"], "/a"}, - {["b"], "/b"}, - {["c"], "$(a)$(b)"} - ], - {NewConf, []} = value_sub(Conf), - ?assertEqual("/a/b", proplists:get_value(["c"], NewConf)), - ok. - -value_sub_error_in_second_sub_test() -> - Conf = [ - {["a"], "$(b)/$(c)"}, - {["b"], "/b"}, - {["c"], "$(a)/c"} - ], - {_NewConf, Errors} = value_sub(Conf), - ?assertEqual( - "Circular RHS substitutions: [[\"a\"],[\"c\"],[\"a\"]]", - ?XLATE(hd(Errors)) - ), - ?assertEqual( - "Circular RHS substitutions: [[\"c\"],[\"a\"],[\"c\"]]", - ?XLATE(hd(tl(Errors))) - ), - ok. - -value_sub_false_circle_test() -> - Conf = [ - {["a"], "$(c)/$(c)"}, - {["c"], "C"} - ], - {NewConf, Errors} = value_sub(Conf), - ?assertEqual([], Errors), - ?assertEqual("C/C", proplists:get_value(["a"], NewConf)), - ok. - -value_sub_paren_test() -> - Conf = [ - {["a"], "$(c)/$(c)"}, - {["c"], "C)"} - ], - {NewConf, Errors} = value_sub(Conf), - ?assertEqual([], Errors), - ?assertEqual("C)/C)", proplists:get_value(["a"], NewConf)), - ok. - -%% test-path -tp(Name) -> - filename:join([code:lib_dir(cuttlefish), "test", Name]). - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_mapping.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_mapping.erl deleted file mode 100644 index 3207c25d15..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_mapping.erl +++ /dev/null @@ -1,545 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_mapping: models a single mapping -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_mapping). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --record(mapping, { - variable::cuttlefish_variable:variable(), - mapping::string(), - default::term(), - commented::term(), - datatype = [string] :: cuttlefish_datatypes:datatype_list(), - level = basic :: basic | intermediate | advanced, - doc = [] :: list(), - include_default = undefined :: string() | undefined, - new_conf_value = undefined :: string() | undefined, - validators = [] :: [string()], - is_merge = false :: boolean(), - see = [] :: [cuttlefish_variable:variable()], - hidden = false :: boolean() - }). - --type mapping() :: #mapping{}. --type raw_mapping() :: {mapping, string(), string(), [proplists:property()]}. --export_type([mapping/0]). - --export([ - parse/1, - parse_and_merge/2, - is_mapping/1, - variable/1, - is_fuzzy_variable/1, - mapping/1, - default/1, - has_default/1, - commented/1, - datatype/1, - level/1, - hidden/1, - doc/1, - see/1, - include_default/1, - new_conf_value/1, - replace/2, - validators/1, - validators/2, - remove_all_but_first/2 - ]). - --spec parse(raw_mapping()) -> mapping() | cuttlefish_error:error(). -parse({mapping, Variable, Mapping, Proplist}) -> - - Datatype = case proplists:get_value(datatype, Proplist, string) of - {enum, Enums} -> - AtomEnums = [ begin - case is_list(E) of - true -> list_to_atom(E); - _ -> E - end - end || E <- Enums ], - [{enum, AtomEnums}]; - L when is_list(L) -> - case cuttlefish_datatypes:is_valid_list(L) of - true -> L; - _ -> {error, {mapping_types, L}} - end; - D -> [D] - end, - - case Datatype of - {error, _} -> - Datatype; - _ -> - #mapping{ - variable = cuttlefish_variable:tokenize(Variable), - default = proplists:get_value(default, Proplist), - commented = proplists:get_value(commented, Proplist), - mapping = Mapping, - level = proplists:get_value(level, Proplist, basic), - datatype = Datatype, - doc = proplists:get_value(doc, Proplist, []), - see = proplists:get_value(see, Proplist, []), - include_default = proplists:get_value(include_default, Proplist), - new_conf_value = proplists:get_value(new_conf_value, Proplist), - validators = proplists:get_value(validators, Proplist, []), - hidden = proplists:get_value(hidden, Proplist, false) - } - end; -parse(X) -> - {error, {mapping_parse, X}}. - -%% If this mapping exists, do something. -%% That something is usually a simple replace, unless the proplist in -%% the raw mapping contains the atom 'merge'. -%% -%% This fuction assumes it's run as part of a foldl over new schema elements -%% in which case, there's only ever one instance of a key in the list -%% so keyreplace works fine. --spec parse_and_merge( - raw_mapping(), [mapping()]) -> [mapping()]. -parse_and_merge({mapping, Variable, _Mapping, Props} = MappingSource, Mappings) -> - Var = cuttlefish_variable:tokenize(Variable), - case lists:keyfind(Var, #mapping.variable, Mappings) of - false -> - [ parse(MappingSource) | Mappings]; - OldMapping -> - MaybeMergedMapping = case proplists:is_defined(merge, Props) of - true -> - merge(MappingSource, OldMapping); - _ -> - parse(MappingSource) - end, - lists:keyreplace(Var, #mapping.variable, Mappings, MaybeMergedMapping) - end. - --spec merge(raw_mapping(), mapping()) -> mapping(). -merge(NewMappingSource, OldMapping) -> - MergeMapping = parse(NewMappingSource), - #mapping{ - variable = variable(MergeMapping), - mapping = mapping(MergeMapping), - default = choose(default, NewMappingSource, MergeMapping, OldMapping), - commented = choose(commented, NewMappingSource, MergeMapping, OldMapping), - datatype = choose(datatype, NewMappingSource, MergeMapping, OldMapping), - level = choose(level, NewMappingSource, MergeMapping, OldMapping), - doc = choose(doc, NewMappingSource, MergeMapping, OldMapping), - include_default = choose(include_default, NewMappingSource, MergeMapping, OldMapping), - new_conf_value = choose(include_default, NewMappingSource, MergeMapping, OldMapping), - validators = choose(validators, NewMappingSource, MergeMapping, OldMapping), - see = choose(see, NewMappingSource, MergeMapping, OldMapping), - hidden = choose(hidden, NewMappingSource, MergeMapping, OldMapping) - }. - -choose(Field, {_, _, _, PreParseMergeProps}, MergeMapping, OldMapping) -> - Which = case {Field, - proplists:is_defined(Field, PreParseMergeProps), - proplists:get_value(Field, PreParseMergeProps)} of - {see, _, []} -> old; - {doc, _, []} -> old; - {_, true, _} -> new; - _ -> old - end, - case Which of - new -> - ?MODULE:Field(MergeMapping); - old -> - ?MODULE:Field(OldMapping) - end. - --spec is_mapping(any()) -> boolean(). -is_mapping(M) -> - is_tuple(M) andalso element(1, M) =:= mapping. - --spec variable(mapping()) -> [string()]. -variable(M) -> M#mapping.variable. - --spec is_fuzzy_variable(mapping()) -> boolean(). -is_fuzzy_variable(#mapping{variable=VariableDef}) -> - lists:any(fun(X) -> hd(X) =:= $$ end, VariableDef). - --spec mapping(mapping()) -> string(). -mapping(M) -> M#mapping.mapping. - --spec default(mapping()) -> term(). -default(M) -> M#mapping.default. - --spec has_default(mapping()) -> boolean(). -has_default(MappingRecord) -> - default(MappingRecord) =/= undefined. - --spec commented(mapping()) -> term(). -commented(M) -> M#mapping.commented. - --spec datatype(mapping()) -> cuttlefish_datatypes:datatype_list(). -datatype(M) -> M#mapping.datatype. - --spec level(mapping()) -> basic | intermediate | advanced. -level(M) -> M#mapping.level. - --spec hidden(mapping()) -> boolean(). -hidden(M) -> M#mapping.hidden. - --spec doc(mapping()) -> [string()]. -doc(M) -> M#mapping.doc. - --spec see(mapping()) -> [cuttlefish_variable:variable()]. -see(M) -> M#mapping.see. - --spec include_default(mapping()) -> string() | undefined. -include_default(M) -> M#mapping.include_default. - --spec new_conf_value(mapping()) -> string() | undefined. -new_conf_value(M) -> M#mapping.new_conf_value. - --spec validators(mapping()) -> [string()]. -validators(M) -> M#mapping.validators. - --spec validators(mapping(), [cuttlefish_validator:validator()]) -> [cuttlefish_validator:validator()]. -validators(M, Validators) -> - lists:foldr(fun(VName, Vs) -> - case lists:keyfind(VName, 2, Validators) of - false -> Vs; - V -> [V|Vs] - end - end, [], M#mapping.validators). - --spec replace(mapping(), [mapping()]) -> [mapping()]. -replace(Mapping, ListOfMappings) -> - Exists = lists:keymember(variable(Mapping), #mapping.variable, ListOfMappings), - case Exists of - true -> - lists:keyreplace(variable(Mapping), #mapping.variable, ListOfMappings, Mapping); - _ -> - [Mapping | ListOfMappings] - end. - --spec remove_all_but_first(string(), [mapping()]) -> [mapping()]. -remove_all_but_first(MappingName, Mappings) -> - lists:foldr( - fun(#mapping{mapping=MN}=M, Acc) when MN =:= MappingName-> - [M|lists:keydelete(MN, #mapping.mapping, Acc)]; - (M, Acc) -> - [M|Acc] - end, [], Mappings). - --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -mapping_test() -> - - SampleMapping = { - mapping, - "conf.key", - "erlang.key", - [ - {level, advanced}, - {default, "default value"}, - {datatype, {enum, [on, off]}}, - {commented, "commented value"}, - {include_default, "default_substitution"}, - {new_conf_value, "config_file_val"}, - {doc, ["documentation", "for feature"]}, - {validators, ["valid.the.impailer"]}, - hidden - ] - }, - - Record = parse(SampleMapping), - - ?assertEqual(["conf","key"], Record#mapping.variable), - ?assertEqual("default value", Record#mapping.default), - ?assertEqual("erlang.key", Record#mapping.mapping), - ?assertEqual(advanced, Record#mapping.level), - ?assertEqual([{enum, [on, off]}], Record#mapping.datatype), - ?assertEqual(["documentation", "for feature"], Record#mapping.doc), - ?assertEqual("default_substitution", Record#mapping.include_default), - ?assertEqual("config_file_val", Record#mapping.new_conf_value), - ?assertEqual(["valid.the.impailer"], Record#mapping.validators), - ?assertEqual(true, Record#mapping.hidden), - - %% funciton tests - ?assertEqual(["conf","key"], variable(Record)), - ?assertEqual("default value", default(Record)), - ?assertEqual("erlang.key", mapping(Record)), - ?assertEqual(advanced, level(Record)), - ?assertEqual([{enum, [on, off]}], datatype(Record)), - ?assertEqual(["documentation", "for feature"], doc(Record)), - ?assertEqual("default_substitution", include_default(Record)), - ?assertEqual("config_file_val", new_conf_value(Record)), - ?assertEqual(["valid.the.impailer"], validators(Record)), - ?assertEqual(true, hidden(Record)), - - ok. - -replace_test() -> - Element1 = parse({ - mapping, - "conf.key18", - "erlang.key4", - [ - {level, advanced}, - {default, "default value"}, - {datatype, {enum, [on, off]}}, - {commented, "commented value"}, - {include_default, "default_substitution"}, - {new_conf_value, "conf_val18"}, - {doc, ["documentation", "for feature"]} - ] - }), - - SampleMappings = [Element1, - parse({ - mapping, - "conf.key", - "erlang.key2", - [ - {level, advanced}, - {default, "default value"}, - {datatype, {enum, [on, off]}}, - {commented, "commented value"}, - {include_default, "default_substitution"}, - {new_conf_value, "conf_val_A"}, - {doc, ["documentation", "for feature"]} - ] - }) - ], - - Override = parse({ - mapping, - "conf.key", - "erlang.key", - [ - {level, advanced}, - {default, "default value"}, - {datatype, {enum, [on, off]}}, - {commented, "commented value"}, - {include_default, "default_substitution"}, - {new_conf_value, "conf_val_B"}, - {doc, ["documentation", "for feature"]} - ] - }), - - NewMappings = replace(Override, SampleMappings), - ?assertEqual([Element1, Override], NewMappings), - ok. - -validators_test() -> - Validators = [ - cuttlefish_validator:parse( - {validator, "a", "a desc", fun(_X) -> true end} - ), - cuttlefish_validator:parse({ - validator, "b", "b desc", fun(_X) -> true end - }), - cuttlefish_validator:parse({ - validator, "c", "c desc", fun(_X) -> true end - }) - ], - - %% Hack for coverage - [ begin - Fun = cuttlefish_validator:func(V), - ?assert(Fun(x)) - end || V <- Validators], - Mapping = parse({ - mapping, - "conf.key", - "erlang.key1", - [ - {validators, ["a", "b"]} - ] - }), - - [A, B, _C] = Validators, - - ?assertEqual([A,B], validators(Mapping, Validators)), - - MappingWithMissingValidator = parse({ - mapping, - "conf.key", - "erlang.key1", - [ - {validators, ["a", "d"]} %% There is no "d" - ] - }), - ?assertEqual([A], validators(MappingWithMissingValidator, Validators)), - - ok. - -parse_and_merge_test() -> - SampleMappings = [parse({ - mapping, - "conf.key", - "erlang.key1", - [ - {level, advanced}, - {default, "default value"}, - {datatype, {enum, [on, off]}}, - {commented, "commented value"}, - {include_default, "default_substitution"}, - {new_conf_value, "conf_val_A"}, - {doc, ["documentation", "for feature"]}, - hidden - ] - }), - parse({ - mapping, - "conf.key2", - "erlang.key2", - [ - {level, advanced}, - {default, "default value"}, - {datatype, {enum, [on, off]}}, - {commented, "commented value"}, - {include_default, "default_substitution"}, - {new_conf_value, "conf_val_B"}, - {doc, ["documentation", "for feature"]} - ] - }) - ], - - NewMappings = parse_and_merge({mapping, "conf.key", "erlang.key3", [{hidden, false}]}, SampleMappings), - - ?assertEqual("erlang.key3", mapping(hd(NewMappings))), - ?assertEqual(false, hidden(hd(NewMappings))), - ok. - -smart_merge_test() -> - OldM1 = parse({mapping, "thing.to.merge", "some.key", [ - {default, 7}, - {datatype, integer}, - {doc, ["documentation", "for feature"]} - ]}), - OldM2 = parse({mapping, "thing.not.merged", "some.other_key", [{default, 6}, {datatype, integer}]}), - - OriginalMappings = [OldM1, OldM2], - - NewRawNoMergeMapping = {mapping, "thing.to.merge", "some.new_other_key", [{level, advanced}]}, - [NewUnMergedMapping, OldM2] = parse_and_merge( - NewRawNoMergeMapping, - OriginalMappings), - - ?assertEqual(["thing", "to", "merge"], variable(NewUnMergedMapping)), - ?assertEqual(undefined, default(NewUnMergedMapping)), - ?assertEqual("some.new_other_key", mapping(NewUnMergedMapping)), - ?assertEqual(advanced, level(NewUnMergedMapping)), - ?assertEqual([string], datatype(NewUnMergedMapping)), - ?assertEqual([], doc(NewUnMergedMapping)), - ?assertEqual(undefined, include_default(NewUnMergedMapping)), - ?assertEqual([], validators(NewUnMergedMapping)), - - NewRawMergeMapping = {mapping, "thing.to.merge", "some.new_key", [merge, {level, advanced}]}, - [NewMergedMapping, OldM2] = NewMappings = parse_and_merge( - NewRawMergeMapping, - OriginalMappings), - - ?assertEqual(["thing", "to", "merge"], variable(NewMergedMapping)), - ?assertEqual(7, default(NewMergedMapping)), - ?assertEqual("some.new_key", mapping(NewMergedMapping)), - ?assertEqual(advanced, level(NewMergedMapping)), - ?assertEqual([integer], datatype(NewMergedMapping)), - ?assertEqual(["documentation", "for feature"], doc(NewMergedMapping)), - ?assertEqual(undefined, include_default(NewMergedMapping)), - ?assertEqual([], validators(NewMergedMapping)), - - NewerRawMergeMapping = {mapping, "thing.to.merge", "some.third_key", [merge, {default, 42}]}, - - [NewerMergedMapping, OldM2] = parse_and_merge( - NewerRawMergeMapping, - NewMappings), - - ?assertEqual(["thing", "to", "merge"], variable(NewerMergedMapping)), - ?assertEqual(42, default(NewerMergedMapping)), - ?assertEqual("some.third_key", mapping(NewerMergedMapping)), - ?assertEqual(advanced, level(NewerMergedMapping)), - ?assertEqual([integer], datatype(NewerMergedMapping)), - ?assertEqual(["documentation", "for feature"], doc(NewerMergedMapping)), - ?assertEqual(undefined, include_default(NewerMergedMapping)), - ?assertEqual([], validators(NewerMergedMapping)), - ok. - -accidentally_used_strings_for_enums_test() -> - Mapping = parse({ - mapping, - "conf.key2", - "erlang.key2", - [ - {datatype, {enum, ["on", "off"]}} - ] - }), - ?assertEqual([{enum, [on, off]}], cuttlefish_mapping:datatype(Mapping)), - ok. - -parse_error_test() -> - {ErrorAtom, ErrorTuple} = parse(not_a_raw_mapping), - ?assertEqual(error, ErrorAtom), - ?assertEqual( - "Poorly formatted input to cuttlefish_mapping:parse/1 : not_a_raw_mapping", - ?XLATE(ErrorTuple)), - ok. - -is_mapping_test() -> - ?assert(not(is_mapping(not_a_mapping))), - - M = parse({ - mapping, - "conf.key2", - "erlang.key2", - [ - {datatype, {enum, ["on", "off"]}} - ] - }), - ?assert(is_mapping(M)), - ok. - -%% conf.key can be any integer or the atom undefined. -extended_types_parse_test() -> - Mapping = parse({ - mapping, - "conf.key", - "erlang.key", - [ - {datatype, [integer, {atom, undefined}]} - ] - }), - - ?assertEqual([integer, {atom, undefined}], cuttlefish_mapping:datatype(Mapping)), - ok. - -datatype_cannot_be_empty_list_test() -> - Mapping = parse({ - mapping, - "conf.key", - "erlang.key", - [ - {datatype, []} - ] - }), - ?assertMatch({error, _}, Mapping), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_rebar_plugin.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_rebar_plugin.erl deleted file mode 100644 index e262303cc7..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_rebar_plugin.erl +++ /dev/null @@ -1,95 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_rebar_plugin: generates an application's default .conf -%% as part of the build -%% -%% Copyright (c) 2013 Basho Technologies, Inc. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --module(cuttlefish_rebar_plugin). - --export([ - generate/2 -]). - -%% =================================================================== -%% Public API -%% =================================================================== -generate(Config0, ReltoolFile) -> - case should_i_run(Config0, ReltoolFile) of - {ok, Config, ReltoolConfig} -> - TargetDir = rebar_rel_utils:get_target_dir(Config, ReltoolConfig), - - %% Finally, overlay the files specified by the overlay section - case lists:keyfind(overlay, 1, ReltoolConfig) of - {overlay, Overlays} when is_list(Overlays) -> - SchemaOverlays = lists:filter(fun(Overlay) -> - element(1, Overlay) =:= template - andalso filename:extension(element(3, Overlay)) =:= ".schema" - end, - Overlays), - - Schemas = lists:sort([ - lists:flatten(filename:join(TargetDir, element(3, Schema))) - || Schema <- SchemaOverlays]), - - io:format("Schema: ~p~n", [Schemas]), - - case cuttlefish_schema:files(Schemas) of - {errorlist, _Es} -> - %% These errors were already printed - error; - {_Translations, Mappings, _Validators} -> - make_default_file(Config, TargetDir, Mappings) - end; - - false -> - %%io:format("No {overlay, [...]} found in reltool.config.\n", []); - ok; - _ -> - io:format("{overlay, [...]} entry in reltool.config " - "must be a list.\n", []) - end, - ok; - no -> - ok - end, - ok. - -make_default_file(Config, TargetDir, Mappings) -> - %% I really wanted this to default to the application name. The problem - %% is that the type of application that uses cuttlefish is also the kind - %% that doesn't have an .app.src file, so rebar doesn't get it. - %% I could have done something with cwd, but I didn't like that because you - %% could be building anywhere. So, cuttlefish it is. he's pretty cool anyway. - File = rebar_config:get_local(Config, cuttlefish_filename, "cuttlefish.conf"), - Filename = filename:join([TargetDir, "etc", File]), - - cuttlefish_conf:generate_file(Mappings, Filename), - ok. - -%% Only run for rel directory -should_i_run(Config0, ReltoolFile) -> - case rebar_rel_utils:is_rel_dir() of - {true, _} -> - %% Load the reltool configuration from the file - {Config, ReltoolConfig} = rebar_rel_utils:load_config(Config0, ReltoolFile), - {ok, Config, ReltoolConfig}; - false -> - no - end. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_schema.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_schema.erl deleted file mode 100644 index 19a019cce5..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_schema.erl +++ /dev/null @@ -1,511 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_schema: slurps schema files -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- - --module(cuttlefish_schema). - --export([files/1, strings/1]). - -%% Exported for unit testing in other projects --export([merger/1, string_fun_factory/0]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --include("cuttlefish.hrl"). - --type schema() :: { - [cuttlefish_translation:translation()], - [cuttlefish_mapping:mapping()], - [cuttlefish_validator:validator()]}. --export_type([schema/0]). - --spec files([string()]) -> schema() | cuttlefish_error:errorlist(). -files(ListOfSchemaFiles) -> - merger(fun file/2, ListOfSchemaFiles). - --spec strings([string()]) -> schema() | cuttlefish_error:errorlist(). -strings(ListOfStrings) -> - merger(fun string/2, ListOfStrings). - --spec merger(fun((string(), schema()) -> schema() | cuttlefish_error:errorlist()), [string()]) -> - schema() | cuttlefish_error:errorlist(). -merger(Fun, ListOfInputs) -> - merger([ {Fun, Input} || Input <- ListOfInputs ]). - --spec merger([{fun((string(), schema()) -> schema() | cuttlefish_error:errorlist()), string()}]) -> - schema() | cuttlefish_error:errorlist(). -merger(ListOfFunInputPairs) -> - Schema = lists:foldr( - fun({Fun, Input}, {TranslationAcc, MappingAcc, ValidatorAcc}) -> - case Fun(Input, {TranslationAcc, MappingAcc, ValidatorAcc}) of - {errorlist, Errors} -> - %% These have already been logged. We're not moving forward with this - %% but, return them anyway so the rebar plugin can display them - %% with io:format, since it doesn't have lager. - {errorlist, Errors}; - {Translations, Mappings, Validators} -> - NewMappings = lists:foldr( - fun cuttlefish_mapping:replace/2, - MappingAcc, - Mappings), - - NewTranslations = lists:foldr( - fun cuttlefish_translation:replace/2, - TranslationAcc, - Translations), - - NewValidators = lists:foldr( - fun cuttlefish_validator:replace/2, - ValidatorAcc, - Validators), - - {NewTranslations, NewMappings, NewValidators} - end - end, - {[], [], []}, - ListOfFunInputPairs), - filter(Schema). - -%% This filter is *ONLY* for the case of multiple mappings to a single -%% erlang app setting, *AND* there's no corresponding translation for -%% that app setting --spec filter(schema() | cuttlefish_error:errorlist()) -> schema() | cuttlefish_error:errorlist(). -filter({errorlist, Errorlist}) -> - {errorlist, Errorlist}; -filter({Translations, Mappings, Validators}) -> - Counts = count_mappings(Mappings), - {MappingsToCheck, _} = lists:unzip(Counts), - NewMappings = lists:foldl( - fun(MappingName, Acc) -> - case lists:any( - fun(T) -> cuttlefish_translation:mapping(T) =:= MappingName end, - Translations) of - false -> - cuttlefish_mapping:remove_all_but_first(MappingName, Acc); - _ -> Acc - end - end, - Mappings, MappingsToCheck), - - {Translations, NewMappings, Validators}. - -count_mappings(Mappings) -> - lists:foldl( - fun(M, Acc) -> - orddict:update_counter(cuttlefish_mapping:mapping(M), 1, Acc) - end, - orddict:new(), - Mappings). - --spec file(string(), schema()) -> schema() | cuttlefish_error:errorlist(). -file(Filename, Schema) -> - {ok, B} = file:read_file(Filename), - %% latin-1 is easier to support generically. We'll revisit utf-8 - %% support in the future. - S = unicode:characters_to_list(B, latin1), - case string(S, Schema) of - {errorlist, Errors} -> - cuttlefish_error:print("Error parsing schema: ~s", [Filename]), - {errorlist, Errors}; - NewSchema -> - NewSchema - end. - -%% @doc this exists so that we can create the fun using non exported -%% functions for unit testing --spec string_fun_factory() -> fun((string(), schema()) -> - schema() | cuttlefish_error:errorlist()). -string_fun_factory() -> - fun string/2. - --spec string(string(), schema()) -> schema() | cuttlefish_error:errorlist(). -string(S, {T, M, V}) -> - case erl_scan:string(S) of - {ok, Tokens, _} -> - CommentTokens = erl_comment_scan:string(S), - {Translations, Mappings, Validators, Errors} = parse_schema(Tokens, CommentTokens, {T, M, V, []}), - - case length(Errors) of - 0 -> - {Translations, Mappings, Validators}; - _ -> - lists:foreach(fun({error, _Term}=E) -> - cuttlefish_error:print(E) end, - Errors), - {errorlist, Errors} - end; - {error, {Line, erl_scan, _}, _} -> - Error = {erl_scan, Line}, - ErrStr = cuttlefish_error:xlate(Error), - ?logger:error(lists:flatten(ErrStr)), - {errorlist, [{error, Error}]} - end. - --spec parse_schema( - [any()], - [any()], - {[cuttlefish_translation:translation()], - [cuttlefish_mapping:mapping()], - [cuttlefish_validator:validator()], - [cuttlefish_error:error()]} - ) -> - {[cuttlefish_translation:translation()], - [cuttlefish_mapping:mapping()], - [cuttlefish_validator:validator()], - [cuttlefish_error:error()]}. -%% We're done! We don't care about any comments after the last schema item -parse_schema([], _LeftoverComments, {TAcc, MAcc, VAcc, EAcc}) -> - {lists:reverse(TAcc), lists:reverse(MAcc), lists:reverse(VAcc), lists:reverse(EAcc)}; -parse_schema(ScannedTokens, CommentTokens, {TAcc, MAcc, VAcc, EAcc}) -> - {LineNo, Tokens, TailTokens } = parse_schema_tokens(ScannedTokens), - {Comments, TailComments} = lists:foldr( - fun(X={CommentLineNo, _, _, Comment}, {C, TC}) -> - case CommentLineNo < LineNo of - true -> {Comment ++ C, TC}; - _ -> {C, [X|TC]} - end - end, - {[], []}, - CommentTokens), - - NewAcc = case parse(Tokens) of - {error, {erl_parse, Reason}} -> - {TAcc, MAcc, VAcc, [{error, {erl_parse, {Reason, LineNo}}} | EAcc]}; - {mapping, {mapping, Variable, Mapping, Proplist}} -> - Attributes = comment_parser(Comments), - Doc = proplists:get_value(doc, Attributes, []), - See = get_see(Attributes), - MappingSource = {mapping, Variable, Mapping, [{see, See},{doc, Doc}|Proplist]}, - {TAcc, cuttlefish_mapping:parse_and_merge(MappingSource, MAcc), VAcc, EAcc}; - {translation, Return} -> - {cuttlefish_translation:parse_and_merge(Return, TAcc), MAcc, VAcc, EAcc}; - {validator, Return} -> - {TAcc, MAcc, cuttlefish_validator:parse_and_merge(Return, VAcc), EAcc}; - Other -> - {TAcc, MAcc, VAcc, [{error, {parse_schema, Other}} | EAcc]} - end, - parse_schema(TailTokens, TailComments, NewAcc). - -parse_schema_tokens(Scanned) -> - parse_schema_tokens(Scanned, []). - -parse_schema_tokens([], Acc=[Last|_]) -> - %% When you've reached the end of file without encountering a dot, - %% return the result anyway and let erl_parse produce the error. - {element(2, Last), lists:reverse(Acc), []}; -parse_schema_tokens(Scanned, Acc=[{dot, LineNo}|_]) -> - {LineNo, lists:reverse(Acc), Scanned}; -parse_schema_tokens([H|Scanned], Acc) -> - parse_schema_tokens(Scanned, [H|Acc]). - --spec parse(list()) -> { mapping | translation | validator, tuple()} | cuttlefish_error:error(). -parse(Scanned) -> - case erl_parse:parse_exprs(Scanned) of - {ok, Parsed} -> - {value, X, _} = erl_eval:exprs(Parsed,[]), - {element(1, X), X}; - {error, {_Line, erl_parse, [H|_T]=Strings}} when is_list(H) -> - {error, {erl_parse, lists:flatten(Strings)}}; - {error, {_Line, erl_parse, Term}} -> - {error, {erl_parse, io_lib:format("~p", [Term])}}; - E -> - {error, {erl_parse_unexpected, E}} - end. - --spec get_see([proplists:property()]) -> [cuttlefish_variable:variable()]. -get_see(Proplist) -> - [ cuttlefish_variable:tokenize(Line) - || [Line] <- proplists:get_all_values(see, Proplist)]. - - -comment_parser(Comments) -> - StrippedComments = - lists:filter(fun(X) -> X =/= [] end, - [percent_stripper(C) || C <- Comments]), - %% now, let's go annotation hunting - - AttrList = lists:foldl( - fun(Line, Acc) -> - case {Line, Acc} of - {[ $@ | T], _} -> - Annotation = hd(string:tokens(T, [$\s])), - [{list_to_atom(Annotation), [percent_stripper(T -- Annotation)] }|Acc]; - { _, []} -> []; - {String, _} -> - [{Annotation, Strings}|T] = Acc, - [{Annotation, [String|Strings]}|T] - end - end, [], StrippedComments), - SortedList = lists:reverse([ {Attr, lists:reverse(Value)} || {Attr, Value} <- AttrList]), - CorrectedList = attribute_formatter(SortedList), - CorrectedList. - -%% Just handles the @doc business -attribute_formatter([Other | T]) -> - [ Other | attribute_formatter(T)]; -attribute_formatter([]) -> []. - -percent_stripper(Line) -> - percent_stripper_r(percent_stripper_l(Line)). - -percent_stripper_l([$%|T]) -> percent_stripper_l(T); -percent_stripper_l([$\s|T]) -> percent_stripper_l(T); -percent_stripper_l(Line) -> Line. - -percent_stripper_r(Line) -> - lists:reverse( - percent_stripper_l( - lists:reverse(Line))). --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -%% Test helpers --spec file(string()) -> schema() | cuttlefish_error:errorlist(). -file(Filename) -> - file(Filename, {[], [], []}). --spec string(string()) -> schema() | cuttlefish_error:errorlist(). -string(S) -> - string(S, {[], [], []}). - -percent_stripper_test() -> - ?assertEqual("hi!", percent_stripper("%%% hi!")), - ?assertEqual("hi!", percent_stripper("%% hi!")), - ?assertEqual("hi!", percent_stripper("% hi!")), - ?assertEqual("hi!", percent_stripper(" hi!")), - ?assertEqual("hi!", percent_stripper(" % % hi!")), - ?assertEqual("hi!", percent_stripper("% % % hi!")), - ?assertEqual("hi!", percent_stripper("% % % hi! % % %")), - ok. - -comment_parser_test() -> - Comments = [ - " ", - "%% @doc this is a sample doc", - "%% it spans multiple lines %%", - "", - "%% there can be line breaks", - "%% @datatype enum on, off", - "%% @advanced", - "%% @include_default name_substitution", - "%% @mapping riak_kv.anti_entropy", - "%% @see mapping.a", - "%% @see mapping.b" - ], - ParsedComments = comment_parser(Comments), - ?assertEqual(["this is a sample doc", - "it spans multiple lines", - "there can be line breaks"], - proplists:get_value(doc, ParsedComments)), - ?assertEqual([["mapping.a"], ["mapping.b"]], - proplists:get_all_values(see, ParsedComments)), - ok. - -bad_file_test() -> - cuttlefish_test_logger:bounce(), - {errorlist, ErrorList} = file(tp("bad_erlang.schema")), - - Logs = cuttlefish_test_logger:get_logs(), - [L1|Tail] = Logs, - [L2|[]] = Tail, - ?assertMatch({match, _}, re:run(L1, "Error scanning erlang near line 10")), - ?assertMatch({match, _}, re:run(L2, "Error parsing schema: .*bad_erlang.schema")), - - ?assertEqual([ - {error, {erl_scan, 10}} - ], ErrorList), - ok. - -parse_invalid_erlang_test() -> - cuttlefish_test_logger:bounce(), - SchemaString = lists:flatten([ - "%% @doc some doc\n", - "%% the doc continues!\n", - "{mapping, \"ring_size\", \"riak_core.ring_creation_size\", [\n", - " {datatype, penguin}" - "}.\n" - ]), - Parsed = string(SchemaString), - - [Log] = cuttlefish_test_logger:get_logs(), - ?assertMatch({match, _}, re:run(Log, "Schema parse error near line number 4")), - ?assertMatch({match, _}, re:run(Log, "syntax error before: ")), - ?assertMatch({match, _}, re:run(Log, "'}'")), - - ?assertEqual({errorlist, [{error, {erl_parse, {"syntax error before: '}'", 4}}}]}, - Parsed). - - -parse_bad_datatype_test() -> - cuttlefish_test_logger:bounce(), - - SchemaString = lists:flatten([ - "%% @doc some doc\n", - "%% the doc continues!\n", - "{mapping, \"ring_size\", \"riak_core.ring_creation_size\", [\n", - " {default, \"blue\"}, ", - " {datatype, penguin}" - "]}.\n" - ]), - _Parsed = string(SchemaString), - ?assertEqual([], cuttlefish_test_logger:get_logs()). - -files_test() -> - %% files/1 takes a list of schemas in priority order. - %% Loads them in reverse order, as things are overridden - {Translations, Mappings, Validators} = files( - [ - tp("multi1.schema"), - tp("multi2.schema"), - tp("multi3.schema") - ]), - - ?assertEqual(6, length(Mappings)), - [M1, M2, M3, M4, M5, M6] = Mappings, - - %% Check mappings in correct order - io:format("~p", [Mappings]), - ?assertEqual(["top_level", "var1"], cuttlefish_mapping:variable(M1)), - ?assertEqual(["a", "some", "var1"], cuttlefish_mapping:variable(M2)), - ?assertEqual(["a", "some", "var2"], cuttlefish_mapping:variable(M3)), - ?assertEqual(["a", "some", "var3"], cuttlefish_mapping:variable(M4)), - ?assertEqual(["b", "some", "var1"], cuttlefish_mapping:variable(M5)), - ?assertEqual(["b", "some", "var2"], cuttlefish_mapping:variable(M6)), - - - %% Check correct mapping overrides - ?assertEqual("app_a.big_var", cuttlefish_mapping:mapping(M1)), - ?assertEqual("app_a.some_var1", cuttlefish_mapping:mapping(M2)), - ?assertEqual("app_a.some_var", cuttlefish_mapping:mapping(M3)), - ?assertEqual("app_a.some_var3", cuttlefish_mapping:mapping(M4)), - ?assertEqual("app_b.some_var3", cuttlefish_mapping:mapping(M5)), - ?assertEqual("app_b.some_var2", cuttlefish_mapping:mapping(M6)), - - ?assertEqual(6, length(Translations)), - [T1, T2, T3, T4, T5, T6] = Translations, - - %% Check translation overrides - AssertTran = fun(Mapping, Translation, Expected) -> - - %% Check Order - ?assertEqual(Mapping, cuttlefish_translation:mapping(Translation)), - %% Check Override - F1 = cuttlefish_translation:func(Translation), - ?assertEqual(Expected, F1(x)) - end, - - AssertTran("app_a.big_var", T1, "tippedy top"), - AssertTran("app_a.some_var1", T2, "a1"), - AssertTran("app_a.some_var2", T3, "a2"), - AssertTran("app_a.some_var3", T4, "toplevel"), - AssertTran("app_b.some_var1", T5, "b3"), - AssertTran("app_b.some_var2", T6, "b2"), - - %% One more time, for validators! - ?assertEqual(5, length(Validators)), - [V1, V2, V3, V4, V5] = Validators, - - %% Now check overrides - AssertVal = fun(Name, Validator, Expected) -> - %% Check Order - ?assertEqual(Name, cuttlefish_validator:name(Validator)), - %% Check Override - F1 = cuttlefish_validator:func(Validator), - ?assertEqual(Expected, F1(x)) - end, - - AssertVal("top.val", V1, false), - AssertVal("a.validator1", V2, true), - AssertVal("a.validator2", V3, false), - AssertVal("b.validator1", V4, false), - AssertVal("b.validator2", V5, true), - - ok. - -get_see_test() -> - Proplist = [ - {doc, ["line1", "line2", "line3"]}, - {see, ["a.b"]}, - {see, ["a.c"]} - ], - ?assertEqual([["a","b"],["a","c"]], get_see(Proplist)), - ok. - -see_test() -> - String = "{mapping, \"a.b\", \"e.k\", []}.\n" - ++ "%% @see a.b\n" - ++ "{mapping, \"a.c\", \"e.j\", []}.\n", - {_, Mappings, _} = strings([String]), - ?assertEqual(2, length(Mappings)), - [M1, M2] = Mappings, - ?assertEqual([], cuttlefish_mapping:see(M1)), - ?assertEqual([["a", "b"]], cuttlefish_mapping:see(M2)), - ok. - -strings_filtration_test() -> - - String = "{mapping, \"a.b\", \"e.k\", []}.\n" - ++ "{mapping, \"a.c\", \"e.k\", []}.\n" - ++ "{mapping, \"a.d\", \"e.j\", []}.\n" - ++ "{mapping, \"a.e\", \"e.j\", []}.\n" - ++ "{translation, \"e.j\", fun(X) -> \"1\" end}.\n" - ++ "{mapping, \"b.a\", \"e.i\", []}.\n" - ++ "{mapping, \"b.b\", \"e.i\", []}.\n" - ++ "{mapping, \"b.c\", \"e.i\", []}.\n" - ++ "{translation, \"e.i\", fun(X) -> \"1\" end}.\n", - {Translations, Mappings, _} = strings([String]), - ?assertEqual(2, length(Translations)), - ?assertEqual(6, length(Mappings)), - ?assertEqual(["a", "b"], cuttlefish_mapping:variable(hd(Mappings))), - ?assertEqual(["b", "b"], cuttlefish_mapping:variable(lists:nth(5, Mappings))), - ok. - -error_test() -> - {ErrorAtom, Errors} = strings(["tyktorp"]), - io:format("~p", [Errors]), - ?assertEqual(errorlist, ErrorAtom), - - {errorlist, [{error, Error}]} = strings(["{mapping, \"a\", [{datatype, unsupported_datatype}]}."]), - ?assertEqual( - "Unknown parse return: {mapping,\n {mapping,\"a\",[{datatype,unsupported_datatype}]}}", - ?XLATE(Error)), - ok. - -merge_across_multiple_schemas_test() -> - StringSchema1 = "{mapping, \"a.b\", \"erlang.key\", [merge, {default, on}]}.", - StringSchema2 = "%%@doc hi\n{mapping, \"a.b\", \"erlang.key\", [{default, off}, {datatype, flag}]}.", - - {_, Mappings, _} = strings([StringSchema1, StringSchema2]), - ?assertEqual(1, length(Mappings)), - [Mapping] = Mappings, - ?assertEqual([flag], cuttlefish_mapping:datatype(Mapping)), - ?assertEqual(on, cuttlefish_mapping:default(Mapping)), - ?assertEqual(["hi"], cuttlefish_mapping:doc(Mapping)), - ok. - -%% test-path -tp(Name) -> - filename:join([code:lib_dir(cuttlefish), "test", Name]). - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_translation.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_translation.erl deleted file mode 100644 index 5ce558d7fb..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_translation.erl +++ /dev/null @@ -1,228 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_translation: models a cuttlefish translation -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_translation). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --record(translation, { - mapping::string(), - func::fun() - }). --type translation() :: #translation{}. --type translation_fun() :: fun(([proplists:property()]) -> any()). --type raw_translation() :: {translation, string(), translation_fun()} | {translation, string()}. --export_type([translation/0]). - --export([ - parse/1, - parse_and_merge/2, - is_translation/1, - mapping/1, - func/1, - replace/2]). - --spec parse(raw_translation()) -> translation() | cuttlefish_error:error(). -parse({translation, Mapping}) -> - #translation{ - mapping = Mapping - }; -parse({translation, Mapping, Fun}) -> - #translation{ - mapping = Mapping, - func = Fun - }; -parse(X) -> - {error, {translation_parse, X}}. - -%% This assumes it's run as part of a foldl over new schema elements -%% in which case, there's only ever one instance of a key in the list -%% so keyreplace works fine. --spec parse_and_merge( - raw_translation(), [translation()]) -> [translation()]. -parse_and_merge({translation, Mapping}, Translations) -> - lists:keydelete(Mapping, #translation.mapping, Translations); -parse_and_merge({translation, Mapping, _} = TranslationSource, Translations) -> - NewTranslation = parse(TranslationSource), - case lists:keyfind(Mapping, #translation.mapping, Translations) of - false -> - [ NewTranslation | Translations]; - _OldMapping -> - lists:keyreplace(Mapping, #translation.mapping, Translations, NewTranslation) - end. - --spec is_translation(any()) -> boolean(). -is_translation(T) -> is_tuple(T) andalso element(1, T) =:= translation. - --spec mapping(translation()) -> string(). -mapping(T) -> T#translation.mapping. - --spec func(translation()) -> fun(). -func(T) -> T#translation.func. - --spec replace(translation(), [translation()]) -> [translation()]. -replace(Translation, ListOfTranslations) -> - Exists = lists:keymember(mapping(Translation), #translation.mapping, ListOfTranslations), - case Exists of - true -> - lists:keyreplace(mapping(Translation), #translation.mapping, ListOfTranslations, Translation); - _ -> - [Translation | ListOfTranslations] - end. - --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -parse_test() -> - TranslationDataStruct = { - translation, - "mapping", - fun(X) -> X*2 end - }, - - Translation = parse(TranslationDataStruct), - - ?assertEqual("mapping", Translation#translation.mapping), - F = Translation#translation.func, - ?assertEqual(4, F(2)), - ok. - - -getter_test() -> - Translation = #translation{ - mapping = "mapping", - func = fun(X) -> X*2 end - }, - - ?assertEqual("mapping", mapping(Translation)), - - Fun = func(Translation), - ?assertEqual(4, Fun(2)), - ok. - - -replace_test() -> - Element1 = #translation{ - mapping = "mapping18", - func = fun(X) -> X*2 end - }, - ?assertEqual(4, (Element1#translation.func)(2)), - - Element2 = #translation{ - mapping = "mapping1", - func = fun(X) -> X*4 end - }, - ?assertEqual(8, (Element2#translation.func)(2)), - - SampleTranslations = [Element1, Element2], - - Override = #translation{ - mapping = "mapping1", - func = fun(X) -> X*5 end - }, - ?assertEqual(25, (Override#translation.func)(5)), - - NewTranslations = replace(Override, SampleTranslations), - ?assertEqual([Element1, Override], NewTranslations), - ok. - -parse_and_merge_test() -> - Sample1 = #translation{ - mapping = "mapping1", - func = fun(X) -> X*3 end - }, - ?assertEqual(6, (Sample1#translation.func)(2)), - - Sample2 = #translation{ - mapping = "mapping2", - func = fun(X) -> X*4 end - }, - ?assertEqual(8, (Sample2#translation.func)(2)), - - SampleTranslations = [Sample1, Sample2], - - NewTranslations = parse_and_merge( - {translation, "mapping1", fun(X) -> X * 10 end}, - SampleTranslations), - F = func(hd(NewTranslations)), - ?assertEqual(50, F(5)), - ok. - -parse_error_test() -> - {ErrorAtom, ErrorTuple} = parse(not_a_raw_translation), - ?assertEqual(error, ErrorAtom), - ?assertEqual( - "Poorly formatted input to cuttlefish_translation:parse/1 : not_a_raw_translation", - ?XLATE(ErrorTuple)), - ok. - -parse_empty_test() -> - TranslationDataStruct = { - translation, - "mapping" - }, - - Translation = parse(TranslationDataStruct), - - ?assertEqual("mapping", Translation#translation.mapping), - F = Translation#translation.func, - ?assertEqual(undefined, F), - ok. - -parse_and_merge_empty_test() -> - Sample1 = #translation{ - mapping = "mapping1", - func = fun(X) -> X*3 end - }, - ?assertEqual(6, (Sample1#translation.func)(2)), - - Sample2 = #translation{ - mapping = "mapping2", - func = fun(X) -> X*4 end - }, - ?assertEqual(8, (Sample2#translation.func)(2)), - - SampleTranslations = [Sample1, Sample2], - - NewTranslations = parse_and_merge( - {translation, "mapping1"}, - SampleTranslations), - F = func(hd(NewTranslations)), - ?assertEqual(1, length(NewTranslations)), - ?assertEqual(40, F(10)), - ok. - -is_translation_test() -> - ?assert(not(is_translation(not_a_translation))), - - T = #translation{ - mapping = "mapping1", - func = fun(X) -> X*3 end - }, - ?assertEqual(6, (T#translation.func)(2)), - ?assert(is_translation(T)), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_util.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_util.erl deleted file mode 100644 index 22854f753c..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_util.erl +++ /dev/null @@ -1,183 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_util: various cuttlefish utility functions -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_util). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([ - replace_proplist_value/3, - numerify/1, - ceiling/1, - levenshtein/2]). - -%% Legacy API --export([ - conf_get_value/2, - conf_get_value/3, - filter_by_variable_starts_with/2, - matches_for_variable_def/2, - fuzzy_variable_match/2 -]). - --include("cuttlefish.hrl"). - -%% @deprecated -conf_get_value(Key, Conf) -> - ?logger:warning("cuttlefish_util:conf_get_value/2 has been deprecated. use cuttlefish:conf_get/2"), - cuttlefish:conf_get(Key, Conf). - -%% @deprecated -conf_get_value(Key, Conf, Default) -> - ?logger:warning("cuttlefish_util:conf_get_value/3 has been deprecated. use cuttlefish:conf_get/3"), - cuttlefish:conf_get(Key, Conf, Default). - -%% @deprecated -filter_by_variable_starts_with(Prefix, Conf) -> - ?logger:warning("cuttlefish_util:filter_by_variable_starts_with/2 has been deprecated. use cuttlefish_variable:filter_by_prefix/2"), - cuttlefish_variable:filter_by_prefix(Prefix, Conf). - -%% @deprecated -matches_for_variable_def(VarDef, Conf) -> - ?logger:warning("cuttlefish_util:matches_for_variable_def/2 has been deprecated. use cuttlefish_variable:fuzzy_matches/2"), - cuttlefish_variable:fuzzy_matches(VarDef, Conf). - -%% @deprecated -fuzzy_variable_match(Var, VarDef) -> - ?logger:warning("cuttlefish_util:fuzzy_variable_match/2 has been deprecated. use cuttlefish_variable:is_fuzzy_match/2"), - cuttlefish_variable:is_fuzzy_match(Var, VarDef). - -%% @doc replace the element in a proplist --spec replace_proplist_value(atom() | string(), any(), [{string(), any()}]) -> [{string(), any()}]. -replace_proplist_value(Key, Value, Proplist) -> - lists:keystore(Key, 1, Proplist, {Key, Value}). - -%% @doc Turn a string into a number if `list_to_float' or -%% `list_to_integer' accept it as valid --spec numerify(string()) -> integer()|float()|cuttlefish_error:error(). -numerify([$.|_]=Num) -> numerify([$0|Num]); -numerify(String) -> - try list_to_float(String) of - Float -> Float - catch - _:_ -> - try list_to_integer(String) of - Int -> Int - catch - _:_ -> - {error, {number_parse, String}} - end - end. - -%% @doc remember when you learned about decimal places. about a minute -%% later, you learned about rounding up and down. This is rounding up. --spec ceiling(float()) -> integer(). -ceiling(X) -> - T = erlang:trunc(X), - case (X - T) of - Neg when Neg < 0 -> T; - Pos when Pos > 0 -> T + 1; - _ -> T - end. - -%% Levenshtein code by Adam Lindberg, Fredrik Svensson via -%% http://www.trapexit.org/String_similar_to_(Levenshtein) -%% -%%------------------------------------------------------------------------------ -%% @spec levenshtein(StringA :: string(), StringB :: string()) -> integer() -%% @doc Calculates the Levenshtein distance between two strings -%% @end -%%------------------------------------------------------------------------------ -levenshtein(Samestring, Samestring) -> 0; -levenshtein(String, []) -> length(String); -levenshtein([], String) -> length(String); -levenshtein(Source, Target) -> - levenshtein_rec(Source, Target, lists:seq(0, length(Target)), 1). - -%% Recurses over every character in the source string and calculates a list of distances -levenshtein_rec([SrcHead|SrcTail], Target, DistList, Step) -> - levenshtein_rec(SrcTail, Target, levenshtein_distlist(Target, DistList, SrcHead, [Step], Step), Step + 1); -levenshtein_rec([], _, DistList, _) -> - lists:last(DistList). - -%% Generates a distance list with distance values for every character in the target string -levenshtein_distlist([TargetHead|TargetTail], [DLH|DLT], SourceChar, NewDistList, LastDist) when length(DLT) > 0 -> - Min = lists:min([LastDist + 1, hd(DLT) + 1, DLH + dif(TargetHead, SourceChar)]), - levenshtein_distlist(TargetTail, DLT, SourceChar, NewDistList ++ [Min], Min); -levenshtein_distlist([], _, _, NewDistList, _) -> - NewDistList. - -% Calculates the difference between two characters or other values -dif(C, C) -> 0; -dif(_, _) -> 1. - --ifdef(TEST). - -replace_proplist_value_test() -> - Proplist = [ - {"test1", 1}, - {"test2", 2}, - {"test3", 3} - ], - - NewProplist = replace_proplist_value("test2", 8, Proplist), - ?assertEqual( - 8, - proplists:get_value("test2", NewProplist) - ), - ok. - -replace_proplist_value_when_undefined_test() -> - Proplist = [ - {"test1", 1}, - {"test2", 2} - ], - - NewProplist = replace_proplist_value("test3", 3, Proplist), - ?assertEqual( - 3, - proplists:get_value("test3", NewProplist) - ), - ok. - -levenshtein_test() -> - ?assertEqual(0, levenshtein("X", "X")), - ?assertEqual(1, levenshtein("X", "XX")), - ?assertEqual(1, levenshtein("penguin", "penguino")), - ?assertEqual(1, levenshtein("dtrace", "ctrace")), - ?assertEqual(5, levenshtein("anti_entropy", "anti_entropy.tick")), - ?assertEqual(1, levenshtein("anti_entropy", "anti-entropy")), - ?assertEqual(4, levenshtein("", "four")), - ?assertEqual(4, levenshtein("four", "")), - ok. - -ceiling_test() -> - ?assertEqual(9, ceiling(8.99999)), - ?assertEqual(9, ceiling(8.00001)), - ?assertEqual(9, ceiling(9.0)), - ?assertEqual(-2, ceiling(-2.0000001)), - ?assertEqual(-2, ceiling(-2.9999999)), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_validator.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_validator.erl deleted file mode 100644 index 4d6c29e78f..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_validator.erl +++ /dev/null @@ -1,204 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% cuttlefish_validator: models a cuttlefish validator -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_validator). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --record(validator, { - name::string(), - description::string(), - func::fun() - }). --type validator() :: #validator{}. --type validator_fun() :: fun((any()) -> boolean()). --type raw_validator() :: {validator, string(), string(), validator_fun()}. --export_type([validator/0]). - --export([ - parse/1, - parse_and_merge/2, - is_validator/1, - name/1, - description/1, - func/1, - replace/2]). - --spec parse(raw_validator()) -> validator() | cuttlefish_error:error(). -parse({validator, Name, Description, Fun}) -> - #validator{ - name = Name, - description = Description, - func = Fun - }; -parse(X) -> - {error, {validator_parse, X}}. - -%% This assumes it's run as part of a foldl over new schema elements -%% in which case, there's only ever one instance of a key in the list -%% so keyreplace works fine. --spec parse_and_merge( - raw_validator(), [validator()]) -> [validator()|cuttlefish_error:error()]. -parse_and_merge({validator, ValidatorName, _, _} = ValidatorSource, Validators) -> - NewValidator = parse(ValidatorSource), - case lists:keyfind(ValidatorName, #validator.name, Validators) of - false -> - [ NewValidator | Validators]; - _OldMapping -> - lists:keyreplace(ValidatorName, #validator.name, Validators, NewValidator) - end. - --spec is_validator(any()) -> boolean(). -is_validator(V) -> is_tuple(V) andalso element(1, V) =:= validator. - --spec name(validator()) -> string(). -name(V) -> V#validator.name. - --spec description(validator()) -> string(). -description(V) -> V#validator.description. - --spec func(validator()) -> fun(). -func(V) -> V#validator.func. - --spec replace(validator(), [validator()]) -> [validator()]. -replace(Validator, ListOfValidators) -> - Exists = lists:keymember(name(Validator), #validator.name, ListOfValidators), - case Exists of - true -> - lists:keyreplace(name(Validator), #validator.name, ListOfValidators, Validator); - _ -> - [Validator | ListOfValidators] - end. - --ifdef(TEST). - --define(XLATE(X), lists:flatten(cuttlefish_error:xlate(X))). - -parse_test() -> - ValidatorDataStruct = { - validator, - "name", - "description", - fun(X) -> X*2 end - }, - - Validator = parse(ValidatorDataStruct), - - ?assertEqual("name", Validator#validator.name), - ?assertEqual("description", Validator#validator.description), - F = Validator#validator.func, - ?assertEqual(4, F(2)), - ok. - - -getter_test() -> - Validator = #validator{ - name = "name", - description = "description", - func = fun(X) -> X*2 end - }, - - ?assertEqual("name", name(Validator)), - ?assertEqual("description", description(Validator)), - - Fun = func(Validator), - ?assertEqual(4, Fun(2)), - ok. - - -replace_test() -> - Element1 = #validator{ - name = "name18", - description = "description18", - func = fun(X) -> X*2 end - }, - ?assertEqual(4, (Element1#validator.func)(2)), - - Element2 = #validator{ - name = "name1", - description = "description1", - func = fun(X) -> X*4 end - }, - ?assertEqual(8, (Element2#validator.func)(2)), - - SampleValidators = [Element1, Element2], - - Override = #validator{ - name = "name1", - description = "description1", - func = fun(X) -> X*5 end - }, - ?assertEqual(25, (Override#validator.func)(5)), - - NewValidators = replace(Override, SampleValidators), - ?assertEqual([Element1, Override], NewValidators), - ok. - -remove_duplicates_test() -> - Sample1 = #validator{ - name = "name1", - description = "description1", - func = fun(X) -> X*3 end - }, - ?assertEqual(6, (Sample1#validator.func)(2)), - - Sample2 = #validator{ - name = "name1", - description = "description1", - func = fun(X) -> X*4 end - }, - ?assertEqual(8, (Sample2#validator.func)(2)), - - SampleValidators = [Sample1, Sample2], - - [NewValidator|_] = parse_and_merge( - {validator, "name1", "description2", fun(X) -> X*10 end}, - SampleValidators), - F = func(NewValidator), - ?assertEqual(50, F(5)), - ?assertEqual("description2", description(NewValidator)), - ?assertEqual("name1", name(NewValidator)), - ok. - -parse_error_test() -> - {ErrorAtom, ErrorTerm} = parse(not_a_raw_validator), - ?assertEqual(error, ErrorAtom), - ?assertEqual( - "Poorly formatted input to cuttlefish_validator:parse/1 : not_a_raw_validator", - ?XLATE(ErrorTerm)), - ok. - -is_validator_test() -> - ?assert(not(is_validator(not_a_validator))), - - V = #validator{ - name = "name1", - description = "description1", - func = fun(X) -> X*4 end - }, - ?assertEqual(8, (V#validator.func)(2)), - ?assert(is_validator(V)), - ok. - --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_variable.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_variable.erl deleted file mode 100644 index 76fa1815d6..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_variable.erl +++ /dev/null @@ -1,273 +0,0 @@ -%% ------------------------------------------------------------------- -%% -%% handles both variable and variable definitions -%% -%% Copyright (c) 2013 Basho Technologies, Inc. All Rights Reserved. -%% -%% This file is provided to you under the Apache License, -%% Version 2.0 (the "License"); you may not use this file -%% except in compliance with the License. You may obtain -%% a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, -%% software distributed under the License is distributed on an -%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -%% KIND, either express or implied. See the License for the -%% specific language governing permissions and limitations -%% under the License. -%% -%% ------------------------------------------------------------------- --module(cuttlefish_variable). - --type variable() :: [string()]. --export_type([variable/0]). - --ifdef(TEST). --ifdef(EQC). --include_lib("eqc/include/eqc.hrl"). --define(QC_OUT(Prop), on_output(fun(F,A) -> io:format(user, F, A) end, Prop)). --endif. --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - --export([ - format/1, - tokenize/1, - split_on_match/1, - replace_match/2, - extract_first_match/2, - fuzzy_matches/2, - is_fuzzy_match/2, - filter_by_prefix/2 -]). - -%% @doc Formats a variable back into its dot-separated version. -%% Inverse of tokenize/1. --spec format(variable()) -> string(). -format(Key=[H|_]) when is_list(H) -> - Escaped = [re:replace(Word, "[.]", "\\\\&", [{return, list}, global]) || - Word <- Key], - string:join(Escaped, "."). - -%% @doc like string:tokens(Key, "."), but if the dot was escaped -%% i.e. \\., don't tokenize that --spec tokenize(string()) -> variable(). -tokenize(Key) -> - tokenize(Key, "", []). - -tokenize([$\\, $. |Rest], Part, Acc) -> - tokenize(Rest, [$. |Part], Acc); -tokenize([$. |Rest], Part, Acc) -> - tokenize(Rest, "", [lists:reverse(Part)|Acc]); -tokenize([], "", Acc) -> - lists:reverse(Acc); -tokenize([], Part, Acc) -> - lists:reverse([lists:reverse(Part)|Acc]); -tokenize([Char|Rest], Part, Acc) -> - tokenize(Rest, [Char|Part], Acc). - -%% @doc split a key definition into: -%% * Prefix: Things before the $var -%% * Var: The $var itself -%% * Suffix: Things after the $var --spec split_on_match(variable()) -> {variable(), string(), variable()}. -split_on_match(Variable) -> - {PrefixToks, MatchGroup, SuffixToks} = lists:foldl( - fun(T, {Prefix, MatchGroup, Suffix}) -> - case {T, MatchGroup} of - {[$$|_], []} -> {Prefix, T, Suffix}; - {_, []} -> {[T|Prefix], MatchGroup, Suffix}; - {_, _} -> {Prefix, MatchGroup, [T|Suffix]} - end - end, - {[], [], []}, - Variable), - { - lists:reverse(PrefixToks), - MatchGroup, - lists:reverse(SuffixToks) - }. - -%% @doc replaces the $var in Key with Sub --spec replace_match(variable(), string()) -> variable(). -replace_match(Variable, Sub) -> - [ begin - case {H, Sub} of - {$$, undefined} -> T; - {$$, Sub} -> Sub; - _ -> Tok - end - end || [H|T]=Tok <- Variable]. - --spec extract_first_match(variable(), variable()) -> - nomatch | [{string(), string()}]. -%% If the lengths are equal, try to pair up a fuzzy segment with its match. -extract_first_match(VariableDef, Variable) when length(VariableDef) == length(Variable) -> - extract_first_match(VariableDef, Variable, nomatch); -%% This could never match because they are different lengths. -extract_first_match(_,_) -> nomatch. - -%% We have a perfect match, or no match at all, so return the result. -extract_first_match([], [], Result) when is_list(Result) -> - %% If the Result is 'nomatch', the last function clause will be - %% the only one that matches. - lists:reverse(Result); -%% We found the first fuzzy segment, grab the binding of the segment. -extract_first_match([[$$|_]=Fuzzy|VariableDef], [Value|Variable], nomatch) -> - extract_first_match(VariableDef, Variable, [{Fuzzy, Value}]); -%% We found a fuzzy segment and already have a match, so just recurse. -extract_first_match([[$$|_]=Fuzzy|VariableDef], [Value|Variable], Result) -> - extract_first_match(VariableDef, Variable, [{Fuzzy, Value}|Result]); -%% We found two segments that are static and equal. -extract_first_match([X|VariableDef], [X|Variable], Result) -> - extract_first_match(VariableDef, Variable, Result); -%% Something else happened, so we don't match! -extract_first_match(_,_,_) -> nomatch. - -%% @doc given a KeyDef "a.b.$c.d", what are the possible values for $c -%% in the set of Keys in Conf = [{Key, Value}]? --spec fuzzy_matches(variable(), cuttlefish_conf:conf()) -> - [{string(), any()}]. -fuzzy_matches(VariableDef, Conf) -> - lists:foldl( - fun({Variable, _}, Acc) -> - case extract_first_match(VariableDef, Variable) of - nomatch -> - Acc; - [Match|_] -> - [Match|Acc] - end - end, [], Conf). - -%% @doc could this fixed Key be a match for the variable key KeyDef? -%% e.g. could a.b.$var.d =:= a.b.c.d? --spec is_fuzzy_match(variable(), variable()) -> boolean(). -is_fuzzy_match(Variable, VariableDef) -> - case length(Variable) =:= length(VariableDef) of - true -> - Zipped = lists:zip(Variable, VariableDef), - lists:all( - fun({X,Y}) -> - X =:= Y orelse hd(Y) =:= $$ - end, - Zipped); - _ -> false - end. - - -%% @doc For Proplist, return the subset of the proplist that starts -%% with "Key" --spec filter_by_prefix(string() | [string()], - [{[string()], any()}]) -> - [{[string()], any()}]. -filter_by_prefix([H|_T]=Prefix, Proplist) when is_list(H) -> - [ T || {Key,_}=T <- Proplist, lists:prefix(Prefix, Key) ]; -filter_by_prefix(StringPrefix, Proplist) -> - filter_by_prefix(tokenize(StringPrefix), Proplist). - --ifdef(TEST). - -tokenize_variable_key_test() -> - ?assertEqual(["a", "b", "c", "d"], (tokenize("a.b.c.d"))), - ?assertEqual(["a", "b.c", "d"], (tokenize("a.b\\.c.d"))), - - %% Covers GH #22 - ?assertEqual( - ["listener", "http"], - (tokenize("listener.http.")) - ), - ok. - -split_variable_on_match_test() -> - ?assertEqual({["a", "b"], "$c", ["d", "e"]}, (split_on_match(["a", "b", "$c", "d", "e"]))), - ?assertEqual({["a", "b", "c", "d", "e"], [], []}, (split_on_match(["a", "b", "c", "d", "e"]))), - ?assertEqual({[], "$a", ["b", "c", "d", "e"]}, (split_on_match(["$a", "b", "c", "d", "e"]))), - ok. - -variable_match_replace_test() -> - ?assertEqual(["a", "b", "c"], (replace_match(["a", "b", "c"], "d"))), - ?assertEqual(["a", "b", "c"], (replace_match(["a", "b", "c"], "e"))), - ?assertEqual(["a", "b", "c"], (replace_match(["a", "b", "c"], "f"))), - ?assertEqual(["a", "b", "c"], (replace_match(["a", "b", "c"], "g"))), - ?assertEqual(["a", "g", "c"], (replace_match(["a", "$b", "c"], "g"))), - ?assertEqual(["a", "b", "c"], (replace_match(["a", "$b", "c"], undefined))), - - ok. - -fuzzy_variable_match_test() -> - ?assert(is_fuzzy_match(["alpha","bravo","charlie","delta"], ["alpha","bravo","charlie","delta"])), - ?assert(is_fuzzy_match(["alpha","bravo","anything","delta"], ["alpha","bravo","$charlie","delta"])), - ?assertNot(is_fuzzy_match(["alpha","bravo.anything","delta"], ["alpha","bravo","charlie","delta"])), - ?assert(is_fuzzy_match(["alpha","bravo","any.thing","delta"], ["alpha","bravo","$charlie","delta"])), - ?assert(is_fuzzy_match(["alpha","bravo","any.thing.you.need","delta"], ["alpha","bravo","$charlie","delta"])), - ok. - -matches_for_variable_def_test() -> - Conf = [ - {["multi_backend","backend1","storage_backend"], 1}, - {["multi_backend","backend2","storage_backend"], 2}, - {["multi_backend","backend.3","storage_backend"], 3}, - {["multi_backend","backend4","storage_backend"], 4} - ], - - Vars = proplists:get_all_values("$name", - fuzzy_matches(["multi_backend","$name","storage_backend"], Conf) - ), - - ?assertEqual(4, (length(Vars))), - ?assert(lists:member("backend1", Vars)), - ?assert(lists:member("backend2", Vars)), - ?assert(lists:member("backend.3", Vars)), - ?assert(lists:member("backend4", Vars)), - ?assertEqual(4, (length(Vars))), - ok. - -filter_by_variable_starts_with_test() -> - Proplist = [ - {["regular","key"], 1}, - {["other","normal","key"], 2}, - {["prefixed","key1"], 3}, - {["prefixed","key2"], 4}, - {["interleaved","key"], 5}, - {["prefixed","key3"], 6} - ], - - FilteredByList = filter_by_prefix(["prefixed"], Proplist), - ?assertEqual([ - {["prefixed","key1"], 3}, - {["prefixed","key2"], 4}, - {["prefixed","key3"], 6} - ], - FilteredByList), - - FilteredByString = filter_by_prefix("prefixed", Proplist), - ?assertEqual([ - {["prefixed","key1"], 3}, - {["prefixed","key2"], 4}, - {["prefixed","key3"], 6} - ], - FilteredByString), - ok. - --ifdef(EQC). -variable_roundtrip_test_() -> - {timeout, 15, - [?_assert(quickcheck(eqc:testing_time(3,?QC_OUT(prop_format_tokenize_roundtrip()))))]}. - -prop_format_tokenize_roundtrip() -> - ?FORALL(Variable, non_empty(list(gen_word())), - tokenize(format(Variable)) == Variable). - -gen_word() -> - ?LET(F, non_empty(list(gen_word_char())), lists:flatten(F)). - -gen_word_char() -> - oneof([$., $_, $-, - choose($0, $9), - choose($A, $Z), - choose($a, $z)]). --endif. --endif. diff --git a/_build/emqx/lib/cuttlefish/src/cuttlefish_vmargs.erl b/_build/emqx/lib/cuttlefish/src/cuttlefish_vmargs.erl deleted file mode 100644 index a39a6d23b1..0000000000 --- a/_build/emqx/lib/cuttlefish/src/cuttlefish_vmargs.erl +++ /dev/null @@ -1,60 +0,0 @@ --module(cuttlefish_vmargs). - --export([stringify/1]). - --ifdef(TEST). --include_lib("eunit/include/eunit.hrl"). --compile(export_all). --endif. - -%% @doc turns a proplist into a list of strings suitable for vm.args files --spec stringify(undefined | [{any(), string()}]) -> [string()]. -stringify(undefined) -> - []; -stringify(VMArgsProplist) -> - [ stringify_line(K, V) || {K, V} <- VMArgsProplist ]. - - -stringify_line(K, V) when is_list(V) -> - lists:flatten(io_lib:format("~s ~s", [K, V])); -stringify_line(K, V) -> - lists:flatten(io_lib:format("~s ~w", [K, V])). - --ifdef(TEST). - -stringify_test() -> - VMArgsProplist = [ - {'-name', "dev1@127.0.0.1"}, - {'-setcookie', 'riak'}, - {'-smp', enable}, - {'+W',"w"}, - {'+K',"true"}, - {'+A',"64"}, - {'-env ERL_MAX_PORTS',"64000"}, - {'-env ERL_FULLSWEEP_AFTER',"0"}, - {'-env ERL_CRASH_DUMP',"./log/erl_crash.dump"}, - {'-env ERL_MAX_ETS_TABLES',"256000"}, - {'+P', "256000"}, - {'-kernel net_ticktime', "42"} - ], - - VMArgs = stringify(VMArgsProplist), - - Expected = [ - "-name dev1@127.0.0.1", - "-setcookie riak", - "-smp enable", - "+W w", - "+K true", - "+A 64", - "-env ERL_MAX_PORTS 64000", - "-env ERL_FULLSWEEP_AFTER 0", - "-env ERL_CRASH_DUMP ./log/erl_crash.dump", - "-env ERL_MAX_ETS_TABLES 256000", - "+P 256000", - "-kernel net_ticktime 42" - ], - [ ?assertEqual(E, V) || {E, V} <- lists:zip(Expected, VMArgs)], - ok. - --endif. diff --git a/_build/emqx/lib/ecpool/.gitignore b/_build/emqx/lib/ecpool/.gitignore deleted file mode 100644 index d082ef6f55..0000000000 --- a/_build/emqx/lib/ecpool/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -.eunit -deps -*.o -*.beam -*.plt -erl_crash.dump -ebin -rel/example_project -.concrete/DEV_MODE -.rebar -tmp -_build/ -rebar.lock -logs/ -.rebar3 diff --git a/_build/emqx/lib/ecpool/.travis.yml b/_build/emqx/lib/ecpool/.travis.yml deleted file mode 100644 index 98d9d33df4..0000000000 --- a/_build/emqx/lib/ecpool/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: erlang - -otp_release: - - 22.0 - - 21.3 - -before_install: - - git clone https://hub.fastgit.org/erlang/rebar3.git; cd rebar3; ./bootstrap; sudo mv rebar3 /usr/local/bin/; cd .. - -script: - - make compile - - make xref - - make ct - - make cover - - make dialyzer - -after_success: - - make coveralls - -sudo: false diff --git a/_build/emqx/lib/ecpool/LICENSE b/_build/emqx/lib/ecpool/LICENSE deleted file mode 100644 index 68a43e189d..0000000000 --- a/_build/emqx/lib/ecpool/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2018 EMQ X - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/_build/emqx/lib/ecpool/Makefile b/_build/emqx/lib/ecpool/Makefile deleted file mode 100644 index a21f8ab33a..0000000000 --- a/_build/emqx/lib/ecpool/Makefile +++ /dev/null @@ -1,29 +0,0 @@ -.PHONY: deps test - -REBAR=rebar3 - -all: deps compile xref - -deps: - @$(REBAR) get-deps - -compile: - @$(REBAR) compile - -xref: - @$(REBAR) xref - -clean: - @$(REBAR) clean - -ct: - @$(REBAR) ct - -cover: - @$(REBAR) cover - -edoc: - @$(REBAR) edoc - -dialyzer: compile - @$(REBAR) dialyzer diff --git a/_build/emqx/lib/ecpool/README.md b/_build/emqx/lib/ecpool/README.md deleted file mode 100644 index b555847a5c..0000000000 --- a/_build/emqx/lib/ecpool/README.md +++ /dev/null @@ -1,96 +0,0 @@ -# Erlang Connection/Client Pool - -`ecpool` is different with worker-pool libraries in that it is designed to pool connection/clients to server or database. - -`ecpool` tries to avoid the erlang application crash when the server or database going down. - -## Overview - -A pool worker to manage/monitor the connection to server or database: - -``` -PoolWorker -> Conn -> DB -``` - -Use client: - -``` -ecpool:with_client(Pool, fun(Client) -> call(Client) end). -``` - -## Usage - -### Start the pool - -``` -ecpool:start_pool(Pool, Mod, Opts). -``` - -For example: - -``` -PgOpts = [%% Pool Size - {pool_size, 10}, - %% Pool Type: round_robin | random | hash - {pool_type, round_robin}, - %% Auto reconnect - {auto_reconnect, 3}, - - %% epgsql opts - {host, "localhost"}, - {port, 5432}, - {username, "feng"}, - {password, ""}, - {database, "mqtt"}, - {encoding, utf8}], - -ecpool:start_pool(epgsql_pool, epgsql_pool_client, PgOpts) -``` - -### The Callback Module - -Pool Worker Callback: - -``` --callback connect(ConnOpts :: list()) -> {ok, pid()} | {error, any()}. -``` - -For example, epgsql_pool_client module: - -``` --module(epgsql_pool_client). - --behavihour(ecpool_worker). - -connect(Opts) -> - Host = proplists:get_value(host, Opts), - Username = proplists:get_value(username, Opts), - Password = proplists:get_value(password, Opts), - epgsql:connect(Host, Username, Password, conn_opts(Opts)). - -squery(Pool, Sql) -> - ecpool:with_client(Pool, fun(Client) -> epgsql:squery(Client, Sql) end). -``` - -## Design - -The `ecpool` supervisor tree: - -``` -pool_sup[one_for_all supervisor] - pool[gen-server] - worker_sup[one_for_one supervisor] - worker1 -> connection1 - worker2 -> connection1 - .... -``` - -## Author - -Feng Lee - -## License - -The Apache License Version 2.0 - - diff --git a/_build/emqx/lib/ecpool/rebar.config b/_build/emqx/lib/ecpool/rebar.config deleted file mode 100644 index 29b60bc421..0000000000 --- a/_build/emqx/lib/ecpool/rebar.config +++ /dev/null @@ -1,28 +0,0 @@ -%% -*- mode: erlang;erlang-indent-level: 4;indent-tabs-mode: nil -*- -%% ex: ts=4 sw=4 ft=erlang et - -{require_min_otp_vsn, "R20"}. - -%warnings_as_errors, warn_untyped_record, -{erl_opts, [warn_export_all, - warn_unused_import, - {i, "include"}, - {src_dirs, ["src"]} - ]}. - -{xref_checks, [undefined_function_calls]}. -{cover_enabled, true}. -{cover_print_enabled, true}. - -{edoc_opts, [{dialyzer_specs, all}, - {report_missing_type, true}, - {report_type_mismatch, true}, - {pretty_print, erl_pp}, - {preprocess, true}]}. - -{validate_app_modules, true}. - -{eunit_opts, [verbose]}. - -{deps, [{gproc, "0.8.0"}]}. - diff --git a/_build/emqx/lib/ecpool/src/ecpool.app.src b/_build/emqx/lib/ecpool/src/ecpool.app.src deleted file mode 100644 index fca0b1be78..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool.app.src +++ /dev/null @@ -1,14 +0,0 @@ -{application, ecpool, - [{description, "Erlang Client/Connection Pool"}, - {vsn, "git"}, - {registered, []}, - {applications, [kernel, - stdlib, - gproc - ]}, - {mod, {ecpool_app, []}}, - {env, []}, - {licenses,["Apache-2.0"]}, - {maintainers, ["Feng Lee "]}, - {links,[{"Github","https://hub.fastgit.org/emqx/ecpool"}]} - ]}. diff --git a/_build/emqx/lib/ecpool/src/ecpool.erl b/_build/emqx/lib/ecpool/src/ecpool.erl deleted file mode 100644 index 58b587e91b..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool.erl +++ /dev/null @@ -1,116 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool). - --export([ pool_spec/4 - , start_pool/3 - , start_sup_pool/3 - , stop_sup_pool/1 - , get_client/1 - , get_client/2 - , with_client/2 - , with_client/3 - , name/1 - , workers/1 - ]). - --export([set_reconnect_callback/2, add_reconnect_callback/2]). - --export_type([ pool_name/0 - , pool_type/0 - , option/0 - ]). - --type(pool_name() :: term()). - --type(pool_type() :: random | hash | round_robin). - --type(reconn_callback() :: {fun((pid()) -> term())}). - --type(option() :: {pool_size, pos_integer()} - | {pool_type, pool_type()} - | {auto_reconnect, false | pos_integer()} - | {on_reconnect, reconn_callback()} - | tuple()). - -pool_spec(ChildId, Pool, Mod, Opts) -> - #{id => ChildId, - start => {?MODULE, start_pool, [Pool, Mod, Opts]}, - restart => permanent, - shutdown => 5000, - type => supervisor, - modules => [ecpool_pool_sup]}. - -%% @doc Start the pool sup. --spec(start_pool(atom(), atom(), [option()]) -> {ok, pid()} | {error, term()}). -start_pool(Pool, Mod, Opts) when is_atom(Pool) -> - ecpool_pool_sup:start_link(Pool, Mod, Opts). - -%% @doc Start the pool supervised by ecpool_sup -start_sup_pool(Pool, Mod, Opts) when is_atom(Pool) -> - ecpool_sup:start_pool(Pool, Mod, Opts). - -%% @doc Start the pool supervised by ecpool_sup -stop_sup_pool(Pool) when is_atom(Pool) -> - ecpool_sup:stop_pool(Pool). - -%% @doc Get client/connection --spec(get_client(atom()) -> pid()). -get_client(Pool) -> - gproc_pool:pick_worker(name(Pool)). - -%% @doc Get client/connection with hash key. --spec(get_client(atom(), any()) -> pid()). -get_client(Pool, Key) -> - gproc_pool:pick_worker(name(Pool), Key). - --spec(set_reconnect_callback(atom(), reconn_callback()) -> ok). -set_reconnect_callback(Pool, Callback) -> - [ecpool_worker:set_reconnect_callback(Worker, Callback) - || {_WorkerName, Worker} <- ecpool:workers(Pool)], - ok. - --spec(add_reconnect_callback(atom(), reconn_callback()) -> ok). -add_reconnect_callback(Pool, Callback) -> - [ecpool_worker:add_reconnect_callback(Worker, Callback) - || {_WorkerName, Worker} <- ecpool:workers(Pool)], - ok. - -%% @doc Call the fun with client/connection --spec(with_client(atom(), fun((Client :: pid()) -> any())) -> no_return()). -with_client(Pool, Fun) when is_atom(Pool) -> - with_worker(gproc_pool:pick_worker(name(Pool)), Fun). - -%% @doc Call the fun with client/connection --spec(with_client(atom(), any(), fun((Client :: pid()) -> term())) -> no_return()). -with_client(Pool, Key, Fun) when is_atom(Pool) -> - with_worker(gproc_pool:pick_worker(name(Pool), Key), Fun). - --spec(with_worker(Worker :: pid(), fun((Client :: pid()) -> any())) -> no_return()). -with_worker(Worker, Fun) -> - case ecpool_worker:client(Worker) of - {ok, Client} -> Fun(Client); - {error, Reason} -> {error, Reason} - end. - -%% @doc Pool workers -workers(Pool) -> - gproc_pool:active_workers(name(Pool)). - -%% @doc ecpool name -name(Pool) -> {?MODULE, Pool}. - diff --git a/_build/emqx/lib/ecpool/src/ecpool_app.erl b/_build/emqx/lib/ecpool/src/ecpool_app.erl deleted file mode 100644 index b120c87389..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool_app.erl +++ /dev/null @@ -1,29 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool_app). - --behaviour(application). - -%% Application callbacks --export([start/2, stop/1]). - -start(_StartType, _StartArgs) -> - ecpool_sup:start_link(). - -stop(_State) -> - ok. - diff --git a/_build/emqx/lib/ecpool/src/ecpool_pool.erl b/_build/emqx/lib/ecpool/src/ecpool_pool.erl deleted file mode 100644 index 2d44148f9c..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool_pool.erl +++ /dev/null @@ -1,108 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool_pool). - --behaviour(gen_server). - -%% API Function Exports --export([start_link/2]). - --export([info/1]). - -%% gen_server Function Exports --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --import(proplists, [get_value/3]). - --record(state, {name, size, type}). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - --spec(start_link(ecpool:pool_name(), list(ecpool:option())) - -> {ok, pid()} | {error, term()}). -start_link(Pool, Opts) -> - gen_server:start_link(?MODULE, [Pool, Opts], []). - --spec(info(pid()) -> list()). -info(Pid) -> - gen_server:call(Pid, info). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Pool, Opts]) -> - Schedulers = erlang:system_info(schedulers), - PoolSize = get_value(pool_size, Opts, Schedulers), - PoolType = get_value(pool_type, Opts, random), - ok = ensure_pool(ecpool:name(Pool), PoolType, [{size, PoolSize}]), - ok = lists:foreach( - fun(I) -> - ensure_pool_worker(ecpool:name(Pool), {Pool, I}, I) - end, lists:seq(1, PoolSize)), - {ok, #state{name = Pool, size = PoolSize, type = PoolType}}. - -ensure_pool(Pool, Type, Opts) -> - try gproc_pool:new(Pool, Type, Opts) - catch - error:exists -> ok - end. - -ensure_pool_worker(Pool, Name, Slot) -> - try gproc_pool:add_worker(Pool, Name, Slot) - catch - error:exists -> ok - end. - -handle_call(info, _From, State = #state{name = Pool, size = Size, type = Type}) -> - Workers = ecpool:workers(Pool), - Info = [{pool_name, Pool}, - {pool_size, Size}, - {pool_type, Type}, - {workers, Workers}], - {reply, Info, State}; - -handle_call(Req, _From, State) -> - logger:error("[Pool] unexpected request: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - logger:error("[Pool] unexpected msg: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - logger:error("[Pool] unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #state{name = Pool, size = Size}) -> - lists:foreach( - fun(I) -> - gproc_pool:remove_worker(ecpool:name(Pool), {Pool, I}) - end, lists:seq(1, Size)), - gproc_pool:delete(ecpool:name(Pool)). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - diff --git a/_build/emqx/lib/ecpool/src/ecpool_pool_sup.erl b/_build/emqx/lib/ecpool/src/ecpool_pool_sup.erl deleted file mode 100644 index 4d7d9874a1..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool_pool_sup.erl +++ /dev/null @@ -1,36 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool_pool_sup). - --behaviour(supervisor). - -%% API --export([start_link/3]). - -%% Supervisor callbacks --export([init/1]). - -start_link(Pool, Mod, Opts) -> - supervisor:start_link(?MODULE, [Pool, Mod, Opts]). - -init([Pool, Mod, Opts]) -> - {ok, { {one_for_all, 10, 100}, [ - {pool, {ecpool_pool, start_link, [Pool, Opts]}, - transient, 16#ffff, worker, [ecpool_pool]}, - {worker_sup, {ecpool_worker_sup, start_link, [Pool, Mod, Opts]}, - transient, infinity, supervisor, [ecpool_worker_sup]}] }}. - diff --git a/_build/emqx/lib/ecpool/src/ecpool_sup.erl b/_build/emqx/lib/ecpool/src/ecpool_sup.erl deleted file mode 100644 index b539544334..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool_sup.erl +++ /dev/null @@ -1,90 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool_sup). - --behaviour(supervisor). - --export([start_link/0]). - -%% API --export([ start_pool/3 - , stop_pool/1 - , get_pool/1 - ]). - --export([pools/0]). - -%% Supervisor callbacks --export([init/1]). - -%% @doc Start supervisor. --spec(start_link() -> {ok, pid()} | {error, term()}). -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%%-------------------------------------------------------------------- -%% Start/Stop a pool -%%-------------------------------------------------------------------- - -%% @doc Start a pool. --spec(start_pool(atom(), atom(), list(tuple())) -> {ok, pid()} | {error, term()}). -start_pool(Pool, Mod, Opts) when is_atom(Pool) -> - supervisor:start_child(?MODULE, pool_spec(Pool, Mod, Opts)). - -%% @doc Stop a pool. --spec(stop_pool(Pool :: atom()) -> ok | {error, term()}). -stop_pool(Pool) when is_atom(Pool) -> - ChildId = child_id(Pool), - case supervisor:terminate_child(?MODULE, ChildId) of - ok -> - supervisor:delete_child(?MODULE, ChildId); - {error, Reason} -> - {error, Reason} - end. - -%% @doc Get a pool. --spec(get_pool(atom()) -> undefined | pid()). -get_pool(Pool) when is_atom(Pool) -> - ChildId = child_id(Pool), - case [Pid || {Id, Pid, supervisor, _} <- supervisor:which_children(?MODULE), Id =:= ChildId] of - [] -> undefined; - L -> hd(L) - end. - -%% @doc Get All Pools supervisored by the ecpool_sup. --spec(pools() -> [{atom(), pid()}]). -pools() -> - [{Pool, Pid} || {{pool_sup, Pool}, Pid, supervisor, _} - <- supervisor:which_children(?MODULE)]. - -%%-------------------------------------------------------------------- -%% Supervisor callbacks -%%-------------------------------------------------------------------- - -init([]) -> - {ok, { {one_for_one, 10, 100}, []} }. - -pool_spec(Pool, Mod, Opts) -> - #{id => child_id(Pool), - start => {ecpool_pool_sup, start_link, [Pool, Mod, Opts]}, - restart => transient, - shutdown => infinity, - type => supervisor, - modules => [ecpool_pool_sup]}. - -child_id(Pool) -> {pool_sup, Pool}. - diff --git a/_build/emqx/lib/ecpool/src/ecpool_worker.erl b/_build/emqx/lib/ecpool/src/ecpool_worker.erl deleted file mode 100644 index 182a6c4970..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool_worker.erl +++ /dev/null @@ -1,239 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool_worker). - --behaviour(gen_server). - --export([start_link/4]). - -%% API Function Exports --export([ client/1 - , is_connected/1 - , set_reconnect_callback/2 - , add_reconnect_callback/2 - ]). - -%% gen_server Function Exports --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --record(state, { - pool :: ecpool:poo_name(), - id :: pos_integer(), - client :: pid() | undefined, - mod :: module(), - on_reconnect :: ecpool:reconn_callback(), - on_disconnect :: ecpool:reconn_callback(), - supervisees = [], - opts :: proplists:proplist() - }). - -%%-------------------------------------------------------------------- -%% Callback -%%-------------------------------------------------------------------- - --ifdef(use_specs). - --callback(connect(ConnOpts :: list()) - -> {ok, pid()} | {error, Reason :: term()}). - --else. - --export([behaviour_info/1]). - -behaviour_info(callbacks) -> - [{connect, 1}]; -behaviour_info(_Other) -> - undefined. - --endif. - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -%% @doc Start a pool worker. --spec(start_link(atom(), pos_integer(), module(), list()) -> - {ok, pid()} | ignore | {error, any()}). -start_link(Pool, Id, Mod, Opts) -> - gen_server:start_link(?MODULE, [Pool, Id, Mod, Opts], []). - -%% @doc Get client/connection. --spec(client(pid()) -> {ok, Client :: pid()} | {error, Reason :: term()}). -client(Pid) -> - gen_server:call(Pid, client, infinity). - -%% @doc Is client connected? --spec(is_connected(pid()) -> boolean()). -is_connected(Pid) -> - gen_server:call(Pid, is_connected, infinity). - --spec(set_reconnect_callback(pid(), ecpool:reconn_callback()) -> ok). -set_reconnect_callback(Pid, OnReconnect) -> - gen_server:cast(Pid, {set_reconn_callbk, OnReconnect}). - --spec(add_reconnect_callback(pid(), ecpool:reconn_callback()) -> ok). -add_reconnect_callback(Pid, OnReconnect) -> - gen_server:cast(Pid, {add_reconn_callbk, OnReconnect}). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Pool, Id, Mod, Opts]) -> - process_flag(trap_exit, true), - State = #state{pool = Pool, - id = Id, - mod = Mod, - opts = Opts, - on_reconnect = proplists:get_value(on_reconnect, Opts), - on_disconnect = proplists:get_value(on_disconnect, Opts) - }, - case connect_internal(State) of - {ok, NewState} -> - gproc_pool:connect_worker(ecpool:name(Pool), {Pool, Id}), - {ok, NewState}; - {error, Error} -> {stop, Error} - end. - -handle_call(is_connected, _From, State = #state{client = Client}) when is_pid(Client) -> - IsAlive = Client =/= undefined andalso is_process_alive(Client), - {reply, IsAlive, State}; - -handle_call(is_connected, _From, State = #state{client = Client}) -> - {reply, Client =/= undefined, State}; - -handle_call(client, _From, State = #state{client = undefined}) -> - {reply, {error, disconnected}, State}; - -handle_call(client, _From, State = #state{client = Client}) -> - {reply, {ok, Client}, State}; - -handle_call(Req, _From, State) -> - logger:error("[PoolWorker] unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({set_reconn_callbk, OnReconnect}, State) -> - {noreply, State#state{on_reconnect = OnReconnect}}; - -handle_cast({add_reconn_callbk, OnReconnect}, State = #state{on_reconnect = OnReconnectList}) when is_list(OnReconnectList) -> - {noreply, State#state{on_reconnect = [OnReconnect | OnReconnectList]}}; - -handle_cast({add_reconn_callbk, OnReconnect}, State = #state{on_reconnect = undefined}) -> - {noreply, State#state{on_reconnect = [OnReconnect]}}; - -handle_cast({add_reconn_callbk, OnReconnect}, State = #state{on_reconnect = OnReconnect0}) -> - {noreply, State#state{on_reconnect = [OnReconnect, OnReconnect0]}}; - -handle_cast(_Msg, State) -> - {noreply, State}. - -handle_info({'EXIT', Pid, Reason}, State = #state{opts = Opts, supervisees = SupPids}) -> - case lists:member(Pid, SupPids) of - true -> - case proplists:get_value(auto_reconnect, Opts, false) of - false -> {stop, Reason, State}; - Secs -> reconnect(Secs, State) - end; - false -> - logger:debug("~p received unexpected exit:~0p from ~p. Supervisees: ~p", - [?MODULE, Reason, Pid, SupPids]), - {noreply, State} - end; - -handle_info(reconnect, State = #state{opts = Opts, on_reconnect = OnReconnect}) -> - case connect_internal(State) of - {ok, NewState = #state{client = Client}} -> - handle_reconnect(Client, OnReconnect), - {noreply, NewState}; - {Err, _Reason} when Err =:= error orelse Err =:= 'EXIT' -> - reconnect(proplists:get_value(auto_reconnect, Opts), State) - end; - -handle_info(Info, State) -> - logger:error("[PoolWorker] unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #state{pool = Pool, id = Id, - client = Client, - on_disconnect = Disconnect}) -> - handle_disconnect(Client, Disconnect), - gproc_pool:disconnect_worker(ecpool:name(Pool), {Pool, Id}). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal Functions -%%-------------------------------------------------------------------- - -connect(#state{mod = Mod, opts = Opts, id = Id}) -> - Mod:connect([{ecpool_worker_id, Id} | connopts(Opts, [])]). - -connopts([], Acc) -> - Acc; -connopts([{Key, _}|Opts], Acc) - when Key =:= pool_size; - Key =:= pool_type; - Key =:= auto_reconnect; - Key =:= on_reconnect -> - connopts(Opts, Acc); - -connopts([Opt|Opts], Acc) -> - connopts(Opts, [Opt|Acc]). - -reconnect(Secs, State = #state{client = Client, on_disconnect = Disconnect, supervisees = SubPids}) -> - [erlang:unlink(P) || P <- SubPids, is_pid(P)], - handle_disconnect(Client, Disconnect), - erlang:send_after(timer:seconds(Secs), self(), reconnect), - {noreply, State#state{client = undefined}}. - -handle_reconnect(_, undefined) -> - ok; -handle_reconnect(undefined, _) -> - ok; -handle_reconnect(Client, OnReconnectList) when is_list(OnReconnectList) -> - [OnReconnect(Client) || OnReconnect <- OnReconnectList]; -handle_reconnect(Client, OnReconnect) -> - OnReconnect(Client). - -handle_disconnect(undefined, _) -> - ok; -handle_disconnect(_, undefined) -> - ok; -handle_disconnect(Client, Disconnect) -> - Disconnect(Client). - -connect_internal(State) -> - try connect(State) of - {ok, Client} when is_pid(Client) -> - erlang:link(Client), - {ok, State#state{client = Client, supervisees = [Client]}}; - {ok, Client, #{supervisees := SupPids} = _SupOpts} when is_list(SupPids) -> - [erlang:link(P) || P <- SupPids], - {ok, State#state{client = Client, supervisees = SupPids}}; - {error, Error} -> - {error, Error} - catch - _C:Reason -> {error, Reason} - end. - diff --git a/_build/emqx/lib/ecpool/src/ecpool_worker_sup.erl b/_build/emqx/lib/ecpool/src/ecpool_worker_sup.erl deleted file mode 100644 index c4e2092a93..0000000000 --- a/_build/emqx/lib/ecpool/src/ecpool_worker_sup.erl +++ /dev/null @@ -1,43 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ecpool_worker_sup). - --behaviour(supervisor). - --export([start_link/3]). - --export([init/1]). - -start_link(Pool, Mod, Opts) when is_atom(Pool) -> - supervisor:start_link(?MODULE, [Pool, Mod, Opts]). - -init([Pool, Mod, Opts]) -> - WorkerSpec = fun(Id) -> - #{id => {worker, Id}, - start => {ecpool_worker, start_link, [Pool, Id, Mod, Opts]}, - restart => transient, - shutdown => 5000, - type => worker, - modules => [ecpool_worker, Mod]} - end, - Workers = [WorkerSpec(I) || I <- lists:seq(1, pool_size(Opts))], - {ok, { {one_for_one, 10, 60}, Workers} }. - -pool_size(Opts) -> - Schedulers = erlang:system_info(schedulers), - proplists:get_value(pool_size, Opts, Schedulers). - diff --git a/_build/emqx/lib/ekka/.github/workflows/run_test_case.yaml b/_build/emqx/lib/ekka/.github/workflows/run_test_case.yaml deleted file mode 100644 index d7f6a4130f..0000000000 --- a/_build/emqx/lib/ekka/.github/workflows/run_test_case.yaml +++ /dev/null @@ -1,34 +0,0 @@ -name: Run test case - -on: [push, pull_request] - -jobs: - - run_test_case: - - runs-on: ubuntu-latest - - container: - image: erlang:22.1 - - steps: - - uses: actions/checkout@v1 - - name: Run tests - run: | - make eunit - make ct - make cover - - name: Coveralls - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - make coveralls - - uses: actions/upload-artifact@v1 - if: always() - with: - name: logs - path: _build/test/logs - - uses: actions/upload-artifact@v1 - with: - name: cover - path: _build/test/cover diff --git a/_build/emqx/lib/ekka/.gitignore b/_build/emqx/lib/ekka/.gitignore deleted file mode 100644 index 0aa48e9f54..0000000000 --- a/_build/emqx/lib/ekka/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -.eunit -deps -*.o -*.beam -*.plt -*.swp -erl_crash.dump -ebin/* -rel/example_project -.concrete/DEV_MODE -.rebar -.erlang.mk/ -!data/app.etcd.config -ekka.d -Mnesia* -logs/ -.DS_Store -cover/ -ct.coverdata -ebin/test -eunit.coverdata -test/ct.cover.spec -log/ -.erlang.mk/ -erlang.mk -ekka.d -_build/ -.rebar3/ -rebar.lock diff --git a/_build/emqx/lib/ekka/LICENSE b/_build/emqx/lib/ekka/LICENSE deleted file mode 100644 index 8dada3edaf..0000000000 --- a/_build/emqx/lib/ekka/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/_build/emqx/lib/ekka/Makefile b/_build/emqx/lib/ekka/Makefile deleted file mode 100644 index 3a90db05ef..0000000000 --- a/_build/emqx/lib/ekka/Makefile +++ /dev/null @@ -1,48 +0,0 @@ -REBAR := rebar3 - -CT_NODE_NAME = ct@127.0.0.1 - -.PHONY: all -all: compile - -compile: - $(REBAR) compile - -.PHONY: clean -clean: distclean - -.PHONY: distclean -distclean: - @rm -rf _build erl_crash.dump rebar3.crashdump rebar.lock - -.PHONY: xref -xref: - $(REBAR) xref - -.PHONY: eunit -eunit: compile - $(REBAR) eunit verbose=true - -.PHONY: ct -ct: compile - $(REBAR) as test ct -v --readable=false --name $(CT_NODE_NAME) - -cover: - $(REBAR) cover - -.PHONY: coveralls -coveralls: - @rebar3 as test coveralls send - -.PHONY: dialyzer -dialyzer: - $(REBAR) dialyzer - -CUTTLEFISH_SCRIPT = _build/default/lib/cuttlefish/cuttlefish - -$(CUTTLEFISH_SCRIPT): - @${REBAR} get-deps - @if [ ! -f cuttlefish ]; then make -C _build/default/lib/cuttlefish; fi - -app.config: $(CUTTLEFISH_SCRIPT) - $(verbose) $(CUTTLEFISH_SCRIPT) -l info -e etc/ -c etc/ekka.conf.example -i priv/ekka.schema -d data/ diff --git a/_build/emqx/lib/ekka/README.md b/_build/emqx/lib/ekka/README.md deleted file mode 100644 index 22491c4edb..0000000000 --- a/_build/emqx/lib/ekka/README.md +++ /dev/null @@ -1,345 +0,0 @@ - -# Ekka - -Ekka - Autocluster and Autoheal for EMQ X Broker. Ekka helps build a new distribution layer for EMQ X R2.3+. - -``` ----------- ---------- -| EMQX |<--- MQTT--->| EMQX | -|--------| |--------| -| Ekka |<----RPC---->| Ekka | -|--------| |--------| -| Mnesia |<--Cluster-->| Mnesia | -|--------| |--------| -| Kernel |<----TCP---->| Kernel | ----------- ---------- -``` - -## Node discovery and Autocluster - -Ekka supports erlang node discovery and autocluster using various strategies: - -Strategy | Description ------------|-------------------------------------- -manual | Join cluster manually -static | Static node list -mcast | IP Multicast -dns | DNS A Records -etcd | etcd -k8s | Kubernetes - -The configuration example files are under 'etc/' folder. - -### Cluster using static node list - -Cuttlefish style config: - -``` -cluster.discovery = static - -cluster.static.seeds = ekka1@127.0.0.1,ekka2@127.0.0.1 -``` - -Erlang config: - -``` -{cluster_discovery, - {static, [ - {seeds, ['ekka1@127.0.0.1', 'ekka2@127.0.0.1']} - ]}}, -``` - -### Cluster using IP Multicast - -Cuttlefish style config: - -``` -cluster.discovery = mcast - -## IP Multicast Address. -## -## Value: IP Address -cluster.mcast.addr = 239.192.0.1 - -## Multicast Ports. -## -## Value: Port List -cluster.mcast.ports = 4369,4370 - -## Multicast Iface. -## -## Value: Iface Address -## -## Default: 0.0.0.0 -cluster.mcast.iface = 0.0.0.0 - -## Multicast Ttl. -## -## Value: 0-255 -cluster.mcast.ttl = 255 - -## Multicast loop. -## -## Value: on | off -cluster.mcast.loop = on -``` - -Erlang config: - -``` -{cluster_discovery, - {mcast, [ - {addr, {239,192,0,1}}, - {ports, [4369,4370]}, - {iface, {0,0,0,0}}, - {ttl, 255}, - {loop, true} - ]}}, -``` - -### Cluster using DNS A records - -Cuttlefish style config: - -``` -cluster.discovery = dns - -## DNS name. -## -## Value: String -cluster.dns.name = localhost - -## The App name is used to build 'node.name' with IP address. -## -## Value: String -cluster.dns.app = ekka -``` - -Erlang config: - -``` -{cluster_discovery, - {dns, [ - {name, "localhost"}, - {app, "ekka"} - ]}}, -``` - -### Cluster using etcd - -Cuttlefish style config: - -``` -cluster.discovery = etcd - -## Etcd server list, seperated by ','. -## -## Value: String -cluster.etcd.server = http://127.0.0.1:2379 - -## The prefix helps build nodes path in etcd. Each node in the cluster -## will create a path in etcd: v2/keys/// -## -## Value: String -cluster.etcd.prefix = ekkacl - -## The TTL for node's path in etcd. -## -## Value: Duration -## -## Default: 1m, 1 minute -cluster.etcd.node_ttl = 1m - -## Path to a file containing the client's private PEM-encoded key. -## -## Value: File -## -## cluster.etcd.keyfile = {{platform_etc_dir}}/certs/client-key.pem - -## Path to the file containing the client's certificate -## -## Value: File -## -## cluster.etcd.certfile = {{platform_etc_dir}}/certs/client.pem - -## Path to the file containing PEM-encoded CA certificates. The CA certificates -## are used during server authentication and when building the client certificate chain. -## -## Value: File -## -## cluster.etcd.cacertfile = {{platform_etc_dir}}/certs/ca.pem -``` - -Erlang config: - -``` -{cluster_discovery, - {etcd, [ - {server, ["http://127.0.0.1:2379"]}, - {prefix, "ekkacluster"}, - %%{ssl_options, [ - %% {keyfile, "path/to/client-key.pem"}, - %% {certfile, "path/to/client.pem"}, - %% {cacertfile, "path/to/ca.pem"} - %%]}, - {node_ttl, 60000} - ]}}, -``` - -### Cluster using Kubernates - -Cuttlefish style config: - -``` -cluster.discovery = k8s - -## Kubernates API server list, seperated by ','. -## -## Value: String -## cluster.k8s.apiserver = http://10.110.111.204:8080 - -## The service name helps lookup EMQ nodes in the cluster. -## -## Value: String -## cluster.k8s.service_name = ekka - -## The name space of k8s -## -## Value: String -## cluster.k8s.namespace = default - -## The address type is used to extract host from k8s service. -## -## Value: ip | dns | hostname -## cluster.k8s.address_type = ip - -## The app name helps build 'node.name'. -## -## Value: String -## cluster.k8s.app_name = ekka - -## The suffix added to dns and hostname get from k8s service -## -## Value: String -## cluster.k8s.suffix = pod.cluster.local -``` - -Erlang config: - -``` -{cluster_discovery, - {k8s, [ - {apiserver, "http://10.110.111.204:8080"}, - {namespace, "default"}, - {service_name, "ekka"}, - {address_type, ip}, - {app_name, "ekka"}, - {suffix, "pod.cluster.local"} - ]}} -``` - -## Network partition and Autoheal - -### Autoheal Design - -When network partition occurs, the following steps to heal the cluster if autoheal is enabled: - -1. Node reports the partitions to a leader node which has the oldest guid. - -2. Leader node create a global netsplit view and choose one node in the majority as coordinator. - -3. Leader node requests the coordinator to autoheal the network partition. - -4. Coordinator node reboots all the nodes in the minority side. - -### Enable autoheal - -Erlang config: - -``` -{cluster_autoheal, true}, -``` - -Cuttlefish style config: - -``` -cluster.autoheal = on -``` - -## Node down and Autoclean - -### Autoclean Design - -A down node will be removed from the cluster if autoclean is enabled. - -### Enable autoclean - -Erlang config: - -``` -{cluster_autoclean, 60000}, -``` - -Cuttlefish style config: - -``` -cluster.autoclean = 5m -``` - -## Lock Service - -Ekka implements a simple distributed lock service in 0.3 release. The Lock APIs: - -Acquire lock: - -``` --spec(acquire(resource()) -> {boolean(), [node()]}). -ekka_locker:acquire(Resource). - --spec(acquire(atom(), resource(), lock_type()) -> lock_result()). -ekka_locker:acquire(ekka_locker, Resource, Type). -``` - -Release lock: - -``` --spec(release(resource()) -> lock_result()). -ekka_locker:release(Resource). - --spec(release(atom(), resource()) -> lock_result()). -ekka_locker:release(Name, Resource). -``` - -The lock type: - -``` --type(lock_type() :: local | leader | quorum | all). -``` - -## Cluster without epmd - -The ekka 0.6.0 release implements erlang distribiton without epmd. - -See: http://erlang.org/pipermail/erlang-questions/2015-December/087013.html - -For example: - -``` -## Dist port: 4370 -erl -pa ebin -pa _build/default/lib/*/ebin -proto_dist ekka -start_epmd false -epmd_module ekka_epmd -name node1@127.0.0.1 -s ekka -## Dist port: 4371 -erl -pa ebin -pa _build/default/lib/*/ebin -proto_dist ekka -start_epmd false -epmd_module ekka_epmd -name node2@127.0.0.1 -s ekka -## Dist port: 4372 -erl -pa ebin -pa _build/default/lib/*/ebin -proto_dist ekka -start_epmd false -epmd_module ekka_epmd -name node3@127.0.0.1 -s ekka -``` - -The erlang distribution port can be tuned by ekka `inet_dist_base_port` env. The default port is 4370. - -## License - -Apache License Version 2.0 - -## Author - -EMQ X Team. - diff --git a/_build/emqx/lib/ekka/data/app.etcd.config b/_build/emqx/lib/ekka/data/app.etcd.config deleted file mode 100644 index 09fb105cf2..0000000000 --- a/_build/emqx/lib/ekka/data/app.etcd.config +++ /dev/null @@ -1,6 +0,0 @@ -[{ekka,[{cluster_autoheal,true}, - {cluster_autoclean,300000}, - {cluster_name,ekka}, - {cluster_discovery,{etcd,[{server,["http://127.0.0.1:2379"]}, - {prefix,"ekkacluster"}, - {node_ttl,60000}]}}]}]. diff --git a/_build/emqx/lib/ekka/data/app.mcast.config b/_build/emqx/lib/ekka/data/app.mcast.config deleted file mode 100644 index 2221300d4f..0000000000 --- a/_build/emqx/lib/ekka/data/app.mcast.config +++ /dev/null @@ -1,11 +0,0 @@ -[{ekka, [ - {cluster_autoheal,true}, - {cluster_autoclean,300000}, - {cluster_name,ekka}, - {cluster_discovery, {mcast, [ - {addr,{239,192,0,1}}, - {ports,[4369,4370,4371,4372,4373]}, - {iface,{0,0,0,0}}, - {ttl, 255}, - {loop,true}]}} -]}]. diff --git a/_build/emqx/lib/ekka/etc/ekka.conf.example b/_build/emqx/lib/ekka/etc/ekka.conf.example deleted file mode 100644 index aa95908c2b..0000000000 --- a/_build/emqx/lib/ekka/etc/ekka.conf.example +++ /dev/null @@ -1,181 +0,0 @@ -##-------------------------------------------------------------------- -## Cluster -##-------------------------------------------------------------------- - -## Cluster name. -## -## Value: String -cluster.name = ekka - -## Enable cluster mode. -## -## Value: on | off -## -## Default: on -cluster.enable = on - -## Cluster auto-discovery strategy. -## -## Value: Enum -## - manual: Manual join command -## - static: Static node list -## - mcast: IP Multicast -## - dns: DNS A Records -## - etcd: etcd -## - k8s: Kubernates -## -## Default: manual -cluster.discovery = manual - -## Enable cluster autoheal from network partition. -## -## Value: on | off | Duration -## -## Default: 15 Seconds -cluster.autoheal = 15s - -## Autoclean down node. A down node will be removed from the cluster -## if this value > 0. -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 5m -cluster.autoclean = 5m - -## Specify the erlang distributed protocol for the cluster. -## -## Value: Enum -## - inet_tcp: the default; handles TCP streams with IPv4 addressing. -## - inet6_tcp: handles TCP with IPv6 addressing. -## - inet_tls: using TLS for Erlang Distribution. -## -## vm.args: -proto_dist inet_tcp -cluster.proto_dist = inet_tcp - -##-------------------------------------------------------------------- -## Cluster using static node list. - -## Node list of the cluster. -## -## Value: String -## cluster.static.seeds = ekka1@127.0.0.1,ekka2@127.0.0.1 - -##-------------------------------------------------------------------- -## Cluster using IP Multicast. - -## IP Multicast Address. -## -## Value: IP Address -## cluster.mcast.addr = 239.192.0.1 - -## Multicast Ports. -## -## Value: Port List -## cluster.mcast.ports = 4369,4370 - -## Multicast Iface. -## -## Value: Iface Address -## -## Default: 0.0.0.0 -## cluster.mcast.iface = 0.0.0.0 - -## Multicast Ttl. -## -## Value: 0-255 -## cluster.mcast.ttl = 255 - -## Multicast loop. -## -## Value: on | off -## cluster.mcast.loop = on - -##-------------------------------------------------------------------- -## Cluster using DNS A records. - -## DNS name. -## -## Value: String -## cluster.dns.name = localhost - -## The App name is used to build 'node.name' with IP address. -## -## Value: String -## cluster.dns.app = ekka - -##-------------------------------------------------------------------- -## Cluster using etcd - -## Etcd server list, seperated by ','. -## -## Value: String -## cluster.etcd.server = http://127.0.0.1:2379 - -## The prefix helps build nodes path in etcd. Each node in the cluster -## will create a path in etcd: v2/keys/// -## -## Value: String -## cluster.etcd.prefix = ekkacl - -## The TTL for node's path in etcd. -## -## Value: Duration -## -## Default: 1m, 1 minute -## cluster.etcd.node_ttl = 1m - -## Path to a file containing the client's private PEM-encoded key. -## -## Value: File -## -## cluster.etcd.keyfile = {{platform_etc_dir}}/certs/client-key.pem - -## Path to the file containing the client's certificate -## -## Value: File -## -## cluster.etcd.certfile = {{platform_etc_dir}}/certs/client.pem - -## Path to the file containing PEM-encoded CA certificates. The CA certificates -## are used during server authentication and when building the client certificate chain. -## -## Value: File -## -## cluster.etcd.cacertfile = {{platform_etc_dir}}/certs/ca.pem - -##-------------------------------------------------------------------- -## Cluster using Kubernates - -## Kubernates API server list, seperated by ','. -## -## Value: String -## cluster.k8s.apiserver = http://10.110.111.204:8080 - -## The service name helps lookup EMQ nodes in the cluster. -## -## Value: String -## cluster.k8s.service_name = ekka - -## The name space of k8s -## -## Value: String -## cluster.k8s.namespace = default - -## The address type is used to extract host from k8s service. -## -## Value: ip | dns | hostname -## cluster.k8s.address_type = ip - -## The app name helps build 'node.name'. -## -## Value: String -## cluster.k8s.app_name = ekka - -## The suffix added to dns and hostname get from k8s service -## -## Value: String -## cluster.k8s.suffix = pod.cluster.local - diff --git a/_build/emqx/lib/ekka/etc/ekka.config.example b/_build/emqx/lib/ekka/etc/ekka.config.example deleted file mode 100644 index 37feae5f75..0000000000 --- a/_build/emqx/lib/ekka/etc/ekka.config.example +++ /dev/null @@ -1,49 +0,0 @@ -[{ekka, [ - {cluster_name, ekka}, - {cluster_autoheal, true}, - {cluster_autoclean, 60000}, - {proto_dist, inet_tcp}, - -%% Clustering via static node list -%% {cluster_discovery, {static, [ -%% {seeds, ['ekka1@127.0.0.1', 'ekka2@127.0.0.1']} -%% ]}}, - -%% Clustering via IP Multicast -%% {cluster_discovery, {mcast, [ -%% {addr, {239,192,0,1}}, -%% {ports, [4369,4370]}, -%% {iface, {0,0,0,0}}, -%% {ttl, 255}, -%% {loop, true} -%% ]}}, - -%% Clustering via DNS A Record -%% {cluster_discovery, {dns, [ -%% {name, "localhost"}, -%% {app, "ekka"} -%% ]}}, - -%% Clustering via etcd -%% {cluster_discovery, {etcd, [ -%% {server, ["http://127.0.0.1:2379"]}, -%% {prefix, "ekkacluster"}, -%% {ssl_options, [{keyfile, "path/to/client-key.pem"}, -%% {certfile, "path/to/client.pem"}, -%% {cacertfile, "path/to/ca.pem"} -%% ]}, -%% {node_ttl, 60000} -%% ]}}, - -%% Clustering via k8s -%% {cluster_discovery, {k8s, [ -%% {apiserver, "http://10.110.111.204:8080"}, -%% {namespace, "default"}, -%% {service_name, "ekka"}, -%% {address_type, ip}, -%% {app_name, "ekka"}, -%% {suffix, "pod.cluster.local"} -%% ]}}, - - {cluster_discovery, {manual, []}} -]}]. diff --git a/_build/emqx/lib/ekka/include/ekka.hrl b/_build/emqx/lib/ekka/include/ekka.hrl deleted file mode 100644 index 4d38cccead..0000000000 --- a/_build/emqx/lib/ekka/include/ekka.hrl +++ /dev/null @@ -1,19 +0,0 @@ - --type(cluster() :: atom()). - --type(member_status() :: joining | up | healing | leaving | down). - --type(member_address() :: {inet:ip_address(), inet:port_number()}). - --record(member, { - node :: node(), - addr :: undefined | member_address(), - guid :: ekka_guid:guid(), - hash :: pos_integer(), - status :: member_status(), - mnesia :: running | stopped | false, - ltime :: erlang:timestamp() - }). - --type(member() :: #member{}). - diff --git a/_build/emqx/lib/ekka/priv/ekka.schema b/_build/emqx/lib/ekka/priv/ekka.schema deleted file mode 100644 index d409b316c0..0000000000 --- a/_build/emqx/lib/ekka/priv/ekka.schema +++ /dev/null @@ -1,200 +0,0 @@ -%%-------------------------------------------------------------------- -%% Cluster -%%-------------------------------------------------------------------- - -%% @doc Cluster name -{mapping, "cluster.name", "ekka.cluster_name", [ - {default, ekka}, - {datatype, atom} -]}. - -%% @doc Cluster enable -{mapping, "cluster.enable", "ekka.cluster_enable", [ - {default, on}, - {datatype, flag} -]}. - -%% @doc Cluster discovery -{mapping, "cluster.discovery", "ekka.cluster_discovery", [ - {default, manual}, - {datatype, atom} -]}. - -%% @doc Clean down node from the cluster -{mapping, "cluster.autoclean", "ekka.cluster_autoclean", [ - {datatype, {duration, ms}} -]}. - -%% @doc Cluster autoheal -{mapping, "cluster.autoheal", "ekka.cluster_autoheal", [ - {datatype, [flag, {duration, ms}]}, - {default, off} -]}. - -%% @doc The erlang distributed protocol for the cluster -{mapping, "cluster.proto_dist", "ekka.proto_dist", [ - {default, inet_tcp}, - {datatype, {enum, [inet_tcp, inet6_tcp, inet_tls]}} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by static node list - -{mapping, "cluster.static.seeds", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster using UDP Multicast - -{mapping, "cluster.mcast.addr", "ekka.cluster_discovery", [ - {default, "239.192.0.1"}, - {datatype, string} -]}. - -{mapping, "cluster.mcast.ports", "ekka.cluster_discovery", [ - {default, "4369"}, - {datatype, string} -]}. - -{mapping, "cluster.mcast.iface", "ekka.cluster_discovery", [ - {datatype, string}, - {default, "0.0.0.0"} -]}. - -{mapping, "cluster.mcast.ttl", "ekka.cluster_discovery", [ - {datatype, integer}, - {default, 255} -]}. - -{mapping, "cluster.mcast.loop", "ekka.cluster_discovery", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "cluster.mcast.sndbuf", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "16KB"} -]}. - -{mapping, "cluster.mcast.recbuf", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "16KB"} -]}. - -{mapping, "cluster.mcast.buffer", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "32KB"} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by DNS A Record - -{mapping, "cluster.dns.name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.dns.app", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster using etcd - -{mapping, "cluster.etcd.server", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.prefix", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.node_ttl", "ekka.cluster_discovery", [ - {datatype, {duration, ms}}, - {default, "1m"} -]}. - -{mapping, "cluster.etcd.ssl.keyfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.ssl.certfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.ssl.cacertfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster on K8s - -{mapping, "cluster.k8s.apiserver", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.service_name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.address_type", "ekka.cluster_discovery", [ - {datatype, {enum, [ip, dns, hostname]}} -]}. - -{mapping, "cluster.k8s.app_name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.namespace", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.suffix", "ekka.cluster_discovery", [ - {datatype, string}, - {default, ""} -]}. - -{translation, "ekka.cluster_discovery", fun(Conf) -> - Strategy = cuttlefish:conf_get("cluster.discovery", Conf), - Filter = fun(Opts) -> [{K, V} || {K, V} <- Opts, V =/= undefined] end, - IpPort = fun(S) -> - [Addr, Port] = string:tokens(S, ":"), - {ok, Ip} = inet:parse_address(Addr), - {Ip, Port} - end, - Options = fun(static) -> - [{seeds, [list_to_atom(S) || S <- string:tokens(cuttlefish:conf_get("cluster.static.seeds", Conf, ""), ",")]}]; - (mcast) -> - {ok, Addr} = inet:parse_address(cuttlefish:conf_get("cluster.mcast.addr", Conf)), - {ok, Iface} = inet:parse_address(cuttlefish:conf_get("cluster.mcast.iface", Conf)), - Ports = [list_to_integer(S) || S <- string:tokens(cuttlefish:conf_get("cluster.mcast.ports", Conf), ",")], - [{addr, Addr}, {ports, Ports}, {iface, Iface}, - {ttl, cuttlefish:conf_get("cluster.mcast.ttl", Conf, 1)}, - {loop, cuttlefish:conf_get("cluster.mcast.loop", Conf, true)}]; - (dns) -> - [{name, cuttlefish:conf_get("cluster.dns.name", Conf)}, - {app, cuttlefish:conf_get("cluster.dns.app", Conf)}]; - (etcd) -> - SslOpts = fun(Conf) -> - Options = cuttlefish_variable:filter_by_prefix("cluster.etcd.ssl", Conf), - lists:map(fun({["cluster", "etcd", "ssl", Name], Value}) -> - {list_to_atom(Name), Value} - end, Options) - end, - [{server, string:tokens(cuttlefish:conf_get("cluster.etcd.server", Conf), ",")}, - {prefix, cuttlefish:conf_get("cluster.etcd.prefix", Conf, "emqcl")}, - {node_ttl, cuttlefish:conf_get("cluster.etcd.node_ttl", Conf, 60)}, - {ssl_options, SslOpts(Conf)}]; - (k8s) -> - [{apiserver, cuttlefish:conf_get("cluster.k8s.apiserver", Conf)}, - {service_name, cuttlefish:conf_get("cluster.k8s.service_name", Conf)}, - {address_type, cuttlefish:conf_get("cluster.k8s.address_type", Conf, ip)}, - {app_name, cuttlefish:conf_get("cluster.k8s.app_name", Conf)}, - {namespace, cuttlefish:conf_get("cluster.k8s.namespace", Conf)}, - {suffix, cuttlefish:conf_get("cluster.k8s.suffix", Conf, "")}]; - (manual) -> - [ ] - end, - {Strategy, Filter(Options(Strategy))} -end}. - diff --git a/_build/emqx/lib/ekka/rebar.config b/_build/emqx/lib/ekka/rebar.config deleted file mode 100644 index 3adfa76b81..0000000000 --- a/_build/emqx/lib/ekka/rebar.config +++ /dev/null @@ -1,35 +0,0 @@ -{minimum_otp_vsn, "21.0"}. - -{deps, [{jsx, "2.10.0"}]}. - -{erl_opts, [warn_unused_vars, - warn_shadow_vars, - warn_unused_import, - warn_obsolete_guard, - debug_info, - compressed %% for edge - ]}. - -{validate_app_modules, true}. - -{xref_checks, [undefined_function_calls, undefined_functions, - locals_not_used, deprecated_function_calls, - warnings_as_errors, deprecated_functions - ]}. - -{eunit_opts, [verbose, {report,{eunit_surefire,[{dir,"."}]}}]}. - -{cover_enabled, true}. -{cover_opts, [verbose]}. -{cover_export_enabled, true}. - -{dialyzer, []}. -{dialyzer_base_plt_apps, [kernel, stdlib, erts, sasl, ssl, syntax_tools, compiler, crypto, jsx]}. - -{profiles, - [{test, - [{plugins, [{coveralls, {git, "https://hub.fastgit.org/emqx/coveralls-erl", {branch, "github"}}}]}, - {deps, [{meck, "0.8.13"}, {proper, "1.3.0"}]}, - {erl_opts, [debug_info]} - ]} - ]}. diff --git a/_build/emqx/lib/ekka/rebar.config.script b/_build/emqx/lib/ekka/rebar.config.script deleted file mode 100644 index 5447ffb33c..0000000000 --- a/_build/emqx/lib/ekka/rebar.config.script +++ /dev/null @@ -1,20 +0,0 @@ -%% -*-: erlang -*- - -case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of - {"true", Token} when is_list(Token) -> - CONFIG1 = [{coveralls_repo_token, Token}, - {coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")}, - {coveralls_commit_sha, os:getenv("GITHUB_SHA")}, - {coveralls_service_number, os:getenv("GITHUB_RUN_NUMBER")}, - {coveralls_coverdata, "_build/test/cover/*.coverdata"}, - {coveralls_service_name, "github"} | CONFIG], - case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request" - andalso string:tokens(os:getenv("GITHUB_REF"), "/") of - [_, "pull", PRNO, _] -> - [{coveralls_service_pull_request, PRNO} | CONFIG1]; - _ -> - CONFIG1 - end; - _ -> - CONFIG -end. diff --git a/_build/emqx/lib/ekka/scripts/cluster.etcd.sh b/_build/emqx/lib/ekka/scripts/cluster.etcd.sh deleted file mode 100644 index 24e0a1cc23..0000000000 --- a/_build/emqx/lib/ekka/scripts/cluster.etcd.sh +++ /dev/null @@ -1,5 +0,0 @@ - -erl -pa ebin/ -pa deps/*/ebin -name ekka1@127.0.0.1 -setcookie cookie -config data/app.etcd -s ekka -s ekka autocluster - -erl -pa ebin/ -pa deps/*/ebin -name ekka2@127.0.0.1 -setcookie cookie -config data/app.etcd -s ekka -s ekka autocluster - diff --git a/_build/emqx/lib/ekka/scripts/cluster.mcast.sh b/_build/emqx/lib/ekka/scripts/cluster.mcast.sh deleted file mode 100644 index 344cb0b6ab..0000000000 --- a/_build/emqx/lib/ekka/scripts/cluster.mcast.sh +++ /dev/null @@ -1,4 +0,0 @@ - -erl -pa ebin/ -pa deps/*/ebin -name ekka1@127.0.0.1 -setcookie cookie -config data/app.mcast -s ekka -s ekka autocluster - -erl -pa ebin/ -pa deps/*/ebin -name ekka2@127.0.0.1 -setcookie cookie -config data/app.mcast -s ekka -s ekka autocluster diff --git a/_build/emqx/lib/ekka/src/ekka.app.src b/_build/emqx/lib/ekka/src/ekka.app.src deleted file mode 100644 index 6d91f7d6ab..0000000000 --- a/_build/emqx/lib/ekka/src/ekka.app.src +++ /dev/null @@ -1,21 +0,0 @@ -{application, ekka, - [{description, "Autocluster and Autoheal for EMQ X Broker"}, - {vsn, "git"}, - {mod, {ekka_app,[]}}, - {registered, - [ekka_sup, - ekka_membership, - ekka_cluster_sup, - ekka_node_monitor - ]}, - {applications, - [kernel, - stdlib, - mnesia, - inets - ]}, - {modules, []}, - {licenses, ["Apache 2.0"]}, - {maintainers, ["EMQ X Team "]}, - {links, [{"Github","https://hub.fastgit.org/emqx/ekka"}]} - ]}. diff --git a/_build/emqx/lib/ekka/src/ekka.erl b/_build/emqx/lib/ekka/src/ekka.erl deleted file mode 100644 index eb40579807..0000000000 --- a/_build/emqx/lib/ekka/src/ekka.erl +++ /dev/null @@ -1,257 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka). - --include("ekka.hrl"). - -%% Start/Stop --export([start/0, stop/0]). - -%% Env --export([env/1, env/2]). - -%% Info --export([info/0, info/1]). - -%% Cluster API --export([cluster_name/0]). --export([ join/1 - , leave/0 - , force_leave/1 - ]). - -%% Autocluster API --export([ autocluster/0 - , autocluster/1 - ]). - -%% Register callback --export([ callback/1 - , callback/2 - ]). - -%% Node API --export([ is_aliving/1 - , is_running/2 - ]). - -%% Membership API --export([ members/0 - , is_member/1 - , local_member/0 - , nodelist/0 - , nodelist/1 - ]). - -%% Membership Monitor API --export([ monitor/1 - , monitor/2 - , unmonitor/1 - , unmonitor/2 - ]). - -%% Locker API --export([ lock/1 - , lock/2 - , lock/3 - , unlock/1 - , unlock/2 - ]). - --define(IS_MON_TYPE(T), T == membership orelse T == partition). - --type(info_key() :: members | running_nodes | stopped_nodes | partitions). - --type(infos() :: #{members := list(member()), - running_nodes := list(node()), - stopped_nodes := list(node()), - partitions := list(node()) - }). - --export_type([info_key/0, infos/0]). - -%%-------------------------------------------------------------------- -%% Start/Stop -%%-------------------------------------------------------------------- - --spec(start() -> ok). -start() -> - case ekka_mnesia:start() of - ok -> ok; - {error, {timeout, Tables}} -> - logger:error("Mnesia wait_for_tables timeout: ~p", [Tables]), - ok; - {error, Reason} -> - error(Reason) - end, - {ok, _Apps} = application:ensure_all_started(ekka), - ok. - --spec(stop() -> ok). -stop() -> - application:stop(ekka). - -%%-------------------------------------------------------------------- -%% Env -%%-------------------------------------------------------------------- - --spec(env(atom()) -> undefined | {ok, term()}). -env(Key) -> - application:get_env(ekka, Key). - --spec(env(atom(), term()) -> term()). -env(Key, Default) -> - application:get_env(ekka, Key, Default). - -%%-------------------------------------------------------------------- -%% Info -%%-------------------------------------------------------------------- - --spec(info(info_key()) -> term()). -info(Key) -> - maps:get(Key, info()). - --spec(info() -> infos()). -info() -> - ClusterInfo = ekka_cluster:info(), - Partitions = ekka_node_monitor:partitions(), - maps:merge(ClusterInfo, #{members => members(), - partitions => Partitions - }). - -%%-------------------------------------------------------------------- -%% Cluster API -%%-------------------------------------------------------------------- - --spec(cluster_name() -> cluster()). -cluster_name() -> env(cluster_name, undefined). - -%% @doc Join the cluster --spec(join(node()) -> ok | ignore | {error, term()}). -join(Node) -> ekka_cluster:join(Node). - -%% @doc Leave from Cluster. --spec(leave() -> ok | {error, term()}). -leave() -> ekka_cluster:leave(). - -%% @doc Force a node leave from cluster. --spec(force_leave(node()) -> ok | ignore | {error, term()}). -force_leave(Node) -> ekka_cluster:force_leave(Node). - -%%-------------------------------------------------------------------- -%% Autocluster -%%-------------------------------------------------------------------- - -autocluster() -> autocluster(ekka). - -autocluster(App) -> - case env(cluster_enable, true) andalso ekka_autocluster:enabled() of - true -> ekka_autocluster:run(App); - false -> ok - end. - -%%-------------------------------------------------------------------- -%% Register callback -%%-------------------------------------------------------------------- - --spec(callback(atom()) -> undefined | function()). -callback(Name) -> - env({callback, Name}). - --spec(callback(atom(), function()) -> ok). -callback(Name, Fun) -> - application:set_env(ekka, {callback, Name}, Fun). - -%%-------------------------------------------------------------------- -%% Node API -%%-------------------------------------------------------------------- - -%% @doc Is node aliving? --spec(is_aliving(node()) -> boolean()). -is_aliving(Node) -> - ekka_node:is_aliving(Node). - -%% @doc Is the application running? --spec(is_running(node(), atom()) -> boolean()). -is_running(Node, App) -> - ekka_node:is_running(Node, App). - -%%-------------------------------------------------------------------- -%% Membership API -%%-------------------------------------------------------------------- - -%% Cluster members --spec(members() -> list(member())). -members() -> ekka_membership:members(). - -%% Local member --spec(local_member() -> member()). -local_member() -> ekka_membership:local_member(). - -%% Is node a member? --spec(is_member(node()) -> boolean()). -is_member(Node) -> ekka_membership:is_member(Node). - -%% Node list --spec(nodelist() -> list(node())). -nodelist() -> ekka_membership:nodelist(). - --spec(nodelist(up|down) -> list(node())). -nodelist(Status) -> ekka_membership:nodelist(Status). - -%%-------------------------------------------------------------------- -%% Membership Monitor API -%%-------------------------------------------------------------------- - -monitor(Type) when ?IS_MON_TYPE(Type) -> - ekka_membership:monitor(Type, self(), true). - -monitor(Type, Fun) when is_function(Fun), ?IS_MON_TYPE(Type) -> - ekka_membership:monitor(Type, Fun, true). - -unmonitor(Type) when ?IS_MON_TYPE(Type) -> - ekka_membership:monitor(Type, self(), false). - -unmonitor(Type, Fun) when is_function(Fun), ?IS_MON_TYPE(Type) -> - ekka_membership:monitor(Type, Fun, false). - -%%-------------------------------------------------------------------- -%% Locker API -%%-------------------------------------------------------------------- - --spec(lock(ekka_locker:resource()) -> ekka_locker:lock_result()). -lock(Resource) -> - ekka_locker:acquire(Resource). - --spec(lock(ekka_locker:resource(), ekka_locker:lock_type()) - -> ekka_locker:lock_result()). -lock(Resource, Type) -> - ekka_locker:acquire(ekka_locker, Resource, Type). - --spec(lock(ekka_locker:resource(), ekka_locker:lock_type(), ekka_locker:piggyback()) - -> ekka_locker:lock_result()). -lock(Resource, Type, Piggyback) -> - ekka_locker:acquire(ekka_locker, Resource, Type, Piggyback). - --spec(unlock(ekka_locker:resource()) -> ekka_locker:lock_result()). -unlock(Resource) -> - ekka_locker:release(Resource). - --spec(unlock(ekka_locker:resource(), ekka_locker:lock_type()) -> ekka_locker:lock_result()). -unlock(Resource, Type) -> - ekka_locker:release(ekka_locker, Resource, Type). - diff --git a/_build/emqx/lib/ekka/src/ekka_app.erl b/_build/emqx/lib/ekka/src/ekka_app.erl deleted file mode 100644 index 9ecda4ead6..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_app.erl +++ /dev/null @@ -1,28 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_app). - --behaviour(application). - --export([start/2, stop/1]). - -start(_Type, _Args) -> - ekka_sup:start_link(). - -stop(_State) -> - ok. - diff --git a/_build/emqx/lib/ekka/src/ekka_autoclean.erl b/_build/emqx/lib/ekka/src/ekka_autoclean.erl deleted file mode 100644 index 2c9c33533c..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_autoclean.erl +++ /dev/null @@ -1,51 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_autoclean). - --include("ekka.hrl"). - --export([init/0, check/1]). - --record(autoclean, {expiry, timer}). - --opaque(autoclean() :: #autoclean{}). - --export_type([autoclean/0]). - -init() -> - case ekka:env(cluster_autoclean) of - {ok, Expiry} -> timer_backoff(#autoclean{expiry = Expiry}); - undefined -> undefined - end. - -timer_backoff(State = #autoclean{expiry = Expiry}) -> - TRef = ekka_node_monitor:run_after(Expiry div 4, autoclean), - State#autoclean{timer = TRef}. - -check(State = #autoclean{expiry = Expiry}) -> - [maybe_clean(Member, Expiry) || Member <- ekka_membership:members(down)], - timer_backoff(State). - -maybe_clean(#member{node = Node, ltime = LTime}, Expiry) -> - case expired(LTime, Expiry) of - true -> ekka_cluster:force_leave(Node); - false -> ok - end. - -expired(LTime, Expiry) -> - timer:now_diff(erlang:timestamp(), LTime) div 1000 > Expiry. - diff --git a/_build/emqx/lib/ekka/src/ekka_autocluster.erl b/_build/emqx/lib/ekka/src/ekka_autocluster.erl deleted file mode 100644 index 49da9567fe..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_autocluster.erl +++ /dev/null @@ -1,166 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_autocluster). - --include("ekka.hrl"). - --export([enabled/0 , run/1, unregister_node/0]). - --export([acquire_lock/1, release_lock/1]). - --define(LOG(Level, Format, Args), - logger:Level("Ekka(AutoCluster): " ++ Format, Args)). - --spec(enabled() -> boolean()). -enabled() -> - case ekka:env(cluster_discovery) of - {ok, {manual, _}} -> false; - {ok, _Strategy} -> true; - undefined -> false - end. - --spec(run(atom()) -> any()). -run(App) -> - case acquire_lock(App) of - ok -> - spawn(fun() -> - group_leader(whereis(init), self()), - wait_application_ready(App, 10), - try - discover_and_join() - catch - _:Error:Stacktrace -> - ?LOG(error, "Discover error: ~p~n~p", [Error, Stacktrace]) - after - release_lock(App) - end, - maybe_run_again(App) - end); - failed -> ignore - end. - -wait_application_ready(_App, 0) -> - timeout; -wait_application_ready(App, Retries) -> - case ekka_node:is_running(App) of - true -> ok; - false -> timer:sleep(1000), - wait_application_ready(App, Retries - 1) - end. - -maybe_run_again(App) -> - %% Check if the node joined cluster? - case ekka_mnesia:is_node_in_cluster() of - true -> ok; - false -> timer:sleep(5000), - run(App) - end. - --spec(discover_and_join() -> any()). -discover_and_join() -> - with_strategy( - fun(Mod, Options) -> - case Mod:lock(Options) of - ok -> - discover_and_join(Mod, Options), - log_error("Unlock", Mod:unlock(Options)); - ignore -> - timer:sleep(rand:uniform(3000)), - discover_and_join(Mod, Options); - {error, Reason} -> - ?LOG(error, "AutoCluster stopped for lock error: ~p", [Reason]) - end - end). - --spec(unregister_node() -> ok). -unregister_node() -> - with_strategy( - fun(Mod, Options) -> - log_error("Unregister", Mod:unregister(Options)) - end). - --spec(acquire_lock(atom()) -> ok | failed). -acquire_lock(App) -> - case application:get_env(App, autocluster_lock) of - undefined -> - application:set_env(App, autocluster_lock, true); - {ok, _} -> failed - end. - --spec(release_lock(atom()) -> ok). -release_lock(App) -> - application:unset_env(App, autocluster_lock). - -with_strategy(Fun) -> - case ekka:env(cluster_discovery) of - {ok, {manual, _}} -> - ignore; - {ok, {Strategy, Options}} -> - Fun(strategy_module(Strategy), Options); - undefined -> - ignore - end. - -strategy_module(Strategy) -> - case code:is_loaded(Strategy) of - {file, _} -> Strategy; %% Provider? - false -> list_to_atom("ekka_cluster_" ++ atom_to_list(Strategy)) - end. - -discover_and_join(Mod, Options) -> - case Mod:discover(Options) of - {ok, Nodes} -> - maybe_join([N || N <- Nodes, ekka_node:is_aliving(N)]), - log_error("Register", Mod:register(Options)); - {error, Reason} -> - ?LOG(error, "Discovery error: ~p", [Reason]) - end. - -maybe_join([]) -> - ignore; -maybe_join(Nodes) -> - case ekka_mnesia:is_node_in_cluster() of - true -> ignore; - false -> join_with(find_oldest_node(Nodes)) - end. - -join_with(false) -> - ignore; -join_with(Node) when Node =:= node() -> - ignore; -join_with(Node) -> - ekka_cluster:join(Node). - -find_oldest_node([Node]) -> - Node; -find_oldest_node(Nodes) -> - case rpc:multicall(Nodes, ekka_membership, local_member, []) of - {ResL, []} -> - case [M || M <- ResL, is_record(M, member)] of - [] -> ?LOG(error, "Bad members found on nodes ~p: ~p", [Nodes, ResL]), - false; - Members -> - (ekka_membership:oldest(Members))#member.node - end; - {ResL, BadNodes} -> - ?LOG(error, "Bad nodes found: ~p, ResL: ", [BadNodes, ResL]), false - end. - -log_error(Format, {error, Reason}) -> - ?LOG(error, Format ++ " error: ~p", [Reason]); -log_error(_Format, _Ok) -> ok. - diff --git a/_build/emqx/lib/ekka/src/ekka_autoheal.erl b/_build/emqx/lib/ekka/src/ekka_autoheal.erl deleted file mode 100644 index dfa70e379f..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_autoheal.erl +++ /dev/null @@ -1,158 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_autoheal). - --export([ init/0 - , enabled/0 - , proc/1 - , handle_msg/2 - ]). - --record(autoheal, {delay, role, proc, timer}). - --opaque(autoheal() :: #autoheal{}). - --export_type([autoheal/0]). - --define(DEFAULT_DELAY, 15000). --define(LOG(Level, Format, Args), - logger:Level("Ekka(Autoheal): " ++ Format, Args)). - -init() -> - case enabled() of - {true, Delay} -> #autoheal{delay = Delay}; - false -> undefined - end. - -enabled() -> - case ekka:env(cluster_autoheal, true) of - false -> false; - true -> {true, ?DEFAULT_DELAY}; - Delay when is_integer(Delay) -> - {true, Delay} - end. - -proc(undefined) -> undefined; -proc(#autoheal{proc = Proc}) -> - Proc. - -handle_msg(Msg, undefined) -> - ?LOG(error, "Autoheal not enabled! Unexpected msg: ~p", [Msg]), undefined; - -handle_msg({report_partition, _Node}, Autoheal = #autoheal{proc = Proc}) - when Proc =/= undefined -> - Autoheal; - -handle_msg({report_partition, Node}, Autoheal = #autoheal{delay = Delay, timer = TRef}) -> - case ekka_membership:leader() =:= node() of - true -> - ensure_cancel_timer(TRef), - TRef1 = ekka_node_monitor:run_after(Delay, {autoheal, {create_splitview, node()}}), - Autoheal#autoheal{role = leader, timer = TRef1}; - false -> - ?LOG(critical, "I am not leader, but received partition report from ~s", [Node]), - Autoheal - end; - -handle_msg(Msg = {create_splitview, Node}, Autoheal = #autoheal{delay = Delay, timer = TRef}) - when Node =:= node() -> - ensure_cancel_timer(TRef), - case ekka_membership:is_all_alive() of - true -> - Nodes = ekka_mnesia:cluster_nodes(all), - case rpc:multicall(Nodes, ekka_mnesia, cluster_view, []) of - {Views, []} -> - SplitView = lists:sort(fun compare_view/2, lists:usort(Views)), - ekka_node_monitor:cast(coordinator(SplitView), {heal_partition, SplitView}); - {_Views, BadNodes} -> - ?LOG(critical, "Bad nodes found when autoheal: ~p", [BadNodes]) - end, - Autoheal#autoheal{timer = undefined}; - false -> - Autoheal#autoheal{timer = ekka_node_monitor:run_after(Delay, {autoheal, Msg})} - end; - -handle_msg(Msg = {create_splitview, _Node}, Autoheal) -> - ?LOG(critical, "I am not leader, but received : ~p", [Msg]), - Autoheal; - -handle_msg({heal_partition, SplitView}, Autoheal = #autoheal{proc = undefined}) -> - Proc = spawn_link(fun() -> - ?LOG(info, "Healing partition: ~p", [SplitView]), - _ = heal_partition(SplitView) - end), - Autoheal#autoheal{role = coordinator, proc = Proc}; - -handle_msg({heal_partition, SplitView}, Autoheal= #autoheal{proc = _Proc}) -> - ?LOG(critical, "Unexpected heal_partition msg: ~p", [SplitView]), - Autoheal; - -handle_msg({'EXIT', Pid, normal}, Autoheal = #autoheal{proc = Pid}) -> - Autoheal#autoheal{proc = undefined}; -handle_msg({'EXIT', Pid, Reason}, Autoheal = #autoheal{proc = Pid}) -> - ?LOG(critical, "Autoheal process crashed: ~s", [Reason]), - Autoheal#autoheal{proc = undefined}; - -handle_msg(Msg, Autoheal) -> - ?LOG(critical, "Unexpected msg: ~p", [Msg, Autoheal]), - Autoheal. - -compare_view({Running1, _} , {Running2, _}) -> - Len1 = length(Running1), Len2 = length(Running2), - if - Len1 > Len2 -> true; - Len1 == Len2 -> lists:member(node(), Running1); - true -> false - end. - -coordinator([{Nodes, _} | _]) -> - ekka_membership:coordinator(Nodes). - --spec heal_partition(list()) -> list(node()). -heal_partition([]) -> - []; -%% All nodes connected. -heal_partition([{_, []}]) -> - []; -%% Partial partitions happened. -heal_partition([{Nodes, []}|_]) -> - reboot_minority(Nodes -- [node()]); -heal_partition([{Majority, Minority}, {Minority, Majority}]) -> - reboot_minority(Minority); -heal_partition(SplitView) -> - ?LOG(critical, "Cannot heal the partitions: ~p", [SplitView]), - error({unknown_splitview, SplitView}). - -reboot_minority(Minority) -> - lists:foreach(fun shutdown/1, Minority), - timer:sleep(rand:uniform(1000) + 100), - lists:foreach(fun reboot/1, Minority), - Minority. - -shutdown(Node) -> - Ret = rpc:call(Node, ekka_cluster, heal, [shutdown]), - ?LOG(critical, "Shutdown ~s for autoheal: ~p", [Node, Ret]). - -reboot(Node) -> - Ret = rpc:call(Node, ekka_cluster, heal, [reboot]), - ?LOG(critical, "Reboot ~s for autoheal: ~p", [Node, Ret]). - -ensure_cancel_timer(undefined) -> - ok; -ensure_cancel_timer(TRef) -> - catch erlang:cancel_timer(TRef). - diff --git a/_build/emqx/lib/ekka/src/ekka_boot.erl b/_build/emqx/lib/ekka/src/ekka_boot.erl deleted file mode 100644 index 0daad07e8b..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_boot.erl +++ /dev/null @@ -1,62 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_boot). - --export([apply_module_attributes/1, all_module_attributes/1]). - -%% only {F, Args}... -apply_module_attributes(Name) -> - [{Module, [apply(Module, F, Args) || {F, Args} <- Attrs]} || - {_App, Module, Attrs} <- all_module_attributes(Name)]. - -%% Copy from rabbit_misc.erl -all_module_attributes(Name) -> - Targets = - lists:usort( - lists:append( - [[{App, Module} || Module <- Modules] || - {App, _, _} <- ignore_lib_apps(application:loaded_applications()), - {ok, Modules} <- [application:get_key(App, modules)]])), - lists:foldl( - fun ({App, Module}, Acc) -> - case lists:append([Atts || {N, Atts} <- module_attributes(Module), - N =:= Name]) of - [] -> Acc; - Atts -> [{App, Module, Atts} | Acc] - end - end, [], Targets). - -module_attributes(Module) -> - case catch Module:module_info(attributes) of - {'EXIT', {undef, [{Module, module_info, [attributes], []} | _]}} -> - []; - {'EXIT', Reason} -> - exit(Reason); - V -> - V - end. - -ignore_lib_apps(Apps) -> - LibApps = [kernel, stdlib, sasl, appmon, eldap, erts, - syntax_tools, ssl, crypto, mnesia, os_mon, - inets, goldrush, gproc, runtime_tools, - snmp, otp_mibs, public_key, asn1, ssh, hipe, - common_test, observer, webtool, xmerl, tools, - test_server, compiler, debugger, eunit, et, - wx], - [App || App = {Name, _, _} <- Apps, not lists:member(Name, LibApps)]. - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster.erl b/_build/emqx/lib/ekka/src/ekka_cluster.erl deleted file mode 100644 index cbd76e782e..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster.erl +++ /dev/null @@ -1,120 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc Cluster via Mnesia database. --module(ekka_cluster). - --export([info/0, info/1]). - -%% Cluster API --export([ join/1 - , leave/0 - , force_leave/1 - , status/1 - ]). - -%% RPC call for Cluster Management --export([ prepare/1 - , heal/1 - , reboot/0 - ]). - --type(info_key() :: running_nodes | stopped_nodes). - --type(infos() :: #{running_nodes := list(node()), - stopped_nodes := list(node()) - }). - --export_type([info_key/0, infos/0]). - --spec(info(atom()) -> list(node())). -info(Key) -> maps:get(Key, info()). - --spec(info() -> infos()). -info() -> ekka_mnesia:cluster_info(). - -%% @doc Cluster status of the node. -status(Node) -> ekka_mnesia:cluster_status(Node). - -%% @doc Join the cluster --spec(join(node()) -> ok | ignore | {error, term()}). -join(Node) when Node =:= node() -> - ignore; -join(Node) when is_atom(Node) -> - case {ekka_mnesia:is_node_in_cluster(Node), ekka_node:is_running(Node, ekka)} of - {false, true} -> - prepare(join), ok = ekka_mnesia:join_cluster(Node), reboot(); - {false, false} -> - {error, {node_down, Node}}; - {true, _} -> - {error, {already_in_cluster, Node}} - end. - -%% @doc Leave from the cluster. --spec(leave() -> ok | {error, any()}). -leave() -> - case ekka_mnesia:running_nodes() -- [node()] of - [_|_] -> - prepare(leave), ok = ekka_mnesia:leave_cluster(), reboot(); - [] -> - {error, node_not_in_cluster} - end. - -%% @doc Force a node leave from cluster. --spec(force_leave(node()) -> ok | ignore | {error, term()}). -force_leave(Node) when Node =:= node() -> - ignore; -force_leave(Node) -> - case ekka_mnesia:is_node_in_cluster(Node) - andalso rpc:call(Node, ?MODULE, prepare, [leave]) of - ok -> - case ekka_mnesia:remove_from_cluster(Node) of - ok -> rpc:call(Node, ?MODULE, reboot, []); - Error -> Error - end; - false -> - {error, node_not_in_cluster}; - {badrpc, nodedown} -> - ekka_membership:announce({force_leave, Node}), - ekka_mnesia:remove_from_cluster(Node); - {badrpc, Reason} -> - {error, Reason} - end. - -%% @doc Heal partitions --spec(heal(shutdown | reboot) -> ok | {error, term()}). -heal(shutdown) -> - prepare(heal), ekka_mnesia:ensure_stopped(); -heal(reboot) -> - ekka_mnesia:ensure_started(), reboot(). - -%% @doc Prepare to join or leave the cluster. --spec(prepare(join | leave) -> ok | {error, term()}). -prepare(Action) -> - ekka_membership:announce(Action), - case ekka:callback(prepare) of - {ok, Prepare} -> Prepare(Action); - undefined -> application:stop(ekka) - end. - -%% @doc Reboot after join or leave cluster. --spec(reboot() -> ok | {error, term()}). -reboot() -> - case ekka:callback(reboot) of - {ok, Reboot} -> Reboot(); - undefined -> ekka:start() - end. - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_dns.erl b/_build/emqx/lib/ekka/src/ekka_cluster_dns.erl deleted file mode 100644 index d1d327b6ba..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_dns.erl +++ /dev/null @@ -1,50 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_dns). - --behaviour(ekka_cluster_strategy). - --import(proplists, [get_value/2]). - -%% Cluster strategy callbacks --export([ discover/1 - , lock/1 - , unlock/1 - , register/1 - , unregister/1 - ]). - -discover(Options) -> - Name = get_value(name, Options), - App = get_value(app, Options), - {ok, [node_name(App, IP) || IP <- inet_res:lookup(Name, in, a)]}. - -node_name(App, IP) -> - list_to_atom(App ++ "@" ++ inet:ntoa(IP)). - -lock(_Options) -> - ignore. - -unlock(_Options) -> - ignore. - -register(_Options) -> - ignore. - -unregister(_Options) -> - ignore. - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_etcd.erl b/_build/emqx/lib/ekka/src/ekka_cluster_etcd.erl deleted file mode 100644 index 373b28eaab..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_etcd.erl +++ /dev/null @@ -1,169 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_etcd). - --behaviour(ekka_cluster_strategy). - --export([ discover/1 - , lock/1 - , unlock/1 - , register/1 - , unregister/1 - ]). - -%% TTL callback --export([etcd_set_node_key/1]). - --define(LOG(Level, Format, Args), logger:Level("Ekka(etcd): " ++ Format, Args)). - -%%-------------------------------------------------------------------- -%% ekka_cluster_strategy callbacks -%%-------------------------------------------------------------------- - -discover(Options) -> - case etcd_get_nodes_key(Options) of - {ok, Response} -> - {ok, extract_nodes(Response)}; - {error, {404, _}} -> - case ensure_nodes_path(Options) of - {ok, _} -> discover(Options); - Error -> Error - end; - {error, Reason} -> - {error, Reason} - end. - -lock(Options) -> - lock(Options, 10). - -lock(_Options, 0) -> - {error, failed}; - -lock(Options, Retries) -> - case etcd_set_lock_key(Options) of - {ok, _Response} -> ok; - {error, {412, _}} -> - timer:sleep(1000), - lock(Options, Retries -1); - {error, Reason} -> - {error, Reason} - end. - -unlock(Options) -> - case etcd_del_lock_key(Options) of - {ok, _Response} -> ok; - {error, Reason} -> - {error, Reason} - end. - -register(Options) -> - case etcd_set_node_key(Options) of - {ok, _Response} -> - ensure_node_ttl(Options); - {error, Reason} -> - {error, Reason} - end. - -unregister(Options) -> - ok = ekka_cluster_sup:stop_child(ekka_node_ttl), - case etcd_del_node_key(Options) of - {ok, _Response} -> ok; - {error, Reason} -> - {error, Reason} - end. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -extract_nodes([]) -> - []; -extract_nodes(Response) -> - [extract_node(V) || V <- maps:get(<<"nodes">>, maps:get(<<"node">>, Response), [])]. - -ensure_node_ttl(Options) -> - Ttl = proplists:get_value(node_ttl, Options), - MFA = {?MODULE, etcd_set_node_key, [Options]}, - case ekka_cluster_sup:start_child(ekka_node_ttl, [Ttl, MFA]) of - {ok, _Pid} -> ok; - {error, {already_started, _Pid}} -> ok; - Err = {error, _} -> Err - end. - -extract_node(V) -> - list_to_atom(binary_to_list(lists:last(binary:split(maps:get(<<"key">>, V), <<"/">>, [global])))). - -ensure_nodes_path(Options) -> - etcd_set(server(Options), nodes_path(Options), [{dir, true}], ssl_options(Options)). - -etcd_get_nodes_key(Options) -> - etcd_get(server(Options), nodes_path(Options), [{recursive, true}], ssl_options(Options)). - -etcd_set_node_key(Options) -> - Ttl = config(node_ttl, Options) div 1000, - etcd_set(server(Options), node_path(Options), [{ttl, Ttl}], ssl_options(Options)). - -etcd_del_node_key(Options) -> - etcd_del(server(Options), node_path(Options), [], ssl_options(Options)). - -etcd_set_lock_key(Options) -> - Values = [{ttl, 30}, {'prevExist', false}, {value, node()}], - etcd_set(server(Options), lock_path(Options), Values, ssl_options(Options)). - -etcd_del_lock_key(Options) -> - Values = [{'prevExist', true}, {'prevValue', node()}], - etcd_del(server(Options), lock_path(Options), Values, ssl_options(Options)). - -server(Options) -> - config(server, Options). - -ssl_options(Options) -> - case proplists:get_value(ssl_options, Options, []) of - [] -> []; - SSLOptions -> [{ssl, SSLOptions}] - end. - -config(Key, Options) -> - proplists:get_value(Key, Options). - -etcd_get(Servers, Key, Params, HttpOpts) -> - ekka_httpc:get(rand_addr(Servers), Key, Params, HttpOpts). - -etcd_set(Servers, Key, Params, HttpOpts) -> - ekka_httpc:put(rand_addr(Servers), Key, Params, HttpOpts). - -etcd_del(Servers, Key, Params, HttpOpts) -> - ekka_httpc:delete(rand_addr(Servers), Key, Params, HttpOpts). - -nodes_path(Options) -> - with_prefix(config(prefix, Options), "/nodes"). - -node_path(Options) -> - with_prefix(config(prefix, Options), "/nodes/" ++ atom_to_list(node())). - -lock_path(Options) -> - with_prefix(config(prefix, Options), "/lock"). - -with_prefix(Prefix, Path) -> - Cluster = atom_to_list(ekka:env(cluster_name, ekka)), - lists:concat(["v2/keys/", Prefix, "/", Cluster, Path]). - -rand_addr([Addr]) -> - Addr; -rand_addr(AddrList) -> - lists:nth(rand:uniform(length(AddrList)), AddrList). - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_k8s.erl b/_build/emqx/lib/ekka/src/ekka_cluster_k8s.erl deleted file mode 100644 index 2e5e4b76c3..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_k8s.erl +++ /dev/null @@ -1,122 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_k8s). - --behaviour(ekka_cluster_strategy). - -%% Cluster strategy callbacks. --export([ discover/1 - , lock/1 - , unlock/1 - , register/1 - , unregister/1 - ]). - --import(proplists, [get_value/2, get_value/3]). - --define(SERVICE_ACCOUNT_PATH, "/var/run/secrets/kubernetes.io/serviceaccount/"). - --define(LOG(Level, Format, Args), logger:Level("Ekka(k8s): " ++ Format, Args)). - -%%-------------------------------------------------------------------- -%% ekka_cluster_strategy callbacks -%%-------------------------------------------------------------------- - -discover(Options) -> - Server = get_value(apiserver, Options), - Service = get_value(service_name, Options), - App = get_value(app_name, Options, "ekka"), - AddrType = get_value(address_type, Options, ip), - Namespace = get_value(namespace, Options, "default"), - Suffix = get_value(suffix, Options, ""), - case k8s_service_get(Server, Service, Namespace) of - {ok, Response} -> - Addresses = extract_addresses(AddrType, Response), - {ok, [node_name(App, Addr, Service, AddrType, Namespace, Suffix) || Addr <- Addresses]}; - {error, Reason} -> - {error, Reason} - end. - -node_name(App, Addr, Service, hostname, Namespace, Suffix) when length(Suffix) > 0 -> - list_to_atom(lists:concat([App, "@", binary_to_list(Addr), ".", Service, ".", Namespace, ".", Suffix])); - -node_name(App, Addr, _Service, dns, Namespace, Suffix) when length(Suffix) > 0 -> - list_to_atom(lists:concat([App, "@", binary_to_list(Addr), ".", Namespace, ".", Suffix])); - -node_name(App, Addr, _, _, _, _) -> - list_to_atom(App ++ "@" ++ binary_to_list(Addr)). - -lock(_Options) -> - ignore. - -unlock(_Options) -> - ignore. - -register(_Options) -> - ignore. - -unregister(_Options) -> - ignore. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -k8s_service_get(Server, Service, Namespace) -> - Headers = [{"Authorization", "Bearer " ++ token()}], - HttpOpts = case filelib:is_file(cert_path()) of - true -> [{ssl, [{cacertfile, cert_path()}]}]; - false -> [{ssl, [{verify, verify_none}]}] - end, - ekka_httpc:get(Server, service_path(Service, Namespace), [], Headers, HttpOpts). - -service_path(Service, Namespace) -> - lists:concat(["api/v1/namespaces/", Namespace, "/endpoints/", Service]). - -% namespace() -> -% binary_to_list(trim(read_file("namespace", <<"default">>))). - -token() -> - binary_to_list(trim(read_file("token", <<"">>))). - -cert_path() -> ?SERVICE_ACCOUNT_PATH ++ "/ca.crt". - -read_file(Name, Default) -> - case file:read_file(?SERVICE_ACCOUNT_PATH ++ Name) of - {ok, Data} -> Data; - {error, Error} -> - ?LOG(error, "Cannot read ~s: ~p", [Name, Error]), - Default - end. - -trim(S) -> binary:replace(S, <<"\n">>, <<>>). - -extract_addresses(Type, Response) -> - lists:flatten( - [[extract_host(Type, Addr) - || Addr <- maps:get(<<"addresses">>, Subset, [])] - || Subset <- maps:get(<<"subsets">>, Response, [])]). - -extract_host(ip, Addr) -> - maps:get(<<"ip">>, Addr); - -extract_host(hostname, Addr) -> - maps:get(<<"hostname">>, Addr); - -extract_host(dns, Addr) -> - binary:replace(maps:get(<<"ip">>, Addr), <<".">>, <<"-">>, [global]). - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_mcast.erl b/_build/emqx/lib/ekka/src/ekka_cluster_mcast.erl deleted file mode 100644 index 690e0e524c..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_mcast.erl +++ /dev/null @@ -1,231 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_mcast). - --behaviour(gen_server). - --behaviour(ekka_cluster_strategy). - -%% Cluster strategy callbacks --export([ discover/1 - , lock/1 - , unlock/1 - , register/1 - , unregister/1 - ]). - --export([ ensure_started/1 - , start_link/1 - , stop/0 - ]). - -%% For tests --export([get_sock/0]). - -%% gen_server Callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --import(proplists, [get_value/2, get_value/3]). - --type(option() :: {addr, inet:ip_address()} - | {ports, list(inet:port_number())} - | {iface, inet:ip_address()} - | {ttl, pos_integer()} - | {loop, boolean()} - | {senbuf, pos_integer()} - | {recbuf, pos_integer()} - | {buffer, pos_integer()}). - --record(state, { - sock :: inet:socket(), - addr :: inet:ip_address(), - ports :: list(inet:port_number()), - cookie :: integer(), - seen :: list(node()) - }). - --define(SERVER, ?MODULE). - --define(LOG(Level, Format, Args), - logger:Level("Ekka(Mcast): " ++ Format, Args)). - -%%-------------------------------------------------------------------- -%% ekka_cluster_strategy callbacks -%%-------------------------------------------------------------------- - -discover(Options) -> - Server = case whereis(?SERVER) of - Pid when is_pid(Pid) -> Pid; - undefined -> ensure_started(Options) - end, - gen_server:call(Server, discover, 60000). - -lock(_Options) -> - ignore. - -unlock(_Options) -> - ignore. - -register(_Options) -> - ignore. - -unregister(_Options) -> - ignore. - -%%-------------------------------------------------------------------- -%% Start/stop mcast server -%%-------------------------------------------------------------------- - -ensure_started(Options) -> - case ekka_cluster_sup:start_child(?SERVER, [Options]) of - {ok, Pid} -> Pid; - {error, {already_started, Pid}} -> Pid - end. - --spec(start_link(list(option())) -> {ok, pid()} | {error, term()}). -start_link(Options) -> - gen_server:start_link({local, ?SERVER}, ?MODULE, Options, []). - --spec(stop() -> ok). -stop() -> gen_server:stop(?SERVER). - --spec(get_sock() -> inet:socket()). -get_sock() -> - gen_server:call(?SERVER, get_sock). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init(Options) -> - Addr = get_value(addr, Options), - Ports = get_value(ports, Options), - Loop = get_value(loop, Options, true), - TTL = get_value(ttl, Options, 1), - Iface = get_value(iface, Options, {0,0,0,0}), - case udp_open(Ports, [{multicast_if, Iface}, - {multicast_ttl, TTL}, - {multicast_loop, Loop}, - {add_membership, {Addr, Iface}}]) of - {ok, Sock} -> - Cookie = erlang:phash2(erlang:get_cookie()), - {ok, #state{sock = Sock, addr = Addr, ports = Ports, - cookie = Cookie, seen = []}}; - {error, Error} -> {stop, Error} - end. - -handle_call(discover, From, State = #state{sock = Sock, addr = Addr, - ports = Ports, cookie = Cookie}) -> - lists:foreach(fun(Port) -> - udp_send(Sock, Addr, Port, ping(Cookie)) - end, Ports), - erlang:send_after(3000, self(), {reply, discover, From}), - {noreply, State}; - -handle_call(get_sock, _From, State = #state{sock = Sock}) -> - {reply, Sock, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignore, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({reply, discover, From}, State = #state{seen = Seen}) -> - gen_server:reply(From, {ok, [node() | Seen]}), - {noreply, State#state{seen = []}, hibernate}; - -handle_info({udp, Sock, _Ip, InPort, Data}, - State = #state{sock = Sock, addr = Addr, - cookie = Cookie, seen = Seen}) -> - %%io:format("~s recv handshake from ~p: ~p~n", - %% [node(), {Ip, InPort}, binary_to_term(Data)]), - Cluster = ekka:env(cluster_name, ekka), - {noreply, try binary_to_term(Data) of - {ping, Node, _Cluster, _Cookie} when Node =:= node() -> - State; - {ping, Node, Cluster, Cookie} -> - udp_send(Sock, Addr, InPort, pong(Cookie)), - State#state{seen = lists:usort([Node | Seen])}; - {pong, Node, _Cluster, _Cookie} when Node =:= node() -> - State; - {pong, Node, Cluster, Cookie} -> - State#state{seen = lists:usort([Node | Seen])}; - Handshake = {_Type, _Node, _Cluster, _Cookie} -> - ?LOG(error, "Bad handshake: ~p", [Handshake]), - State; - Term -> ?LOG(error, "Bad term: ~p", [Term]), - State - catch - error:badarg -> - ?LOG(error, "Corrupt data: ~p", [Data]), - State - end, hibernate}; - -handle_info({udp_passive, Sock}, State = #state{sock = Sock}) -> - inet:setopts(Sock, [{active, 10}]), - {noreply, State}; - -handle_info({udp_closed, Sock}, State = #state{sock = Sock}) -> - {stop, udp_closed, State}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #state{sock = Sock}) -> - gen_udp:close(Sock). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -ping(Cookie) -> handshake(ping, Cookie). - -pong(Cookie) -> handshake(pong, Cookie). - -handshake(Type, Cookie) -> - {Type, node(), ekka:env(cluster_name, undefined), Cookie}. - -udp_open([], _Options) -> - {error, eaddrinuse}; - -udp_open([Port|Ports], Options) -> - case gen_udp:open(Port, [binary, {active, 10}, {reuseaddr, true} | Options]) of - {ok, Sock} -> - {ok, Sock}; - {error, eaddrinuse} -> - ?LOG(warning, "Multicast Adddress inuse: ~p", [Port]), - udp_open(Ports, Options); - {error, Reason} -> - {error, Reason} - end. - -udp_send(Sock, Addr, Port, Term) -> - gen_udp:send(Sock, Addr, Port, term_to_binary(Term)). - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_static.erl b/_build/emqx/lib/ekka/src/ekka_cluster_static.erl deleted file mode 100644 index 0de3d59225..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_static.erl +++ /dev/null @@ -1,42 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_static). - --behaviour(ekka_cluster_strategy). - --export([ discover/1 - , lock/1 - , unlock/1 - , register/1 - , unregister/1 - ]). - -discover(Options) -> - {ok, proplists:get_value(seeds, Options, [])}. - -lock(_Options) -> - ignore. - -unlock(_Options) -> - ignore. - -register(_Options) -> - ignore. - -unregister(_Options) -> - ignore. - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_strategy.erl b/_build/emqx/lib/ekka/src/ekka_cluster_strategy.erl deleted file mode 100644 index 7386812e91..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_strategy.erl +++ /dev/null @@ -1,43 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_strategy). - --ifdef(use_specs). - --type(options() :: proplists:proplist()). - --callback(discover(options()) -> {ok, list(node())} | {error, term()}). - --callback(lock(options()) -> ok | ignore | {error, term()}). - --callback(unlock(options()) -> ok | ignore | {error, term()}). - --callback(register(options()) -> ok | ignore | {error, term()}). - --callback(unregister(options()) -> ok | ignore | {error, term()}). - --else. - --export([behaviour_info/1]). - -behaviour_info(callbacks) -> - [{discover, 1}, {lock, 1}, {unlock, 1}, {register, 1}, {unregister, 1}]; -behaviour_info(_Other) -> - undefined. - --endif. - diff --git a/_build/emqx/lib/ekka/src/ekka_cluster_sup.erl b/_build/emqx/lib/ekka/src/ekka_cluster_sup.erl deleted file mode 100644 index d07be822ee..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_cluster_sup.erl +++ /dev/null @@ -1,68 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_cluster_sup). - --behaviour(supervisor). - --export([start_link/0]). - -%% API --export([start_child/2, stop_child/1]). - -%% Supervisor callbacks --export([init/1]). - -%%-------------------------------------------------------------------- -%% API functions -%%-------------------------------------------------------------------- - --spec(start_link() -> {ok, pid()} | ignore | {error, term()}). -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -start_child(M, Args) -> - supervisor:start_child(?MODULE, child_spec(M, Args)). - -child_spec(M, Args) -> - {M, {M, start_link, Args}, permanent, 5000, worker, [M]}. - -stop_child(M) -> - case supervisor:terminate_child(?MODULE, M) of - ok -> supervisor:delete_child(?MODULE, M); - {error, not_found} -> ok; - Error -> Error - end. - -%%-------------------------------------------------------------------- -%% Supervisor callbacks -%%-------------------------------------------------------------------- - -init([]) -> - Childs = case ekka:env(cluster_discovery) of - {ok, {mcast, Options}} -> - Mcast = #{id => ekka_cluster_mcast, - start => {ekka_cluster_mcast, start_link, [Options]}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [ekka_cluster_mcast] - }, - [Mcast]; - _Other -> [] - end, - {ok, {{one_for_one, 10, 100}, Childs}}. - diff --git a/_build/emqx/lib/ekka/src/ekka_dist.erl b/_build/emqx/lib/ekka/src/ekka_dist.erl deleted file mode 100644 index a668c5804c..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_dist.erl +++ /dev/null @@ -1,95 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_dist). - --export([listen/1, - select/1, - accept/1, - accept_connection/5, - setup/5, - close/1, - childspecs/0]). - --export([port/1]). - --define(DEFAULT_PORT, 4370). --define(MAX_PORT_LIMIT, 60000). - -listen(Name) -> - %% Here we figure out what port we want to listen on. - Port = port(Name), - - %% Set both "min" and "max" variables, to force the port number to - %% this one. - ok = application:set_env(kernel, inet_dist_listen_min, Port), - ok = application:set_env(kernel, inet_dist_listen_max, Port), - - %% Finally run the real function! - with_module(fun(M) -> M:listen(Name) end). - -select(Node) -> - with_module(fun(M) -> M:select(Node) end). - -accept(Listen) -> - with_module(fun(M) -> M:accept(Listen) end). - -accept_connection(AcceptPid, Socket, MyNode, Allowed, SetupTime) -> - with_module(fun(M) -> - M:accept_connection(AcceptPid, Socket, MyNode, Allowed, SetupTime) - end). - -setup(Node, Type, MyNode, LongOrShortNames, SetupTime) -> - with_module(fun(M) -> - M:setup(Node, Type, MyNode, LongOrShortNames, SetupTime) - end). - -close(Listen) -> - with_module(fun(M) -> M:close(Listen) end). - -childspecs() -> - with_module(fun(M) -> M:childspecs() end). - -with_module(Fun) -> - Proto = application:get_env(ekka, proto_dist, inet_tcp), - Fun(list_to_existing_atom(atom_to_list(Proto) ++ "_dist")). - -%% @doc Figure out dist port from node's name. --spec(port(node() | string()) -> inet:port_number()). -port(Name) when is_atom(Name) -> - port(atom_to_list(Name)); -port(Name) when is_list(Name) -> - %% Figure out the base port. If not specified using the - %% inet_dist_base_port kernel environment variable, default to - %% 4370, one above the epmd port. - BasePort = application:get_env(kernel, inet_dist_base_port, ?DEFAULT_PORT), - - %% Now, figure out our "offset" on top of the base port. The - %% offset is the integer just to the left of the @ sign in our node - %% name. If there is no such number, the offset is 0. - %% - %% Also handle the case when no hostname was specified. - BasePort + offset(Name). - -%% @doc Figure out the offset by node's name -offset(NodeName) -> - ShortName = re:replace(NodeName, "@.*$", ""), - case re:run(ShortName, "[0-9]+$", [{capture, first, list}]) of - nomatch -> - 0; - {match, [OffsetAsString]} -> - (list_to_integer(OffsetAsString) rem ?MAX_PORT_LIMIT) - end. diff --git a/_build/emqx/lib/ekka/src/ekka_epmd.erl b/_build/emqx/lib/ekka/src/ekka_epmd.erl deleted file mode 100644 index 7b8807f539..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_epmd.erl +++ /dev/null @@ -1,67 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc https://www.erlang-solutions.com/blog/erlang-and-elixir-distribution-without-epmd.html - --module(ekka_epmd). - --include("ekka.hrl"). - -%% epmd_module callbacks --export([start_link/0]). --export([port_please/2, port_please/3]). --export([names/0, names/1]). --export([register_node/2, register_node/3]). -%% -export([address_please/3]). - -%% The supervisor module erl_distribution tries to add us as a child -%% process. We don't need a child process, so return 'ignore'. -start_link() -> - ignore. - -register_node(_Name, _Port) -> - %% This is where we would connect to epmd and tell it which port - %% we're listening on, but since we're epmd-less, we don't do that. - - %% Need to return a "creation" number between 1 and 3. - Creation = rand:uniform(3), - {ok, Creation}. - -%% As of Erlang/OTP 19.1, register_node/3 is used instead of -%% register_node/2, passing along the address family, 'inet_tcp' or -%% 'inet6_tcp'. This makes no difference for our purposes. -register_node(Name, Port, _Family) -> - register_node(Name, Port). - -port_please(Name, _IP) -> - Port = ekka_dist:port(Name), - %% The distribution protocol version number has been 5 ever since - %% Erlang/OTP R6. - Version = 5, - {port, Port, Version}. - -port_please(Name, IP, _Timeout) -> - port_please(Name, IP). - -names() -> - {ok, H} = inet:gethostname(), - names(H). - -names(_Hostname) -> - %% Since we don't have epmd, we don't really know what other nodes - %% there are. - {error, address}. - diff --git a/_build/emqx/lib/ekka/src/ekka_guid.erl b/_build/emqx/lib/ekka/src/ekka_guid.erl deleted file mode 100644 index 269555fbb4..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_guid.erl +++ /dev/null @@ -1,136 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc Generate global unique id. -%% -%% -------------------------------------------------------- -%% | Timestamp | NodeID + PID | Sequence | -%% |<------- 64bits ------->|<--- 48bits --->|<- 16bits ->| -%% -------------------------------------------------------- -%% -%% 1. Timestamp: erlang:system_time if Erlang >= R18, otherwise os:timestamp -%% 2. NodeId: encode node() to 2 bytes integer -%% 3. Pid: encode pid to 4 bytes integer -%% 4. Sequence: 2 bytes sequence in one process -%% -%% @end - --module(ekka_guid). - --export([ gen/0 - , new/0 - , timestamp/1 - , to_hexstr/1 - , from_hexstr/1 - ]). - --define(MAX_SEQ, 16#FFFF). - --type(guid() :: <<_:128>>). - --export_type([guid/0]). - -%% @doc Generate a global unique id. --spec(gen() -> guid()). -gen() -> - Guid = case get(guid) of - undefined -> new(); - {_Ts, NPid, Seq} -> next(NPid, Seq) - end, - put(guid, Guid), bin(Guid). - -new() -> - {ts(), npid(), 0}. - --spec(timestamp(guid()) -> integer()). -timestamp(<>) -> - Ts. - -next(NPid, Seq) when Seq >= ?MAX_SEQ -> - {ts(), NPid, 0}; -next(NPid, Seq) -> - {ts(), NPid, Seq + 1}. - -bin({Ts, NPid, Seq}) -> - <>. - -ts() -> - case erlang:function_exported(erlang, system_time, 1) of - true -> %% R18 - erlang:system_time(micro_seconds); - false -> - {MegaSeconds, Seconds, MicroSeconds} = os:timestamp(), - (MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds - end. - -%% Copied from https://hub.fastgit.org/okeuday/uuid.git. -npid() -> - <> = - crypto:hash(sha, erlang:list_to_binary(erlang:atom_to_list(node()))), - - % later, when the pid format changes, handle the different format - ExternalTermFormatVersion = 131, - PidExtType = 103, - <> = erlang:term_to_binary(self()), - % 72 bits for the Erlang pid - <> = binary:part(PidBin, erlang:byte_size(PidBin), -9), - - % reduce the 160 bit NodeData checksum to 16 bits - NodeByte1 = ((((((((NodeD01 bxor NodeD02) - bxor NodeD03) - bxor NodeD04) - bxor NodeD05) - bxor NodeD06) - bxor NodeD07) - bxor NodeD08) - bxor NodeD09) - bxor NodeD10, - NodeByte2 = (((((((((NodeD11 bxor NodeD12) - bxor NodeD13) - bxor NodeD14) - bxor NodeD15) - bxor NodeD16) - bxor NodeD17) - bxor NodeD18) - bxor NodeD19) - bxor NodeD20) - bxor PidCR1, - - % reduce the Erlang pid to 32 bits - PidByte1 = PidID1 bxor PidSR4, - PidByte2 = PidID2 bxor PidSR3, - PidByte3 = PidID3 bxor PidSR2, - PidByte4 = PidID4 bxor PidSR1, - - <> = <>, - NPid. - -to_hexstr(<>) -> - list_to_binary(integer_to_list(I, 16)). - -from_hexstr(S) -> - I = list_to_integer(binary_to_list(S), 16), <>. - diff --git a/_build/emqx/lib/ekka/src/ekka_httpc.erl b/_build/emqx/lib/ekka/src/ekka_httpc.erl deleted file mode 100644 index 572499c0de..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_httpc.erl +++ /dev/null @@ -1,101 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_httpc). - --export([ get/3 - , get/4 - , get/5 - , post/3 - , post/4 - , put/3 - , put/4 - , delete/3 - , delete/4 - ]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - -get(Addr, Path, Params) -> - get(Addr, Path, Params, []). - -get(Addr, Path, Params, Headers) -> - get(Addr, Path, Params, Headers, []). - -get(Addr, Path, Params, Headers, HttpOpts) -> - Req = {build_url(Addr, Path, Params), Headers}, - parse_response(httpc:request(get, Req, [{autoredirect, true} | HttpOpts], [])). - -post(Addr, Path, Params) -> - post(Addr, Path, Params, []). - -post(Addr, Path, Params, HttpOpts) -> - Req = {build_url(Addr, Path), [], "application/x-www-form-urlencoded", build_query(Params)}, - parse_response(httpc:request(post, Req, [{autoredirect, true} | HttpOpts], [])). - -put(Addr, Path, Params) -> - put(Addr, Path, Params, []). - -put(Addr, Path, Params, HttpOpts) -> - Req = {build_url(Addr, Path), [], "application/x-www-form-urlencoded", build_query(Params)}, - parse_response(httpc:request(put, Req, [{autoredirect, true} | HttpOpts], [])). - -delete(Addr, Path, Params) -> - delete(Addr, Path, Params, []). - -delete(Addr, Path, Params, HttpOpts) -> - Req = {build_url(Addr, Path, Params), []}, - parse_response(httpc:request(delete, Req, HttpOpts, [])). - --spec(build_url(string(), string()) -> string()). -build_url(Addr, Path) -> - lists:concat([Addr, "/", Path]). - -build_url(Addr, Path, Params) -> - lists:concat([build_url(Addr, Path), "?", build_query(Params)]). - -build_query(Params) -> - string:join([urlencode(Param) || Param <- Params], "&"). - -urlencode(L) when is_list(L) -> - http_uri:encode(L); -urlencode({K, V}) -> - urlencode(K) ++ "=" ++ urlencode(V); -urlencode(A) when is_atom(A) -> - urlencode(atom_to_list(A)); -urlencode(I) when is_integer(I) -> - urlencode(integer_to_list(I)); -urlencode(B) when is_binary(B) -> - urlencode(binary_to_list(B)). - -parse_response({ok, {{_, Code, _}, _Headers, Body}}) -> - parse_response({ok, Code, Body}); -parse_response({ok, {Code, Body}}) -> - parse_response({ok, Code, Body}); -parse_response({ok, 200, Body}) -> - {ok, jsx:decode(iolist_to_binary(Body), [return_maps])}; -parse_response({ok, 201, Body}) -> - {ok, jsx:decode(iolist_to_binary(Body), [return_maps])}; -parse_response({ok, 204, _Body}) -> - {ok, []}; -parse_response({ok, Code, Body}) -> - {error, {Code, Body}}; -parse_response({error, Reason}) -> - {error, Reason}. - diff --git a/_build/emqx/lib/ekka/src/ekka_locker.erl b/_build/emqx/lib/ekka/src/ekka_locker.erl deleted file mode 100644 index 604fe52907..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_locker.erl +++ /dev/null @@ -1,311 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_locker). - --include_lib("stdlib/include/ms_transform.hrl"). - --behaviour(gen_server). - --export([ start_link/0 - , start_link/1 - , start_link/2 - ]). - -%% For test cases --export([stop/0, stop/1]). - -%% Lock APIs --export([ acquire/1 - , acquire/2 - , acquire/3 - , acquire/4 - ]). - --export([ release/1 - , release/2 - , release/3 - ]). - -%% For RPC call --export([ acquire_lock/2 - , acquire_lock/3 - , release_lock/2 - ]). - -%% gen_server Callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --type(resource() :: term()). - --type(lock_type() :: local | leader | quorum | all). - --type(lock_result() :: {boolean, [node() | {node(), any()}]}). - --type(piggyback() :: mfa()). - --export_type([ resource/0 - , lock_type/0 - , lock_result/0 - , piggyback/0 - ]). - --record(lock, { - resource :: resource(), - owner :: pid(), - counter :: integer(), - created :: erlang:timestamp() - }). - --record(lease, {expiry, timer}). - --record(state, {locks, lease, monitors}). - --define(SERVER, ?MODULE). --define(LOG(Level, Format, Args), - logger:Level("Ekka(Locker): " ++ Format, Args)). - -%% 15 seconds by default --define(LEASE_TIME, 15000). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - --spec(start_link() -> {ok, pid()} | {error, term()}). -start_link() -> - start_link(?SERVER). - --spec(start_link(atom()) -> {ok, pid()} | ignore | {error, any()}). -start_link(Name) -> - start_link(Name, ?LEASE_TIME). - --spec(start_link(atom(), pos_integer()) -> {ok, pid()} | ignore | {error, any()}). -start_link(Name, LeaseTime) -> - gen_server:start_link({local, Name}, ?MODULE, [Name, LeaseTime], []). - --spec(stop() -> ok). -stop() -> - stop(?SERVER). - --spec(stop(atom()) -> ok). -stop(Name) -> - gen_server:call(Name, stop). - --spec(acquire(resource()) -> {boolean(), [node()]}). -acquire(Resource) -> - acquire(?SERVER, Resource). - --spec(acquire(atom(), resource()) -> lock_result()). -acquire(Name, Resource) when is_atom(Name) -> - acquire(Name, Resource, local). - --spec(acquire(atom(), resource(), lock_type()) -> lock_result()). -acquire(Name, Resource, Type) -> - acquire(Name, Resource, Type, undefined). - --spec(acquire(atom(), resource(), lock_type(), piggyback()) -> lock_result()). -acquire(Name, Resource, local, Piggyback) when is_atom(Name) -> - acquire_lock(Name, lock_obj(Resource), Piggyback); -acquire(Name, Resource, leader, Piggyback) when is_atom(Name)-> - Leader = ekka_membership:leader(), - case rpc:call(Leader, ?MODULE, acquire_lock, - [Name, lock_obj(Resource), Piggyback]) of - Err = {badrpc, _Reason} -> - {false, [{Leader, Err}]}; - Res -> Res - end; -acquire(Name, Resource, quorum, Piggyback) when is_atom(Name) -> - Ring = ekka_membership:ring(up), - Nodes = ekka_ring:find_nodes(Resource, Ring), - acquire_locks(Nodes, Name, lock_obj(Resource), Piggyback); - -acquire(Name, Resource, all, Piggyback) when is_atom(Name) -> - acquire_locks(ekka_membership:nodelist(up), - Name, lock_obj(Resource), Piggyback). - -acquire_locks(Nodes, Name, LockObj, Piggyback) -> - {ResL, _BadNodes} - = rpc:multicall(Nodes, ?MODULE, acquire_lock, [Name, LockObj, Piggyback]), - case merge_results(ResL) of - Res = {true, _} -> Res; - Res = {false, _} -> - rpc:multicall(Nodes, ?MODULE, release_lock, [Name, LockObj]), - Res - end. - -acquire_lock(Name, LockObj, Piggyback) -> - {acquire_lock(Name, LockObj), [with_piggyback(node(), Piggyback)]}. - -acquire_lock(Name, LockObj = #lock{resource = Resource, owner = Owner}) -> - Pos = #lock.counter, - %% check lock status and set the lock atomically - try ets:update_counter(Name, Resource, [{Pos, 0}, {Pos, 1, 1, 1}], LockObj) of - [0, 1] -> %% no lock before, lock it - true; - [1, 1] -> %% has already been locked, either by self or by others - case ets:lookup(Name, Resource) of - [#lock{owner = Owner}] -> true; - _Other -> false - end - catch - error:badarg -> - %% While remote node is booting, this might fail because - %% the ETS table has not been created at that moment - true - end. - -with_piggyback(Node, undefined) -> - Node; -with_piggyback(Node, {M, F, Args}) -> - {Node, erlang:apply(M, F, Args)}. - -lock_obj(Resource) -> - #lock{resource = Resource, - owner = self(), - counter = 0, - created = erlang:system_time(millisecond) - }. - --spec(release(resource()) -> lock_result()). -release(Resource) -> - release(?SERVER, Resource). - --spec(release(atom(), resource()) -> lock_result()). -release(Name, Resource) -> - release(Name, Resource, local). - --spec(release(atom(), resource(), lock_type()) -> lock_result()). -release(Name, Resource, local) -> - release_lock(Name, lock_obj(Resource)); -release(Name, Resource, leader) -> - Leader = ekka_membership:leader(), - case rpc:call(Leader, ?MODULE, release_lock, [Name, lock_obj(Resource)]) of - Err = {badrpc, _Reason} -> - {false, [{Leader, Err}]}; - Res -> Res - end; -release(Name, Resource, quorum) -> - Ring = ekka_membership:ring(up), - Nodes = ekka_ring:find_nodes(Resource, Ring), - release_locks(Nodes, Name, lock_obj(Resource)); -release(Name, Resource, all) -> - release_locks(ekka_membership:nodelist(up), Name, lock_obj(Resource)). - -release_locks(Nodes, Name, LockObj) -> - {ResL, _BadNodes} = rpc:multicall(Nodes, ?MODULE, release_lock, [Name, LockObj]), - merge_results(ResL). - -release_lock(Name, #lock{resource = Resource, owner = Owner}) -> - Res = try ets:lookup(Name, Resource) of - [Lock = #lock{owner = Owner}] -> - ets:delete_object(Name, Lock); - [_Lock] -> false; - [] -> true - catch - error:badarg -> true - end, - {Res, [node()]}. - -merge_results(ResL) -> - merge_results(ResL, [], []). -merge_results([], Succ, []) -> - {true, lists:flatten(Succ)}; -merge_results([], _, Failed) -> - {false, lists:flatten(Failed)}; -merge_results([{true, Res}|ResL], Succ, Failed) -> - merge_results(ResL, [Res|Succ], Failed); -merge_results([{false, Res}|ResL], Succ, Failed) -> - merge_results(ResL, Succ, [Res|Failed]). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Name, LeaseTime]) -> - Tab = ets:new(Name, [public, set, named_table, {keypos, 2}, - {read_concurrency, true}, {write_concurrency, true}]), - TRef = timer:send_interval(LeaseTime * 2, check_lease), - Lease = #lease{expiry = LeaseTime, timer = TRef}, - {ok, #state{locks = Tab, lease = Lease, monitors = #{}}}. - -handle_call(stop, _From, State) -> - {stop, normal, ok, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignore, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(check_lease, State = #state{locks = Tab, lease = Lease, monitors = Monitors}) -> - Monitors1 = lists:foldl( - fun(#lock{resource = Resource, owner = Owner}, MonAcc) -> - case maps:find(Owner, MonAcc) of - {ok, Resources} -> - maps:put(Owner, [Resource|Resources], MonAcc); - error -> - _MRef = erlang:monitor(process, Owner), - maps:put(Owner, [Resource], MonAcc) - end - end, Monitors, check_lease(Tab, Lease, erlang:system_time(millisecond))), - {noreply, State#state{monitors = Monitors1}, hibernate}; - -handle_info({'DOWN', _MRef, process, DownPid, _Reason}, - State = #state{locks = Tab, monitors = Monitors}) -> - case maps:find(DownPid, Monitors) of - {ok, Resources} -> - lists:foreach( - fun(Resource) -> - case ets:lookup(Tab, Resource) of - [Lock = #lock{owner = OwnerPid}] when OwnerPid =:= DownPid -> - ets:delete_object(Tab, Lock); - _ -> ok - end - end, Resources), - {noreply, State#state{monitors = maps:remove(DownPid, Monitors)}}; - error -> - {noreply, State} - end; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State = #state{lease = Lease}) -> - cancel_lease(Lease). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -check_lease(Tab, #lease{expiry = Expiry}, Now) -> - Spec = ets:fun2ms(fun({_, _, _, _, T} = Resource) when (Now - T) > Expiry -> Resource end), - ets:select(Tab, Spec). - -cancel_lease(#lease{timer = TRef}) -> timer:cancel(TRef). - diff --git a/_build/emqx/lib/ekka/src/ekka_locker_sup.erl b/_build/emqx/lib/ekka/src/ekka_locker_sup.erl deleted file mode 100644 index 3fc8269ab6..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_locker_sup.erl +++ /dev/null @@ -1,37 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_locker_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -init([]) -> - Locker = #{id => ekka_locker, - start => {ekka_locker, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [ekka_locker] - }, - {ok, {{one_for_one, 100, 3600}, [Locker]}}. - diff --git a/_build/emqx/lib/ekka/src/ekka_membership.erl b/_build/emqx/lib/ekka/src/ekka_membership.erl deleted file mode 100644 index 348560ed18..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_membership.erl +++ /dev/null @@ -1,428 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_membership). - --behaviour(gen_server). - --include("ekka.hrl"). - --export([start_link/0, stop/0]). - -%% Ring API --export([ring/0, ring/1]). - -%% Members API --export([ local_member/0 - , lookup_member/1 - , members/0 - , members/1 - , is_member/1 - , oldest/1 - ]). - --export([ leader/0 - , nodelist/0 - , nodelist/1 - , coordinator/0 - , coordinator/1 - ]). - --export([is_all_alive/0]). - -%% Monitor API --export([monitor/3]). - -%% Announce API --export([announce/1]). - -%% Ping/Pong API --export([ping/2, pong/2]). - -%% On Node/Mnesia Status --export([ node_up/1 - , node_down/1 - , mnesia_up/1 - , mnesia_down/1 - ]). - -%% On Cluster Status --export([ partition_occurred/1 - , partition_healed/1 - ]). - -%% gen_server Callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --record(state, {monitors, events}). - --type(event_type() :: partition | membership). - --define(SERVER, ?MODULE). --define(LOG(Level, Format, Args), - logger:Level("Ekka(Membership): " ++ Format, Args)). - --spec(start_link() -> {ok, pid()} | {error, term()}). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - --spec(stop() -> ok). -stop() -> - gen_server:stop(?SERVER). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - --spec(ring() -> [member()]). -ring() -> - lists:keysort(#member.hash, members()). - --spec(ring(up | down) -> [member()]). -ring(Status) -> - lists:keysort(#member.hash, members(Status)). - --spec(local_member() -> member()). -local_member() -> - lookup_member(node()). - --spec(lookup_member(node()) -> member() | false). -lookup_member(Node) -> - case ets:lookup(membership, Node) of [M] -> M; [] -> false end. - --spec(is_member(node()) -> boolean()). -is_member(Node) -> - ets:member(membership, Node). - --spec(members() -> [member()]). -members() -> - ets:tab2list(membership). - --spec(members(up | down) -> [member()]). -members(Status) -> - [M || M = #member{status = St} <- members(), St =:= Status]. - -%% Get leader node of the members --spec(leader() -> node()). -leader() -> - Member = oldest(members()), Member#member.node. - -%% Get coordinator node from all the alive members --spec(coordinator() -> node()). -coordinator() -> - Member = oldest(members(up)), Member#member.node. - -%% Get Coordinator from nodes --spec(coordinator(list(node())) -> node()). -coordinator(Nodes) -> - Member = oldest([M || M <- [lookup_member(N) || N <- Nodes], M =/= false]), - Member#member.node. - -%% Get oldest member. -oldest(Members) -> - hd(lists:sort(fun compare/2, Members)). - -%% @private -compare(M1, M2) -> - M1#member.guid < M2#member.guid. - --spec(nodelist() -> [node()]). -nodelist() -> - [Node || #member{node = Node} <- members()]. - --spec(nodelist(up | down) -> [node()]). -nodelist(Status) -> - [Node || #member{node = Node} <- members(Status)]. - --spec(is_all_alive() -> boolean()). -is_all_alive() -> - length(ekka_mnesia:cluster_nodes(all) -- [node() | nodes()]) == 0. - --spec(monitor(event_type(), pid() | function(), boolean()) -> ok). -monitor(Type, PidOrFun, OnOff) -> - call({monitor, {Type, PidOrFun, OnOff}}). - --spec(announce(join | leave | heal | {force_leave, node()}) -> ok). -announce(Action) -> - call({announce, Action}). - --spec(ping(node(), member()) -> ok). -ping(Node, Member) -> - case ekka_node:is_aliving(Node) of - true -> ping(Node, Member, 5); - false -> ignore - end. - -ping(Node, _Member, 0) -> - ?LOG(error, "Failed to ping ~s~n", [Node]); -ping(Node, Member, Retries) -> - case ekka_node:is_running(Node, ekka) of - true -> cast(Node, {ping, Member}); - false -> timer:sleep(1000), - ping(Node, Member, Retries -1) - end. - -pong(Node, Member) -> - cast(Node, {pong, Member}). - --spec(node_up(node()) -> ok). -node_up(Node) -> - cast({node_up, Node}). - --spec(node_down(node()) -> ok). -node_down(Node) -> - cast({node_down, Node}). - --spec(mnesia_up(node()) -> ok). -mnesia_up(Node) -> - cast({mnesia_up, Node}). - --spec(mnesia_down(node()) -> ok). -mnesia_down(Node) -> - cast({mnesia_down, Node}). - --spec partition_occurred(node()) -> ok. -partition_occurred(Node) -> - cast({partition_occurred, Node}). - --spec partition_healed(node()) -> ok. -partition_healed(Node) -> - cast({partition_healed, Node}). - -%% @private -cast(Msg) -> - gen_server:cast(?SERVER, Msg). - -%% @private -cast(Node, Msg) -> - gen_server:cast({?SERVER, Node}, Msg). - -%% @private -call(Req) -> - gen_server:call(?SERVER, Req). - -%%-------------------------------------------------------------------- -%% gen_server Callbacks -%%-------------------------------------------------------------------- - -init([]) -> - _ = ets:new(membership, [ordered_set, protected, named_table, {keypos, 2}]), - IsMnesiaRunning = case lists:member(node(), ekka_mnesia:running_nodes()) of - true -> running; - false -> stopped - end, - LocalMember = with_hash(#member{node = node(), guid = ekka_guid:gen(), - status = up, mnesia = IsMnesiaRunning, - ltime = erlang:timestamp() - }), - true = ets:insert(membership, LocalMember), - lists:foreach(fun(Node) -> - spawn(?MODULE, ping, [Node, LocalMember]) - end, ekka_mnesia:cluster_nodes(all) -- [node()]), - {ok, #state{monitors = [], events = []}}. - -with_hash(Member = #member{node = Node, guid = Guid}) -> - Member#member{hash = erlang:phash2({Node, Guid}, trunc(math:pow(2, 32) - 1))}. - -handle_call({monitor, {Type, PidOrFun, true}}, _From, State) -> - reply(ok, add_monitor({Type, PidOrFun}, State)); - -handle_call({monitor, {Type, PidOrFun, false}}, _From, State) -> - reply(ok, del_monitor({Type, PidOrFun}, State)); - -handle_call({announce, Action}, _From, State) - when Action == join; Action == leave; Action == heal -> - Status = case Action of - join -> joining; - heal -> healing; - leave -> leaving - end, - _ = [cast(N, {Status, node()}) || N <- nodelist(), N =/= node()], - reply(ok, State); - -handle_call({announce, {force_leave, Node}}, _From, State) -> - _ = [cast(N, {leaving, Node}) || N <- nodelist(), N =/= Node], - reply(ok, State); - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignore, State}. - -handle_cast({node_up, Node}, State) -> - ?LOG(info, "Node ~s up", [Node]), - case ekka_mnesia:is_node_in_cluster(Node) of - true -> - Member = case lookup(Node) of - [M] -> M#member{status = up}; - [] -> #member{node = Node, status = up} - end, - insert(Member#member{mnesia = ekka_mnesia:cluster_status(Node)}); - false -> ignore - end, - notify({node, up, Node}, State), - {noreply, State}; - -handle_cast({node_down, Node}, State) -> - ?LOG(info, "Node ~s down", [Node]), - case lookup(Node) of - [#member{status = leaving}] -> - ets:delete(membership, Node); - [Member] -> - insert(Member#member{status = down}); - [] -> ignore - end, - notify({node, down, Node}, State), - {noreply, State}; - -handle_cast({joining, Node}, State) -> - ?LOG(info, "Node ~s joining", [Node]), - insert(case lookup(Node) of - [Member] -> Member#member{status = joining}; - [] -> #member{node = Node, status = joining} - end), - notify({node, joining, Node}, State), - {noreply, State}; - -handle_cast({healing, Node}, State) -> - ?LOG(info, "Node ~s healing", [Node]), - case lookup(Node) of - [Member] -> insert(Member#member{status = healing}); - [] -> ignore - end, - notify({node, healing, Node}, State), - {noreply, State}; - -handle_cast({ping, Member = #member{node = Node}}, State) -> - pong(Node, local_member()), - insert(Member#member{mnesia = ekka_mnesia:cluster_status(Node)}), - {noreply, State}; - -handle_cast({pong, Member = #member{node = Node}}, State) -> - insert(Member#member{mnesia = ekka_mnesia:cluster_status(Node)}), - {noreply, State}; - -handle_cast({leaving, Node}, State) -> - ?LOG(info, "Node ~s leaving", [Node]), - case lookup(Node) of - [#member{status = down}] -> - ets:delete(membership, Node); - [Member] -> - insert(Member#member{status = leaving}); - [] -> ignore - end, - notify({node, leaving, Node}, State), - {noreply, State}; - -handle_cast({mnesia_up, Node}, State) -> - ?LOG(info, "Mnesia ~s up", [Node]), - insert(case lookup(Node) of - [Member] -> - Member#member{status = up, mnesia = running}; - [] -> - #member{node = Node, status = up, mnesia = running} - end), - spawn(?MODULE, pong, [Node, local_member()]), - notify({mnesia, up, Node}, State), - {noreply, State}; - -handle_cast({mnesia_down, Node}, State) -> - ?LOG(info, "Mnesia ~s down", [Node]), - case lookup(Node) of - [#member{status = leaving}] -> - ets:delete(membership, Node); - [Member] -> - insert(Member#member{mnesia = stopped}); - [] -> ignore - end, - notify({mnesia, down, Node}, State), - {noreply, State}; - -handle_cast({partition_occurred, Node}, State) -> - notify(partition, {occurred, Node}, State), - {noreply, State}; - -handle_cast({partition_healed, Nodes}, State) -> - notify(partition, {healed, Nodes}, State), - {noreply, State}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({'DOWN', _MRef, process, DownPid, _Reason}, - State = #state{monitors = Monitors}) -> - Left = [M || M = {{_, Pid}, _} <- Monitors, Pid =/= DownPid], - {noreply, State#state{monitors = Left}}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -lookup(Node) -> - ets:lookup(membership, Node). - -insert(Member) -> - ets:insert(membership, Member#member{ltime = erlang:timestamp()}). - -reply(Reply, State) -> - {reply, Reply, State}. - -notify(Event, State) -> - notify(membership, Event, State). - -notify(Type, Event, #state{monitors = Monitors}) -> - Notify = fun(P) when is_pid(P) -> - P ! {Type, Event}; - (F) when is_function(F) -> - F({Type, Event}) - end, - [Notify(PidOrFun) || {{T, PidOrFun}, _} <- Monitors, T == Type]. - -add_monitor({Type, PidOrFun}, S = #state{monitors = Monitors}) -> - case lists:keymember({Type, PidOrFun}, 1, Monitors) of - true -> S; - false -> - MRef = case is_pid(PidOrFun) of - true -> erlang:monitor(process, PidOrFun); - _ -> undefined - end, - S#state{monitors = [{{Type, PidOrFun}, MRef} | Monitors]} - end. - -del_monitor({Type, PidOrFun}, S = #state{monitors = Monitors}) -> - case lists:keyfind({Type, PidOrFun}, 1, Monitors) of - false -> S; - {_, MRef} -> - is_pid(PidOrFun) andalso erlang:demonitor(MRef, [flush]), - S#state{monitors = lists:delete({{Type, PidOrFun}, MRef}, Monitors)} - end. - diff --git a/_build/emqx/lib/ekka/src/ekka_mnesia.erl b/_build/emqx/lib/ekka/src/ekka_mnesia.erl deleted file mode 100644 index 4bb8021068..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_mnesia.erl +++ /dev/null @@ -1,312 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_mnesia). - --include("ekka.hrl"). - -%% Start and stop mnesia --export([ start/0 - , ensure_started/0 - , ensure_stopped/0 - , connect/1 - ]). - -%% Mnesia Cluster API --export([ join_cluster/1 - , leave_cluster/0 - , remove_from_cluster/1 - , cluster_info/0 - , cluster_status/1 - , cluster_view/0 - , cluster_nodes/1 - , running_nodes/0 - ]). - --export([ is_node_in_cluster/0 - , is_node_in_cluster/1 - ]). - -%% Dir, schema and tables --export([ data_dir/0 - , copy_schema/1 - , delete_schema/0 - , del_schema_copy/1 - , create_table/2 - , copy_table/1 - , copy_table/2 - ]). - -%%-------------------------------------------------------------------- -%% Start and init mnesia -%%-------------------------------------------------------------------- - -%% @doc Start mnesia database --spec(start() -> ok | {error, term()}). -start() -> - ensure_ok(ensure_data_dir()), - ensure_ok(init_schema()), - ok = mnesia:start(), - init_tables(), - wait_for(tables). - -%% @private -ensure_data_dir() -> - case filelib:ensure_dir(data_dir()) of - ok -> ok; - {error, Reason} -> {error, Reason} - end. - -%% @doc Data dir --spec(data_dir() -> string()). -data_dir() -> mnesia:system_info(directory). - -%% @doc Ensure mnesia started --spec(ensure_started() -> ok | {error, any()}). -ensure_started() -> - ok = mnesia:start(), wait_for(start). - -%% @doc Ensure mnesia stopped --spec(ensure_stopped() -> ok | {error, any()}). -ensure_stopped() -> - stopped = mnesia:stop(), wait_for(stop). - -%% @private -%% @doc Init mnesia schema or tables. -init_schema() -> - case mnesia:system_info(extra_db_nodes) of - [] -> mnesia:create_schema([node()]); - [_|_] -> ok - end. - -%% @private -%% @doc Init mnesia tables. -init_tables() -> - case mnesia:system_info(extra_db_nodes) of - [] -> create_tables(); - [_|_] -> copy_tables() - end. - -%% @doc Create mnesia tables. -create_tables() -> - ekka_boot:apply_module_attributes(boot_mnesia). - -%% @doc Copy mnesia tables. -copy_tables() -> - ekka_boot:apply_module_attributes(copy_mnesia). - -%% @doc Create mnesia table. --spec(create_table(Name:: atom(), TabDef :: list()) -> ok | {error, any()}). -create_table(Name, TabDef) -> - ensure_tab(mnesia:create_table(Name, TabDef)). - -%% @doc Copy mnesia table. --spec(copy_table(Name :: atom()) -> ok). -copy_table(Name) -> - copy_table(Name, ram_copies). - --spec(copy_table(Name:: atom(), ram_copies | disc_copies) -> ok). -copy_table(Name, RamOrDisc) -> - ensure_tab(mnesia:add_table_copy(Name, node(), RamOrDisc)). - -%% @doc Copy schema. -copy_schema(Node) -> - case mnesia:change_table_copy_type(schema, Node, disc_copies) of - {atomic, ok} -> ok; - {aborted, {already_exists, schema, Node, disc_copies}} -> - ok; - {aborted, Error} -> - {error, Error} - end. - -%% @doc Force to delete schema. -delete_schema() -> - mnesia:delete_schema([node()]). - -%% @doc Delete schema copy -del_schema_copy(Node) -> - case mnesia:del_table_copy(schema, Node) of - {atomic, ok} -> ok; - {aborted, Reason} -> {error, Reason} - end. - -%%-------------------------------------------------------------------- -%% Cluster mnesia -%%-------------------------------------------------------------------- - -%% @doc Join the mnesia cluster --spec(join_cluster(node()) -> ok). -join_cluster(Node) when Node =/= node() -> - %% Stop mnesia and delete schema first - ensure_ok(ensure_stopped()), - ensure_ok(delete_schema()), - %% Start mnesia and cluster to node - ensure_ok(ensure_started()), - ensure_ok(connect(Node)), - ensure_ok(copy_schema(node())), - %% Copy tables - copy_tables(), - ensure_ok(wait_for(tables)). - -%% @doc Cluster Info --spec(cluster_info() -> map()). -cluster_info() -> - Running = mnesia:system_info(running_db_nodes), - Stopped = mnesia:system_info(db_nodes) -- Running, - #{running_nodes => lists:sort(Running), - stopped_nodes => lists:sort(Stopped) - }. - -%% @doc Cluster status of the node --spec(cluster_status(node()) -> running | stopped | false). -cluster_status(Node) -> - case is_node_in_cluster(Node) of - true -> - case lists:member(Node, running_nodes()) of - true -> running; - false -> stopped - end; - false -> false - end. - --spec(cluster_view() -> {[node()], [node()]}). -cluster_view() -> - list_to_tuple([lists:sort(cluster_nodes(Status)) - || Status <- [running, stopped]]). - -%% @doc This node try leave the cluster --spec(leave_cluster() -> ok | {error, any()}). -leave_cluster() -> - case running_nodes() -- [node()] of - [] -> - {error, node_not_in_cluster}; - Nodes -> - case lists:any(fun(Node) -> - case leave_cluster(Node) of - ok -> true; - {error, _Reason} -> false - end - end, Nodes) of - true -> ok; - false -> {error, {failed_to_leave, Nodes}} - end - end. - --spec(leave_cluster(node()) -> ok | {error, any()}). -leave_cluster(Node) when Node =/= node() -> - case is_running_db_node(Node) of - true -> - ensure_ok(ensure_stopped()), - ensure_ok(rpc:call(Node, ?MODULE, del_schema_copy, [node()])), - ensure_ok(delete_schema()); - %%ensure_ok(start()); %% restart? - false -> - {error, {node_not_running, Node}} - end. - -%% @doc Remove node from mnesia cluster. --spec(remove_from_cluster(node()) -> ok | {error, any()}). -remove_from_cluster(Node) when Node =/= node() -> - case {is_node_in_cluster(Node), is_running_db_node(Node)} of - {true, true} -> - ensure_ok(rpc:call(Node, ?MODULE, ensure_stopped, [])), - mnesia_lib:del(extra_db_nodes, Node), - ensure_ok(del_schema_copy(Node)), - ensure_ok(rpc:call(Node, ?MODULE, delete_schema, [])); - {true, false} -> - mnesia_lib:del(extra_db_nodes, Node), - ensure_ok(del_schema_copy(Node)); - %ensure_ok(rpc:call(Node, ?MODULE, delete_schema, [])); - {false, _} -> - {error, node_not_in_cluster} - end. - -%% @doc Is this node in mnesia cluster? -is_node_in_cluster() -> - ekka_mnesia:cluster_nodes(all) =/= [node()]. - -%% @doc Is the node in mnesia cluster? --spec(is_node_in_cluster(node()) -> boolean()). -is_node_in_cluster(Node) when Node =:= node() -> - is_node_in_cluster(); -is_node_in_cluster(Node) -> - lists:member(Node, cluster_nodes(all)). - -%% @private -%% @doc Is running db node. -is_running_db_node(Node) -> - lists:member(Node, running_nodes()). - -%% @doc Cluster with node. --spec(connect(node()) -> ok | {error, any()}). -connect(Node) -> - case mnesia:change_config(extra_db_nodes, [Node]) of - {ok, [Node]} -> ok; - {ok, []} -> {error, {failed_to_connect_node, Node}}; - Error -> Error - end. - -%% @doc Running nodes. --spec(running_nodes() -> list(node())). -running_nodes() -> cluster_nodes(running). - -%% @doc Cluster nodes. --spec(cluster_nodes(all | running | stopped) -> [node()]). -cluster_nodes(all) -> - mnesia:system_info(db_nodes); -cluster_nodes(running) -> - mnesia:system_info(running_db_nodes); -cluster_nodes(stopped) -> - cluster_nodes(all) -- cluster_nodes(running). - -%% @private -ensure_ok(ok) -> ok; -ensure_ok({error, {_Node, {already_exists, _Node}}}) -> ok; -ensure_ok({badrpc, Reason}) -> throw({error, {badrpc, Reason}}); -ensure_ok({error, Reason}) -> throw({error, Reason}). - -%% @private -ensure_tab({atomic, ok}) -> ok; -ensure_tab({aborted, {already_exists, _Name}}) -> ok; -ensure_tab({aborted, {already_exists, _Name, _Node}})-> ok; -ensure_tab({aborted, Error}) -> Error. - -%% @doc Wait for mnesia to start, stop or tables ready. --spec(wait_for(start | stop | tables) -> ok | {error, Reason :: atom()}). -wait_for(start) -> - case mnesia:system_info(is_running) of - yes -> ok; - no -> {error, mnesia_unexpectedly_stopped}; - stopping -> {error, mnesia_unexpectedly_stopping}; - starting -> timer:sleep(1000), wait_for(start) - end; - -wait_for(stop) -> - case mnesia:system_info(is_running) of - no -> ok; - yes -> {error, mnesia_unexpectedly_running}; - starting -> {error, mnesia_unexpectedly_starting}; - stopping -> timer:sleep(1000), wait_for(stop) - end; - -wait_for(tables) -> - Tables = mnesia:system_info(local_tables), - case mnesia:wait_for_tables(Tables, 150000) of - ok -> ok; - {error, Reason} -> {error, Reason}; - {timeout, BadTables} -> {error, {timeout, BadTables}} - end. - diff --git a/_build/emqx/lib/ekka/src/ekka_node.erl b/_build/emqx/lib/ekka/src/ekka_node.erl deleted file mode 100644 index f369782366..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_node.erl +++ /dev/null @@ -1,57 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_node). - -%% Node API --export([ is_aliving/1 - , is_running/1 - , is_running/2 - , parse_name/1 - ]). - -%% @doc Is the node aliving? --spec(is_aliving(node()) -> boolean()). -is_aliving(Node) when Node =:= node() -> - true; -is_aliving(Node) -> - lists:member(Node, nodes()) orelse net_adm:ping(Node) =:= pong. - -%% @doc Is the application running? --spec(is_running(atom()) -> boolean()). -is_running(App) -> - lists:keymember(App, 1, application:which_applications()). - -%% @doc Is the application running? --spec(is_running(node(), atom()) -> boolean()). -is_running(Node, App) -> - case rpc:call(Node, ekka_node, is_running, [App]) of - {badrpc, _} -> false; - Result -> Result - end. - -%% @doc Parse node name. --spec(parse_name(string()) -> atom()). -parse_name(Name) when is_list(Name) -> - case string:tokens(Name, "@") of - [_Node, _Host] -> list_to_atom(Name); - _ -> with_host(Name) - end. - -with_host(Name) -> - [_, Host] = string:tokens(atom_to_list(node()), "@"), - list_to_atom(lists:concat([Name, "@", Host])). - diff --git a/_build/emqx/lib/ekka/src/ekka_node_monitor.erl b/_build/emqx/lib/ekka/src/ekka_node_monitor.erl deleted file mode 100644 index c232a546f3..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_node_monitor.erl +++ /dev/null @@ -1,225 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_node_monitor). - --behaviour(gen_server). - --include("ekka.hrl"). - -%% API --export([start_link/0, stop/0]). - --export([partitions/0]). - -%% Internal Exports --export([cast/2, run_after/2]). - -%% gen_server Callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --record(state, { - partitions :: list(node()), - heartbeat :: undefined | reference(), - autoheal :: ekka_autoheal:autoheal(), - autoclean :: ekka_autoclean:autoclean() - }). - --define(SERVER, ?MODULE). --define(LOG(Level, Format, Args), - logger:Level("Ekka(Monitor): " ++ Format, Args)). - -%% @doc Start the node monitor. --spec(start_link() -> {ok, pid()} | {error, term()}). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - -stop() -> gen_server:stop(?SERVER). - -%% @doc Get partitions. -partitions() -> - gen_server:call(?SERVER, partitions). - -%% @private -cast(Node, Msg) -> - gen_server:cast({?SERVER, Node}, Msg). - -%% @private -run_after(Delay, Msg) -> - erlang:send_after(Delay, ?SERVER, Msg). - -%%-------------------------------------------------------------------- -%% gen_server Callbacks -%%-------------------------------------------------------------------- - -init([]) -> - process_flag(trap_exit, true), - rand:seed(exsplus, erlang:timestamp()), - net_kernel:monitor_nodes(true, [{node_type, visible}, nodedown_reason]), - {ok, _} = mnesia:subscribe(system), - lists:foreach(fun(N) -> self() ! {nodeup, N, []} end, nodes() -- [node()]), - State = #state{partitions = [], - autoheal = ekka_autoheal:init(), - autoclean = ekka_autoclean:init() - }, - {ok, ensure_heartbeat(State)}. - -handle_call(partitions, _From, State = #state{partitions = Partitions}) -> - {reply, Partitions, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignore, State}. - -handle_cast({heartbeat, _FromNode}, State) -> - {noreply, State}; - -handle_cast({suspect, FromNode, TargetNode}, State) -> - ?LOG(info, "Suspect from ~s: ~s~n", [FromNode, TargetNode]), - spawn(fun() -> - Status = case net_adm:ping(TargetNode) of - pong -> up; - pang -> down - end, - cast(FromNode, {confirm, TargetNode, Status}) - end), - {noreply, State}; - -handle_cast({confirm, TargetNode, Status}, State) -> - ?LOG(info, "Confirm ~s ~s", [TargetNode, Status]), - {noreply, State}; - -handle_cast(Msg = {report_partition, _Node}, State) -> - {noreply, autoheal_handle_msg(Msg, State)}; - -handle_cast(Msg = {heal_partition, _SplitView}, State) -> - {noreply, autoheal_handle_msg(Msg, State)}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({nodeup, Node, _Info}, State) -> - ekka_membership:node_up(Node), - {noreply, State}; - -handle_info({nodedown, Node, _Info}, State) -> - ekka_membership:node_down(Node), - run_after(3000, {suspect, Node}), - {noreply, State}; - -handle_info({suspect, Node}, State) -> - case ekka_mnesia:running_nodes() -- [node(), Node] of - [ProxyNode|_] -> - cast(ProxyNode, {suspect, node(), Node}); - [] -> ignore - end, - {noreply, State}; - -handle_info({mnesia_system_event, {mnesia_up, Node}}, - State = #state{partitions = Partitions}) -> - ekka_membership:mnesia_up(Node), - case lists:member(Node, Partitions) of - false -> ok; - true -> ekka_membership:partition_healed(Node) - end, - {noreply, State#state{partitions = lists:delete(Node, Partitions)}}; - -handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> - ekka_membership:mnesia_down(Node), - {noreply, State}; - -handle_info({mnesia_system_event, {inconsistent_database, Context, Node}}, - State = #state{partitions = Partitions}) -> - ?LOG(critical, "Network partition detected from node ~s: ~p", [Node, Context]), - ekka_membership:partition_occurred(Node), - case ekka_autoheal:enabled() of - {true, _} -> run_after(3000, confirm_partition); - false -> ignore - end, - {noreply, State#state{partitions = lists:usort([Node | Partitions])}}; - -handle_info({mnesia_system_event, {mnesia_overload, Details}}, State) -> - ?LOG(error, "Mnesia overload: ~p", [Details]), - {noreply, State}; - -handle_info({mnesia_system_event, Event}, State) -> - ?LOG(error, "Mnesia system event: ~p", [Event]), - {noreply, State}; - -%% Confirm if we should report the partitions -handle_info(confirm_partition, State = #state{partitions = []}) -> - {noreply, State}; - -handle_info(confirm_partition, State = #state{partitions = Partitions}) -> - Leader = ekka_membership:leader(), - case ekka_node:is_running(Leader, ekka) of - true -> cast(Leader, {report_partition, node()}); - false -> ?LOG(critical, "Leader is down, cannot autoheal the partitions: ~p", [Partitions]) - end, - {noreply, State}; - -handle_info({autoheal, Msg}, State) -> - {noreply, autoheal_handle_msg(Msg, State)}; - -handle_info(heartbeat, State) -> - AliveNodes = [N || N <- ekka_mnesia:cluster_nodes(all), - lists:member(N, nodes())], - lists:foreach(fun(Node) -> - cast(Node, {heartbeat, node()}) - end, AliveNodes), - {noreply, ensure_heartbeat(State#state{heartbeat = undefined})}; - -handle_info(Msg = {'EXIT', Pid, _Reason}, State = #state{autoheal = Autoheal}) -> - case ekka_autoheal:proc(Autoheal) of - Pid -> {noreply, autoheal_handle_msg(Msg, State)}; - _ -> {noreply, State} - end; - -%% Autoclean Event. -handle_info(autoclean, State = #state{autoclean = AutoClean}) -> - {noreply, State#state{autoclean = ekka_autoclean:check(AutoClean)}}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -ensure_heartbeat(State = #state{heartbeat = undefined}) -> - Interval = rand:uniform(2000) + 2000, - State#state{heartbeat = run_after(Interval, heartbeat)}; - -ensure_heartbeat(State) -> - State. - -autoheal_handle_msg(Msg, State = #state{autoheal = Autoheal}) -> - State#state{autoheal = ekka_autoheal:handle_msg(Msg, Autoheal)}. - diff --git a/_build/emqx/lib/ekka/src/ekka_node_ttl.erl b/_build/emqx/lib/ekka/src/ekka_node_ttl.erl deleted file mode 100644 index 8b85196f38..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_node_ttl.erl +++ /dev/null @@ -1,62 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_node_ttl). - --behaviour(gen_statem). - -%% API --export([start_link/2, stop/0]). - -%% gen_statem callbacks --export([ init/1 - , callback_mode/0 - , handle_event/4 - , terminate/3 - , code_change/4 - ]). - --record(state, {ttl, mfa}). - -start_link(Ttl, MFA) -> - gen_statem:start_link({local, ?MODULE}, ?MODULE, [Ttl, MFA], []). - -stop() -> gen_statem:stop(?MODULE). - -%%-------------------------------------------------------------------- -%% gen_statem callbacks -%%-------------------------------------------------------------------- - -init([Ttl, MFA]) -> - {ok, alive, #state{ttl = Ttl, mfa = MFA}, Ttl div 2}. - -callback_mode() -> handle_event_function. - -handle_event(timeout, _Timeout, alive, State = #state{ttl = Ttl, mfa = {M, F, A}}) -> - try - erlang:apply(M, F, A) - catch - _:Error:Stacktrace -> - logger:error("TTL error: ~p Statcktrace:~n~p", [Error, Stacktrace]) - end, - {next_state, alive, State, Ttl div 2}. - -terminate(_Reason, _StateName, _State) -> - ok. - -code_change(_OldVsn, StateName, State, _Extra) -> - {ok, StateName, State}. - diff --git a/_build/emqx/lib/ekka/src/ekka_ring.erl b/_build/emqx/lib/ekka/src/ekka_ring.erl deleted file mode 100644 index 0552d7b599..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_ring.erl +++ /dev/null @@ -1,92 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_ring). - --include("ekka.hrl"). - --export([ find_node/2 - , find_nodes/2 - , find_nodes/3 - ]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --type(key() :: term()). --type(ring() :: list(member())). - --export_type([key/0, ring/0]). - --define(BASE, 4294967295). %% trunc(math:pow(2, 32) - 1)) - --spec(find_node(key(), ring()) -> node()). -find_node(Key, Ring) -> - (next_member(phash(Key), Ring))#member.node. - -next_member(Hash, Ring = [Head|_]) -> - next_member(Hash, Head, Ring). - -next_member(_Hash, Head, []) -> - Head; -next_member(Hash, _Head, [M = #member{hash = MHash}|_]) - when MHash >= Hash -> - M; -next_member(Hash, Head, [_|Ring]) -> - next_member(Hash, Head, Ring). - --spec(find_nodes(key(), ring()) -> list(node())). -find_nodes(Key, Ring) -> - Count = min(quorum(Ring), length(Ring)), - find_nodes(Key, Count, Ring). - --spec(find_nodes(key(), pos_integer(), ring()) -> list(node())). -find_nodes(Key, Count, Ring) -> - [N || #member{node = N} <- next_members(phash(Key), Count, Ring)]. - -next_members(_Hash, Count, Ring) when Count >= length(Ring) -> - Ring; -next_members(Hash, Count, Ring) -> - {Left, Right} = split_ring(Hash, Ring), - case length(Right) >= Count of - true -> - lists:sublist(Right, 1, Count); - false -> - lists:append(Right, lists:sublist(Left, 1, Count - length(Right))) - end. - -split_ring(Hash, Ring) -> - split_ring(Hash, Ring, [], []). - -split_ring(_Hash, [], Left, Right) -> - {lists:reverse(Left), lists:reverse(Right)}; - -split_ring(Hash, [M = #member{hash = MHash}|Ring], Left, Right) -> - case Hash =< MHash of - true -> split_ring(Hash, Ring, Left, [M|Right]); - false -> split_ring(Hash, Ring, [M|Left], Right) - end. - -quorum(Ring) -> - case length(Ring) div 2 + 1 of - N when N > 3 -> 3; - N -> N - end. - -phash(Key) -> erlang:phash2(Key, ?BASE). - diff --git a/_build/emqx/lib/ekka/src/ekka_sup.erl b/_build/emqx/lib/ekka/src/ekka_sup.erl deleted file mode 100644 index bb2e952330..0000000000 --- a/_build/emqx/lib/ekka/src/ekka_sup.erl +++ /dev/null @@ -1,51 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2019 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(ekka_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -init([]) -> - {ok, {{one_for_all, 0, 3600}, - [child(ekka_cluster_sup, supervisor), - child(ekka_membership, worker), - child(ekka_node_monitor, worker), - child(ekka_locker_sup, supervisor) - ]}}. - -child(Mod, worker) -> - #{id => Mod, - start => {Mod, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [Mod]}; - -child(Mod, supervisor) -> - #{id => Mod, - start => {Mod, start_link, []}, - restart => permanent, - shutdown => infinity, - type => supervisor, - modules => [Mod]}. - diff --git a/_build/emqx/lib/emqtt/.github/workflows/build_packages.yaml b/_build/emqx/lib/emqtt/.github/workflows/build_packages.yaml deleted file mode 100644 index 30e02adca7..0000000000 --- a/_build/emqx/lib/emqtt/.github/workflows/build_packages.yaml +++ /dev/null @@ -1,139 +0,0 @@ -name: Build packages - -on: - push: - pull_request: - release: - types: - - published - - prereleased - -jobs: - - build: - runs-on: ubuntu-latest - - strategy: - matrix: - os: - - ubuntu18.04 - - ubuntu16.04 - - ubuntu14.04 - - debian10 - - debian9 - - debian8 - - opensuse - - centos7 - - centos6 - - steps: - - uses: actions/checkout@v1 - - name: build emqx packages - env: - ERL_OTP: erl22.1 - SYSTEM: ${{ matrix.os }} - run: | - docker run -i --name emqtt-$SYSTEM-build -v $(pwd):/emqtt emqx/build-env:$ERL_OTP-$SYSTEM /bin/bash -c "cd /emqtt && .github/workflows/script/build.sh" - cd _packages && for var in $(ls); do sudo bash -c "echo $(sha256sum $var | awk '{print $1}') > $var.sha256"; done && cd - - - uses: actions/upload-artifact@v1 - with: - name: packages-${{ matrix.os }} - path: _packages/. - - build-on-mac: - runs-on: macos-latest - - steps: - - uses: actions/checkout@v1 - - name: prepare - run: | - /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" - brew install curl zip unzip gnu-sed erlang - echo "/usr/local/bin:$PATH" >> ~/.bashrc - - name: install rebar3 - run: | - curl -Lo /usr/local/bin/rebar3 https://s3.amazonaws.com/rebar3/rebar3 - chmod +x /usr/local/bin/rebar3 - - name: build - run: | - .github/workflows/script/build.sh - pkg=emqtt-macos-$(git describe --tags --always).zip - openssl dgst -sha256 _packages/$pkg | awk '{print $2}' > _packages/$pkg.sha256 - - uses: actions/upload-artifact@v1 - with: - name: packages-mac - path: _packages/. - - release: - runs-on: ubuntu-latest - - needs: [build, build-on-mac] - - steps: - - uses: actions/checkout@v2 - - uses: actions/download-artifact@v1 - with: - name: packages-ubuntu18.04 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-ubuntu16.04 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-ubuntu14.04 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-debian10 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-debian9 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-debian8 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-opensuse - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-centos7 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-centos6 - path: _packages - - uses: actions/download-artifact@v1 - with: - name: packages-mac - path: _packages - - name: set aws - run: | - curl "https://d1vvhvl2y92vvt.cloudfront.net/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" - unzip awscliv2.zip - sudo ./aws/install - aws2 configure set aws_access_key_id ${{ secrets.AwsAccessKeyId }} - aws2 configure set aws_secret_access_key ${{ secrets.AwsSecretAccessKey }} - aws2 configure set default.region us-west-2 - - name: get packages - run: | - cd _packages && for var in $( ls |grep emqtt |grep -v sha256); do - echo "$(cat $var.sha256) $var" | sha256sum -c || exit 1 - done - - name: upload aws - if: github.event_name == 'release' - run: | - version=$(echo ${{ github.ref }} | sed -r "s .*/.*/(.*) \1 g") - aws2 s3 cp --recursive ./_packages s3://packages.emqx.io/emqtt/$version - aws2 cloudfront create-invalidation --distribution-id E3TYD0WSP4S14P --paths "/emqtt/$version/*" - - name: upload github - if: github.event_name == 'release' - run: | - version=$(echo ${{ github.ref }} | sed -r "s .*/.*/(.*) \1 g") - for var in $(ls _packages) ; do - .github/workflows/script/upload_github_release_asset.sh owner=emqx repo=emqtt tag=$version filename=_packages/$var github_api_token=$(echo ${{ secrets.AccessToken }}) - done diff --git a/_build/emqx/lib/emqtt/.github/workflows/run_test_case.yaml b/_build/emqx/lib/emqtt/.github/workflows/run_test_case.yaml deleted file mode 100644 index 0cf157aa44..0000000000 --- a/_build/emqx/lib/emqtt/.github/workflows/run_test_case.yaml +++ /dev/null @@ -1,35 +0,0 @@ -name: Run test case - -on: - push: - pull_request: - release: - types: - - published - - prereleased - -jobs: - - run_test_case: - - runs-on: ubuntu-latest - - container: - image: erlang:22.1 - - steps: - - uses: actions/checkout@v1 - - name: Run tests - run: | - make eunit - make ct - make cover - - uses: actions/upload-artifact@v1 - if: always() - with: - name: logs - path: _build/test/logs - - uses: actions/upload-artifact@v1 - with: - name: cover - path: _build/test/cover \ No newline at end of file diff --git a/_build/emqx/lib/emqtt/.github/workflows/script/build.sh b/_build/emqx/lib/emqtt/.github/workflows/script/build.sh deleted file mode 100644 index bc759e4267..0000000000 --- a/_build/emqx/lib/emqtt/.github/workflows/script/build.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/sh -set -ex - -export PACKAGE_PATH="_packages" - -build_pkg(){ - if [ $(uname) = Linux ]; then - make pkg - elif [ $(uname) = Darwin ]; then - pkg=emqtt-macos-$(git describe --tags --always).zip - make emqtt - mkdir -p $PACKAGE_PATH - - cd _build/emqtt/rel && zip -rq $pkg emqtt && cd - - mv _build/emqtt/rel/$pkg $PACKAGE_PATH - fi -} - -test_pkg(){ - for var in $(ls $PACKAGE_PATH/emqtt-*);do - case ${var##*.} in - "zip") - unzip -q $var - ./emqtt/bin/emqtt pub -t 'hello' --payload 'hello world' -h broker.emqx.io - rm -rf emqtt - ;; - "deb") - dpkg -i $var - if [ $(dpkg -l |grep emqtt |awk '{print $1}') != 'ii' ];then - echo 'package install error' && exit 1 - fi - emqtt pub -t 'hello' --payload 'hello world' -h broker.emqx.io - dpkg -r emqtt - if [ $(dpkg -l |grep emqtt |awk '{print $1}') != 'rc' ];then - echo 'package remove error' && exit 1 - fi - dpkg -P emqtt - if [ ! -z $(dpkg -l |grep emqtt) ];then - echo 'package uninstall error' && exit 1 - fi - ;; - "rpm") - rpm -ivh $var - emqtt pub -t 'hello' --payload 'hello world' -h broker.emqx.io - rpm -e emqtt - ;; - esac - done -} - -build_pkg -test_pkg \ No newline at end of file diff --git a/_build/emqx/lib/emqtt/.github/workflows/script/upload_github_release_asset.sh b/_build/emqx/lib/emqtt/.github/workflows/script/upload_github_release_asset.sh deleted file mode 100644 index 206e3cd6f7..0000000000 --- a/_build/emqx/lib/emqtt/.github/workflows/script/upload_github_release_asset.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bash -# -# Author: Stefan Buck -# License: MIT -# https://gist.github.com/stefanbuck/ce788fee19ab6eb0b4447a85fc99f447 -# -# -# This script accepts the following parameters: -# -# * owner -# * repo -# * tag -# * filename -# * github_api_token -# -# Script to upload a release asset using the GitHub API v3. -# -# Example: -# -# upload-github-release-asset.sh github_api_token=TOKEN owner=stefanbuck repo=playground tag=v0.1.0 filename=./build.zip -# - -# Check dependencies. -set -e -xargs=$(which gxargs || which xargs) - -# Validate settings. -[ "$TRACE" ] && set -x - -CONFIG=$@ - -for line in $CONFIG; do - eval "$line" -done - -# Define variables. -GH_API="https://api.github.com" -GH_REPO="$GH_API/repos/$owner/$repo" -GH_TAGS="$GH_REPO/releases/tags/$tag" -AUTH="Authorization: token $github_api_token" -WGET_ARGS="--content-disposition --auth-no-challenge --no-cookie" -CURL_ARGS="-LJO#" - -if [[ "$tag" == 'LATEST' ]]; then - GH_TAGS="$GH_REPO/releases/latest" -fi - -# Validate token. -curl -o /dev/null -sH "$AUTH" $GH_REPO || { echo "Error: Invalid repo, token or network issue!"; exit 1; } - -# Read asset tags. -response=$(curl -sH "$AUTH" $GH_TAGS) - -# Get ID of the asset based on given filename. -eval $(echo "$response" | grep -m 1 "id.:" | grep -w id | tr : = | tr -cd '[[:alnum:]]=') -[ "$id" ] || { echo "Error: Failed to get release id for tag: $tag"; echo "$response" | awk 'length($0)<100' >&2; exit 1; } - -# Upload asset -echo "Uploading asset... " - -# Construct url -GH_ASSET="https://uploads.github.com/repos/$owner/$repo/releases/$id/assets?name=$(basename $filename)" - -curl "$GITHUB_OAUTH_BASIC" --data-binary @"$filename" -H "Authorization: token $github_api_token" -H "Content-Type: application/octet-stream" $GH_ASSET diff --git a/_build/emqx/lib/emqtt/.gitignore b/_build/emqx/lib/emqtt/.gitignore deleted file mode 100644 index 9f96629a7b..0000000000 --- a/_build/emqx/lib/emqtt/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -.eunit -deps -*.o -*.beam -*.plt -erl_crash.dump -ebin -rel/example_project -.concrete/DEV_MODE -.rebar -.idea -.idea/ -test/ct.cover.spec -ct.coverdata -eunit.coverdata -logs/ -cover/ -.DS_Store -_build/ -_packages/ -rebar3.crashdump -*.swp -rebar.lock -emqtt.app.src -emqtt_cli \ No newline at end of file diff --git a/_build/emqx/lib/emqtt/.rebar3/rebar_compiler_erl/source.dag b/_build/emqx/lib/emqtt/.rebar3/rebar_compiler_erl/source.dag deleted file mode 100644 index 23dadafbf1..0000000000 Binary files a/_build/emqx/lib/emqtt/.rebar3/rebar_compiler_erl/source.dag and /dev/null differ diff --git a/_build/emqx/lib/emqtt/.travis.yml b/_build/emqx/lib/emqtt/.travis.yml deleted file mode 100644 index e2a3233d63..0000000000 --- a/_build/emqx/lib/emqtt/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: erlang - -sudo: false - -otp_release: - - 21.3 - - 22.0 - -script: - - make diff --git a/_build/emqx/lib/emqtt/LICENSE b/_build/emqx/lib/emqtt/LICENSE deleted file mode 100644 index 051827022c..0000000000 --- a/_build/emqx/lib/emqtt/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2019, Anonymous . - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/_build/emqx/lib/emqtt/Makefile b/_build/emqx/lib/emqtt/Makefile deleted file mode 100644 index c3f0c8939e..0000000000 --- a/_build/emqx/lib/emqtt/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -.PHONY: all compile unlock clean distclean xref eunit ct dialyzer - -CT_NODE_NAME = ct@127.0.0.1 - -REBAR := rebar3 - -all: emqtt - -emqtt: compile - $(REBAR) as emqtt release - -pkg: compile - $(REBAR) as emqtt_pkg release - make -C packages - -compile: escript - $(REBAR) compile - -unlock: - $(REBAR) unlock - -clean: distclean - -distclean: - @rm -rf _build _packages erl_crash.dump rebar3.crashdump rebar.lock emqtt_cli - -xref: - $(REBAR) xref - -eunit: compile - $(REBAR) eunit verbose=true - -ct: compile - $(REBAR) as test ct -v --name $(CT_NODE_NAME) - -cover: - $(REBAR) cover - -dialyzer: - $(REBAR) dialyzer - -escript: - $(REBAR) as escript escriptize - diff --git a/_build/emqx/lib/emqtt/README.md b/_build/emqx/lib/emqtt/README.md deleted file mode 100644 index a2d9e3144b..0000000000 --- a/_build/emqx/lib/emqtt/README.md +++ /dev/null @@ -1,837 +0,0 @@ -# emqtt - -MQTT client library and command line tools implemented in Erlang that supports MQTT v5.0/3.1.1/3.1. - -# Getting started - -## As a Command Line Tool - -### Build - -``` -$ make -``` - -Once you've compiled successfully you will get a script called `emqtt` in `_buile/emqtt/rel/emqtt/bin`. We can see what `emqtt` can do with `--help` option: - -``` -$ ./emqtt --help -Usage: emqtt pub | sub [--help] -``` - -`emqtt pub` is used to publish a single message on a topic and exit. `emqtt sub` is used to subscribe to a topic and print the messages that it receives. - -### Command-line Syntax - -Options can have both short (single character) and long (string) option names. - -A short option can have the following syntax: - -``` --e arg Single option 'e', argument "arg" -``` - -A long option can have the following syntax: - -``` ---example=arg Single option 'example', argument "arg" ---example arg Single option 'example', argument "arg" -``` - -### Publish - -#### Synopsis - -``` -./emqtt pub [-h []] [-p ] [-I ] - [-V []] [-u ] - [-P ] [-C ] [-k []] - [-t ] [-q []] [-r []] - [--help ] [--will-topic ] - [--will-payload ] - [--will-qos []] - [--will-retain []] - [--enable-websocket []] - [--enable-ssl []] - [--tls-version []] - [--CAfile ] [--cert ] - [--key ] [--payload ] - [--repeat []] - [--repeat-delay []] -``` - -#### Options - -**`-h, --host`** - -  Specify the host to connect to, support for domain name and IP address. Defaults to localhost. - -**`-p, --port`** - -  Specify the port to connect to. If not given, the default of 1883 for MQTT or 8883 for MQTT over TLS will be used. - -**`-I, --iface`** - -  Specify the network interface or ip address to use. - -**`-V, --protocol-version`** - -  Specify the MQTT protocol version used by the client. Can be `v3.1`, `v3.1.1` and `v5`. Defaults to `v5`. - -**`-u, --username`** - -  Specify the username that can be used by the broker for authentication and authorization. - -**`-P, --password`** - -  Specify the password for the username. - -**`-C, --clientid`** - -  Specify the client identifier. If not given, the client identifier in the format `emqtt--` will be automatically generated by `emqtt_cli`. - -**`-k, --keepalive`** - -  Specify the interval in seconds sending PINGREQ packets to the broker. Defaults to 300 seconds. - -**`-t, --topic`** - -  Specify the MQTT topic you want to publish. If the topic beginning with $, you must use single quote(`'`) to specify the topic rather than double quotes(`"`). This is a required option. - -**`-q, --qos`** - -  Specify the quality of service for the message. Can be 0, 1 and 2. Defaults to 0. - -**`-r, --retain`** - -  Specify whether the message is a retained message. Defaults to false. - -**`--payload`** - -  Specify the application message is to be published. This is a required option. - -**`--repeat`** - -  Specify the number of times the message will be repeatedly published. Defaults to 1. - -**`--repeat-count`** - -  Specify the number of seconds to wait after the previous message was delivered before publishing the next. Defaults to 0, it means to publish repeated messages as soon as the previous message is sent. - -**`--will-topic`** - -  Specify the topic of the will message sent when the client disconnects unexpectedly. - -**`--will-qos`** - -  Specify the quality of service of the will message. Defaults to 0. This must be used in conjunction with `--will-topic`. - -**`--will-retain`** - -  Specify whether the will message is a retained message. Defaults to false. This must be used in conjunction with `--will-topic`. - -**`--will-payload`** - -  Specify the application message that will be stored by the broker and sent out if this client disconnects unexpectedly. This must be used in conjunction with `--will-topic`. - -**`--enable-websocket`** - -  Specify enable WebSocket transport or not. This option can't be used with `--enable-ssl` currently. - -**`--enable-ssl`** - -  Specify enable SSL/TLS transport or not. This option can't be used with `--enable-websocket` currently. - -**`--tls-version`** - -  Specify which TLS protocol version to use when communicating with the broker. Valid options are tlsv1.3, tlsv1.2, tlsv1.1 and tlsv1. Defaults to tlsv1.2. - -**`--CAfile`** - -  Specify the path to a file containing PEM encoded CA certificates. This must be used in conjunction with `--enable-ssl`. - -**`--cert`** - -  Specify the path to a file containing a PEM encoded certificate for this client, if required by the server. This must be used in conjunction with `--enable-ssl`. - -**`--key`** - -  Specify the path to a file containing a PEM encoded private key for this client, if required by the server. This must be used in conjunction with `--enable-ssl`. - -#### Examples - -**Publish a simple message over a TCP connection** - -``` -$ ./emqtt pub -t "hello" --payload "hello world" -Client emqtt-zhouzibodeMacBook-Pro-4623faa14d8256e9cb95 sent CONNECT -Client emqtt-zhouzibodeMacBook-Pro-4623faa14d8256e9cb95 sent PUBLISH (Q0, R0, D0, Topic=hello, Payload=...(11 bytes)) -Client emqtt-zhouzibodeMacBook-Pro-4623faa14d8256e9cb95 sent DISCONNECT -``` - -**Publish a simple message over a TLS connection** - -``` -$ ./emqtt pub --enable-ssl=true -t "hello" --payload "hello world" --CAfile=certs/cacert.pem --cert=certs/client-cert.pem --key=certs/client-key.pem -Client emqtt-zhouzibodeMacBook-Pro-cec9489c26e3ed7a38eb sent CONNECT -Client emqtt-zhouzibodeMacBook-Pro-cec9489c26e3ed7a38eb sent PUBLISH (Q0, R0, D0, Topic=hello, Payload=...(11 bytes)) -Client emqtt-zhouzibodeMacBook-Pro-cec9489c26e3ed7a38eb sent DISCONNECT -``` - -**Publish a message repeatedly over a WebSocket connection** - -``` -$ ./emqtt pub --enable-websocket=true -p 8083 -t "hello" --payload "hello world" -Client emqtt-zhouzibodeMacBook-Pro-1e4677ab46cecf1298ac sent CONNECT -Client emqtt-zhouzibodeMacBook-Pro-1e4677ab46cecf1298ac sent PUBLISH (Q0, R0, D0, Topic=hello, Payload=...(11 bytes)) -Client emqtt-zhouzibodeMacBook-Pro-1e4677ab46cecf1298ac sent DISCONNECT -``` - -### Subscribe - -#### Synopsis - -``` -./emqtt sub [-h []] [-p ] [-I ] - [-V []] [-u ] - [-P ] [-C ] [-k []] - [-t ] [-q []] [--help ] - [--will-topic ] - [--will-payload ] - [--will-qos []] - [--will-retain []] - [--enable-websocket []] - [--enable-ssl []] - [--tls-version []] - [--CAfile ] [--cert ] - [--key ] - [--retain-as-publish []] - [--retain-handling []] -``` - -#### Options - -**`-h, --host`** - -  See also [--host](#host). - -**`-p, --port`** - -  See also [--port](#port). - -**`-I, --iface`** - -  See also [--iface](#iface). - -**`-V, --protocol-version`** - -  See also [--protocol-version](#protocol-version). - -**`-u, --username`** - -  See also [--username](#username). - -**`-P, --password`** - -  See also [--password](#password). - -**`-C, --clientid`** - -  See also [--clientid](#clientid). - -**`-k, --keepalive`** - -  See also [--keepalive](#keepalive). - -**`-t, --topic`** - -  Specify the MQTT topic you want to subscribe to. This is a required option. - -**`-q, --qos`** - -  Specify the maximum qos level at which the broker can send application messages to the client. Defaults to 0. - -**`--retain-as-publish`** - -  Specify the Retain As Publish option in subscription options. Defaults to 0. - -**`--retain-handling`** - -  Specify the Retain Handling option in subscription options. Defaults to 0. - -**`--will-topic`** - -  See also [--will-topic](#will-topic). - -**`--will-qos`** - -  See also [--will-qos](#will-qos). - -**`--will-retain`** - -  See also [--will-retain](#will-retain). - -**`--will-payload`** - -  See also [--will-payload](#will-payload). - -**`--enable-websocket`** - -  See also [--enable-websocket](#enable-websocket). - -**`--enable-ssl`** - -  See also [--enable-ssl](#enable-ssl). - -**`--tls-version`** - -  See also [--tls-version](#tls-version). - -**`--CAfile`** - -  See also [--CAfile](#CAfile). - -**`--cert`** - -  See also [--cert](#cert). - -**`--key`** - -  See also [--key](#key). - -#### Examples - -**Build Non-shared Subscription and Recv "hello world"** - -``` -$ ./emqtt sub -t "hello" -Client emqtt-zhouzibodeMacBook-Pro-1686fee6fdb99f674f2c sent CONNECT -Client emqtt-zhouzibodeMacBook-Pro-1686fee6fdb99f674f2c subscribed to hello -hello world -``` - -**Build Shared Subscription and Recv "hello world"** - -``` -$ ./emqtt sub -t '$share/group/hello' -Client emqtt-zhouzibodeMacBook-Pro-288e65bb3f4013d30249 sent CONNECT -Client emqtt-zhouzibodeMacBook-Pro-288e65bb3f4013d30249 subscribed to $share/group/hello -hello world -``` ----- - -## As a Dependency Library - -### Add to rebar3 project - -Add to `rebar.config` - -```erlang -... -{deps, [{emqtt, {git, "https://hub.fastgit.org/emqx/emqtt", {tag, "v1.2.0"}}}]}. -... -``` - -### Build - -``` -$ rebar3 compile -``` - -### Data Types - -**option()** - -``` -option() = {name, atom()} | - {owner, pid()} | - {host, host()} | - {port, inet:port_number()} | - {tcp_opts, [gen_tcp:option()]} | - {ssl, boolean()} | - {ssl_opts, [ssl:ssl_option()]} | - {ws_path, string()} | - {connect_timeout, pos_integer()} | - {bridge_mode, boolean()} | - {clientid, iodata()} | - {clean_start, boolean()} | - {username, iodata()} | - {password, iodata()} | - {proto_ver, v3 | v4 | v5} | - {keepalive, non_neg_integer()} | - {max_inflight, pos_integer()} | - {retry_interval, pos_integer()} | - {will_topic, iodata()} | - {will_payload, iodate()} | - {will_retain, boolean()} | - {will_qos, qos()} | - {will_props, properties()} | - {auto_ack, boolean()} | - {ack_timeout, pos_integer()} | - {force_ping, boolean()} | - {properties, properties()} -``` - -**client()** - -``` -client() = pid() | atom() -``` - -**host()** - -``` -host() = inet:ip_address() | inet:hostname() -``` - -**properties()** - -``` -properties() = #{'Payload-Format-Indicator' => 0..1, - 'Message-Expiry-Interval' => 0..16#FFFFFFFF, - 'Content-Type' => binary(), - 'Response-Topic' => binary(), - 'Correlation-Data' => binary(), - 'Subscription-Identifier' => 0..16#7FFFFFFF, - 'Session-Expiry-Interval' => 0..16#FFFFFFFF, - 'Assigned-Client-Identifier' => binary(), - 'Server-Keep-Alive' => 0..16#FFFF, - 'Authentication-Method' => binary(), - 'Authentication-Data' => binary(), - 'Request-Problem-Information' => 0..1, - 'Will-Delay-Interval' => 0..16#FFFFFFFF, - 'Request-Response-Information' => 0..1, - 'Response-Information' => binary(), - 'Server-Reference' => binary(), - 'Reason-String' => binary(), - 'Receive-Maximum' => 1..16#FFFF, - 'Topic-Alias-Maximum' => 0..16#FFFF, - 'Topic-Alias' => 1..16#FFFF, - 'Maximum-QoS' => 0..1, - 'Retain-Available' => 0..1, - 'User-Property' => [{binary(), binary()}], - 'Maximum-Packet-Size' => 1..16#FFFFFFFF, - 'Wildcard-Subscription-Available' => 0..1, - 'Subscription-Identifier-Available' => 0..1, - 'Shared-Subscription-Available' => 0..1} -``` - -**qos()** - -``` -qos() = 0 | 1 | 2 -``` - -**qos_name()** - -``` -qos_name() = qos0 | at_most_once | - qos1 | at_least_once | - qos2 | exactly_once -``` - -**topic()** - -``` -topic() = binary() -``` - -**payload()** - -``` -payload() = iodata() -``` - -**packet_id()** - -``` -packet_id() = 0..16#FFFF -``` - -**subopt()** - -``` -subopt() = {rh, 0 | 1 | 2} | - {rap, boolean()} | - {nl, boolean()} | - {qos, qos() | qos_name()} -``` - -**pubopt()** - -``` -pubopt() = {retain, boolean()} | - {qos, qos() | qos_name()} -``` - -**reason_code()** - -``` -reason_code() = 0..16#FF -``` - -### Exports - -**emqtt:start_link() -> {ok, Pid} | ignore | {error, Reason}** - -**emqtt:start_link(Options) -> {ok, Pid} | ignore | {error, Reason}** - -  **Types** - -    **Pid = pid()** - -    **Reason = term()** - -    **Options = [[option()](#option)]** - -Start MQTT client process with specified options. `Options` will be used in connecting and running. - -The following options are available: - -`{name, Name}` - -If a name is provided, the gen_statem will be registered with this name. For details see the documentation for the first argument of `gen_statem:start_link/4`. - -`{owner, Pid}` - -Client process will send messages like `{diconnected, ReasonCode, Properties}` to the owner process. - -`{host, Host}` - -The host of the MQTT server to be connected. Host can be a hostname or an IP address. Defaults to `localhost` - -`{port, Port}` - -The port of the MQTT server to be connected. If not given, the default of 1883 for MQTT or 8883 for MQTT over TLS will be used. - -`{tcp_opts, Options}` - -Additional options for `gen_tcp:connect/3`. - -`{ssl, boolean()}` - -Enable SSL/TLS transport or not. Defaults to false. - -`{ssl_opts, Options}` - -Additional options for `ssl:connect/3`. - -`{ws_path, Path}` - -Path to the resource. Defaults to `/mqtt` - -`{connect_timeout, Timeout}` - -The maximum time to wait to connect to the server and the server returns a CONNACK. Defaults to 60s. - -`{bridge_mode, boolean()}` - -Enable bridge mode or not. Defaults to false. - -`{clientid, ClientID}` - -Specify the client identifier. If not given, the client identifier will use the value assigned by the server in MQTT v5 or be automatically generated by internal code in MQTT v3.1/v3.1.1. - -`{clean_start, CleanStart}` - -Whether the server should discard any existing session and start a new session. Defaults to true. - -`{username, Username}` - -Username used by the server for authentication and authorization. - -`{password, Password}` - -Password used by the server for authentication and authorization. - -`{proto_ver, ProtocolVersion}` - -MQTT protocol version. Defaults to `v4`. - -`{keepalive, Keepalive}` - -Maximum time interval that is permitted to elapse between the point at which the Client finishes transmitting one MQTT Control Packet and the point it starts sending the next. It will be replaced by server keep alive returned from MQTT server. - -`{max_inflight, MaxInflight}` - -Max number of QoS 1 and QoS 2 packets in flight. In other words, the number of packets that were sent but not yet acked. Defaults to `infinity`, means no limit. - -`{retry_interval, RetryInterval}` - -Interval to retry sending packets that have been sent but not received a response. Defaults to 30s. - -`{will_topic, WillTopic}` - -Topic of will message. - -`{will_payload, WillPayload}` - -Payload of will message. - -`{will_retain, WillRetain}` - -Whether the server should publish the will message as a retained message. Defaults to false. - -`{will_qos, WillQoS}` - -QoS of will message. Defaults to 0. - -`{will_props, WillProperties}` - -Properties of will message. - -`{auto_ack, boolean()}` - -If true (the default), cliean process will automatically send ack packet like PUBACK when it receives a packet from the server. If false, application decides what to do. - -`{ack_timeout, AckTimeout}` - -Maximum time to wait for a reply message. Defaults to 30s. - -`{force_ping, boolean()}` - -If false (the default), if any other packet is sent during keep alive interval, the ping packet will not be sent this time. If true, the ping packet will be sent every time. - -`{properties, Properties}` - -Properties of CONNECT packet. - -**emqtt:connect(Client) -> {ok, Properties} | {error, Reason}** - -  **Types** - -    **Client = [client()](#client)** - -    **Properties = [properties()](#properties)** - -    **Reason = timeout | inet:posix() | any()** - -Connect to the MQTT server over TCP or TLS and send a `CONNECT` packet with the options specified in `start_link/1, 2`. `Client` must be a pid returned from `start_link/1, 2` or a name specified in `start_link/1, 2`. - -Returns: - -- `{ok, Properties}` if a MQTT connection is established. `Properties` is propterties in CONNACK packet returned from MQTT server. - -- `{error, timeout}` if connection can't be established within the specified time - -- `{error, inet:posix()}` A POSIX error value if something else goes wrong. - -**emqtt:ws_connect(Client) -> {ok, Properties} | {error, Reason}** - -  **Types** - -    Same as `emqtt:connect/1` - -Connect to the MQTT server over Websocket and send a `CONNECT` packet with the options specified in `start_link/1, 2`. `Client` must be a pid returned from `start_link/1, 2` or a name specified in `start_link/1, 2`. - -**emqtt:disconnect(Client) -> ok | {error, Reason}** - -**emqtt:disconnect(Client, ReasonCode) -> ok | {error, Reason}** - -**emqtt:disconnect(Client, ReasonCode, Properties) -> ok | {error, Reason}** - -  **Types** - -    **Client = [client()](#client)** - -    **ReasonCode = [reason_code()](#reasoncode)** - -    **Properties = [properties()](#properties)** - -    **Reason = closed | inet:posix()** - -Send a `DISCONNECT` packet to the MQTT server. `ReasonCode` specifies a MQTT reason code for `DISCONNECT` packet, defaults to 0 meaning normal disconnection. `Properties` specifies properties for `DISCONNECT` packet, defaults to `#{}` meaning no properties are attached. - -**emqtt:ping(Client) -> pong | {error, Reason}** - -  **Types** - -    **Client = [client()](#client)** - -    **Reason = ack_timeout** - -Send a `PINGREQ` packet to the MQTT server. If `PINGRESP` packet is received from the server within the timeout period, `pong` is returned. If not, `{error, ack_timeout}` is returned. - -**emqtt:subscribe(Client, Properties, Subscriptions) -> {ok, Properties, ReasonCodes} | {error, Reason})** - -  **Types** - -    **Client = [client()](#client)** - -    **Properties = [properties()](#properties)** - -    **Subscriptions = [{[topic()](#topic), [[subopt()](#subopt)]}]** - -    **ReasonCodes = [[reason_code()](#reasoncode)]** - -    **Reason = term()** - -Send a `SUBSCRIBE` packet to the MQTT server. `Properties` specifies properties for `SUBSCRIBE` packet, defaults to `#{}` meaning no properties are attached. `Subscriptions` specifies pairs of topic filter and subscription options. The topic filter is requried, the subscription options can be `[]`, equivalent to `[{rh, 0}, {rap, 0}, {nl, 0}, {qos, 0}]`. - -**emqtt:unsubscribe(Client, Properties, Topics) -> {ok, Properties, ReasonCodes} | {error, Reason})** - -  **Types** - -    **Client = [client()](#client)** - -    **Properties = [properties()](#properties)** - -    **Topics = [[topic()](#topic)]** - -    **ReasonCodes = [[reason_code()](#reasoncode)]** - -    **Reason = term()** - -Send a `UNSUBSCRIBE` packet to the MQTT server. `Properties` specifies properties for `SUBSCRIBE` packet, defaults to `#{}` meaning no properties are attached. `Topics` specifies a list of topic filter with at least one topic filter. - -**emqtt:publish(Client, Topic, Properties, Payload, PubOpts) -> ok | {ok, PacketId} | {error, Reason})** - -  **Types** - -    **Client = [client()](#client)** - -    **Topic = [topic()](#topic)** - -    **Properties = [properties()](#properties)** - -    **Payload = [payload()](#payload)** - -    **PubOpts = [[pubopt()](#pubopt)]** - -    **PacketId = [packet_id()](#packetid)** - -    **Reason = term()** - -Send a `PUBLISH` packet to the MQTT server. `Topic`, `Properties` and `Payload` specify topic, properties and payload for `PUBLISH` packet. `PubOpts` specifies qos and retain flag for `PUBLISH` packet, defaults to `[]`, equivalent to `[{qos, 0}, {retain, false}]`. - -Returns: - -- `ok` Ii a QoS 0 packet is sent. - -- `{ok, PacketId}` if a QoS 1/2 packet is sent, the packet identifier will be returned. - -- `{error, Reason}` if something goes wrong. - -**emqtt:puback(Client, PacketId) -> ok** - -**emqtt:puback(Client, PacketId, ReasonCode) -> ok** - -**emqtt:puback(Client, PacketId, ReasonCode, Properties) -> ok** - -  **Types** - -    **Client = [client()](#client)** - -    **PacketId = [packet_id()](#packetid)** - -    **ReasonCode = [reason_code()](#reasoncode)** - -    **Properties = [properties()](#properties)** - -Send a `PUBACK` packet to the MQTT server. `PacketId`, `ReasonCode` and `Properties` specify packet identifier, reason code and properties for `PUBACK` packet. - -**emqtt:pubrec(Client, PacketId) -> ok** - -**emqtt:pubrec(Client, PacketId, ReasonCode) -> ok** - -**emqtt:pubrec(Client, PacketId, ReasonCode, Properties) -> ok** - -  **Types** - -    Same as `emqtt:puback/2, 3, 4`. - -Send a `PUBREC` packet to the MQTT server. `PacketId`, `ReasonCode` and `Properties` specify packet identifier, reason code and properties for `PUBREC` packet. - -**emqtt:pubrel(Client, PacketId) -> ok** - -**emqtt:pubrel(Client, PacketId, ReasonCode) -> ok** - -**emqtt:pubrel(Client, PacketId, ReasonCode, Properties) -> ok** - -  **Types** - -    Same as `emqtt:puback/2, 3, 4`. - -Send a `PUBREL` packet to the MQTT server. `PacketId`, `ReasonCode` and `Properties` specify packet identifier, reason code and properties for `PUBREL` packet. - -**emqtt:pubcomp(Client, PacketId) -> ok** - -**emqtt:pubcomp(Client, PacketId, ReasonCode) -> ok** - -**emqtt:pubcomp(Client, PacketId, ReasonCode, Properties) -> ok** - -  **Types** - -    Same as `emqtt:puback/2, 3, 4`. - -Send a `PUBCOMP` packet to the MQTT server. `PacketId`, `ReasonCode` and `Properties` specify packet identifier, reason code and properties for `PUBCOMP` packet. - -**emqtt:subscriptions(Client) -> Subscriptions** - -  **Types** - -    **Client = [client()](#client)** - -    **Subscriptions = [{[topic()](#topic), [[subopt()](#subopt)]}]** - -Return all subscriptions. - -**emqtt:stop(Client) -> ok** - -  **Types** - -    **Client = [client()](#client)** - -Stop a client process. - -**emqtt:pause(Client) -> ok** - -  **Types** - -    **Client = [client()](#client)** - -Pause the client process. The paused client process will ignore all `PUBLISH` packets received and not send `PINGREQ` packet if `force_ping` is set to false. - -**emqtt:resume(Client) -> ok** - -  **Types** - -    **Client = [client()](#client)** - -Resume a client process from a paused state. - -### Examples - -``` -{ok, ConnPid} = emqtt:start_link([{clientid, ClientId}]). -{ok, _Props} = emqtt:connect(ConnPid). - -SubOpts = [{qos, 1}]. -{ok, _Props, _ReasonCodes} = emqtt:subscribe(ConnPid, #{}, [{<<"hello">>, SubOpts}]). - -ok = emqtt:publish(ConnPid, <<"hello">>, #{}, <<"Hello World!">>, [{qos, 0}]). -{ok, _PktId} = emqtt:publish(ConnPid, <<"hello">>, #{}, <<"Hello World!">>, [{qos, 1}]). - -receive - {disconnect, ReasonCode, Properties} -> - io:format("Recv a DISONNECT packet - ReasonCode: ~p, Properties: ~p~n", [ReasonCode, Properties]); - {publish, PUBLISH} -> - io:format("Recv a PUBLISH packet: ~p~n", [PUBLISH]); - {puback, {PacketId, ReasonCode, Properties}} -> - io:format("Recv a PUBACK packet - PacketId: ~p, ReasonCode: ~p, Properties: ~p~n", [PacketId, ReasonCode, Properties]) -end. - -{ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, #{}, <<"hello">]). - -ok = emqtt:disconnect(ConnPid). -ok = emqtt:stop(ConnPid). -``` - -## License - -Apache License Version 2.0 - -## Author - -EMQ X Team. - diff --git a/_build/emqx/lib/emqtt/TODO b/_build/emqx/lib/emqtt/TODO deleted file mode 100644 index f2bad14743..0000000000 --- a/_build/emqx/lib/emqtt/TODO +++ /dev/null @@ -1,31 +0,0 @@ -0. app.src - -Update app.src - -1. Tests - -Sock -Frame -Props - -2. README - -3. Docs - -4. Improve ws support: - #{ connect_timeout => Timeout, - %% http_opts => http_opts(), - %% http2_opts => http2_opts(), - %% protocols => [http | http2], - retry => 3, - retry_timeout => 3000 - %% TODO... - %% supervise => false - %% tcp_opts => [gen_tcp:connect_option()], - %% tls_handshake_timeout => timeout(), - %% tls_opts => [ssl:connect_option()], - %% trace => boolean(), - %% transport => tcp | tls | ssl, - %% ws_opts => ws_opts() - }, - diff --git a/_build/emqx/lib/emqtt/bin/emqtt b/_build/emqx/lib/emqtt/bin/emqtt deleted file mode 100644 index c17d0b91bb..0000000000 --- a/_build/emqx/lib/emqtt/bin/emqtt +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh -set -e - -## constants from relx template -RUNNER_ROOT_DIR="{{ runner_root_dir }}" -RUNNER_BIN_DIR="{{ runner_bin_dir }}" -ERTS_VSN="{{ erts_vsn }}" - -ERTS_PATH=$RUNNER_ROOT_DIR/erts-$ERTS_VSN/bin - -exec ${ERTS_PATH}/escript ${RUNNER_BIN_DIR}/emqtt_cli $@ \ No newline at end of file diff --git a/_build/emqx/lib/emqtt/include/emqtt.hrl b/_build/emqx/lib/emqtt/include/emqtt.hrl deleted file mode 100644 index de835f4d0f..0000000000 --- a/_build/emqx/lib/emqtt/include/emqtt.hrl +++ /dev/null @@ -1,542 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --ifndef(EMQTT_HRL). --define(EMQTT_HRL, true). - -%%-------------------------------------------------------------------- -%% MQTT SockOpts -%%-------------------------------------------------------------------- - --define(MQTT_SOCKOPTS, [binary, {packet, raw}, {reuseaddr, true}, - {backlog, 512}, {nodelay, true}]). - -%%-------------------------------------------------------------------- -%% MQTT Protocol Version and Names -%%-------------------------------------------------------------------- - --define(MQTT_PROTO_V3, 3). --define(MQTT_PROTO_V4, 4). --define(MQTT_PROTO_V5, 5). - --define(PROTOCOL_NAMES, [ - {?MQTT_PROTO_V3, <<"MQIsdp">>}, - {?MQTT_PROTO_V4, <<"MQTT">>}, - {?MQTT_PROTO_V5, <<"MQTT">>}]). - -%%-------------------------------------------------------------------- -%% MQTT QoS Levels -%%-------------------------------------------------------------------- - --define(QOS_0, 0). %% At most once --define(QOS_1, 1). %% At least once --define(QOS_2, 2). %% Exactly once - --define(IS_QOS(I), (I >= ?QOS_0 andalso I =< ?QOS_2)). - --define(QOS_I(Name), - begin - (case Name of - ?QOS_0 -> ?QOS_0; - qos0 -> ?QOS_0; - at_most_once -> ?QOS_0; - ?QOS_1 -> ?QOS_1; - qos1 -> ?QOS_1; - at_least_once -> ?QOS_1; - ?QOS_2 -> ?QOS_2; - qos2 -> ?QOS_2; - exactly_once -> ?QOS_2 - end) - end). - --define(IS_QOS_NAME(I), - (I =:= qos0 orelse I =:= at_most_once orelse - I =:= qos1 orelse I =:= at_least_once orelse - I =:= qos2 orelse I =:= exactly_once)). - -%%-------------------------------------------------------------------- -%% Maximum ClientId Length. -%%-------------------------------------------------------------------- - --define(MAX_CLIENTID_LEN, 65535). - -%%-------------------------------------------------------------------- -%% MQTT Control Packet Types -%%-------------------------------------------------------------------- - --define(RESERVED, 0). %% Reserved --define(CONNECT, 1). %% Client request to connect to Server --define(CONNACK, 2). %% Server to Client: Connect acknowledgment --define(PUBLISH, 3). %% Publish message --define(PUBACK, 4). %% Publish acknowledgment --define(PUBREC, 5). %% Publish received (assured delivery part 1) --define(PUBREL, 6). %% Publish release (assured delivery part 2) --define(PUBCOMP, 7). %% Publish complete (assured delivery part 3) --define(SUBSCRIBE, 8). %% Client subscribe request --define(SUBACK, 9). %% Server Subscribe acknowledgment --define(UNSUBSCRIBE, 10). %% Unsubscribe request --define(UNSUBACK, 11). %% Unsubscribe acknowledgment --define(PINGREQ, 12). %% PING request --define(PINGRESP, 13). %% PING response --define(DISCONNECT, 14). %% Client or Server is disconnecting --define(AUTH, 15). %% Authentication exchange - --define(TYPE_NAMES, [ - 'CONNECT', - 'CONNACK', - 'PUBLISH', - 'PUBACK', - 'PUBREC', - 'PUBREL', - 'PUBCOMP', - 'SUBSCRIBE', - 'SUBACK', - 'UNSUBSCRIBE', - 'UNSUBACK', - 'PINGREQ', - 'PINGRESP', - 'DISCONNECT', - 'AUTH']). - -%%-------------------------------------------------------------------- -%% MQTT V3.1.1 Connect Return Codes -%%-------------------------------------------------------------------- - --define(CONNACK_ACCEPT, 0). %% Connection accepted --define(CONNACK_PROTO_VER, 1). %% Unacceptable protocol version --define(CONNACK_INVALID_ID, 2). %% Client Identifier is correct UTF-8 but not allowed by the Server --define(CONNACK_SERVER, 3). %% Server unavailable --define(CONNACK_CREDENTIALS, 4). %% Username or password is malformed --define(CONNACK_AUTH, 5). %% Client is not authorized to connect - -%%-------------------------------------------------------------------- -%% MQTT V5.0 Reason Codes -%%-------------------------------------------------------------------- - --define(RC_SUCCESS, 16#00). --define(RC_NORMAL_DISCONNECTION, 16#00). --define(RC_GRANTED_QOS_0, 16#00). --define(RC_GRANTED_QOS_1, 16#01). --define(RC_GRANTED_QOS_2, 16#02). --define(RC_DISCONNECT_WITH_WILL_MESSAGE, 16#04). --define(RC_NO_MATCHING_SUBSCRIBERS, 16#10). --define(RC_NO_SUBSCRIPTION_EXISTED, 16#11). --define(RC_CONTINUE_AUTHENTICATION, 16#18). --define(RC_RE_AUTHENTICATE, 16#19). --define(RC_UNSPECIFIED_ERROR, 16#80). --define(RC_MALFORMED_PACKET, 16#81). --define(RC_PROTOCOL_ERROR, 16#82). --define(RC_IMPLEMENTATION_SPECIFIC_ERROR, 16#83). --define(RC_UNSUPPORTED_PROTOCOL_VERSION, 16#84). --define(RC_CLIENT_IDENTIFIER_NOT_VALID, 16#85). --define(RC_BAD_USER_NAME_OR_PASSWORD, 16#86). --define(RC_NOT_AUTHORIZED, 16#87). --define(RC_SERVER_UNAVAILABLE, 16#88). --define(RC_SERVER_BUSY, 16#89). --define(RC_BANNED, 16#8A). --define(RC_SERVER_SHUTTING_DOWN, 16#8B). --define(RC_BAD_AUTHENTICATION_METHOD, 16#8C). --define(RC_KEEP_ALIVE_TIMEOUT, 16#8D). --define(RC_SESSION_TAKEN_OVER, 16#8E). --define(RC_TOPIC_FILTER_INVALID, 16#8F). --define(RC_TOPIC_NAME_INVALID, 16#90). --define(RC_PACKET_IDENTIFIER_IN_USE, 16#91). --define(RC_PACKET_IDENTIFIER_NOT_FOUND, 16#92). --define(RC_RECEIVE_MAXIMUM_EXCEEDED, 16#93). --define(RC_TOPIC_ALIAS_INVALID, 16#94). --define(RC_PACKET_TOO_LARGE, 16#95). --define(RC_MESSAGE_RATE_TOO_HIGH, 16#96). --define(RC_QUOTA_EXCEEDED, 16#97). --define(RC_ADMINISTRATIVE_ACTION, 16#98). --define(RC_PAYLOAD_FORMAT_INVALID, 16#99). --define(RC_RETAIN_NOT_SUPPORTED, 16#9A). --define(RC_QOS_NOT_SUPPORTED, 16#9B). --define(RC_USE_ANOTHER_SERVER, 16#9C). --define(RC_SERVER_MOVED, 16#9D). --define(RC_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED, 16#9E). --define(RC_CONNECTION_RATE_EXCEEDED, 16#9F). --define(RC_MAXIMUM_CONNECT_TIME, 16#A0). --define(RC_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED, 16#A1). --define(RC_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED, 16#A2). - -%%-------------------------------------------------------------------- -%% Maximum MQTT Packet ID and Length -%%-------------------------------------------------------------------- - --define(MAX_PACKET_ID, 16#ffff). --define(MAX_PACKET_SIZE, 16#fffffff). - -%%-------------------------------------------------------------------- -%% MQTT Frame Mask -%%-------------------------------------------------------------------- - --define(HIGHBIT, 2#10000000). --define(LOWBITS, 2#01111111). - -%%-------------------------------------------------------------------- -%% MQTT Packet Fixed Header -%%-------------------------------------------------------------------- - --record(mqtt_packet_header, { - type = ?RESERVED, - dup = false, - qos = ?QOS_0, - retain = false - }). - -%%-------------------------------------------------------------------- -%% MQTT Packets -%%-------------------------------------------------------------------- - --define(DEFAULT_SUBOPTS, #{rh => 0, %% Retain Handling - rap => 0, %% Retain as Publish - nl => 0, %% No Local - qos => 0 %% QoS - }). - --record(mqtt_packet_connect, { - proto_name = <<"MQTT">>, - proto_ver = ?MQTT_PROTO_V4, - is_bridge = false, - clean_start = true, - will_flag = false, - will_qos = ?QOS_0, - will_retain = false, - keepalive = 0, - properties = undefined, - clientid = <<>>, - will_props = undefined, - will_topic = undefined, - will_payload = undefined, - username = undefined, - password = undefined - }). - --record(mqtt_packet_connack, { - ack_flags, - reason_code, - properties - }). - --record(mqtt_packet_publish, { - topic_name, - packet_id, - properties - }). - --record(mqtt_packet_puback, { - packet_id, - reason_code, - properties - }). - --record(mqtt_packet_subscribe, { - packet_id, - properties, - topic_filters - }). - --record(mqtt_packet_suback, { - packet_id, - properties, - reason_codes - }). - --record(mqtt_packet_unsubscribe, { - packet_id, - properties, - topic_filters - }). - --record(mqtt_packet_unsuback, { - packet_id, - properties, - reason_codes - }). - --record(mqtt_packet_disconnect, { - reason_code, - properties - }). - --record(mqtt_packet_auth, { - reason_code, - properties - }). - -%%-------------------------------------------------------------------- -%% MQTT Message -%%-------------------------------------------------------------------- - --record(mqtt_msg, { - qos = ?QOS_0 :: emqtt:qos(), - retain = false :: boolean(), - dup = false :: boolean(), - packet_id :: emqtt:packet_id(), - topic :: emqtt:topic(), - props :: emqtt:properties(), - payload :: binary() - }). - -%%-------------------------------------------------------------------- -%% MQTT Control Packet -%%-------------------------------------------------------------------- - --record(mqtt_packet, { - header :: #mqtt_packet_header{}, - variable :: #mqtt_packet_connect{} - | #mqtt_packet_connack{} - | #mqtt_packet_publish{} - | #mqtt_packet_puback{} - | #mqtt_packet_subscribe{} - | #mqtt_packet_suback{} - | #mqtt_packet_unsubscribe{} - | #mqtt_packet_unsuback{} - | #mqtt_packet_disconnect{} - | #mqtt_packet_auth{} - | pos_integer() - | undefined, - payload :: binary() | undefined - }). - -%%-------------------------------------------------------------------- -%% MQTT Packet Match -%%-------------------------------------------------------------------- - --define(CONNECT_PACKET(Var), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNECT}, - variable = Var}). - --define(CONNACK_PACKET(ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNACK}, - variable = #mqtt_packet_connack{ack_flags = 0, - reason_code = ReasonCode} - }). - --define(CONNACK_PACKET(ReasonCode, SessPresent), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNACK}, - variable = #mqtt_packet_connack{ack_flags = SessPresent, - reason_code = ReasonCode} - }). - --define(CONNACK_PACKET(ReasonCode, SessPresent, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNACK}, - variable = #mqtt_packet_connack{ack_flags = SessPresent, - reason_code = ReasonCode, - properties = Properties} - }). - --define(AUTH_PACKET(), - #mqtt_packet{header = #mqtt_packet_header{type = ?AUTH}, - variable = #mqtt_packet_auth{reason_code = 0} - }). - --define(AUTH_PACKET(ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?AUTH}, - variable = #mqtt_packet_auth{reason_code = ReasonCode} - }). - --define(AUTH_PACKET(ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?AUTH}, - variable = #mqtt_packet_auth{reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBLISH_PACKET(QoS), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, qos = QoS}}). - --define(PUBLISH_PACKET(QoS, PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{packet_id = PacketId} - }). - --define(PUBLISH_PACKET(QoS, Topic, PacketId, Payload), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId}, - payload = Payload - }). - --define(PUBLISH_PACKET(QoS, Topic, PacketId, Properties, Payload), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId, - properties = Properties}, - payload = Payload - }). - --define(PUBACK_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBACK}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBACK_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBACK}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBACK_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBACK}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBREC_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREC}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBREC_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREC}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBREC_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREC}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBREL_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREL, - qos = ?QOS_1}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBREL_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREL, - qos = ?QOS_1}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBREL_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREL, - qos = ?QOS_1}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBCOMP_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBCOMP}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBCOMP_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBCOMP}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBCOMP_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBCOMP}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(SUBSCRIBE_PACKET(PacketId, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_subscribe{packet_id = PacketId, - topic_filters = TopicFilters} - }). - --define(SUBSCRIBE_PACKET(PacketId, Properties, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_subscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters} - }). - --define(SUBACK_PACKET(PacketId, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBACK}, - variable = #mqtt_packet_suback{packet_id = PacketId, - reason_codes = ReasonCodes} - }). - --define(SUBACK_PACKET(PacketId, Properties, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBACK}, - variable = #mqtt_packet_suback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes} - }). - --define(UNSUBSCRIBE_PACKET(PacketId, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_unsubscribe{packet_id = PacketId, - topic_filters = TopicFilters} - }). - --define(UNSUBSCRIBE_PACKET(PacketId, Properties, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_unsubscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters} - }). - --define(UNSUBACK_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBACK}, - variable = #mqtt_packet_unsuback{packet_id = PacketId} - }). - --define(UNSUBACK_PACKET(PacketId, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBACK}, - variable = #mqtt_packet_unsuback{packet_id = PacketId, - reason_codes = ReasonCodes} - }). - --define(UNSUBACK_PACKET(PacketId, Properties, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBACK}, - variable = #mqtt_packet_unsuback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes} - }). - --define(DISCONNECT_PACKET(), - #mqtt_packet{header = #mqtt_packet_header{type = ?DISCONNECT}, - variable = #mqtt_packet_disconnect{reason_code = 0} - }). - --define(DISCONNECT_PACKET(ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?DISCONNECT}, - variable = #mqtt_packet_disconnect{reason_code = ReasonCode} - }). - --define(DISCONNECT_PACKET(ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?DISCONNECT}, - variable = #mqtt_packet_disconnect{reason_code = ReasonCode, - properties = Properties} - }). - --define(PACKET(Type), #mqtt_packet{header = #mqtt_packet_header{type = Type}}). - --endif. diff --git a/_build/emqx/lib/emqtt/packages/Makefile b/_build/emqx/lib/emqtt/packages/Makefile deleted file mode 100644 index ee90fa3f03..0000000000 --- a/_build/emqx/lib/emqtt/packages/Makefile +++ /dev/null @@ -1,56 +0,0 @@ -export - -ifneq ($(shell uname -s),Linux) - $(shell echo "Please execute this script under Linux") - exit -endif - -MKFILE := $(abspath $(lastword $(MAKEFILE_LIST))) -SOURCE_PATH := $(shell dirname $(MKFILE))/.. -REL_PATH := $(SOURCE_PATH)/_build/emqtt/rel -PACKAGES_PATH := $(SOURCE_PATH)/_packages - -# The version-release used for package -PKG_VSN := $(shell git describe --tags --always) - -ifneq ($(shell cat /etc/*-release |grep -o -i centos),) - ID := centos - VERSION_ID := $(shell rpm --eval '%{centos_ver}') -else - ID := $(shell sed -n '/^ID=/p' /etc/os-release | sed -r 's/ID=(.*)/\1/g' | sed 's/"//g' ) - VERSION_ID := $(shell sed -n '/^VERSION_ID=/p' /etc/os-release | sed -r 's/VERSION_ID=(.*)/\1/g' | sed 's/"//g') -endif -SYSTEM := $(shell echo $(ID)$(VERSION_ID) | sed -r "s/([a-zA-Z]*)-.*/\1/g") -## -## Support RPM and Debian based linux systems -## -ifeq ($(ID),ubuntu) - PKGERDIR := deb -else ifeq ($(ID),debian) - PKGERDIR := deb -else ifeq ($(ID),raspbian) - PKGERDIR := deb -else - PKGERDIR := rpm -endif - -.PHONY: all -all: zip - $(if $(PKGERDIR),,$(error "Operating system '$(OS)' not supported")) - $(MAKE) -C $(PKGERDIR) - -.PHONY: zip -zip: - $(MAKE) -C ../ emqtt - mkdir -p $(PACKAGES_PATH) - cd $(REL_PATH) && zip -rq emqtt-$(SYSTEM)-$(PKG_VSN).zip emqtt - mv $(REL_PATH)/emqtt-$(SYSTEM)-$(PKG_VSN).zip $(PACKAGES_PATH) - -.PHONY: deb -deb: - make -C deb - -.PHONY: rpm -rpm: - make -C rpm - diff --git a/_build/emqx/lib/emqtt/packages/README.md b/_build/emqx/lib/emqtt/packages/README.md deleted file mode 100644 index cdb3384fbc..0000000000 --- a/_build/emqx/lib/emqtt/packages/README.md +++ /dev/null @@ -1,24 +0,0 @@ -emqx-packages -============= - -EMQ X RPM/Debian Packages - -NOTICE: Requires Erlang/OTP R21+ to build since 3.0 release. - -How to use ----------------------------- - -``` -cd project-root-directory-path -EMQX_DEPS_DEFAULT_VSN=${version} make emqx-pkg -``` - -License -------- - -Apache License Version 2.0 - -Author ------- - -EMQ X Team. diff --git a/_build/emqx/lib/emqtt/packages/deb/Makefile b/_build/emqx/lib/emqtt/packages/deb/Makefile deleted file mode 100644 index 5da3399cfe..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/Makefile +++ /dev/null @@ -1,22 +0,0 @@ -# Keep this short to avoid bloating beam files with long file path info -TOPDIR := /tmp/emqx -SRCDIR := $(TOPDIR)/$(PKG_VSN) -DEB_VSN := $(PKG_VSN:v%=%) - -ARCH := $(shell dpkg --print-architecture) -SOURCE_PKG := emqtt_$(DEB_VSN)_$(ARCH) -TARGET_PKG := emqtt-$(SYSTEM)-$(PKG_VSN)_$(ARCH) - -.PHONY: all -all: prepare - cp -r debian $(SRCDIR)/ - sed -i "s##$(shell date -u '+%a, %d %b %Y %T %z')#g" $(SRCDIR)/debian/changelog - sed -i "s##$(DEB_VSN)#g" $(SRCDIR)/debian/changelog - cd $(SRCDIR) && dpkg-buildpackage -us -uc - mkdir -p $(PACKAGES_PATH) - cp $(SRCDIR)/../$(SOURCE_PKG).deb $(PACKAGES_PATH)/$(TARGET_PKG).deb - -prepare: - rm -rf $(SRCDIR) - mkdir -p $(TOPDIR) $(SRCDIR) - cp -r $(REL_PATH)/emqtt $(SRCDIR) diff --git a/_build/emqx/lib/emqtt/packages/deb/debian/changelog b/_build/emqx/lib/emqtt/packages/deb/debian/changelog deleted file mode 100644 index 22adb30617..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/debian/changelog +++ /dev/null @@ -1,5 +0,0 @@ -emqtt () unstable; urgency=medium - - * See github commit history: https://hub.fastgit.org/emqx/emqx - - -- emqx diff --git a/_build/emqx/lib/emqtt/packages/deb/debian/compat b/_build/emqx/lib/emqtt/packages/deb/debian/compat deleted file mode 100644 index ec635144f6..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/debian/compat +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/_build/emqx/lib/emqtt/packages/deb/debian/control b/_build/emqx/lib/emqtt/packages/deb/debian/control deleted file mode 100644 index 5e476aefe2..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/debian/control +++ /dev/null @@ -1,12 +0,0 @@ -Source: emqtt -Section: unknown -Priority: optional -Maintainer: emqx -Build-Depends: debhelper (>=9) -Standards-Version: 3.9.6 -Homepage: https://www.emqx.io - -Package: emqtt -Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends} -Description: Erlang MQTT v5.0 Client compatible with MQTT v3.0 diff --git a/_build/emqx/lib/emqtt/packages/deb/debian/copyright b/_build/emqx/lib/emqtt/packages/deb/debian/copyright deleted file mode 100644 index 8f71f43fee..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/debian/copyright +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/_build/emqx/lib/emqtt/packages/deb/debian/postinst b/_build/emqx/lib/emqtt/packages/deb/debian/postinst deleted file mode 100644 index 911e5c1081..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/debian/postinst +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# postinst script for emqtt -# -# see: dh_installdeb(1) - -set -e - -chmod -R 0755 /usr/lib/emqtt/bin -[ -f /usr/bin/emqtt ] && rm /usr/bin/emqtt -[ -f /usr/bin/emqtt_cli ] && rm /usr/bin/emqtt_cli -ln -s /usr/lib/emqtt/bin/emqtt /usr/bin/emqtt -ln -s /usr/lib/emqtt/bin/emqtt_cli /usr/bin/emqtt_cli - -exit 0 diff --git a/_build/emqx/lib/emqtt/packages/deb/debian/rules b/_build/emqx/lib/emqtt/packages/deb/debian/rules deleted file mode 100644 index 3dbe8795f8..0000000000 --- a/_build/emqx/lib/emqtt/packages/deb/debian/rules +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/make -f -# -*- makefile -*- -# Sample debian/rules that uses debhelper. -# This file was originally written by Joey Hess and Craig Small. -# As a special exception, when this file is copied by dh-make into a -# dh-make output file, you may use that output file without restriction. -# This special exception was added by Craig Small in version 0.37 of dh-make. - -# modified for node_package by dizzyd@basho.com and jared@basho.com - -# Uncomment this to turn on verbose mode. -export DH_VERBOSE=1 - - -## Clear variables that may confound our build of sub-projects; also -## note that it is necessary to use overlay_vars relative to .. as -## the generate command EXECUTES in rel/ -build: - -clean: - dh_clean - rm -f build - # make clean - -## dh_shlibdeps was added to figure out the dependencies on shared libraries -## and will populate the ${shlibs:Depends} callout in the control file -install: build - dh_testdir - dh_testroot - dh_prep - dh_installdirs - - mkdir -p debian/emqtt/usr/lib/emqtt - cp -R emqtt/* debian/emqtt/usr/lib/emqtt - - dh_shlibdeps - -# We have nothing to do by default. -binary-indep: install build-stamp -build-stamp: - -# Build architecture-dependent files here. -binary-arch: install - dh_strip -a - dh_compress -a - dh_installdeb - dh_gencontrol - dh_builddeb - -binary: binary-indep binary-arch diff --git a/_build/emqx/lib/emqtt/packages/rpm/Makefile b/_build/emqx/lib/emqtt/packages/rpm/Makefile deleted file mode 100644 index eab30a726c..0000000000 --- a/_build/emqx/lib/emqtt/packages/rpm/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -# Keep this short to avoid bloating beam files with long file path info -TOPDIR := $(shell rpm --eval "%{_topdir}") -RPM_VSN ?= $(shell echo $(PKG_VSN) | grep -oE "[0-9]+\.[0-9]+(\.[0-9]+)?") -RPM_REL ?= $(shell echo $(PKG_VSN) | grep -oE "(alpha|beta|rc)\.[0-9]") - -ARCH := $(shell arch) -TARGET_PKG := emqtt-$(SYSTEM)-$(PKG_VSN).$(ARCH) -ifeq ($(RPM_REL),) - # no tail - RPM_REL := 1 -endif -SOURCE_PKG := emqtt-$(SYSTEM)-v$(RPM_VSN)-$(RPM_REL).$(ARCH) - -.PHONY: all -all: prepare - rpmbuild -v -bb \ - --define "_package_name emqtt" \ - --define "_name emqtt" \ - --define "_builddir $(TOPDIR)/$(PKG_VSN)/BUILD" \ - --define "_version $(RPM_VSN)" \ - --define "_release $(RPM_REL)" \ - --define "_ostype -$(SYSTEM)" \ - emqtt.spec - mkdir -p $(PACKAGES_PATH) - cp $(TOPDIR)/RPMS/$(ARCH)/$(SOURCE_PKG).rpm $(PACKAGES_PATH)/$(TARGET_PKG).rpm - -prepare: - rm -rf $(TOPDIR) - mkdir -p $(TOPDIR)/$(PKG_VSN)/BUILD - cp -r $(REL_PATH)/emqtt $(TOPDIR)/$(PKG_VSN)/BUILD diff --git a/_build/emqx/lib/emqtt/packages/rpm/emqtt.spec b/_build/emqx/lib/emqtt/packages/rpm/emqtt.spec deleted file mode 100644 index 794062f625..0000000000 --- a/_build/emqx/lib/emqtt/packages/rpm/emqtt.spec +++ /dev/null @@ -1,54 +0,0 @@ -%define debug_package %{nil} -%define _user %{_name} -%define _group %{_name} -%define _lib_home /usr/lib/%{_name} -%define _build_name_fmt %{_arch}/%{_name}%{?_ostype}-v%{_version}-%{_release}.%{_arch}.rpm - -Name: %{_package_name} -Version: %{_version} -Release: %{_release}%{?dist} -Summary: emqtt -Group: System Environment/Daemons -License: Apache License Version 2.0 -URL: https://www.emqx.io -BuildRoot: %{_tmppath}/%{_name}-%{_version}-root -Provides: %{_name} - -%description -Erlang MQTT v5.0 Client compatible with MQTT v3.0. - -%prep - -%build - -%install -if [-d %{buildroot}]; then - rm -rf %{buildroot} -fi -mkdir -p %{buildroot}%{_lib_home} -cp -r %{_builddir}/%{_name}/* %{buildroot}%{_lib_home}/ - -%pre - -%post -if [ $1 = 1 ]; then - ln -s %{_lib_home}/bin/emqtt %{_bindir}/emqtt - ln -s %{_lib_home}/bin/emqtt_cli %{_bindir}/emqtt_cli -fi - -%preun -if [ $1 = 0 ]; then - rm -f %{_bindir}/emqtt - rm -f %{_bindir}/emqtt_cli -fi -exit 0 - -%files -%defattr(-,root,root) -%{_lib_home} - -%clean -rm -rf %{buildroot} - -%changelog - diff --git a/_build/emqx/lib/emqtt/pre-compile b/_build/emqx/lib/emqtt/pre-compile deleted file mode 100644 index 9a1d78b88a..0000000000 --- a/_build/emqx/lib/emqtt/pre-compile +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env escript - --mode(compile). - -main(_Args) -> - update_apps(os:getenv("WITH_WS")). - -add_app(Apps, NewApp) -> - Apps ++ [NewApp]. - -del_app(Apps, OldApp) -> - Apps -- [OldApp]. - -update_apps("true") -> - do_update_apps(fun add_app/2); -update_apps(_false) -> - do_update_apps(fun del_app/2). - -do_update_apps(Operator) -> - FilePath = filename:join(["src", "emqtt.app.src"]), - {ok, [{application, emqtt, PropLists0}]} = file:consult(FilePath), - Applications0 = proplists:get_value(applications, PropLists0), - Applications = Operator(Applications0, gun), - PropLists = [{applications, Applications} | proplists:delete(applications, PropLists0)], - NewAppSrc = {application, emqtt, PropLists}, - ok = file:write_file(FilePath, [io_lib:format("~p.\n", [NewAppSrc])]). - - - diff --git a/_build/emqx/lib/emqtt/rebar.config b/_build/emqx/lib/emqtt/rebar.config deleted file mode 100644 index 351ce03817..0000000000 --- a/_build/emqx/lib/emqtt/rebar.config +++ /dev/null @@ -1,104 +0,0 @@ -{minimum_otp_vsn, "21.0"}. - -{erl_opts, [debug_info, - warn_export_all, - warn_unused_import - ]}. - -{deps, [ - {cowlib, {git, "https://hub.fastgit.org/ninenines/cowlib", {tag, "2.6.0"}}}, - {gun, {git, "https://hub.fastgit.org/ninenines/gun", {tag, "1.3.0"}}}, - {getopt, "1.0.1"}]}. - -{escript_name, emqtt_cli}. -{escript_main_app, emqtt}. -{escript_incl_apps, [getopt,gun,cowlib]}. -{escript_emu_args, "%%! -smp true +K true +A 16 +P 200000 -env ERL_MAX_PORTS 100000 -env ERTS_MAX_PORTS 100000\n"}. -{escript_shebang, "#!/usr/bin/env escript\n"}. - -{profiles, - [{test, - [{deps, - [{meck, "0.8.13"}, % hex - {emqx, {git, "https://hub.fastgit.org/emqx/emqx", {branch, "master"}}}, % git - {emqx_auth_username, {git, "https://hub.fastgit.org/emqx/emqx-auth-username", {branch, "master"}}}, - {emqx_ct_helpers, {git, "https://hub.fastgit.org/emqx/emqx-ct-helpers", {branch, "develop"}}} - ]}, - {erl_opts, [debug_info]} - ]}, - {escript, []}, - {emqtt, - [{relx, - [{release, {emqtt, git_describe}, [ - kernel, - sasl, - crypto, - public_key, - asn1, - syntax_tools, - ssl, - os_mon, - inets, - compiler, - runtime_tools - ]}, - {overlay_vars,["vars.config"]}, - {overlay, [ - {copy, "_build/escript/bin/emqtt_cli", "bin/emqtt_cli"}, - {copy,"bin/emqtt","bin/emqtt"}, - {template,"bin/emqtt","bin/emqtt"} - ]}, - {include_src, false}, - {extended_start_script, false}, - {generate_start_script, false}, - {sys_config, false}, - {vm_args, false} - ]} - ]}, - {emqtt_pkg, - [{relx, - [{release, {emqtt, git_describe}, [ - kernel, - sasl, - crypto, - public_key, - asn1, - syntax_tools, - ssl, - os_mon, - inets, - compiler, - runtime_tools - ]}, - {overlay_vars,["vars-pkg.config"]}, - {overlay, [ - {copy, "_build/escript/bin/emqtt_cli", "bin/emqtt_cli"}, - {copy,"bin/emqtt","bin/emqtt"}, - {template,"bin/emqtt","bin/emqtt"} - ]}, - {include_src, false}, - {extended_start_script, false}, - {generate_start_script, false}, - {sys_config, false}, - {vm_args, false} - ]} - ]} - ]}. - -{cover_enabled, true}. -{cover_opts, [verbose]}. -{cover_export_enabled, true}. - -{xref_checks, [undefined_function_calls]}. - -{dialyzer_base_plt_apps, - [kernel, - stdlib, - erts, - sasl, - ssl, - syntax_tools, - compiler, - crypto]}. - - diff --git a/_build/emqx/lib/emqtt/rebar.config.script b/_build/emqx/lib/emqtt/rebar.config.script deleted file mode 100644 index 81f3ec7e80..0000000000 --- a/_build/emqx/lib/emqtt/rebar.config.script +++ /dev/null @@ -1,22 +0,0 @@ -%%-*- mode: erlang -*- - -%% ============================================================================== -%% Relx configs -%% ============================================================================== -Keyfind = fun(K, L) -> {K, V} = lists:keyfind(K, 1, L), V end, - -NewRelx = - fun(Name, Profiles) -> - EMQTT = Keyfind(Name, Profiles), - Relx = Keyfind(relx, EMQTT), - {release, {emqtt, Vsn}, Apps} = lists:keyfind(release, 1, Relx), - GitDescribe = lists:last(string:tokens(os:cmd("git describe --tags --always"), "\n")), - Relx1 = lists:keystore(release, 1, Relx, {release, {emqtt, GitDescribe}, Apps}), - [{relx, Relx1}] - end, - -Profiles = Keyfind(profiles, CONFIG), -Profiles1 = lists:keystore(emqtt, 1, Profiles, {emqtt, NewRelx(emqtt, Profiles)}), -Profiles2 = lists:keystore(emqtt_pkg, 1, Profiles1, {emqtt_pkg, NewRelx(emqtt_pkg, Profiles1)}), -NewConfig = lists:keystore(profiles, 1, CONFIG, {profiles, Profiles2}), -NewConfig. \ No newline at end of file diff --git a/_build/emqx/lib/emqtt/src/emqtt.erl b/_build/emqx/lib/emqtt/src/emqtt.erl deleted file mode 100644 index 67a1e5da5d..0000000000 --- a/_build/emqx/lib/emqtt/src/emqtt.erl +++ /dev/null @@ -1,1364 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqtt). - --behaviour(gen_statem). - --include("emqtt.hrl"). - --export([ start_link/0 - , start_link/1 - ]). - --export([ connect/1 - , ws_connect/1 - , disconnect/1 - , disconnect/2 - , disconnect/3 - ]). - --export([ping/1]). - -%% PubSub --export([ subscribe/2 - , subscribe/3 - , subscribe/4 - , publish/2 - , publish/3 - , publish/4 - , publish/5 - , unsubscribe/2 - , unsubscribe/3 - ]). - -%% Puback... --export([ puback/2 - , puback/3 - , puback/4 - , pubrec/2 - , pubrec/3 - , pubrec/4 - , pubrel/2 - , pubrel/3 - , pubrel/4 - , pubcomp/2 - , pubcomp/3 - , pubcomp/4 - ]). - --export([subscriptions/1]). - --export([info/1, stop/1]). - -%% For test cases --export([ pause/1 - , resume/1 - ]). - --export([ initialized/3 - , waiting_for_connack/3 - , connected/3 - , inflight_full/3 - , random_client_id/0 - , reason_code_name/1 - ]). - --export([ init/1 - , callback_mode/0 - , handle_event/4 - , terminate/3 - , code_change/4 - ]). - - --export_type([ host/0 - , option/0 - , properties/0 - , payload/0 - , pubopt/0 - , subopt/0 - , mqtt_msg/0 - , client/0 - ]). - --type(host() :: inet:ip_address() | inet:hostname()). - -%% Message handler is a set of callbacks defined to handle MQTT messages -%% as well as the disconnect event. --define(NO_MSG_HDLR, undefined). --type(msg_handler() :: #{puback := fun((_) -> any()), - publish := fun((emqx_types:message()) -> any()), - disconnected := fun(({reason_code(), _Properties :: term()}) -> any()) - }). - --type(option() :: {name, atom()} - | {owner, pid()} - | {msg_handler, msg_handler()} - | {host, host()} - | {hosts, [{host(), inet:port_number()}]} - | {port, inet:port_number()} - | {tcp_opts, [gen_tcp:option()]} - | {ssl, boolean()} - | {ssl_opts, [ssl:ssl_option()]} - | {ws_path, string()} - | {connect_timeout, pos_integer()} - | {bridge_mode, boolean()} - | {clientid, iodata()} - | {clean_start, boolean()} - | {username, iodata()} - | {password, iodata()} - | {proto_ver, v3 | v4 | v5} - | {keepalive, non_neg_integer()} - | {max_inflight, pos_integer()} - | {retry_interval, timeout()} - | {will_topic, iodata()} - | {will_payload, iodata()} - | {will_retain, boolean()} - | {will_qos, qos()} - | {will_props, properties()} - | {auto_ack, boolean()} - | {ack_timeout, pos_integer()} - | {force_ping, boolean()} - | {properties, properties()}). - --type(maybe(T) :: undefined | T). --type(topic() :: binary()). --type(payload() :: iodata()). --type(packet_id() :: 0..16#FFFF). --type(reason_code() :: 0..16#FF). --type(properties() :: #{atom() => term()}). --type(version() :: ?MQTT_PROTO_V3 - | ?MQTT_PROTO_V4 - | ?MQTT_PROTO_V5). --type(qos() :: ?QOS_0 | ?QOS_1 | ?QOS_2). --type(qos_name() :: qos0 | at_most_once | - qos1 | at_least_once | - qos2 | exactly_once). --type(pubopt() :: {retain, boolean()} - | {qos, qos() | qos_name()}). --type(subopt() :: {rh, 0 | 1 | 2} - | {rap, boolean()} - | {nl, boolean()} - | {qos, qos() | qos_name()}). - --type(subscribe_ret() :: - {ok, properties(), [reason_code()]} | {error, term()}). - --type(conn_mod() :: emqtt_sock | emqtt_ws). - --type(client() :: pid() | atom()). - --opaque(mqtt_msg() :: #mqtt_msg{}). - --record(state, { - name :: atom(), - owner :: pid(), - msg_handler :: ?NO_MSG_HDLR | msg_handler(), - host :: host(), - port :: inet:port_number(), - hosts :: [{host(), inet:port_number()}], - conn_mod :: conn_mod(), - socket :: inet:socket() | pid(), - sock_opts :: [emqtt_sock:option()|emqtt_ws:option()], - connect_timeout :: pos_integer(), - bridge_mode :: boolean(), - clientid :: binary(), - clean_start :: boolean(), - username :: maybe(binary()), - password :: maybe(binary()), - proto_ver :: version(), - proto_name :: iodata(), - keepalive :: non_neg_integer(), - keepalive_timer :: maybe(reference()), - force_ping :: boolean(), - paused :: boolean(), - will_flag :: boolean(), - will_msg :: mqtt_msg(), - properties :: properties(), - pending_calls :: list(), - subscriptions :: map(), - max_inflight :: infinity | pos_integer(), - inflight :: #{packet_id() => term()}, - awaiting_rel :: map(), - auto_ack :: boolean(), - ack_timeout :: pos_integer(), - ack_timer :: reference(), - retry_interval :: pos_integer(), - retry_timer :: reference(), - session_present :: boolean(), - last_packet_id :: packet_id(), - parse_state :: emqtt_frame:parse_state() - }). - --record(call, {id, from, req, ts}). - -%% Default timeout --define(DEFAULT_KEEPALIVE, 60). --define(DEFAULT_RETRY_INTERVAL, 30000). --define(DEFAULT_ACK_TIMEOUT, 30000). --define(DEFAULT_CONNECT_TIMEOUT, 60000). - --define(PROPERTY(Name, Val), #state{properties = #{Name := Val}}). - --define(WILL_MSG(QoS, Retain, Topic, Props, Payload), - #mqtt_msg{qos = QoS, - retain = Retain, - topic = Topic, - props = Props, - payload = Payload - }). - --define(NO_CLIENT_ID, <<>>). - --define(LOG(Level, Format, Args, State), - begin - (logger:log(Level, #{}, #{report_cb => fun(_) -> {"emqtt(~s): "++(Format), ([State#state.clientid|Args])} end})) - end). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - --spec(start_link() -> gen_statem:start_ret()). -start_link() -> start_link([]). - --spec(start_link(map() | [option()]) -> gen_statem:start_ret()). -start_link(Options) when is_map(Options) -> - start_link(maps:to_list(Options)); -start_link(Options) when is_list(Options) -> - ok = emqtt_props:validate( - proplists:get_value(properties, Options, #{})), - case proplists:get_value(name, Options) of - undefined -> - gen_statem:start_link(?MODULE, [with_owner(Options)], []); - Name when is_atom(Name) -> - gen_statem:start_link({local, Name}, ?MODULE, [with_owner(Options)], []) - end. - -with_owner(Options) -> - case proplists:get_value(owner, Options) of - Owner when is_pid(Owner) -> Options; - undefined -> [{owner, self()} | Options] - end. - --spec(connect(client()) -> {ok, properties()} | {error, term()}). -connect(Client) -> - call(Client, {connect, emqtt_sock}). - -ws_connect(Client) -> - call(Client, {connect, emqtt_ws}). - -%% @private -call(Client, Req) -> - gen_statem:call(Client, Req, infinity). - --spec(subscribe(client(), topic() | {topic(), qos() | qos_name() | [subopt()]} | [{topic(), qos()}]) - -> subscribe_ret()). -subscribe(Client, Topic) when is_binary(Topic) -> - subscribe(Client, {Topic, ?QOS_0}); -subscribe(Client, {Topic, QoS}) when is_binary(Topic), is_atom(QoS) -> - subscribe(Client, {Topic, ?QOS_I(QoS)}); -subscribe(Client, {Topic, QoS}) when is_binary(Topic), ?IS_QOS(QoS) -> - subscribe(Client, [{Topic, ?QOS_I(QoS)}]); -subscribe(Client, Topics) when is_list(Topics) -> - subscribe(Client, #{}, lists:map( - fun({Topic, QoS}) when is_binary(Topic), is_atom(QoS) -> - {Topic, [{qos, ?QOS_I(QoS)}]}; - ({Topic, QoS}) when is_binary(Topic), ?IS_QOS(QoS) -> - {Topic, [{qos, ?QOS_I(QoS)}]}; - ({Topic, Opts}) when is_binary(Topic), is_list(Opts) -> - {Topic, Opts} - end, Topics)). - --spec(subscribe(client(), topic(), qos() | qos_name() | [subopt()]) -> - subscribe_ret(); - (client(), properties(), [{topic(), qos() | [subopt()]}]) -> - subscribe_ret()). -subscribe(Client, Topic, QoS) when is_binary(Topic), is_atom(QoS) -> - subscribe(Client, Topic, ?QOS_I(QoS)); -subscribe(Client, Topic, QoS) when is_binary(Topic), ?IS_QOS(QoS) -> - subscribe(Client, Topic, [{qos, QoS}]); -subscribe(Client, Topic, Opts) when is_binary(Topic), is_list(Opts) -> - subscribe(Client, #{}, [{Topic, Opts}]); -subscribe(Client, Properties, Topics) when is_map(Properties), is_list(Topics) -> - Topics1 = [{Topic, parse_subopt(Opts)} || {Topic, Opts} <- Topics], - gen_statem:call(Client, {subscribe, Properties, Topics1}). - --spec(subscribe(client(), properties(), topic(), qos() | qos_name() | [subopt()]) - -> subscribe_ret()). -subscribe(Client, Properties, Topic, QoS) - when is_map(Properties), is_binary(Topic), is_atom(QoS) -> - subscribe(Client, Properties, Topic, ?QOS_I(QoS)); -subscribe(Client, Properties, Topic, QoS) - when is_map(Properties), is_binary(Topic), ?IS_QOS(QoS) -> - subscribe(Client, Properties, Topic, [{qos, QoS}]); -subscribe(Client, Properties, Topic, Opts) - when is_map(Properties), is_binary(Topic), is_list(Opts) -> - subscribe(Client, Properties, [{Topic, Opts}]). - -parse_subopt(Opts) -> - parse_subopt(Opts, #{rh => 0, rap => 0, nl => 0, qos => ?QOS_0}). - -parse_subopt([], Result) -> - Result; -parse_subopt([{rh, I} | Opts], Result) when I >= 0, I =< 2 -> - parse_subopt(Opts, Result#{rh := I}); -parse_subopt([{rap, true} | Opts], Result) -> - parse_subopt(Opts, Result#{rap := 1}); -parse_subopt([{rap, false} | Opts], Result) -> - parse_subopt(Opts, Result#{rap := 0}); -parse_subopt([{nl, true} | Opts], Result) -> - parse_subopt(Opts, Result#{nl := 1}); -parse_subopt([{nl, false} | Opts], Result) -> - parse_subopt(Opts, Result#{nl := 0}); -parse_subopt([{qos, QoS} | Opts], Result) -> - parse_subopt(Opts, Result#{qos := ?QOS_I(QoS)}); -parse_subopt([_ | Opts], Result) -> - parse_subopt(Opts, Result). - --spec(publish(client(), topic(), payload()) -> ok | {error, term()}). -publish(Client, Topic, Payload) when is_binary(Topic) -> - publish(Client, #mqtt_msg{topic = Topic, qos = ?QOS_0, payload = iolist_to_binary(Payload)}). - --spec(publish(client(), topic(), payload(), qos() | qos_name() | [pubopt()]) - -> ok | {ok, packet_id()} | {error, term()}). -publish(Client, Topic, Payload, QoS) when is_binary(Topic), is_atom(QoS) -> - publish(Client, Topic, Payload, [{qos, ?QOS_I(QoS)}]); -publish(Client, Topic, Payload, QoS) when is_binary(Topic), ?IS_QOS(QoS) -> - publish(Client, Topic, Payload, [{qos, QoS}]); -publish(Client, Topic, Payload, Opts) when is_binary(Topic), is_list(Opts) -> - publish(Client, Topic, #{}, Payload, Opts). - --spec(publish(client(), topic(), properties(), payload(), [pubopt()]) - -> ok | {ok, packet_id()} | {error, term()}). -publish(Client, Topic, Properties, Payload, Opts) - when is_binary(Topic), is_map(Properties), is_list(Opts) -> - ok = emqtt_props:validate(Properties), - Retain = proplists:get_bool(retain, Opts), - QoS = ?QOS_I(proplists:get_value(qos, Opts, ?QOS_0)), - publish(Client, #mqtt_msg{qos = QoS, - retain = Retain, - topic = Topic, - props = Properties, - payload = iolist_to_binary(Payload)}). - --spec(publish(client(), #mqtt_msg{}) -> ok | {ok, packet_id()} | {error, term()}). -publish(Client, Msg) -> - gen_statem:call(Client, {publish, Msg}). - --spec(unsubscribe(client(), topic() | [topic()]) -> subscribe_ret()). -unsubscribe(Client, Topic) when is_binary(Topic) -> - unsubscribe(Client, [Topic]); -unsubscribe(Client, Topics) when is_list(Topics) -> - unsubscribe(Client, #{}, Topics). - --spec(unsubscribe(client(), properties(), topic() | [topic()]) -> subscribe_ret()). -unsubscribe(Client, Properties, Topic) when is_map(Properties), is_binary(Topic) -> - unsubscribe(Client, Properties, [Topic]); -unsubscribe(Client, Properties, Topics) when is_map(Properties), is_list(Topics) -> - gen_statem:call(Client, {unsubscribe, Properties, Topics}). - --spec(ping(client()) -> pong). -ping(Client) -> - gen_statem:call(Client, ping). - --spec(disconnect(client()) -> ok). -disconnect(Client) -> - disconnect(Client, ?RC_SUCCESS). - --spec(disconnect(client(), reason_code()) -> ok). -disconnect(Client, ReasonCode) -> - disconnect(Client, ReasonCode, #{}). - --spec(disconnect(client(), reason_code(), properties()) -> ok). -disconnect(Client, ReasonCode, Properties) -> - gen_statem:call(Client, {disconnect, ReasonCode, Properties}). - -%%-------------------------------------------------------------------- -%% For test cases -%%-------------------------------------------------------------------- - -puback(Client, PacketId) when is_integer(PacketId) -> - puback(Client, PacketId, ?RC_SUCCESS). -puback(Client, PacketId, ReasonCode) - when is_integer(PacketId), is_integer(ReasonCode) -> - puback(Client, PacketId, ReasonCode, #{}). -puback(Client, PacketId, ReasonCode, Properties) - when is_integer(PacketId), is_integer(ReasonCode), is_map(Properties) -> - gen_statem:cast(Client, {puback, PacketId, ReasonCode, Properties}). - -pubrec(Client, PacketId) when is_integer(PacketId) -> - pubrec(Client, PacketId, ?RC_SUCCESS). -pubrec(Client, PacketId, ReasonCode) - when is_integer(PacketId), is_integer(ReasonCode) -> - pubrec(Client, PacketId, ReasonCode, #{}). -pubrec(Client, PacketId, ReasonCode, Properties) - when is_integer(PacketId), is_integer(ReasonCode), is_map(Properties) -> - gen_statem:cast(Client, {pubrec, PacketId, ReasonCode, Properties}). - -pubrel(Client, PacketId) when is_integer(PacketId) -> - pubrel(Client, PacketId, ?RC_SUCCESS). -pubrel(Client, PacketId, ReasonCode) - when is_integer(PacketId), is_integer(ReasonCode) -> - pubrel(Client, PacketId, ReasonCode, #{}). -pubrel(Client, PacketId, ReasonCode, Properties) - when is_integer(PacketId), is_integer(ReasonCode), is_map(Properties) -> - gen_statem:cast(Client, {pubrel, PacketId, ReasonCode, Properties}). - -pubcomp(Client, PacketId) when is_integer(PacketId) -> - pubcomp(Client, PacketId, ?RC_SUCCESS). -pubcomp(Client, PacketId, ReasonCode) - when is_integer(PacketId), is_integer(ReasonCode) -> - pubcomp(Client, PacketId, ReasonCode, #{}). -pubcomp(Client, PacketId, ReasonCode, Properties) - when is_integer(PacketId), is_integer(ReasonCode), is_map(Properties) -> - gen_statem:cast(Client, {pubcomp, PacketId, ReasonCode, Properties}). - -subscriptions(Client) -> - gen_statem:call(Client, subscriptions). - -info(Client) -> - gen_statem:call(Client, info). - -stop(Client) -> - gen_statem:call(Client, stop). - -pause(Client) -> - gen_statem:call(Client, pause). - -resume(Client) -> - gen_statem:call(Client, resume). - -%%-------------------------------------------------------------------- -%% gen_statem callbacks -%%-------------------------------------------------------------------- - -init([Options]) -> - process_flag(trap_exit, true), - ClientId = case {proplists:get_value(proto_ver, Options, v4), - proplists:get_value(clientid, Options)} of - {v5, undefined} -> ?NO_CLIENT_ID; - {_ver, undefined} -> random_client_id(); - {_ver, Id} -> iolist_to_binary(Id) - end, - State = init(Options, #state{host = {127,0,0,1}, - port = 1883, - hosts = [], - conn_mod = emqtt_sock, - sock_opts = [], - bridge_mode = false, - clientid = ClientId, - clean_start = true, - proto_ver = ?MQTT_PROTO_V4, - proto_name = <<"MQTT">>, - keepalive = ?DEFAULT_KEEPALIVE, - force_ping = false, - paused = false, - will_flag = false, - will_msg = #mqtt_msg{}, - pending_calls = [], - subscriptions = #{}, - max_inflight = infinity, - inflight = #{}, - awaiting_rel = #{}, - properties = #{}, - auto_ack = true, - ack_timeout = ?DEFAULT_ACK_TIMEOUT, - retry_interval = ?DEFAULT_RETRY_INTERVAL, - connect_timeout = ?DEFAULT_CONNECT_TIMEOUT, - last_packet_id = 1 - }), - {ok, initialized, init_parse_state(State)}. - -random_client_id() -> - rand:seed(exsplus, erlang:timestamp()), - I1 = rand:uniform(round(math:pow(2, 48))) - 1, - I2 = rand:uniform(round(math:pow(2, 32))) - 1, - {ok, Host} = inet:gethostname(), - RandId = io_lib:format("~12.16.0b~8.16.0b", [I1, I2]), - iolist_to_binary(["emqtt-", Host, "-", RandId]). - -init([], State) -> - State; -init([{name, Name} | Opts], State) -> - init(Opts, State#state{name = Name}); -init([{owner, Owner} | Opts], State) when is_pid(Owner) -> - link(Owner), - init(Opts, State#state{owner = Owner}); -init([{msg_handler, Hdlr} | Opts], State) -> - init(Opts, State#state{msg_handler = Hdlr}); -init([{host, Host} | Opts], State) -> - init(Opts, State#state{host = Host}); -init([{port, Port} | Opts], State) -> - init(Opts, State#state{port = Port}); -init([{hosts, Hosts} | Opts], State) -> - Hosts1 = - lists:foldl(fun({Host, Port}, Acc) -> - [{Host, Port}|Acc]; - (Host, Acc) -> - [{Host, 1883}|Acc] - end, [], Hosts), - init(Opts, State#state{hosts = Hosts1}); -init([{tcp_opts, TcpOpts} | Opts], State = #state{sock_opts = SockOpts}) -> - init(Opts, State#state{sock_opts = merge_opts(SockOpts, TcpOpts)}); -init([{ssl, EnableSsl} | Opts], State) -> - case lists:keytake(ssl_opts, 1, Opts) of - {value, SslOpts, WithOutSslOpts} -> - init([SslOpts, {ssl, EnableSsl}| WithOutSslOpts], State); - false -> - init([{ssl_opts, []}, {ssl, EnableSsl}| Opts], State) - end; -init([{ssl_opts, SslOpts} | Opts], State = #state{sock_opts = SockOpts}) -> - case lists:keytake(ssl, 1, Opts) of - {value, {ssl, true}, WithOutEnableSsl} -> - ok = ssl:start(), - SockOpts1 = merge_opts(SockOpts, [{ssl_opts, SslOpts}]), - init(WithOutEnableSsl, State#state{sock_opts = SockOpts1}); - {value, {ssl, false}, WithOutEnableSsl} -> - init(WithOutEnableSsl, State); - false -> - init(Opts, State) - end; -init([{ws_path, Path} | Opts], State = #state{sock_opts = SockOpts}) -> - init(Opts, State#state{sock_opts = [{ws_path, Path}|SockOpts]}); -init([{clientid, ClientId} | Opts], State) -> - init(Opts, State#state{clientid = iolist_to_binary(ClientId)}); -init([{clean_start, CleanStart} | Opts], State) when is_boolean(CleanStart) -> - init(Opts, State#state{clean_start = CleanStart}); -init([{username, Username} | Opts], State) -> - init(Opts, State#state{username = iolist_to_binary(Username)}); -init([{password, Password} | Opts], State) -> - init(Opts, State#state{password = iolist_to_binary(Password)}); -init([{keepalive, Secs} | Opts], State) -> - init(Opts, State#state{keepalive = Secs}); -init([{proto_ver, v3} | Opts], State) -> - init(Opts, State#state{proto_ver = ?MQTT_PROTO_V3, - proto_name = <<"MQIsdp">>}); -init([{proto_ver, v4} | Opts], State) -> - init(Opts, State#state{proto_ver = ?MQTT_PROTO_V4, - proto_name = <<"MQTT">>}); -init([{proto_ver, v5} | Opts], State) -> - init(Opts, State#state{proto_ver = ?MQTT_PROTO_V5, - proto_name = <<"MQTT">>}); -init([{will_topic, Topic} | Opts], State = #state{will_msg = WillMsg}) -> - WillMsg1 = init_will_msg({topic, Topic}, WillMsg), - init(Opts, State#state{will_flag = true, will_msg = WillMsg1}); -init([{will_props, Properties} | Opts], State = #state{will_msg = WillMsg}) -> - init(Opts, State#state{will_msg = init_will_msg({props, Properties}, WillMsg)}); -init([{will_payload, Payload} | Opts], State = #state{will_msg = WillMsg}) -> - init(Opts, State#state{will_msg = init_will_msg({payload, Payload}, WillMsg)}); -init([{will_retain, Retain} | Opts], State = #state{will_msg = WillMsg}) -> - init(Opts, State#state{will_msg = init_will_msg({retain, Retain}, WillMsg)}); -init([{will_qos, QoS} | Opts], State = #state{will_msg = WillMsg}) -> - init(Opts, State#state{will_msg = init_will_msg({qos, QoS}, WillMsg)}); -init([{connect_timeout, Timeout}| Opts], State) -> - init(Opts, State#state{connect_timeout = timer:seconds(Timeout)}); -init([{ack_timeout, Timeout}| Opts], State) -> - init(Opts, State#state{ack_timeout = timer:seconds(Timeout)}); -init([force_ping | Opts], State) -> - init(Opts, State#state{force_ping = true}); -init([{force_ping, ForcePing} | Opts], State) when is_boolean(ForcePing) -> - init(Opts, State#state{force_ping = ForcePing}); -init([{properties, Properties} | Opts], State = #state{properties = InitProps}) -> - init(Opts, State#state{properties = maps:merge(InitProps, Properties)}); -init([{max_inflight, infinity} | Opts], State) -> - init(Opts, State#state{max_inflight = infinity, - inflight = #{}}); -init([{max_inflight, I} | Opts], State) when is_integer(I) -> - init(Opts, State#state{max_inflight = I, - inflight = #{}}); -init([auto_ack | Opts], State) -> - init(Opts, State#state{auto_ack = true}); -init([{auto_ack, AutoAck} | Opts], State) when is_boolean(AutoAck) -> - init(Opts, State#state{auto_ack = AutoAck}); -init([{retry_interval, I} | Opts], State) -> - init(Opts, State#state{retry_interval = timer:seconds(I)}); -init([{bridge_mode, Mode} | Opts], State) when is_boolean(Mode) -> - init(Opts, State#state{bridge_mode = Mode}); -init([_Opt | Opts], State) -> - init(Opts, State). - -init_will_msg({topic, Topic}, WillMsg) -> - WillMsg#mqtt_msg{topic = iolist_to_binary(Topic)}; -init_will_msg({props, Props}, WillMsg) -> - WillMsg#mqtt_msg{props = Props}; -init_will_msg({payload, Payload}, WillMsg) -> - WillMsg#mqtt_msg{payload = iolist_to_binary(Payload)}; -init_will_msg({retain, Retain}, WillMsg) when is_boolean(Retain) -> - WillMsg#mqtt_msg{retain = Retain}; -init_will_msg({qos, QoS}, WillMsg) -> - WillMsg#mqtt_msg{qos = ?QOS_I(QoS)}. - -init_parse_state(State = #state{proto_ver = Ver, properties = Properties}) -> - MaxSize = maps:get('Maximum-Packet-Size', Properties, ?MAX_PACKET_SIZE), - ParseState = emqtt_frame:initial_parse_state( - #{max_size => MaxSize, version => Ver}), - State#state{parse_state = ParseState}. - -merge_opts(Defaults, Options) -> - lists:foldl( - fun({Opt, Val}, Acc) -> - lists:keystore(Opt, 1, Acc, {Opt, Val}); - (Opt, Acc) -> - lists:usort([Opt | Acc]) - end, Defaults, Options). - -callback_mode() -> state_functions. - -initialized({call, From}, {connect, ConnMod}, State = #state{sock_opts = SockOpts, - connect_timeout = Timeout}) -> - case sock_connect(ConnMod, hosts(State), SockOpts, Timeout) of - {ok, Sock} -> - case mqtt_connect(run_sock(State#state{conn_mod = ConnMod, socket = Sock})) of - {ok, NewState} -> - {next_state, waiting_for_connack, - add_call(new_call(connect, From), NewState), [Timeout]}; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - -initialized(EventType, EventContent, State) -> - handle_event(EventType, EventContent, initialized, State). - -mqtt_connect(State = #state{clientid = ClientId, - clean_start = CleanStart, - bridge_mode = IsBridge, - username = Username, - password = Password, - proto_ver = ProtoVer, - proto_name = ProtoName, - keepalive = KeepAlive, - will_flag = WillFlag, - will_msg = WillMsg, - properties = Properties}) -> - ?WILL_MSG(WillQoS, WillRetain, WillTopic, WillProps, WillPayload) = WillMsg, - ConnProps = emqtt_props:filter(?CONNECT, Properties), - send(?CONNECT_PACKET( - #mqtt_packet_connect{proto_ver = ProtoVer, - proto_name = ProtoName, - is_bridge = IsBridge, - clean_start = CleanStart, - will_flag = WillFlag, - will_qos = WillQoS, - will_retain = WillRetain, - keepalive = KeepAlive, - properties = ConnProps, - clientid = ClientId, - will_props = WillProps, - will_topic = WillTopic, - will_payload = WillPayload, - username = Username, - password = Password}), State). - -waiting_for_connack(cast, ?CONNACK_PACKET(?RC_SUCCESS, - SessPresent, - Properties), - State = #state{properties = AllProps, - clientid = ClientId}) -> - case take_call(connect, State) of - {value, #call{from = From}, State1} -> - AllProps1 = case Properties of - undefined -> AllProps; - _ -> maps:merge(AllProps, Properties) - end, - Reply = {ok, Properties}, - State2 = State1#state{clientid = assign_id(ClientId, AllProps1), - properties = AllProps1, - session_present = SessPresent}, - {next_state, connected, ensure_keepalive_timer(State2), - [{reply, From, Reply}]}; - false -> - {stop, bad_connack} - end; - -waiting_for_connack(cast, ?CONNACK_PACKET(ReasonCode, - _SessPresent, - Properties), - State = #state{proto_ver = ProtoVer}) -> - Reason = reason_code_name(ReasonCode, ProtoVer), - case take_call(connect, State) of - {value, #call{from = From}, _State} -> - Reply = {error, {Reason, Properties}}, - {stop_and_reply, {shutdown, Reason}, [{reply, From, Reply}]}; - false -> {stop, connack_error} - end; - -waiting_for_connack(timeout, _Timeout, State) -> - case take_call(connect, State) of - {value, #call{from = From}, _State} -> - Reply = {error, connack_timeout}, - {stop_and_reply, connack_timeout, [{reply, From, Reply}]}; - false -> {stop, connack_timeout} - end; - -waiting_for_connack(EventType, EventContent, State) -> - case take_call(connect, State) of - {value, #call{from = From}, _State} -> - case handle_event(EventType, EventContent, waiting_for_connack, State) of - {stop, Reason, State} -> - Reply = {error, {Reason, EventContent}}, - {stop_and_reply, Reason, [{reply, From, Reply}]}; - StateCallbackResult -> - StateCallbackResult - end; - false -> {stop, connack_timeout} - end. - -connected({call, From}, subscriptions, #state{subscriptions = Subscriptions}) -> - {keep_state_and_data, [{reply, From, maps:to_list(Subscriptions)}]}; - -connected({call, From}, info, State) -> - Info = lists:zip(record_info(fields, state), tl(tuple_to_list(State))), - {keep_state_and_data, [{reply, From, Info}]}; - -connected({call, From}, pause, State) -> - {keep_state, State#state{paused = true}, [{reply, From, ok}]}; - -connected({call, From}, resume, State) -> - {keep_state, State#state{paused = false}, [{reply, From, ok}]}; - -connected({call, From}, clientid, #state{clientid = ClientId}) -> - {keep_state_and_data, [{reply, From, ClientId}]}; - -connected({call, From}, SubReq = {subscribe, Properties, Topics}, - State = #state{last_packet_id = PacketId, subscriptions = Subscriptions}) -> - case send(?SUBSCRIBE_PACKET(PacketId, Properties, Topics), State) of - {ok, NewState} -> - Call = new_call({subscribe, PacketId}, From, SubReq), - Subscriptions1 = - lists:foldl(fun({Topic, Opts}, Acc) -> - maps:put(Topic, Opts, Acc) - end, Subscriptions, Topics), - {keep_state, ensure_ack_timer(add_call(Call,NewState#state{subscriptions = Subscriptions1}))}; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - -connected({call, From}, {publish, Msg = #mqtt_msg{qos = ?QOS_0}}, State) -> - case send(Msg, State) of - {ok, NewState} -> - {keep_state, NewState, [{reply, From, ok}]}; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - -connected({call, From}, {publish, Msg = #mqtt_msg{qos = QoS}}, - State = #state{inflight = Inflight, last_packet_id = PacketId}) - when (QoS =:= ?QOS_1); (QoS =:= ?QOS_2) -> - Msg1 = Msg#mqtt_msg{packet_id = PacketId}, - case send(Msg1, State) of - {ok, NewState} -> - Inflight1 = maps:put(PacketId, {publish, Msg1, os:timestamp()}, Inflight), - State1 = ensure_retry_timer(NewState#state{inflight = Inflight1}), - Actions = [{reply, From, {ok, PacketId}}], - case is_inflight_full(State1) of - true -> {next_state, inflight_full, State1, Actions}; - false -> {keep_state, State1, Actions} - end; - {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, {error, {PacketId, Reason}}}]} - end; - -connected({call, From}, UnsubReq = {unsubscribe, Properties, Topics}, - State = #state{last_packet_id = PacketId}) -> - case send(?UNSUBSCRIBE_PACKET(PacketId, Properties, Topics), State) of - {ok, NewState} -> - Call = new_call({unsubscribe, PacketId}, From, UnsubReq), - {keep_state, ensure_ack_timer(add_call(Call, NewState))}; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - -connected({call, From}, ping, State) -> - case send(?PACKET(?PINGREQ), State) of - {ok, NewState} -> - Call = new_call(ping, From), - {keep_state, ensure_ack_timer(add_call(Call, NewState))}; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - -connected({call, From}, {disconnect, ReasonCode, Properties}, State) -> - case send(?DISCONNECT_PACKET(ReasonCode, Properties), State) of - {ok, NewState} -> - {stop_and_reply, normal, [{reply, From, ok}], NewState}; - Error = {error, Reason} -> - {stop_and_reply, Reason, [{reply, From, Error}]} - end; - -connected(cast, {puback, PacketId, ReasonCode, Properties}, State) -> - send_puback(?PUBACK_PACKET(PacketId, ReasonCode, Properties), State); - -connected(cast, {pubrec, PacketId, ReasonCode, Properties}, State) -> - send_puback(?PUBREC_PACKET(PacketId, ReasonCode, Properties), State); - -connected(cast, {pubrel, PacketId, ReasonCode, Properties}, State) -> - send_puback(?PUBREL_PACKET(PacketId, ReasonCode, Properties), State); - -connected(cast, {pubcomp, PacketId, ReasonCode, Properties}, State) -> - send_puback(?PUBCOMP_PACKET(PacketId, ReasonCode, Properties), State); - -connected(cast, ?PUBLISH_PACKET(_QoS, _PacketId), #state{paused = true}) -> - keep_state_and_data; - -connected(cast, Packet = ?PUBLISH_PACKET(?QOS_0, _PacketId), State) -> - {keep_state, deliver(packet_to_msg(Packet), State)}; - -connected(cast, Packet = ?PUBLISH_PACKET(?QOS_1, _PacketId), State) -> - publish_process(?QOS_1, Packet, State); - -connected(cast, Packet = ?PUBLISH_PACKET(?QOS_2, _PacketId), State) -> - publish_process(?QOS_2, Packet, State); - -connected(cast, ?PUBACK_PACKET(_PacketId, _ReasonCode, _Properties) = PubAck, State) -> - {keep_state, delete_inflight(PubAck, State)}; - -connected(cast, ?PUBREC_PACKET(PacketId), State = #state{inflight = Inflight}) -> - NState = case maps:find(PacketId, Inflight) of - {ok, {publish, _Msg, _Ts}} -> - Inflight1 = maps:put(PacketId, {pubrel, PacketId, os:timestamp()}, Inflight), - State#state{inflight = Inflight1}; - {ok, {pubrel, _Ref, _Ts}} -> - ?LOG(notice, "Duplicated PUBREC Packet: ~p", [PacketId], State), - State; - error -> - ?LOG(warning, "Unexpected PUBREC Packet: ~p", [PacketId], State), - State - end, - send_puback(?PUBREL_PACKET(PacketId), NState); - -%%TODO::... if auto_ack is false, should we take PacketId from the map? -connected(cast, ?PUBREL_PACKET(PacketId), - State = #state{awaiting_rel = AwaitingRel, auto_ack = AutoAck}) -> - case maps:take(PacketId, AwaitingRel) of - {Packet, AwaitingRel1} -> - NewState = deliver(packet_to_msg(Packet), State#state{awaiting_rel = AwaitingRel1}), - case AutoAck of - true -> send_puback(?PUBCOMP_PACKET(PacketId), NewState); - false -> {keep_state, NewState} - end; - error -> - ?LOG(warning, "Unexpected PUBREL: ~p", [PacketId], State), - keep_state_and_data - end; - -connected(cast, ?PUBCOMP_PACKET(_PacketId, _ReasonCode, _Properties) = PubComp, State) -> - {keep_state, delete_inflight(PubComp, State)}; - -connected(cast, ?SUBACK_PACKET(PacketId, Properties, ReasonCodes), - State = #state{subscriptions = _Subscriptions}) -> - case take_call({subscribe, PacketId}, State) of - {value, #call{from = From}, NewState} -> - %%TODO: Merge reason codes to subscriptions? - Reply = {ok, Properties, ReasonCodes}, - {keep_state, NewState, [{reply, From, Reply}]}; - false -> - keep_state_and_data - end; - -connected(cast, ?UNSUBACK_PACKET(PacketId, Properties, ReasonCodes), - State = #state{subscriptions = Subscriptions}) -> - case take_call({unsubscribe, PacketId}, State) of - {value, #call{from = From, req = {_, _, Topics}}, NewState} -> - Subscriptions1 = - lists:foldl(fun(Topic, Acc) -> - maps:remove(Topic, Acc) - end, Subscriptions, Topics), - {keep_state, NewState#state{subscriptions = Subscriptions1}, - [{reply, From, {ok, Properties, ReasonCodes}}]}; - false -> - keep_state_and_data - end; - -connected(cast, ?PACKET(?PINGRESP), #state{pending_calls = []}) -> - keep_state_and_data; -connected(cast, ?PACKET(?PINGRESP), State) -> - case take_call(ping, State) of - {value, #call{from = From}, NewState} -> - {keep_state, NewState, [{reply, From, pong}]}; - false -> - keep_state_and_data - end; - -connected(cast, ?DISCONNECT_PACKET(ReasonCode, Properties), State) -> - {stop, {disconnected, ReasonCode, Properties}, State}; - -connected(info, {timeout, _TRef, keepalive}, State = #state{force_ping = true}) -> - case send(?PACKET(?PINGREQ), State) of - {ok, NewState} -> - {keep_state, ensure_keepalive_timer(NewState)}; - Error -> {stop, Error} - end; - -connected(info, {timeout, TRef, keepalive}, - State = #state{conn_mod = ConnMod, socket = Sock, - paused = Paused, keepalive_timer = TRef}) -> - case (not Paused) andalso should_ping(ConnMod, Sock) of - true -> - case send(?PACKET(?PINGREQ), State) of - {ok, NewState} -> - {keep_state, ensure_keepalive_timer(NewState), [hibernate]}; - Error -> {stop, Error} - end; - false -> - {keep_state, ensure_keepalive_timer(State), [hibernate]}; - {error, Reason} -> - {stop, Reason} - end; - -connected(info, {timeout, TRef, ack}, State = #state{ack_timer = TRef, - ack_timeout = Timeout, - pending_calls = Calls}) -> - NewState = State#state{ack_timer = undefined, - pending_calls = timeout_calls(Timeout, Calls)}, - {keep_state, ensure_ack_timer(NewState)}; - -connected(info, {timeout, TRef, retry}, State = #state{retry_timer = TRef, - inflight = Inflight}) -> - case maps:size(Inflight) == 0 of - true -> {keep_state, State#state{retry_timer = undefined}}; - false -> retry_send(State) - end; - -connected(EventType, EventContent, Data) -> - handle_event(EventType, EventContent, connected, Data). - -inflight_full({call, _From}, {publish, #mqtt_msg{qos = QoS}}, _State) when (QoS =:= ?QOS_1); (QoS =:= ?QOS_2) -> - {keep_state_and_data, [postpone]}; -inflight_full(cast, ?PUBACK_PACKET(_PacketId, _ReasonCode, _Properties) = PubAck, State) -> - delete_inflight_when_full(PubAck, State); -inflight_full(cast, ?PUBCOMP_PACKET(_PacketId, _ReasonCode, _Properties) = PubComp, State) -> - delete_inflight_when_full(PubComp, State); -inflight_full(EventType, EventContent, Data) -> - %% inflight_full is a sub-state of connected state, - %% delegate all other events to connected state. - connected(EventType, EventContent, Data). - -handle_event({call, From}, stop, _StateName, _State) -> - {stop_and_reply, normal, [{reply, From, ok}]}; - -handle_event(info, {gun_ws, ConnPid, _StreamRef, {binary, Data}}, - _StateName, State = #state{socket = ConnPid}) -> - ?LOG(debug, "RECV Data: ~p", [Data], State), - process_incoming(iolist_to_binary(Data), [], State); - -handle_event(info, {gun_down, ConnPid, _, Reason, _, _}, - _StateName, State = #state{socket = ConnPid}) -> - ?LOG(debug, "WebSocket down! Reason: ~p", [Reason], State), - {stop, Reason, State}; - -handle_event(info, {TcpOrSsL, _Sock, Data}, _StateName, State) - when TcpOrSsL =:= tcp; TcpOrSsL =:= ssl -> - ?LOG(debug, "RECV Data: ~p", [Data], State), - process_incoming(Data, [], run_sock(State)); - -handle_event(info, {Error, _Sock, Reason}, _StateName, State) - when Error =:= tcp_error; Error =:= ssl_error -> - ?LOG(error, "The connection error occured ~p, reason:~p", - [Error, Reason], State), - {stop, {shutdown, Reason}, State}; - -handle_event(info, {Closed, _Sock}, _StateName, State) - when Closed =:= tcp_closed; Closed =:= ssl_closed -> - ?LOG(debug, "~p", [Closed], State), - {stop, {shutdown, Closed}, State}; - -handle_event(info, {'EXIT', Owner, Reason}, _, State = #state{owner = Owner}) -> - ?LOG(debug, "Got EXIT from owner, Reason: ~p", [Reason], State), - {stop, {shutdown, Reason}, State}; - -handle_event(info, {inet_reply, _Sock, ok}, _, _State) -> - keep_state_and_data; - -handle_event(info, {inet_reply, _Sock, {error, Reason}}, _, State) -> - ?LOG(error, "Got tcp error: ~p", [Reason], State), - {stop, {shutdown, Reason}, State}; - -handle_event(info, EventContent = {'EXIT', _Pid, normal}, StateName, State) -> - ?LOG(info, "State: ~s, Unexpected Event: (info, ~p)", - [StateName, EventContent], State), - keep_state_and_data; - -handle_event(EventType, EventContent, StateName, State) -> - ?LOG(error, "State: ~s, Unexpected Event: (~p, ~p)", - [StateName, EventType, EventContent], State), - keep_state_and_data. - -%% Mandatory callback functions -terminate(Reason, _StateName, State = #state{conn_mod = ConnMod, socket = Socket}) -> - case Reason of - {disconnected, ReasonCode, Properties} -> - %% backward compatible - ok = eval_msg_handler(State, disconnected, {ReasonCode, Properties}); - _ -> - ok = eval_msg_handler(State, disconnected, Reason) - end, - case Socket =:= undefined of - true -> ok; - _ -> ConnMod:close(Socket) - end. - -code_change(_Vsn, State, Data, _Extra) -> - {ok, State, Data}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -should_ping(ConnMod, Sock) -> - case ConnMod:getstat(Sock, [send_oct]) of - {ok, [{send_oct, Val}]} -> - OldVal = get(send_oct), put(send_oct, Val), - OldVal == undefined orelse OldVal == Val; - Error = {error, _Reason} -> - Error - end. - -is_inflight_full(#state{max_inflight = infinity}) -> - false; -is_inflight_full(#state{max_inflight = MaxLimit, inflight = Inflight}) -> - maps:size(Inflight) >= MaxLimit. - -delete_inflight(?PUBACK_PACKET(PacketId, ReasonCode, Properties), - State = #state{inflight = Inflight}) -> - case maps:find(PacketId, Inflight) of - {ok, {publish, #mqtt_msg{packet_id = PacketId}, _Ts}} -> - ok = eval_msg_handler(State, puback, #{packet_id => PacketId, - reason_code => ReasonCode, - properties => Properties}), - State#state{inflight = maps:remove(PacketId, Inflight)}; - error -> - ?LOG(warning, "Unexpected PUBACK: ~p", [PacketId], State), - State - end; -delete_inflight(?PUBCOMP_PACKET(PacketId, ReasonCode, Properties), - State = #state{inflight = Inflight}) -> - case maps:find(PacketId, Inflight) of - {ok, {pubrel, _PacketId, _Ts}} -> - ok = eval_msg_handler(State, puback, #{packet_id => PacketId, - reason_code => ReasonCode, - properties => Properties}), - State#state{inflight = maps:remove(PacketId, Inflight)}; - error -> - ?LOG(warning, "Unexpected PUBCOMP Packet: ~p", [PacketId], State), - State - end. - -delete_inflight_when_full(Packet, State) -> - State1 = delete_inflight(Packet, State), - case is_inflight_full(State1) of - true -> {keep_state, State1}; - false -> {next_state, connected, State1} - end. - -assign_id(?NO_CLIENT_ID, Props) -> - case maps:find('Assigned-Client-Identifier', Props) of - {ok, Value} -> - Value; - _ -> - error(bad_client_id) - end; -assign_id(Id, _Props) -> - Id. - -publish_process(?QOS_1, Packet = ?PUBLISH_PACKET(?QOS_1, PacketId), - State0 = #state{auto_ack = AutoAck}) -> - State = deliver(packet_to_msg(Packet), State0), - case AutoAck of - true -> send_puback(?PUBACK_PACKET(PacketId), State); - false -> {keep_state, State} - end; -publish_process(?QOS_2, Packet = ?PUBLISH_PACKET(?QOS_2, PacketId), - State = #state{awaiting_rel = AwaitingRel}) -> - case send_puback(?PUBREC_PACKET(PacketId), State) of - {keep_state, NewState} -> - AwaitingRel1 = maps:put(PacketId, Packet, AwaitingRel), - {keep_state, NewState#state{awaiting_rel = AwaitingRel1}}; - Stop -> Stop - end. - -ensure_keepalive_timer(State = ?PROPERTY('Server-Keep-Alive', Secs)) -> - ensure_keepalive_timer(timer:seconds(Secs), State#state{keepalive = Secs}); -ensure_keepalive_timer(State = #state{keepalive = 0}) -> - State; -ensure_keepalive_timer(State = #state{keepalive = I}) -> - ensure_keepalive_timer(timer:seconds(I), State). -ensure_keepalive_timer(I, State) when is_integer(I) -> - State#state{keepalive_timer = erlang:start_timer(I, self(), keepalive)}. - -new_call(Id, From) -> - new_call(Id, From, undefined). -new_call(Id, From, Req) -> - #call{id = Id, from = From, req = Req, ts = os:timestamp()}. - -add_call(Call, Data = #state{pending_calls = Calls}) -> - Data#state{pending_calls = [Call | Calls]}. - -take_call(Id, Data = #state{pending_calls = Calls}) -> - case lists:keytake(Id, #call.id, Calls) of - {value, Call, Left} -> - {value, Call, Data#state{pending_calls = Left}}; - false -> false - end. - -timeout_calls(Timeout, Calls) -> - timeout_calls(os:timestamp(), Timeout, Calls). -timeout_calls(Now, Timeout, Calls) -> - lists:foldl(fun(C = #call{from = From, ts = Ts}, Acc) -> - case (timer:now_diff(Now, Ts) div 1000) >= Timeout of - true -> - gen_statem:reply(From, {error, ack_timeout}), - Acc; - false -> [C | Acc] - end - end, [], Calls). - -ensure_ack_timer(State = #state{ack_timer = undefined, - ack_timeout = Timeout, - pending_calls = Calls}) when length(Calls) > 0 -> - State#state{ack_timer = erlang:start_timer(Timeout, self(), ack)}; -ensure_ack_timer(State) -> State. - -ensure_retry_timer(State = #state{retry_interval = Interval}) -> - do_ensure_retry_timer(Interval, State). - -do_ensure_retry_timer(Interval, State = #state{retry_timer = undefined}) - when Interval > 0 -> - State#state{retry_timer = erlang:start_timer(Interval, self(), retry)}; -do_ensure_retry_timer(_Interval, State) -> - State. - -retry_send(State = #state{inflight = Inflight}) -> - SortFun = fun({_, _, Ts1}, {_, _, Ts2}) -> Ts1 < Ts2 end, - Msgs = lists:sort(SortFun, maps:values(Inflight)), - retry_send(Msgs, os:timestamp(), State ). - -retry_send([], _Now, State) -> - {keep_state, ensure_retry_timer(State)}; -retry_send([{Type, Msg, Ts} | Msgs], Now, State = #state{retry_interval = Interval}) -> - Diff = timer:now_diff(Now, Ts) div 1000, %% micro -> ms - case (Diff >= Interval) of - true -> case retry_send(Type, Msg, Now, State) of - {ok, NewState} -> retry_send(Msgs, Now, NewState); - {error, Error} -> {stop, Error} - end; - false -> {keep_state, do_ensure_retry_timer(Interval - Diff, State)} - end. - -retry_send(publish, Msg = #mqtt_msg{qos = QoS, packet_id = PacketId}, - Now, State = #state{inflight = Inflight}) -> - Msg1 = Msg#mqtt_msg{dup = (QoS =:= ?QOS_1)}, - case send(Msg1, State) of - {ok, NewState} -> - Inflight1 = maps:put(PacketId, {publish, Msg1, Now}, Inflight), - {ok, NewState#state{inflight = Inflight1}}; - Error = {error, _Reason} -> - Error - end; -retry_send(pubrel, PacketId, Now, State = #state{inflight = Inflight}) -> - case send(?PUBREL_PACKET(PacketId), State) of - {ok, NewState} -> - Inflight1 = maps:put(PacketId, {pubrel, PacketId, Now}, Inflight), - {ok, NewState#state{inflight = Inflight1}}; - Error = {error, _Reason} -> - Error - end. - -deliver(#mqtt_msg{qos = QoS, dup = Dup, retain = Retain, packet_id = PacketId, - topic = Topic, props = Props, payload = Payload}, - State) -> - Msg = #{qos => QoS, dup => Dup, retain => Retain, packet_id => PacketId, - topic => Topic, properties => Props, payload => Payload, - client_pid => self()}, - ok = eval_msg_handler(State, publish, Msg), - State. - -eval_msg_handler(#state{msg_handler = ?NO_MSG_HDLR, - owner = Owner}, - disconnected, {ReasonCode, Properties}) when is_integer(ReasonCode) -> - %% Special handling for disconnected message when there is no handler callback - Owner ! {disconnected, ReasonCode, Properties}, - ok; -eval_msg_handler(#state{msg_handler = ?NO_MSG_HDLR}, - disconnected, _OtherReason) -> - %% do nothing to be backward compatible - ok; -eval_msg_handler(#state{msg_handler = ?NO_MSG_HDLR, - owner = Owner}, Kind, Msg) -> - Owner ! {Kind, Msg}, - ok; -eval_msg_handler(#state{msg_handler = Handler}, Kind, Msg) -> - F = maps:get(Kind, Handler), - _ = F(Msg), - ok. - -packet_to_msg(#mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - dup = Dup, - qos = QoS, - retain = R}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId, - properties = Props}, - payload = Payload}) -> - #mqtt_msg{qos = QoS, retain = R, dup = Dup, packet_id = PacketId, - topic = Topic, props = Props, payload = Payload}. - -msg_to_packet(#mqtt_msg{qos = QoS, dup = Dup, retain = Retain, packet_id = PacketId, - topic = Topic, props = Props, payload = Payload}) -> - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS, - retain = Retain, - dup = Dup}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId, - properties = Props}, - payload = Payload}. - -%%-------------------------------------------------------------------- -%% Socket Connect/Send - -sock_connect(ConnMod, Hosts, SockOpts, Timeout) -> - sock_connect(ConnMod, Hosts, SockOpts, Timeout, {error, no_hosts}). - -sock_connect(_ConnMod, [], _SockOpts, _Timeout, LastErr) -> - LastErr; -sock_connect(ConnMod, [{Host, Port} | Hosts], SockOpts, Timeout, _LastErr) -> - case ConnMod:connect(Host, Port, SockOpts, Timeout) of - {ok, SockOrPid} -> - {ok, SockOrPid}; - Error = {error, _Reason} -> - sock_connect(ConnMod, Hosts, SockOpts, Timeout, Error) - end. - -hosts(#state{hosts = [], host = Host, port = Port}) -> - [{Host, Port}]; -hosts(#state{hosts = Hosts}) -> Hosts. - -send_puback(Packet, State) -> - case send(Packet, State) of - {ok, NewState} -> {keep_state, NewState}; - {error, Reason} -> {stop, {shutdown, Reason}} - end. - -send(Msg, State) when is_record(Msg, mqtt_msg) -> - send(msg_to_packet(Msg), State); - -send(Packet, State = #state{conn_mod = ConnMod, socket = Sock, proto_ver = Ver}) - when is_record(Packet, mqtt_packet) -> - Data = emqtt_frame:serialize(Packet, Ver), - ?LOG(debug, "SEND Data: ~1000p", [Packet], State), - case ConnMod:send(Sock, Data) of - ok -> {ok, bump_last_packet_id(State)}; - Error -> Error - end. - -run_sock(State = #state{conn_mod = ConnMod, socket = Sock}) -> - ConnMod:setopts(Sock, [{active, once}]), State. - -%%-------------------------------------------------------------------- -%% Process incomming - -process_incoming(<<>>, Packets, State) -> - {keep_state, State, next_events(Packets)}; - -process_incoming(Bytes, Packets, State = #state{parse_state = ParseState}) -> - try emqtt_frame:parse(Bytes, ParseState) of - {ok, Packet, Rest, NParseState} -> - process_incoming(Rest, [Packet|Packets], State#state{parse_state = NParseState}); - {more, NParseState} -> - {keep_state, State#state{parse_state = NParseState}, next_events(Packets)} - catch - error:Error -> {stop, Error} - end. - --compile({inline, [next_events/1]}). -next_events([]) -> []; -next_events([Packet]) -> - {next_event, cast, Packet}; -next_events(Packets) -> - [{next_event, cast, Packet} || Packet <- lists:reverse(Packets)]. - -%%-------------------------------------------------------------------- -%% packet_id generation - -bump_last_packet_id(State = #state{last_packet_id = Id}) -> - State#state{last_packet_id = next_packet_id(Id)}. - --spec next_packet_id(packet_id()) -> packet_id(). -next_packet_id(?MAX_PACKET_ID) -> 1; -next_packet_id(Id) -> Id + 1. - -%%-------------------------------------------------------------------- -%% ReasonCode Name - -reason_code_name(I, Ver) when Ver >= ?MQTT_PROTO_V5 -> - reason_code_name(I); -reason_code_name(0, _Ver) -> connection_acceptd; -reason_code_name(1, _Ver) -> unacceptable_protocol_version; -reason_code_name(2, _Ver) -> client_identifier_not_valid; -reason_code_name(3, _Ver) -> server_unavaliable; -reason_code_name(4, _Ver) -> malformed_username_or_password; -reason_code_name(5, _Ver) -> unauthorized_client; -reason_code_name(_, _Ver) -> unknown_error. - -reason_code_name(16#00) -> success; -reason_code_name(16#01) -> granted_qos1; -reason_code_name(16#02) -> granted_qos2; -reason_code_name(16#04) -> disconnect_with_will_message; -reason_code_name(16#10) -> no_matching_subscribers; -reason_code_name(16#11) -> no_subscription_existed; -reason_code_name(16#18) -> continue_authentication; -reason_code_name(16#19) -> re_authenticate; -reason_code_name(16#80) -> unspecified_error; -reason_code_name(16#81) -> malformed_Packet; -reason_code_name(16#82) -> protocol_error; -reason_code_name(16#83) -> implementation_specific_error; -reason_code_name(16#84) -> unsupported_protocol_version; -reason_code_name(16#85) -> client_identifier_not_valid; -reason_code_name(16#86) -> bad_username_or_password; -reason_code_name(16#87) -> not_authorized; -reason_code_name(16#88) -> server_unavailable; -reason_code_name(16#89) -> server_busy; -reason_code_name(16#8A) -> banned; -reason_code_name(16#8B) -> server_shutting_down; -reason_code_name(16#8C) -> bad_authentication_method; -reason_code_name(16#8D) -> keepalive_timeout; -reason_code_name(16#8E) -> session_taken_over; -reason_code_name(16#8F) -> topic_filter_invalid; -reason_code_name(16#90) -> topic_name_invalid; -reason_code_name(16#91) -> packet_identifier_inuse; -reason_code_name(16#92) -> packet_identifier_not_found; -reason_code_name(16#93) -> receive_maximum_exceeded; -reason_code_name(16#94) -> topic_alias_invalid; -reason_code_name(16#95) -> packet_too_large; -reason_code_name(16#96) -> message_rate_too_high; -reason_code_name(16#97) -> quota_exceeded; -reason_code_name(16#98) -> administrative_action; -reason_code_name(16#99) -> payload_format_invalid; -reason_code_name(16#9A) -> retain_not_supported; -reason_code_name(16#9B) -> qos_not_supported; -reason_code_name(16#9C) -> use_another_server; -reason_code_name(16#9D) -> server_moved; -reason_code_name(16#9E) -> shared_subscriptions_not_supported; -reason_code_name(16#9F) -> connection_rate_exceeded; -reason_code_name(16#A0) -> maximum_connect_time; -reason_code_name(16#A1) -> subscription_identifiers_not_supported; -reason_code_name(16#A2) -> wildcard_subscriptions_not_supported; -reason_code_name(_Code) -> unknown_error. diff --git a/_build/emqx/lib/emqtt/src/emqtt_cli.erl b/_build/emqx/lib/emqtt/src/emqtt_cli.erl deleted file mode 100644 index 95042b1f74..0000000000 --- a/_build/emqx/lib/emqtt/src/emqtt_cli.erl +++ /dev/null @@ -1,327 +0,0 @@ --module(emqtt_cli). - --include("emqtt.hrl"). - --export([ main/1 - ]). - --import(proplists, [get_value/2]). - --define(CMD_NAME, "emqtt"). - --define(HELP_OPT, - [{help, undefined, "help", boolean, - "help information"} - ]). - --define(CONN_SHORT_OPTS, - [{host, $h, "host", {string, "localhost"}, - "mqtt server hostname or IP address"}, - {port, $p, "port", integer, - "mqtt server port number"}, - {iface, $I, "iface", string, - "specify the network interface or ip address to use"}, - {protocol_version, $V, "protocol-version", {atom, 'v5'}, - "mqtt protocol version: v3.1 | v3.1.1 | v5"}, - {username, $u, "username", string, - "username for connecting to server"}, - {password, $P, "password", string, - "password for connecting to server"}, - {clientid, $C, "clientid", string, - "client identifier"}, - {keepalive, $k, "keepalive", {integer, 300}, - "keep alive in seconds"} - ]). - --define(CONN_LONG_OPTS, - [{will_topic, undefined, "will-topic", string, - "topic in will message"}, - {will_payload, undefined, "will-payload", string, - "payload in will message"}, - {will_qos, undefined, "will-qos", {integer, 0}, - "qos in will message"}, - {will_retain, undefined, "will-retain", {boolean, false}, - "retain in will message"}, - {enable_websocket, undefined, "enable-websocket", {boolean, false}, - "enable websocket transport or not"}, - {enable_ssl, undefined, "enable-ssl", {boolean, false}, - "enable ssl/tls or not"}, - {tls_version, undefined, "tls-version", {atom, 'tlsv1.2'}, - "TLS protocol version used when the client connects to the broker"}, - {cafile, undefined, "CAfile", string, - "path to a file containing pem-encoded ca certificates"}, - {cert, undefined, "cert", string, - "path to a file containing the user certificate on pem format"}, - {key, undefined, "key", string, - "path to the file containing the user's private pem-encoded key"} - ]). - --define(PUB_OPTS, ?CONN_SHORT_OPTS ++ - [{topic, $t, "topic", string, - "mqtt topic on which to publish the message"}, - {qos, $q, "qos", {integer, 0}, - "qos level of assurance for delivery of an application message"}, - {retain, $r, "retain", {boolean, false}, - "retain message or not"} - ] ++ ?HELP_OPT ++ ?CONN_LONG_OPTS ++ - [{payload, undefined, "payload", string, - "application message that is being published"}, - {repeat, undefined, "repeat", {integer, 1}, - "the number of times the message will be repeatedly published"}, - {repeat_delay, undefined, "repeat-delay", {integer, 0}, - "the number of seconds to wait after the previous message was delivered before publishing the next"} - ]). - --define(SUB_OPTS, ?CONN_SHORT_OPTS ++ - [{topic, $t, "topic", string, - "mqtt topic to subscribe to"}, - {qos, $q, "qos", {integer, 0}, - "maximum qos level at which the server can send application messages to the client"} - ] ++ ?HELP_OPT ++ ?CONN_LONG_OPTS ++ - [{retain_as_publish, undefined, "retain-as-publish", {boolean, false}, - "retain as publih option in subscription options"}, - {retain_handling, undefined, "retain-handling", {integer, 0}, - "retain handling option in subscription options"} - ]). - -main(["sub" | Argv]) -> - {ok, {Opts, _Args}} = getopt:parse(?SUB_OPTS, Argv), - ok = maybe_help(sub, Opts), - ok = check_required_args(sub, [topic], Opts), - main(sub, Opts); - -main(["pub" | Argv]) -> - {ok, {Opts, _Args}} = getopt:parse(?PUB_OPTS, Argv), - ok = maybe_help(pub, Opts), - ok = check_required_args(pub, [topic, payload], Opts), - main(pub, Opts); - -main(_Argv) -> - io:format("Usage: ~s pub | sub [--help]~n", [?CMD_NAME]). - -main(PubSub, Opts) -> - application:ensure_all_started(emqtt), - NOpts = enrich_opts(parse_cmd_opts(Opts)), - {ok, Client} = emqtt:start_link(NOpts), - ConnRet = case proplists:get_bool(enable_websocket, NOpts) of - true -> emqtt:ws_connect(Client); - false -> emqtt:connect(Client) - end, - case ConnRet of - {ok, Properties} -> - io:format("Client ~s sent CONNECT~n", [get_value(clientid, NOpts)]), - case PubSub of - pub -> - publish(Client, NOpts, proplists:get_value(repeat, Opts)), - disconnect(Client, NOpts); - sub -> - subscribe(Client, NOpts), - KeepAlive = maps:get('Server-Keep-Alive', Properties, get_value(keepalive, NOpts)) * 1000, - timer:send_interval(KeepAlive, ping), - receive_loop(Client) - end; - {error, Reason} -> - io:format("Client ~s failed to sent CONNECT due to ~p~n", [get_value(clientid, NOpts), Reason]) - end. - -publish(Client, Opts, 1) -> - do_publish(Client, Opts); -publish(Client, Opts, Repeat) -> - do_publish(Client, Opts), - case proplists:get_value(repeat_delay, Opts) of - 0 -> ok; - RepeatDelay -> timer:sleep(RepeatDelay * 1000) - end, - publish(Client, Opts, Repeat - 1). - -do_publish(Client, Opts) -> - case emqtt:publish(Client, get_value(topic, Opts), get_value(payload, Opts), Opts) of - {error, Reason} -> - io:format("Client ~s failed to sent PUBLISH due to ~p~n", [get_value(clientid, Opts), Reason]); - {error, _PacketId, Reason} -> - io:format("Client ~s failed to sent PUBLISH due to ~p~n", [get_value(clientid, Opts), Reason]); - _ -> - io:format("Client ~s sent PUBLISH (Q~p, R~p, D0, Topic=~s, Payload=...(~p bytes))~n", - [get_value(clientid, Opts), - get_value(qos, Opts), - i(get_value(retain, Opts)), - get_value(topic, Opts), - length(binary_to_list(get_value(payload, Opts)))]) - end. - -subscribe(Client, Opts) -> - case emqtt:subscribe(Client, get_value(topic, Opts), Opts) of - {ok, _, [ReasonCode]} when 0 =< ReasonCode andalso ReasonCode =< 2 -> - io:format("Client ~s subscribed to ~s~n", [get_value(clientid, Opts), get_value(topic, Opts)]); - {ok, _, [ReasonCode]} -> - io:format("Client ~s failed to subscribe to ~s due to ~s~n", [get_value(clientid, Opts), - get_value(topic, Opts), - emqtt:reason_code_name(ReasonCode)]); - {error, Reason} -> - io:format("Client ~s failed to send SUBSCRIBE due to ~p~n", [get_value(clientid, Opts), Reason]) - end. - -disconnect(Client, Opts) -> - case emqtt:disconnect(Client) of - ok -> - io:format("Client ~s sent DISCONNECT~n", [get_value(clientid, Opts)]); - {error, Reason} -> - io:format("Client ~s failed to send DISCONNECT due to ~p~n", [get_value(clientid, Opts), Reason]) - end. - -maybe_help(PubSub, Opts) -> - case proplists:get_value(help, Opts) of - true -> - usage(PubSub), - halt(0); - _ -> ok - end. - -usage(PubSub) -> - Opts = case PubSub of - pub -> ?PUB_OPTS; - sub -> ?SUB_OPTS - end, - getopt:usage(Opts, ?CMD_NAME ++ " " ++ atom_to_list(PubSub)). - -check_required_args(PubSub, Keys, Opts) -> - lists:foreach(fun(Key) -> - case lists:keyfind(Key, 1, Opts) of - false -> - io:format("Error: '~s' required~n", [Key]), - usage(PubSub), - halt(1); - _ -> ok - end - end, Keys). - -parse_cmd_opts(Opts) -> - parse_cmd_opts(Opts, []). - -parse_cmd_opts([], Acc) -> - Acc; -parse_cmd_opts([{host, Host} | Opts], Acc) -> - parse_cmd_opts(Opts, [{host, Host} | Acc]); -parse_cmd_opts([{port, Port} | Opts], Acc) -> - parse_cmd_opts(Opts, [{port, Port} | Acc]); -parse_cmd_opts([{iface, Interface} | Opts], Acc) -> - NAcc = case inet:parse_address(Interface) of - {ok, IPAddress0} -> - maybe_append(tcp_opts, {ifaddr, IPAddress0}, Acc); - _ -> - case inet:getifaddrs() of - {ok, IfAddrs} -> - case lists:filter(fun({addr, {_, _, _, _}}) -> true; - (_) -> false - end, proplists:get_value(Interface, IfAddrs, [])) of - [{addr, IPAddress0}] -> maybe_append(tcp_opts, {ifaddr, IPAddress0}, Acc); - _ -> Acc - end; - _ -> Acc - end - end, - parse_cmd_opts(Opts, NAcc); -parse_cmd_opts([{protocol_version, 'v3.1'} | Opts], Acc) -> - parse_cmd_opts(Opts, [{proto_ver, v3} | Acc]); -parse_cmd_opts([{protocol_version, 'v3.1.1'} | Opts], Acc) -> - parse_cmd_opts(Opts, [{proto_ver, v4} | Acc]); -parse_cmd_opts([{protocol_version, 'v5'} | Opts], Acc) -> - parse_cmd_opts(Opts, [{proto_ver, v5} | Acc]); -parse_cmd_opts([{username, Username} | Opts], Acc) -> - parse_cmd_opts(Opts, [{username, list_to_binary(Username)} | Acc]); -parse_cmd_opts([{password, Password} | Opts], Acc) -> - parse_cmd_opts(Opts, [{password, list_to_binary(Password)} | Acc]); -parse_cmd_opts([{clientid, Clientid} | Opts], Acc) -> - parse_cmd_opts(Opts, [{clientid, list_to_binary(Clientid)} | Acc]); -parse_cmd_opts([{will_topic, Topic} | Opts], Acc) -> - parse_cmd_opts(Opts, [{will_topic, list_to_binary(Topic)} | Acc]); -parse_cmd_opts([{will_payload, Payload} | Opts], Acc) -> - parse_cmd_opts(Opts, [{will_payload, list_to_binary(Payload)} | Acc]); -parse_cmd_opts([{will_qos, Qos} | Opts], Acc) -> - parse_cmd_opts(Opts, [{will_qos, Qos} | Acc]); -parse_cmd_opts([{will_retain, Retain} | Opts], Acc) -> - parse_cmd_opts(Opts, [{will_retain, Retain} | Acc]); -parse_cmd_opts([{keepalive, I} | Opts], Acc) -> - parse_cmd_opts(Opts, [{keepalive, I} | Acc]); -parse_cmd_opts([{enable_websocket, Enable} | Opts], Acc) -> - parse_cmd_opts(Opts, [{enable_websocket, Enable} | Acc]); -parse_cmd_opts([{enable_ssl, Enable} | Opts], Acc) -> - parse_cmd_opts(Opts, [{ssl, Enable} | Acc]); -parse_cmd_opts([{tls_version, Version} | Opts], Acc) - when Version =:= 'tlsv1' orelse Version =:= 'tlsv1.1'orelse - Version =:= 'tlsv1.2' orelse Version =:= 'tlsv1.3' -> - parse_cmd_opts(Opts, maybe_append(ssl_opts, {versions, [Version]}, Acc)); -parse_cmd_opts([{cafile, CAFile} | Opts], Acc) -> - parse_cmd_opts(Opts, maybe_append(ssl_opts, {cacertfile, CAFile}, Acc)); -parse_cmd_opts([{cert, Cert} | Opts], Acc) -> - parse_cmd_opts(Opts, maybe_append(ssl_opts, {certfile, Cert}, Acc)); -parse_cmd_opts([{key, Key} | Opts], Acc) -> - parse_cmd_opts(Opts, maybe_append(ssl_opts, {keyfile, Key}, Acc)); -parse_cmd_opts([{qos, QoS} | Opts], Acc) -> - parse_cmd_opts(Opts, [{qos, QoS} | Acc]); -parse_cmd_opts([{retain_as_publish, RetainAsPublish} | Opts], Acc) -> - parse_cmd_opts(Opts, [{rap, RetainAsPublish} | Acc]); -parse_cmd_opts([{retain_handling, RetainHandling} | Opts], Acc) -> - parse_cmd_opts(Opts, [{rh, RetainHandling} | Acc]); -parse_cmd_opts([{retain, Retain} | Opts], Acc) -> - parse_cmd_opts(Opts, [{retain, Retain} | Acc]); -parse_cmd_opts([{topic, Topic} | Opts], Acc) -> - parse_cmd_opts(Opts, [{topic, list_to_binary(Topic)} | Acc]); -parse_cmd_opts([{payload, Payload} | Opts], Acc) -> - parse_cmd_opts(Opts, [{payload, list_to_binary(Payload)} | Acc]); -parse_cmd_opts([{repeat, Repeat} | Opts], Acc) -> - parse_cmd_opts(Opts, [{repeat, Repeat} | Acc]); -parse_cmd_opts([{repeat_delay, RepeatDelay} | Opts], Acc) -> - parse_cmd_opts(Opts, [{repeat_delay, RepeatDelay} | Acc]); -parse_cmd_opts([_ | Opts], Acc) -> - parse_cmd_opts(Opts, Acc). - -maybe_append(Key, Value, TupleList) -> - case lists:keytake(Key, 1, TupleList) of - {value, {Key, OldValue}, NewTupleList} -> - [{Key, [Value | OldValue]} | NewTupleList]; - false -> - [{Key, [Value]} | TupleList] - end. - -enrich_opts(Opts) -> - pipeline([fun enrich_clientid_opt/1, - fun enrich_port_opt/1], Opts). - -enrich_clientid_opt(Opts) -> - case lists:keyfind(clientid, 1, Opts) of - false -> [{clientid, emqtt:random_client_id()} | Opts]; - _ -> Opts - end. - -enrich_port_opt(Opts) -> - case proplists:get_value(port, Opts) of - undefined -> - Port = case proplists:get_value(ssl, Opts) of - true -> 8883; - false -> 1883 - end, - [{port, Port} | Opts]; - _ -> Opts - end. - -pipeline([], Input) -> - Input; - -pipeline([Fun|More], Input) -> - pipeline(More, erlang:apply(Fun, [Input])). - -receive_loop(Client) -> - receive - {publish, #{payload := Payload}} -> - io:format("~s~n", [Payload]), - receive_loop(Client); - ping -> - emqtt:ping(Client), - receive_loop(Client); - _Other -> - receive_loop(Client) - end. - -i(true) -> 1; -i(false) -> 0. diff --git a/_build/emqx/lib/emqtt/src/emqtt_frame.erl b/_build/emqx/lib/emqtt/src/emqtt_frame.erl deleted file mode 100644 index 2f3ef6b4e4..0000000000 --- a/_build/emqx/lib/emqtt/src/emqtt_frame.erl +++ /dev/null @@ -1,749 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqtt_frame). - --include("emqtt.hrl"). - --export([ initial_parse_state/0 - , initial_parse_state/1 - ]). - --export([ parse/1 - , parse/2 - , serialize_fun/0 - , serialize_fun/1 - , serialize/1 - , serialize/2 - ]). - --export_type([ options/0 - , parse_state/0 - , parse_result/0 - , serialize_fun/0 - ]). - --type(version() :: ?MQTT_PROTO_V3 - | ?MQTT_PROTO_V4 - | ?MQTT_PROTO_V5). - --type(options() :: #{strict_mode => boolean(), - max_size => 1..?MAX_PACKET_SIZE, - version => version()}). - --opaque(parse_state() :: {none, options()} | cont_fun()). - --opaque(parse_result() :: {more, cont_fun()} - | {ok, #mqtt_packet{}, binary(), parse_state()}). - --type(cont_fun() :: fun((binary()) -> parse_result())). - --type(serialize_fun() :: fun((emqx_types:packet()) -> iodata())). - --define(none(Options), {none, Options}). - --define(DEFAULT_OPTIONS, - #{strict_mode => false, - max_size => ?MAX_PACKET_SIZE, - version => ?MQTT_PROTO_V4 - }). - -%%-------------------------------------------------------------------- -%% Init Parse State -%%-------------------------------------------------------------------- - --spec(initial_parse_state() -> {none, options()}). -initial_parse_state() -> - initial_parse_state(#{}). - --spec(initial_parse_state(options()) -> {none, options()}). -initial_parse_state(Options) when is_map(Options) -> - ?none(merge_opts(Options)). - -%% @pivate -merge_opts(Options) -> - maps:merge(?DEFAULT_OPTIONS, Options). - -%%-------------------------------------------------------------------- -%% Parse MQTT Frame -%%-------------------------------------------------------------------- - --spec(parse(binary()) -> parse_result()). -parse(Bin) -> - parse(Bin, initial_parse_state()). - --spec(parse(binary(), parse_state()) -> parse_result()). -parse(<<>>, {none, Options}) -> - {more, fun(Bin) -> parse(Bin, {none, Options}) end}; -parse(<>, - {none, Options = #{strict_mode := StrictMode}}) -> - %% Validate header if strict mode. - StrictMode andalso validate_header(Type, Dup, QoS, Retain), - Header = #mqtt_packet_header{type = Type, - dup = bool(Dup), - qos = QoS, - retain = bool(Retain) - }, - Header1 = case fixqos(Type, QoS) of - QoS -> Header; - FixedQoS -> Header#mqtt_packet_header{qos = FixedQoS} - end, - parse_remaining_len(Rest, Header1, Options); -parse(Bin, Cont) when is_binary(Bin), is_function(Cont) -> - Cont(Bin). - -parse_remaining_len(<<>>, Header, Options) -> - {more, fun(Bin) -> parse_remaining_len(Bin, Header, Options) end}; -parse_remaining_len(Rest, Header, Options) -> - parse_remaining_len(Rest, Header, 1, 0, Options). - -parse_remaining_len(_Bin, _Header, _Multiplier, Length, #{max_size := MaxSize}) - when Length > MaxSize -> - error(frame_too_large); -parse_remaining_len(<<>>, Header, Multiplier, Length, Options) -> - {more, fun(Bin) -> parse_remaining_len(Bin, Header, Multiplier, Length, Options) end}; -%% Match DISCONNECT without payload -parse_remaining_len(<<0:8, Rest/binary>>, Header = #mqtt_packet_header{type = ?DISCONNECT}, 1, 0, Options) -> - Packet = packet(Header, #mqtt_packet_disconnect{reason_code = ?RC_SUCCESS}), - {ok, Packet, Rest, ?none(Options)}; -%% Match PINGREQ. -parse_remaining_len(<<0:8, Rest/binary>>, Header, 1, 0, Options) -> - parse_frame(Rest, Header, 0, Options); -%% Match PUBACK, PUBREC, PUBREL, PUBCOMP, UNSUBACK... -parse_remaining_len(<<0:1, 2:7, Rest/binary>>, Header, 1, 0, Options) -> - parse_frame(Rest, Header, 2, Options); -parse_remaining_len(<<1:1, Len:7, Rest/binary>>, Header, Multiplier, Value, Options) -> - parse_remaining_len(Rest, Header, Multiplier * ?HIGHBIT, Value + Len * Multiplier, Options); -parse_remaining_len(<<0:1, Len:7, Rest/binary>>, Header, Multiplier, Value, - Options = #{max_size := MaxSize}) -> - FrameLen = Value + Len * Multiplier, - if - FrameLen > MaxSize -> error(frame_too_large); - true -> parse_frame(Rest, Header, FrameLen, Options) - end. - -parse_frame(Bin, Header, 0, Options) -> - {ok, packet(Header), Bin, ?none(Options)}; - -parse_frame(Bin, Header, Length, Options) -> - case Bin of - <> -> - case parse_packet(Header, FrameBin, Options) of - {Variable, Payload} -> - {ok, packet(Header, Variable, Payload), Rest, ?none(Options)}; - Variable = #mqtt_packet_connect{proto_ver = Ver} -> - {ok, packet(Header, Variable), Rest, ?none(Options#{version := Ver})}; - Variable -> - {ok, packet(Header, Variable), Rest, ?none(Options)} - end; - TooShortBin -> - {more, fun(BinMore) -> - parse_frame(<>, Header, Length, Options) - end} - end. - --compile({inline, [packet/1, packet/2, packet/3]}). -packet(Header) -> - #mqtt_packet{header = Header}. -packet(Header, Variable) -> - #mqtt_packet{header = Header, variable = Variable}. -packet(Header, Variable, Payload) -> - #mqtt_packet{header = Header, variable = Variable, payload = Payload}. - -parse_packet(#mqtt_packet_header{type = ?CONNECT}, FrameBin, _Options) -> - {ProtoName, Rest} = parse_utf8_string(FrameBin), - <> = Rest, - % Note: Crash when reserved flag doesn't equal to 0, there is no strict - % compliance with the MQTT5.0. - <> = Rest1, - - {Properties, Rest3} = parse_properties(Rest2, ProtoVer), - {ClientId, Rest4} = parse_utf8_string(Rest3), - ConnPacket = #mqtt_packet_connect{proto_name = ProtoName, - proto_ver = ProtoVer, - is_bridge = (BridgeTag =:= 8), - clean_start = bool(CleanStart), - will_flag = bool(WillFlag), - will_qos = WillQoS, - will_retain = bool(WillRetain), - keepalive = KeepAlive, - properties = Properties, - clientid = ClientId - }, - {ConnPacket1, Rest5} = parse_will_message(ConnPacket, Rest4), - {Username, Rest6} = parse_utf8_string(Rest5, bool(UsernameFlag)), - {Passsword, <<>>} = parse_utf8_string(Rest6, bool(PasswordFlag)), - ConnPacket1#mqtt_packet_connect{username = Username, password = Passsword}; - -parse_packet(#mqtt_packet_header{type = ?CONNACK}, - <>, #{version := Ver}) -> - {Properties, <<>>} = parse_properties(Rest, Ver), - #mqtt_packet_connack{ack_flags = AckFlags, - reason_code = ReasonCode, - properties = Properties - }; - -parse_packet(#mqtt_packet_header{type = ?PUBLISH, qos = QoS}, Bin, - #{strict_mode := StrictMode, version := Ver}) -> - {TopicName, Rest} = parse_utf8_string(Bin), - {PacketId, Rest1} = case QoS of - ?QOS_0 -> {undefined, Rest}; - _ -> parse_packet_id(Rest) - end, - (PacketId =/= undefined) andalso - StrictMode andalso validate_packet_id(PacketId), - {Properties, Payload} = parse_properties(Rest1, Ver), - Publish = #mqtt_packet_publish{topic_name = TopicName, - packet_id = PacketId, - properties = Properties - }, - {Publish, Payload}; - -parse_packet(#mqtt_packet_header{type = PubAck}, <>, #{strict_mode := StrictMode}) - when ?PUBACK =< PubAck, PubAck =< ?PUBCOMP -> - StrictMode andalso validate_packet_id(PacketId), - #mqtt_packet_puback{packet_id = PacketId, reason_code = 0}; - -parse_packet(#mqtt_packet_header{type = PubAck}, <>, - #{strict_mode := StrictMode, version := Ver = ?MQTT_PROTO_V5}) - when ?PUBACK =< PubAck, PubAck =< ?PUBCOMP -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, <<>>} = parse_properties(Rest, Ver), - #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties - }; - -parse_packet(#mqtt_packet_header{type = ?SUBSCRIBE}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - TopicFilters = parse_topic_filters(subscribe, Rest1), - ok = validate_subqos([QoS || {_, #{qos := QoS}} <- TopicFilters]), - #mqtt_packet_subscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters - }; - -parse_packet(#mqtt_packet_header{type = ?SUBACK}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - ReasonCodes = parse_reason_codes(Rest1), - #mqtt_packet_suback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes - }; - -parse_packet(#mqtt_packet_header{type = ?UNSUBSCRIBE}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - TopicFilters = parse_topic_filters(unsubscribe, Rest1), - #mqtt_packet_unsubscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters - }; - -parse_packet(#mqtt_packet_header{type = ?UNSUBACK}, <>, - #{strict_mode := StrictMode}) -> - StrictMode andalso validate_packet_id(PacketId), - #mqtt_packet_unsuback{packet_id = PacketId}; - -parse_packet(#mqtt_packet_header{type = ?UNSUBACK}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - ReasonCodes = parse_reason_codes(Rest1), - #mqtt_packet_unsuback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes - }; - -parse_packet(#mqtt_packet_header{type = ?DISCONNECT}, <>, - #{version := ?MQTT_PROTO_V5}) -> - {Properties, <<>>} = parse_properties(Rest, ?MQTT_PROTO_V5), - #mqtt_packet_disconnect{reason_code = ReasonCode, - properties = Properties - }; - -parse_packet(#mqtt_packet_header{type = ?AUTH}, <>, - #{version := ?MQTT_PROTO_V5}) -> - {Properties, <<>>} = parse_properties(Rest, ?MQTT_PROTO_V5), - #mqtt_packet_auth{reason_code = ReasonCode, properties = Properties}. - -parse_will_message(Packet = #mqtt_packet_connect{will_flag = true, - proto_ver = Ver}, Bin) -> - {Props, Rest} = parse_properties(Bin, Ver), - {Topic, Rest1} = parse_utf8_string(Rest), - {Payload, Rest2} = parse_binary_data(Rest1), - {Packet#mqtt_packet_connect{will_props = Props, - will_topic = Topic, - will_payload = Payload - }, Rest2}; -parse_will_message(Packet, Bin) -> {Packet, Bin}. - --compile({inline, [parse_packet_id/1]}). -parse_packet_id(<>) -> - {PacketId, Rest}. - -parse_properties(Bin, Ver) when Ver =/= ?MQTT_PROTO_V5 -> - {undefined, Bin}; -%% TODO: version mess? -parse_properties(<<>>, ?MQTT_PROTO_V5) -> - {#{}, <<>>}; -parse_properties(<<0, Rest/binary>>, ?MQTT_PROTO_V5) -> - {#{}, Rest}; -parse_properties(Bin, ?MQTT_PROTO_V5) -> - {Len, Rest} = parse_variable_byte_integer(Bin), - <> = Rest, - {parse_property(PropsBin, #{}), Rest1}. - -parse_property(<<>>, Props) -> - Props; -parse_property(<<16#01, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Payload-Format-Indicator' => Val}); -parse_property(<<16#02, Val:32/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Message-Expiry-Interval' => Val}); -parse_property(<<16#03, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Content-Type' => Val}); -parse_property(<<16#08, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Response-Topic' => Val}); -parse_property(<<16#09, Len:16/big, Val:Len/binary, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Correlation-Data' => Val}); -parse_property(<<16#0B, Bin/binary>>, Props) -> - {Val, Rest} = parse_variable_byte_integer(Bin), - parse_property(Rest, Props#{'Subscription-Identifier' => Val}); -parse_property(<<16#11, Val:32/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Session-Expiry-Interval' => Val}); -parse_property(<<16#12, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Assigned-Client-Identifier' => Val}); -parse_property(<<16#13, Val:16, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Server-Keep-Alive' => Val}); -parse_property(<<16#15, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Authentication-Method' => Val}); -parse_property(<<16#16, Len:16/big, Val:Len/binary, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Authentication-Data' => Val}); -parse_property(<<16#17, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Request-Problem-Information' => Val}); -parse_property(<<16#18, Val:32, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Will-Delay-Interval' => Val}); -parse_property(<<16#19, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Request-Response-Information' => Val}); -parse_property(<<16#1A, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Response-Information' => Val}); -parse_property(<<16#1C, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Server-Reference' => Val}); -parse_property(<<16#1F, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Reason-String' => Val}); -parse_property(<<16#21, Val:16/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Receive-Maximum' => Val}); -parse_property(<<16#22, Val:16/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Topic-Alias-Maximum' => Val}); -parse_property(<<16#23, Val:16/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Topic-Alias' => Val}); -parse_property(<<16#24, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Maximum-QoS' => Val}); -parse_property(<<16#25, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Retain-Available' => Val}); -parse_property(<<16#26, Bin/binary>>, Props) -> - {Pair, Rest} = parse_utf8_pair(Bin), - case maps:find('User-Property', Props) of - {ok, UserProps} -> - UserProps1 = lists:append(UserProps, [Pair]), - parse_property(Rest, Props#{'User-Property' := UserProps1}); - error -> - parse_property(Rest, Props#{'User-Property' => [Pair]}) - end; -parse_property(<<16#27, Val:32, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Maximum-Packet-Size' => Val}); -parse_property(<<16#28, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Wildcard-Subscription-Available' => Val}); -parse_property(<<16#29, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Subscription-Identifier-Available' => Val}); -parse_property(<<16#2A, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Shared-Subscription-Available' => Val}). - -parse_variable_byte_integer(Bin) -> - parse_variable_byte_integer(Bin, 1, 0). -parse_variable_byte_integer(<<1:1, Len:7, Rest/binary>>, Multiplier, Value) -> - parse_variable_byte_integer(Rest, Multiplier * ?HIGHBIT, Value + Len * Multiplier); -parse_variable_byte_integer(<<0:1, Len:7, Rest/binary>>, Multiplier, Value) -> - {Value + Len * Multiplier, Rest}. - -parse_topic_filters(subscribe, Bin) -> - [{Topic, #{rh => Rh, rap => Rap, nl => Nl, qos => QoS}} - || <> <= Bin]; - -parse_topic_filters(unsubscribe, Bin) -> - [Topic || <> <= Bin]. - -parse_reason_codes(Bin) -> - [Code || <> <= Bin]. - -parse_utf8_pair(<>) -> - {{Key, Val}, Rest}. - -parse_utf8_string(Bin, false) -> - {undefined, Bin}; -parse_utf8_string(Bin, true) -> - parse_utf8_string(Bin). - -parse_utf8_string(<>) -> - {Str, Rest}. - -parse_binary_data(<>) -> - {Data, Rest}. - -%%-------------------------------------------------------------------- -%% Serialize MQTT Packet -%%-------------------------------------------------------------------- - -serialize_fun() -> serialize_fun(?DEFAULT_OPTIONS). - -serialize_fun(#mqtt_packet_connect{proto_ver = ProtoVer, properties = ConnProps}) -> - MaxSize = get_property('Maximum-Packet-Size', ConnProps, ?MAX_PACKET_SIZE), - serialize_fun(#{version => ProtoVer, max_size => MaxSize}); - -serialize_fun(#{version := Ver, max_size := MaxSize}) -> - fun(Packet) -> - IoData = serialize(Packet, Ver), - case is_too_large(IoData, MaxSize) of - true -> <<>>; - false -> IoData - end - end. - --spec(serialize(#mqtt_packet{}) -> iodata()). -serialize(Packet) -> serialize(Packet, ?MQTT_PROTO_V4). - --spec(serialize(#mqtt_packet{}, version()) -> iodata()). -serialize(#mqtt_packet{header = Header, - variable = Variable, - payload = Payload}, Ver) -> - serialize(Header, serialize_variable(Variable, Ver), serialize_payload(Payload)). - -serialize(#mqtt_packet_header{type = Type, - dup = Dup, - qos = QoS, - retain = Retain - }, VariableBin, PayloadBin) - when ?CONNECT =< Type andalso Type =< ?AUTH -> - Len = iolist_size(VariableBin) + iolist_size(PayloadBin), - [<>, - serialize_remaining_len(Len), VariableBin, PayloadBin]. - -serialize_variable(#mqtt_packet_connect{ - proto_name = ProtoName, - proto_ver = ProtoVer, - is_bridge = IsBridge, - clean_start = CleanStart, - will_flag = WillFlag, - will_qos = WillQoS, - will_retain = WillRetain, - keepalive = KeepAlive, - properties = Properties, - clientid = ClientId, - will_props = WillProps, - will_topic = WillTopic, - will_payload = WillPayload, - username = Username, - password = Password}, _Ver) -> - [serialize_binary_data(ProtoName), - <<(case IsBridge of - true -> 16#80 + ProtoVer; - false -> ProtoVer - end):8, - (flag(Username)):1, - (flag(Password)):1, - (flag(WillRetain)):1, - WillQoS:2, - (flag(WillFlag)):1, - (flag(CleanStart)):1, - 0:1, - KeepAlive:16/big-unsigned-integer>>, - serialize_properties(Properties, ProtoVer), - serialize_utf8_string(ClientId), - case WillFlag of - true -> [serialize_properties(WillProps, ProtoVer), - serialize_utf8_string(WillTopic), - serialize_binary_data(WillPayload)]; - false -> <<>> - end, - serialize_utf8_string(Username, true), - serialize_utf8_string(Password, true)]; - -serialize_variable(#mqtt_packet_connack{ack_flags = AckFlags, - reason_code = ReasonCode, - properties = Properties}, Ver) -> - [AckFlags, ReasonCode, serialize_properties(Properties, Ver)]; - -serialize_variable(#mqtt_packet_publish{topic_name = TopicName, - packet_id = PacketId, - properties = Properties}, Ver) -> - [serialize_utf8_string(TopicName), - if - PacketId =:= undefined -> <<>>; - true -> <> - end, - serialize_properties(Properties, Ver)]; - -serialize_variable(#mqtt_packet_puback{packet_id = PacketId}, Ver) - when Ver == ?MQTT_PROTO_V3; Ver == ?MQTT_PROTO_V4 -> - <>; -serialize_variable(#mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties - }, - Ver = ?MQTT_PROTO_V5) -> - [<>, ReasonCode, - serialize_properties(Properties, Ver)]; - -serialize_variable(#mqtt_packet_subscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_topic_filters(subscribe, TopicFilters, Ver)]; - -serialize_variable(#mqtt_packet_suback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_reason_codes(ReasonCodes)]; - -serialize_variable(#mqtt_packet_unsubscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_topic_filters(unsubscribe, TopicFilters, Ver)]; - -serialize_variable(#mqtt_packet_unsuback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_reason_codes(ReasonCodes)]; - -serialize_variable(#mqtt_packet_disconnect{}, Ver) - when Ver == ?MQTT_PROTO_V3; Ver == ?MQTT_PROTO_V4 -> - <<>>; - -serialize_variable(#mqtt_packet_disconnect{reason_code = ReasonCode, - properties = Properties}, - Ver = ?MQTT_PROTO_V5) -> - [ReasonCode, serialize_properties(Properties, Ver)]; -serialize_variable(#mqtt_packet_disconnect{}, _Ver) -> - <<>>; - -serialize_variable(#mqtt_packet_auth{reason_code = ReasonCode, - properties = Properties}, - Ver = ?MQTT_PROTO_V5) -> - [ReasonCode, serialize_properties(Properties, Ver)]; - -serialize_variable(PacketId, ?MQTT_PROTO_V3) when is_integer(PacketId) -> - <>; -serialize_variable(PacketId, ?MQTT_PROTO_V4) when is_integer(PacketId) -> - <>; -serialize_variable(undefined, _Ver) -> - <<>>. - -serialize_payload(undefined) -> <<>>; -serialize_payload(Bin) -> Bin. - -serialize_properties(_Props, Ver) when Ver =/= ?MQTT_PROTO_V5 -> - <<>>; -serialize_properties(Props, ?MQTT_PROTO_V5) -> - serialize_properties(Props). - -serialize_properties(undefined) -> - <<0>>; -serialize_properties(Props) when map_size(Props) == 0 -> - <<0>>; -serialize_properties(Props) when is_map(Props) -> - Bin = << <<(serialize_property(Prop, Val))/binary>> || {Prop, Val} <- maps:to_list(Props) >>, - [serialize_variable_byte_integer(byte_size(Bin)), Bin]. - -serialize_property(_, undefined) -> - <<>>; -serialize_property('Payload-Format-Indicator', Val) -> - <<16#01, Val>>; -serialize_property('Message-Expiry-Interval', Val) -> - <<16#02, Val:32/big>>; -serialize_property('Content-Type', Val) -> - <<16#03, (serialize_utf8_string(Val))/binary>>; -serialize_property('Response-Topic', Val) -> - <<16#08, (serialize_utf8_string(Val))/binary>>; -serialize_property('Correlation-Data', Val) -> - <<16#09, (byte_size(Val)):16, Val/binary>>; -serialize_property('Subscription-Identifier', Val) -> - <<16#0B, (serialize_variable_byte_integer(Val))/binary>>; -serialize_property('Session-Expiry-Interval', Val) -> - <<16#11, Val:32/big>>; -serialize_property('Assigned-Client-Identifier', Val) -> - <<16#12, (serialize_utf8_string(Val))/binary>>; -serialize_property('Server-Keep-Alive', Val) -> - <<16#13, Val:16/big>>; -serialize_property('Authentication-Method', Val) -> - <<16#15, (serialize_utf8_string(Val))/binary>>; -serialize_property('Authentication-Data', Val) -> - <<16#16, (iolist_size(Val)):16, Val/binary>>; -serialize_property('Request-Problem-Information', Val) -> - <<16#17, Val>>; -serialize_property('Will-Delay-Interval', Val) -> - <<16#18, Val:32/big>>; -serialize_property('Request-Response-Information', Val) -> - <<16#19, Val>>; -serialize_property('Response-Information', Val) -> - <<16#1A, (serialize_utf8_string(Val))/binary>>; -serialize_property('Server-Reference', Val) -> - <<16#1C, (serialize_utf8_string(Val))/binary>>; -serialize_property('Reason-String', Val) -> - <<16#1F, (serialize_utf8_string(Val))/binary>>; -serialize_property('Receive-Maximum', Val) -> - <<16#21, Val:16/big>>; -serialize_property('Topic-Alias-Maximum', Val) -> - <<16#22, Val:16/big>>; -serialize_property('Topic-Alias', Val) -> - <<16#23, Val:16/big>>; -serialize_property('Maximum-QoS', Val) -> - <<16#24, Val>>; -serialize_property('Retain-Available', Val) -> - <<16#25, Val>>; -serialize_property('User-Property', {Key, Val}) -> - <<16#26, (serialize_utf8_pair({Key, Val}))/binary>>; -serialize_property('User-Property', Props) when is_list(Props) -> - << <<(serialize_property('User-Property', {Key, Val}))/binary>> - || {Key, Val} <- Props >>; -serialize_property('Maximum-Packet-Size', Val) -> - <<16#27, Val:32/big>>; -serialize_property('Wildcard-Subscription-Available', Val) -> - <<16#28, Val>>; -serialize_property('Subscription-Identifier-Available', Val) -> - <<16#29, Val>>; -serialize_property('Shared-Subscription-Available', Val) -> - <<16#2A, Val>>. - -serialize_topic_filters(subscribe, TopicFilters, ?MQTT_PROTO_V5) -> - << <<(serialize_utf8_string(Topic))/binary, - ?RESERVED:2, Rh:2, (flag(Rap)):1,(flag(Nl)):1, QoS:2 >> - || {Topic, #{rh := Rh, rap := Rap, nl := Nl, qos := QoS}} <- TopicFilters >>; - -serialize_topic_filters(subscribe, TopicFilters, _Ver) -> - << <<(serialize_utf8_string(Topic))/binary, ?RESERVED:6, QoS:2>> - || {Topic, #{qos := QoS}} <- TopicFilters >>; - -serialize_topic_filters(unsubscribe, TopicFilters, _Ver) -> - << <<(serialize_utf8_string(Topic))/binary>> || Topic <- TopicFilters >>. - -serialize_reason_codes(undefined) -> - <<>>; -serialize_reason_codes(ReasonCodes) when is_list(ReasonCodes) -> - << <> || Code <- ReasonCodes >>. - -serialize_utf8_pair({Name, Value}) -> - << (serialize_utf8_string(Name))/binary, (serialize_utf8_string(Value))/binary >>. - -serialize_binary_data(Bin) -> - [<<(byte_size(Bin)):16/big-unsigned-integer>>, Bin]. - -serialize_utf8_string(undefined, false) -> - error(utf8_string_undefined); -serialize_utf8_string(undefined, true) -> - <<>>; -serialize_utf8_string(String, _AllowNull) -> - serialize_utf8_string(String). - -serialize_utf8_string(String) -> - StringBin = unicode:characters_to_binary(String), - Len = byte_size(StringBin), - true = (Len =< 16#ffff), - <>. - -serialize_remaining_len(I) -> - serialize_variable_byte_integer(I). - -serialize_variable_byte_integer(N) when N =< ?LOWBITS -> - <<0:1, N:7>>; -serialize_variable_byte_integer(N) -> - <<1:1, (N rem ?HIGHBIT):7, (serialize_variable_byte_integer(N div ?HIGHBIT))/binary>>. - -%% Is the frame too large? --spec(is_too_large(iodata(), pos_integer()) -> boolean()). -is_too_large(IoData, MaxSize) -> - iolist_size(IoData) >= MaxSize. - -get_property(_Key, undefined, Default) -> - Default; -get_property(Key, Props, Default) -> - maps:get(Key, Props, Default). - -%% Validate header if sctrict mode. See: mqtt-v5.0: 2.1.3 Flags -validate_header(?CONNECT, 0, 0, 0) -> ok; -validate_header(?CONNACK, 0, 0, 0) -> ok; -validate_header(?PUBLISH, 0, ?QOS_0, _) -> ok; -validate_header(?PUBLISH, _, ?QOS_1, _) -> ok; -validate_header(?PUBLISH, 0, ?QOS_2, _) -> ok; -validate_header(?PUBACK, 0, 0, 0) -> ok; -validate_header(?PUBREC, 0, 0, 0) -> ok; -validate_header(?PUBREL, 0, 1, 0) -> ok; -validate_header(?PUBCOMP, 0, 0, 0) -> ok; -validate_header(?SUBSCRIBE, 0, 1, 0) -> ok; -validate_header(?SUBACK, 0, 0, 0) -> ok; -validate_header(?UNSUBSCRIBE, 0, 1, 0) -> ok; -validate_header(?UNSUBACK, 0, 0, 0) -> ok; -validate_header(?PINGREQ, 0, 0, 0) -> ok; -validate_header(?PINGRESP, 0, 0, 0) -> ok; -validate_header(?DISCONNECT, 0, 0, 0) -> ok; -validate_header(?AUTH, 0, 0, 0) -> ok; -validate_header(_Type, _Dup, _QoS, _Rt) -> error(bad_frame_header). - --compile({inline, [validate_packet_id/1]}). -validate_packet_id(0) -> error(bad_packet_id); -validate_packet_id(_) -> ok. - -validate_subqos([3|_]) -> error(bad_subqos); -validate_subqos([_|T]) -> validate_subqos(T); -validate_subqos([]) -> ok. - -bool(0) -> false; -bool(1) -> true. - -flag(undefined) -> ?RESERVED; -flag(false) -> 0; -flag(true) -> 1; -flag(X) when is_integer(X) -> X; -flag(B) when is_binary(B) -> 1. - -fixqos(?PUBREL, 0) -> 1; -fixqos(?SUBSCRIBE, 0) -> 1; -fixqos(?UNSUBSCRIBE, 0) -> 1; -fixqos(_Type, QoS) -> QoS. - diff --git a/_build/emqx/lib/emqtt/src/emqtt_props.erl b/_build/emqx/lib/emqtt/src/emqtt_props.erl deleted file mode 100644 index d0f3089b16..0000000000 --- a/_build/emqx/lib/emqtt/src/emqtt_props.erl +++ /dev/null @@ -1,176 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc MQTT5 Properties --module(emqtt_props). - --include("emqtt.hrl"). - --export([ id/1 - , name/1 - , filter/2 - , validate/1 - ]). - -%% For tests --export([all/0]). - --type(prop_name() :: atom()). --type(prop_id() :: pos_integer()). - --define(PROPS_TABLE, - #{16#01 => {'Payload-Format-Indicator', 'Byte', [?PUBLISH]}, - 16#02 => {'Message-Expiry-Interval', 'Four-Byte-Integer', [?PUBLISH]}, - 16#03 => {'Content-Type', 'UTF8-Encoded-String', [?PUBLISH]}, - 16#08 => {'Response-Topic', 'UTF8-Encoded-String', [?PUBLISH]}, - 16#09 => {'Correlation-Data', 'Binary-Data', [?PUBLISH]}, - 16#0B => {'Subscription-Identifier', 'Variable-Byte-Integer', [?PUBLISH, ?SUBSCRIBE]}, - 16#11 => {'Session-Expiry-Interval', 'Four-Byte-Integer', [?CONNECT, ?CONNACK, ?DISCONNECT]}, - 16#12 => {'Assigned-Client-Identifier', 'UTF8-Encoded-String', [?CONNACK]}, - 16#13 => {'Server-Keep-Alive', 'Two-Byte-Integer', [?CONNACK]}, - 16#15 => {'Authentication-Method', 'UTF8-Encoded-String', [?CONNECT, ?CONNACK, ?AUTH]}, - 16#16 => {'Authentication-Data', 'Binary-Data', [?CONNECT, ?CONNACK, ?AUTH]}, - 16#17 => {'Request-Problem-Information', 'Byte', [?CONNECT]}, - 16#18 => {'Will-Delay-Interval', 'Four-Byte-Integer', ['WILL']}, - 16#19 => {'Request-Response-Information', 'Byte', [?CONNECT]}, - 16#1A => {'Response-Information', 'UTF8-Encoded-String', [?CONNACK]}, - 16#1C => {'Server-Reference', 'UTF8-Encoded-String', [?CONNACK, ?DISCONNECT]}, - 16#1F => {'Reason-String', 'UTF8-Encoded-String', [?CONNACK, ?DISCONNECT, ?PUBACK, - ?PUBREC, ?PUBREL, ?PUBCOMP, - ?SUBACK, ?UNSUBACK, ?AUTH]}, - 16#21 => {'Receive-Maximum', 'Two-Byte-Integer', [?CONNECT, ?CONNACK]}, - 16#22 => {'Topic-Alias-Maximum', 'Two-Byte-Integer', [?CONNECT, ?CONNACK]}, - 16#23 => {'Topic-Alias', 'Two-Byte-Integer', [?PUBLISH]}, - 16#24 => {'Maximum-QoS', 'Byte', [?CONNACK]}, - 16#25 => {'Retain-Available', 'Byte', [?CONNACK]}, - 16#26 => {'User-Property', 'UTF8-String-Pair', 'ALL'}, - 16#27 => {'Maximum-Packet-Size', 'Four-Byte-Integer', [?CONNECT, ?CONNACK]}, - 16#28 => {'Wildcard-Subscription-Available', 'Byte', [?CONNACK]}, - 16#29 => {'Subscription-Identifier-Available', 'Byte', [?CONNACK]}, - 16#2A => {'Shared-Subscription-Available', 'Byte', [?CONNACK]} - }). - --spec(id(prop_name()) -> prop_id()). -id('Payload-Format-Indicator') -> 16#01; -id('Message-Expiry-Interval') -> 16#02; -id('Content-Type') -> 16#03; -id('Response-Topic') -> 16#08; -id('Correlation-Data') -> 16#09; -id('Subscription-Identifier') -> 16#0B; -id('Session-Expiry-Interval') -> 16#11; -id('Assigned-Client-Identifier') -> 16#12; -id('Server-Keep-Alive') -> 16#13; -id('Authentication-Method') -> 16#15; -id('Authentication-Data') -> 16#16; -id('Request-Problem-Information') -> 16#17; -id('Will-Delay-Interval') -> 16#18; -id('Request-Response-Information') -> 16#19; -id('Response-Information') -> 16#1A; -id('Server-Reference') -> 16#1C; -id('Reason-String') -> 16#1F; -id('Receive-Maximum') -> 16#21; -id('Topic-Alias-Maximum') -> 16#22; -id('Topic-Alias') -> 16#23; -id('Maximum-QoS') -> 16#24; -id('Retain-Available') -> 16#25; -id('User-Property') -> 16#26; -id('Maximum-Packet-Size') -> 16#27; -id('Wildcard-Subscription-Available') -> 16#28; -id('Subscription-Identifier-Available') -> 16#29; -id('Shared-Subscription-Available') -> 16#2A; -id(Name) -> error({bad_property, Name}). - --spec(name(prop_id()) -> prop_name()). -name(16#01) -> 'Payload-Format-Indicator'; -name(16#02) -> 'Message-Expiry-Interval'; -name(16#03) -> 'Content-Type'; -name(16#08) -> 'Response-Topic'; -name(16#09) -> 'Correlation-Data'; -name(16#0B) -> 'Subscription-Identifier'; -name(16#11) -> 'Session-Expiry-Interval'; -name(16#12) -> 'Assigned-Client-Identifier'; -name(16#13) -> 'Server-Keep-Alive'; -name(16#15) -> 'Authentication-Method'; -name(16#16) -> 'Authentication-Data'; -name(16#17) -> 'Request-Problem-Information'; -name(16#18) -> 'Will-Delay-Interval'; -name(16#19) -> 'Request-Response-Information'; -name(16#1A) -> 'Response-Information'; -name(16#1C) -> 'Server-Reference'; -name(16#1F) -> 'Reason-String'; -name(16#21) -> 'Receive-Maximum'; -name(16#22) -> 'Topic-Alias-Maximum'; -name(16#23) -> 'Topic-Alias'; -name(16#24) -> 'Maximum-QoS'; -name(16#25) -> 'Retain-Available'; -name(16#26) -> 'User-Property'; -name(16#27) -> 'Maximum-Packet-Size'; -name(16#28) -> 'Wildcard-Subscription-Available'; -name(16#29) -> 'Subscription-Identifier-Available'; -name(16#2A) -> 'Shared-Subscription-Available'; -name(Id) -> error({unsupported_property, Id}). - -filter(PacketType, Props) when is_map(Props) -> - maps:from_list(filter(PacketType, maps:to_list(Props))); - -filter(PacketType, Props) when ?CONNECT =< PacketType, PacketType =< ?AUTH, is_list(Props) -> - Filter = fun(Name) -> - case maps:find(id(Name), ?PROPS_TABLE) of - {ok, {Name, _Type, 'ALL'}} -> - true; - {ok, {Name, _Type, AllowedTypes}} -> - lists:member(PacketType, AllowedTypes); - error -> false - end - end, - [Prop || Prop = {Name, _} <- Props, Filter(Name)]. - -validate(Props) when is_map(Props) -> - lists:foreach(fun validate_prop/1, maps:to_list(Props)). - -validate_prop(Prop = {Name, Val}) -> - case maps:find(id(Name), ?PROPS_TABLE) of - {ok, {Name, Type, _}} -> - validate_value(Type, Val) - orelse error(bad_property, Prop); - error -> - error({bad_property, Prop}) - end. - -validate_value('Byte', Val) -> - is_integer(Val) andalso Val =< 16#FF; -validate_value('Two-Byte-Integer', Val) -> - is_integer(Val) andalso 0 =< Val andalso Val =< 16#FFFF; -validate_value('Four-Byte-Integer', Val) -> - is_integer(Val) andalso 0 =< Val andalso Val =< 16#FFFFFFFF; -validate_value('Variable-Byte-Integer', Val) -> - is_integer(Val) andalso 0 =< Val andalso Val =< 16#7FFFFFFF; -validate_value('UTF8-String-Pair', {Name, Val}) -> - validate_value('UTF8-Encoded-String', Name) - andalso validate_value('UTF8-Encoded-String', Val); -validate_value('UTF8-String-Pair', Pairs) when is_list(Pairs) -> - lists:foldl(fun(Pair, OK) -> - OK andalso validate_value('UTF8-String-Pair', Pair) - end, true, Pairs); -validate_value('UTF8-Encoded-String', Val) -> - is_binary(Val); -validate_value('Binary-Data', Val) -> - is_binary(Val); -validate_value(_Type, _Val) -> false. - --spec(all() -> map()). -all() -> ?PROPS_TABLE. - diff --git a/_build/emqx/lib/emqtt/src/emqtt_sock.erl b/_build/emqx/lib/emqtt/src/emqtt_sock.erl deleted file mode 100644 index 8de3c35baa..0000000000 --- a/_build/emqx/lib/emqtt/src/emqtt_sock.erl +++ /dev/null @@ -1,127 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqtt_sock). - --export([ connect/4 - , send/2 - , recv/2 - , close/1 - ]). - --export([ sockname/1 - , setopts/2 - , getstat/2 - ]). - --record(ssl_socket, {tcp, ssl}). - --type(socket() :: inet:socket() | #ssl_socket{}). - --type(sockname() :: {inet:ip_address(), inet:port_number()}). - --type(option() :: gen_tcp:connect_option() | {ssl_opts, [ssl:ssl_option()]}). - --export_type([socket/0, option/0]). - --define(DEFAULT_TCP_OPTIONS, [binary, {packet, raw}, {active, false}, - {nodelay, true}, {reuseaddr, true}]). - --spec(connect(inet:ip_address() | inet:hostname(), - inet:port_number(), [option()], timeout()) - -> {ok, socket()} | {error, term()}). -connect(Host, Port, SockOpts, Timeout) -> - TcpOpts = merge_opts(?DEFAULT_TCP_OPTIONS, - lists:keydelete(ssl_opts, 1, SockOpts)), - case gen_tcp:connect(Host, Port, TcpOpts, Timeout) of - {ok, Sock} -> - case lists:keyfind(ssl_opts, 1, SockOpts) of - {ssl_opts, SslOpts} -> - ssl_upgrade(Sock, SslOpts, Timeout); - false -> {ok, Sock} - end; - {error, Reason} -> - {error, Reason} - end. - -ssl_upgrade(Sock, SslOpts, Timeout) -> - TlsVersions = proplists:get_value(versions, SslOpts, []), - Ciphers = proplists:get_value(ciphers, SslOpts, default_ciphers(TlsVersions)), - SslOpts2 = merge_opts(SslOpts, [{ciphers, Ciphers}]), - case ssl:connect(Sock, SslOpts2, Timeout) of - {ok, SslSock} -> - ok = ssl:controlling_process(SslSock, self()), - {ok, #ssl_socket{tcp = Sock, ssl = SslSock}}; - {error, Reason} -> {error, Reason} - end. - --spec(send(socket(), iodata()) -> ok | {error, einval | closed}). -send(Sock, Data) when is_port(Sock) -> - try erlang:port_command(Sock, Data) of - true -> ok - catch - error:badarg -> {error, einval} - end; -send(#ssl_socket{ssl = SslSock}, Data) -> - ssl:send(SslSock, Data). - --spec(recv(socket(), non_neg_integer()) - -> {ok, iodata()} | {error, closed | inet:posix()}). -recv(Sock, Length) when is_port(Sock) -> - gen_tcp:recv(Sock, Length); -recv(#ssl_socket{ssl = SslSock}, Length) -> - ssl:recv(SslSock, Length). - --spec(close(socket()) -> ok). -close(Sock) when is_port(Sock) -> - gen_tcp:close(Sock); -close(#ssl_socket{ssl = SslSock}) -> - ssl:close(SslSock). - --spec(setopts(socket(), [gen_tcp:option() | ssl:socketoption()]) -> ok). -setopts(Sock, Opts) when is_port(Sock) -> - inet:setopts(Sock, Opts); -setopts(#ssl_socket{ssl = SslSock}, Opts) -> - ssl:setopts(SslSock, Opts). - --spec(getstat(socket(), [atom()]) - -> {ok, [{atom(), integer()}]} | {error, term()}). -getstat(Sock, Options) when is_port(Sock) -> - inet:getstat(Sock, Options); -getstat(#ssl_socket{tcp = Sock}, Options) -> - inet:getstat(Sock, Options). - --spec(sockname(socket()) -> {ok, sockname()} | {error, term()}). -sockname(Sock) when is_port(Sock) -> - inet:sockname(Sock); -sockname(#ssl_socket{ssl = SslSock}) -> - ssl:sockname(SslSock). - --spec(merge_opts(list(), list()) -> list()). -merge_opts(Defaults, Options) -> - lists:foldl( - fun({Opt, Val}, Acc) -> - lists:keystore(Opt, 1, Acc, {Opt, Val}); - (Opt, Acc) -> - lists:usort([Opt | Acc]) - end, Defaults, Options). - -default_ciphers(TlsVersions) -> - lists:foldl( - fun(TlsVer, Ciphers) -> - Ciphers ++ ssl:cipher_suites(all, TlsVer) - end, [], TlsVersions). - diff --git a/_build/emqx/lib/emqtt/src/emqtt_ws.erl b/_build/emqx/lib/emqtt/src/emqtt_ws.erl deleted file mode 100644 index 4bae30199b..0000000000 --- a/_build/emqx/lib/emqtt/src/emqtt_ws.erl +++ /dev/null @@ -1,87 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqtt_ws). - --export([ connect/4 - , send/2 - , close/1 - ]). - --export([ setopts/2 - , getstat/2 - ]). - --type(option() :: {ws_path, string()}). - --export_type([option/0]). - --define(WS_OPTS, #{compress => false, - protocols => [{<<"mqtt">>, gun_ws_h}] - }). - --define(WS_HEADERS, [{"cache-control", "no-cache"}]). - -connect(Host, Port, Opts, Timeout) -> - {ok, _} = application:ensure_all_started(gun), - %% 1. open connection - ConnOpts = #{connect_timeout => Timeout, - retry => 3, - retry_timeout => 30000 - }, - case gun:open(Host, Port, ConnOpts) of - {ok, ConnPid} -> - {ok, _} = gun:await_up(ConnPid, Timeout), - case upgrade(ConnPid, Opts, Timeout) of - {ok, _Headers} -> {ok, ConnPid}; - Error -> Error - end; - Error -> Error - end. - --spec(upgrade(pid(), list(), timeout()) - -> {ok, Headers :: list()} | {error, Reason :: term()}). -upgrade(ConnPid, Opts, Timeout) -> - %% 2. websocket upgrade - Path = proplists:get_value(ws_path, Opts, "/mqtt"), - StreamRef = gun:ws_upgrade(ConnPid, Path, ?WS_HEADERS, ?WS_OPTS), - receive - {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], Headers} -> - {ok, Headers}; - {gun_response, ConnPid, _, _, Status, Headers} -> - {error, {ws_upgrade_failed, Status, Headers}}; - {gun_error, ConnPid, StreamRef, Reason} -> - {error, {ws_upgrade_failed, Reason}} - after Timeout -> - {error, timeout} - end. - -%% fake stats:) -getstat(_WsPid, Options) -> - {ok, [{Opt, 0} || Opt <- Options]}. - -setopts(_WsPid, _Opts) -> - ok. - --spec(send(pid(), iodata()) -> ok). -send(WsPid, Data) -> - gun:ws_send(WsPid, {binary, Data}). - --spec(close(pid()) -> ok). -close(WsPid) -> - gun:shutdown(WsPid). - - diff --git a/_build/emqx/lib/emqtt/vars-pkg.config b/_build/emqx/lib/emqtt/vars-pkg.config deleted file mode 100644 index ad936fc5e3..0000000000 --- a/_build/emqx/lib/emqtt/vars-pkg.config +++ /dev/null @@ -1,5 +0,0 @@ -%% -%% bin/emqtt -%% -{runner_root_dir, "/usr/lib/emqtt"}. -{runner_bin_dir, "/usr/bin"}. diff --git a/_build/emqx/lib/emqx/.editorconfig b/_build/emqx/lib/emqx/.editorconfig deleted file mode 100644 index c563aa10d7..0000000000 --- a/_build/emqx/lib/emqx/.editorconfig +++ /dev/null @@ -1,27 +0,0 @@ -# EditorConfig is awesome: https://EditorConfig.org - -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -charset = utf-8 -end_of_line = lf -trim_trailing_whitespace = true -insert_final_newline = true - - -# Matches multiple files with brace expansion notation -# Set default charset -[*.{erl, src, hrl}] -indent_style = space -indent_size = 4 - -# Tab indentation (no size specified) -[Makefile] -indent_style = tab - -# Matches the exact files either package.json or .travis.yml -[{.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE.md b/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f28160c509..0000000000 --- a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,10 +0,0 @@ -#### Environment - -- OS: -- Erlang/OTP: -- EMQ: - -#### Description - -*A description of the issue* - diff --git a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/bug-report.md b/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/bug-report.md deleted file mode 100644 index 0258866dd6..0000000000 --- a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/bug-report.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: Bug Report -about: Create a report to help us improve -title: '' -labels: Support -assignees: tigercl - ---- - - - - -**Environment**: - -- EMQ X version (e.g. `emqx_ctl status`): -- Hardware configuration (e.g. `lscpu`): -- OS (e.g. `cat /etc/os-release`): -- Kernel (e.g. `uname -a`): -- Erlang/OTP version (in case you build emqx from source code): -- Others: - -**What happened and what you expected to happen**: - -**How to reproduce it (as minimally and precisely as possible)**: - -**Anything else we need to know?**: diff --git a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/feature-request.md b/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/feature-request.md deleted file mode 100644 index 67b1dfa828..0000000000 --- a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/feature-request.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -name: Feature Request -about: Suggest an idea for this project -title: '' -labels: Feature -assignees: tigercl - ---- - - - -**What would you like to be added/modified**: - -**Why is this needed**: diff --git a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/support-needed.md b/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/support-needed.md deleted file mode 100644 index 80b494077b..0000000000 --- a/_build/emqx/lib/emqx/.github/ISSUE_TEMPLATE/support-needed.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: Support Needed -about: Asking a question about usages, docs or anything you're insterested in -title: '' -labels: Support -assignees: tigercl - ---- - -**Please describe your problem in detail, if necessary, you can upload the log file through the attachment**: diff --git a/_build/emqx/lib/emqx/.github/weekly-digest.yml b/_build/emqx/lib/emqx/.github/weekly-digest.yml deleted file mode 100644 index 7197467d0e..0000000000 --- a/_build/emqx/lib/emqx/.github/weekly-digest.yml +++ /dev/null @@ -1,7 +0,0 @@ -# Configuration for weekly-digest - https://hub.fastgit.org/apps/weekly-digest -publishDay: monday -canPublishIssues: true -canPublishPullRequests: true -canPublishContributors: true -canPublishStargazers: true -canPublishCommits: true diff --git a/_build/emqx/lib/emqx/.github/workflows/run_test_case.yaml b/_build/emqx/lib/emqx/.github/workflows/run_test_case.yaml deleted file mode 100644 index ef49d86967..0000000000 --- a/_build/emqx/lib/emqx/.github/workflows/run_test_case.yaml +++ /dev/null @@ -1,41 +0,0 @@ -name: Run test case - -on: [push, pull_request] - -jobs: - - run_test_case: - - runs-on: ubuntu-latest - - container: - image: erlang:22.1 - - steps: - - uses: actions/checkout@v1 - - name: Code dialyzer - run: | - make xref - make dialyzer - rm -f rebar.lock - - name: Run tests - run: | - make eunit - rm -f rebar.lock - make ct - rm -f rebar.lock - make cover - - name: Coveralls - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - make coveralls - - uses: actions/upload-artifact@v1 - if: always() - with: - name: logs - path: _build/test/logs - - uses: actions/upload-artifact@v1 - with: - name: cover - path: _build/test/cover diff --git a/_build/emqx/lib/emqx/.gitignore b/_build/emqx/lib/emqx/.gitignore deleted file mode 100644 index aaec950d46..0000000000 --- a/_build/emqx/lib/emqx/.gitignore +++ /dev/null @@ -1,43 +0,0 @@ -.eunit -deps -!deps/.placeholder -*.o -*.beam -*.plt -erl_crash.dump -ebin -!ebin/.placeholder -.concrete/DEV_MODE -.rebar -test/ebin/*.beam -.exrc -plugins/*/ebin -log/ -*.swp -*.so -.erlang.mk/ -cover/ -emqx.d -eunit.coverdata -test/ct.cover.spec -logs -ct.coverdata -.idea/ -emqx.iml -_rel/ -data/ -_build -.rebar3 -rebar3.crashdump -.DS_Store -emqx.iml -bbmustache/ -etc/gen.emqx.conf -compile_commands.json -cuttlefish -rebar.lock -xrefr -erlang.mk -*.coverdata -etc/emqx.conf.rendered -Mnesia.*/ diff --git a/_build/emqx/lib/emqx/LICENSE b/_build/emqx/lib/emqx/LICENSE deleted file mode 100644 index 8dada3edaf..0000000000 --- a/_build/emqx/lib/emqx/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/_build/emqx/lib/emqx/Makefile b/_build/emqx/lib/emqx/Makefile deleted file mode 100644 index 853a3d5b91..0000000000 --- a/_build/emqx/lib/emqx/Makefile +++ /dev/null @@ -1,139 +0,0 @@ -## shallow clone for speed - -REBAR_GIT_CLONE_OPTIONS += --depth 1 -export REBAR_GIT_CLONE_OPTIONS - -SUITES_FILES := $(shell find test -name '*_SUITE.erl' | sort) - -CT_SUITES := $(foreach value,$(SUITES_FILES),$(shell val=$$(basename $(value) .erl); echo $${val%_*})) - -CT_NODE_NAME = emqxct@127.0.0.1 - -RUN_NODE_NAME = emqxdebug@127.0.0.1 - -.PHONY: all -all: compile - -.PHONY: tests -tests: eunit ct - -.PHONY: run -run: run_setup unlock - @rebar3 as test get-deps - @rebar3 as test auto --name $(RUN_NODE_NAME) --script scripts/run_emqx.escript - -.PHONY: run_setup -run_setup: - @erl -noshell -eval \ - "{ok, [[HOME]]} = init:get_argument(home), \ - FilePath = HOME ++ \"/.config/rebar3/rebar.config\", \ - case file:consult(FilePath) of \ - {ok, Term} -> \ - NewTerm = case lists:keyfind(plugins, 1, Term) of \ - false -> [{plugins, [rebar3_auto]} | Term]; \ - {plugins, OldPlugins} -> \ - NewPlugins0 = OldPlugins -- [rebar3_auto], \ - NewPlugins = [rebar3_auto | NewPlugins0], \ - lists:keyreplace(plugins, 1, Term, {plugins, NewPlugins}) \ - end, \ - ok = file:write_file(FilePath, [io_lib:format(\"~p.\n\", [I]) || I <- NewTerm]); \ - _Enoent -> \ - os:cmd(\"mkdir -p ~/.config/rebar3/ \"), \ - NewTerm=[{plugins, [rebar3_auto]}], \ - ok = file:write_file(FilePath, [io_lib:format(\"~p.\n\", [I]) || I <- NewTerm]) \ - end, \ - halt(0)." - -.PHONY: shell -shell: - @rebar3 as test auto - -compile: unlock - @rebar3 compile - -unlock: - @rebar3 unlock - -clean: distclean - -## Cuttlefish escript is built by default when cuttlefish app (as dependency) was built -CUTTLEFISH_SCRIPT := _build/default/lib/cuttlefish/cuttlefish - -.PHONY: cover -cover: - @rebar3 cover - -.PHONY: coveralls -coveralls: - @rebar3 as test coveralls send - -.PHONY: xref -xref: - @rebar3 xref - -.PHONY: dialyzer -dialyzer: - @rebar3 dialyzer - -.PHONY: proper -proper: - @rebar3 proper -d test/props -c - -.PHONY: deps -deps: - @rebar3 get-deps - -.PHONY: eunit -eunit: - @rebar3 eunit -v - -.PHONY: ct_setup -ct_setup: - rebar3 as test compile - @mkdir -p data - @if [ ! -f data/loaded_plugins ]; then touch data/loaded_plugins; fi - @ln -s -f '../../../../etc' _build/test/lib/emqx/ - @ln -s -f '../../../../data' _build/test/lib/emqx/ - -.PHONY: ct -ct: ct_setup - @rebar3 ct -v --name $(CT_NODE_NAME) --suite=$(shell echo $(foreach var,$(CT_SUITES),test/$(var)_SUITE) | tr ' ' ',') - -## Run one single CT with rebar3 -## e.g. make ct-one-suite suite=emqx_bridge -.PHONY: $(SUITES:%=ct-%) -$(CT_SUITES:%=ct-%): ct_setup - @rebar3 ct -v --readable=false --name $(CT_NODE_NAME) --suite=$(@:ct-%=%)_SUITE --cover - -.PHONY: app.config -app.config: $(CUTTLEFISH_SCRIPT) etc/gen.emqx.conf - $(CUTTLEFISH_SCRIPT) -l info -e etc/ -c etc/gen.emqx.conf -i priv/emqx.schema -d data/ - -$(CUTTLEFISH_SCRIPT): - @rebar3 get-deps - @if [ ! -f cuttlefish ]; then make -C _build/default/lib/cuttlefish; fi - -bbmustache: - @git clone https://hub.fastgit.org/soranoba/bbmustache.git && cd bbmustache && ./rebar3 compile && cd .. - -# This hack is to generate a conf file for testing -# relx overlay is used for release -etc/gen.emqx.conf: bbmustache etc/emqx.conf - @erl -noshell -pa bbmustache/_build/default/lib/bbmustache/ebin -eval \ - "{ok, Temp} = file:read_file('etc/emqx.conf'), \ - {ok, Vars0} = file:consult('vars'), \ - Vars = [{atom_to_list(N), list_to_binary(V)} || {N, V} <- Vars0], \ - Targ = bbmustache:render(Temp, Vars), \ - ok = file:write_file('etc/gen.emqx.conf', Targ), \ - halt(0)." - -.PHONY: gen-clean -gen-clean: - @rm -rf bbmustache - @rm -f etc/gen.emqx.conf etc/emqx.conf.rendered - -.PHONY: distclean -distclean: gen-clean - @rm -rf Mnesia.* - @rm -rf _build cover deps logs log data - @rm -f rebar.lock compile_commands.json cuttlefish erl_crash.dump diff --git a/_build/emqx/lib/emqx/README-CN.md b/_build/emqx/lib/emqx/README-CN.md deleted file mode 100644 index 44e5dd68ff..0000000000 --- a/_build/emqx/lib/emqx/README-CN.md +++ /dev/null @@ -1,99 +0,0 @@ -# EMQ X Broker - -[![GitHub Release](https://img.shields.io/github/release/emqx/emqx?color=brightgreen)](https://hub.fastgit.org/emqx/emqx/releases) -[![Build Status](https://travis-ci.org/emqx/emqx.svg)](https://travis-ci.org/emqx/emqx) -[![Coverage Status](https://coveralls.io/repos/github/emqx/emqx/badge.svg)](https://coveralls.io/github/emqx/emqx) -[![Docker Pulls](https://img.shields.io/docker/pulls/emqx/emqx)](https://hub.docker.com/r/emqx/emqx) -[![Slack Invite]()](https://slack-invite.emqx.io) -[![Twitter](https://img.shields.io/badge/Twitter-EMQ%20X-1DA1F2?logo=twitter)](https://twitter.com/emqtt) - -[![最棒的物联网 MQTT 开源团队期待您的加入](https://www.emqx.io/static/img/github_readme_cn_bg.png)](https://www.emqx.io/cn/careers) - -[English](./README.md) | 简体中文 - -*EMQ X* 是一款完全开源,高度可伸缩,高可用的分布式 MQTT 消息服务器,适用于 IoT、M2M 和移动应用程序,可处理千万级别的并发客户端。 - -从 3.0 版本开始,*EMQ X* 完整支持 MQTT V5.0 协议规范,向下兼容 MQTT V3.1 和 V3.1.1,并支持 MQTT-SN、CoAP、LwM2M、WebSocket 和 STOMP 等通信协议。EMQ X 3.0 单集群可支持千万级别的 MQTT 并发连接。 - -- 新功能的完整列表,请参阅 [EMQ X Release Notes](https://hub.fastgit.org/emqx/emqx/releases)。 -- 获取更多信息,请访问 [EMQ X 官网](https://www.emqx.io/cn/)。 - -## 安装 - -*EMQ X* 是跨平台的,支持 Linux、Unix、macOS 以及 Windows。这意味着 *EMQ X* 可以部署在 x86_64 架构的服务器上,也可以部署在 Raspberry Pi 这样的 ARM 设备上。 - -#### EMQ X Docker 镜像安装 - -``` -docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8883:8883 -p 8084:8084 -p 18083:18083 emqx/emqx -``` - -#### 二进制软件包安装 - -需从 [EMQ X 下载](https://www.emqx.io/cn/downloads) 页面获取相应操作系统的二进制软件包。 - -- [单节点安装文档](https://docs.emqx.io/broker/latest/cn/getting-started/install.html) -- [集群配置文档](https://docs.emqx.io/broker/latest/cn/advanced/cluster.html) - -## 从源码构建 - -3.0 版本开始,构建 *EMQ X* 需要 Erlang/OTP R21+。 - -``` -git clone https://hub.fastgit.org/emqx/emqx-rel.git - -cd emqx-rel && make - -cd _rel/emqx && ./bin/emqx console -``` - -## 快速入门 - -``` -# Start emqx -./bin/emqx start - -# Check Status -./bin/emqx_ctl status - -# Stop emqx -./bin/emqx stop -``` - -*EMQ X* 启动,可以使用浏览器访问 http://localhost:18083 来查看 Dashboard。 - -## FAQ - -访问 [EMQ X FAQ](https://docs.emqx.io/broker/latest/cn/faq/faq.html) 以获取常见问题的帮助。 - -## 产品路线 - -通过 [EMQ X Roadmap uses Github milestones](https://hub.fastgit.org/emqx/emqx/milestones) 参与跟踪项目进度。 - -## 社区、讨论、贡献和支持 - -你可通过以下途径与 EMQ 社区及开发者联系: - -- [Slack](https://slack-invite.emqx.io) -- [Twitter](https://twitter.com/emqtt) -- [Facebook](https://www.facebook.com/emqxmqtt) -- [Reddit](https://www.reddit.com/r/emqx/) -- [Forum](https://groups.google.com/d/forum/emqtt) -- [Weibo](https://weibo.com/emqtt) -- [Blog](https://www.emqx.io/cn/blog) - -欢迎你将任何 bug、问题和功能请求提交到 [emqx/emqx](https://hub.fastgit.org/emqx/emqx/issues)。 - -## MQTT 规范 - -你可以通过以下链接了解与查阅 MQTT 协议: - -[MQTT Version 3.1.1](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html) - -[MQTT Version 5.0](https://docs.oasis-open.org/mqtt/mqtt/v5.0/cs02/mqtt-v5.0-cs02.html) - -[MQTT SN](http://mqtt.org/new/wp-content/uploads/2009/06/MQTT-SN_spec_v1.2.pdf) - -## 开源许可 - -Apache License 2.0, 详见 [LICENSE](./LICENSE)。 diff --git a/_build/emqx/lib/emqx/README.md b/_build/emqx/lib/emqx/README.md deleted file mode 100644 index 9b74445f7c..0000000000 --- a/_build/emqx/lib/emqx/README.md +++ /dev/null @@ -1,99 +0,0 @@ -# EMQ X Broker - -[![GitHub Release](https://img.shields.io/github/release/emqx/emqx?color=brightgreen)](https://hub.fastgit.org/emqx/emqx/releases) -[![Build Status](https://travis-ci.org/emqx/emqx.svg)](https://travis-ci.org/emqx/emqx) -[![Coverage Status](https://coveralls.io/repos/github/emqx/emqx/badge.svg?branch=master)](https://coveralls.io/github/emqx/emqx?branch=master) -[![Docker Pulls](https://img.shields.io/docker/pulls/emqx/emqx)](https://hub.docker.com/r/emqx/emqx) -[![Slack Invite]()](https://slack-invite.emqx.io) -[![Twitter](https://img.shields.io/badge/Twitter-EMQ%20X-1DA1F2?logo=twitter)](https://twitter.com/emqtt) - -[![The best IoT MQTT open source team looks forward to your joining](https://www.emqx.io/static/img/github_readme_en_bg.png)](https://www.emqx.io/careers) - -English | [简体中文](./README-CN.md) - -*EMQ X* broker is a fully open source, highly scalable, highly available distributed MQTT messaging broker for IoT, M2M and Mobile applications that can handle tens of millions of concurrent clients. - -Starting from 3.0 release, *EMQ X* broker fully supports MQTT V5.0 protocol specifications and backward compatible with MQTT V3.1 and V3.1.1, as well as other communication protocols such as MQTT-SN, CoAP, LwM2M, WebSocket and STOMP. The 3.0 release of the *EMQ X* broker can scaled to 10+ million concurrent MQTT connections on one cluster. - -- For full list of new features, please read [EMQ X Release Notes](https://hub.fastgit.org/emqx/emqx/releases). -- For more information, please visit [EMQ X homepage](https://www.emqx.io). - -## Installation - -The *EMQ X* broker is cross-platform, which supports Linux, Unix, macOS and Windows. It means *EMQ X* can be deployed on x86_64 architecture servers and ARM devices like Raspberry Pi. - -#### Installing via EMQ X Docker Image - -``` -docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8883:8883 -p 8084:8084 -p 18083:18083 emqx/emqx -``` - -#### Installing via Binary Package - -Get the binary package of the corresponding OS from [EMQ X Download](https://www.emqx.io/downloads) page. - -- [Single Node Install](https://docs.emqx.io/broker/latest/en/getting-started/installation.html) -- [Multi Node Install](https://docs.emqx.io/broker/latest/en/advanced/cluster.html) - - -## Build From Source - -The *EMQ X* broker requires Erlang/OTP R21+ to build since 3.0 release. - -``` -git clone -b v4.0.0 https://hub.fastgit.org/emqx/emqx-rel.git - -cd emqx-rel && make - -cd _build/emqx/rel/emqx && ./bin/emqx console - -``` - -## Quick Start - -``` -# Start emqx -./bin/emqx start - -# Check Status -./bin/emqx_ctl status - -# Stop emqx -./bin/emqx stop -``` - -To view the dashboard after running, use your browser to open: http://localhost:18083 - -## FAQ - -Visiting [EMQ X FAQ](https://docs.emqx.io/broker/latest/en/faq/faq.html) to get help of common problems. - -## Roadmap - -The [EMQ X Roadmap uses Github milestones](https://hub.fastgit.org/emqx/emqx/milestones) to track the progress of the project. - -## Community, discussion, contribution, and support - -You can reach the EMQ community and developers via the following channels: -- [Slack](https://slack-invite.emqx.io/) -- [Twitter](https://twitter.com/emqtt) -- [Facebook](https://www.facebook.com/emqxmqtt) -- [Reddit](https://www.reddit.com/r/emqx/) -- [Forum](https://groups.google.com/d/forum/emqtt) -- [Blog](https://medium.com/@emqtt) - -Please submit any bugs, issues, and feature requests to [emqx/emqx](https://hub.fastgit.org/emqx/emqx/issues). - -## MQTT Specifications - -You can read the mqtt protocol via the following links: - -[MQTT Version 3.1.1](https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html) - -[MQTT Version 5.0](https://docs.oasis-open.org/mqtt/mqtt/v5.0/cs02/mqtt-v5.0-cs02.html) - -[MQTT SN](http://mqtt.org/new/wp-content/uploads/2009/06/MQTT-SN_spec_v1.2.pdf) - -## License - -Apache License 2.0, see [LICENSE](./LICENSE). diff --git a/_build/emqx/lib/emqx/etc/acl.conf b/_build/emqx/lib/emqx/etc/acl.conf deleted file mode 100644 index af2fb0dd11..0000000000 --- a/_build/emqx/lib/emqx/etc/acl.conf +++ /dev/null @@ -1,26 +0,0 @@ -%%-------------------------------------------------------------------- -%% [ACL](https://docs.emqx.io/broker/v3/en/config.html) -%% -%% -type(who() :: all | binary() | -%% {ipaddr, esockd_access:cidr()} | -%% {client, binary()} | -%% {user, binary()}). -%% -%% -type(access() :: subscribe | publish | pubsub). -%% -%% -type(topic() :: binary()). -%% -%% -type(rule() :: {allow, all} | -%% {allow, who(), access(), list(topic())} | -%% {deny, all} | -%% {deny, who(), access(), list(topic())}). -%%-------------------------------------------------------------------- - -{allow, {user, "dashboard"}, subscribe, ["$SYS/#"]}. - -{allow, {ipaddr, "127.0.0.1"}, pubsub, ["$SYS/#", "#"]}. - -{deny, all, subscribe, ["$SYS/#", {eq, "#"}]}. - -{allow, all}. - diff --git a/_build/emqx/lib/emqx/etc/acl.conf.paho b/_build/emqx/lib/emqx/etc/acl.conf.paho deleted file mode 100644 index 5beec43470..0000000000 --- a/_build/emqx/lib/emqx/etc/acl.conf.paho +++ /dev/null @@ -1,14 +0,0 @@ -%%-------------------------------------------------------------------- -%% For paho interoperability test cases -%%-------------------------------------------------------------------- - -{deny, {client, "myclientid"}, subscribe, ["test/nosubscribe"]}. - -{allow, {user, "dashboard"}, subscribe, ["$SYS/#"]}. - -{allow, {ipaddr, "127.0.0.1"}, pubsub, ["$SYS/#", "#"]}. - -{deny, all, subscribe, ["$SYS/#", {eq, "#"}]}. - -{allow, all}. - diff --git a/_build/emqx/lib/emqx/etc/certs/README b/_build/emqx/lib/emqx/etc/certs/README deleted file mode 100644 index 114a360aca..0000000000 --- a/_build/emqx/lib/emqx/etc/certs/README +++ /dev/null @@ -1 +0,0 @@ -Place your SSL/TLS Certificates here. diff --git a/_build/emqx/lib/emqx/etc/certs/cacert.pem b/_build/emqx/lib/emqx/etc/certs/cacert.pem deleted file mode 100644 index 604fd23628..0000000000 --- a/_build/emqx/lib/emqx/etc/certs/cacert.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDUTCCAjmgAwIBAgIJAPPYCjTmxdt/MA0GCSqGSIb3DQEBCwUAMD8xCzAJBgNV -BAYTAkNOMREwDwYDVQQIDAhoYW5nemhvdTEMMAoGA1UECgwDRU1RMQ8wDQYDVQQD -DAZSb290Q0EwHhcNMjAwNTA4MDgwNjUyWhcNMzAwNTA2MDgwNjUyWjA/MQswCQYD -VQQGEwJDTjERMA8GA1UECAwIaGFuZ3pob3UxDDAKBgNVBAoMA0VNUTEPMA0GA1UE -AwwGUm9vdENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzcgVLex1 -EZ9ON64EX8v+wcSjzOZpiEOsAOuSXOEN3wb8FKUxCdsGrsJYB7a5VM/Jot25Mod2 -juS3OBMg6r85k2TWjdxUoUs+HiUB/pP/ARaaW6VntpAEokpij/przWMPgJnBF3Ur -MjtbLayH9hGmpQrI5c2vmHQ2reRZnSFbY+2b8SXZ+3lZZgz9+BaQYWdQWfaUWEHZ -uDaNiViVO0OT8DRjCuiDp3yYDj3iLWbTA/gDL6Tf5XuHuEwcOQUrd+h0hyIphO8D -tsrsHZ14j4AWYLk1CPA6pq1HIUvEl2rANx2lVUNv+nt64K/Mr3RnVQd9s8bK+TXQ -KGHd2Lv/PALYuwIDAQABo1AwTjAdBgNVHQ4EFgQUGBmW+iDzxctWAWxmhgdlE8Pj -EbQwHwYDVR0jBBgwFoAUGBmW+iDzxctWAWxmhgdlE8PjEbQwDAYDVR0TBAUwAwEB -/zANBgkqhkiG9w0BAQsFAAOCAQEAGbhRUjpIred4cFAFJ7bbYD9hKu/yzWPWkMRa -ErlCKHmuYsYk+5d16JQhJaFy6MGXfLgo3KV2itl0d+OWNH0U9ULXcglTxy6+njo5 -CFqdUBPwN1jxhzo9yteDMKF4+AHIxbvCAJa17qcwUKR5MKNvv09C6pvQDJLzid7y -E2dkgSuggik3oa0427KvctFf8uhOV94RvEDyqvT5+pgNYZ2Yfga9pD/jjpoHEUlo -88IGU8/wJCx3Ds2yc8+oBg/ynxG8f/HmCC1ET6EHHoe2jlo8FpU/SgGtghS1YL30 -IWxNsPrUP+XsZpBJy/mvOhE5QXo6Y35zDqqj8tI7AGmAWu22jg== ------END CERTIFICATE----- diff --git a/_build/emqx/lib/emqx/etc/certs/cert.pem b/_build/emqx/lib/emqx/etc/certs/cert.pem deleted file mode 100644 index 092390b1d2..0000000000 --- a/_build/emqx/lib/emqx/etc/certs/cert.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDEzCCAfugAwIBAgIBAjANBgkqhkiG9w0BAQsFADA/MQswCQYDVQQGEwJDTjER -MA8GA1UECAwIaGFuZ3pob3UxDDAKBgNVBAoMA0VNUTEPMA0GA1UEAwwGUm9vdENB -MB4XDTIwMDUwODA4MDcwNVoXDTMwMDUwNjA4MDcwNVowPzELMAkGA1UEBhMCQ04x -ETAPBgNVBAgMCGhhbmd6aG91MQwwCgYDVQQKDANFTVExDzANBgNVBAMMBlNlcnZl -cjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALNeWT3pE+QFfiRJzKmn -AMUrWo3K2j/Tm3+Xnl6WLz67/0rcYrJbbKvS3uyRP/stXyXEKw9CepyQ1ViBVFkW -Aoy8qQEOWFDsZc/5UzhXUnb6LXr3qTkFEjNmhj+7uzv/lbBxlUG1NlYzSeOB6/RT -8zH/lhOeKhLnWYPXdXKsa1FL6ij4X8DeDO1kY7fvAGmBn/THh1uTpDizM4YmeI+7 -4dmayA5xXvARte5h4Vu5SIze7iC057N+vymToMk2Jgk+ZZFpyXrnq+yo6RaD3ANc -lrc4FbeUQZ5a5s5Sxgs9a0Y3WMG+7c5VnVXcbjBRz/aq2NtOnQQjikKKQA8GF080 -BQkCAwEAAaMaMBgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwDQYJKoZIhvcNAQEL -BQADggEBAJefnMZpaRDHQSNUIEL3iwGXE9c6PmIsQVE2ustr+CakBp3TZ4l0enLt -iGMfEVFju69cO4oyokWv+hl5eCMkHBf14Kv51vj448jowYnF1zmzn7SEzm5Uzlsa -sqjtAprnLyof69WtLU1j5rYWBuFX86yOTwRAFNjm9fvhAcrEONBsQtqipBWkMROp -iUYMkRqbKcQMdwxov+lHBYKq9zbWRoqLROAn54SRqgQk6c15JdEfgOOjShbsOkIH -UhqcwRkQic7n1zwHVGVDgNIZVgmJ2IdIWBlPEC7oLrRrBD/X1iEEXtKab6p5o22n -KB5mN+iQaE+Oe2cpGKZJiJRdM+IqDDQ= ------END CERTIFICATE----- diff --git a/_build/emqx/lib/emqx/etc/certs/client-cert.pem b/_build/emqx/lib/emqx/etc/certs/client-cert.pem deleted file mode 100644 index 09d8552218..0000000000 --- a/_build/emqx/lib/emqx/etc/certs/client-cert.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDEzCCAfugAwIBAgIBATANBgkqhkiG9w0BAQsFADA/MQswCQYDVQQGEwJDTjER -MA8GA1UECAwIaGFuZ3pob3UxDDAKBgNVBAoMA0VNUTEPMA0GA1UEAwwGUm9vdENB -MB4XDTIwMDUwODA4MDY1N1oXDTMwMDUwNjA4MDY1N1owPzELMAkGA1UEBhMCQ04x -ETAPBgNVBAgMCGhhbmd6aG91MQwwCgYDVQQKDANFTVExDzANBgNVBAMMBkNsaWVu -dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMy4hoksKcZBDbY680u6 -TS25U51nuB1FBcGMlF9B/t057wPOlxF/OcmbxY5MwepS41JDGPgulE1V7fpsXkiW -1LUimYV/tsqBfymIe0mlY7oORahKji7zKQ2UBIVFhdlvQxunlIDnw6F9popUgyHt -dMhtlgZK8oqRwHxO5dbfoukYd6J/r+etS5q26sgVkf3C6dt0Td7B25H9qW+f7oLV -PbcHYCa+i73u9670nrpXsC+Qc7Mygwa2Kq/jwU+ftyLQnOeW07DuzOwsziC/fQZa -nbxR+8U9FNftgRcC3uP/JMKYUqsiRAuaDokARZxVTV5hUElfpO6z6/NItSDvvh3i -eikCAwEAAaMaMBgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwDQYJKoZIhvcNAQEL -BQADggEBABchYxKo0YMma7g1qDswJXsR5s56Czx/I+B41YcpMBMTrRqpUC0nHtLk -M7/tZp592u/tT8gzEnQjZLKBAhFeZaR3aaKyknLqwiPqJIgg0pgsBGITrAK3Pv4z -5/YvAJJKgTe5UdeTz6U4lvNEux/4juZ4pmqH4qSFJTOzQS7LmgSmNIdd072rwXBd -UzcSHzsJgEMb88u/LDLjj1pQ7AtZ4Tta8JZTvcgBFmjB0QUi6fgkHY6oGat/W4kR -jSRUBlMUbM/drr2PVzRc2dwbFIl3X+ZE6n5Sl3ZwRAC/s92JU6CPMRW02muVu6xl -goraNgPISnrbpR6KjxLZkVembXzjNNc= ------END CERTIFICATE----- diff --git a/_build/emqx/lib/emqx/etc/certs/client-key.pem b/_build/emqx/lib/emqx/etc/certs/client-key.pem deleted file mode 100644 index 2b3f30cf6d..0000000000 --- a/_build/emqx/lib/emqx/etc/certs/client-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAzLiGiSwpxkENtjrzS7pNLblTnWe4HUUFwYyUX0H+3TnvA86X -EX85yZvFjkzB6lLjUkMY+C6UTVXt+mxeSJbUtSKZhX+2yoF/KYh7SaVjug5FqEqO -LvMpDZQEhUWF2W9DG6eUgOfDoX2milSDIe10yG2WBkryipHAfE7l1t+i6Rh3on+v -561LmrbqyBWR/cLp23RN3sHbkf2pb5/ugtU9twdgJr6Lve73rvSeulewL5BzszKD -BrYqr+PBT5+3ItCc55bTsO7M7CzOIL99BlqdvFH7xT0U1+2BFwLe4/8kwphSqyJE -C5oOiQBFnFVNXmFQSV+k7rPr80i1IO++HeJ6KQIDAQABAoIBAGWgvPjfuaU3qizq -uti/FY07USz0zkuJdkANH6LiSjlchzDmn8wJ0pApCjuIE0PV/g9aS8z4opp5q/gD -UBLM/a8mC/xf2EhTXOMrY7i9p/I3H5FZ4ZehEqIw9sWKK9YzC6dw26HabB2BGOnW -5nozPSQ6cp2RGzJ7BIkxSZwPzPnVTgy3OAuPOiJytvK+hGLhsNaT+Y9bNDvplVT2 -ZwYTV8GlHZC+4b2wNROILm0O86v96O+Qd8nn3fXjGHbMsAnONBq10bZS16L4fvkH -5G+W/1PeSXmtZFppdRRDxIW+DWcXK0D48WRliuxcV4eOOxI+a9N2ZJZZiNLQZGwg -w3A8+mECgYEA8HuJFrlRvdoBe2U/EwUtG74dcyy30L4yEBnN5QscXmEEikhaQCfX -Wm6EieMcIB/5I5TQmSw0cmBMeZjSXYoFdoI16/X6yMMuATdxpvhOZGdUGXxhAH+x -xoTUavWZnEqW3fkUU71kT5E2f2i+0zoatFESXHeslJyz85aAYpP92H0CgYEA2e5A -Yozt5eaA1Gyhd8SeptkEU4xPirNUnVQHStpMWUb1kzTNXrPmNWccQ7JpfpG6DcYl -zUF6p6mlzY+zkMiyPQjwEJlhiHM2NlL1QS7td0R8ewgsFoyn8WsBI4RejWrEG9td -EDniuIw+pBFkcWthnTLHwECHdzgquToyTMjrBB0CgYEA28tdGbrZXhcyAZEhHAZA -Gzog+pKlkpEzeonLKIuGKzCrEKRecIK5jrqyQsCjhS0T7ZRnL4g6i0s+umiV5M5w -fcc292pEA1h45L3DD6OlKplSQVTv55/OYS4oY3YEJtf5mfm8vWi9lQeY8sxOlQpn -O+VZTdBHmTC8PGeTAgZXHZUCgYA6Tyv88lYowB7SN2qQgBQu8jvdGtqhcs/99GCr -H3N0I69LPsKAR0QeH8OJPXBKhDUywESXAaEOwS5yrLNP1tMRz5Vj65YUCzeDG3kx -gpvY4IMp7ArX0bSRvJ6mYSFnVxy3k174G3TVCfksrtagHioVBGQ7xUg5ltafjrms -n8l55QKBgQDVzU8tQvBVqY8/1lnw11Vj4fkE/drZHJ5UkdC1eenOfSWhlSLfUJ8j -ds7vEWpRPPoVuPZYeR1y78cyxKe1GBx6Wa2lF5c7xjmiu0xbRnrxYeLolce9/ntp -asClqpnHT8/VJYTD7Kqj0fouTTZf0zkig/y+2XERppd8k+pSKjUCPQ== ------END RSA PRIVATE KEY----- diff --git a/_build/emqx/lib/emqx/etc/certs/key.pem b/_build/emqx/lib/emqx/etc/certs/key.pem deleted file mode 100644 index 6c338216e5..0000000000 --- a/_build/emqx/lib/emqx/etc/certs/key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAs15ZPekT5AV+JEnMqacAxStajcraP9Obf5eeXpYvPrv/Stxi -sltsq9Le7JE/+y1fJcQrD0J6nJDVWIFUWRYCjLypAQ5YUOxlz/lTOFdSdvotevep -OQUSM2aGP7u7O/+VsHGVQbU2VjNJ44Hr9FPzMf+WE54qEudZg9d1cqxrUUvqKPhf -wN4M7WRjt+8AaYGf9MeHW5OkOLMzhiZ4j7vh2ZrIDnFe8BG17mHhW7lIjN7uILTn -s36/KZOgyTYmCT5lkWnJeuer7KjpFoPcA1yWtzgVt5RBnlrmzlLGCz1rRjdYwb7t -zlWdVdxuMFHP9qrY206dBCOKQopADwYXTzQFCQIDAQABAoIBAQCuvCbr7Pd3lvI/ -n7VFQG+7pHRe1VKwAxDkx2t8cYos7y/QWcm8Ptwqtw58HzPZGWYrgGMCRpzzkRSF -V9g3wP1S5Scu5C6dBu5YIGc157tqNGXB+SpdZddJQ4Nc6yGHXYERllT04ffBGc3N -WG/oYS/1cSteiSIrsDy/91FvGRCi7FPxH3wIgHssY/tw69s1Cfvaq5lr2NTFzxIG -xCvpJKEdSfVfS9I7LYiymVjst3IOR/w76/ZFY9cRa8ZtmQSWWsm0TUpRC1jdcbkm -ZoJptYWlP+gSwx/fpMYftrkJFGOJhHJHQhwxT5X/ajAISeqjjwkWSEJLwnHQd11C -Zy2+29lBAoGBANlEAIK4VxCqyPXNKfoOOi5dS64NfvyH4A1v2+KaHWc7lqaqPN49 -ezfN2n3X+KWx4cviDD914Yc2JQ1vVJjSaHci7yivocDo2OfZDmjBqzaMp/y+rX1R -/f3MmiTqMa468rjaxI9RRZu7vDgpTR+za1+OBCgMzjvAng8dJuN/5gjlAoGBANNY -uYPKtearBmkqdrSV7eTUe49Nhr0XotLaVBH37TCW0Xv9wjO2xmbm5Ga/DCtPIsBb -yPeYwX9FjoasuadUD7hRvbFu6dBa0HGLmkXRJZTcD7MEX2Lhu4BuC72yDLLFd0r+ -Ep9WP7F5iJyagYqIZtz+4uf7gBvUDdmvXz3sGr1VAoGAdXTD6eeKeiI6PlhKBztF -zOb3EQOO0SsLv3fnodu7ZaHbUgLaoTMPuB17r2jgrYM7FKQCBxTNdfGZmmfDjlLB -0xZ5wL8ibU30ZXL8zTlWPElST9sto4B+FYVVF/vcG9sWeUUb2ncPcJ/Po3UAktDG -jYQTTyuNGtSJHpad/YOZctkCgYBtWRaC7bq3of0rJGFOhdQT9SwItN/lrfj8hyHA -OjpqTV4NfPmhsAtu6j96OZaeQc+FHvgXwt06cE6Rt4RG4uNPRluTFgO7XYFDfitP -vCppnoIw6S5BBvHwPP+uIhUX2bsi/dm8vu8tb+gSvo4PkwtFhEr6I9HglBKmcmog -q6waEQKBgHyecFBeM6Ls11Cd64vborwJPAuxIW7HBAFj/BS99oeG4TjBx4Sz2dFd -rzUibJt4ndnHIvCN8JQkjNG14i9hJln+H3mRss8fbZ9vQdqG+2vOWADYSzzsNI55 -RFY7JjluKcVkp/zCDeUxTU3O6sS+v6/3VE11Cob6OYQx3lN5wrZ3 ------END RSA PRIVATE KEY----- diff --git a/_build/emqx/lib/emqx/etc/emqx.conf b/_build/emqx/lib/emqx/etc/emqx.conf deleted file mode 100644 index ce07623927..0000000000 --- a/_build/emqx/lib/emqx/etc/emqx.conf +++ /dev/null @@ -1,2177 +0,0 @@ -##==================================================================== -## EMQ X Configuration R4.0 -##==================================================================== - -##-------------------------------------------------------------------- -## Cluster -##-------------------------------------------------------------------- - -## Cluster name. -## -## Value: String -cluster.name = emqxcl - -## Specify the erlang distributed protocol. -## -## Value: Enum -## - inet_tcp: the default; handles TCP streams with IPv4 addressing. -## - inet6_tcp: handles TCP with IPv6 addressing. -## - inet_tls: using TLS for Erlang Distribution. -## -## vm.args: -proto_dist inet_tcp -cluster.proto_dist = inet_tcp - -## Cluster auto-discovery strategy. -## -## Value: Enum -## - manual: Manual join command -## - static: Static node list -## - mcast: IP Multicast -## - dns: DNS A Record -## - etcd: etcd -## - k8s: Kubernetes -## -## Default: manual -cluster.discovery = manual - -## Enable cluster autoheal from network partition. -## -## Value: on | off -## -## Default: on -cluster.autoheal = on - -## Autoclean down node. A down node will be removed from the cluster -## if this value > 0. -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 5m -cluster.autoclean = 5m - -##-------------------------------------------------------------------- -## Cluster using static node list - -## Node list of the cluster. -## -## Value: String -## cluster.static.seeds = emqx1@127.0.0.1,emqx2@127.0.0.1 - -##-------------------------------------------------------------------- -## Cluster using IP Multicast. - -## IP Multicast Address. -## -## Value: IP Address -## cluster.mcast.addr = 239.192.0.1 - -## Multicast Ports. -## -## Value: Port List -## cluster.mcast.ports = 4369,4370 - -## Multicast Iface. -## -## Value: Iface Address -## -## Default: 0.0.0.0 -## cluster.mcast.iface = 0.0.0.0 - -## Multicast Ttl. -## -## Value: 0-255 -## cluster.mcast.ttl = 255 - -## Multicast loop. -## -## Value: on | off -## cluster.mcast.loop = on - -##-------------------------------------------------------------------- -## Cluster using DNS A records. - -## DNS name. -## -## Value: String -## cluster.dns.name = localhost - -## The App name is used to build 'node.name' with IP address. -## -## Value: String -## cluster.dns.app = emqx - -##-------------------------------------------------------------------- -## Cluster using etcd - -## Etcd server list, seperated by ','. -## -## Value: String -## cluster.etcd.server = http://127.0.0.1:2379 - -## The prefix helps build nodes path in etcd. Each node in the cluster -## will create a path in etcd: v2/keys/// -## -## Value: String -## cluster.etcd.prefix = emqxcl - -## The TTL for node's path in etcd. -## -## Value: Duration -## -## Default: 1m, 1 minute -## cluster.etcd.node_ttl = 1m - -## Path to a file containing the client's private PEM-encoded key. -## -## Value: File -## cluster.etcd.ssl.keyfile = {{ platform_etc_dir }}/certs/client-key.pem - -## The path to a file containing the client's certificate. -## -## Value: File -## cluster.etcd.ssl.certfile = {{ platform_etc_dir }}/certs/client.pem - -## Path to the file containing PEM-encoded CA certificates. The CA certificates -## are used during server authentication and when building the client certificate chain. -## -## Value: File -## cluster.etcd.ssl.cacertfile = {{ platform_etc_dir }}/certs/ca.pem - -##-------------------------------------------------------------------- -## Cluster using Kubernetes - -## Kubernetes API server list, seperated by ','. -## -## Value: String -## cluster.k8s.apiserver = http://10.110.111.204:8080 - -## The service name helps lookup EMQ nodes in the cluster. -## -## Value: String -## cluster.k8s.service_name = emqx - -## The address type is used to extract host from k8s service. -## -## Value: ip | dns | hostname -## cluster.k8s.address_type = ip - -## The app name helps build 'node.name'. -## -## Value: String -## cluster.k8s.app_name = emqx - -## The suffix added to dns and hostname get from k8s service -## -## Value: String -## cluster.k8s.suffix = pod.cluster.local - -## Kubernetes Namespace -## -## Value: String -## cluster.k8s.namespace = default - -##-------------------------------------------------------------------- -## Node -##-------------------------------------------------------------------- - -## Node name. -## -## See: http://erlang.org/doc/reference_manual/distributed.html -## -## Value: @ -## -## Default: emqx@127.0.0.1 -node.name = emqx@127.0.0.1 - -## Cookie for distributed node communication. -## -## Value: String -node.cookie = emqxsecretcookie - -## Data dir for the node -## -## Value: Folder -node.data_dir = {{ platform_data_dir }} - -## Heartbeat monitoring of an Erlang runtime system. Comment the line to disable -## heartbeat, or set the value as 'on' -## -## Value: on -## -## vm.args: -heart -## node.heartbeat = on - -## Sets the number of threads in async thread pool. Valid range is 0-1024. -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: 0-1024 -## -## vm.args: +A Number -## node.async_threads = 4 - -## Sets the maximum number of simultaneously existing processes for this -## system if a Number is passed as value. -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: Number [1024-134217727] -## -## vm.args: +P Number -## node.process_limit = 2097152 - -## Sets the maximum number of simultaneously existing ports for this system. -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: Number [1024-134217727] -## -## vm.args: +Q Number -## node.max_ports = 1048576 - -## Sets the distribution buffer busy limit (dist_buf_busy_limit). -## -## See: http://erlang.org/doc/man/erl.html -## -## Value: Number [1KB-2GB] -## -## vm.args: +zdbbl size -## node.dist_buffer_size = 8MB - -## Sets the maximum number of ETS tables. Note that mnesia and SSL will -## create temporary ETS tables. -## -## Value: Number -## -## vm.args: +e Number -## node.max_ets_tables = 262144 - -## Global GC Interval. -## -## Value: Duration -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 20s: 20 seconds -## -## Defaut: 15 minutes -node.global_gc_interval = 15m - -## Tweak GC to run more often. -## -## Value: Number [0-65535] -## -## vm.args: -env ERL_FULLSWEEP_AFTER Number -## node.fullsweep_after = 1000 - -## Crash dump log file. -## -## Value: Log file -node.crash_dump = {{ platform_log_dir }}/crash.dump - -## Specify SSL Options in the file if using SSL for Erlang Distribution. -## -## Value: File -## -## vm.args: -ssl_dist_optfile -## node.ssl_dist_optfile = {{ platform_etc_dir }}/ssl_dist.conf - -## Sets the net_kernel tick time. TickTime is specified in seconds. -## Notice that all communicating nodes are to have the same TickTime -## value specified. -## -## See: http://www.erlang.org/doc/man/kernel_app.html#net_ticktime -## -## Value: Number -## -## vm.args: -kernel net_ticktime Number -## node.dist_net_ticktime = 120 - -## Sets the port range for the listener socket of a distributed Erlang node. -## Note that if there are firewalls between clustered nodes, this port segment -## for nodes’ communication should be allowed. -## -## See: http://www.erlang.org/doc/man/kernel_app.html -## -## Value: Port [1024-65535] -node.dist_listen_min = 6369 -node.dist_listen_max = 6369 - -##-------------------------------------------------------------------- -## RPC -##-------------------------------------------------------------------- -## RPC Mode. -## -## Value: sync | async -rpc.mode = async - -## Max batch size of async RPC requests. -## -## Value: Integer -## Zero or negative value disables rpc batching. -## -## NOTE: RPC batch won't work when rpc.mode = sync -rpc.async_batch_size = 256 - -## TCP server port for RPC. -## -## Value: Port [1024-65535] -rpc.tcp_server_port = 5369 - -## TCP port for outgoing RPC connections. -## -## Value: Port [1024-65535] -rpc.tcp_client_port = 5369 - -## Number of outgoing RPC connections. -## -## Value: Interger [1-256] -## Defaults to NumberOfCPUSchedulers / 2 -#rpc.tcp_client_num = 1 - -## RCP Client connect timeout. -## -## Value: Seconds -rpc.connect_timeout = 5s - -## TCP send timeout of RPC client and server. -## -## Value: Seconds -rpc.send_timeout = 5s - -## Authentication timeout -## -## Value: Seconds -rpc.authentication_timeout = 5s - -## Default receive timeout for call() functions -## -## Value: Seconds -rpc.call_receive_timeout = 15s - -## Socket idle keepalive. -## -## Value: Seconds -rpc.socket_keepalive_idle = 900s - -## TCP Keepalive probes interval. -## -## Value: Seconds -rpc.socket_keepalive_interval = 75s - -## Probes lost to close the connection -## -## Value: Integer -rpc.socket_keepalive_count = 9 - -## Size of TCP send buffer. -## -## Value: Bytes -rpc.socket_sndbuf = 1MB - -## Size of TCP receive buffer. -## -## Value: Seconds -rpc.socket_recbuf = 1MB - -## Size of user-level software socket buffer. -## -## Value: Seconds -rpc.socket_buffer = 1MB - -##-------------------------------------------------------------------- -## Log -##-------------------------------------------------------------------- - -## Where to emit the logs. -## Enable the console (standard output) logs. -## -## Value: off | file | console | both -## - off: disable logs entirely -## - file: write logs only to file -## - console: write logs only to standard I/O -## - both: write logs both to file and standard I/O -log.to = both - -## The log severity level. -## -## Value: debug | info | notice | warning | error | critical | alert | emergency -## -## Note: Only the messages with severity level higher than or equal to -## this level will be logged. -## -## Default: warning -log.level = warning - -## The dir for log files. -## -## Value: Folder -log.dir = {{ platform_log_dir }} - -## The log filename for logs of level specified in "log.level". -## -## If `log.rotation` is enabled, this is the base name of the -## files. Each file in a rotated log is named .N, where N is an integer. -## -## Value: String -## Default: emqx.log -log.file = emqx.log - -## Limits the total number of characters printed for each log event. -## -## Value: Integer -## Default: No Limit -#log.chars_limit = 8192 - -## Enables the log rotation. -## With this enabled, new log files will be created when the current -## log file is full, max to `log.rotation.size` files will be created. -## -## Value: on | off -## Default: on -log.rotation = on - -## Maximum size of each log file. -## -## Value: Number -## Default: 10M -## Supported Unit: KB | MB | GB -log.rotation.size = 10MB - -## Maximum rotation count of log files. -## -## Value: Number -## Default: 5 -log.rotation.count = 5 - -## To create additional log files for specific log levels. -## -## Value: File Name -## Format: log.$level.file = $filename, -## where "$level" can be one of: debug, info, notice, warning, -## error, critical, alert, emergency -## Note: Log files for a specific log level will only contain all the logs -## that higher than or equal to that level -## -#log.info.file = info.log -#log.error.file = error.log - -## The max allowed queue length before switching to sync mode. -## -## Log overload protection parameter. If the message queue grows -## larger than this value the handler switches from anync to sync mode. -## -## Default: 100 -## -#log.sync_mode_qlen = 100 - -## The max allowed queue length before switching to drop mode. -## -## Log overload protection parameter. When the message queue grows -## larger than this threshold, the handler switches to a mode in which -## it drops all new events that senders want to log. -## -## Default: 3000 -## -#log.drop_mode_qlen = 3000 - -## The max allowed queue length before switching to flush mode. -## -## Log overload protection parameter. If the length of the message queue -## grows larger than this threshold, a flush (delete) operation takes place. -## To flush events, the handler discards the messages in the message queue -## by receiving them in a loop without logging. -## -## Default: 8000 -## -#log.flush_qlen = 8000 - -## Kill the log handler when it gets overloaded. -## -## Log overload protection parameter. It is possible that a handler, -## even if it can successfully manage peaks of high load without crashing, -## can build up a large message queue, or use a large amount of memory. -## We could kill the log handler in these cases and restart it after a -## few seconds. -## -## Default: on -## -#log.overload_kill = on - -## The max allowed queue length before killing the log hanlder. -## -## Log overload protection parameter. This is the maximum allowed queue -## length. If the message queue grows larger than this, the handler -## process is terminated. -## -## Default: 20000 -## -#log.overload_kill_qlen = 20000 - -## The max allowed memory size before killing the log hanlder. -## -## Log overload protection parameter. This is the maximum memory size -## that the handler process is allowed to use. If the handler grows -## larger than this, the process is terminated. -## -## Default: 30MB -## -#log.overload_kill_mem_size = 30MB - -## Restart the log hanlder after some seconds. -## -## Log overload protection parameter. If the handler is terminated, -## it restarts automatically after a delay specified in seconds. -## The value "infinity" prevents restarts. -## -## Default: 5s -## -#log.overload_kill_restart_after = 5s - -## Max burst count and time window for burst control. -## -## Log overload protection parameter. Large bursts of log events - many -## events received by the handler under a short period of time - can -## potentially cause problems. By specifying the maximum number of events -## to be handled within a certain time frame, the handler can avoid -## choking the log with massive amounts of printouts. -## -## This config controls the maximum number of events to handle within -## a time frame. After the limit is reached, successive events are -## dropped until the end of the time frame. -## -## Note that there would be no warning if any messages were -## dropped because of burst control. -## -## Comment this config out to disable the burst control feature. -## -## Value: MaxBurstCount,TimeWindow -## Default: disabled -## -#log.burst_limit = 20000, 1s - -##-------------------------------------------------------------------- -## Authentication/Access Control -##-------------------------------------------------------------------- - -## Allow anonymous authentication by default if no auth plugins loaded. -## Notice: Disable the option in production deployment! -## -## Value: true | false -allow_anonymous = true - -## Allow or deny if no ACL rules matched. -## -## Value: allow | deny -acl_nomatch = allow - -## Default ACL File. -## -## Value: File Name -acl_file = {{ platform_etc_dir }}/acl.conf - -## Whether to enable ACL cache. -## -## If enabled, ACLs roles for each client will be cached in the memory -## -## Value: on | off -enable_acl_cache = on - -## The maximum count of ACL entries can be cached for a client. -## -## Value: Integer greater than 0 -## Default: 32 -acl_cache_max_size = 32 - -## The time after which an ACL cache entry will be deleted -## -## Value: Duration -## Default: 1 minute -acl_cache_ttl = 1m - -## The action when acl check reject current operation -## -## Value: ignore | disconnect -## Default: ignore -acl_deny_action = ignore - -## Specify the global flapping detect policy. -## The value is a string composed of flapping threshold, duration and banned interval. -## 1. threshold: an integer to specfify the disconnected times of a MQTT Client; -## 2. duration: the time window for flapping detect; -## 3. banned interval: the banned interval if a flapping is detected. -## -## Value: Integer,Duration,Duration -flapping_detect_policy = 30, 1m, 5m - -##-------------------------------------------------------------------- -## MQTT Protocol -##-------------------------------------------------------------------- - -## Maximum MQTT packet size allowed. -## -## Value: Bytes -## Default: 1MB -mqtt.max_packet_size = 1MB - -## Maximum length of MQTT clientId allowed. -## -## Value: Number [23-65535] -mqtt.max_clientid_len = 65535 - -## Maximum topic levels allowed. 0 means no limit. -## -## Value: Number -mqtt.max_topic_levels = 0 - -## Maximum QoS allowed. -## -## Value: 0 | 1 | 2 -mqtt.max_qos_allowed = 2 - -## Maximum Topic Alias, 0 means no topic alias supported. -## -## Value: 0-65535 -mqtt.max_topic_alias = 65535 - -## Whether the Server supports MQTT retained messages. -## -## Value: boolean -mqtt.retain_available = true - -## Whether the Server supports MQTT Wildcard Subscriptions -## -## Value: boolean -mqtt.wildcard_subscription = true - -## Whether the Server supports MQTT Shared Subscriptions. -## -## Value: boolean -mqtt.shared_subscription = true - -## Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -## -## Value: true | false -mqtt.ignore_loop_deliver = false - -## Whether to parse the MQTT frame in strict mode -## -## Value: true | false -mqtt.strict_mode = false - -## Specify the response information returned to the client -## -## Value: String -## mqtt.response_information = example - -##-------------------------------------------------------------------- -## Zones -##-------------------------------------------------------------------- - -##-------------------------------------------------------------------- -## External Zone - -## Idle timeout of the external MQTT connections. -## -## Value: duration -zone.external.idle_timeout = 15s - -## Publish limit for the external MQTT connections. -## -## Value: Number,Duration -## Example: 100 messages per 10 seconds. -## zone.external.publish_limit = 100,10s - -## Enable ACL check. -## -## Value: Flag -zone.external.enable_acl = on - -## Enable ban check. -## -## Value: Flag -zone.external.enable_ban = on - -## Enable per connection statistics. -## -## Value: on | off -zone.external.enable_stats = on - -## The action when acl check reject current operation -## -## Value: ignore | disconnect -## Default: ignore -zone.external.acl_deny_action = ignore - -## Force the MQTT connection process GC after this number of -## messages | bytes passed through. -## -## Numbers delimited by `|'. Zero or negative is to disable. -zone.external.force_gc_policy = 16000|16MB - -## Max message queue length and total heap size to force shutdown -## connection/session process. -## Message queue here is the Erlang process mailbox, but not the number -## of queued MQTT messages of QoS 1 and 2. -## -## Numbers delimited by `|'. Zero or negative is to disable. -## zone.external.force_shutdown_policy = 32000|32MB - -## Maximum MQTT packet size allowed. -## -## Value: Bytes -## Default: 1MB -## zone.external.max_packet_size = 64KB - -## Maximum length of MQTT clientId allowed. -## -## Value: Number [23-65535] -## zone.external.max_clientid_len = 1024 - -## Maximum topic levels allowed. 0 means no limit. -## -## Value: Number -## zone.external.max_topic_levels = 7 - -## Maximum QoS allowed. -## -## Value: 0 | 1 | 2 -## zone.external.max_qos_allowed = 2 - -## Maximum Topic Alias, 0 means no limit. -## -## Value: 0-65535 -## zone.external.max_topic_alias = 65535 - -## Whether the Server supports retained messages. -## -## Value: boolean -## zone.external.retain_available = true - -## Whether the Server supports Wildcard Subscriptions -## -## Value: boolean -## zone.external.wildcard_subscription = false - -## Whether the Server supports Shared Subscriptions -## -## Value: boolean -## zone.external.shared_subscription = false - -## Server Keep Alive -## -## Value: Number -## zone.external.server_keepalive = 0 - -## The backoff for MQTT keepalive timeout. The broker will kick a connection out -## until 'Keepalive * backoff * 2' timeout. -## -## Value: Float > 0.5 -zone.external.keepalive_backoff = 0.75 - -## Maximum number of subscriptions allowed, 0 means no limit. -## -## Value: Number -zone.external.max_subscriptions = 0 - -## Force to upgrade QoS according to subscription. -## -## Value: on | off -zone.external.upgrade_qos = off - -## Maximum size of the Inflight Window storing QoS1/2 messages delivered but unacked. -## -## Value: Number -zone.external.max_inflight = 32 - -## Retry interval for QoS1/2 message delivering. -## -## Value: Duration -zone.external.retry_interval = 30s - -## Maximum QoS2 packets (Client -> Broker) awaiting PUBREL, 0 means no limit. -## -## Value: Number -zone.external.max_awaiting_rel = 100 - -## The QoS2 messages (Client -> Broker) will be dropped if awaiting PUBREL timeout. -## -## Value: Duration -zone.external.await_rel_timeout = 300s - -## Default session expiry interval for MQTT V3.1.1 connections. -## -## Value: Duration -## -d: day -## -h: hour -## -m: minute -## -s: second -## -## Default: 2h, 2 hours -zone.external.session_expiry_interval = 2h - -## Maximum queue length. Enqueued messages when persistent client disconnected, -## or inflight window is full. 0 means no limit. -## -## Value: Number >= 0 -zone.external.max_mqueue_len = 1000 - -## Topic priorities. -## 'none' to indicate no priority table (by default), hence all messages -## are treated equal -## -## Priority number [1-255] -## Example: topic/1=10,topic/2=8 -## NOTE: comma and equal signs are not allowed for priority topic names -## NOTE: messages for topics not in the priority table are treated as -## either highest or lowest priority depending on the configured -## value for mqueue_default_priority -## -zone.external.mqueue_priorities = none - -## Default to highest priority for topics not matching priority table -## -## Value: highest | lowest -zone.external.mqueue_default_priority = highest - -## Whether to enqueue QoS0 messages. -## -## Value: false | true -zone.external.mqueue_store_qos0 = true - -## Whether to turn on flapping detect -## -## Value: on | off -zone.external.enable_flapping_detect = off - -## All the topics will be prefixed with the mountpoint path if this option is enabled. -## -## Variables in mountpoint path: -## - %c: clientid -## - %u: username -## -## Value: String -## zone.external.mountpoint = devicebound/ - -## Whether use username replace client id -## -## Value: boolean -## Default: false -zone.external.use_username_as_clientid = false - -## Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -## -## Value: true | false -zone.external.ignore_loop_deliver = false - -## Whether to parse the MQTT frame in strict mode -## -## Value: true | false -zone.external.strict_mode = false - -## Specify the response information returned to the client -## -## Value: String -## zone.external.response_information = example - -##-------------------------------------------------------------------- -## Internal Zone - -zone.internal.allow_anonymous = true - -## Enable per connection stats. -## -## Value: Flag -zone.internal.enable_stats = on - -## Enable ACL check. -## -## Value: Flag -zone.internal.enable_acl = off - -## The action when acl check reject current operation -## -## Value: ignore | disconnect -## Default: ignore -zone.internal.acl_deny_action = ignore - -## See zone.$name.force_gc_policy -## zone.internal.force_gc_policy = 128000|128MB - -## See zone.$name.wildcard_subscription. -## -## Value: boolean -## zone.internal.wildcard_subscription = true - -## See zone.$name.shared_subscription. -## -## Value: boolean -## zone.internal.shared_subscription = true - -## See zone.$name.max_subscriptions. -## -## Value: Integer -zone.internal.max_subscriptions = 0 - -## See zone.$name.max_inflight -## -## Value: Number -zone.internal.max_inflight = 128 - -## See zone.$name.max_awaiting_rel -## -## Value: Number -zone.internal.max_awaiting_rel = 1000 - -## See zone.$name.max_mqueue_len -## -## Value: Number >= 0 -zone.internal.max_mqueue_len = 10000 - -## Whether to enqueue Qos0 messages. -## -## Value: false | true -zone.internal.mqueue_store_qos0 = true - -## Whether to turn on flapping detect -## -## Value: on | off -zone.internal.enable_flapping_detect = off - -## See zone.$name.force_shutdown_policy -## zone.internal.force_shutdown_policy = 128000|128MB - -## All the topics will be prefixed with the mountpoint path if this option is enabled. -## -## Variables in mountpoint path: -## - %c: clientid -## - %u: username -## -## Value: String -## zone.internal.mountpoint = cloudbound/ - -## Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -## -## Value: true | false -zone.internal.ignore_loop_deliver = false - -## Whether to parse the MQTT frame in strict mode -## -## Value: true | false -zone.internal.strict_mode = false - -## Specify the response information returned to the client -## -## Value: String -## zone.internal.response_information = example - -## Allow the zone's clients to bypass authentication step -## -## Value: true | false -zone.internal.bypass_auth_plugins = true - -##-------------------------------------------------------------------- -## Listeners -##-------------------------------------------------------------------- - -##-------------------------------------------------------------------- -## MQTT/TCP - External TCP Listener for MQTT Protocol - -## listener.tcp.$name is the IP address and port that the MQTT/TCP -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 1883, 127.0.0.1:1883, ::1:1883 -listener.tcp.external = 0.0.0.0:1883 - -## The acceptor pool for external MQTT/TCP listener. -## -## Value: Number -listener.tcp.external.acceptors = 8 - -## Maximum number of concurrent MQTT/TCP connections. -## -## Value: Number -listener.tcp.external.max_connections = 1024000 - -## Maximum external connections per second. -## -## Value: Number -listener.tcp.external.max_conn_rate = 1000 - -## Specify the {active, N} option for the external MQTT/TCP Socket. -## -## Value: Number -listener.tcp.external.active_n = 100 - -## Zone of the external MQTT/TCP listener belonged to. -## -## See: zone.$name.* -## -## Value: String -listener.tcp.external.zone = external - -## Rate limit for the external MQTT/TCP connections. Format is 'limit,duration'. -## -## Value: limit,duration -## Default: 100KB incoming per 10 seconds. -## listener.tcp.external.rate_limit = 100KB,10s - -## The access control rules for the MQTT/TCP listener. -## -## See: https://hub.fastgit.org/emqtt/esockd#allowdeny -## -## Value: ACL Rule -## -## Example: allow 192.168.0.0/24 -listener.tcp.external.access.1 = allow all - -## Enable the Proxy Protocol V1/2 if the EMQ X cluster is deployed -## behind HAProxy or Nginx. -## -## See: https://www.haproxy.com/blog/haproxy/proxy-protocol/ -## -## Value: on | off -## listener.tcp.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. EMQ X will close the TCP connection -## if no proxy protocol packet recevied within the timeout. -## -## Value: Duration -## listener.tcp.external.proxy_protocol_timeout = 3s - -## Enable the option for X.509 certificate based authentication. -## EMQX will use the common name of certificate as MQTT username. -## -## Value: cn | dn | crt -## listener.tcp.external.peer_cert_as_username = cn - -## The TCP backlog defines the maximum length that the queue of pending -## connections can grow to. -## -## Value: Number >= 0 -listener.tcp.external.backlog = 1024 - -## The TCP send timeout for external MQTT connections. -## -## Value: Duration -listener.tcp.external.send_timeout = 15s - -## Close the TCP connection if send timeout. -## -## Value: on | off -listener.tcp.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for MQTT connections. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -## listener.tcp.external.recbuf = 2KB - -## The TCP send buffer(os kernel) for MQTT connections. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -## listener.tcp.external.sndbuf = 2KB - -## The size of the user-level software buffer used by the driver. -## Not to be confused with options sndbuf and recbuf, which correspond -## to the Kernel socket buffers. It is recommended to have val(buffer) -## >= max(val(sndbuf),val(recbuf)) to avoid performance issues because -## of unnecessary copying. val(buffer) is automatically set to the above -## maximum when values sndbuf or recbuf are set. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -## listener.tcp.external.buffer = 2KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## Value: on | off -## listener.tcp.external.tune_buffer = off - -## The TCP_NODELAY flag for MQTT connections. Small amounts of data are -## sent immediately if the option is enabled. -## -## Value: true | false -listener.tcp.external.nodelay = true - -## The SO_REUSEADDR flag for TCP listener. -## -## Value: true | false -listener.tcp.external.reuseaddr = true - -##-------------------------------------------------------------------- -## Internal TCP Listener for MQTT Protocol - -## The IP address and port that the internal MQTT/TCP protocol listener -## will bind. -## -## Value: IP:Port, Port -## -## Examples: 11883, 127.0.0.1:11883, ::1:11883 -listener.tcp.internal = 127.0.0.1:11883 - -## The acceptor pool for internal MQTT/TCP listener. -## -## Value: Number -listener.tcp.internal.acceptors = 4 - -## Maximum number of concurrent MQTT/TCP connections. -## -## Value: Number -listener.tcp.internal.max_connections = 1024000 - -## Maximum internal connections per second. -## -## Value: Number -listener.tcp.internal.max_conn_rate = 1000 - -## Specify the {active, N} option for the internal MQTT/TCP Socket. -## -## Value: Number -listener.tcp.internal.active_n = 1000 - -## Zone of the internal MQTT/TCP listener belonged to. -## -## Value: String -listener.tcp.internal.zone = internal - -## Rate limit for the internal MQTT/TCP connections. -## -## See: listener.tcp.$name.rate_limit -## -## Value: limit,duration -## Default: 1MB incoming per second. -## listener.tcp.internal.rate_limit = 1MB,1s - -## The TCP backlog of internal MQTT/TCP Listener. -## -## See: listener.tcp.$name.backlog -## -## Value: Number >= 0 -listener.tcp.internal.backlog = 512 - -## The TCP send timeout for internal MQTT connections. -## -## See: listener.tcp.$name.send_timeout -## -## Value: Duration -listener.tcp.internal.send_timeout = 5s - -## Close the MQTT/TCP connection if send timeout. -## -## See: listener.tcp.$name.send_timeout_close -## -## Value: on | off -listener.tcp.internal.send_timeout_close = on - -## The TCP receive buffer(os kernel) for internal MQTT connections. -## -## See: listener.tcp.$name.recbuf -## -## Value: Bytes -listener.tcp.internal.recbuf = 64KB - -## The TCP send buffer(os kernel) for internal MQTT connections. -## -## See: http://erlang.org/doc/man/inet.html -## -## Value: Bytes -listener.tcp.internal.sndbuf = 64KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.tcp.$name.buffer -## -## Value: Bytes -## listener.tcp.internal.buffer = 16KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## See: listener.tcp.$name.tune_buffer -## -## Value: on | off -## listener.tcp.internal.tune_buffer = off - -## The TCP_NODELAY flag for internal MQTT connections. -## -## See: listener.tcp.$name.nodelay -## -## Value: true | false -listener.tcp.internal.nodelay = false - -## The SO_REUSEADDR flag for MQTT/TCP Listener. -## -## Value: true | false -listener.tcp.internal.reuseaddr = true - -##-------------------------------------------------------------------- -## MQTT/SSL - External SSL Listener for MQTT Protocol - -## listener.ssl.$name is the IP address and port that the MQTT/SSL -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 8883, 127.0.0.1:8883, ::1:8883 -listener.ssl.external = 8883 - -## The acceptor pool for external MQTT/SSL listener. -## -## Value: Number -listener.ssl.external.acceptors = 16 - -## Maximum number of concurrent MQTT/SSL connections. -## -## Value: Number -listener.ssl.external.max_connections = 102400 - -## Maximum MQTT/SSL connections per second. -## -## Value: Number -listener.ssl.external.max_conn_rate = 500 - -## Specify the {active, N} option for the internal MQTT/SSL Socket. -## -## Value: Number -listener.ssl.external.active_n = 100 - -## Zone of the external MQTT/SSL listener belonged to. -## -## Value: String -listener.ssl.external.zone = external - -## The access control rules for the MQTT/SSL listener. -## -## See: listener.tcp.$name.access -## -## Value: ACL Rule -listener.ssl.external.access.1 = allow all - -## Rate limit for the external MQTT/SSL connections. -## -## Value: limit,duration -## Default: 100KB incoming per 10 seconds. -## listener.ssl.external.rate_limit = 100KB,10s - -## Enable the Proxy Protocol V1/2 if the EMQ cluster is deployed behind -## HAProxy or Nginx. -## -## See: listener.tcp.$name.proxy_protocol -## -## Value: on | off -## listener.ssl.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. -## -## See: listener.tcp.$name.proxy_protocol_timeout -## -## Value: Duration -## listener.ssl.external.proxy_protocol_timeout = 3s - -## TLS versions only to protect from POODLE attack. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: String, seperated by ',' -## listener.ssl.external.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## TLS Handshake timeout. -## -## Value: Duration -listener.ssl.external.handshake_timeout = 15s - -## Path to the file containing the user's private PEM-encoded key. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: File -listener.ssl.external.keyfile = {{ platform_etc_dir }}/certs/key.pem - -## Path to a file containing the user certificate. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: File -listener.ssl.external.certfile = {{ platform_etc_dir }}/certs/cert.pem - -## Path to the file containing PEM-encoded CA certificates. The CA certificates -## are used during server authentication and when building the client certificate chain. -## -## Value: File -## listener.ssl.external.cacertfile = {{ platform_etc_dir }}/certs/cacert.pem - -## The Ephemeral Diffie-Helman key exchange is a very effective way of -## ensuring Forward Secrecy by exchanging a set of keys that never hit -## the wire. Since the DH key is effectively signed by the private key, -## it needs to be at least as strong as the private key. In addition, -## the default DH groups that most of the OpenSSL installations have -## are only a handful (since they are distributed with the OpenSSL -## package that has been built for the operating system it’s running on) -## and hence predictable (not to mention, 1024 bits only). -## In order to escape this situation, first we need to generate a fresh, -## strong DH group, store it in a file and then use the option above, -## to force our SSL application to use the new DH group. Fortunately, -## OpenSSL provides us with a tool to do that. Simply run: -## openssl dhparam -out dh-params.pem 2048 -## -## Value: File -## listener.ssl.external.dhfile = {{ platform_etc_dir }}/certs/dh-params.pem - -## A server only does x509-path validation in mode verify_peer, -## as it then sends a certificate request to the client (this -## message is not sent if the verify option is verify_none). -## You can then also want to specify option fail_if_no_peer_cert. -## More information at: http://erlang.org/doc/man/ssl.html -## -## Value: verify_peer | verify_none -## listener.ssl.external.verify = verify_peer - -## Used together with {verify, verify_peer} by an SSL server. If set to true, -## the server fails if the client does not have a certificate to send, that is, -## sends an empty certificate. -## -## Value: true | false -## listener.ssl.external.fail_if_no_peer_cert = true - -## This is the single most important configuration option of an Erlang SSL -## application. Ciphers (and their ordering) define the way the client and -## server encrypt information over the wire, from the initial Diffie-Helman -## key exchange, the session key encryption ## algorithm and the message -## digest algorithm. Selecting a good cipher suite is critical for the -## application’s data security, confidentiality and performance. -## -## The cipher list above offers: -## -## A good balance between compatibility with older browsers. -## It can get stricter for Machine-To-Machine scenarios. -## Perfect Forward Secrecy. -## No old/insecure encryption and HMAC algorithms -## -## Most of it was copied from Mozilla’s Server Side TLS article -## -## Value: Ciphers -listener.ssl.external.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA - -## Ciphers for TLS PSK. -## Note that 'listener.ssl.external.ciphers' and 'listener.ssl.external.psk_ciphers' cannot -## be configured at the same time. -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -#listener.ssl.external.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## SSL parameter renegotiation is a feature that allows a client and a server -## to renegotiate the parameters of the SSL connection on the fly. -## RFC 5746 defines a more secure way of doing this. By enabling secure renegotiation, -## you drop support for the insecure renegotiation, prone to MitM attacks. -## -## Value: on | off -## listener.ssl.external.secure_renegotiate = off - -## A performance optimization setting, it allows clients to reuse -## pre-existing sessions, instead of initializing new ones. -## Read more about it here. -## -## See: http://erlang.org/doc/man/ssl.html -## -## Value: on | off -## listener.ssl.external.reuse_sessions = on - -## An important security setting, it forces the cipher to be set based -## on the server-specified order instead of the client-specified order, -## hence enforcing the (usually more properly configured) security -## ordering of the server administrator. -## -## Value: on | off -## listener.ssl.external.honor_cipher_order = on - -## Use the CN, DN or CRT field from the client certificate as a username. -## Notice that 'verify' should be set as 'verify_peer'. -## -## Value: cn | dn | crt -## listener.ssl.external.peer_cert_as_username = cn - -## TCP backlog for the SSL connection. -## -## See listener.tcp.$name.backlog -## -## Value: Number >= 0 -## listener.ssl.external.backlog = 1024 - -## The TCP send timeout for the SSL connection. -## -## See listener.tcp.$name.send_timeout -## -## Value: Duration -## listener.ssl.external.send_timeout = 15s - -## Close the SSL connection if send timeout. -## -## See: listener.tcp.$name.send_timeout_close -## -## Value: on | off -## listener.ssl.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for the SSL connections. -## -## See: listener.tcp.$name.recbuf -## -## Value: Bytes -## listener.ssl.external.recbuf = 4KB - -## The TCP send buffer(os kernel) for internal MQTT connections. -## -## See: listener.tcp.$name.sndbuf -## -## Value: Bytes -## listener.ssl.external.sndbuf = 4KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.tcp.$name.buffer -## -## Value: Bytes -## listener.ssl.external.buffer = 4KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## See: listener.tcp.$name.tune_buffer -## -## Value: on | off -## listener.ssl.external.tune_buffer = off - -## The TCP_NODELAY flag for SSL connections. -## -## See: listener.tcp.$name.nodelay -## -## Value: true | false -## listener.ssl.external.nodelay = true - -## The SO_REUSEADDR flag for MQTT/SSL Listener. -## -## Value: true | false -listener.ssl.external.reuseaddr = true - -##-------------------------------------------------------------------- -## External WebSocket listener for MQTT protocol - -## listener.ws.$name is the IP address and port that the MQTT/WebSocket -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 8083, 127.0.0.1:8083, ::1:8083 -listener.ws.external = 8083 - -## The path of WebSocket MQTT endpoint -## -## Value: URL Path -listener.ws.external.mqtt_path = /mqtt - -## The acceptor pool for external MQTT/WebSocket listener. -## -## Value: Number -listener.ws.external.acceptors = 4 - -## Maximum number of concurrent MQTT/WebSocket connections. -## -## Value: Number -listener.ws.external.max_connections = 102400 - -## Maximum MQTT/WebSocket connections per second. -## -## Value: Number -listener.ws.external.max_conn_rate = 1000 - -## Simulate the {active, N} option for the MQTT/WebSocket connections. -## -## Value: Number -listener.ws.external.active_n = 100 - -## Rate limit for the MQTT/WebSocket connections. -## -## Value: Limit,Duration -## Default: 100KB incoming per 10 seconds. -## listener.ws.external.rate_limit = 100KB,10s - -## Zone of the external MQTT/WebSocket listener belonged to. -## -## Value: String -listener.ws.external.zone = external - -## The access control for the MQTT/WebSocket listener. -## -## See: listener.ws.$name.access -## -## Value: ACL Rule -listener.ws.external.access.1 = allow all - -## Verify if the protocol header is valid. Turn off for WeChat MiniApp. -## -## Value: on | off -listener.ws.external.verify_protocol_header = on - -## Enable the Proxy Protocol V1/2 if the EMQ cluster is deployed behind -## HAProxy or Nginx. -## -## See: listener.ws.$name.proxy_protocol -## -## Value: on | off -## listener.ws.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. -## -## See: listener.ws.$name.proxy_protocol_timeout -## -## Value: Duration -## listener.ws.external.proxy_protocol_timeout = 3s - -## The TCP backlog of external MQTT/WebSocket Listener. -## -## See: listener.ws.$name.backlog -## -## Value: Number >= 0 -listener.ws.external.backlog = 1024 - -## The TCP send timeout for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.send_timeout -## -## Value: Duration -listener.ws.external.send_timeout = 15s - -## Close the MQTT/WebSocket connection if send timeout. -## -## See: listener.ws.$name.send_timeout_close -## -## Value: on | off -listener.ws.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.recbuf -## -## Value: Bytes -## listener.ws.external.recbuf = 2KB - -## The TCP send buffer(os kernel) for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.sndbuf -## -## Value: Bytes -## listener.ws.external.sndbuf = 2KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.ws.$name.buffer -## -## Value: Bytes -## listener.ws.external.buffer = 2KB - -## Sets the 'buffer = max(sndbuf, recbuf)' if this option is enabled. -## -## See: listener.ws.$name.tune_buffer -## -## Value: on | off -## listener.ws.external.tune_buffer = off - -## The TCP_NODELAY flag for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.nodelay -## -## Value: true | false -listener.ws.external.nodelay = true - -## The compress flag for external MQTT/WebSocket connections. -## -## If this Value is set true,the websocket message would be compressed -## -## Value: true | false -## listener.ws.external.compress = true - -## The level of deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.level -## -## Value: none | default | best_compression | best_speed -## listener.ws.external.deflate_opts.level = default - -## The mem_level of deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.mem_level -## -## Valid range is 1-9 -## listener.ws.external.deflate_opts.mem_level = 8 - -## The strategy of deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.strategy -## -## Value: default | filtered | huffman_only | rle -## listener.ws.external.deflate_opts.strategy = default - -## The deflate option for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.server_context_takeover -## -## Value: takeover | no_takeover -## listener.ws.external.deflate_opts.server_context_takeover = takeover - -## The deflate option for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.client_context_takeover -## -## Value: takeover | no_takeover -## listener.ws.external.deflate_opts.client_context_takeover = takeover - -## The deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.server_max_window_bits -## -## Valid range is 8-15 -## listener.ws.external.deflate_opts.server_max_window_bits = 15 - -## The deflate options for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.deflate_opts.client_max_window_bits -## -## Valid range is 8-15 -## listener.ws.external.deflate_opts.client_max_window_bits = 15 - -## The idle timeout for external MQTT/WebSocket connections. -## -## See: listener.ws.$name.idle_timeout -## -## Value: Duration -## listener.ws.external.idle_timeout = 60s - -## The max frame size for external MQTT/WebSocket connections. -## -## -## Value: Number -## listener.ws.external.max_frame_size = 0 - -##-------------------------------------------------------------------- -## External WebSocket/SSL listener for MQTT Protocol - -## listener.wss.$name is the IP address and port that the MQTT/WebSocket/SSL -## listener will bind. -## -## Value: IP:Port | Port -## -## Examples: 8084, 127.0.0.1:8084, ::1:8084 -listener.wss.external = 8084 - -## The path of WebSocket MQTT endpoint -## -## Value: URL Path -listener.wss.external.mqtt_path = /mqtt - -## The acceptor pool for external MQTT/WebSocket/SSL listener. -## -## Value: Number -listener.wss.external.acceptors = 4 - -## Maximum number of concurrent MQTT/Webwocket/SSL connections. -## -## Value: Number -listener.wss.external.max_connections = 16 - -## Maximum MQTT/WebSocket/SSL connections per second. -## -## See: listener.tcp.$name.max_conn_rate -## -## Value: Number -listener.wss.external.max_conn_rate = 1000 - -## Simulate the {active, N} option for the MQTT/WebSocket/SSL connections. -## -## Value: Number -listener.wss.external.active_n = 100 - -## Rate limit for the MQTT/WebSocket/SSL connections. -## -## Value: Limit,Duration -## Default: 100KB incoming per 10 seconds. -## listener.wss.external.rate_limit = 100KB,10s - -## Zone of the external MQTT/WebSocket/SSL listener belonged to. -## -## Value: String -listener.wss.external.zone = external - -## The access control rules for the MQTT/WebSocket/SSL listener. -## -## See: listener.tcp.$name.access. -## -## Value: ACL Rule -listener.wss.external.access.1 = allow all - -## See: listener.ws.external.verify_protocol_header -## -## Value: on | off -listener.wss.external.verify_protocol_header = on - -## Enable the Proxy Protocol V1/2 support. -## -## See: listener.tcp.$name.proxy_protocol -## -## Value: on | off -## listener.wss.external.proxy_protocol = on - -## Sets the timeout for proxy protocol. -## -## See: listener.tcp.$name.proxy_protocol_timeout -## -## Value: Duration -## listener.wss.external.proxy_protocol_timeout = 3s - -## TLS versions only to protect from POODLE attack. -## -## See: listener.ssl.$name.tls_versions -## -## Value: String, seperated by ',' -## listener.wss.external.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## Path to the file containing the user's private PEM-encoded key. -## -## See: listener.ssl.$name.keyfile -## -## Value: File -listener.wss.external.keyfile = {{ platform_etc_dir }}/certs/key.pem - -## Path to a file containing the user certificate. -## -## See: listener.ssl.$name.certfile -## -## Value: File -listener.wss.external.certfile = {{ platform_etc_dir }}/certs/cert.pem - -## Path to the file containing PEM-encoded CA certificates. -## -## See: listener.ssl.$name.cacert -## -## Value: File -## listener.wss.external.cacertfile = {{ platform_etc_dir }}/certs/cacert.pem - -## See: listener.ssl.$name.dhfile -## -## Value: File -## listener.ssl.external.dhfile = {{ platform_etc_dir }}/certs/dh-params.pem - -## See: listener.ssl.$name.vefify -## -## Value: vefify_peer | verify_none -## listener.wss.external.verify = verify_peer - -## See: listener.ssl.$name.fail_if_no_peer_cert -## -## Value: false | true -## listener.wss.external.fail_if_no_peer_cert = true - -## See: listener.ssl.$name.ciphers -## -## Value: Ciphers -listener.wss.external.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA - -## Ciphers for TLS PSK. -## Note that 'listener.wss.external.ciphers' and 'listener.wss.external.psk_ciphers' cannot -## be configured at the same time. -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -## listener.wss.external.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## See: listener.ssl.$name.secure_renegotiate -## -## Value: on | off -## listener.wss.external.secure_renegotiate = off - -## See: listener.ssl.$name.reuse_sessions -## -## Value: on | off -## listener.wss.external.reuse_sessions = on - -## See: listener.ssl.$name.honor_cipher_order -## -## Value: on | off -## listener.wss.external.honor_cipher_order = on - -## See: listener.ssl.$name.peer_cert_as_username -## -## Value: cn | dn | crt -## listener.wss.external.peer_cert_as_username = cn - -## TCP backlog for the WebSocket/SSL connection. -## -## See: listener.tcp.$name.backlog -## -## Value: Number >= 0 -listener.wss.external.backlog = 1024 - -## The TCP send timeout for the WebSocket/SSL connection. -## -## See: listener.tcp.$name.send_timeout -## -## Value: Duration -listener.wss.external.send_timeout = 15s - -## Close the WebSocket/SSL connection if send timeout. -## -## See: listener.tcp.$name.send_timeout_close -## -## Value: on | off -listener.wss.external.send_timeout_close = on - -## The TCP receive buffer(os kernel) for the WebSocket/SSL connections. -## -## See: listener.tcp.$name.recbuf -## -## Value: Bytes -## listener.wss.external.recbuf = 4KB - -## The TCP send buffer(os kernel) for the WebSocket/SSL connections. -## -## See: listener.tcp.$name.sndbuf -## -## Value: Bytes -## listener.wss.external.sndbuf = 4KB - -## The size of the user-level software buffer used by the driver. -## -## See: listener.tcp.$name.buffer -## -## Value: Bytes -## listener.wss.external.buffer = 4KB - -## The TCP_NODELAY flag for WebSocket/SSL connections. -## -## See: listener.tcp.$name.nodelay -## -## Value: true | false -## listener.wss.external.nodelay = true - -## The compress flag for external WebSocket/SSL connections. -## -## If this Value is set true,the websocket message would be compressed -## -## Value: true | false -## listener.wss.external.compress = true - -## The level of deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.level -## -## Value: none | default | best_compression | best_speed -## listener.wss.external.deflate_opts.level = default - -## The mem_level of deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.mem_level -## -## Valid range is 1-9 -## listener.wss.external.deflate_opts.mem_level = 8 - -## The strategy of deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.strategy -## -## Value: default | filtered | huffman_only | rle -## listener.wss.external.deflate_opts.strategy = default - -## The deflate option for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.server_context_takeover -## -## Value: takeover | no_takeover -## listener.wss.external.deflate_opts.server_context_takeover = takeover - -## The deflate option for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.client_context_takeover -## -## Value: takeover | no_takeover -## listener.wss.external.deflate_opts.client_context_takeover = takeover - -## The deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.server_max_window_bits -## -## Valid range is 8-15 -## listener.wss.external.deflate_opts.server_max_window_bits = 15 - -## The deflate options for external WebSocket/SSL connections. -## -## See: listener.wss.$name.deflate_opts.client_max_window_bits -## -## Valid range is 8-15 -## listener.wss.external.deflate_opts.client_max_window_bits = 15 - -## The idle timeout for external WebSocket/SSL connections. -## -## See: listener.wss.$name.idle_timeout -## -## Value: Duration -## listener.wss.external.idle_timeout = 60s - -## The max frame size for external WebSocket/SSL connections. -## -## Value: Number -## listener.wss.external.max_frame_size = 0 - -##-------------------------------------------------------------------- -## Modules -##-------------------------------------------------------------------- -## The file to store loaded module names. -## -## Value: File -modules.loaded_file = {{ platform_data_dir }}/loaded_modules - -##-------------------------------------------------------------------- -## Presence Module - -## Sets the QoS for presence MQTT message. -## -## Value: 0 | 1 | 2 -module.presence.qos = 1 - -##-------------------------------------------------------------------- -## Subscription Module - -## Subscribe the Topics automatically when client connected. -## -## Value: String -## module.subscription.1.topic = connected/%c/%u - -## Qos of the proxy subscription. -## -## Value: 0 | 1 | 2 -## Default: 0 -## module.subscription.1.qos = 0 - -## No Local of the proxy subscription options. -## This configuration only takes effect in the MQTT V5 protocol. -## -## Value: 0 | 1 -## Default: 0 -## module.subscription.1.nl = 0 - -## Retain As Published of the proxy subscription options. -## This configuration only takes effect in the MQTT V5 protocol. -## -## Value: 0 | 1 -## Default: 0 -## module.subscription.1.rap = 0 - -## Retain Handling of the proxy subscription options. -## This configuration only takes effect in the MQTT V5 protocol. -## -## Value: 0 | 1 | 2 -## Default: 0 -## module.subscription.1.rh = 0 - -##-------------------------------------------------------------------- -## Rewrite Module - -## {rewrite, Topic, Re, Dest} -## module.rewrite.rule.1 = x/# ^x/y/(.+)$ z/y/$1 -## module.rewrite.rule.2 = y/+/z/# ^y/(.+)/z/(.+)$ y/z/$2 - -##------------------------------------------------------------------- -## Plugins -##------------------------------------------------------------------- - -## The etc dir for plugins' config. -## -## Value: Folder -plugins.etc_dir = {{ platform_etc_dir }}/plugins/ - -## The file to store loaded plugin names. -## -## Value: File -plugins.loaded_file = {{ platform_data_dir }}/loaded_plugins - -## The directory of extension plugins. -## -## Value: File -plugins.expand_plugins_dir = {{ platform_plugins_dir }}/ - -##-------------------------------------------------------------------- -## Broker -##-------------------------------------------------------------------- - -## System interval of publishing $SYS messages. -## -## Value: Duration -## Default: 1m, 1 minute -broker.sys_interval = 1m - -## System heartbeat interval of publishing following heart beat message: -## - "$SYS/brokers//uptime" -## - "$SYS/brokers//datetime" -## -## Value: Duration -## Default: 30s -broker.sys_heartbeat = 30s - -## Session locking strategy in a cluster. -## -## Value: Enum -## - local -## - one -## - quorum -## - all -broker.session_locking_strategy = quorum - -## Dispatch strategy for shared subscription -## -## Value: Enum -## - random -## - round_robin -## - sticky -## - hash -broker.shared_subscription_strategy = random - -## Enable/disable shared dispatch acknowledgement for QoS1 and QoS2 messages -## This should allow messages to be dispatched to a different subscriber in -## the group in case the picked (based on shared_subscription_strategy) one # is offline -## -## Value: Enum -## - true -## - false -broker.shared_dispatch_ack_enabled = false - -## Enable batch clean for deleted routes. -## -## Value: Flag -broker.route_batch_clean = off - -##-------------------------------------------------------------------- -## System Monitor -##-------------------------------------------------------------------- - -## Enable Long GC monitoring. Disable if the value is 0. -## Notice: don't enable the monitor in production for: -## https://hub.fastgit.org/erlang/otp/blob/feb45017da36be78d4c5784d758ede619fa7bfd3/erts/emulator/beam/erl_gc.c#L421 -## -## Value: Duration -## - h: hour -## - m: minute -## - s: second -## - ms: milliseconds -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 0.1s: 0.1 seconds -## - 100ms : 100 milliseconds -## -## Default: 0ms -sysmon.long_gc = 0 - -## Enable Long Schedule(ms) monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: Duration -## - h: hour -## - m: minute -## - s: second -## - ms: milliseconds -## -## Examples: -## - 2h: 2 hours -## - 30m: 30 minutes -## - 0.1s: 0.1 seconds -## - 100ms: 100 milliseconds -## -## Default: 0ms -sysmon.long_schedule = 240ms - -## Enable Large Heap monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: bytes -## -## Default: 8M words. 32MB on 32-bit VM, 64MB on 64-bit VM. -sysmon.large_heap = 8MB - -## Enable Busy Port monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: true | false -sysmon.busy_port = false - -## Enable Busy Dist Port monitoring. -## -## See: http://erlang.org/doc/man/erlang.html#system_monitor-2 -## -## Value: true | false -sysmon.busy_dist_port = true - -## The time interval for the periodic cpu check -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 60s -os_mon.cpu_check_interval = 60s - -## The threshold, as percentage of system cpu, for how much system cpu can be used before the corresponding alarm is set. -## -## Default: 80% -os_mon.cpu_high_watermark = 80% - -## The threshold, as percentage of system cpu, for how much system cpu can be used before the corresponding alarm is clear. -## -## Default: 60% -os_mon.cpu_low_watermark = 60% - -## The time interval for the periodic memory check -## -## Value: Duration -## -h: hour, e.g. '2h' for 2 hours -## -m: minute, e.g. '5m' for 5 minutes -## -s: second, e.g. '30s' for 30 seconds -## -## Default: 60s -os_mon.mem_check_interval = 60s - -## The threshold, as percentage of system memory, for how much system memory can be allocated before the corresponding alarm is set. -## -## Default: 70% -os_mon.sysmem_high_watermark = 70% - -## The threshold, as percentage of system memory, for how much system memory can be allocated by one Erlang process before the corresponding alarm is set. -## -## Default: 5% -os_mon.procmem_high_watermark = 5% - -## The time interval for the periodic process limit check -## -## Value: Duration -## -## Default: 30s -vm_mon.check_interval = 30s - -## The threshold, as percentage of processes, for how many processes can simultaneously exist at the local node before the corresponding alarm is set. -## -## Default: 80% -vm_mon.process_high_watermark = 80% - -## The threshold, as percentage of processes, for how many processes can simultaneously exist at the local node before the corresponding alarm is clear. -## -## Default: 60% -vm_mon.process_low_watermark = 60% - -{{ additional_configs }} diff --git a/_build/emqx/lib/emqx/etc/ssl_dist.conf b/_build/emqx/lib/emqx/etc/ssl_dist.conf deleted file mode 100644 index 50b0e32796..0000000000 --- a/_build/emqx/lib/emqx/etc/ssl_dist.conf +++ /dev/null @@ -1,11 +0,0 @@ -%% The options in the {server, Opts} tuple are used when calling ssl:ssl_accept/3, -%% and the options in the {client, Opts} tuple are used when calling ssl:connect/4. -%% -%% More information at: http://erlang.org/doc/apps/ssl/ssl_distribution.html -[{server, - [{certfile, "{{ platform_etc_dir }}/certs/cert.pem"}, - {keyfile, "{{ platform_etc_dir }}/certs/key.pem"}, - {secure_renegotiate, true}, - {depth, 0}]}, - {client, - [{secure_renegotiate, true}]}]. diff --git a/_build/emqx/lib/emqx/etc/vm.args b/_build/emqx/lib/emqx/etc/vm.args deleted file mode 100644 index d18d2f20db..0000000000 --- a/_build/emqx/lib/emqx/etc/vm.args +++ /dev/null @@ -1,115 +0,0 @@ -###################################################################### -## Erlang VM Args for EMQ X Broker -###################################################################### - -## NOTE: -## -## Arguments configured in this file might be overridden by configs from `emqx.conf`. -## -## Some basic VM arguments are to be configured in `emqx.conf`, -## such as `node.name` for `-name` and `node.cooke` for `-setcookie`. - -## Sets the maximum number of simultaneously existing processes for this system. -+P 2097152 - -## Sets the maximum number of simultaneously existing ports for this system. -+Q 1048576 - -## Sets the maximum number of ETS tables -+e 262144 - -## Sets the maximum number of atoms the virtual machine can handle. -#+t 1048576 - -## Set the location of crash dumps -#-env ERL_CRASH_DUMP {{ platform_log_dir }}/crash.dump - -## Set how many times generational garbages collections can be done without -## forcing a fullsweep collection. --env ERL_FULLSWEEP_AFTER 1000 - -## Heartbeat management; auto-restarts VM if it dies or becomes unresponsive -## (Disabled by default..use with caution!) -#-heart - -## Specify the erlang distributed protocol. -## Can be one of: inet_tcp, inet6_tcp, inet_tls -#-proto_dist inet_tcp - -## Specify SSL Options in the file if using SSL for Erlang Distribution. -## Used only when -proto_dist set to inet_tls -#-ssl_dist_optfile {{ platform_etc_dir }}/ssl_dist.conf - -## Specifies the net_kernel tick time in seconds. -## This is the approximate time a connected node may be unresponsive until -## it is considered down and thereby disconnected. --kernel net_ticktime 120 - -## Sets the distribution buffer busy limit (dist_buf_busy_limit). -#+zdbbl 8192 - -## Sets default scheduler hint for port parallelism. -+spp true - -## Sets the number of threads in async thread pool. Valid range is 0-1024. -## Increase the parameter if there are many simultaneous file I/O operations. -+A 4 - -## Sets the default heap size of processes to the size Size. -#+hms 233 - -## Sets the default binary virtual heap size of processes to the size Size. -#+hmbs 46422 - -## Sets the default maximum heap size of processes to the size Size. -## Defaults to 0, which means that no maximum heap size is used. -##For more information, see process_flag(max_heap_size, MaxHeapSize). -#+hmax 0 - -## Sets the default value for process flag message_queue_data. Defaults to on_heap. -#+hmqd on_heap | off_heap - -## Sets the number of IO pollsets to use when polling for I/O. -#+IOp 1 - -## Sets the number of IO poll threads to use when polling for I/O. -## Increase this for the busy systems with many concurrent connection. -+IOt 4 - -## Sets the number of scheduler threads to create and scheduler threads to set online. -#+S 8:8 - -## Sets the number of dirty CPU scheduler threads to create and dirty CPU scheduler threads to set online. -#+SDcpu 8:8 - -## Sets the number of dirty I/O scheduler threads to create. -+SDio 8 - -## Suggested stack size, in kilowords, for scheduler threads. -#+sss 32 - -## Suggested stack size, in kilowords, for dirty CPU scheduler threads. -#+sssdcpu 40 - -## Suggested stack size, in kilowords, for dirty IO scheduler threads. -#+sssdio 40 - -## Sets scheduler bind type. -## Can be one of: u, ns, ts, ps, s, nnts, nnps, tnnps, db -#+sbt db - -## Sets a user-defined CPU topology. -#+sct L0-3c0-3p0N0:L4-7c0-3p1N1 - -## Sets the mapping of warning messages for error_logger -#+W w - -## Sets time warp mode: no_time_warp | single_time_warp | multi_time_warp -#+C no_time_warp - -## Prevents loading information about source filenames and line numbers. -#+L - -## Specifies how long time (in milliseconds) to spend shutting down the system. -## See: http://erlang.org/doc/man/erl.html --shutdown_time 30000 diff --git a/_build/emqx/lib/emqx/etc/vm.args.edge b/_build/emqx/lib/emqx/etc/vm.args.edge deleted file mode 100644 index 9f722d1dd7..0000000000 --- a/_build/emqx/lib/emqx/etc/vm.args.edge +++ /dev/null @@ -1,114 +0,0 @@ -###################################################################### -## Erlang VM Args for EMQ X Edge -###################################################################### - -## NOTE: -## -## Arguments configured in this file might be overridden by configs from `emqx.conf`. -## -## Some basic VM arguments are to be configured in `emqx.conf`, -## such as `node.name` for `-name` and `node.cooke` for `-setcookie`. - -## Sets the maximum number of simultaneously existing processes for this system. -+P 16384 -## Sets the maximum number of simultaneously existing ports for this system. -+Q 4096 - -## Sets the maximum number of ETS tables -+e 512 - -## Sets the maximum number of atoms the virtual machine can handle. -+t 262144 - -## Set the location of crash dumps --env ERL_CRASH_DUMP {{ platform_log_dir }}/crash.dump - -## Set how many times generational garbages collections can be done without -## forcing a fullsweep collection. --env ERL_FULLSWEEP_AFTER 0 - -## Heartbeat management; auto-restarts VM if it dies or becomes unresponsive -## (Disabled by default..use with caution!) --heart - -## Specify the erlang distributed protocol. -## Can be one of: inet_tcp, inet6_tcp, inet_tls -#-proto_dist inet_tcp - -## Specify SSL Options in the file if using SSL for Erlang Distribution. -## Used only when -proto_dist set to inet_tls -#-ssl_dist_optfile {{ platform_etc_dir }}/ssl_dist.conf - -## Specifies the net_kernel tick time in seconds. -## This is the approximate time a connected node may be unresponsive until -## it is considered down and thereby disconnected. -#-kernel net_ticktime 60 - -## Sets the distribution buffer busy limit (dist_buf_busy_limit). -+zdbbl 1024 - -## Sets default scheduler hint for port parallelism. -+spp false - -## Sets the number of threads in async thread pool. Valid range is 0-1024. -## Increase the parameter if there are many simultaneous file I/O operations. -+A 1 - -## Sets the default heap size of processes to the size Size. -#+hms 233 - -## Sets the default binary virtual heap size of processes to the size Size. -#+hmbs 46422 - -## Sets the default maximum heap size of processes to the size Size. -## Defaults to 0, which means that no maximum heap size is used. -##For more information, see process_flag(max_heap_size, MaxHeapSize). -#+hmax 0 - -## Sets the default value for process flag message_queue_data. Defaults to on_heap. -#+hmqd on_heap | off_heap - -## Sets the number of IO pollsets to use when polling for I/O. -+IOp 1 - -## Sets the number of IO poll threads to use when polling for I/O. -+IOt 1 - -## Sets the number of scheduler threads to create and scheduler threads to set online. -+S 1:1 - -## Sets the number of dirty CPU scheduler threads to create and dirty CPU scheduler threads to set online. -+SDcpu 1:1 - -## Sets the number of dirty I/O scheduler threads to create. -+SDio 1 - -## Suggested stack size, in kilowords, for scheduler threads. -#+sss 32 - -## Suggested stack size, in kilowords, for dirty CPU scheduler threads. -#+sssdcpu 40 - -## Suggested stack size, in kilowords, for dirty IO scheduler threads. -#+sssdio 40 - -## Sets scheduler bind type. -## Can be one of: u, ns, ts, ps, s, nnts, nnps, tnnps, db -#+sbt db - -## Sets a user-defined CPU topology. -#+sct L0-3c0-3p0N0:L4-7c0-3p1N1 - -## Sets the mapping of warning messages for error_logger -#+W w - -## Sets time warp mode: no_time_warp | single_time_warp | multi_time_warp -#+C no_time_warp - -## Prevents loading information about source filenames and line numbers. -+L - -## Specifies how long time (in milliseconds) to spend shutting down the system. -## See: http://erlang.org/doc/man/erl.html --shutdown_time 10000 - diff --git a/_build/emqx/lib/emqx/include/emqx.hrl b/_build/emqx/lib/emqx/include/emqx.hrl deleted file mode 100644 index 5a10b84e65..0000000000 --- a/_build/emqx/lib/emqx/include/emqx.hrl +++ /dev/null @@ -1,170 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --ifndef(EMQ_X_HRL). --define(EMQ_X_HRL, true). - -%%-------------------------------------------------------------------- -%% Common -%%-------------------------------------------------------------------- - --define(Otherwise, true). - -%%-------------------------------------------------------------------- -%% Banner -%%-------------------------------------------------------------------- - --define(PROTOCOL_VERSION, "MQTT/5.0"). - --define(ERTS_MINIMUM_REQUIRED, "10.0"). - -%%-------------------------------------------------------------------- -%% Configs -%%-------------------------------------------------------------------- - --define(NO_PRIORITY_TABLE, none). - -%%-------------------------------------------------------------------- -%% Topics' prefix: $SYS | $queue | $share -%%-------------------------------------------------------------------- - -%% System topic --define(SYSTOP, <<"$SYS/">>). - -%% Queue topic --define(QUEUE, <<"$queue/">>). - -%%-------------------------------------------------------------------- -%% Message and Delivery -%%-------------------------------------------------------------------- - --record(subscription, {topic, subid, subopts}). - -%% See 'Application Message' in MQTT Version 5.0 --record(message, { - %% Global unique message ID - id :: binary(), - %% Message QoS - qos = 0, - %% Message from - from :: atom() | binary(), - %% Message flags - flags = #{} :: emqx_types:flags(), - %% Message headers. May contain any metadata. e.g. the - %% protocol version number, username, peerhost or - %% the PUBLISH properties (MQTT 5.0). - headers = #{} :: emqx_types:headers(), - %% Topic that the message is published to - topic :: emqx_types:topic(), - %% Message Payload - payload :: emqx_types:payload(), - %% Timestamp (Unit: millisecond) - timestamp :: integer() - }). - --record(delivery, { - sender :: pid(), %% Sender of the delivery - message :: #message{} %% The message delivered - }). - -%%-------------------------------------------------------------------- -%% Route -%%-------------------------------------------------------------------- - --record(route, { - topic :: binary(), - dest :: node() | {binary(), node()} - }). - -%%-------------------------------------------------------------------- -%% Trie -%%-------------------------------------------------------------------- - --type(trie_node_id() :: binary() | atom()). - --record(trie_node, { - node_id :: trie_node_id(), - edge_count = 0 :: non_neg_integer(), - topic :: binary() | undefined, - flags :: list(atom()) | undefined - }). - --record(trie_edge, { - node_id :: trie_node_id(), - word :: binary() | atom() - }). - --record(trie, { - edge :: #trie_edge{}, - node_id :: trie_node_id() - }). - -%%-------------------------------------------------------------------- -%% Alarm -%%-------------------------------------------------------------------- - --record(alarm, { - id :: binary(), - severity :: notice | warning | error | critical, - title :: iolist(), - summary :: iolist(), - %% Timestamp (Unit: millisecond) - timestamp :: integer() | undefined - }). - -%%-------------------------------------------------------------------- -%% Plugin -%%-------------------------------------------------------------------- - --record(plugin, { - name :: atom(), - dir :: string() | undefined, - descr :: string(), - vendor :: string() | undefined, - active = false :: boolean(), - info = #{} :: map(), - type :: atom() - }). - -%%-------------------------------------------------------------------- -%% Command -%%-------------------------------------------------------------------- - --record(command, { - name :: atom(), - action :: atom(), - args = [] :: list(), - opts = [] :: list(), - usage :: string(), - descr :: string() - }). - -%%-------------------------------------------------------------------- -%% Banned -%%-------------------------------------------------------------------- - --record(banned, { - who :: {clientid, binary()} - | {username, binary()} - | {ip_address, inet:ip_address()}, - by :: binary(), - reason :: binary(), - at :: integer(), - until :: integer() - }). - --endif. - diff --git a/_build/emqx/lib/emqx/include/emqx_mqtt.hrl b/_build/emqx/lib/emqx/include/emqx_mqtt.hrl deleted file mode 100644 index 078baf3013..0000000000 --- a/_build/emqx/lib/emqx/include/emqx_mqtt.hrl +++ /dev/null @@ -1,559 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --ifndef(EMQ_X_MQTT_HRL). --define(EMQ_X_MQTT_HRL, true). - --define(UINT_MAX, 16#FFFFFFFF). - -%%-------------------------------------------------------------------- -%% MQTT SockOpts -%%-------------------------------------------------------------------- - --define(MQTT_SOCKOPTS, [binary, {packet, raw}, {reuseaddr, true}, - {backlog, 512}, {nodelay, true}]). - -%%-------------------------------------------------------------------- -%% MQTT Protocol Version and Names -%%-------------------------------------------------------------------- - --define(MQTT_PROTO_V3, 3). --define(MQTT_PROTO_V4, 4). --define(MQTT_PROTO_V5, 5). - --define(PROTOCOL_NAMES, [ - {?MQTT_PROTO_V3, <<"MQIsdp">>}, - {?MQTT_PROTO_V4, <<"MQTT">>}, - {?MQTT_PROTO_V5, <<"MQTT">>}]). - -%%-------------------------------------------------------------------- -%% MQTT QoS Levels -%%-------------------------------------------------------------------- - --define(QOS_0, 0). %% At most once --define(QOS_1, 1). %% At least once --define(QOS_2, 2). %% Exactly once - --define(IS_QOS(I), (I >= ?QOS_0 andalso I =< ?QOS_2)). - --define(QOS_I(Name), - begin - (case Name of - ?QOS_0 -> ?QOS_0; - qos0 -> ?QOS_0; - at_most_once -> ?QOS_0; - ?QOS_1 -> ?QOS_1; - qos1 -> ?QOS_1; - at_least_once -> ?QOS_1; - ?QOS_2 -> ?QOS_2; - qos2 -> ?QOS_2; - exactly_once -> ?QOS_2 - end) - end). - --define(IS_QOS_NAME(I), - (I =:= qos0 orelse I =:= at_most_once orelse - I =:= qos1 orelse I =:= at_least_once orelse - I =:= qos2 orelse I =:= exactly_once)). - -%%-------------------------------------------------------------------- -%% Maximum ClientId Length. -%%-------------------------------------------------------------------- - --define(MAX_CLIENTID_LEN, 65535). - -%%-------------------------------------------------------------------- -%% MQTT Control Packet Types -%%-------------------------------------------------------------------- - --define(RESERVED, 0). %% Reserved --define(CONNECT, 1). %% Client request to connect to Server --define(CONNACK, 2). %% Server to Client: Connect acknowledgment --define(PUBLISH, 3). %% Publish message --define(PUBACK, 4). %% Publish acknowledgment --define(PUBREC, 5). %% Publish received (assured delivery part 1) --define(PUBREL, 6). %% Publish release (assured delivery part 2) --define(PUBCOMP, 7). %% Publish complete (assured delivery part 3) --define(SUBSCRIBE, 8). %% Client subscribe request --define(SUBACK, 9). %% Server Subscribe acknowledgment --define(UNSUBSCRIBE, 10). %% Unsubscribe request --define(UNSUBACK, 11). %% Unsubscribe acknowledgment --define(PINGREQ, 12). %% PING request --define(PINGRESP, 13). %% PING response --define(DISCONNECT, 14). %% Client or Server is disconnecting --define(AUTH, 15). %% Authentication exchange - --define(TYPE_NAMES, [ - 'CONNECT', - 'CONNACK', - 'PUBLISH', - 'PUBACK', - 'PUBREC', - 'PUBREL', - 'PUBCOMP', - 'SUBSCRIBE', - 'SUBACK', - 'UNSUBSCRIBE', - 'UNSUBACK', - 'PINGREQ', - 'PINGRESP', - 'DISCONNECT', - 'AUTH']). - -%%-------------------------------------------------------------------- -%% MQTT V3.1.1 Connect Return Codes -%%-------------------------------------------------------------------- - --define(CONNACK_ACCEPT, 0). %% Connection accepted --define(CONNACK_PROTO_VER, 1). %% Unacceptable protocol version --define(CONNACK_INVALID_ID, 2). %% Client Identifier is correct UTF-8 but not allowed by the Server --define(CONNACK_SERVER, 3). %% Server unavailable --define(CONNACK_CREDENTIALS, 4). %% Username or password is malformed --define(CONNACK_AUTH, 5). %% Client is not authorized to connect - -%%-------------------------------------------------------------------- -%% MQTT V5.0 Reason Codes -%%-------------------------------------------------------------------- - --define(RC_SUCCESS, 16#00). --define(RC_NORMAL_DISCONNECTION, 16#00). --define(RC_GRANTED_QOS_0, 16#00). --define(RC_GRANTED_QOS_1, 16#01). --define(RC_GRANTED_QOS_2, 16#02). --define(RC_DISCONNECT_WITH_WILL_MESSAGE, 16#04). --define(RC_NO_MATCHING_SUBSCRIBERS, 16#10). --define(RC_NO_SUBSCRIPTION_EXISTED, 16#11). --define(RC_CONTINUE_AUTHENTICATION, 16#18). --define(RC_RE_AUTHENTICATE, 16#19). --define(RC_UNSPECIFIED_ERROR, 16#80). --define(RC_MALFORMED_PACKET, 16#81). --define(RC_PROTOCOL_ERROR, 16#82). --define(RC_IMPLEMENTATION_SPECIFIC_ERROR, 16#83). --define(RC_UNSUPPORTED_PROTOCOL_VERSION, 16#84). --define(RC_CLIENT_IDENTIFIER_NOT_VALID, 16#85). --define(RC_BAD_USER_NAME_OR_PASSWORD, 16#86). --define(RC_NOT_AUTHORIZED, 16#87). --define(RC_SERVER_UNAVAILABLE, 16#88). --define(RC_SERVER_BUSY, 16#89). --define(RC_BANNED, 16#8A). --define(RC_SERVER_SHUTTING_DOWN, 16#8B). --define(RC_BAD_AUTHENTICATION_METHOD, 16#8C). --define(RC_KEEP_ALIVE_TIMEOUT, 16#8D). --define(RC_SESSION_TAKEN_OVER, 16#8E). --define(RC_TOPIC_FILTER_INVALID, 16#8F). --define(RC_TOPIC_NAME_INVALID, 16#90). --define(RC_PACKET_IDENTIFIER_IN_USE, 16#91). --define(RC_PACKET_IDENTIFIER_NOT_FOUND, 16#92). --define(RC_RECEIVE_MAXIMUM_EXCEEDED, 16#93). --define(RC_TOPIC_ALIAS_INVALID, 16#94). --define(RC_PACKET_TOO_LARGE, 16#95). --define(RC_MESSAGE_RATE_TOO_HIGH, 16#96). --define(RC_QUOTA_EXCEEDED, 16#97). --define(RC_ADMINISTRATIVE_ACTION, 16#98). --define(RC_PAYLOAD_FORMAT_INVALID, 16#99). --define(RC_RETAIN_NOT_SUPPORTED, 16#9A). --define(RC_QOS_NOT_SUPPORTED, 16#9B). --define(RC_USE_ANOTHER_SERVER, 16#9C). --define(RC_SERVER_MOVED, 16#9D). --define(RC_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED, 16#9E). --define(RC_CONNECTION_RATE_EXCEEDED, 16#9F). --define(RC_MAXIMUM_CONNECT_TIME, 16#A0). --define(RC_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED, 16#A1). --define(RC_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED, 16#A2). - -%%-------------------------------------------------------------------- -%% Maximum MQTT Packet ID and Length -%%-------------------------------------------------------------------- - --define(MAX_PACKET_ID, 16#FFFF). --define(MAX_PACKET_SIZE, 16#FFFFFFF). --define(MAX_TOPIC_AlIAS, 16#FFFF). - -%%-------------------------------------------------------------------- -%% MQTT Frame Mask -%%-------------------------------------------------------------------- - --define(HIGHBIT, 2#10000000). --define(LOWBITS, 2#01111111). - -%%-------------------------------------------------------------------- -%% MQTT Packet Fixed Header -%%-------------------------------------------------------------------- - --record(mqtt_packet_header, { - type = ?RESERVED, - dup = false, - qos = ?QOS_0, - retain = false - }). - -%%-------------------------------------------------------------------- -%% MQTT Packets -%%-------------------------------------------------------------------- - --define(DEFAULT_SUBOPTS, #{rh => 0, %% Retain Handling - rap => 0, %% Retain as Publish - nl => 0, %% No Local - qos => 0 %% QoS - }). - --record(mqtt_packet_connect, { - proto_name = <<"MQTT">>, - proto_ver = ?MQTT_PROTO_V4, - is_bridge = false, - clean_start = true, - will_flag = false, - will_qos = ?QOS_0, - will_retain = false, - keepalive = 0, - properties = #{}, - clientid = <<>>, - will_props = #{}, - will_topic = undefined, - will_payload = undefined, - username = undefined, - password = undefined - }). - --record(mqtt_packet_connack, { - ack_flags, - reason_code, - properties = #{} - }). - --record(mqtt_packet_publish, { - topic_name, - packet_id, - properties = #{} - }). - --record(mqtt_packet_puback, { - packet_id, - reason_code, - properties = #{} - }). - --record(mqtt_packet_subscribe, { - packet_id, - properties = #{}, - topic_filters - }). - --record(mqtt_packet_suback, { - packet_id, - properties = #{}, - reason_codes - }). - --record(mqtt_packet_unsubscribe, { - packet_id, - properties = #{}, - topic_filters - }). - --record(mqtt_packet_unsuback, { - packet_id, - properties = #{}, - reason_codes - }). - --record(mqtt_packet_disconnect, { - reason_code, - properties = #{} - }). - --record(mqtt_packet_auth, { - reason_code, - properties = #{} - }). - -%%-------------------------------------------------------------------- -%% MQTT Control Packet -%%-------------------------------------------------------------------- - --record(mqtt_packet, { - header :: #mqtt_packet_header{}, - variable :: #mqtt_packet_connect{} - | #mqtt_packet_connack{} - | #mqtt_packet_publish{} - | #mqtt_packet_puback{} - | #mqtt_packet_subscribe{} - | #mqtt_packet_suback{} - | #mqtt_packet_unsubscribe{} - | #mqtt_packet_unsuback{} - | #mqtt_packet_disconnect{} - | #mqtt_packet_auth{} - | pos_integer() - | undefined, - payload :: binary() | undefined - }). - -%%-------------------------------------------------------------------- -%% MQTT Message Internal -%%-------------------------------------------------------------------- - --record(mqtt_msg, { - qos = ?QOS_0, - retain = false, - dup = false, - packet_id, - topic, - props, - payload - }). - -%%-------------------------------------------------------------------- -%% MQTT Packet Match -%%-------------------------------------------------------------------- - --define(CONNECT_PACKET(), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNECT}}). - --define(CONNECT_PACKET(Var), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNECT}, - variable = Var}). - --define(CONNACK_PACKET(ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNACK}, - variable = #mqtt_packet_connack{ack_flags = 0, - reason_code = ReasonCode} - }). - --define(CONNACK_PACKET(ReasonCode, SessPresent), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNACK}, - variable = #mqtt_packet_connack{ack_flags = SessPresent, - reason_code = ReasonCode} - }). - --define(CONNACK_PACKET(ReasonCode, SessPresent, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?CONNACK}, - variable = #mqtt_packet_connack{ack_flags = SessPresent, - reason_code = ReasonCode, - properties = Properties} - }). - --define(AUTH_PACKET(), - #mqtt_packet{header = #mqtt_packet_header{type = ?AUTH}, - variable = #mqtt_packet_auth{reason_code = 0} - }). - --define(AUTH_PACKET(ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?AUTH}, - variable = #mqtt_packet_auth{reason_code = ReasonCode} - }). - --define(AUTH_PACKET(ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?AUTH}, - variable = #mqtt_packet_auth{reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBLISH_PACKET(QoS), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, qos = QoS}}). - --define(PUBLISH_PACKET(QoS, PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{packet_id = PacketId} - }). - --define(PUBLISH_PACKET(QoS, Topic, PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId} - }). - --define(PUBLISH_PACKET(QoS, Topic, PacketId, Payload), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId}, - payload = Payload - }). - --define(PUBLISH_PACKET(QoS, Topic, PacketId, Properties, Payload), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - qos = QoS}, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId, - properties = Properties}, - payload = Payload - }). - --define(PUBACK_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBACK}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBACK_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBACK}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBACK_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBACK}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBREC_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREC}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBREC_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREC}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBREC_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREC}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBREL_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREL, - qos = ?QOS_1}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBREL_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREL, - qos = ?QOS_1}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBREL_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBREL, - qos = ?QOS_1}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(PUBCOMP_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBCOMP}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = 0} - }). - --define(PUBCOMP_PACKET(PacketId, ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBCOMP}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode} - }). - --define(PUBCOMP_PACKET(PacketId, ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBCOMP}, - variable = #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties} - }). - --define(SUBSCRIBE_PACKET(PacketId, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_subscribe{packet_id = PacketId, - topic_filters = TopicFilters} - }). - --define(SUBSCRIBE_PACKET(PacketId, Properties, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_subscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters} - }). - --define(SUBACK_PACKET(PacketId, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBACK}, - variable = #mqtt_packet_suback{packet_id = PacketId, - reason_codes = ReasonCodes} - }). - --define(SUBACK_PACKET(PacketId, Properties, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?SUBACK}, - variable = #mqtt_packet_suback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes} - }). - --define(UNSUBSCRIBE_PACKET(PacketId, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_unsubscribe{packet_id = PacketId, - topic_filters = TopicFilters} - }). - --define(UNSUBSCRIBE_PACKET(PacketId, Properties, TopicFilters), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBSCRIBE, - qos = ?QOS_1}, - variable = #mqtt_packet_unsubscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters} - }). - --define(UNSUBACK_PACKET(PacketId), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBACK}, - variable = #mqtt_packet_unsuback{packet_id = PacketId} - }). - --define(UNSUBACK_PACKET(PacketId, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBACK}, - variable = #mqtt_packet_unsuback{packet_id = PacketId, - reason_codes = ReasonCodes} - }). - --define(UNSUBACK_PACKET(PacketId, Properties, ReasonCodes), - #mqtt_packet{header = #mqtt_packet_header{type = ?UNSUBACK}, - variable = #mqtt_packet_unsuback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes} - }). - --define(DISCONNECT_PACKET(), - #mqtt_packet{header = #mqtt_packet_header{type = ?DISCONNECT}, - variable = #mqtt_packet_disconnect{reason_code = 0} - }). - --define(DISCONNECT_PACKET(ReasonCode), - #mqtt_packet{header = #mqtt_packet_header{type = ?DISCONNECT}, - variable = #mqtt_packet_disconnect{reason_code = ReasonCode} - }). - --define(DISCONNECT_PACKET(ReasonCode, Properties), - #mqtt_packet{header = #mqtt_packet_header{type = ?DISCONNECT}, - variable = #mqtt_packet_disconnect{reason_code = ReasonCode, - properties = Properties} - }). - --define(PACKET(Type), #mqtt_packet{header = #mqtt_packet_header{type = Type}}). - --define(SHARE, "$share"). --define(SHARE(Group, Topic), emqx_topic:join([<>, Group, Topic])). --define(IS_SHARE(Topic), case Topic of <> -> true; _ -> false end). - --endif. diff --git a/_build/emqx/lib/emqx/include/logger.hrl b/_build/emqx/lib/emqx/include/logger.hrl deleted file mode 100644 index eb669a3fa5..0000000000 --- a/_build/emqx/lib/emqx/include/logger.hrl +++ /dev/null @@ -1,50 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% debug | info | notice | warning | error | critical | alert | emergency - --compile({parse_transform, emqx_logger}). - --define(DEBUG(Format), ?LOG(debug, Format, [])). --define(DEBUG(Format, Args), ?LOG(debug, Format, Args)). - --define(INFO(Format), ?LOG(info, Format, [])). --define(INFO(Format, Args), ?LOG(info, Format, Args)). - --define(NOTICE(Format), ?LOG(notice, Format, [])). --define(NOTICE(Format, Args), ?LOG(notice, Format, Args)). - --define(WARN(Format), ?LOG(warning, Format, [])). --define(WARN(Format, Args), ?LOG(warning, Format, Args)). - --define(ERROR(Format), ?LOG(error, Format, [])). --define(ERROR(Format, Args), ?LOG(error, Format, Args)). - --define(CRITICAL(Format), ?LOG(critical, Format, [])). --define(CRITICAL(Format, Args), ?LOG(critical, Format, Args)). - --define(ALERT(Format), ?LOG(alert, Format, [])). --define(ALERT(Format, Args), ?LOG(alert, Format, Args)). - --define(LOG(Level, Format), ?LOG(Level, Format, [])). - --define(LOG(Level, Format, Args), - begin - (logger:log(Level,#{},#{report_cb => fun(_) -> {'$logger_header'()++(Format), (Args)} end, - mfa => {?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY}, - line => ?LINE})) - end). - diff --git a/_build/emqx/lib/emqx/include/types.hrl b/_build/emqx/lib/emqx/include/types.hrl deleted file mode 100644 index e92f3f2a27..0000000000 --- a/_build/emqx/lib/emqx/include/types.hrl +++ /dev/null @@ -1,26 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --type(maybe(T) :: undefined | T). - --type(startlink_ret() :: {ok, pid()} | ignore | {error, term()}). - --type(ok_or_error(Reason) :: ok | {error, Reason}). - --type(ok_or_error(Value, Reason) :: {ok, Value} | {error, Reason}). - --type(mfargs() :: {module(), atom(), [term()]}). - diff --git a/_build/emqx/lib/emqx/priv/emqx.schema b/_build/emqx/lib/emqx/priv/emqx.schema deleted file mode 100644 index 6cb56cd073..0000000000 --- a/_build/emqx/lib/emqx/priv/emqx.schema +++ /dev/null @@ -1,2093 +0,0 @@ -%%-*- mode: erlang -*- -%% EMQ X R4.0 config mapping - -%%-------------------------------------------------------------------- -%% Cluster -%%-------------------------------------------------------------------- - -%% @doc Cluster name -{mapping, "cluster.name", "ekka.cluster_name", [ - {default, emqxcl}, - {datatype, atom} -]}. - -%% @doc Cluster discovery -{mapping, "cluster.discovery", "ekka.cluster_discovery", [ - {default, manual}, - {datatype, atom} -]}. - -%% @doc Clean down node from the cluster -{mapping, "cluster.autoclean", "ekka.cluster_autoclean", [ - {datatype, {duration, ms}} -]}. - -%% @doc Cluster autoheal -{mapping, "cluster.autoheal", "ekka.cluster_autoheal", [ - {datatype, flag}, - {default, off} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by static node list - -{mapping, "cluster.static.seeds", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by UDP Multicast - -{mapping, "cluster.mcast.addr", "ekka.cluster_discovery", [ - {default, "239.192.0.1"}, - {datatype, string} -]}. - -{mapping, "cluster.mcast.ports", "ekka.cluster_discovery", [ - {default, "4369"}, - {datatype, string} -]}. - -{mapping, "cluster.mcast.iface", "ekka.cluster_discovery", [ - {datatype, string}, - {default, "0.0.0.0"} -]}. - -{mapping, "cluster.mcast.ttl", "ekka.cluster_discovery", [ - {datatype, integer}, - {default, 255} -]}. - -{mapping, "cluster.mcast.loop", "ekka.cluster_discovery", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "cluster.mcast.sndbuf", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "16KB"} -]}. - -{mapping, "cluster.mcast.recbuf", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "16KB"} -]}. - -{mapping, "cluster.mcast.buffer", "ekka.cluster_discovery", [ - {datatype, bytesize}, - {default, "32KB"} -]}. - -%%-------------------------------------------------------------------- -%% Cluster by DNS A Record - -{mapping, "cluster.dns.name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%% @doc The erlang distributed protocol -{mapping, "cluster.proto_dist", "ekka.proto_dist", [ - {default, "inet_tcp"}, - {datatype, {enum, [inet_tcp, inet6_tcp, inet_tls]}}, - hidden -]}. - -{mapping, "cluster.dns.app", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster using etcd - -{mapping, "cluster.etcd.server", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.prefix", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.node_ttl", "ekka.cluster_discovery", [ - {datatype, {duration, ms}}, - {default, "1m"} -]}. - -{mapping, "cluster.etcd.ssl.keyfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.ssl.certfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.etcd.ssl.cacertfile", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Cluster on K8s - -{mapping, "cluster.k8s.apiserver", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.service_name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.address_type", "ekka.cluster_discovery", [ - {datatype, {enum, [ip, dns, hostname]}} -]}. - -{mapping, "cluster.k8s.app_name", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.namespace", "ekka.cluster_discovery", [ - {datatype, string} -]}. - -{mapping, "cluster.k8s.suffix", "ekka.cluster_discovery", [ - {datatype, string}, - {default, ""} - ]}. - -{translation, "ekka.cluster_discovery", fun(Conf) -> - Strategy = cuttlefish:conf_get("cluster.discovery", Conf), - Filter = fun(Opts) -> [{K, V} || {K, V} <- Opts, V =/= undefined] end, - IpPort = fun(S) -> - [Addr, Port] = string:tokens(S, ":"), - {ok, Ip} = inet:parse_address(Addr), - {Ip, Port} - end, - Options = fun(static) -> - [{seeds, [list_to_atom(S) || S <- string:tokens(cuttlefish:conf_get("cluster.static.seeds", Conf, ""), ",")]}]; - (mcast) -> - {ok, Addr} = inet:parse_address(cuttlefish:conf_get("cluster.mcast.addr", Conf)), - {ok, Iface} = inet:parse_address(cuttlefish:conf_get("cluster.mcast.iface", Conf)), - Ports = [list_to_integer(S) || S <- string:tokens(cuttlefish:conf_get("cluster.mcast.ports", Conf), ",")], - [{addr, Addr}, {ports, Ports}, {iface, Iface}, - {ttl, cuttlefish:conf_get("cluster.mcast.ttl", Conf, 1)}, - {loop, cuttlefish:conf_get("cluster.mcast.loop", Conf, true)}]; - (dns) -> - [{name, cuttlefish:conf_get("cluster.dns.name", Conf)}, - {app, cuttlefish:conf_get("cluster.dns.app", Conf)}]; - (etcd) -> - SslOpts = fun(Conf) -> - Options = cuttlefish_variable:filter_by_prefix("cluster.etcd.ssl", Conf), - lists:map(fun({["cluster", "etcd", "ssl", Name], Value}) -> - {list_to_atom(Name), Value} - end, Options) - end, - [{server, string:tokens(cuttlefish:conf_get("cluster.etcd.server", Conf), ",")}, - {prefix, cuttlefish:conf_get("cluster.etcd.prefix", Conf, "emqcl")}, - {node_ttl, cuttlefish:conf_get("cluster.etcd.node_ttl", Conf, 60)}, - {ssl_options, SslOpts(Conf)}]; - (k8s) -> - [{apiserver, cuttlefish:conf_get("cluster.k8s.apiserver", Conf)}, - {service_name, cuttlefish:conf_get("cluster.k8s.service_name", Conf)}, - {address_type, cuttlefish:conf_get("cluster.k8s.address_type", Conf, ip)}, - {app_name, cuttlefish:conf_get("cluster.k8s.app_name", Conf)}, - {namespace, cuttlefish:conf_get("cluster.k8s.namespace", Conf)}, - {suffix, cuttlefish:conf_get("cluster.k8s.suffix", Conf, "")}]; - (manual) -> - [ ] - end, - {Strategy, Filter(Options(Strategy))} -end}. - -%%-------------------------------------------------------------------- -%% Node -%%-------------------------------------------------------------------- - -%% @doc Node name -{mapping, "node.name", "vm_args.-name", [ - {default, "emqx@127.0.0.1"} -]}. - -%% @doc Specify SSL Options in the file if using SSL for erlang distribution -{mapping, "node.ssl_dist_optfile", "vm_args.-ssl_dist_optfile", [ - {datatype, string}, - hidden -]}. - -%% @doc Secret cookie for distributed erlang node -{mapping, "node.cookie", "vm_args.-setcookie", [ - {default, "emqxsecretcookie"} -]}. - -{mapping, "node.data_dir", "emqx.data_dir", [ - {datatype, string} -]}. - -%% @doc http://erlang.org/doc/man/heart.html -{mapping, "node.heartbeat", "vm_args.-heart", [ - {datatype, flag}, - hidden -]}. - -{translation, "vm_args.-heart", fun(Conf) -> - case cuttlefish:conf_get("node.heartbeat", Conf) of - true -> ""; - false -> cuttlefish:invalid("should be 'on' or comment the line!") - end -end}. - -%% @doc More information at: http://erlang.org/doc/man/erl.html -{mapping, "node.async_threads", "vm_args.+A", [ - {datatype, integer}, - {validators, ["range:0-1024"]} -]}. - -%% @doc Erlang Process Limit -{mapping, "node.process_limit", "vm_args.+P", [ - {datatype, integer}, - hidden -]}. - -%% @doc The maximum number of concurrent ports/sockets. -%% Valid range is 1024-134217727 -{mapping, "node.max_ports", "vm_args.+Q", [ - {datatype, integer}, - {validators, ["range4ports"]} -]}. - -{validator, "range4ports", "must be 1024 to 134217727", - fun(X) -> X >= 1024 andalso X =< 134217727 end}. - -%% @doc http://www.erlang.org/doc/man/erl.html#%2bzdbbl -{mapping, "node.dist_buffer_size", "vm_args.+zdbbl", [ - {datatype, bytesize}, - {commented, "32MB"}, - hidden, - {validators, ["zdbbl_range"]} -]}. - -{translation, "vm_args.+zdbbl", - fun(Conf) -> - ZDBBL = cuttlefish:conf_get("node.dist_buffer_size", Conf, undefined), - case ZDBBL of - undefined -> undefined; - X when is_integer(X) -> cuttlefish_util:ceiling(X / 1024); %% Bytes to Kilobytes; - _ -> undefined - end - end}. - -{validator, "zdbbl_range", "must be between 1KB and 2097151KB", - fun(ZDBBL) -> - %% 2097151KB = 2147482624 - ZDBBL >= 1024 andalso ZDBBL =< 2147482624 - end -}. - -%% @doc Global GC Interval -{mapping, "node.global_gc_interval", "emqx.global_gc_interval", [ - {datatype, {duration, s}} -]}. - -%% @doc http://www.erlang.org/doc/man/erlang.html#system_flag-2 -{mapping, "node.fullsweep_after", "vm_args.-env ERL_FULLSWEEP_AFTER", [ - {default, 1000}, - {datatype, integer}, - hidden, - {validators, ["positive_integer"]} -]}. - -{validator, "positive_integer", "must be a positive integer", - fun(X) -> X >= 0 end}. - -%% Note: OTP R15 and earlier uses -env ERL_MAX_ETS_TABLES, -%% R16+ uses +e -%% @doc The ETS table limit -{mapping, "node.max_ets_tables", - cuttlefish:otp("R16", "vm_args.+e", "vm_args.-env ERL_MAX_ETS_TABLES"), [ - {default, 256000}, - {datatype, integer}, - hidden -]}. - -%% @doc Set the location of crash dumps -{mapping, "node.crash_dump", "vm_args.-env ERL_CRASH_DUMP", [ - {default, "{{crash_dump}}"}, - {datatype, file}, - hidden -]}. - -%% @doc http://www.erlang.org/doc/man/kernel_app.html#net_ticktime -{mapping, "node.dist_net_ticktime", "vm_args.-kernel net_ticktime", [ - {datatype, integer}, - hidden -]}. - -%% @doc http://www.erlang.org/doc/man/kernel_app.html -{mapping, "node.dist_listen_min", "kernel.inet_dist_listen_min", [ - {commented, 6369}, - {datatype, integer}, - hidden -]}. - -%% @see node.dist_listen_min -{mapping, "node.dist_listen_max", "kernel.inet_dist_listen_max", [ - {commented, 6369}, - {datatype, integer}, - hidden -]}. - -%%-------------------------------------------------------------------- -%% RPC -%%-------------------------------------------------------------------- - -%% RPC Mode. -{mapping, "rpc.mode", "emqx.rpc_mode", [ - {default, async}, - {datatype, {enum, [sync, async]}} -]}. - -{mapping, "rpc.async_batch_size", "gen_rpc.max_batch_size", [ - {default, 256}, - {datatype, integer} -]}. - -%% RPC server port. -{mapping, "rpc.tcp_server_port", "gen_rpc.tcp_server_port", [ - {default, 5369}, - {datatype, integer} -]}. - -%% Default TCP port for outgoing connections -{mapping, "rpc.tcp_client_port", "gen_rpc.tcp_client_port", [ - {default, 5369}, - {datatype, integer} -]}. - -%% Default TCP port for outgoing connections -{mapping, "rpc.tcp_client_num", "gen_rpc.tcp_client_num", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:gt_0_lt_256"]} -]}. - -{translation, "gen_rpc.tcp_client_num", fun(Conf) -> - case cuttlefish:conf_get("rpc.tcp_client_num", Conf) of - 0 -> max(1, erlang:system_info(schedulers) div 2); - V -> V - end -end}. - -%% Client connect timeout -{mapping, "rpc.connect_timeout", "gen_rpc.connect_timeout", [ - {default, "5s"}, - {datatype, {duration, ms}} -]}. - -%% Client and Server send timeout -{mapping, "rpc.send_timeout", "gen_rpc.send_timeout", [ - {default, 5000}, - {datatype, {duration, ms}} -]}. - -%% Authentication timeout -{mapping, "rpc.authentication_timeout", "gen_rpc.authentication_timeout", [ - {default, 5000}, - {datatype, {duration, ms}} -]}. - -%% Default receive timeout for call() functions -{mapping, "rpc.call_receive_timeout", "gen_rpc.call_receive_timeout", [ - {default, 15000}, - {datatype, {duration, ms}} -]}. - -%% Socket keepalive configuration -{mapping, "rpc.socket_keepalive_idle", "gen_rpc.socket_keepalive_idle", [ - {default, 7200}, - {datatype, {duration, s}} -]}. - -%% Seconds between probes -{mapping, "rpc.socket_keepalive_interval", "gen_rpc.socket_keepalive_interval", [ - {default, 75}, - {datatype, {duration, s}} -]}. - -%% Probes lost to close the connection -{mapping, "rpc.socket_keepalive_count", "gen_rpc.socket_keepalive_count", [ - {default, 9}, - {datatype, integer} -]}. - -%% Size of TCP send buffer -{mapping, "rpc.socket_sndbuf", "gen_rpc.socket_sndbuf", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -%% Size of TCP receive buffer -{mapping, "rpc.socket_recbuf", "gen_rpc.socket_recbuf", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -%% Size of TCP receive buffer -{mapping, "rpc.socket_buffer", "gen_rpc.socket_buffer", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -{validator, "range:gt_0_lt_256", "must greater than 0 and less than 256", - fun(X) -> X >= 0 andalso X < 256 end -}. - -%%-------------------------------------------------------------------- -%% Log -%%-------------------------------------------------------------------- - -{mapping, "log.to", "kernel.logger", [ - {default, console}, - {datatype, {enum, [off, file, console, both]}} -]}. - -{mapping, "log.level", "kernel.logger", [ - {default, warning}, - {datatype, {enum, [debug, info, notice, warning, error, critical, alert, emergency, all]}} -]}. - -{mapping, "log.primary_log_level", "kernel.logger_level", [ - {default, warning}, - {datatype, {enum, [debug, info, notice, warning, error, critical, alert, emergency, all]}} -]}. - -{mapping, "log.logger_sasl_compatible", "kernel.logger_sasl_compatible", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "log.dir", "kernel.logger", [ - {default, "log"}, - {datatype, string} -]}. - -{mapping, "log.file", "kernel.logger", [ - {default, "emqx.log"}, - {datatype, file} -]}. - -{mapping, "log.chars_limit", "kernel.logger", [ - {default, -1}, - {datatype, integer} -]}. - -{mapping, "log.rotation", "kernel.logger", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "log.rotation.size", "kernel.logger", [ - {default, "10MB"}, - {datatype, bytesize} -]}. - -{mapping, "log.size", "kernel.logger", [ - {default, infinity}, - {datatype, [bytesize, atom]} -]}. - -{mapping, "log.rotation.count", "kernel.logger", [ - {default, 5}, - {datatype, integer} -]}. - -{mapping, "log.$level.file", "kernel.logger", [ - {datatype, file} -]}. - -{mapping, "log.sync_mode_qlen", "kernel.logger", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "log.drop_mode_qlen", "kernel.logger", [ - {default, 3000}, - {datatype, integer} -]}. - -{mapping, "log.flush_qlen", "kernel.logger", [ - {default, 8000}, - {datatype, integer} -]}. - -{mapping, "log.overload_kill", "kernel.logger", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "log.overload_kill_mem_size", "kernel.logger", [ - {default, "30MB"}, - {datatype, bytesize} -]}. - -{mapping, "log.overload_kill_qlen", "kernel.logger", [ - {default, 20000}, - {datatype, integer} -]}. - -{mapping, "log.overload_kill_restart_after", "kernel.logger", [ - {default, "5s"}, - {datatype, [{duration, ms}, atom]} -]}. - -{mapping, "log.burst_limit", "kernel.logger", [ - {default, "disabled"}, - {datatype, string} -]}. - -{mapping, "log.sasl", "sasl.sasl_error_logger", [ - {default, off}, - {datatype, flag}, - hidden -]}. - -{mapping, "log.error_logger", "kernel.error_logger", [ - {default, silent}, - {datatype, {enum, [silent]}}, - hidden -]}. - -%% disable lager -{mapping, "lager.handlers", "lager.handlers", [ - {default, []}, - hidden -]}. -{mapping, "lager.crash_log", "lager.crash_log", [ - {default, off}, - {datatype, flag}, - hidden -]}. - -{translation, "kernel.logger_level", fun(_, _, Conf) -> - cuttlefish:conf_get("log.level", Conf) -end}. - -{translation, "kernel.logger", fun(Conf) -> - LogTo = cuttlefish:conf_get("log.to", Conf), - LogLevel = cuttlefish:conf_get("log.level", Conf), - LogType = case cuttlefish:conf_get("log.rotation", Conf) of - true -> wrap; - false -> halt - end, - CharsLimit = case cuttlefish:conf_get("log.chars_limit", Conf) of - -1 -> unlimited; - V -> V - end, - Formatter = {emqx_logger_formatter, - #{template => - [time," [",level,"] ", - {clientid, - [{peername, - [clientid,"@",peername," "], - [clientid, " "]}], - [{peername, - [peername," "], - []}]}, - msg,"\n"], - chars_limit => CharsLimit}}, - {BustLimitOn, {MaxBurstCount, TimeWindow}} = - case string:tokens(cuttlefish:conf_get("log.burst_limit", Conf), ", ") of - ["disabled"] -> {false, {20000, 1000}}; - [Count, Window] -> - {true, {list_to_integer(Count), - case cuttlefish_duration:parse(Window, ms) of - Secs when is_integer(Secs) -> Secs; - {error, Reason1} -> error(Reason1) - end}} - end, - FileConf = fun(Filename) -> - BasicConf = - #{type => LogType, - file => filename:join(cuttlefish:conf_get("log.dir", Conf), Filename), - max_no_files => cuttlefish:conf_get("log.rotation.count", Conf), - sync_mode_qlen => cuttlefish:conf_get("log.sync_mode_qlen", Conf), - drop_mode_qlen => cuttlefish:conf_get("log.drop_mode_qlen", Conf), - flush_qlen => cuttlefish:conf_get("log.flush_qlen", Conf), - overload_kill_enable => cuttlefish:conf_get("log.overload_kill", Conf), - overload_kill_qlen => cuttlefish:conf_get("log.overload_kill_qlen", Conf), - overload_kill_mem_size => cuttlefish:conf_get("log.overload_kill_mem_size", Conf), - overload_kill_restart_after => cuttlefish:conf_get("log.overload_kill_restart_after", Conf), - burst_limit_enable => BustLimitOn, - burst_limit_max_count => MaxBurstCount, - burst_limit_window_time => TimeWindow - }, - MaxNoBytes = case LogType of - wrap -> cuttlefish:conf_get("log.rotation.size", Conf); - halt -> cuttlefish:conf_get("log.size", Conf) - end, - BasicConf#{max_no_bytes => MaxNoBytes} - end, - - %% For the default logger that outputs to console - DefaultHandler = - if LogTo =:= console orelse LogTo =:= both -> - [{handler, default, logger_std_h, - #{level => LogLevel, - config => #{type => standard_io}, - formatter => Formatter}}]; - true -> - [{handler, default, undefined}] - end, - - %% For the file logger - FileHandler = - if LogTo =:= file orelse LogTo =:= both -> - [{handler, file, logger_disk_log_h, - #{level => LogLevel, - config => FileConf(cuttlefish:conf_get("log.file", Conf)), - formatter => Formatter, - filesync_repeat_interval => no_repeat}}]; - true -> [] - end, - - %% For creating additional log files for specific log levels. - AdditionalLogFiles = - lists:foldl( - fun({[_, Level, _] = K, Filename}, Acc) when LogTo =:= file; LogTo =:= both -> - case cuttlefish_variable:is_fuzzy_match(K, ["log", "$level", "file"]) of - true -> [{Level, Filename} | Acc]; - false -> Acc - end; - ({_K, _V}, Acc) -> - Acc - end, [], Conf), - AdditionalHandlers = - [{handler, list_to_atom("file_for_"++Level), logger_disk_log_h, - #{level => list_to_atom(Level), - config => FileConf(Filename), - formatter => Formatter, - filesync_repeat_interval => no_repeat}} - || {Level, Filename} <- AdditionalLogFiles], - - DefaultHandler ++ FileHandler ++ AdditionalHandlers -end}. - -%%-------------------------------------------------------------------- -%% Authentication/ACL -%%-------------------------------------------------------------------- - -%% @doc Allow anonymous authentication. -{mapping, "allow_anonymous", "emqx.allow_anonymous", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc ACL nomatch. -{mapping, "acl_nomatch", "emqx.acl_nomatch", [ - {default, deny}, - {datatype, {enum, [allow, deny]}} -]}. - -%% @doc Default ACL file. -{mapping, "acl_file", "emqx.acl_file", [ - {datatype, string}, - hidden -]}. - -%% @doc Enable ACL cache for publish. -{mapping, "enable_acl_cache", "emqx.enable_acl_cache", [ - {default, on}, - {datatype, flag} -]}. - -%% @doc ACL cache time-to-live. -{mapping, "acl_cache_ttl", "emqx.acl_cache_ttl", [ - {default, "1m"}, - {datatype, {duration, ms}} -]}. - -%% @doc ACL cache size. -{mapping, "acl_cache_max_size", "emqx.acl_cache_max_size", [ - {default, 32}, - {datatype, integer}, - {validators, ["range:gt_0"]} -]}. - -%% @doc Action when acl check reject current operation -{mapping, "acl_deny_action", "emqx.acl_deny_action", [ - {default, ignore}, - {datatype, {enum, [ignore, disconnect]}} -]}. - -%% @doc Flapping detect policy -{mapping, "flapping_detect_policy", "emqx.flapping_detect_policy", [ - {datatype, string}, - {default, "30,1m,5m"} -]}. - -{translation, "emqx.flapping_detect_policy", fun(Conf) -> - Policy = cuttlefish:conf_get("flapping_detect_policy", Conf), - [Threshold, Duration, Interval] = string:tokens(Policy, ", "), - ParseDuration = fun(S, Dur) -> - case cuttlefish_duration:parse(S, Dur) of - I when is_integer(I) -> I; - {error, Reason} -> error(Reason) - end - end, - #{threshold => list_to_integer(Threshold), - duration => ParseDuration(Duration, ms), - banned_interval => ParseDuration(Interval, s) - } -end}. - -{validator, "range:gt_0", "must greater than 0", - fun(X) -> X > 0 end -}. - -%%-------------------------------------------------------------------- -%% MQTT Protocol -%%-------------------------------------------------------------------- - -%% @doc Max Packet Size Allowed, 1MB by default. -{mapping, "mqtt.max_packet_size", "emqx.max_packet_size", [ - {default, "1MB"}, - {datatype, bytesize} -]}. - -%% @doc Set the Max ClientId Length Allowed. -{mapping, "mqtt.max_clientid_len", "emqx.max_clientid_len", [ - {default, 65535}, - {datatype, integer} -]}. - -%% @doc Set the Maximum topic levels. -{mapping, "mqtt.max_topic_levels", "emqx.max_topic_levels", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Set the Maximum QoS allowed. -{mapping, "mqtt.max_qos_allowed", "emqx.max_qos_allowed", [ - {default, 2}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -%% @doc Set the Maximum Topic Alias. -{mapping, "mqtt.max_topic_alias", "emqx.max_topic_alias", [ - {default, 65535}, - {datatype, integer} -]}. - -%% @doc Whether the server supports MQTT retained messages. -{mapping, "mqtt.retain_available", "emqx.retain_available", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports MQTT Wildcard Subscriptions. -{mapping, "mqtt.wildcard_subscription", "emqx.wildcard_subscription", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports MQTT Shared Subscriptions. -{mapping, "mqtt.shared_subscription", "emqx.shared_subscription", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether to ignore loop delivery of messages.(for mqtt v3.1.1) -{mapping, "mqtt.ignore_loop_deliver", "emqx.ignore_loop_deliver", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether to parse the MQTT frame in strict mode -{mapping, "mqtt.strict_mode", "emqx.strict_mode", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Specify the response information returned to the client -{mapping, "mqtt.response_information", "emqx.response_information", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Zones -%%-------------------------------------------------------------------- - -%% @doc Idle timeout of the MQTT connection. -{mapping, "zone.$name.idle_timeout", "emqx.zones", [ - {default, "15s"}, - {datatype, {duration, ms}} -]}. - -{mapping, "zone.$name.allow_anonymous", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "zone.$name.acl_nomatch", "emqx.zones", [ - {datatype, {enum, [allow, deny]}} -]}. - -%% @doc Enable ACL check. -{mapping, "zone.$name.enable_acl", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Action when acl check reject current operation -{mapping, "zone.$name.acl_deny_action", "emqx.zones", [ - {default, ignore}, - {datatype, {enum, [ignore, disconnect]}} -]}. - -%% @doc Enable Ban. -{mapping, "zone.$name.enable_ban", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Enable per connection statistics. -{mapping, "zone.$name.enable_stats", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Publish limit of the MQTT connections. -{mapping, "zone.$name.publish_limit", "emqx.zones", [ - {datatype, string} -]}. - -%% @doc Max Packet Size Allowed, 64K by default. -{mapping, "zone.$name.max_packet_size", "emqx.zones", [ - {datatype, bytesize} -]}. - -%% @doc Set the Max ClientId Length Allowed. -{mapping, "zone.$name.max_clientid_len", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Set the Maximum topic levels. -{mapping, "zone.$name.max_topic_levels", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Set the Maximum QoS allowed. -{mapping, "zone.$name.max_qos_allowed", "emqx.zones", [ - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -%% @doc Set the Maximum topic alias. -{mapping, "zone.$name.max_topic_alias", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Whether the server supports retained messages. -{mapping, "zone.$name.retain_available", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports Wildcard Subscriptions. -{mapping, "zone.$name.wildcard_subscription", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether the Server supports Shared Subscriptions. -{mapping, "zone.$name.shared_subscription", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Server Keepalive -{mapping, "zone.$name.server_keepalive", "emqx.zones", [ - {datatype, integer} -]}. - -%% @doc Keepalive backoff -{mapping, "zone.$name.keepalive_backoff", "emqx.zones", [ - {default, 0.75}, - {datatype, float} -]}. - -%% @doc Max Number of Subscriptions Allowed. -{mapping, "zone.$name.max_subscriptions", "emqx.zones", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Upgrade QoS according to subscription? -{mapping, "zone.$name.upgrade_qos", "emqx.zones", [ - {default, off}, - {datatype, flag} -]}. - -%% @doc Max number of QoS 1 and 2 messages that can be “inflight” at one time. -%% 0 means no limit -{mapping, "zone.$name.max_inflight", "emqx.zones", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Retry interval for redelivering QoS1/2 messages. -{mapping, "zone.$name.retry_interval", "emqx.zones", [ - {default, "30s"}, - {datatype, {duration, s}} -]}. - -%% @doc Max Packets that Awaiting PUBREL, 0 means no limit -{mapping, "zone.$name.max_awaiting_rel", "emqx.zones", [ - {default, 0}, - {datatype, integer} -]}. - -%% @doc Awaiting PUBREL timeout -{mapping, "zone.$name.await_rel_timeout", "emqx.zones", [ - {default, "300s"}, - {datatype, {duration, s}} -]}. - -%% @doc Ignore loop delivery of messages -{mapping, "zone.$name.ignore_loop_deliver", "emqx.zones", [ - {datatype, {enum, [true, false]}} -]}. - -%% @doc Session Expiry Interval -{mapping, "zone.$name.session_expiry_interval", "emqx.zones", [ - {default, "2h"}, - {datatype, {duration, s}} -]}. - -%% @doc Max queue length. Enqueued messages when persistent client -%% disconnected, or inflight window is full. 0 means no limit. -{mapping, "zone.$name.max_mqueue_len", "emqx.zones", [ - {default, 1000}, - {datatype, integer} -]}. - -%% @doc Topic Priorities, comma separated topic=priority pairs, -%% where priority should be integer in range 1-255 (inclusive) -%% 1 being the lowest and 255 being the highest. -%% default value `none` to indicate no priority table, hence all -%% messages are treated equal, which means either highest ('infinity'), -%% or lowest (0) depending on mqueue_default_priority config. -{mapping, "zone.$name.mqueue_priorities", "emqx.zones", [ - {default, "none"}, - {datatype, string} -]}. - -%% @doc Default priority for topics not in priority table. -{mapping, "zone.$name.mqueue_default_priority", "emqx.zones", [ - {default, lowest}, - {datatype, {enum, [highest, lowest]}} -]}. - -%% @doc Queue Qos0 messages? -{mapping, "zone.$name.mqueue_store_qos0", "emqx.zones", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "zone.$name.enable_flapping_detect", "emqx.zones", [ - {datatype, flag}, - {default, off} -]}. - -%% @doc Force connection/session process GC after this number of -%% messages | bytes passed through. -%% Numbers delimited by `|'. Zero or negative is to disable. -{mapping, "zone.$name.force_gc_policy", "emqx.zones", [ - {datatype, string} - ]}. - -%% @doc Max message queue length and total heap size to force shutdown -%% connection/session process. -%% Message queue here is the Erlang process mailbox, but not the number -%% of queued MQTT messages of QoS 1 and 2. -%% Zero or negative is to disable. -{mapping, "zone.$name.force_shutdown_policy", "emqx.zones", [ - {datatype, string} -]}. - -{mapping, "zone.$name.mountpoint", "emqx.zones", [ - {datatype, string} -]}. - -%% @doc Use username replace client id -{mapping, "zone.$name.use_username_as_clientid", "emqx.zones", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Whether to parse the MQTT frame in strict mode -{mapping, "zone.$name.strict_mode", "emqx.zones", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Specify the response information returned to the client -{mapping, "zone.$name.response_information", "emqx.zones", [ - {datatype, string} -]}. - -%% @doc Whether to bypass the authentication step -{mapping, "zone.$name.bypass_auth_plugins", "emqx.zones", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -{translation, "emqx.zones", fun(Conf) -> - Mapping = fun("publish_limit", Val) -> - [L, D] = string:tokens(Val, ", "), - Limit = list_to_integer(L), - Duration = case cuttlefish_duration:parse(D, s) of - Secs when is_integer(Secs) -> Secs; - {error, Reason} -> error(Reason) - end, - Rate = Limit / Duration, - {publish_limit, {Rate, Limit}}; - ("force_gc_policy", Val) -> - [Count, Bytes] = string:tokens(Val, "| "), - GcPolicy = case cuttlefish_bytesize:parse(Bytes) of - {error, Reason} -> - error(Reason); - Bytes1 -> - #{bytes => Bytes1, - count => list_to_integer(Count)} - end, - {force_gc_policy, GcPolicy}; - ("force_shutdown_policy", Val) -> - [Len, Siz] = string:tokens(Val, "| "), - MaxSiz = case WordSize = erlang:system_info(wordsize) of - 8 -> % arch_64 - (1 bsl 59) - 1; - 4 -> % arch_32 - (1 bsl 27) - 1 - end, - ShutdownPolicy = - case cuttlefish_bytesize:parse(Siz) of - {error, Reason} -> - error(Reason); - Siz1 when Siz1 > MaxSiz -> - cuttlefish:invalid(io_lib:format("force_shutdown_policy: heap-size ~s is too large", [Siz])); - Siz1 -> - #{message_queue_len => list_to_integer(Len), - max_heap_size => Siz1 div WordSize} - end, - {force_shutdown_policy, ShutdownPolicy}; - ("mqueue_priorities", Val) -> - case Val of - "none" -> {mqueue_priorities, none}; % NO_PRIORITY_TABLE - _ -> - MqueuePriorities = lists:foldl(fun(T, Acc) -> - %% NOTE: space in "= " is intended - [Topic, Prio] = string:tokens(T, "= "), - P = list_to_integer(Prio), - (P < 0 orelse P > 255) andalso error({bad_priority, Topic, Prio}), - maps:put(iolist_to_binary(Topic), P, Acc) - end, #{}, string:tokens(Val, ",")), - {mqueue_priorities, MqueuePriorities} - end; - ("mountpoint", Val) -> - {mountpoint, iolist_to_binary(Val)}; - ("response_information", Val) -> - {response_information, iolist_to_binary(Val)}; - (Opt, Val) -> - {list_to_atom(Opt), Val} - end, - maps:to_list( - lists:foldl( - fun({["zone", Name, Opt], Val}, Zones) -> - maps:update_with(list_to_atom(Name), - fun(Opts) -> [Mapping(Opt, Val)|Opts] end, - [Mapping(Opt, Val)], Zones) - end, #{}, lists:usort(cuttlefish_variable:filter_by_prefix("zone.", Conf)))) -end}. - -%%-------------------------------------------------------------------- -%% Listeners -%%-------------------------------------------------------------------- - -%%-------------------------------------------------------------------- -%% TCP Listeners - -{mapping, "listener.tcp.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.tcp.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.tcp.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.tcp.$name.rate_limit", "emqx.listeners", [ - {default, undefined}, - {datatype, string} -]}. - -{mapping, "listener.tcp.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.tcp.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.tcp.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -{mapping, "listener.tcp.$name.peer_cert_as_username", "emqx.listeners", [ - {datatype, {enum, [cn, dn, crt]}} -]}. - -{mapping, "listener.tcp.$name.backlog", "emqx.listeners", [ - {datatype, integer}, - {default, 1024} -]}. - -{mapping, "listener.tcp.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.tcp.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.tcp.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.tcp.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.tcp.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.tcp.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.tcp.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.tcp.$name.reuseaddr", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -%%-------------------------------------------------------------------- -%% SSL Listeners - -{mapping, "listener.ssl.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.ssl.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.rate_limit", "emqx.listeners", [ - {default, undefined}, - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -{mapping, "listener.ssl.$name.backlog", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ssl.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.ssl.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.ssl.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ssl.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ssl.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ssl.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.ssl.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ssl.$name.reuseaddr", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ssl.$name.tls_versions", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.psk_ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.handshake_timeout", "emqx.listeners", [ - {default, "15s"}, - {datatype, {duration, ms}} -]}. - -{mapping, "listener.ssl.$name.dhfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.keyfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.certfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.cacertfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ssl.$name.verify", "emqx.listeners", [ - {datatype, atom} -]}. - -{mapping, "listener.ssl.$name.fail_if_no_peer_cert", "emqx.listeners", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "listener.ssl.$name.secure_renegotiate", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.reuse_sessions", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.honor_cipher_order", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ssl.$name.peer_cert_as_username", "emqx.listeners", [ - {datatype, {enum, [cn, dn, crt]}} -]}. - -%%-------------------------------------------------------------------- -%% MQTT/WebSocket Listeners - -{mapping, "listener.ws.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.ws.$name.mqtt_path", "emqx.listeners", [ - {default, "/mqtt"}, - {datatype, string} -]}. - -{mapping, "listener.ws.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ws.$name.rate_limit", "emqx.listeners", [ - {default, undefined}, - {datatype, string} -]}. - -{mapping, "listener.ws.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.ws.$name.verify_protocol_header", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.ws.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.ws.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -{mapping, "listener.ws.$name.backlog", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.ws.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.ws.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.ws.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ws.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ws.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.ws.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.ws.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ws.$name.compress", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.level", "emqx.listeners", [ - {datatype, {enum, [none, default, best_compression, best_speed]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.mem_level", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:1-9"]}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.strategy", "emqx.listeners", [ - {datatype, {enum, [default, filtered, huffman_only, rle]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.server_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.client_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.server_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - -{mapping, "listener.ws.$name.deflate_opts.client_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - -{mapping, "listener.ws.$name.idle_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - hidden -]}. - -{mapping, "listener.ws.$name.max_frame_size", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - -%%-------------------------------------------------------------------- -%% MQTT/WebSocket/SSL Listeners - -{mapping, "listener.wss.$name", "emqx.listeners", [ - {datatype, [integer, ip]} -]}. - -{mapping, "listener.wss.$name.mqtt_path", "emqx.listeners", [ - {default, "/mqtt"}, - {datatype, string} -]}. - -{mapping, "listener.wss.$name.acceptors", "emqx.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.max_connections", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.max_conn_rate", "emqx.listeners", [ - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.active_n", "emqx.listeners", [ - {default, 100}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.zone", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.rate_limit", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.verify_protocol_header", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.access.$id", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.proxy_protocol", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.proxy_protocol_timeout", "emqx.listeners", [ - {datatype, {duration, ms}} -]}. - -%%{mapping, "listener.wss.$name.handshake_timeout", "emqx.listeners", [ -%% {default, "15s"}, -%% {datatype, {duration, ms}} -%%]}. - -{mapping, "listener.wss.$name.backlog", "emqx.listeners", [ - {default, 1024}, - {datatype, integer} -]}. - -{mapping, "listener.wss.$name.send_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - {default, "15s"} -]}. - -{mapping, "listener.wss.$name.send_timeout_close", "emqx.listeners", [ - {datatype, flag}, - {default, on} -]}. - -{mapping, "listener.wss.$name.recbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.wss.$name.sndbuf", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.wss.$name.buffer", "emqx.listeners", [ - {datatype, bytesize}, - hidden -]}. - -{mapping, "listener.wss.$name.tune_buffer", "emqx.listeners", [ - {datatype, flag}, - hidden -]}. - -{mapping, "listener.wss.$name.nodelay", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.wss.$name.tls_versions", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.psk_ciphers", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.keyfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.certfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.cacertfile", "emqx.listeners", [ - {datatype, string} -]}. - -{mapping, "listener.wss.$name.verify", "emqx.listeners", [ - {datatype, atom} -]}. - -{mapping, "listener.wss.$name.fail_if_no_peer_cert", "emqx.listeners", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "listener.wss.$name.secure_renegotiate", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.reuse_sessions", "emqx.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.honor_cipher_order", "emqx.listeners", [ - {datatype, flag} -]}. - -{mapping, "listener.wss.$name.peer_cert_as_username", "emqx.listeners", [ - {datatype, {enum, [cn, dn, crt]}} -]}. - -{mapping, "listener.wss.$name.compress", "emqx.listeners", [ - {datatype, {enum, [true, false]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.level", "emqx.listeners", [ - {datatype, {enum, [none, default, best_compression, best_speed]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.mem_level", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:1-9"]}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.strategy", "emqx.listeners", [ - {datatype, {enum, [default, filtered, huffman_only, rle]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.server_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.client_context_takeover", "emqx.listeners", [ - {datatype, {enum, [takeover, no_takeover]}}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.server_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:8-15"]}, - hidden -]}. - -{mapping, "listener.wss.$name.deflate_opts.client_max_window_bits", "emqx.listeners", [ - {datatype, integer}, - {validators, ["range:8-15"]}, - hidden -]}. - -{mapping, "listener.wss.$name.idle_timeout", "emqx.listeners", [ - {datatype, {duration, ms}}, - hidden -]}. - -{mapping, "listener.wss.$name.max_frame_size", "emqx.listeners", [ - {datatype, integer}, - hidden -]}. - - - -{translation, "emqx.listeners", fun(Conf) -> - - Filter = fun(Opts) -> [{K, V} || {K, V} <- Opts, V =/= undefined] end, - - Atom = fun(undefined) -> undefined; (S) -> list_to_atom(S) end, - - Access = fun(S) -> - [A, CIDR] = string:tokens(S, " "), - {list_to_atom(A), case CIDR of "all" -> all; _ -> CIDR end} - end, - - AccOpts = fun(Prefix) -> - case cuttlefish_variable:filter_by_prefix(Prefix ++ ".access", Conf) of - [] -> []; - Rules -> [{access_rules, [Access(Rule) || {_, Rule} <- Rules]}] - end - end, - - RateLimit = fun(undefined) -> - undefined; - (Val) -> - [L, D] = string:tokens(Val, ", "), - Limit = case cuttlefish_bytesize:parse(L) of - Sz when is_integer(Sz) -> Sz; - {error, Reason} -> error(Reason) - end, - Duration = case cuttlefish_duration:parse(D, s) of - Secs when is_integer(Secs) -> Secs; - {error, Reason1} -> error(Reason1) - end, - Rate = Limit / Duration, - {Rate, Limit} - end, - - LisOpts = fun(Prefix) -> - Filter([{acceptors, cuttlefish:conf_get(Prefix ++ ".acceptors", Conf)}, - {mqtt_path, cuttlefish:conf_get(Prefix ++ ".mqtt_path", Conf, undefined)}, - {max_connections, cuttlefish:conf_get(Prefix ++ ".max_connections", Conf)}, - {max_conn_rate, cuttlefish:conf_get(Prefix ++ ".max_conn_rate", Conf, undefined)}, - {active_n, cuttlefish:conf_get(Prefix ++ ".active_n", Conf, undefined)}, - {tune_buffer, cuttlefish:conf_get(Prefix ++ ".tune_buffer", Conf, undefined)}, - {zone, Atom(cuttlefish:conf_get(Prefix ++ ".zone", Conf, undefined))}, - {rate_limit, RateLimit(cuttlefish:conf_get(Prefix ++ ".rate_limit", Conf, undefined))}, - {proxy_protocol, cuttlefish:conf_get(Prefix ++ ".proxy_protocol", Conf, undefined)}, - {proxy_protocol_timeout, cuttlefish:conf_get(Prefix ++ ".proxy_protocol_timeout", Conf, undefined)}, - {verify_protocol_header, cuttlefish:conf_get(Prefix ++ ".verify_protocol_header", Conf, undefined)}, - {peer_cert_as_username, cuttlefish:conf_get(Prefix ++ ".peer_cert_as_username", Conf, undefined)}, - {compress, cuttlefish:conf_get(Prefix ++ ".compress", Conf, undefined)}, - {idle_timeout, cuttlefish:conf_get(Prefix ++ ".idle_timeout", Conf, undefined)}, - {max_frame_size, cuttlefish:conf_get(Prefix ++ ".max_frame_size", Conf, undefined)} | AccOpts(Prefix)]) - end, - DeflateOpts = fun(Prefix) -> - Filter([{level, cuttlefish:conf_get(Prefix ++ ".deflate_opts.level", Conf, undefined)}, - {mem_level, cuttlefish:conf_get(Prefix ++ ".deflate_opts.mem_level", Conf, undefined)}, - {strategy, cuttlefish:conf_get(Prefix ++ ".deflate_opts.strategy", Conf, undefined)}, - {server_context_takeover, cuttlefish:conf_get(Prefix ++ ".deflate_opts.server_context_takeover", Conf, undefined)}, - {client_context_takeover, cuttlefish:conf_get(Prefix ++ ".deflate_opts.client_context_takeover", Conf, undefined)}, - {server_max_windows_bits, cuttlefish:conf_get(Prefix ++ ".deflate_opts.server_max_window_bits", Conf, undefined)}, - {client_max_windows_bits, cuttlefish:conf_get(Prefix ++ ".deflate_opts.client_max_window_bits", Conf, undefined)}]) - end, - TcpOpts = fun(Prefix) -> - Filter([{backlog, cuttlefish:conf_get(Prefix ++ ".backlog", Conf, undefined)}, - {send_timeout, cuttlefish:conf_get(Prefix ++ ".send_timeout", Conf, undefined)}, - {send_timeout_close, cuttlefish:conf_get(Prefix ++ ".send_timeout_close", Conf, undefined)}, - {recbuf, cuttlefish:conf_get(Prefix ++ ".recbuf", Conf, undefined)}, - {sndbuf, cuttlefish:conf_get(Prefix ++ ".sndbuf", Conf, undefined)}, - {buffer, cuttlefish:conf_get(Prefix ++ ".buffer", Conf, undefined)}, - {nodelay, cuttlefish:conf_get(Prefix ++ ".nodelay", Conf, true)}, - {reuseaddr, cuttlefish:conf_get(Prefix ++ ".reuseaddr", Conf, undefined)}]) - end, - SplitFun = fun(undefined) -> undefined; (S) -> string:tokens(S, ",") end, - MapPSKCiphers = fun(PSKCiphers) -> - lists:map( - fun("PSK-AES128-CBC-SHA") -> {psk, aes_128_cbc, sha}; - ("PSK-AES256-CBC-SHA") -> {psk, aes_256_cbc, sha}; - ("PSK-3DES-EDE-CBC-SHA") -> {psk, '3des_ede_cbc', sha}; - ("PSK-RC4-SHA") -> {psk, rc4_128, sha} - end, PSKCiphers) - end, - SslOpts = fun(Prefix) -> - Versions = case SplitFun(cuttlefish:conf_get(Prefix ++ ".tls_versions", Conf, undefined)) of - undefined -> undefined; - L -> [list_to_atom(V) || V <- L] - end, - TLSCiphers = cuttlefish:conf_get(Prefix++".ciphers", Conf, undefined), - PSKCiphers = cuttlefish:conf_get(Prefix++".psk_ciphers", Conf, undefined), - Ciphers = - case {TLSCiphers, PSKCiphers} of - {undefined, undefined} -> - cuttlefish:invalid(Prefix++".ciphers or "++Prefix++".psk_ciphers is absent"); - {TLSCiphers, undefined} -> - SplitFun(TLSCiphers); - {undefined, PSKCiphers} -> - MapPSKCiphers(SplitFun(PSKCiphers)); - {_TLSCiphers, _PSKCiphers} -> - cuttlefish:invalid(Prefix++".ciphers and "++Prefix++".psk_ciphers cannot be configured at the same time") - end, - UserLookupFun = - case PSKCiphers of - undefined -> undefined; - _ -> {fun emqx_psk:lookup/3, <<>>} - end, - Filter([{versions, Versions}, - {ciphers, Ciphers}, - {user_lookup_fun, UserLookupFun}, - {handshake_timeout, cuttlefish:conf_get(Prefix ++ ".handshake_timeout", Conf, undefined)}, - {dhfile, cuttlefish:conf_get(Prefix ++ ".dhfile", Conf, undefined)}, - {keyfile, cuttlefish:conf_get(Prefix ++ ".keyfile", Conf, undefined)}, - {certfile, cuttlefish:conf_get(Prefix ++ ".certfile", Conf, undefined)}, - {cacertfile, cuttlefish:conf_get(Prefix ++ ".cacertfile", Conf, undefined)}, - {verify, cuttlefish:conf_get(Prefix ++ ".verify", Conf, undefined)}, - {fail_if_no_peer_cert, cuttlefish:conf_get(Prefix ++ ".fail_if_no_peer_cert", Conf, undefined)}, - {secure_renegotiate, cuttlefish:conf_get(Prefix ++ ".secure_renegotiate", Conf, undefined)}, - {reuse_sessions, cuttlefish:conf_get(Prefix ++ ".reuse_sessions", Conf, undefined)}, - {honor_cipher_order, cuttlefish:conf_get(Prefix ++ ".honor_cipher_order", Conf, undefined)}]) - end, - - TcpListeners = fun(Type, Name) -> - Prefix = string:join(["listener", Type, Name], "."), - case cuttlefish:conf_get(Prefix, Conf, undefined) of - undefined -> []; - ListenOn -> - [{Atom(Type), ListenOn, [{deflate_options, DeflateOpts(Prefix)}, - {tcp_options, TcpOpts(Prefix)} | LisOpts(Prefix)]}] - end - end, - - SslListeners = fun(Type, Name) -> - Prefix = string:join(["listener", Type, Name], "."), - case cuttlefish:conf_get(Prefix, Conf, undefined) of - undefined -> - []; - ListenOn -> - [{Atom(Type), ListenOn, [{deflate_options, DeflateOpts(Prefix)}, - {tcp_options, TcpOpts(Prefix)}, - {ssl_options, SslOpts(Prefix)} | LisOpts(Prefix)]}] - end - end, - - lists:flatten([TcpListeners(Type, Name) || {["listener", Type, Name], ListenOn} - <- cuttlefish_variable:filter_by_prefix("listener.tcp", Conf) - ++ cuttlefish_variable:filter_by_prefix("listener.ws", Conf)] - ++ - [SslListeners(Type, Name) || {["listener", Type, Name], ListenOn} - <- cuttlefish_variable:filter_by_prefix("listener.ssl", Conf) - ++ cuttlefish_variable:filter_by_prefix("listener.wss", Conf)]) -end}. - -%%-------------------------------------------------------------------- -%% Modules -%%-------------------------------------------------------------------- - -{mapping, "modules.loaded_file", "emqx.modules_loaded_file", [ - {datatype, string} -]}. - -{mapping, "module.presence.qos", "emqx.modules", [ - {default, 1}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -{mapping, "module.subscription.$id.topic", "emqx.modules", [ - {datatype, string} -]}. - -{mapping, "module.subscription.$id.qos", "emqx.modules", [ - {default, 1}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -{mapping, "module.subscription.$id.nl", "emqx.modules", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:0-1"]} -]}. - -{mapping, "module.subscription.$id.rap", "emqx.modules", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:0-1"]} -]}. - -{mapping, "module.subscription.$id.rh", "emqx.modules", [ - {default, 0}, - {datatype, integer}, - {validators, ["range:0-2"]} -]}. - -{mapping, "module.rewrite.rule.$id", "emqx.modules", [ - {datatype, string} -]}. - -{translation, "emqx.modules", fun(Conf) -> - Subscriptions = fun() -> - List = cuttlefish_variable:filter_by_prefix("module.subscription", Conf), - TopicList = [{N, Topic}|| {[_,"subscription",N,"topic"], Topic} <- List], - [{iolist_to_binary(T), #{ qos => cuttlefish:conf_get("module.subscription." ++ N ++ ".qos", Conf, 0), - nl => cuttlefish:conf_get("module.subscription." ++ N ++ ".nl", Conf, 0), - rap => cuttlefish:conf_get("module.subscription." ++ N ++ ".rap", Conf, 0), - rh => cuttlefish:conf_get("module.subscription." ++ N ++ ".rh", Conf, 0) - }} || {N, T} <- TopicList] - end, - Rewrites = fun() -> - Rules = cuttlefish_variable:filter_by_prefix("module.rewrite.rule", Conf), - lists:map(fun({[_, "rewrite", "rule", I], Rule}) -> - [Topic, Re, Dest] = string:tokens(Rule, " "), - {rewrite, list_to_binary(Topic), list_to_binary(Re), list_to_binary(Dest)} - end, Rules) - end, - lists:append([ - [{emqx_mod_presence, [{qos, cuttlefish:conf_get("module.presence.qos", Conf, 1)}]}], - [{emqx_mod_subscription, Subscriptions()}], - [{emqx_mod_rewrite, Rewrites()}], - [{emqx_mod_topic_metrics, []}], - [{emqx_mod_delayed, []}], - [{emqx_mod_acl_internal, []}] - ]) -end}. - -%%------------------------------------------------------------------- -%% Plugins -%%------------------------------------------------------------------- - -{mapping, "plugins.etc_dir", "emqx.plugins_etc_dir", [ - {datatype, string} -]}. - -{mapping, "plugins.loaded_file", "emqx.plugins_loaded_file", [ - {datatype, string} -]}. - -{mapping, "plugins.expand_plugins_dir", "emqx.expand_plugins_dir", [ - {datatype, string} -]}. - -%%-------------------------------------------------------------------- -%% Broker -%%-------------------------------------------------------------------- - -{mapping, "broker.sys_interval", "emqx.broker_sys_interval", [ - {datatype, {duration, ms}}, - {default, "1m"} -]}. - -{mapping, "broker.sys_heartbeat", "emqx.broker_sys_heartbeat", [ - {datatype, {duration, ms}}, - {default, "30s"} -]}. - -{mapping, "broker.enable_session_registry", "emqx.enable_session_registry", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "broker.session_locking_strategy", "emqx.session_locking_strategy", [ - {default, quorum}, - {datatype, {enum, [local,one,quorum,all]}} -]}. - -%% @doc Shared Subscription Dispatch Strategy. -{mapping, "broker.shared_subscription_strategy", "emqx.shared_subscription_strategy", [ - {default, round_robin}, - {datatype, - {enum, - [random, %% randomly pick a subscriber - round_robin, %% round robin alive subscribers one message after another - sticky, %% pick a random subscriber and stick to it - hash %% hash client ID to a group member - ]}} -]}. - -%% @doc Enable or disable shared dispatch acknowledgement for QoS1 and QoS2 messages -{mapping, "broker.shared_dispatch_ack_enabled", "emqx.shared_dispatch_ack_enabled", - [ {default, false}, - {datatype, {enum, [true, false]}} - ]}. - -{mapping, "broker.route_batch_clean", "emqx.route_batch_clean", [ - {default, on}, - {datatype, flag} -]}. - -%%-------------------------------------------------------------------- -%% System Monitor -%%-------------------------------------------------------------------- - -%% @doc Long GC, don't monitor in production mode for: -%% https://hub.fastgit.org/erlang/otp/blob/feb45017da36be78d4c5784d758ede619fa7bfd3/erts/emulator/beam/erl_gc.c#L421 -{mapping, "sysmon.long_gc", "emqx.sysmon", [ - {default, 0}, - {datatype, [integer, {duration, ms}]} -]}. - -%% @doc Long Schedule(ms) -{mapping, "sysmon.long_schedule", "emqx.sysmon", [ - {default, 240}, - {datatype, [integer, {duration, ms}]} -]}. - -%% @doc Large Heap -{mapping, "sysmon.large_heap", "emqx.sysmon", [ - {default, "8MB"}, - {datatype, bytesize} -]}. - -%% @doc Monitor Busy Port -{mapping, "sysmon.busy_port", "emqx.sysmon", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -%% @doc Monitor Busy Dist Port -{mapping, "sysmon.busy_dist_port", "emqx.sysmon", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{translation, "emqx.sysmon", fun(Conf) -> - Configs = cuttlefish_variable:filter_by_prefix("sysmon", Conf), - [{list_to_atom(Name), Value} || {[_, Name], Value} <- Configs] -end}. - -%%-------------------------------------------------------------------- -%% Operating System Monitor -%%-------------------------------------------------------------------- - -{mapping, "os_mon.cpu_check_interval", "emqx.os_mon", [ - {default, 60}, - {datatype, {duration, s}} -]}. - -{mapping, "os_mon.cpu_high_watermark", "emqx.os_mon", [ - {default, "80%"}, - {datatype, {percent, float}} -]}. - -{mapping, "os_mon.cpu_low_watermark", "emqx.os_mon", [ - {default, "60%"}, - {datatype, {percent, float}} -]}. - -{mapping, "os_mon.mem_check_interval", "emqx.os_mon", [ - {default, 60}, - {datatype, {duration, s}} -]}. - -{mapping, "os_mon.sysmem_high_watermark", "emqx.os_mon", [ - {default, "70%"}, - {datatype, {percent, float}} -]}. - -{mapping, "os_mon.procmem_high_watermark", "emqx.os_mon", [ - {default, "5%"}, - {datatype, {percent, float}} -]}. - -{translation, "emqx.os_mon", fun(Conf) -> - Configs = cuttlefish_variable:filter_by_prefix("os_mon", Conf), - [{list_to_atom(Name), Value} || {[_, Name], Value} <- Configs] -end}. - -%%-------------------------------------------------------------------- -%% VM Monitor -%%-------------------------------------------------------------------- -{mapping, "vm_mon.check_interval", "emqx.vm_mon", [ - {default, 30}, - {datatype, {duration, s}} -]}. - -{mapping, "vm_mon.process_high_watermark", "emqx.vm_mon", [ - {default, "80%"}, - {datatype, {percent, float}} -]}. - -{mapping, "vm_mon.process_low_watermark", "emqx.vm_mon", [ - {default, "60%"}, - {datatype, {percent, float}} -]}. - -{translation, "emqx.vm_mon", fun(Conf) -> - Configs = cuttlefish_variable:filter_by_prefix("vm_mon", Conf), - [{list_to_atom(Name), Value} || {[_, Name], Value} <- Configs] -end}. diff --git a/_build/emqx/lib/emqx/rebar.config b/_build/emqx/lib/emqx/rebar.config deleted file mode 100644 index 3ded89857e..0000000000 --- a/_build/emqx/lib/emqx/rebar.config +++ /dev/null @@ -1,49 +0,0 @@ -{minimum_otp_vsn, "21.3"}. - -{plugins, [rebar3_proper]}. - -{deps, - [{gproc, {git, "https://hub.fastgit.org/uwiger/gproc", {tag, "0.8.0"}}}, - {jsx, "2.10.0"}, - {cowboy, {git, "https://hub.fastgit.org/emqx/cowboy", {tag, "2.7.1"}}}, - {esockd, {git, "https://hub.fastgit.org/emqx/esockd", {tag, "5.7.0"}}}, - {ekka, {git, "https://hub.fastgit.org/emqx/ekka", {tag, "0.7.3"}}}, - {gen_rpc, {git, "https://hub.fastgit.org/emqx/gen_rpc", {tag, "2.4.1"}}}, - {cuttlefish, {git, "https://hub.fastgit.org/emqx/cuttlefish", {tag, "v3.0.0"}}} - ]}. - -{erl_opts, [warn_unused_vars, - warn_shadow_vars, - warn_unused_import, - warn_obsolete_guard, - debug_info, - compressed %% for edge - ]}. - -{overrides, [{add, [{erl_opts, [compressed]}]}]}. - -{edoc_opts, [{preprocess, true}]}. - -{xref_checks, [undefined_function_calls, undefined_functions, - locals_not_used, deprecated_function_calls, - warnings_as_errors, deprecated_functions - ]}. - -{cover_enabled, true}. -{cover_opts, [verbose]}. -{cover_export_enabled, true}. - -{erl_first_files, ["src/emqx_logger.erl"]}. - -{profiles, - [{test, - [{plugins, [{coveralls, {git, "https://hub.fastgit.org/emqx/coveralls-erl", {branch, "github"}}}]}, - {deps, - [{bbmustache, "1.7.0"}, - {emqtt, {git, "https://hub.fastgit.org/emqx/emqtt", {tag, "1.2.0"}}}, - {emqx_ct_helpers, {git, "https://hub.fastgit.org/emqx/emqx-ct-helpers", {tag, "1.3.0"}}} - ]}, - {erl_opts, [debug_info]} - ]} - ]}. - diff --git a/_build/emqx/lib/emqx/rebar.config.script b/_build/emqx/lib/emqx/rebar.config.script deleted file mode 100644 index 5447ffb33c..0000000000 --- a/_build/emqx/lib/emqx/rebar.config.script +++ /dev/null @@ -1,20 +0,0 @@ -%% -*-: erlang -*- - -case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of - {"true", Token} when is_list(Token) -> - CONFIG1 = [{coveralls_repo_token, Token}, - {coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")}, - {coveralls_commit_sha, os:getenv("GITHUB_SHA")}, - {coveralls_service_number, os:getenv("GITHUB_RUN_NUMBER")}, - {coveralls_coverdata, "_build/test/cover/*.coverdata"}, - {coveralls_service_name, "github"} | CONFIG], - case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request" - andalso string:tokens(os:getenv("GITHUB_REF"), "/") of - [_, "pull", PRNO, _] -> - [{coveralls_service_pull_request, PRNO} | CONFIG1]; - _ -> - CONFIG1 - end; - _ -> - CONFIG -end. diff --git a/_build/emqx/lib/emqx/scripts/run_emqx.escript b/_build/emqx/lib/emqx/scripts/run_emqx.escript deleted file mode 100644 index 10767820b6..0000000000 --- a/_build/emqx/lib/emqx/scripts/run_emqx.escript +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env escript - -main(_) -> - start(). - -start() -> - ok = application:load(mnesia), - MnesiaName = lists:concat(["Mnesia.", atom_to_list(node())]), - MnesiaDir = filename:join(["_build", "data", MnesiaName]), - ok = application:set_env(mnesia, dir, MnesiaDir), - SpecEmqxConfig = fun(_) -> ok end, - start(SpecEmqxConfig). - -start(SpecEmqxConfig) -> - SchemaPath = filename:join(["priv", "emqx.schema"]), - ConfPath = filename:join(["etc", "emqx.conf"]), - emqx_ct_helpers:start_app(emqx, SchemaPath, ConfPath, SpecEmqxConfig). diff --git a/_build/emqx/lib/emqx/src/emqx.app.src b/_build/emqx/lib/emqx/src/emqx.app.src deleted file mode 100644 index 1535331f55..0000000000 --- a/_build/emqx/lib/emqx/src/emqx.app.src +++ /dev/null @@ -1,16 +0,0 @@ -{application, emqx, - [{description, "EMQ X Broker"}, - {id, "emqx"}, - {vsn, "git"}, - {modules, []}, - {registered, []}, - {applications, [kernel,stdlib,gproc,gen_rpc,esockd,cowboy, - sasl,os_mon]}, - {mod, {emqx_app,[]}}, - {env, []}, - {licenses, ["Apache-2.0"]}, - {maintainers, ["EMQ X Team "]}, - {links, [{"Homepage", "https://emqx.io/"}, - {"Github", "https://hub.fastgit.org/emqx/emqx"} - ]} -]}. diff --git a/_build/emqx/lib/emqx/src/emqx.app.src.script b/_build/emqx/lib/emqx/src/emqx.app.src.script deleted file mode 100644 index b76a117200..0000000000 --- a/_build/emqx/lib/emqx/src/emqx.app.src.script +++ /dev/null @@ -1,34 +0,0 @@ -%%-*- mode: erlang -*- -%% .app.src.script - -Config = case os:getenv("EMQX_DESC") of - false -> CONFIG; % env var not defined - [] -> CONFIG; % env var set to empty string - Desc -> - [begin - AppConf0 = lists:keystore(description, 1, AppConf, {description, Desc}), - {application, App, AppConf0} - end || Conf = {application, App, AppConf} <- CONFIG] -end, - -RemoveLeadingV = - fun(Tag) -> - case re:run(Tag, "v\[0-9\]+\.\[0-9\]+\.*") of - nomatch -> - Tag; - {match, _} -> - %% if it is a version number prefixed by 'v' then remove the 'v' - "v" ++ Vsn = Tag, - Vsn - end - end, - -case os:getenv("EMQX_DEPS_DEFAULT_VSN") of - false -> Config; % env var not defined - [] -> Config; % env var set to empty string - Tag -> - [begin - AppConf0 = lists:keystore(vsn, 1, AppConf, {vsn, RemoveLeadingV(Tag)}), - {application, App, AppConf0} - end || Conf = {application, App, AppConf} <- Config] -end. diff --git a/_build/emqx/lib/emqx/src/emqx.erl b/_build/emqx/lib/emqx/src/emqx.erl deleted file mode 100644 index 2c6d444e75..0000000000 --- a/_build/emqx/lib/emqx/src/emqx.erl +++ /dev/null @@ -1,224 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[EMQ X]"). - -%% Start/Stop the application --export([ start/0 - , restart/1 - , is_running/1 - , stop/0 - ]). - --export([ get_env/1 - , get_env/2 - ]). - -%% PubSub API --export([ subscribe/1 - , subscribe/2 - , subscribe/3 - , publish/1 - , unsubscribe/1 - ]). - -%% PubSub management API --export([ topics/0 - , subscriptions/1 - , subscribers/1 - , subscribed/2 - ]). - -%% Hooks API --export([ hook/2 - , hook/3 - , hook/4 - , unhook/2 - , run_hook/2 - , run_fold_hook/3 - ]). - -%% Shutdown and reboot --export([ shutdown/0 - , shutdown/1 - , reboot/0 - ]). - --define(APP, ?MODULE). - --define(COPYRIGHT, "Copyright (c) 2020 EMQ Technologies Co., Ltd"). - --define(LICENSE_MESSAGE, "Licensed under the Apache License, Version 2.0"). - -%%-------------------------------------------------------------------- -%% Bootstrap, is_running... -%%-------------------------------------------------------------------- - -%% @doc Start emqx application --spec(start() -> {ok, list(atom())} | {error, term()}). -start() -> - %% Check OS - %% Check VM - %% Check Mnesia - application:ensure_all_started(?APP). - --spec(restart(string()) -> ok). -restart(ConfFile) -> - reload_config(ConfFile), - shutdown(), - ok = application:stop(mnesia), - application:start(mnesia), - reboot(). - -%% @doc Stop emqx application. --spec(stop() -> ok | {error, term()}). -stop() -> - application:stop(?APP). - -%% @doc Is emqx running? --spec(is_running(node()) -> boolean()). -is_running(Node) -> - case rpc:call(Node, erlang, whereis, [?APP]) of - {badrpc, _} -> false; - undefined -> false; - Pid when is_pid(Pid) -> true - end. - -%% @doc Get environment --spec(get_env(Key :: atom()) -> maybe(term())). -get_env(Key) -> - get_env(Key, undefined). - --spec(get_env(Key :: atom(), Default :: term()) -> term()). -get_env(Key, Default) -> - application:get_env(?APP, Key, Default). - -%%-------------------------------------------------------------------- -%% PubSub API -%%-------------------------------------------------------------------- - --spec(subscribe(emqx_topic:topic() | string()) -> ok). -subscribe(Topic) -> - emqx_broker:subscribe(iolist_to_binary(Topic)). - --spec(subscribe(emqx_topic:topic() | string(), emqx_types:subid() | emqx_types:subopts()) -> ok). -subscribe(Topic, SubId) when is_atom(SubId); is_binary(SubId)-> - emqx_broker:subscribe(iolist_to_binary(Topic), SubId); -subscribe(Topic, SubOpts) when is_map(SubOpts) -> - emqx_broker:subscribe(iolist_to_binary(Topic), SubOpts). - --spec(subscribe(emqx_topic:topic() | string(), - emqx_types:subid() | pid(), emqx_types:subopts()) -> ok). -subscribe(Topic, SubId, SubOpts) when (is_atom(SubId) orelse is_binary(SubId)), is_map(SubOpts) -> - emqx_broker:subscribe(iolist_to_binary(Topic), SubId, SubOpts). - --spec(publish(emqx_types:message()) -> emqx_types:publish_result()). -publish(Msg) -> - emqx_broker:publish(Msg). - --spec(unsubscribe(emqx_topic:topic() | string()) -> ok). -unsubscribe(Topic) -> - emqx_broker:unsubscribe(iolist_to_binary(Topic)). - -%%-------------------------------------------------------------------- -%% PubSub management API -%%-------------------------------------------------------------------- - --spec(topics() -> list(emqx_topic:topic())). -topics() -> emqx_router:topics(). - --spec(subscribers(emqx_topic:topic() | string()) -> [pid()]). -subscribers(Topic) -> - emqx_broker:subscribers(iolist_to_binary(Topic)). - --spec(subscriptions(pid()) -> [{emqx_topic:topic(), emqx_types:subopts()}]). -subscriptions(SubPid) when is_pid(SubPid) -> - emqx_broker:subscriptions(SubPid). - --spec(subscribed(pid() | emqx_types:subid(), emqx_topic:topic() | string()) -> boolean()). -subscribed(SubPid, Topic) when is_pid(SubPid) -> - emqx_broker:subscribed(SubPid, iolist_to_binary(Topic)); -subscribed(SubId, Topic) when is_atom(SubId); is_binary(SubId) -> - emqx_broker:subscribed(SubId, iolist_to_binary(Topic)). - -%%-------------------------------------------------------------------- -%% Hooks API -%%-------------------------------------------------------------------- - --spec(hook(emqx_hooks:hookpoint(), emqx_hooks:action()) -> ok | {error, already_exists}). -hook(HookPoint, Action) -> - emqx_hooks:add(HookPoint, Action). - --spec(hook(emqx_hooks:hookpoint(), - emqx_hooks:action(), - emqx_hooks:filter() | integer() | list()) - -> ok | {error, already_exists}). -hook(HookPoint, Action, Priority) when is_integer(Priority) -> - emqx_hooks:add(HookPoint, Action, Priority); -hook(HookPoint, Action, Filter) when is_function(Filter); is_tuple(Filter) -> - emqx_hooks:add(HookPoint, Action, Filter); -hook(HookPoint, Action, InitArgs) when is_list(InitArgs) -> - emqx_hooks:add(HookPoint, Action, InitArgs). - --spec(hook(emqx_hooks:hookpoint(), emqx_hooks:action(), emqx_hooks:filter(), integer()) - -> ok | {error, already_exists}). -hook(HookPoint, Action, Filter, Priority) -> - emqx_hooks:add(HookPoint, Action, Filter, Priority). - --spec(unhook(emqx_hooks:hookpoint(), function() | {module(), atom()}) -> ok). -unhook(HookPoint, Action) -> - emqx_hooks:del(HookPoint, Action). - --spec(run_hook(emqx_hooks:hookpoint(), list(any())) -> ok | stop). -run_hook(HookPoint, Args) -> - emqx_hooks:run(HookPoint, Args). - --spec(run_fold_hook(emqx_hooks:hookpoint(), list(any()), any()) -> any()). -run_fold_hook(HookPoint, Args, Acc) -> - emqx_hooks:run_fold(HookPoint, Args, Acc). - -%%-------------------------------------------------------------------- -%% Shutdown and reboot -%%-------------------------------------------------------------------- - -shutdown() -> - shutdown(normal). - -shutdown(Reason) -> - ?LOG(critical, "emqx shutdown for ~s", [Reason]), - emqx_alarm_handler:unload(), - emqx_plugins:unload(), - lists:foreach(fun application:stop/1, [emqx, ekka, cowboy, ranch, esockd, gproc]). - -reboot() -> - lists:foreach(fun application:start/1, [gproc, esockd, ranch, cowboy, ekka, emqx]). - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -reload_config(ConfFile) -> - {ok, [Conf]} = file:consult(ConfFile), - lists:foreach(fun({App, Vals}) -> - [application:set_env(App, Par, Val) || {Par, Val} <- Vals] - end, Conf). - diff --git a/_build/emqx/lib/emqx/src/emqx_access_control.erl b/_build/emqx/lib/emqx/src/emqx_access_control.erl deleted file mode 100644 index 32383b3f07..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_access_control.erl +++ /dev/null @@ -1,83 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_access_control). - --include("emqx.hrl"). - --export([authenticate/1]). - --export([ check_acl/3 - ]). - --type(result() :: #{auth_result := emqx_types:auth_result(), - anonymous := boolean() - }). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - --spec(authenticate(emqx_types:clientinfo()) -> {ok, result()} | {error, term()}). -authenticate(ClientInfo = #{zone := Zone}) -> - AuthResult = default_auth_result(Zone), - case emqx_zone:get_env(Zone, bypass_auth_plugins, false) of - true -> - return_auth_result(AuthResult); - false -> - return_auth_result(run_hooks('client.authenticate', [ClientInfo], AuthResult)) - end. - -%% @doc Check ACL --spec(check_acl(emqx_types:clientinfo(), emqx_types:pubsub(), emqx_types:topic()) - -> allow | deny). -check_acl(ClientInfo, PubSub, Topic) -> - case emqx_acl_cache:is_enabled() of - true -> check_acl_cache(ClientInfo, PubSub, Topic); - false -> do_check_acl(ClientInfo, PubSub, Topic) - end. - -check_acl_cache(ClientInfo, PubSub, Topic) -> - case emqx_acl_cache:get_acl_cache(PubSub, Topic) of - not_found -> - AclResult = do_check_acl(ClientInfo, PubSub, Topic), - emqx_acl_cache:put_acl_cache(PubSub, Topic, AclResult), - AclResult; - AclResult -> AclResult - end. - -do_check_acl(ClientInfo = #{zone := Zone}, PubSub, Topic) -> - Default = emqx_zone:get_env(Zone, acl_nomatch, deny), - case run_hooks('client.check_acl', [ClientInfo, PubSub, Topic], Default) of - allow -> allow; - _Other -> deny - end. - -default_auth_result(Zone) -> - case emqx_zone:get_env(Zone, allow_anonymous, false) of - true -> #{auth_result => success, anonymous => true}; - false -> #{auth_result => not_authorized, anonymous => false} - end. - --compile({inline, [run_hooks/3]}). -run_hooks(Name, Args, Acc) -> - ok = emqx_metrics:inc(Name), emqx_hooks:run_fold(Name, Args, Acc). - --compile({inline, [return_auth_result/1]}). -return_auth_result(Result = #{auth_result := success}) -> - {ok, Result}; -return_auth_result(Result) -> - {error, maps:get(auth_result, Result, unknown_error)}. diff --git a/_build/emqx/lib/emqx/src/emqx_access_rule.erl b/_build/emqx/lib/emqx/src/emqx_access_rule.erl deleted file mode 100644 index 89943cdbd0..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_access_rule.erl +++ /dev/null @@ -1,155 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_access_rule). - --include("emqx.hrl"). - -%% APIs --export([ match/3 - , compile/1 - ]). - --export_type([rule/0]). - --type(acl_result() :: allow | deny). - --type(who() :: all | binary() | - {client, binary()} | - {user, binary()} | - {ipaddr, esockd_cidr:cidr_string()}). - --type(access() :: subscribe | publish | pubsub). - --type(rule() :: {acl_result(), all} | - {acl_result(), who(), access(), list(emqx_topic:topic())}). - --define(ALLOW_DENY(A), ((A =:= allow) orelse (A =:= deny))). --define(PUBSUB(A), ((A =:= subscribe) orelse (A =:= publish) orelse (A =:= pubsub))). - -%% @doc Compile Access Rule. -compile({A, all}) when ?ALLOW_DENY(A) -> - {A, all}; - -compile({A, Who, Access, Topic}) when ?ALLOW_DENY(A), ?PUBSUB(Access), is_binary(Topic) -> - {A, compile(who, Who), Access, [compile(topic, Topic)]}; - -compile({A, Who, Access, TopicFilters}) when ?ALLOW_DENY(A), ?PUBSUB(Access) -> - {A, compile(who, Who), Access, [compile(topic, Topic) || Topic <- TopicFilters]}. - -compile(who, all) -> - all; -compile(who, {ipaddr, CIDR}) -> - {ipaddr, esockd_cidr:parse(CIDR, true)}; -compile(who, {client, all}) -> - {client, all}; -compile(who, {client, ClientId}) -> - {client, bin(ClientId)}; -compile(who, {user, all}) -> - {user, all}; -compile(who, {user, Username}) -> - {user, bin(Username)}; -compile(who, {'and', Conds}) when is_list(Conds) -> - {'and', [compile(who, Cond) || Cond <- Conds]}; -compile(who, {'or', Conds}) when is_list(Conds) -> - {'or', [compile(who, Cond) || Cond <- Conds]}; - -compile(topic, {eq, Topic}) -> - {eq, emqx_topic:words(bin(Topic))}; -compile(topic, Topic) -> - Words = emqx_topic:words(bin(Topic)), - case 'pattern?'(Words) of - true -> {pattern, Words}; - false -> Words - end. - -'pattern?'(Words) -> - lists:member(<<"%u">>, Words) - orelse lists:member(<<"%c">>, Words). - -bin(L) when is_list(L) -> - list_to_binary(L); -bin(B) when is_binary(B) -> - B. - -%% @doc Match access rule --spec(match(emqx_types:clientinfo(), emqx_types:topic(), rule()) - -> {matched, allow} | {matched, deny} | nomatch). -match(_ClientInfo, _Topic, {AllowDeny, all}) when ?ALLOW_DENY(AllowDeny) -> - {matched, AllowDeny}; -match(ClientInfo, Topic, {AllowDeny, Who, _PubSub, TopicFilters}) - when ?ALLOW_DENY(AllowDeny) -> - case match_who(ClientInfo, Who) - andalso match_topics(ClientInfo, Topic, TopicFilters) of - true -> {matched, AllowDeny}; - false -> nomatch - end. - -match_who(_ClientInfo, all) -> - true; -match_who(_ClientInfo, {user, all}) -> - true; -match_who(_ClientInfo, {client, all}) -> - true; -match_who(#{clientid := ClientId}, {client, ClientId}) -> - true; -match_who(#{username := Username}, {user, Username}) -> - true; -match_who(#{peerhost := undefined}, {ipaddr, _Tup}) -> - false; -match_who(#{peerhost := IP}, {ipaddr, CIDR}) -> - esockd_cidr:match(IP, CIDR); -match_who(ClientInfo, {'and', Conds}) when is_list(Conds) -> - lists:foldl(fun(Who, Allow) -> - match_who(ClientInfo, Who) andalso Allow - end, true, Conds); -match_who(ClientInfo, {'or', Conds}) when is_list(Conds) -> - lists:foldl(fun(Who, Allow) -> - match_who(ClientInfo, Who) orelse Allow - end, false, Conds); -match_who(_ClientInfo, _Who) -> - false. - -match_topics(_ClientInfo, _Topic, []) -> - false; -match_topics(ClientInfo, Topic, [{pattern, PatternFilter}|Filters]) -> - TopicFilter = feed_var(ClientInfo, PatternFilter), - match_topic(emqx_topic:words(Topic), TopicFilter) - orelse match_topics(ClientInfo, Topic, Filters); -match_topics(ClientInfo, Topic, [TopicFilter|Filters]) -> - match_topic(emqx_topic:words(Topic), TopicFilter) - orelse match_topics(ClientInfo, Topic, Filters). - -match_topic(Topic, {eq, TopicFilter}) -> - Topic == TopicFilter; -match_topic(Topic, TopicFilter) -> - emqx_topic:match(Topic, TopicFilter). - -feed_var(ClientInfo, Pattern) -> - feed_var(ClientInfo, Pattern, []). -feed_var(_ClientInfo, [], Acc) -> - lists:reverse(Acc); -feed_var(ClientInfo = #{clientid := undefined}, [<<"%c">>|Words], Acc) -> - feed_var(ClientInfo, Words, [<<"%c">>|Acc]); -feed_var(ClientInfo = #{clientid := ClientId}, [<<"%c">>|Words], Acc) -> - feed_var(ClientInfo, Words, [ClientId |Acc]); -feed_var(ClientInfo = #{username := undefined}, [<<"%u">>|Words], Acc) -> - feed_var(ClientInfo, Words, [<<"%u">>|Acc]); -feed_var(ClientInfo = #{username := Username}, [<<"%u">>|Words], Acc) -> - feed_var(ClientInfo, Words, [Username|Acc]); -feed_var(ClientInfo, [W|Words], Acc) -> - feed_var(ClientInfo, Words, [W|Acc]). - diff --git a/_build/emqx/lib/emqx/src/emqx_acl_cache.erl b/_build/emqx/lib/emqx/src/emqx_acl_cache.erl deleted file mode 100644 index ef549d8d32..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_acl_cache.erl +++ /dev/null @@ -1,244 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_acl_cache). - --include("emqx.hrl"). - --export([ list_acl_cache/0 - , get_acl_cache/2 - , put_acl_cache/3 - , cleanup_acl_cache/0 - , empty_acl_cache/0 - , dump_acl_cache/0 - , get_cache_max_size/0 - , get_cache_ttl/0 - , is_enabled/0 - ]). - -%% export for test --export([ cache_k/2 - , cache_v/1 - , get_cache_size/0 - , get_newest_key/0 - , get_oldest_key/0 - ]). - --type(acl_result() :: allow | deny). --type(system_time() :: integer()). --type(cache_key() :: {emqx_types:pubsub(), emqx_types:topic()}). --type(cache_val() :: {acl_result(), system_time()}). - --type(acl_cache_entry() :: {cache_key(), cache_val()}). - -%% Wrappers for key and value -cache_k(PubSub, Topic)-> {PubSub, Topic}. -cache_v(AclResult)-> {AclResult, time_now()}. - --spec(is_enabled() -> boolean()). -is_enabled() -> - application:get_env(emqx, enable_acl_cache, true). - --spec(get_cache_max_size() -> integer()). -get_cache_max_size() -> - application:get_env(emqx, acl_cache_max_size, 32). - --spec(get_cache_ttl() -> integer()). -get_cache_ttl() -> - application:get_env(emqx, acl_cache_ttl, 60000). - --spec(list_acl_cache() -> [acl_cache_entry()]). -list_acl_cache() -> - cleanup_acl_cache(), - map_acl_cache(fun(Cache) -> Cache end). - -%% We'll cleanup the cache before replacing an expired acl. --spec(get_acl_cache(emqx_types:pubsub(), emqx_topic:topic()) -> (acl_result() | not_found)). -get_acl_cache(PubSub, Topic) -> - case erlang:get(cache_k(PubSub, Topic)) of - undefined -> not_found; - {AclResult, CachedAt} -> - if_expired(CachedAt, - fun(false) -> - AclResult; - (true) -> - cleanup_acl_cache(), - not_found - end) - end. - -%% If the cache get full, and also the latest one -%% is expired, then delete all the cache entries --spec(put_acl_cache(emqx_types:pubsub(), emqx_topic:topic(), acl_result()) -> ok). -put_acl_cache(PubSub, Topic, AclResult) -> - MaxSize = get_cache_max_size(), true = (MaxSize =/= 0), - Size = get_cache_size(), - if - Size < MaxSize -> - add_acl(PubSub, Topic, AclResult); - Size =:= MaxSize -> - NewestK = get_newest_key(), - {_AclResult, CachedAt} = erlang:get(NewestK), - if_expired(CachedAt, - fun(true) -> - % all cache expired, cleanup first - empty_acl_cache(), - add_acl(PubSub, Topic, AclResult); - (false) -> - % cache full, perform cache replacement - evict_acl_cache(), - add_acl(PubSub, Topic, AclResult) - end) - end. - -%% delete all the acl entries --spec(empty_acl_cache() -> ok). -empty_acl_cache() -> - map_acl_cache(fun({CacheK, _CacheV}) -> - erlang:erase(CacheK) - end), - set_cache_size(0), - keys_queue_set(queue:new()). - -%% delete the oldest acl entry --spec(evict_acl_cache() -> ok). -evict_acl_cache() -> - OldestK = keys_queue_out(), - erlang:erase(OldestK), - decr_cache_size(). - -%% cleanup all the expired cache entries --spec(cleanup_acl_cache() -> ok). -cleanup_acl_cache() -> - keys_queue_set( - cleanup_acl(keys_queue_get())). - -get_oldest_key() -> - keys_queue_pick(queue_front()). -get_newest_key() -> - keys_queue_pick(queue_rear()). - -get_cache_size() -> - case erlang:get(acl_cache_size) of - undefined -> 0; - Size -> Size - end. - -dump_acl_cache() -> - map_acl_cache(fun(Cache) -> Cache end). -map_acl_cache(Fun) -> - [Fun(R) || R = {{SubPub, _T}, _Acl} <- get(), SubPub =:= publish - orelse SubPub =:= subscribe]. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -add_acl(PubSub, Topic, AclResult) -> - K = cache_k(PubSub, Topic), - V = cache_v(AclResult), - case erlang:get(K) of - undefined -> add_new_acl(K, V); - {_AclResult, _CachedAt} -> - update_acl(K, V) - end. - -add_new_acl(K, V) -> - erlang:put(K, V), - keys_queue_in(K), - incr_cache_size(). - -update_acl(K, V) -> - erlang:put(K, V), - keys_queue_update(K). - -cleanup_acl(KeysQ) -> - case queue:out(KeysQ) of - {{value, OldestK}, KeysQ2} -> - {_AclResult, CachedAt} = erlang:get(OldestK), - if_expired(CachedAt, - fun(false) -> KeysQ; - (true) -> - erlang:erase(OldestK), - decr_cache_size(), - cleanup_acl(KeysQ2) - end); - {empty, KeysQ} -> KeysQ - end. - -incr_cache_size() -> - erlang:put(acl_cache_size, get_cache_size() + 1), ok. -decr_cache_size() -> - Size = get_cache_size(), - if Size > 1 -> - erlang:put(acl_cache_size, Size-1); - Size =< 1 -> - erlang:put(acl_cache_size, 0) - end, ok. -set_cache_size(N) -> - erlang:put(acl_cache_size, N), ok. - -%%% Ordered Keys Q %%% -keys_queue_in(Key) -> - %% delete the key first if exists - KeysQ = keys_queue_get(), - keys_queue_set(queue:in(Key, KeysQ)). - -keys_queue_out() -> - case queue:out(keys_queue_get()) of - {{value, OldestK}, Q2} -> - keys_queue_set(Q2), OldestK; - {empty, _Q} -> - undefined - end. - -keys_queue_update(Key) -> - NewKeysQ = keys_queue_remove(Key, keys_queue_get()), - keys_queue_set(queue:in(Key, NewKeysQ)). - -keys_queue_pick(Pick) -> - KeysQ = keys_queue_get(), - case queue:is_empty(KeysQ) of - true -> undefined; - false -> Pick(KeysQ) - end. - -keys_queue_remove(Key, KeysQ) -> - queue:filter(fun - (K) when K =:= Key -> false; (_) -> true - end, KeysQ). - -keys_queue_set(KeysQ) -> - erlang:put(acl_keys_q, KeysQ), ok. -keys_queue_get() -> - case erlang:get(acl_keys_q) of - undefined -> queue:new(); - KeysQ -> KeysQ - end. - -queue_front() -> fun queue:get/1. -queue_rear() -> fun queue:get_r/1. - -time_now() -> erlang:system_time(millisecond). - -if_expired(CachedAt, Fun) -> - TTL = get_cache_ttl(), - Now = time_now(), - if (CachedAt + TTL) =< Now -> - Fun(true); - true -> - Fun(false) - end. diff --git a/_build/emqx/lib/emqx/src/emqx_alarm_handler.erl b/_build/emqx/lib/emqx/src/emqx_alarm_handler.erl deleted file mode 100644 index 77d2b60a0a..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_alarm_handler.erl +++ /dev/null @@ -1,204 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_alarm_handler). - --behaviour(gen_event). - --include("emqx.hrl"). --include("logger.hrl"). - --logger_header("[Alarm Handler]"). - -%% Mnesia bootstrap --export([mnesia/1]). - --boot_mnesia({mnesia, [boot]}). --copy_mnesia({mnesia, [copy]}). - -%% gen_event callbacks --export([ init/1 - , handle_event/2 - , handle_call/2 - , handle_info/2 - , terminate/2 - ]). - --export([ load/0 - , unload/0 - , get_alarms/0 - , get_alarms/1 - ]). - --record(common_alarm, {id, desc}). --record(alarm_history, {id, desc, clear_at}). - --define(ALARM_TAB, emqx_alarm). --define(ALARM_HISTORY_TAB, emqx_alarm_history). - -%%-------------------------------------------------------------------- -%% Mnesia bootstrap -%%-------------------------------------------------------------------- - -mnesia(boot) -> - ok = ekka_mnesia:create_table(?ALARM_TAB, [ - {type, set}, - {disc_copies, [node()]}, - {local_content, true}, - {record_name, common_alarm}, - {attributes, record_info(fields, common_alarm)}]), - ok = ekka_mnesia:create_table(?ALARM_HISTORY_TAB, [ - {type, set}, - {disc_copies, [node()]}, - {local_content, true}, - {record_name, alarm_history}, - {attributes, record_info(fields, alarm_history)}]); - -mnesia(copy) -> - ok = ekka_mnesia:copy_table(?ALARM_TAB), - ok = ekka_mnesia:copy_table(?ALARM_HISTORY_TAB). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -load() -> - gen_event:swap_handler(alarm_handler, {alarm_handler, swap}, {?MODULE, []}). - -%% on the way shutting down, give it back to OTP -unload() -> - gen_event:swap_handler(alarm_handler, {?MODULE, swap}, {alarm_handler, []}). - -get_alarms() -> - get_alarms(present). - -get_alarms(present) -> - Alarms = ets:tab2list(?ALARM_TAB), - [{Id, Desc} || #common_alarm{id = Id, desc = Desc} <- Alarms]; -get_alarms(history) -> - Alarms = ets:tab2list(?ALARM_HISTORY_TAB), - [{Id, Desc, ClearAt} || #alarm_history{id = Id, desc = Desc, clear_at = ClearAt} <- Alarms]. - -%%-------------------------------------------------------------------- -%% gen_event callbacks -%%-------------------------------------------------------------------- - -init({_Args, {alarm_handler, ExistingAlarms}}) -> - init_tables(ExistingAlarms), - {ok, []}; - -init(_) -> - init_tables([]), - {ok, []}. - -handle_event({set_alarm, {AlarmId, AlarmDesc = #alarm{timestamp = undefined}}}, State) -> - handle_event({set_alarm, {AlarmId, AlarmDesc#alarm{timestamp = erlang:system_time(millisecond)}}}, State); -handle_event({set_alarm, Alarm = {AlarmId, AlarmDesc}}, State) -> - ?LOG(warning, "New Alarm: ~p, Alarm Info: ~p", [AlarmId, AlarmDesc]), - case encode_alarm(Alarm) of - {ok, Json} -> - emqx_broker:safe_publish(alarm_msg(topic(alert), Json)); - {error, Reason} -> - ?LOG(error, "Failed to encode alarm: ~p", [Reason]) - end, - set_alarm_(AlarmId, AlarmDesc), - {ok, State}; -handle_event({clear_alarm, AlarmId}, State) -> - ?LOG(info, "Clear Alarm: ~p", [AlarmId]), - case encode_alarm({AlarmId, undefined}) of - {ok, Json} -> - emqx_broker:safe_publish(alarm_msg(topic(clear), Json)); - {error, Reason} -> - ?LOG(error, "Failed to encode alarm: ~p", [Reason]) - end, - clear_alarm_(AlarmId), - {ok, State}; -handle_event(_, State) -> - {ok, State}. - -handle_info(_, State) -> - {ok, State}. - -handle_call(_Query, State) -> - {ok, {error, bad_query}, State}. - -terminate(swap, _State) -> - {emqx_alarm_handler, get_alarms()}; -terminate(_, _) -> - ok. - -%%------------------------------------------------------------------------------ -%% Internal functions -%%------------------------------------------------------------------------------ - -init_tables(ExistingAlarms) -> - mnesia:clear_table(?ALARM_TAB), - lists:foreach(fun({Id, Desc}) -> - set_alarm_history(Id, Desc) - end, ExistingAlarms). - -encode_alarm({AlarmId, #alarm{severity = Severity, - title = Title, - summary = Summary, - timestamp = Ts}}) -> - Descr = #{severity => Severity, - title => iolist_to_binary(Title), - summary => iolist_to_binary(Summary), - timestamp => Ts - }, - emqx_json:safe_encode(#{id => maybe_to_binary(AlarmId), - desc => Descr - }); - -encode_alarm({AlarmId, undefined}) -> - emqx_json:safe_encode(#{id => maybe_to_binary(AlarmId)}); -encode_alarm({AlarmId, AlarmDesc}) -> - emqx_json:safe_encode(#{id => maybe_to_binary(AlarmId), - desc => maybe_to_binary(AlarmDesc) - }). - -alarm_msg(Topic, Payload) -> - emqx_message:make(?MODULE, 0, Topic, Payload, - #{sys => true}, - #{properties => #{'Content-Type' => <<"application/json">>}} - ). - -topic(alert) -> - emqx_topic:systop(<<"alarms/alert">>); -topic(clear) -> - emqx_topic:systop(<<"alarms/clear">>). - -maybe_to_binary(Data) when is_binary(Data) -> - Data; -maybe_to_binary(Data) -> - iolist_to_binary(io_lib:format("~p", [Data])). - -set_alarm_(Id, Desc) -> - mnesia:dirty_write(?ALARM_TAB, #common_alarm{id = Id, desc = Desc}). - -clear_alarm_(Id) -> - case mnesia:dirty_read(?ALARM_TAB, Id) of - [#common_alarm{desc = Desc}] -> - set_alarm_history(Id, Desc), - mnesia:dirty_delete(?ALARM_TAB, Id); - [] -> ok - end. - -set_alarm_history(Id, Desc) -> - His = #alarm_history{id = Id, - desc = Desc, - clear_at = erlang:system_time(millisecond)}, - mnesia:dirty_write(?ALARM_HISTORY_TAB, His). diff --git a/_build/emqx/lib/emqx/src/emqx_app.erl b/_build/emqx/lib/emqx/src/emqx_app.erl deleted file mode 100644 index 689a1b69ef..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_app.erl +++ /dev/null @@ -1,73 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_app). - --behaviour(application). - --export([ start/2 - , stop/1 - ]). - --define(APP, emqx). - -%%-------------------------------------------------------------------- -%% Application callbacks -%%-------------------------------------------------------------------- - -start(_Type, _Args) -> - print_banner(), - ekka:start(), - {ok, Sup} = emqx_sup:start_link(), - ok = emqx_modules:load(), - ok = emqx_plugins:init(), - emqx_plugins:load(), - emqx_boot:is_enabled(listeners) - andalso (ok = emqx_listeners:start()), - start_autocluster(), - register(emqx, self()), - emqx_alarm_handler:load(), - print_vsn(), - {ok, Sup}. - --spec(stop(State :: term()) -> term()). -stop(_State) -> - emqx_alarm_handler:unload(), - emqx_boot:is_enabled(listeners) - andalso emqx_listeners:stop(), - emqx_modules:unload(). - -%%-------------------------------------------------------------------- -%% Print Banner -%%-------------------------------------------------------------------- - -print_banner() -> - io:format("Starting ~s on node ~s~n", [?APP, node()]). - -print_vsn() -> - {ok, Descr} = application:get_key(description), - {ok, Vsn} = application:get_key(vsn), - io:format("~s ~s is running now!~n", [Descr, Vsn]). - -%%-------------------------------------------------------------------- -%% Autocluster -%%-------------------------------------------------------------------- - -start_autocluster() -> - ekka:callback(prepare, fun emqx:shutdown/1), - ekka:callback(reboot, fun emqx:reboot/0), - ekka:autocluster(?APP). - diff --git a/_build/emqx/lib/emqx/src/emqx_banned.erl b/_build/emqx/lib/emqx/src/emqx_banned.erl deleted file mode 100644 index 80f93be705..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_banned.erl +++ /dev/null @@ -1,161 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_banned). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Banned]"). - -%% Mnesia bootstrap --export([mnesia/1]). - --boot_mnesia({mnesia, [boot]}). --copy_mnesia({mnesia, [copy]}). - --export([start_link/0, stop/0]). - --export([ check/1 - , create/1 - , delete/1 - , info/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --define(BANNED_TAB, ?MODULE). - -%%-------------------------------------------------------------------- -%% Mnesia bootstrap -%%-------------------------------------------------------------------- - -mnesia(boot) -> - ok = ekka_mnesia:create_table(?BANNED_TAB, [ - {type, set}, - {disc_copies, [node()]}, - {record_name, banned}, - {attributes, record_info(fields, banned)}, - {storage_properties, [{ets, [{read_concurrency, true}]}]}]); - -mnesia(copy) -> - ok = ekka_mnesia:copy_table(?BANNED_TAB). - -%% @doc Start the banned server. --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - -%% for tests --spec(stop() -> ok). -stop() -> gen_server:stop(?MODULE). - --spec(check(emqx_types:clientinfo()) -> boolean()). -check(ClientInfo) -> - do_check({clientid, maps:get(clientid, ClientInfo, undefined)}) - orelse do_check({username, maps:get(username, ClientInfo, undefined)}) - orelse do_check({peerhost, maps:get(peerhost, ClientInfo, undefined)}). - -do_check({_, undefined}) -> - false; -do_check(Who) when is_tuple(Who) -> - case mnesia:dirty_read(?BANNED_TAB, Who) of - [] -> false; - [#banned{until = Until}] -> - Until > erlang:system_time(second) - end. - --spec(create(emqx_types:banned()) -> ok). -create(#{who := Who, - by := By, - reason := Reason, - at := At, - until := Until}) -> - mnesia:dirty_write(?BANNED_TAB, #banned{who = Who, - by = By, - reason = Reason, - at = At, - until = Until}); -create(Banned) when is_record(Banned, banned) -> - mnesia:dirty_write(?BANNED_TAB, Banned). - --spec(delete({clientid, emqx_types:clientid()} - | {username, emqx_types:username()} - | {peerhost, emqx_types:peerhost()}) -> ok). -delete(Who) -> - mnesia:dirty_delete(?BANNED_TAB, Who). - -info(InfoKey) -> - mnesia:table_info(?BANNED_TAB, InfoKey). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - {ok, ensure_expiry_timer(#{expiry_timer => undefined})}. - -handle_call(Req, _From, State) -> - ?LOG(error, "unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "unexpected msg: ~p", [Msg]), - {noreply, State}. - -handle_info({timeout, TRef, expire}, State = #{expiry_timer := TRef}) -> - mnesia:async_dirty(fun expire_banned_items/1, [erlang:system_time(second)]), - {noreply, ensure_expiry_timer(State), hibernate}; - -handle_info(Info, State) -> - ?LOG(error, "unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{expiry_timer := TRef}) -> - emqx_misc:cancel_timer(TRef). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - --ifdef(TEST). -ensure_expiry_timer(State) -> - State#{expiry_timer := emqx_misc:start_timer(10, expire)}. --else. -ensure_expiry_timer(State) -> - State#{expiry_timer := emqx_misc:start_timer(timer:minutes(1), expire)}. --endif. - -expire_banned_items(Now) -> - mnesia:foldl( - fun(B = #banned{until = Until}, _Acc) when Until < Now -> - mnesia:delete_object(?BANNED_TAB, B, sticky_write); - (_, _Acc) -> ok - end, ok, ?BANNED_TAB). - diff --git a/_build/emqx/lib/emqx/src/emqx_base62.erl b/_build/emqx/lib/emqx/src/emqx_base62.erl deleted file mode 100644 index 52728faab0..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_base62.erl +++ /dev/null @@ -1,106 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_base62). - -%% APIs --export([ encode/1 - , decode/1 - ]). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Encode any data to base62 binary --spec encode(string() | integer() | binary()) -> binary(). -encode(I) when is_integer(I) -> - encode(integer_to_binary(I)); -encode(S) when is_list(S)-> - encode(unicode:characters_to_binary(S)); -encode(B) when is_binary(B) -> - encode(B, <<>>). - -%% encode(D, string) -> -%% binary_to_list(encode(D)). - -%% @doc Decode base62 binary to origin data binary -decode(B) when is_binary(B) -> - decode(B, <<>>). - -%%-------------------------------------------------------------------- -%% Interval Functions -%%-------------------------------------------------------------------- - -encode(<>, Acc) -> - CharList = [encode_char(Index1), encode_char(Index2), encode_char(Index3), encode_char(Index4)], - NewAcc = <>, - encode(Rest, NewAcc); -encode(<>, Acc) -> - CharList = [encode_char(Index1), encode_char(Index2), encode_char(Index3)], - NewAcc = <>, - encode(<<>>, NewAcc); -encode(<>, Acc) -> - CharList = [encode_char(Index1), encode_char(Index2)], - NewAcc = <>, - encode(<<>>, NewAcc); -encode(<<>>, Acc) -> - Acc. - -decode(<>, Acc) - when bit_size(Rest) >= 8-> - case Head == $9 of - true -> - <> = Rest, - DecodeChar = decode_char(9, Head1), - <<_:2, RestBit:6>> = <>, - NewAcc = <>, - decode(Rest1, NewAcc); - false -> - DecodeChar = decode_char(Head), - <<_:2, RestBit:6>> = <>, - NewAcc = <>, - decode(Rest, NewAcc) - end; -decode(<>, Acc) -> - DecodeChar = decode_char(Head), - LeftBitSize = bit_size(Acc) rem 8, - RightBitSize = 8 - LeftBitSize, - <<_:LeftBitSize, RestBit:RightBitSize>> = <>, - NewAcc = <>, - decode(Rest, NewAcc); -decode(<<>>, Acc) -> - Acc. - - -encode_char(I) when I < 26 -> - $A + I; -encode_char(I) when I < 52 -> - $a + I - 26; -encode_char(I) when I < 61 -> - $0 + I - 52; -encode_char(I) -> - [$9, $A + I - 61]. - -decode_char(I) when I >= $a andalso I =< $z -> - I + 26 - $a; -decode_char(I) when I >= $0 andalso I =< $8-> - I + 52 - $0; -decode_char(I) when I >= $A andalso I =< $Z-> - I - $A. - -decode_char(9, I) -> - I + 61 - $A. diff --git a/_build/emqx/lib/emqx/src/emqx_batch.erl b/_build/emqx/lib/emqx/src/emqx_batch.erl deleted file mode 100644 index c6b805e4ef..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_batch.erl +++ /dev/null @@ -1,91 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_batch). - -%% APIs --export([ init/1 - , push/2 - , commit/1 - , size/1 - , items/1 - ]). - --export_type([options/0, batch/0]). - --record(batch, { - batch_size :: non_neg_integer(), - batch_q :: list(any()), - linger_ms :: pos_integer(), - linger_timer :: reference() | undefined, - commit_fun :: function() - }). - --type(options() :: #{ - batch_size => non_neg_integer(), - linger_ms => pos_integer(), - commit_fun := function() - }). - --opaque(batch() :: #batch{}). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - --spec(init(options()) -> batch()). -init(Opts) when is_map(Opts) -> - #batch{batch_size = maps:get(batch_size, Opts, 1000), - batch_q = [], - linger_ms = maps:get(linger_ms, Opts, 1000), - commit_fun = maps:get(commit_fun, Opts)}. - --spec(push(any(), batch()) -> batch()). -push(El, Batch = #batch{batch_q = Q, - linger_ms = Ms, - linger_timer = undefined}) - when length(Q) == 0 -> - TRef = erlang:send_after(Ms, self(), batch_linger_expired), - Batch#batch{batch_q = [El], linger_timer = TRef}; - -%% no limit. -push(El, Batch = #batch{batch_size = 0, batch_q = Q}) -> - Batch#batch{batch_q = [El|Q]}; - -push(El, Batch = #batch{batch_size = MaxSize, batch_q = Q}) - when length(Q) >= MaxSize -> - commit(Batch#batch{batch_q = [El|Q]}); - -push(El, Batch = #batch{batch_q = Q}) -> - Batch#batch{batch_q = [El|Q]}. - --spec(commit(batch()) -> batch()). -commit(Batch = #batch{batch_q = Q, commit_fun = Commit}) -> - _ = Commit(lists:reverse(Q)), - reset(Batch). - -reset(Batch = #batch{linger_timer = TRef}) -> - _ = emqx_misc:cancel_timer(TRef), - Batch#batch{batch_q = [], linger_timer = undefined}. - --spec(size(batch()) -> non_neg_integer()). -size(#batch{batch_q = Q}) -> - length(Q). - --spec(items(batch()) -> list(any())). -items(#batch{batch_q = Q}) -> - lists:reverse(Q). - diff --git a/_build/emqx/lib/emqx/src/emqx_boot.erl b/_build/emqx/lib/emqx/src/emqx_boot.erl deleted file mode 100644 index be27607be4..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_boot.erl +++ /dev/null @@ -1,29 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_boot). - --export([is_enabled/1]). - --define(BOOT_MODULES, [router, broker, listeners]). - --spec(is_enabled(all|router|broker|listeners) -> boolean()). -is_enabled(Mod) -> - (BootMods = boot_modules()) =:= all orelse lists:member(Mod, BootMods). - -boot_modules() -> - application:get_env(emqx, boot_modules, ?BOOT_MODULES). - diff --git a/_build/emqx/lib/emqx/src/emqx_broker.erl b/_build/emqx/lib/emqx/src/emqx_broker.erl deleted file mode 100644 index c5d9c6793d..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_broker.erl +++ /dev/null @@ -1,506 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_broker). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). --include("emqx_mqtt.hrl"). - --logger_header("[Broker]"). - --export([start_link/2]). - -%% PubSub --export([ subscribe/1 - , subscribe/2 - , subscribe/3 - ]). - --export([unsubscribe/1]). - --export([subscriber_down/1]). - --export([ publish/1 - , safe_publish/1 - ]). - --export([dispatch/2]). - -%% PubSub Infos --export([ subscriptions/1 - , subscribers/1 - , subscribed/2 - ]). - --export([ get_subopts/2 - , set_subopts/2 - ]). - --export([topics/0]). - -%% Stats fun --export([stats_fun/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --import(emqx_tables, [lookup_value/2, lookup_value/3]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --define(BROKER, ?MODULE). - -%% ETS tables for PubSub --define(SUBOPTION, emqx_suboption). --define(SUBSCRIBER, emqx_subscriber). --define(SUBSCRIPTION, emqx_subscription). - -%% Guards --define(is_subid(Id), (is_binary(Id) orelse is_atom(Id))). - --spec(start_link(atom(), pos_integer()) -> startlink_ret()). -start_link(Pool, Id) -> - ok = create_tabs(), - gen_server:start_link({local, emqx_misc:proc_name(?BROKER, Id)}, - ?MODULE, [Pool, Id], []). - -%%------------------------------------------------------------------------------ -%% Create tabs -%%------------------------------------------------------------------------------ - --spec(create_tabs() -> ok). -create_tabs() -> - TabOpts = [public, {read_concurrency, true}, {write_concurrency, true}], - - %% SubOption: {SubPid, Topic} -> SubOption - ok = emqx_tables:new(?SUBOPTION, [set | TabOpts]), - - %% Subscription: SubPid -> Topic1, Topic2, Topic3, ... - %% duplicate_bag: o(1) insert - ok = emqx_tables:new(?SUBSCRIPTION, [duplicate_bag | TabOpts]), - - %% Subscriber: Topic -> SubPid1, SubPid2, SubPid3, ... - %% bag: o(n) insert:( - ok = emqx_tables:new(?SUBSCRIBER, [bag | TabOpts]). - -%%------------------------------------------------------------------------------ -%% Subscribe API -%%------------------------------------------------------------------------------ - --spec(subscribe(emqx_topic:topic()) -> ok). -subscribe(Topic) when is_binary(Topic) -> - subscribe(Topic, undefined). - --spec(subscribe(emqx_topic:topic(), emqx_types:subid() | emqx_types:subopts()) -> ok). -subscribe(Topic, SubId) when is_binary(Topic), ?is_subid(SubId) -> - subscribe(Topic, SubId, ?DEFAULT_SUBOPTS); -subscribe(Topic, SubOpts) when is_binary(Topic), is_map(SubOpts) -> - subscribe(Topic, undefined, SubOpts). - --spec(subscribe(emqx_topic:topic(), emqx_types:subid(), emqx_types:subopts()) -> ok). -subscribe(Topic, SubId, SubOpts0) when is_binary(Topic), ?is_subid(SubId), is_map(SubOpts0) -> - SubOpts = maps:merge(?DEFAULT_SUBOPTS, SubOpts0), - case ets:member(?SUBOPTION, {SubPid = self(), Topic}) of - false -> %% New - ok = emqx_broker_helper:register_sub(SubPid, SubId), - do_subscribe(Topic, SubPid, with_subid(SubId, SubOpts)); - true -> %% Existed - set_subopts(SubPid, Topic, with_subid(SubId, SubOpts)), - ok %% ensure to return 'ok' - end. - --compile({inline, [with_subid/2]}). -with_subid(undefined, SubOpts) -> - SubOpts; -with_subid(SubId, SubOpts) -> - maps:put(subid, SubId, SubOpts). - -%% @private -do_subscribe(Topic, SubPid, SubOpts) -> - true = ets:insert(?SUBSCRIPTION, {SubPid, Topic}), - Group = maps:get(share, SubOpts, undefined), - do_subscribe(Group, Topic, SubPid, SubOpts). - -do_subscribe(undefined, Topic, SubPid, SubOpts) -> - case emqx_broker_helper:get_sub_shard(SubPid, Topic) of - 0 -> true = ets:insert(?SUBSCRIBER, {Topic, SubPid}), - true = ets:insert(?SUBOPTION, {{SubPid, Topic}, SubOpts}), - call(pick(Topic), {subscribe, Topic}); - I -> true = ets:insert(?SUBSCRIBER, {{shard, Topic, I}, SubPid}), - true = ets:insert(?SUBOPTION, {{SubPid, Topic}, maps:put(shard, I, SubOpts)}), - call(pick({Topic, I}), {subscribe, Topic, I}) - end; - -%% Shared subscription -do_subscribe(Group, Topic, SubPid, SubOpts) -> - true = ets:insert(?SUBOPTION, {{SubPid, Topic}, SubOpts}), - emqx_shared_sub:subscribe(Group, Topic, SubPid). - -%%-------------------------------------------------------------------- -%% Unsubscribe API -%%-------------------------------------------------------------------- - --spec(unsubscribe(emqx_topic:topic()) -> ok). -unsubscribe(Topic) when is_binary(Topic) -> - SubPid = self(), - case ets:lookup(?SUBOPTION, {SubPid, Topic}) of - [{_, SubOpts}] -> - _ = emqx_broker_helper:reclaim_seq(Topic), - do_unsubscribe(Topic, SubPid, SubOpts); - [] -> ok - end. - -do_unsubscribe(Topic, SubPid, SubOpts) -> - true = ets:delete(?SUBOPTION, {SubPid, Topic}), - true = ets:delete_object(?SUBSCRIPTION, {SubPid, Topic}), - Group = maps:get(share, SubOpts, undefined), - do_unsubscribe(Group, Topic, SubPid, SubOpts). - -do_unsubscribe(undefined, Topic, SubPid, SubOpts) -> - case maps:get(shard, SubOpts, 0) of - 0 -> true = ets:delete_object(?SUBSCRIBER, {Topic, SubPid}), - cast(pick(Topic), {unsubscribed, Topic}); - I -> true = ets:delete_object(?SUBSCRIBER, {{shard, Topic, I}, SubPid}), - cast(pick({Topic, I}), {unsubscribed, Topic, I}) - end; - -do_unsubscribe(Group, Topic, SubPid, _SubOpts) -> - emqx_shared_sub:unsubscribe(Group, Topic, SubPid). - -%%-------------------------------------------------------------------- -%% Publish -%%-------------------------------------------------------------------- - --spec(publish(emqx_types:message()) -> emqx_types:publish_result()). -publish(Msg) when is_record(Msg, message) -> - _ = emqx_tracer:trace(publish, Msg), - emqx_message:is_sys(Msg) orelse emqx_metrics:inc('messages.publish'), - case emqx_hooks:run_fold('message.publish', [], emqx_message:clean_dup(Msg)) of - #message{headers = #{allow_publish := false}} -> - ?LOG(notice, "Stop publishing: ~s", [emqx_message:format(Msg)]), - []; - Msg1 = #message{topic = Topic} -> - route(aggre(emqx_router:match_routes(Topic)), delivery(Msg1)) - end. - -%% Called internally --spec(safe_publish(emqx_types:message()) -> emqx_types:publish_result()). -safe_publish(Msg) when is_record(Msg, message) -> - try - publish(Msg) - catch - _:Error:Stk-> - ?LOG(error, "Publish error: ~0p~n~s~n~0p", - [Error, emqx_message:format(Msg), Stk]), - [] - end. - --compile({inline, [delivery/1]}). -delivery(Msg) -> #delivery{sender = self(), message = Msg}. - -%%-------------------------------------------------------------------- -%% Route -%%-------------------------------------------------------------------- - --spec(route([emqx_types:route_entry()], emqx_types:delivery()) - -> emqx_types:publish_result()). -route([], #delivery{message = Msg}) -> - ok = emqx_hooks:run('message.dropped', [Msg, #{node => node()}, no_subscribers]), - ok = inc_dropped_cnt(Msg), - []; - -route(Routes, Delivery) -> - lists:foldl(fun(Route, Acc) -> - [do_route(Route, Delivery) | Acc] - end, [], Routes). - -do_route({To, Node}, Delivery) when Node =:= node() -> - {Node, To, dispatch(To, Delivery)}; -do_route({To, Node}, Delivery) when is_atom(Node) -> - {Node, To, forward(Node, To, Delivery, emqx:get_env(rpc_mode, async))}; -do_route({To, Group}, Delivery) when is_tuple(Group); is_binary(Group) -> - {share, To, emqx_shared_sub:dispatch(Group, To, Delivery)}. - -aggre([]) -> []; -aggre([#route{topic = To, dest = Node}]) when is_atom(Node) -> - [{To, Node}]; -aggre([#route{topic = To, dest = {Group, _Node}}]) -> - [{To, Group}]; -aggre(Routes) -> - lists:foldl( - fun(#route{topic = To, dest = Node}, Acc) when is_atom(Node) -> - [{To, Node} | Acc]; - (#route{topic = To, dest = {Group, _Node}}, Acc) -> - lists:usort([{To, Group} | Acc]) - end, [], Routes). - -%% @doc Forward message to another node. --spec(forward(node(), emqx_types:topic(), emqx_types:delivery(), RpcMode::sync|async) - -> emqx_types:deliver_result()). -forward(Node, To, Delivery, async) -> - case emqx_rpc:cast(To, Node, ?BROKER, dispatch, [To, Delivery]) of - true -> emqx_metrics:inc('messages.forward'); - {badrpc, Reason} -> - ?LOG(error, "Ansync forward msg to ~s failed due to ~p", [Node, Reason]), - {error, badrpc} - end; - -forward(Node, To, Delivery, sync) -> - case emqx_rpc:call(To, Node, ?BROKER, dispatch, [To, Delivery]) of - {badrpc, Reason} -> - ?LOG(error, "Sync forward msg to ~s failed due to ~p", [Node, Reason]), - {error, badrpc}; - Result -> - emqx_metrics:inc('messages.forward'), Result - end. - --spec(dispatch(emqx_topic:topic(), emqx_types:delivery()) -> emqx_types:deliver_result()). -dispatch(Topic, #delivery{message = Msg}) -> - case subscribers(Topic) of - [] -> ok = emqx_hooks:run('message.dropped', [Msg, #{node => node()}, no_subscribers]), - ok = inc_dropped_cnt(Msg), - {error, no_subscribers}; - [Sub] -> %% optimize? - dispatch(Sub, Topic, Msg); - Subs -> lists:foldl( - fun(Sub, Res) -> - case dispatch(Sub, Topic, Msg) of - ok -> Res; - Err -> Err - end - end, ok, Subs) - end. - -dispatch(SubPid, Topic, Msg) when is_pid(SubPid) -> - case erlang:is_process_alive(SubPid) of - true -> - SubPid ! {deliver, Topic, Msg}, - ok; - false -> {error, subscriber_die} - end; - -dispatch({shard, I}, Topic, Msg) -> - lists:foldl( - fun(SubPid, Res) -> - case dispatch(SubPid, Topic, Msg) of - ok -> Res; - Err -> Err - end - end, ok, subscribers({shard, Topic, I})). - --compile({inline, [inc_dropped_cnt/1]}). -inc_dropped_cnt(Msg) -> - case emqx_message:is_sys(Msg) of - true -> ok; - false -> ok = emqx_metrics:inc('messages.dropped'), - emqx_metrics:inc('messages.dropped.no_subscribers') - end. - --compile({inline, [subscribers/1]}). --spec(subscribers(emqx_topic:topic() | {shard, emqx_topic:topic(), non_neg_integer()}) - -> [pid()]). -subscribers(Topic) when is_binary(Topic) -> - lookup_value(?SUBSCRIBER, Topic, []); -subscribers(Shard = {shard, _Topic, _I}) -> - lookup_value(?SUBSCRIBER, Shard, []). - -%%-------------------------------------------------------------------- -%% Subscriber is down -%%-------------------------------------------------------------------- - --spec(subscriber_down(pid()) -> true). -subscriber_down(SubPid) -> - lists:foreach( - fun(Topic) -> - case lookup_value(?SUBOPTION, {SubPid, Topic}) of - SubOpts when is_map(SubOpts) -> - _ = emqx_broker_helper:reclaim_seq(Topic), - true = ets:delete(?SUBOPTION, {SubPid, Topic}), - case maps:get(shard, SubOpts, 0) of - 0 -> true = ets:delete_object(?SUBSCRIBER, {Topic, SubPid}), - ok = cast(pick(Topic), {unsubscribed, Topic}); - I -> true = ets:delete_object(?SUBSCRIBER, {{shard, Topic, I}, SubPid}), - ok = cast(pick({Topic, I}), {unsubscribed, Topic, I}) - end; - undefined -> ok - end - end, lookup_value(?SUBSCRIPTION, SubPid, [])), - ets:delete(?SUBSCRIPTION, SubPid). - -%%-------------------------------------------------------------------- -%% Management APIs -%%-------------------------------------------------------------------- - --spec(subscriptions(pid() | emqx_types:subid()) - -> [{emqx_topic:topic(), emqx_types:subopts()}]). -subscriptions(SubPid) when is_pid(SubPid) -> - [{Topic, lookup_value(?SUBOPTION, {SubPid, Topic}, #{})} - || Topic <- lookup_value(?SUBSCRIPTION, SubPid, [])]; -subscriptions(SubId) -> - case emqx_broker_helper:lookup_subpid(SubId) of - SubPid when is_pid(SubPid) -> - subscriptions(SubPid); - undefined -> [] - end. - --spec(subscribed(pid() | emqx_types:subid(), emqx_topic:topic()) -> boolean()). -subscribed(SubPid, Topic) when is_pid(SubPid) -> - ets:member(?SUBOPTION, {SubPid, Topic}); -subscribed(SubId, Topic) when ?is_subid(SubId) -> - SubPid = emqx_broker_helper:lookup_subpid(SubId), - ets:member(?SUBOPTION, {SubPid, Topic}). - --spec(get_subopts(pid(), emqx_topic:topic()) -> maybe(emqx_types:subopts())). -get_subopts(SubPid, Topic) when is_pid(SubPid), is_binary(Topic) -> - lookup_value(?SUBOPTION, {SubPid, Topic}); -get_subopts(SubId, Topic) when ?is_subid(SubId) -> - case emqx_broker_helper:lookup_subpid(SubId) of - SubPid when is_pid(SubPid) -> - get_subopts(SubPid, Topic); - undefined -> undefined - end. - --spec(set_subopts(emqx_topic:topic(), emqx_types:subopts()) -> boolean()). -set_subopts(Topic, NewOpts) when is_binary(Topic), is_map(NewOpts) -> - set_subopts(self(), Topic, NewOpts). - -%% @private -set_subopts(SubPid, Topic, NewOpts) -> - Sub = {SubPid, Topic}, - case ets:lookup(?SUBOPTION, Sub) of - [{_, OldOpts}] -> - ets:insert(?SUBOPTION, {Sub, maps:merge(OldOpts, NewOpts)}); - [] -> false - end. - --spec(topics() -> [emqx_topic:topic()]). -topics() -> - emqx_router:topics(). - -%%-------------------------------------------------------------------- -%% Stats fun -%%-------------------------------------------------------------------- - -stats_fun() -> - safe_update_stats(?SUBSCRIBER, 'subscribers.count', 'subscribers.max'), - safe_update_stats(?SUBSCRIPTION, 'subscriptions.count', 'subscriptions.max'), - safe_update_stats(?SUBOPTION, 'suboptions.count', 'suboptions.max'). - -safe_update_stats(Tab, Stat, MaxStat) -> - case ets:info(Tab, size) of - undefined -> ok; - Size -> emqx_stats:setstat(Stat, MaxStat, Size) - end. - -%%-------------------------------------------------------------------- -%% call, cast, pick -%%-------------------------------------------------------------------- - --compile({inline, [call/2, cast/2, pick/1]}). - -call(Broker, Req) -> - gen_server:call(Broker, Req). - -cast(Broker, Msg) -> - gen_server:cast(Broker, Msg). - -%% Pick a broker -pick(Topic) -> - gproc_pool:pick_worker(broker_pool, Topic). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Pool, Id]) -> - true = gproc_pool:connect_worker(Pool, {Pool, Id}), - {ok, #{pool => Pool, id => Id}}. - -handle_call({subscribe, Topic}, _From, State) -> - Ok = emqx_router:do_add_route(Topic), - {reply, Ok, State}; - -handle_call({subscribe, Topic, I}, _From, State) -> - Ok = case get(Shard = {Topic, I}) of - undefined -> - _ = put(Shard, true), - true = ets:insert(?SUBSCRIBER, {Topic, {shard, I}}), - cast(pick(Topic), {subscribe, Topic}); - true -> ok - end, - {reply, Ok, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({subscribe, Topic}, State) -> - case emqx_router:do_add_route(Topic) of - ok -> ok; - {error, Reason} -> - ?LOG(error, "Failed to add route: ~p", [Reason]) - end, - {noreply, State}; - -handle_cast({unsubscribed, Topic}, State) -> - case ets:member(?SUBSCRIBER, Topic) of - false -> - _ = emqx_router:do_delete_route(Topic); - true -> ok - end, - {noreply, State}; - -handle_cast({unsubscribed, Topic, I}, State) -> - case ets:member(?SUBSCRIBER, {shard, Topic, I}) of - false -> - _ = erase({Topic, I}), - true = ets:delete_object(?SUBSCRIBER, {Topic, {shard, I}}), - cast(pick(Topic), {unsubscribed, Topic}); - true -> ok - end, - {noreply, State}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{pool := Pool, id := Id}) -> - gproc_pool:disconnect_worker(Pool, {Pool, Id}). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - diff --git a/_build/emqx/lib/emqx/src/emqx_broker_helper.erl b/_build/emqx/lib/emqx/src/emqx_broker_helper.erl deleted file mode 100644 index 18ebbccf26..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_broker_helper.erl +++ /dev/null @@ -1,165 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_broker_helper). - --behaviour(gen_server). - --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Broker Helper]"). - --export([start_link/0]). - -%% APIs --export([ register_sub/2 - , lookup_subid/1 - , lookup_subpid/1 - , get_sub_shard/2 - , create_seq/1 - , reclaim_seq/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --define(HELPER, ?MODULE). --define(SUBID, emqx_subid). --define(SUBMON, emqx_submon). --define(SUBSEQ, emqx_subseq). --define(SHARD, 1024). - --define(BATCH_SIZE, 100000). - --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?HELPER}, ?MODULE, [], []). - --spec(register_sub(pid(), emqx_types:subid()) -> ok). -register_sub(SubPid, SubId) when is_pid(SubPid) -> - case ets:lookup(?SUBMON, SubPid) of - [] -> - gen_server:cast(?HELPER, {register_sub, SubPid, SubId}); - [{_, SubId}] -> - ok; - _Other -> - error(subid_conflict) - end. - --spec(lookup_subid(pid()) -> maybe(emqx_types:subid())). -lookup_subid(SubPid) when is_pid(SubPid) -> - emqx_tables:lookup_value(?SUBMON, SubPid). - --spec(lookup_subpid(emqx_types:subid()) -> maybe(pid())). -lookup_subpid(SubId) -> - emqx_tables:lookup_value(?SUBID, SubId). - --spec(get_sub_shard(pid(), emqx_topic:topic()) -> non_neg_integer()). -get_sub_shard(SubPid, Topic) -> - case create_seq(Topic) of - Seq when Seq =< ?SHARD -> 0; - _ -> erlang:phash2(SubPid, shards_num()) + 1 - end. - --spec(shards_num() -> pos_integer()). -shards_num() -> - %% Dynamic sharding later... - ets:lookup_element(?HELPER, shards, 2). - --spec(create_seq(emqx_topic:topic()) -> emqx_sequence:seqid()). -create_seq(Topic) -> - emqx_sequence:nextval(?SUBSEQ, Topic). - --spec(reclaim_seq(emqx_topic:topic()) -> emqx_sequence:seqid()). -reclaim_seq(Topic) -> - emqx_sequence:reclaim(?SUBSEQ, Topic). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - %% Helper table - ok = emqx_tables:new(?HELPER, [{read_concurrency, true}]), - %% Shards: CPU * 32 - true = ets:insert(?HELPER, {shards, emqx_vm:schedulers() * 32}), - %% SubSeq: Topic -> SeqId - ok = emqx_sequence:create(?SUBSEQ), - %% SubId: SubId -> SubPid - ok = emqx_tables:new(?SUBID, [public, {read_concurrency, true}, {write_concurrency, true}]), - %% SubMon: SubPid -> SubId - ok = emqx_tables:new(?SUBMON, [public, {read_concurrency, true}, {write_concurrency, true}]), - %% Stats timer - ok = emqx_stats:update_interval(broker_stats, fun emqx_broker:stats_fun/0), - {ok, #{pmon => emqx_pmon:new()}}. - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({register_sub, SubPid, SubId}, State = #{pmon := PMon}) -> - true = (SubId =:= undefined) orelse ets:insert(?SUBID, {SubId, SubPid}), - true = ets:insert(?SUBMON, {SubPid, SubId}), - {noreply, State#{pmon := emqx_pmon:monitor(SubPid, PMon)}}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({'DOWN', _MRef, process, SubPid, _Reason}, State = #{pmon := PMon}) -> - SubPids = [SubPid | emqx_misc:drain_down(?BATCH_SIZE)], - ok = emqx_pool:async_submit( - fun lists:foreach/2, [fun clean_down/1, SubPids]), - {_, PMon1} = emqx_pmon:erase_all(SubPids, PMon), - {noreply, State#{pmon := PMon1}}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - true = emqx_sequence:delete(?SUBSEQ), - emqx_stats:cancel_update(broker_stats). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -clean_down(SubPid) -> - case ets:lookup(?SUBMON, SubPid) of - [{_, SubId}] -> - true = ets:delete(?SUBMON, SubPid), - true = (SubId =:= undefined) - orelse ets:delete_object(?SUBID, {SubId, SubPid}), - emqx_broker:subscriber_down(SubPid); - [] -> ok - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_broker_sup.erl b/_build/emqx/lib/emqx/src/emqx_broker_sup.erl deleted file mode 100644 index 8f62e5111b..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_broker_sup.erl +++ /dev/null @@ -1,55 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_broker_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -%%-------------------------------------------------------------------- -%% Supervisor callbacks -%%-------------------------------------------------------------------- - -init([]) -> - %% Broker pool - PoolSize = emqx_vm:schedulers() * 2, - BrokerPool = emqx_pool_sup:spec([broker_pool, hash, PoolSize, - {emqx_broker, start_link, []}]), - - %% Shared subscription - SharedSub = #{id => shared_sub, - start => {emqx_shared_sub, start_link, []}, - restart => permanent, - shutdown => 2000, - type => worker, - modules => [emqx_shared_sub]}, - - %% Broker helper - Helper = #{id => helper, - start => {emqx_broker_helper, start_link, []}, - restart => permanent, - shutdown => 2000, - type => worker, - modules => [emqx_broker_helper]}, - - {ok, {{one_for_all, 0, 1}, [BrokerPool, SharedSub, Helper]}}. - diff --git a/_build/emqx/lib/emqx/src/emqx_channel.erl b/_build/emqx/lib/emqx/src/emqx_channel.erl deleted file mode 100644 index a5d02734b8..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_channel.erl +++ /dev/null @@ -1,1598 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% MQTT Channel --module(emqx_channel). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Channel]"). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --export([ info/1 - , info/2 - , stats/1 - , caps/1 - ]). - --export([ init/2 - , handle_in/2 - , handle_deliver/2 - , handle_out/3 - , handle_timeout/3 - , handle_call/2 - , handle_info/2 - , terminate/2 - ]). - -%% Exports for CT --export([set_field/3]). - --import(emqx_misc, - [ run_fold/3 - , pipeline/3 - , maybe_apply/2 - ]). - --export_type([channel/0]). - --record(channel, { - %% MQTT ConnInfo - conninfo :: emqx_types:conninfo(), - %% MQTT ClientInfo - clientinfo :: emqx_types:clientinfo(), - %% MQTT Session - session :: maybe(emqx_session:session()), - %% Keepalive - keepalive :: maybe(emqx_keepalive:keepalive()), - %% MQTT Will Msg - will_msg :: maybe(emqx_types:message()), - %% MQTT Topic Aliases - topic_aliases :: emqx_types:topic_aliases(), - %% MQTT Topic Alias Maximum - alias_maximum :: maybe(map()), - %% Authentication Data Cache - auth_cache :: maybe(map()), - %% Timers - timers :: #{atom() => disabled | maybe(reference())}, - %% Conn State - conn_state :: conn_state(), - %% Takeover - takeover :: boolean(), - %% Resume - resuming :: boolean(), - %% Pending delivers when takeovering - pendings :: list() - }). - --opaque(channel() :: #channel{}). - --type(conn_state() :: idle | connecting | connected | disconnected). - --type(reply() :: {outgoing, emqx_types:packet()} - | {outgoing, [emqx_types:packet()]} - | {event, conn_state()|updated} - | {close, Reason :: atom()}). - --type(replies() :: emqx_types:packet() | reply() | [reply()]). - --define(IS_MQTT_V5, #channel{conninfo = #{proto_ver := ?MQTT_PROTO_V5}}). - --define(TIMER_TABLE, #{ - alive_timer => keepalive, - retry_timer => retry_delivery, - await_timer => expire_awaiting_rel, - expire_timer => expire_session, - will_timer => will_message - }). - --define(INFO_KEYS, [conninfo, conn_state, clientinfo, session, will_msg]). - --dialyzer({no_match, [shutdown/4, ensure_timer/2, interval/2]}). - -%%-------------------------------------------------------------------- -%% Info, Attrs and Caps -%%-------------------------------------------------------------------- - -%% @doc Get infos of the channel. --spec(info(channel()) -> emqx_types:infos()). -info(Channel) -> - maps:from_list(info(?INFO_KEYS, Channel)). - --spec(info(list(atom())|atom(), channel()) -> term()). -info(Keys, Channel) when is_list(Keys) -> - [{Key, info(Key, Channel)} || Key <- Keys]; -info(conninfo, #channel{conninfo = ConnInfo}) -> - ConnInfo; -info(zone, #channel{clientinfo = #{zone := Zone}}) -> - Zone; -info(clientid, #channel{clientinfo = #{clientid := ClientId}}) -> - ClientId; -info(clientinfo, #channel{clientinfo = ClientInfo}) -> - ClientInfo; -info(session, #channel{session = Session}) -> - maybe_apply(fun emqx_session:info/1, Session); -info(conn_state, #channel{conn_state = ConnState}) -> - ConnState; -info(keepalive, #channel{keepalive = Keepalive}) -> - maybe_apply(fun emqx_keepalive:info/1, Keepalive); -info(will_msg, #channel{will_msg = undefined}) -> - undefined; -info(will_msg, #channel{will_msg = WillMsg}) -> - emqx_message:to_map(WillMsg); -info(topic_aliases, #channel{topic_aliases = Aliases}) -> - Aliases; -info(alias_maximum, #channel{alias_maximum = Limits}) -> - Limits; -info(timers, #channel{timers = Timers}) -> Timers. - -%% TODO: Add more stats. --spec(stats(channel()) -> emqx_types:stats()). -stats(#channel{session = Session})-> - emqx_session:stats(Session). - --spec(caps(channel()) -> emqx_types:caps()). -caps(#channel{clientinfo = #{zone := Zone}}) -> - emqx_mqtt_caps:get_caps(Zone). - - -%%-------------------------------------------------------------------- -%% Init the channel -%%-------------------------------------------------------------------- - --spec(init(emqx_types:conninfo(), proplists:proplist()) -> channel()). -init(ConnInfo = #{peername := {PeerHost, _Port}, - sockname := {_Host, SockPort}}, Options) -> - Zone = proplists:get_value(zone, Options), - Peercert = maps:get(peercert, ConnInfo, undefined), - Protocol = maps:get(protocol, ConnInfo, mqtt), - MountPoint = emqx_zone:mountpoint(Zone), - ClientInfo = setting_peercert_infos( - Peercert, - #{zone => Zone, - protocol => Protocol, - peerhost => PeerHost, - sockport => SockPort, - clientid => undefined, - username => undefined, - mountpoint => MountPoint, - is_bridge => false, - is_superuser => false - }, Options), - #channel{conninfo = ConnInfo, - clientinfo = ClientInfo, - topic_aliases = #{inbound => #{}, - outbound => #{} - }, - auth_cache = #{}, - timers = #{}, - conn_state = idle, - takeover = false, - resuming = false, - pendings = [] - }. - -setting_peercert_infos(NoSSL, ClientInfo, _Options) - when NoSSL =:= nossl; - NoSSL =:= undefined -> - ClientInfo#{username => undefined}; - -setting_peercert_infos(Peercert, ClientInfo, Options) -> - {DN, CN} = {esockd_peercert:subject(Peercert), - esockd_peercert:common_name(Peercert)}, - Username = case proplists:get_value(peer_cert_as_username, Options) of - cn -> CN; - dn -> DN; - crt -> Peercert; - _ -> undefined - end, - ClientInfo#{username => Username, dn => DN, cn => CN}. - -%%-------------------------------------------------------------------- -%% Handle incoming packet -%%-------------------------------------------------------------------- - --spec(handle_in(emqx_types:packet(), channel()) - -> {ok, channel()} - | {ok, replies(), channel()} - | {shutdown, Reason :: term(), channel()} - | {shutdown, Reason :: term(), replies(), channel()}). -handle_in(?CONNECT_PACKET(), Channel = #channel{conn_state = connected}) -> - handle_out(disconnect, ?RC_PROTOCOL_ERROR, Channel); - -handle_in(?CONNECT_PACKET(ConnPkt), Channel) -> - case pipeline([fun enrich_conninfo/2, - fun run_conn_hooks/2, - fun check_connect/2, - fun enrich_client/2, - fun set_log_meta/2, - fun check_banned/2, - fun auth_connect/2 - ], ConnPkt, Channel#channel{conn_state = connecting}) of - {ok, NConnPkt, NChannel = #channel{clientinfo = ClientInfo}} -> - NChannel1 = NChannel#channel{ - will_msg = emqx_packet:will_msg(NConnPkt), - alias_maximum = init_alias_maximum(NConnPkt, ClientInfo) - }, - case enhanced_auth(?CONNECT_PACKET(NConnPkt), NChannel1) of - {ok, Properties, NChannel2} -> - process_connect(Properties, ensure_connected(NChannel2)); - {continue, Properties, NChannel2} -> - handle_out(auth, {?RC_CONTINUE_AUTHENTICATION, Properties}, NChannel2); - {error, ReasonCode, NChannel2} -> - handle_out(connack, ReasonCode, NChannel2) - end; - {error, ReasonCode, NChannel} -> - handle_out(connack, ReasonCode, NChannel) - end; - -handle_in(Packet = ?AUTH_PACKET(?RC_CONTINUE_AUTHENTICATION, _Properties), Channel = #channel{conn_state = ConnState}) -> - case enhanced_auth(Packet, Channel) of - {ok, NProperties, NChannel} -> - case ConnState of - connecting -> - process_connect(NProperties, ensure_connected(NChannel)); - connected -> - handle_out(auth, {?RC_SUCCESS, NProperties}, NChannel); - _ -> - handle_out(disconnect, ?RC_PROTOCOL_ERROR, Channel) - end; - {continue, NProperties, NChannel} -> - handle_out(auth, {?RC_CONTINUE_AUTHENTICATION, NProperties}, NChannel); - {error, NReasonCode, NChannel} -> - handle_out(connack, NReasonCode, NChannel) - end; - -handle_in(Packet = ?AUTH_PACKET(?RC_RE_AUTHENTICATE, _Properties), Channel = #channel{conn_state = connected}) -> - case enhanced_auth(Packet, Channel) of - {ok, NProperties, NChannel} -> - handle_out(auth, {?RC_SUCCESS, NProperties}, NChannel); - {continue, NProperties, NChannel} -> - handle_out(auth, {?RC_CONTINUE_AUTHENTICATION, NProperties}, NChannel); - {error, NReasonCode, NChannel} -> - handle_out(disconnect, NReasonCode, NChannel) - end; - -handle_in(?PACKET(_), Channel = #channel{conn_state = ConnState}) when ConnState =/= connected -> - handle_out(disconnect, ?RC_PROTOCOL_ERROR, Channel); - -handle_in(Packet = ?PUBLISH_PACKET(_QoS), Channel) -> - case emqx_packet:check(Packet) of - ok -> process_publish(Packet, Channel); - {error, ReasonCode} -> - handle_out(disconnect, ReasonCode, Channel) - end; - -handle_in(?PUBACK_PACKET(PacketId, _ReasonCode, Properties), Channel - = #channel{clientinfo = ClientInfo, session = Session}) -> - case emqx_session:puback(PacketId, Session) of - {ok, Msg, NSession} -> - ok = after_message_acked(ClientInfo, Msg, Properties), - {ok, Channel#channel{session = NSession}}; - {ok, Msg, Publishes, NSession} -> - ok = after_message_acked(ClientInfo, Msg, Properties), - handle_out(publish, Publishes, Channel#channel{session = NSession}); - {error, ?RC_PACKET_IDENTIFIER_IN_USE} -> - ?LOG(warning, "The PUBACK PacketId ~w is inuse.", [PacketId]), - ok = emqx_metrics:inc('packets.puback.inuse'), - {ok, Channel}; - {error, ?RC_PACKET_IDENTIFIER_NOT_FOUND} -> - ?LOG(warning, "The PUBACK PacketId ~w is not found.", [PacketId]), - ok = emqx_metrics:inc('packets.puback.missed'), - {ok, Channel} - end; - -handle_in(?PUBREC_PACKET(PacketId, _ReasonCode, Properties), Channel - = #channel{clientinfo = ClientInfo, session = Session}) -> - case emqx_session:pubrec(PacketId, Session) of - {ok, Msg, NSession} -> - ok = after_message_acked(ClientInfo, Msg, Properties), - NChannel = Channel#channel{session = NSession}, - handle_out(pubrel, {PacketId, ?RC_SUCCESS}, NChannel); - {error, RC = ?RC_PACKET_IDENTIFIER_IN_USE} -> - ?LOG(warning, "The PUBREC PacketId ~w is inuse.", [PacketId]), - ok = emqx_metrics:inc('packets.pubrec.inuse'), - handle_out(pubrel, {PacketId, RC}, Channel); - {error, RC = ?RC_PACKET_IDENTIFIER_NOT_FOUND} -> - ?LOG(warning, "The PUBREC ~w is not found.", [PacketId]), - ok = emqx_metrics:inc('packets.pubrec.missed'), - handle_out(pubrel, {PacketId, RC}, Channel) - end; - -handle_in(?PUBREL_PACKET(PacketId, _ReasonCode), Channel = #channel{session = Session}) -> - case emqx_session:pubrel(PacketId, Session) of - {ok, NSession} -> - NChannel = Channel#channel{session = NSession}, - handle_out(pubcomp, {PacketId, ?RC_SUCCESS}, NChannel); - {error, RC = ?RC_PACKET_IDENTIFIER_NOT_FOUND} -> - ?LOG(warning, "The PUBREL PacketId ~w is not found.", [PacketId]), - ok = emqx_metrics:inc('packets.pubrel.missed'), - handle_out(pubcomp, {PacketId, RC}, Channel) - end; - -handle_in(?PUBCOMP_PACKET(PacketId, _ReasonCode), Channel = #channel{session = Session}) -> - case emqx_session:pubcomp(PacketId, Session) of - {ok, NSession} -> - {ok, Channel#channel{session = NSession}}; - {ok, Publishes, NSession} -> - handle_out(publish, Publishes, Channel#channel{session = NSession}); - {error, ?RC_PACKET_IDENTIFIER_IN_USE} -> - ok = emqx_metrics:inc('packets.pubcomp.inuse'), - {ok, Channel}; - {error, ?RC_PACKET_IDENTIFIER_NOT_FOUND} -> - ?LOG(warning, "The PUBCOMP PacketId ~w is not found", [PacketId]), - ok = emqx_metrics:inc('packets.pubcomp.missed'), - {ok, Channel} - end; - -handle_in(Packet = ?SUBSCRIBE_PACKET(PacketId, Properties, TopicFilters), - Channel = #channel{clientinfo = ClientInfo = #{zone := Zone}}) -> - case emqx_packet:check(Packet) of - ok -> TopicFilters1 = parse_topic_filters(TopicFilters), - TopicFilters2 = put_subid_in_subopts(Properties, TopicFilters1), - TopicFilters3 = run_hooks('client.subscribe', - [ClientInfo, Properties], - TopicFilters2 - ), - {ReasonCodes, NChannel} = process_subscribe(TopicFilters3, Properties, Channel), - case emqx_zone:get_env(Zone, acl_deny_action, ignore) =:= disconnect andalso - lists:any(fun(ReasonCode) -> - ReasonCode =:= ?RC_NOT_AUTHORIZED - end, ReasonCodes) of - true -> - handle_out(disconnect, ?RC_NOT_AUTHORIZED, NChannel); - false -> - handle_out(suback, {PacketId, ReasonCodes}, NChannel) - end; - {error, ReasonCode} -> - handle_out(disconnect, ReasonCode, Channel) - end; - -handle_in(Packet = ?UNSUBSCRIBE_PACKET(PacketId, Properties, TopicFilters), - Channel = #channel{clientinfo = ClientInfo}) -> - case emqx_packet:check(Packet) of - ok -> TopicFilters1 = run_hooks('client.unsubscribe', - [ClientInfo, Properties], - parse_topic_filters(TopicFilters) - ), - {ReasonCodes, NChannel} = process_unsubscribe(TopicFilters1, Properties, Channel), - handle_out(unsuback, {PacketId, ReasonCodes}, NChannel); - {error, ReasonCode} -> - handle_out(disconnect, ReasonCode, Channel) - end; - -handle_in(?PACKET(?PINGREQ), Channel) -> - {ok, ?PACKET(?PINGRESP), Channel}; - -handle_in(?DISCONNECT_PACKET(ReasonCode, Properties), Channel = #channel{conninfo = ConnInfo}) -> - NChannel = maybe_clean_will_msg(ReasonCode, Channel#channel{conninfo = ConnInfo#{disconn_props => Properties}}), - process_disconnect(ReasonCode, Properties, NChannel); - -handle_in(?AUTH_PACKET(), Channel) -> - handle_out(disconnect, ?RC_IMPLEMENTATION_SPECIFIC_ERROR, Channel); - -handle_in({frame_error, Reason}, Channel = #channel{conn_state = idle}) -> - shutdown(Reason, Channel); - -handle_in({frame_error, frame_too_large}, Channel = #channel{conn_state = connecting}) -> - shutdown(frame_too_large, ?CONNACK_PACKET(?RC_PACKET_TOO_LARGE), Channel); -handle_in({frame_error, Reason}, Channel = #channel{conn_state = connecting}) -> - shutdown(Reason, ?CONNACK_PACKET(?RC_MALFORMED_PACKET), Channel); - -handle_in({frame_error, frame_too_large}, Channel = #channel{conn_state = connected}) -> - handle_out(disconnect, {?RC_PACKET_TOO_LARGE, frame_too_large}, Channel); -handle_in({frame_error, Reason}, Channel = #channel{conn_state = connected}) -> - handle_out(disconnect, {?RC_MALFORMED_PACKET, Reason}, Channel); - -handle_in({frame_error, Reason}, Channel = #channel{conn_state = disconnected}) -> - ?LOG(error, "Unexpected frame error: ~p", [Reason]), - {ok, Channel}; - -handle_in(Packet, Channel) -> - ?LOG(error, "Unexpected incoming: ~p", [Packet]), - handle_out(disconnect, ?RC_PROTOCOL_ERROR, Channel). - -%%-------------------------------------------------------------------- -%% Process Connect -%%-------------------------------------------------------------------- - -process_connect(AckProps, Channel = #channel{conninfo = #{clean_start := CleanStart} = ConnInfo, clientinfo = ClientInfo}) -> - case emqx_cm:open_session(CleanStart, ClientInfo, ConnInfo) of - {ok, #{session := Session, present := false}} -> - NChannel = Channel#channel{session = Session}, - handle_out(connack, {?RC_SUCCESS, sp(false), AckProps}, NChannel); - {ok, #{session := Session, present := true, pendings := Pendings}} -> - Pendings1 = lists:usort(lists:append(Pendings, emqx_misc:drain_deliver())), - NChannel = Channel#channel{session = Session, - resuming = true, - pendings = Pendings1 - }, - handle_out(connack, {?RC_SUCCESS, sp(true), AckProps}, NChannel); - {error, client_id_unavailable} -> - handle_out(connack, ?RC_CLIENT_IDENTIFIER_NOT_VALID, Channel); - {error, Reason} -> - ?LOG(error, "Failed to open session due to ~p", [Reason]), - handle_out(connack, ?RC_UNSPECIFIED_ERROR, Channel) - end. - -%%-------------------------------------------------------------------- -%% Process Publish -%%-------------------------------------------------------------------- - -process_publish(Packet = ?PUBLISH_PACKET(QoS, Topic, PacketId), - Channel = #channel{clientinfo = #{zone := Zone}}) -> - case pipeline([fun process_alias/2, - fun check_pub_alias/2, - fun check_pub_acl/2, - fun check_pub_caps/2 - ], Packet, Channel) of - {ok, NPacket, NChannel} -> - Msg = packet_to_message(NPacket, NChannel), - do_publish(PacketId, Msg, NChannel); - {error, ReasonCode, NChannel} when ReasonCode =:= ?RC_NOT_AUTHORIZED -> - ?LOG(warning, "Cannot publish message to ~s due to ~s.", - [Topic, emqx_reason_codes:text(ReasonCode)]), - case emqx_zone:get_env(Zone, acl_deny_action, ignore) of - ignore -> - case QoS of - ?QOS_0 -> {ok, NChannel}; - _ -> - handle_out(puback, {PacketId, ReasonCode}, NChannel) - end; - disconnect -> - handle_out(disconnect, ReasonCode, NChannel) - end; - {error, ReasonCode, NChannel} -> - ?LOG(warning, "Cannot publish message to ~s due to ~s.", - [Topic, emqx_reason_codes:text(ReasonCode)]), - handle_out(disconnect, ReasonCode, NChannel) - end. - -packet_to_message(Packet, #channel{ - conninfo = #{proto_ver := ProtoVer}, - clientinfo = #{ - protocol := Protocol, - clientid := ClientId, - username := Username, - peerhost := PeerHost, - mountpoint := MountPoint - } - }) -> - emqx_mountpoint:mount(MountPoint, - emqx_packet:to_message( - Packet, ClientId, - #{proto_ver => ProtoVer, - protocol => Protocol, - username => Username, - peerhost => PeerHost})). - -do_publish(_PacketId, Msg = #message{qos = ?QOS_0}, Channel) -> - _ = emqx_broker:publish(Msg), - {ok, Channel}; - -do_publish(PacketId, Msg = #message{qos = ?QOS_1}, Channel) -> - Results = emqx_broker:publish(Msg), - RC = puback_reason_code(Results), - handle_out(puback, {PacketId, RC}, Channel); - -do_publish(PacketId, Msg = #message{qos = ?QOS_2}, - Channel = #channel{session = Session}) -> - case emqx_session:publish(PacketId, Msg, Session) of - {ok, Results, NSession} -> - RC = puback_reason_code(Results), - NChannel = Channel#channel{session = NSession}, - NChannel1 = ensure_timer(await_timer, NChannel), - handle_out(pubrec, {PacketId, RC}, NChannel1); - {error, RC = ?RC_PACKET_IDENTIFIER_IN_USE} -> - ok = emqx_metrics:inc('packets.publish.inuse'), - handle_out(pubrec, {PacketId, RC}, Channel); - {error, RC = ?RC_RECEIVE_MAXIMUM_EXCEEDED} -> - ?LOG(warning, "Dropped the qos2 packet ~w " - "due to awaiting_rel is full.", [PacketId]), - ok = emqx_metrics:inc('packets.publish.dropped'), - handle_out(pubrec, {PacketId, RC}, Channel) - end. - --compile({inline, [puback_reason_code/1]}). -puback_reason_code([]) -> ?RC_NO_MATCHING_SUBSCRIBERS; -puback_reason_code([_|_]) -> ?RC_SUCCESS. - --compile({inline, [after_message_acked/3]}). -after_message_acked(ClientInfo, Msg, PubAckProps) -> - ok = emqx_metrics:inc('messages.acked'), - emqx_hooks:run('message.acked', [ClientInfo, - emqx_message:set_header(puback_props, PubAckProps, Msg)]). - -%%-------------------------------------------------------------------- -%% Process Subscribe -%%-------------------------------------------------------------------- - --compile({inline, [process_subscribe/3]}). -process_subscribe(TopicFilters, SubProps, Channel) -> - process_subscribe(TopicFilters, SubProps, Channel, []). - -process_subscribe([], _SubProps, Channel, Acc) -> - {lists:reverse(Acc), Channel}; - -process_subscribe([{TopicFilter, SubOpts}|More], SubProps, Channel, Acc) -> - {RC, NChannel} = do_subscribe(TopicFilter, SubOpts#{sub_props => SubProps}, Channel), - process_subscribe(More, SubProps, NChannel, [RC|Acc]). - -do_subscribe(TopicFilter, SubOpts = #{qos := QoS}, Channel = - #channel{clientinfo = ClientInfo = #{mountpoint := MountPoint}, - session = Session}) -> - case check_subscribe(TopicFilter, SubOpts, Channel) of - ok -> TopicFilter1 = emqx_mountpoint:mount(MountPoint, TopicFilter), - SubOpts1 = enrich_subopts(maps:merge(?DEFAULT_SUBOPTS, SubOpts), Channel), - case emqx_session:subscribe(ClientInfo, TopicFilter1, SubOpts1, Session) of - {ok, NSession} -> - {QoS, Channel#channel{session = NSession}}; - {error, RC} -> {RC, Channel} - end; - {error, RC} -> {RC, Channel} - end. - --compile({inline, [process_force_subscribe/2]}). -process_force_subscribe(Subscriptions, Channel = - #channel{clientinfo = ClientInfo = #{mountpoint := MountPoint}, - session = Session}) -> - lists:foldl(fun({TopicFilter, SubOpts = #{qos := QoS}}, {ReasonCodes, ChannelAcc}) -> - NTopicFilter = emqx_mountpoint:mount(MountPoint, TopicFilter), - NSubOpts = enrich_subopts(maps:merge(?DEFAULT_SUBOPTS, SubOpts), ChannelAcc), - case emqx_session:subscribe(ClientInfo, NTopicFilter, NSubOpts, Session) of - {ok, NSession} -> - {ReasonCodes ++ [QoS], ChannelAcc#channel{session = NSession}}; - {error, ReasonCode} -> - {ReasonCodes ++ [ReasonCode], ChannelAcc} - end - end, {[], Channel}, Subscriptions). - -%%-------------------------------------------------------------------- -%% Process Unsubscribe -%%-------------------------------------------------------------------- - --compile({inline, [process_unsubscribe/3]}). -process_unsubscribe(TopicFilters, UnSubProps, Channel) -> - process_unsubscribe(TopicFilters, UnSubProps, Channel, []). - -process_unsubscribe([], _UnSubProps, Channel, Acc) -> - {lists:reverse(Acc), Channel}; - -process_unsubscribe([{TopicFilter, SubOpts}|More], UnSubProps, Channel, Acc) -> - {RC, NChannel} = do_unsubscribe(TopicFilter, SubOpts#{unsub_props => UnSubProps}, Channel), - process_unsubscribe(More, UnSubProps, NChannel, [RC|Acc]). - -do_unsubscribe(TopicFilter, SubOpts, Channel = - #channel{clientinfo = ClientInfo = #{mountpoint := MountPoint}, - session = Session}) -> - TopicFilter1 = emqx_mountpoint:mount(MountPoint, TopicFilter), - case emqx_session:unsubscribe(ClientInfo, TopicFilter1, SubOpts, Session) of - {ok, NSession} -> - {?RC_SUCCESS, Channel#channel{session = NSession}}; - {error, RC} -> {RC, Channel} - end. - --compile({inline, [process_force_unsubscribe/2]}). -process_force_unsubscribe(Subscriptions, Channel = - #channel{clientinfo = ClientInfo = #{mountpoint := MountPoint}, - session = Session}) -> - lists:foldl(fun({TopicFilter, SubOpts}, {ReasonCodes, ChannelAcc}) -> - NTopicFilter = emqx_mountpoint:mount(MountPoint, TopicFilter), - case emqx_session:unsubscribe(ClientInfo, NTopicFilter, SubOpts, Session) of - {ok, NSession} -> - {ReasonCodes ++ [?RC_SUCCESS], ChannelAcc#channel{session = NSession}}; - {error, ReasonCode} -> - {ReasonCodes ++ [ReasonCode], ChannelAcc} - end - end, {[], Channel}, Subscriptions). - -%%-------------------------------------------------------------------- -%% Process Disconnect -%%-------------------------------------------------------------------- - -%% MQTT-v5.0: 3.14.4 DISCONNECT Actions -maybe_clean_will_msg(?RC_SUCCESS, Channel) -> - Channel#channel{will_msg = undefined}; -maybe_clean_will_msg(_ReasonCode, Channel) -> - Channel. - -%% MQTT-v5.0: 3.14.2.2.2 Session Expiry Interval -process_disconnect(_ReasonCode, #{'Session-Expiry-Interval' := Interval}, - Channel = #channel{conninfo = #{expiry_interval := 0}}) - when Interval > 0 -> - handle_out(disconnect, ?RC_PROTOCOL_ERROR, Channel); - -process_disconnect(ReasonCode, Properties, Channel) -> - NChannel = maybe_update_expiry_interval(Properties, Channel), - {ok, {close, disconnect_reason(ReasonCode)}, NChannel}. - -maybe_update_expiry_interval(#{'Session-Expiry-Interval' := Interval}, - Channel = #channel{conninfo = ConnInfo}) -> - Channel#channel{conninfo = ConnInfo#{expiry_interval => Interval}}; -maybe_update_expiry_interval(_Properties, Channel) -> Channel. - -%%-------------------------------------------------------------------- -%% Handle Delivers from broker to client -%%-------------------------------------------------------------------- - --spec(handle_deliver(list(emqx_types:deliver()), channel()) - -> {ok, channel()} | {ok, replies(), channel()}). -handle_deliver(Delivers, Channel = #channel{conn_state = disconnected, - session = Session}) -> - NSession = emqx_session:enqueue(maybe_nack(Delivers), Session), - {ok, Channel#channel{session = NSession}}; - -handle_deliver(Delivers, Channel = #channel{takeover = true, - pendings = Pendings}) -> - NPendings = lists:append(Pendings, maybe_nack(Delivers)), - {ok, Channel#channel{pendings = NPendings}}; - -handle_deliver(Delivers, Channel = #channel{session = Session}) -> - case emqx_session:deliver(Delivers, Session) of - {ok, Publishes, NSession} -> - NChannel = Channel#channel{session = NSession}, - handle_out(publish, Publishes, ensure_timer(retry_timer, NChannel)); - {ok, NSession} -> - {ok, Channel#channel{session = NSession}} - end. - -%% Nack delivers from shared subscription -maybe_nack(Delivers) -> - lists:filter(fun not_nacked/1, Delivers). - -not_nacked({deliver, _Topic, Msg}) -> - not (emqx_shared_sub:is_ack_required(Msg) - andalso (ok == emqx_shared_sub:nack_no_connection(Msg))). - -%%-------------------------------------------------------------------- -%% Handle outgoing packet -%%-------------------------------------------------------------------- - --spec(handle_out(atom(), term(), channel()) - -> {ok, channel()} - | {ok, replies(), channel()} - | {shutdown, Reason :: term(), channel()} - | {shutdown, Reason :: term(), replies(), channel()}). -handle_out(connack, {?RC_SUCCESS, SP, Props}, Channel = #channel{conninfo = ConnInfo}) -> - AckProps = run_fold([fun enrich_connack_caps/2, - fun enrich_server_keepalive/2, - fun enrich_response_information/2, - fun enrich_assigned_clientid/2 - ], Props, Channel), - NAckProps = run_hooks('client.connack', [ConnInfo, emqx_reason_codes:name(?RC_SUCCESS)], AckProps), - - return_connack(?CONNACK_PACKET(?RC_SUCCESS, SP, NAckProps), - ensure_keepalive(NAckProps, Channel)); - -handle_out(connack, ReasonCode, Channel = #channel{conninfo = ConnInfo}) -> - Reason = emqx_reason_codes:name(ReasonCode), - AckProps = run_hooks('client.connack', [ConnInfo, Reason], emqx_mqtt_props:new()), - AckPacket = ?CONNACK_PACKET(case maps:get(proto_ver, ConnInfo) of - ?MQTT_PROTO_V5 -> ReasonCode; - _ -> emqx_reason_codes:compat(connack, ReasonCode) - end, sp(false), AckProps), - shutdown(Reason, AckPacket, Channel); - -%% Optimize? -handle_out(publish, [], Channel) -> - {ok, Channel}; - -handle_out(publish, Publishes, Channel) -> - {Packets, NChannel} = do_deliver(Publishes, Channel), - {ok, {outgoing, Packets}, NChannel}; - -handle_out(puback, {PacketId, ReasonCode}, Channel) -> - {ok, ?PUBACK_PACKET(PacketId, ReasonCode), Channel}; - -handle_out(pubrec, {PacketId, ReasonCode}, Channel) -> - {ok, ?PUBREC_PACKET(PacketId, ReasonCode), Channel}; - -handle_out(pubrel, {PacketId, ReasonCode}, Channel) -> - {ok, ?PUBREL_PACKET(PacketId, ReasonCode), Channel}; - -handle_out(pubcomp, {PacketId, ReasonCode}, Channel) -> - {ok, ?PUBCOMP_PACKET(PacketId, ReasonCode), Channel}; - -handle_out(suback, {PacketId, ReasonCodes}, Channel = ?IS_MQTT_V5) -> - return_suback(?SUBACK_PACKET(PacketId, ReasonCodes), Channel); - -handle_out(suback, {PacketId, ReasonCodes}, Channel) -> - ReasonCodes1 = [emqx_reason_codes:compat(suback, RC) || RC <- ReasonCodes], - return_suback(?SUBACK_PACKET(PacketId, ReasonCodes1), Channel); - -handle_out(unsuback, {PacketId, ReasonCodes}, Channel = ?IS_MQTT_V5) -> - return_unsuback(?UNSUBACK_PACKET(PacketId, ReasonCodes), Channel); - -handle_out(unsuback, {PacketId, _ReasonCodes}, Channel) -> - return_unsuback(?UNSUBACK_PACKET(PacketId), Channel); - -handle_out(disconnect, ReasonCode, Channel) when is_integer(ReasonCode) -> - ReasonName = disconnect_reason(ReasonCode), - handle_out(disconnect, {ReasonCode, ReasonName}, Channel); - -handle_out(disconnect, {ReasonCode, ReasonName}, Channel = ?IS_MQTT_V5) -> - Packet = ?DISCONNECT_PACKET(ReasonCode), - {ok, [{outgoing, Packet}, {close, ReasonName}], Channel}; - -handle_out(disconnect, {_ReasonCode, ReasonName}, Channel) -> - {ok, {close, ReasonName}, Channel}; - -handle_out(auth, {ReasonCode, Properties}, Channel) -> - {ok, ?AUTH_PACKET(ReasonCode, Properties), Channel}; - -handle_out(Type, Data, Channel) -> - ?LOG(error, "Unexpected outgoing: ~s, ~p", [Type, Data]), - {ok, Channel}. - -%%-------------------------------------------------------------------- -%% Return ConnAck -%%-------------------------------------------------------------------- - -return_connack(AckPacket, Channel) -> - Replies = [{event, connected}, {connack, AckPacket}], - case maybe_resume_session(Channel) of - ignore -> {ok, Replies, Channel}; - {ok, Publishes, NSession} -> - NChannel = Channel#channel{session = NSession, - resuming = false, - pendings = [] - }, - {Packets, NChannel1} = do_deliver(Publishes, NChannel), - Outgoing = [{outgoing, Packets} || length(Packets) > 0], - {ok, Replies ++ Outgoing, NChannel1} - end. - -%%-------------------------------------------------------------------- -%% Deliver publish: broker -> client -%%-------------------------------------------------------------------- - -%% return list(emqx_types:packet()) -do_deliver({pubrel, PacketId}, Channel) -> - {[?PUBREL_PACKET(PacketId, ?RC_SUCCESS)], Channel}; - -do_deliver({PacketId, Msg}, Channel = #channel{clientinfo = ClientInfo = - #{mountpoint := MountPoint}}) -> - case ignore_local(Msg, ClientInfo) of - true -> - ok = emqx_metrics:inc('delivery.dropped'), - ok = emqx_metrics:inc('delivery.dropped.no_local'), - {[], Channel}; - false -> - ok = emqx_metrics:inc('messages.delivered'), - Msg1 = emqx_hooks:run_fold('message.delivered', - [ClientInfo], - emqx_message:update_expiry(Msg) - ), - Msg2 = emqx_mountpoint:unmount(MountPoint, Msg1), - Packet = emqx_message:to_packet(PacketId, Msg2), - {NPacket, NChannel} = packing_alias(Packet, Channel), - {[NPacket], NChannel} - end; - -do_deliver([Publish], Channel) -> - do_deliver(Publish, Channel); - -do_deliver(Publishes, Channel) when is_list(Publishes) -> - {Packets, NChannel} = - lists:foldl(fun(Publish, {Acc, Chann}) -> - {Packets, NChann} = do_deliver(Publish, Chann), - {Packets ++ Acc, NChann} - end, {[], Channel}, Publishes), - {lists:reverse(Packets), NChannel}. - -ignore_local(#message{flags = #{nl := true}, from = ClientId}, - #{clientid := ClientId}) -> - true; -ignore_local(_Msg, _ClientInfo) -> false. - -%%-------------------------------------------------------------------- -%% Handle out suback -%%-------------------------------------------------------------------- - -return_suback(Packet, Channel) -> - {ok, [{outgoing, Packet}, {event, updated}], Channel}. - -return_unsuback(Packet, Channel) -> - {ok, [{outgoing, Packet}, {event, updated}], Channel}. - -%%-------------------------------------------------------------------- -%% Handle call -%%-------------------------------------------------------------------- - --spec(handle_call(Req :: term(), channel()) - -> {reply, Reply :: term(), channel()} - | {shutdown, Reason :: term(), Reply :: term(), channel()} - | {shutdown, Reason :: term(), Reply :: term(), emqx_types:packet(), channel()}). -handle_call(kick, Channel) -> - Channel1 = ensure_disconnected(kicked, Channel), - disconnect_and_shutdown(kicked, ok, Channel1); - -handle_call(discard, Channel) -> - disconnect_and_shutdown(discarded, ok, Channel); - -%% Session Takeover -handle_call({takeover, 'begin'}, Channel = #channel{session = Session}) -> - reply(Session, Channel#channel{takeover = true}); - -handle_call({takeover, 'end'}, Channel = #channel{session = Session, - pendings = Pendings}) -> - ok = emqx_session:takeover(Session), - %% TODO: Should not drain deliver here (side effect) - Delivers = emqx_misc:drain_deliver(), - AllPendings = lists:append(Delivers, Pendings), - disconnect_and_shutdown(takeovered, AllPendings, Channel); - -handle_call(list_acl_cache, Channel) -> - {reply, emqx_acl_cache:list_acl_cache(), Channel}; - -handle_call(Req, Channel) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - reply(ignored, Channel). - -%%-------------------------------------------------------------------- -%% Handle Info -%%-------------------------------------------------------------------- - --spec(handle_info(Info :: term(), channel()) - -> ok | {ok, channel()} | {shutdown, Reason :: term(), channel()}). -handle_info({subscribe, TopicFilters}, Channel = #channel{clientinfo = ClientInfo}) -> - TopicFilters1 = run_hooks('client.subscribe', - [ClientInfo, #{'Internal' => true}], - parse_topic_filters(TopicFilters) - ), - {_ReasonCodes, NChannel} = process_subscribe(TopicFilters1, #{}, Channel), - {ok, NChannel}; - -handle_info({force_subscribe, TopicFilters}, Channel) -> - {_ReasonCodes, NChannel} = process_force_subscribe(parse_topic_filters(TopicFilters), Channel), - {ok, NChannel}; - -handle_info({unsubscribe, TopicFilters}, Channel = #channel{clientinfo = ClientInfo}) -> - TopicFilters1 = run_hooks('client.unsubscribe', - [ClientInfo, #{'Internal' => true}], - parse_topic_filters(TopicFilters) - ), - {_ReasonCodes, NChannel} = process_unsubscribe(TopicFilters1, #{}, Channel), - {ok, NChannel}; - -handle_info({force_unsubscribe, TopicFilters}, Channel) -> - {_ReasonCodes, NChannel} = process_force_unsubscribe(parse_topic_filters(TopicFilters), Channel), - {ok, NChannel}; - -handle_info({sock_closed, Reason}, Channel = #channel{conn_state = idle}) -> - shutdown(Reason, Channel); - -handle_info({sock_closed, Reason}, Channel = #channel{conn_state = connecting}) -> - shutdown(Reason, Channel); - -handle_info({sock_closed, Reason}, Channel = - #channel{conn_state = connected, - clientinfo = ClientInfo = #{zone := Zone}}) -> - emqx_zone:enable_flapping_detect(Zone) - andalso emqx_flapping:detect(ClientInfo), - Channel1 = ensure_disconnected(Reason, mabye_publish_will_msg(Channel)), - case maybe_shutdown(Reason, Channel1) of - {ok, Channel2} -> {ok, {event, disconnected}, Channel2}; - Shutdown -> Shutdown - end; - -handle_info({sock_closed, Reason}, Channel = #channel{conn_state = disconnected}) -> - ?LOG(error, "Unexpected sock_closed: ~p", [Reason]), - {ok, Channel}; - -handle_info(clean_acl_cache, Channel) -> - ok = emqx_acl_cache:empty_acl_cache(), - {ok, Channel}; - -handle_info(Info, Channel) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {ok, Channel}. - -%%-------------------------------------------------------------------- -%% Handle timeout -%%-------------------------------------------------------------------- - --spec(handle_timeout(reference(), Msg :: term(), channel()) - -> {ok, channel()} - | {ok, replies(), channel()} - | {shutdown, Reason :: term(), channel()}). -handle_timeout(_TRef, {keepalive, _StatVal}, - Channel = #channel{keepalive = undefined}) -> - {ok, Channel}; -handle_timeout(_TRef, {keepalive, _StatVal}, - Channel = #channel{conn_state = disconnected}) -> - {ok, Channel}; -handle_timeout(_TRef, {keepalive, StatVal}, - Channel = #channel{keepalive = Keepalive}) -> - case emqx_keepalive:check(StatVal, Keepalive) of - {ok, NKeepalive} -> - NChannel = Channel#channel{keepalive = NKeepalive}, - {ok, reset_timer(alive_timer, NChannel)}; - {error, timeout} -> - handle_out(disconnect, ?RC_KEEP_ALIVE_TIMEOUT, Channel) - end; - -handle_timeout(_TRef, retry_delivery, - Channel = #channel{conn_state = disconnected}) -> - {ok, Channel}; -handle_timeout(_TRef, retry_delivery, - Channel = #channel{session = Session}) -> - case emqx_session:retry(Session) of - {ok, NSession} -> - {ok, clean_timer(retry_timer, Channel#channel{session = NSession})}; - {ok, Publishes, Timeout, NSession} -> - NChannel = Channel#channel{session = NSession}, - handle_out(publish, Publishes, reset_timer(retry_timer, Timeout, NChannel)) - end; - -handle_timeout(_TRef, expire_awaiting_rel, - Channel = #channel{conn_state = disconnected}) -> - {ok, Channel}; -handle_timeout(_TRef, expire_awaiting_rel, - Channel = #channel{session = Session}) -> - case emqx_session:expire(awaiting_rel, Session) of - {ok, NSession} -> - {ok, clean_timer(await_timer, Channel#channel{session = NSession})}; - {ok, Timeout, NSession} -> - {ok, reset_timer(await_timer, Timeout, Channel#channel{session = NSession})} - end; - -handle_timeout(_TRef, expire_session, Channel) -> - shutdown(expired, Channel); - -handle_timeout(_TRef, will_message, Channel = #channel{will_msg = WillMsg}) -> - (WillMsg =/= undefined) andalso publish_will_msg(WillMsg), - {ok, clean_timer(will_timer, Channel#channel{will_msg = undefined})}; - -handle_timeout(_TRef, Msg, Channel) -> - ?LOG(error, "Unexpected timeout: ~p~n", [Msg]), - {ok, Channel}. - -%%-------------------------------------------------------------------- -%% Ensure timers -%%-------------------------------------------------------------------- - -ensure_timer([Name], Channel) -> - ensure_timer(Name, Channel); -ensure_timer([Name | Rest], Channel) -> - ensure_timer(Rest, ensure_timer(Name, Channel)); - -ensure_timer(Name, Channel = #channel{timers = Timers}) -> - TRef = maps:get(Name, Timers, undefined), - Time = interval(Name, Channel), - case TRef == undefined andalso Time > 0 of - true -> ensure_timer(Name, Time, Channel); - false -> Channel %% Timer disabled or exists - end. - -ensure_timer(Name, Time, Channel = #channel{timers = Timers}) -> - Msg = maps:get(Name, ?TIMER_TABLE), - TRef = emqx_misc:start_timer(Time, Msg), - Channel#channel{timers = Timers#{Name => TRef}}. - -reset_timer(Name, Channel) -> - ensure_timer(Name, clean_timer(Name, Channel)). - -reset_timer(Name, Time, Channel) -> - ensure_timer(Name, Time, clean_timer(Name, Channel)). - -clean_timer(Name, Channel = #channel{timers = Timers}) -> - Channel#channel{timers = maps:remove(Name, Timers)}. - -interval(alive_timer, #channel{keepalive = KeepAlive}) -> - emqx_keepalive:info(interval, KeepAlive); -interval(retry_timer, #channel{session = Session}) -> - timer:seconds(emqx_session:info(retry_interval, Session)); -interval(await_timer, #channel{session = Session}) -> - timer:seconds(emqx_session:info(await_rel_timeout, Session)); -interval(expire_timer, #channel{conninfo = ConnInfo}) -> - timer:seconds(maps:get(expiry_interval, ConnInfo)); -interval(will_timer, #channel{will_msg = WillMsg}) -> - timer:seconds(will_delay_interval(WillMsg)). - -%%-------------------------------------------------------------------- -%% Terminate -%%-------------------------------------------------------------------- - --spec(terminate(any(), channel()) -> ok). -terminate(_, #channel{conn_state = idle}) -> ok; -terminate(normal, Channel) -> - run_terminate_hook(normal, Channel); -terminate({shutdown, Reason}, Channel) - when Reason =:= kicked; Reason =:= discarded; Reason =:= takeovered -> - run_terminate_hook(Reason, Channel); -terminate(Reason, Channel = #channel{will_msg = WillMsg}) -> - (WillMsg =/= undefined) andalso publish_will_msg(WillMsg), - run_terminate_hook(Reason, Channel). - -run_terminate_hook(_Reason, #channel{session = undefined}) -> ok; -run_terminate_hook(Reason, #channel{clientinfo = ClientInfo, session = Session}) -> - emqx_session:terminate(ClientInfo, Reason, Session). - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -%%-------------------------------------------------------------------- -%% Enrich MQTT Connect Info - -enrich_conninfo(ConnPkt = #mqtt_packet_connect{ - proto_name = ProtoName, - proto_ver = ProtoVer, - clean_start = CleanStart, - keepalive = Keepalive, - properties = ConnProps, - clientid = ClientId, - username = Username - }, - Channel = #channel{conninfo = ConnInfo, - clientinfo = #{zone := Zone} - }) -> - ExpiryInterval = expiry_interval(Zone, ConnPkt), - ReceiveMaximum = receive_maximum(Zone, ConnProps), - NConnInfo = ConnInfo#{proto_name => ProtoName, - proto_ver => ProtoVer, - clean_start => CleanStart, - keepalive => Keepalive, - clientid => ClientId, - username => Username, - conn_props => ConnProps, - expiry_interval => ExpiryInterval, - receive_maximum => ReceiveMaximum - }, - {ok, Channel#channel{conninfo = NConnInfo}}. - -%% If the Session Expiry Interval is absent the value 0 is used. --compile({inline, [expiry_interval/2]}). -expiry_interval(_Zone, #mqtt_packet_connect{proto_ver = ?MQTT_PROTO_V5, - properties = ConnProps}) -> - emqx_mqtt_props:get('Session-Expiry-Interval', ConnProps, 0); -expiry_interval(Zone, #mqtt_packet_connect{clean_start = false}) -> - emqx_zone:session_expiry_interval(Zone); -expiry_interval(_Zone, #mqtt_packet_connect{clean_start = true}) -> - 0. - --compile({inline, [receive_maximum/2]}). -receive_maximum(Zone, ConnProps) -> - emqx_mqtt_props:get('Receive-Maximum', ConnProps, emqx_zone:max_inflight(Zone)). - -%%-------------------------------------------------------------------- -%% Run Connect Hooks - -run_conn_hooks(ConnPkt, Channel = #channel{conninfo = ConnInfo}) -> - ConnProps = emqx_packet:info(properties, ConnPkt), - case run_hooks('client.connect', [ConnInfo], ConnProps) of - Error = {error, _Reason} -> Error; - NConnProps -> {ok, emqx_packet:set_props(NConnProps, ConnPkt), Channel} - end. - -%%-------------------------------------------------------------------- -%% Check Connect Packet - -check_connect(ConnPkt, #channel{clientinfo = #{zone := Zone}}) -> - emqx_packet:check(ConnPkt, emqx_mqtt_caps:get_caps(Zone)). - -%%-------------------------------------------------------------------- -%% Enrich Client Info - -enrich_client(ConnPkt, Channel = #channel{clientinfo = ClientInfo}) -> - {ok, NConnPkt, NClientInfo} = pipeline([fun set_username/2, - fun set_bridge_mode/2, - fun maybe_username_as_clientid/2, - fun maybe_assign_clientid/2, - fun fix_mountpoint/2 - ], ConnPkt, ClientInfo), - {ok, NConnPkt, Channel#channel{clientinfo = NClientInfo}}. - -set_username(#mqtt_packet_connect{username = Username}, - ClientInfo = #{username := undefined}) -> - {ok, ClientInfo#{username => Username}}; -set_username(_ConnPkt, ClientInfo) -> {ok, ClientInfo}. - -set_bridge_mode(#mqtt_packet_connect{is_bridge = true}, ClientInfo) -> - {ok, ClientInfo#{is_bridge => true}}; -set_bridge_mode(_ConnPkt, _ClientInfo) -> ok. - -maybe_username_as_clientid(_ConnPkt, ClientInfo = #{username := undefined}) -> - {ok, ClientInfo}; -maybe_username_as_clientid(_ConnPkt, ClientInfo = #{zone := Zone, username := Username}) -> - case emqx_zone:use_username_as_clientid(Zone) of - true -> {ok, ClientInfo#{clientid => Username}}; - false -> ok - end. - -maybe_assign_clientid(_ConnPkt, ClientInfo = #{clientid := ClientId}) - when ClientId /= undefined -> - {ok, ClientInfo}; -maybe_assign_clientid(#mqtt_packet_connect{clientid = <<>>}, ClientInfo) -> - %% Generate a rand clientId - {ok, ClientInfo#{clientid => emqx_guid:to_base62(emqx_guid:gen())}}; -maybe_assign_clientid(#mqtt_packet_connect{clientid = ClientId}, ClientInfo) -> - {ok, ClientInfo#{clientid => ClientId}}. - -fix_mountpoint(_ConnPkt, #{mountpoint := undefined}) -> ok; -fix_mountpoint(_ConnPkt, ClientInfo = #{mountpoint := MountPoint}) -> - MountPoint1 = emqx_mountpoint:replvar(MountPoint, ClientInfo), - {ok, ClientInfo#{mountpoint := MountPoint1}}. - -%%-------------------------------------------------------------------- -%% Set log metadata - -set_log_meta(_ConnPkt, #channel{clientinfo = #{clientid := ClientId}}) -> - emqx_logger:set_metadata_clientid(ClientId). - -%%-------------------------------------------------------------------- -%% Check banned - -check_banned(_ConnPkt, #channel{clientinfo = ClientInfo = #{zone := Zone}}) -> - case emqx_zone:enable_ban(Zone) andalso emqx_banned:check(ClientInfo) of - true -> {error, ?RC_BANNED}; - false -> ok - end. - -%%-------------------------------------------------------------------- -%% Auth Connect - -auth_connect(#mqtt_packet_connect{clientid = ClientId, - username = Username, - password = Password - }, - #channel{clientinfo = ClientInfo} = Channel) -> - case emqx_access_control:authenticate(ClientInfo#{password => Password}) of - {ok, AuthResult} -> - is_anonymous(AuthResult) andalso - emqx_metrics:inc('client.auth.anonymous'), - NClientInfo = maps:merge(ClientInfo, AuthResult), - {ok, Channel#channel{clientinfo = NClientInfo}}; - {error, Reason} -> - ?LOG(warning, "Client ~s (Username: '~s') login failed for ~0p", - [ClientId, Username, Reason]), - {error, emqx_reason_codes:connack_error(Reason)} - end. - -is_anonymous(#{anonymous := true}) -> true; -is_anonymous(_AuthResult) -> false. - -%%-------------------------------------------------------------------- -%% Enhanced Authentication - -enhanced_auth(?CONNECT_PACKET(#mqtt_packet_connect{ - proto_ver = Protover, - properties = Properties - }), Channel) -> - case Protover of - ?MQTT_PROTO_V5 -> - AuthMethod = emqx_mqtt_props:get('Authentication-Method', Properties, undefined), - AuthData = emqx_mqtt_props:get('Authentication-Data', Properties, undefined), - do_enhanced_auth(AuthMethod, AuthData, Channel); - _ -> - {ok, #{}, Channel} - end; - -enhanced_auth(?AUTH_PACKET(_ReasonCode, Properties), Channel = #channel{conninfo = ConnInfo}) -> - AuthMethod = emqx_mqtt_props:get('Authentication-Method', emqx_mqtt_props:get(conn_props, ConnInfo, #{}), undefined), - NAuthMethod = emqx_mqtt_props:get('Authentication-Method', Properties, undefined), - AuthData = emqx_mqtt_props:get('Authentication-Data', Properties, undefined), - case NAuthMethod =:= undefined orelse NAuthMethod =/= AuthMethod of - true -> - {error, emqx_reason_codes:connack_error(bad_authentication_method), Channel}; - false -> - do_enhanced_auth(AuthMethod, AuthData, Channel) - end. - -do_enhanced_auth(undefined, undefined, Channel) -> - {ok, #{}, Channel}; -do_enhanced_auth(undefined, _AuthData, Channel) -> - {error, emqx_reason_codes:connack_error(not_authorized), Channel}; -do_enhanced_auth(_AuthMethod, undefined, Channel) -> - {error, emqx_reason_codes:connack_error(not_authorized), Channel}; -do_enhanced_auth(AuthMethod, AuthData, Channel = #channel{auth_cache = Cache}) -> - case run_hooks('client.enhanced_authenticate',[AuthMethod, AuthData], Cache) of - {ok, NAuthData, NCache} -> - NProperties = #{'Authentication-Method' => AuthMethod, 'Authentication-Data' => NAuthData}, - {ok, NProperties, Channel#channel{auth_cache = NCache}}; - {continue, NAuthData, NCache} -> - NProperties = #{'Authentication-Method' => AuthMethod, 'Authentication-Data' => NAuthData}, - {continue, NProperties, Channel#channel{auth_cache = NCache}}; - _ -> - {error, emqx_reason_codes:connack_error(not_authorized), Channel} - end. - -%%-------------------------------------------------------------------- -%% Process Topic Alias - -process_alias(Packet = #mqtt_packet{ - variable = #mqtt_packet_publish{topic_name = <<>>, - properties = #{'Topic-Alias' := AliasId} - } = Publish - }, - Channel = ?IS_MQTT_V5 = #channel{topic_aliases = TopicAliases}) -> - case find_alias(inbound, AliasId, TopicAliases) of - {ok, Topic} -> - NPublish = Publish#mqtt_packet_publish{topic_name = Topic}, - {ok, Packet#mqtt_packet{variable = NPublish}, Channel}; - false -> {error, ?RC_PROTOCOL_ERROR} - end; - -process_alias(#mqtt_packet{ - variable = #mqtt_packet_publish{topic_name = Topic, - properties = #{'Topic-Alias' := AliasId} - } - }, - Channel = ?IS_MQTT_V5 = #channel{topic_aliases = TopicAliases}) -> - NTopicAliases = save_alias(inbound, AliasId, Topic, TopicAliases), - {ok, Channel#channel{topic_aliases = NTopicAliases}}; - -process_alias(_Packet, Channel) -> {ok, Channel}. - -%%-------------------------------------------------------------------- -%% Packing Topic Alias - -packing_alias(Packet = #mqtt_packet{ - variable = #mqtt_packet_publish{topic_name = Topic} = Publish - }, - Channel = ?IS_MQTT_V5 = #channel{topic_aliases = TopicAliases, alias_maximum = Limits}) -> - case find_alias(outbound, Topic, TopicAliases) of - {ok, AliasId} -> - NPublish = Publish#mqtt_packet_publish{ - topic_name = <<>>, - properties = #{'Topic-Alias' => AliasId} - }, - {Packet#mqtt_packet{variable = NPublish}, Channel}; - error -> - #{outbound := Aliases} = TopicAliases, - AliasId = maps:size(Aliases) + 1, - case (Limits =:= undefined) orelse - (AliasId =< maps:get(outbound, Limits, 0)) of - true -> - NTopicAliases = save_alias(outbound, AliasId, Topic, TopicAliases), - NChannel = Channel#channel{topic_aliases = NTopicAliases}, - NPublish = Publish#mqtt_packet_publish{ - topic_name = Topic, - properties = #{'Topic-Alias' => AliasId} - }, - {Packet#mqtt_packet{variable = NPublish}, NChannel}; - false -> {Packet, Channel} - end - end; -packing_alias(Packet, Channel) -> {Packet, Channel}. - -%%-------------------------------------------------------------------- -%% Check Pub Alias - -check_pub_alias(#mqtt_packet{ - variable = #mqtt_packet_publish{ - properties = #{'Topic-Alias' := AliasId} - } - }, - #channel{alias_maximum = Limits}) -> - case (Limits =:= undefined) orelse - (AliasId =< maps:get(inbound, Limits, ?MAX_TOPIC_AlIAS)) of - true -> ok; - false -> {error, ?RC_TOPIC_ALIAS_INVALID} - end; -check_pub_alias(_Packet, _Channel) -> ok. - -%%-------------------------------------------------------------------- -%% Check Pub ACL - -check_pub_acl(#mqtt_packet{variable = #mqtt_packet_publish{topic_name = Topic}}, - #channel{clientinfo = ClientInfo}) -> - case is_acl_enabled(ClientInfo) andalso - emqx_access_control:check_acl(ClientInfo, publish, Topic) of - false -> ok; - allow -> ok; - deny -> {error, ?RC_NOT_AUTHORIZED} - end. - -%%-------------------------------------------------------------------- -%% Check Pub Caps - -check_pub_caps(#mqtt_packet{header = #mqtt_packet_header{qos = QoS, - retain = Retain}, - variable = #mqtt_packet_publish{topic_name = Topic} - }, - #channel{clientinfo = #{zone := Zone}}) -> - emqx_mqtt_caps:check_pub(Zone, #{qos => QoS, retain => Retain, topic => Topic}). - -%%-------------------------------------------------------------------- -%% Check Subscribe - -check_subscribe(TopicFilter, SubOpts, Channel) -> - case check_sub_acl(TopicFilter, Channel) of - allow -> check_sub_caps(TopicFilter, SubOpts, Channel); - deny -> {error, ?RC_NOT_AUTHORIZED} - end. - -%%-------------------------------------------------------------------- -%% Check Sub ACL - -check_sub_acl(TopicFilter, #channel{clientinfo = ClientInfo}) -> - case is_acl_enabled(ClientInfo) andalso - emqx_access_control:check_acl(ClientInfo, subscribe, TopicFilter) of - false -> allow; - Result -> Result - end. - -%%-------------------------------------------------------------------- -%% Check Sub Caps - -check_sub_caps(TopicFilter, SubOpts, #channel{clientinfo = #{zone := Zone}}) -> - emqx_mqtt_caps:check_sub(Zone, TopicFilter, SubOpts). - -%%-------------------------------------------------------------------- -%% Enrich SubId - -put_subid_in_subopts(#{'Subscription-Identifier' := SubId}, TopicFilters) -> - [{Topic, SubOpts#{subid => SubId}} || {Topic, SubOpts} <- TopicFilters]; -put_subid_in_subopts(_Properties, TopicFilters) -> TopicFilters. - -%%-------------------------------------------------------------------- -%% Enrich SubOpts - -enrich_subopts(SubOpts, _Channel = ?IS_MQTT_V5) -> - SubOpts; -enrich_subopts(SubOpts, #channel{clientinfo = #{zone := Zone, is_bridge := IsBridge}}) -> - NL = flag(emqx_zone:ignore_loop_deliver(Zone)), - SubOpts#{rap => flag(IsBridge), nl => NL}. - -%%-------------------------------------------------------------------- -%% Enrich ConnAck Caps - -enrich_connack_caps(AckProps, ?IS_MQTT_V5 = #channel{clientinfo = #{zone := Zone}}) -> - #{max_packet_size := MaxPktSize, - max_qos_allowed := MaxQoS, - retain_available := Retain, - max_topic_alias := MaxAlias, - shared_subscription := Shared, - wildcard_subscription := Wildcard - } = emqx_mqtt_caps:get_caps(Zone), - NAckProps = AckProps#{'Retain-Available' => flag(Retain), - 'Maximum-Packet-Size' => MaxPktSize, - 'Topic-Alias-Maximum' => MaxAlias, - 'Wildcard-Subscription-Available' => flag(Wildcard), - 'Subscription-Identifier-Available' => 1, - 'Shared-Subscription-Available' => flag(Shared) - }, - %% MQTT 5.0 - 3.2.2.3.4: - %% It is a Protocol Error to include Maximum QoS more than once, - %% or to have a value other than 0 or 1. If the Maximum QoS is absent, - %% the Client uses a Maximum QoS of 2. - case MaxQoS =:= 2 of - true -> NAckProps; - _ -> NAckProps#{'Maximum-QoS' => MaxQoS} - end; - -enrich_connack_caps(AckProps, _Channel) -> AckProps. - -%%-------------------------------------------------------------------- -%% Enrich server keepalive - -enrich_server_keepalive(AckProps, #channel{clientinfo = #{zone := Zone}}) -> - case emqx_zone:server_keepalive(Zone) of - undefined -> AckProps; - Keepalive -> AckProps#{'Server-Keep-Alive' => Keepalive} - end. - -%%-------------------------------------------------------------------- -%% Enrich response information - -enrich_response_information(AckProps, #channel{conninfo = #{conn_props := ConnProps}, - clientinfo = #{zone := Zone}}) -> - case emqx_mqtt_props:get('Request-Response-Information', ConnProps, 0) of - 0 -> AckProps; - 1 -> AckProps#{'Response-Information' => emqx_zone:response_information(Zone)} - end. - -%%-------------------------------------------------------------------- -%% Enrich Assigned ClientId - -enrich_assigned_clientid(AckProps, #channel{conninfo = ConnInfo, - clientinfo = #{clientid := ClientId}}) -> - case maps:get(clientid, ConnInfo) of - <<>> -> %% Original ClientId is null. - AckProps#{'Assigned-Client-Identifier' => ClientId}; - _Origin -> AckProps - end. - -%%-------------------------------------------------------------------- -%% Ensure connected - -ensure_connected(Channel = #channel{conninfo = ConnInfo, - clientinfo = ClientInfo}) -> - NConnInfo = ConnInfo#{connected_at => erlang:system_time(millisecond)}, - ok = run_hooks('client.connected', [ClientInfo, NConnInfo]), - Channel#channel{conninfo = NConnInfo, - conn_state = connected - }. - -%%-------------------------------------------------------------------- -%% Init Alias Maximum - -init_alias_maximum(#mqtt_packet_connect{proto_ver = ?MQTT_PROTO_V5, - properties = Properties}, - #{zone := Zone} = _ClientInfo) -> - #{outbound => emqx_mqtt_props:get('Topic-Alias-Maximum', Properties, 0), - inbound => emqx_mqtt_caps:get_caps(Zone, max_topic_alias, ?MAX_TOPIC_AlIAS) - }; -init_alias_maximum(_ConnPkt, _ClientInfo) -> undefined. - -%%-------------------------------------------------------------------- -%% Enrich Keepalive - -ensure_keepalive(#{'Server-Keep-Alive' := Interval}, Channel) -> - ensure_keepalive_timer(Interval, Channel); -ensure_keepalive(_AckProps, Channel = #channel{conninfo = ConnInfo}) -> - ensure_keepalive_timer(maps:get(keepalive, ConnInfo), Channel). - -ensure_keepalive_timer(0, Channel) -> Channel; -ensure_keepalive_timer(Interval, Channel = #channel{clientinfo = #{zone := Zone}}) -> - Backoff = emqx_zone:keepalive_backoff(Zone), - Keepalive = emqx_keepalive:init(round(timer:seconds(Interval) * Backoff)), - ensure_timer(alive_timer, Channel#channel{keepalive = Keepalive}). - -%%-------------------------------------------------------------------- -%% Maybe Resume Session - -maybe_resume_session(#channel{resuming = false}) -> - ignore; -maybe_resume_session(#channel{session = Session, - resuming = true, - pendings = Pendings}) -> - {ok, Publishes, Session1} = emqx_session:replay(Session), - case emqx_session:deliver(Pendings, Session1) of - {ok, Session2} -> - {ok, Publishes, Session2}; - {ok, More, Session2} -> - {ok, lists:append(Publishes, More), Session2} - end. - -%%-------------------------------------------------------------------- -%% Maybe Shutdown the Channel - -maybe_shutdown(Reason, Channel = #channel{conninfo = ConnInfo}) -> - case maps:get(expiry_interval, ConnInfo) of - ?UINT_MAX -> {ok, Channel}; - I when I > 0 -> - {ok, ensure_timer(expire_timer, timer:seconds(I), Channel)}; - _ -> shutdown(Reason, Channel) - end. - -%%-------------------------------------------------------------------- -%% Is ACL enabled? - --compile({inline, [is_acl_enabled/1]}). -is_acl_enabled(#{zone := Zone, is_superuser := IsSuperuser}) -> - (not IsSuperuser) andalso emqx_zone:enable_acl(Zone). - -%%-------------------------------------------------------------------- -%% Parse Topic Filters - --compile({inline, [parse_topic_filters/1]}). -parse_topic_filters(TopicFilters) -> - lists:map(fun emqx_topic:parse/1, TopicFilters). - -%%-------------------------------------------------------------------- -%% Ensure disconnected - -ensure_disconnected(Reason, Channel = #channel{conninfo = ConnInfo, - clientinfo = ClientInfo}) -> - NConnInfo = ConnInfo#{disconnected_at => erlang:system_time(millisecond)}, - ok = run_hooks('client.disconnected', [ClientInfo, Reason, NConnInfo]), - Channel#channel{conninfo = NConnInfo, conn_state = disconnected}. - -%%-------------------------------------------------------------------- -%% Maybe Publish will msg - -mabye_publish_will_msg(Channel = #channel{will_msg = undefined}) -> - Channel; -mabye_publish_will_msg(Channel = #channel{will_msg = WillMsg}) -> - case will_delay_interval(WillMsg) of - 0 -> publish_will_msg(WillMsg), - Channel#channel{will_msg = undefined}; - I -> ensure_timer(will_timer, timer:seconds(I), Channel) - end. - -will_delay_interval(WillMsg) -> - maps:get('Will-Delay-Interval', emqx_message:get_header(properties, WillMsg), 0). - -publish_will_msg(Msg) -> emqx_broker:publish(Msg). - -%%-------------------------------------------------------------------- -%% Disconnect Reason - -disconnect_reason(?RC_SUCCESS) -> normal; -disconnect_reason(ReasonCode) -> emqx_reason_codes:name(ReasonCode). - -reason_code(takeovered) -> ?RC_SESSION_TAKEN_OVER; -reason_code(discarded) -> ?RC_SESSION_TAKEN_OVER; -reason_code(_) -> ?RC_NORMAL_DISCONNECTION. - -%%-------------------------------------------------------------------- -%% Helper functions -%%-------------------------------------------------------------------- - --compile({inline, [run_hooks/2, run_hooks/3]}). -run_hooks(Name, Args) -> - ok = emqx_metrics:inc(Name), emqx_hooks:run(Name, Args). - -run_hooks(Name, Args, Acc) -> - ok = emqx_metrics:inc(Name), emqx_hooks:run_fold(Name, Args, Acc). - --compile({inline, [find_alias/3, save_alias/4]}). - -find_alias(_, _ ,undefined) -> false; -find_alias(inbound, AliasId, _TopicAliases = #{inbound := Aliases}) -> - maps:find(AliasId, Aliases); -find_alias(outbound, Topic, _TopicAliases = #{outbound := Aliases}) -> - maps:find(Topic, Aliases). - -save_alias(_, _, _, undefined) -> false; -save_alias(inbound, AliasId, Topic, TopicAliases = #{inbound := Aliases}) -> - NAliases = maps:put(AliasId, Topic, Aliases), - TopicAliases#{inbound => NAliases}; -save_alias(outbound, AliasId, Topic, TopicAliases = #{outbound := Aliases}) -> - NAliases = maps:put(Topic, AliasId, Aliases), - TopicAliases#{outbound => NAliases}. - --compile({inline, [reply/2, shutdown/2, shutdown/3, sp/1, flag/1]}). - -reply(Reply, Channel) -> - {reply, Reply, Channel}. - -shutdown(success, Channel) -> - shutdown(normal, Channel); -shutdown(Reason, Channel) -> - {shutdown, Reason, Channel}. - -shutdown(success, Reply, Channel) -> - shutdown(normal, Reply, Channel); -shutdown(Reason, Reply, Channel) -> - {shutdown, Reason, Reply, Channel}. - -shutdown(success, Reply, Packet, Channel) -> - shutdown(normal, Reply, Packet, Channel); -shutdown(Reason, Reply, Packet, Channel) -> - {shutdown, Reason, Reply, Packet, Channel}. - -disconnect_and_shutdown(Reason, Reply, Channel = ?IS_MQTT_V5 - = #channel{conn_state = connected}) -> - shutdown(Reason, Reply, ?DISCONNECT_PACKET(reason_code(Reason)), Channel); - -disconnect_and_shutdown(Reason, Reply, Channel) -> - shutdown(Reason, Reply, Channel). - -sp(true) -> 1; -sp(false) -> 0. - -flag(true) -> 1; -flag(false) -> 0. - -%%-------------------------------------------------------------------- -%% For CT tests -%%-------------------------------------------------------------------- - -set_field(Name, Value, Channel) -> - Pos = emqx_misc:index_of(Name, record_info(fields, channel)), - setelement(Pos+1, Channel, Value). - diff --git a/_build/emqx/lib/emqx/src/emqx_cm.erl b/_build/emqx/lib/emqx/src/emqx_cm.erl deleted file mode 100644 index a24bb8fba8..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_cm.erl +++ /dev/null @@ -1,436 +0,0 @@ -%%------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% Channel Manager --module(emqx_cm). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[CM]"). - --export([start_link/0]). - --export([ register_channel/3 - , unregister_channel/1 - ]). - --export([connection_closed/1]). - --export([ get_chan_info/1 - , get_chan_info/2 - , set_chan_info/2 - ]). - --export([ get_chan_stats/1 - , get_chan_stats/2 - , set_chan_stats/2 - ]). - --export([get_chann_conn_mod/2]). - --export([ open_session/3 - , discard_session/1 - , discard_session/2 - , takeover_session/1 - , takeover_session/2 - , kick_session/1 - , kick_session/2 - ]). - --export([ lookup_channels/1 - , lookup_channels/2 - ]). - --export([all_channels/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - -%% Internal export --export([stats_fun/0]). - --type(chan_pid() :: pid()). - -%% Tables for channel management. --define(CHAN_TAB, emqx_channel). --define(CHAN_CONN_TAB, emqx_channel_conn). --define(CHAN_INFO_TAB, emqx_channel_info). - --define(CHAN_STATS, - [{?CHAN_TAB, 'channels.count', 'channels.max'}, - {?CHAN_TAB, 'sessions.count', 'sessions.max'}, - {?CHAN_CONN_TAB, 'connections.count', 'connections.max'} - ]). - -%% Batch drain --define(BATCH_SIZE, 100000). - -%% Server name --define(CM, ?MODULE). - -%% @doc Start the channel manager. --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?CM}, ?MODULE, [], []). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -%% @doc Register a channel with info and stats. --spec(register_channel(emqx_types:clientid(), - emqx_types:infos(), - emqx_types:stats()) -> ok). -register_channel(ClientId, Info = #{conninfo := ConnInfo}, Stats) -> - Chan = {ClientId, ChanPid = self()}, - true = ets:insert(?CHAN_INFO_TAB, {Chan, Info, Stats}), - register_channel_(ClientId, ChanPid, ConnInfo). - -%% @private -%% @doc Register a channel with pid and conn_mod. -%% -%% There is a Race-Condition on one node or cluster when many connections -%% login to Broker with the same clientid. We should register it and save -%% the conn_mod first for taking up the clientid access right. -%% -%% Note that: It should be called on a lock transaction -register_channel_(ClientId, ChanPid, #{conn_mod := ConnMod}) when is_pid(ChanPid) -> - Chan = {ClientId, ChanPid}, - true = ets:insert(?CHAN_TAB, Chan), - true = ets:insert(?CHAN_CONN_TAB, {Chan, ConnMod}), - ok = emqx_cm_registry:register_channel(Chan), - cast({registered, Chan}). - -%% @doc Unregister a channel. --spec(unregister_channel(emqx_types:clientid()) -> ok). -unregister_channel(ClientId) when is_binary(ClientId) -> - true = do_unregister_channel({ClientId, self()}), - ok. - -%% @private -do_unregister_channel(Chan) -> - ok = emqx_cm_registry:unregister_channel(Chan), - true = ets:delete(?CHAN_CONN_TAB, Chan), - true = ets:delete(?CHAN_INFO_TAB, Chan), - ets:delete_object(?CHAN_TAB, Chan). - --spec(connection_closed(emqx_types:clientid()) -> true). -connection_closed(ClientId) -> - connection_closed(ClientId, self()). - --spec(connection_closed(emqx_types:clientid(), chan_pid()) -> true). -connection_closed(ClientId, ChanPid) -> - ets:delete_object(?CHAN_CONN_TAB, {ClientId, ChanPid}). - -%% @doc Get info of a channel. --spec(get_chan_info(emqx_types:clientid()) -> maybe(emqx_types:infos())). -get_chan_info(ClientId) -> - with_channel(ClientId, fun(ChanPid) -> get_chan_info(ClientId, ChanPid) end). - --spec(get_chan_info(emqx_types:clientid(), chan_pid()) - -> maybe(emqx_types:infos())). -get_chan_info(ClientId, ChanPid) when node(ChanPid) == node() -> - Chan = {ClientId, ChanPid}, - try ets:lookup_element(?CHAN_INFO_TAB, Chan, 2) - catch - error:badarg -> undefined - end; -get_chan_info(ClientId, ChanPid) -> - rpc_call(node(ChanPid), get_chan_info, [ClientId, ChanPid]). - -%% @doc Update infos of the channel. --spec(set_chan_info(emqx_types:clientid(), emqx_types:attrs()) -> boolean()). -set_chan_info(ClientId, Info) when is_binary(ClientId) -> - Chan = {ClientId, self()}, - try ets:update_element(?CHAN_INFO_TAB, Chan, {2, Info}) - catch - error:badarg -> false - end. - -%% @doc Get channel's stats. --spec(get_chan_stats(emqx_types:clientid()) -> maybe(emqx_types:stats())). -get_chan_stats(ClientId) -> - with_channel(ClientId, fun(ChanPid) -> get_chan_stats(ClientId, ChanPid) end). - --spec(get_chan_stats(emqx_types:clientid(), chan_pid()) - -> maybe(emqx_types:stats())). -get_chan_stats(ClientId, ChanPid) when node(ChanPid) == node() -> - Chan = {ClientId, ChanPid}, - try ets:lookup_element(?CHAN_INFO_TAB, Chan, 3) - catch - error:badarg -> undefined - end; -get_chan_stats(ClientId, ChanPid) -> - rpc_call(node(ChanPid), get_chan_stats, [ClientId, ChanPid]). - -%% @doc Set channel's stats. --spec(set_chan_stats(emqx_types:clientid(), emqx_types:stats()) -> boolean()). -set_chan_stats(ClientId, Stats) when is_binary(ClientId) -> - set_chan_stats(ClientId, self(), Stats). - --spec(set_chan_stats(emqx_types:clientid(), chan_pid(), emqx_types:stats()) - -> boolean()). -set_chan_stats(ClientId, ChanPid, Stats) -> - Chan = {ClientId, ChanPid}, - try ets:update_element(?CHAN_INFO_TAB, Chan, {3, Stats}) - catch - error:badarg -> false - end. - -%% @doc Open a session. --spec(open_session(boolean(), emqx_types:clientinfo(), emqx_types:conninfo()) - -> {ok, #{session := emqx_session:session(), - present := boolean(), - pendings => list()}} - | {error, Reason :: term()}). -open_session(true, ClientInfo = #{clientid := ClientId}, ConnInfo) -> - Self = self(), - CleanStart = fun(_) -> - ok = discard_session(ClientId), - Session = create_session(ClientInfo, ConnInfo), - register_channel_(ClientId, Self, ConnInfo), - {ok, #{session => Session, present => false}} - end, - emqx_cm_locker:trans(ClientId, CleanStart); - -open_session(false, ClientInfo = #{clientid := ClientId}, ConnInfo) -> - Self = self(), - ResumeStart = fun(_) -> - case takeover_session(ClientId) of - {ok, ConnMod, ChanPid, Session} -> - ok = emqx_session:resume(ClientInfo, Session), - Pendings = ConnMod:call(ChanPid, {takeover, 'end'}), - register_channel_(ClientId, Self, ConnInfo), - {ok, #{session => Session, - present => true, - pendings => Pendings}}; - {error, not_found} -> - Session = create_session(ClientInfo, ConnInfo), - register_channel_(ClientId, Self, ConnInfo), - {ok, #{session => Session, present => false}} - end - end, - emqx_cm_locker:trans(ClientId, ResumeStart). - -create_session(ClientInfo, ConnInfo) -> - Session = emqx_session:init(ClientInfo, ConnInfo), - ok = emqx_metrics:inc('session.created'), - ok = emqx_hooks:run('session.created', [ClientInfo, emqx_session:info(Session)]), - Session. - -%% @doc Try to takeover a session. --spec(takeover_session(emqx_types:clientid()) - -> {error, term()} - | {ok, atom(), pid(), emqx_session:session()}). -takeover_session(ClientId) -> - case lookup_channels(ClientId) of - [] -> {error, not_found}; - [ChanPid] -> - takeover_session(ClientId, ChanPid); - ChanPids -> - [ChanPid|StalePids] = lists:reverse(ChanPids), - ?LOG(error, "More than one channel found: ~p", [ChanPids]), - lists:foreach(fun(StalePid) -> - catch discard_session(ClientId, StalePid) - end, StalePids), - takeover_session(ClientId, ChanPid) - end. - -takeover_session(ClientId, ChanPid) when node(ChanPid) == node() -> - case get_chann_conn_mod(ClientId, ChanPid) of - ConnMod when is_atom(ConnMod) -> - Session = ConnMod:call(ChanPid, {takeover, 'begin'}), - {ok, ConnMod, ChanPid, Session}; - undefined -> - {error, not_found} - end; - -takeover_session(ClientId, ChanPid) -> - rpc_call(node(ChanPid), takeover_session, [ClientId, ChanPid]). - -%% @doc Discard all the sessions identified by the ClientId. --spec(discard_session(emqx_types:clientid()) -> ok). -discard_session(ClientId) when is_binary(ClientId) -> - case lookup_channels(ClientId) of - [] -> ok; - ChanPids -> - lists:foreach( - fun(ChanPid) -> - try - discard_session(ClientId, ChanPid) - catch - _:{noproc,_}:_Stk -> ok; - _:{{shutdown,_},_}:_Stk -> ok; - _:Error:_Stk -> - ?LOG(error, "Failed to discard ~0p: ~0p", [ChanPid, Error]) - end - end, ChanPids) - end. - -discard_session(ClientId, ChanPid) when node(ChanPid) == node() -> - case get_chann_conn_mod(ClientId, ChanPid) of - ConnMod when is_atom(ConnMod) -> - ConnMod:call(ChanPid, discard); - undefined -> ok - end; - -discard_session(ClientId, ChanPid) -> - rpc_call(node(ChanPid), discard_session, [ClientId, ChanPid]). - -kick_session(ClientId) -> - case lookup_channels(ClientId) of - [] -> {error, not_found}; - [ChanPid] -> - kick_session(ClientId, ChanPid); - ChanPids -> - [ChanPid|StalePids] = lists:reverse(ChanPids), - ?LOG(error, "More than one channel found: ~p", [ChanPids]), - lists:foreach(fun(StalePid) -> - catch discard_session(ClientId, StalePid) - end, StalePids), - kick_session(ClientId, ChanPid) - end. - -kick_session(ClientId, ChanPid) when node(ChanPid) == node() -> - case get_chan_info(ClientId, ChanPid) of - #{conninfo := #{conn_mod := ConnMod}} -> - ConnMod:call(ChanPid, kick); - undefined -> - {error, not_found} - end; - -kick_session(ClientId, ChanPid) -> - rpc_call(node(ChanPid), kick_session, [ClientId, ChanPid]). - -%% @doc Is clean start? -% is_clean_start(#{clean_start := false}) -> false; -% is_clean_start(_Attrs) -> true. - -with_channel(ClientId, Fun) -> - case lookup_channels(ClientId) of - [] -> undefined; - [Pid] -> Fun(Pid); - Pids -> Fun(lists:last(Pids)) - end. - -%% @doc Get all channels registed. -all_channels() -> - Pat = [{{'_', '$1'}, [], ['$1']}], - ets:select(?CHAN_TAB, Pat). - -%% @doc Lookup channels. --spec(lookup_channels(emqx_types:clientid()) -> list(chan_pid())). -lookup_channels(ClientId) -> - lookup_channels(global, ClientId). - -%% @doc Lookup local or global channels. --spec(lookup_channels(local | global, emqx_types:clientid()) -> list(chan_pid())). -lookup_channels(global, ClientId) -> - case emqx_cm_registry:is_enabled() of - true -> - emqx_cm_registry:lookup_channels(ClientId); - false -> - lookup_channels(local, ClientId) - end; - -lookup_channels(local, ClientId) -> - [ChanPid || {_, ChanPid} <- ets:lookup(?CHAN_TAB, ClientId)]. - -%% @private -rpc_call(Node, Fun, Args) -> - case rpc:call(Node, ?MODULE, Fun, Args) of - {badrpc, Reason} -> error(Reason); - Res -> Res - end. - -%% @private -cast(Msg) -> gen_server:cast(?CM, Msg). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - TabOpts = [public, {write_concurrency, true}], - ok = emqx_tables:new(?CHAN_TAB, [bag, {read_concurrency, true}|TabOpts]), - ok = emqx_tables:new(?CHAN_CONN_TAB, [bag | TabOpts]), - ok = emqx_tables:new(?CHAN_INFO_TAB, [set, compressed | TabOpts]), - ok = emqx_stats:update_interval(chan_stats, fun ?MODULE:stats_fun/0), - {ok, #{chan_pmon => emqx_pmon:new()}}. - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({registered, {ClientId, ChanPid}}, State = #{chan_pmon := PMon}) -> - PMon1 = emqx_pmon:monitor(ChanPid, ClientId, PMon), - {noreply, State#{chan_pmon := PMon1}}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({'DOWN', _MRef, process, Pid, _Reason}, State = #{chan_pmon := PMon}) -> - ChanPids = [Pid | emqx_misc:drain_down(?BATCH_SIZE)], - {Items, PMon1} = emqx_pmon:erase_all(ChanPids, PMon), - ok = emqx_pool:async_submit(fun lists:foreach/2, [fun clean_down/1, Items]), - {noreply, State#{chan_pmon := PMon1}}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - emqx_stats:cancel_update(chan_stats). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -clean_down({ChanPid, ClientId}) -> - do_unregister_channel({ClientId, ChanPid}). - -stats_fun() -> - lists:foreach(fun update_stats/1, ?CHAN_STATS). - -update_stats({Tab, Stat, MaxStat}) -> - case ets:info(Tab, size) of - undefined -> ok; - Size -> emqx_stats:setstat(Stat, MaxStat, Size) - end. - -get_chann_conn_mod(ClientId, ChanPid) when node(ChanPid) == node() -> - Chan = {ClientId, ChanPid}, - try [ConnMod] = ets:lookup_element(?CHAN_CONN_TAB, Chan, 2), ConnMod - catch - error:badarg -> undefined - end; -get_chann_conn_mod(ClientId, ChanPid) -> - rpc_call(node(ChanPid), get_chann_conn_mod, [ClientId, ChanPid]). - diff --git a/_build/emqx/lib/emqx/src/emqx_cm_locker.erl b/_build/emqx/lib/emqx/src/emqx_cm_locker.erl deleted file mode 100644 index 708d3d23cd..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_cm_locker.erl +++ /dev/null @@ -1,66 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_cm_locker). - --include("emqx.hrl"). --include("types.hrl"). - --export([start_link/0]). - --export([ trans/2 - , trans/3 - , lock/1 - , lock/2 - , unlock/1 - ]). - --spec(start_link() -> startlink_ret()). -start_link() -> - ekka_locker:start_link(?MODULE). - --spec(trans(emqx_types:clientid(), fun(([node()]) -> any())) -> any()). -trans(ClientId, Fun) -> - trans(ClientId, Fun, undefined). - --spec(trans(maybe(emqx_types:clientid()), - fun(([node()])-> any()), ekka_locker:piggyback()) -> any()). -trans(undefined, Fun, _Piggyback) -> - Fun([]); -trans(ClientId, Fun, Piggyback) -> - case lock(ClientId, Piggyback) of - {true, Nodes} -> - try Fun(Nodes) after unlock(ClientId) end; - {false, _Nodes} -> - {error, client_id_unavailable} - end. - --spec(lock(emqx_types:clientid()) -> ekka_locker:lock_result()). -lock(ClientId) -> - ekka_locker:acquire(?MODULE, ClientId, strategy()). - --spec(lock(emqx_types:clientid(), ekka_locker:piggyback()) -> ekka_locker:lock_result()). -lock(ClientId, Piggyback) -> - ekka_locker:acquire(?MODULE, ClientId, strategy(), Piggyback). - --spec(unlock(emqx_types:clientid()) -> {boolean(), [node()]}). -unlock(ClientId) -> - ekka_locker:release(?MODULE, ClientId, strategy()). - --spec(strategy() -> local | one | quorum | all). -strategy() -> - emqx:get_env(session_locking_strategy, quorum). - diff --git a/_build/emqx/lib/emqx/src/emqx_cm_registry.erl b/_build/emqx/lib/emqx/src/emqx_cm_registry.erl deleted file mode 100644 index 6609d70f40..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_cm_registry.erl +++ /dev/null @@ -1,153 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% Global Channel Registry --module(emqx_cm_registry). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Registry]"). - --export([start_link/0]). - --export([is_enabled/0]). - --export([ register_channel/1 - , unregister_channel/1 - ]). - --export([lookup_channels/1]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --define(REGISTRY, ?MODULE). --define(TAB, emqx_channel_registry). --define(LOCK, {?MODULE, cleanup_down}). - --record(channel, {chid, pid}). - -%% @doc Start the global channel registry. --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?REGISTRY}, ?MODULE, [], []). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Is the global registry enabled? --spec(is_enabled() -> boolean()). -is_enabled() -> - emqx:get_env(enable_session_registry, true). - -%% @doc Register a global channel. --spec(register_channel(emqx_types:clientid() - | {emqx_types:clientid(), pid()}) -> ok). -register_channel(ClientId) when is_binary(ClientId) -> - register_channel({ClientId, self()}); - -register_channel({ClientId, ChanPid}) when is_binary(ClientId), is_pid(ChanPid) -> - case is_enabled() of - true -> mnesia:dirty_write(?TAB, record(ClientId, ChanPid)); - false -> ok - end. - -%% @doc Unregister a global channel. --spec(unregister_channel(emqx_types:clientid() - | {emqx_types:clientid(), pid()}) -> ok). -unregister_channel(ClientId) when is_binary(ClientId) -> - unregister_channel({ClientId, self()}); - -unregister_channel({ClientId, ChanPid}) when is_binary(ClientId), is_pid(ChanPid) -> - case is_enabled() of - true -> mnesia:dirty_delete_object(?TAB, record(ClientId, ChanPid)); - false -> ok - end. - -%% @doc Lookup the global channels. --spec(lookup_channels(emqx_types:clientid()) -> list(pid())). -lookup_channels(ClientId) -> - [ChanPid || #channel{pid = ChanPid} <- mnesia:dirty_read(?TAB, ClientId)]. - -record(ClientId, ChanPid) -> - #channel{chid = ClientId, pid = ChanPid}. - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - ok = ekka_mnesia:create_table(?TAB, [ - {type, bag}, - {ram_copies, [node()]}, - {record_name, channel}, - {attributes, record_info(fields, channel)}, - {storage_properties, [{ets, [{read_concurrency, true}, - {write_concurrency, true}]}]}]), - ok = ekka_mnesia:copy_table(?TAB), - ok = ekka:monitor(membership), - {ok, #{}}. - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({membership, {mnesia, down, Node}}, State) -> - global:trans({?LOCK, self()}, - fun() -> - mnesia:transaction(fun cleanup_channels/1, [Node]) - end), - {noreply, State}; - -handle_info({membership, _Event}, State) -> - {noreply, State}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -cleanup_channels(Node) -> - Pat = [{#channel{pid = '$1', _ = '_'}, [{'==', {node, '$1'}, Node}], ['$_']}], - lists:foreach(fun delete_channel/1, mnesia:select(?TAB, Pat, write)). - -delete_channel(Chan) -> - mnesia:delete_object(?TAB, Chan, write). - diff --git a/_build/emqx/lib/emqx/src/emqx_cm_sup.erl b/_build/emqx/lib/emqx/src/emqx_cm_sup.erl deleted file mode 100644 index 02c4cd3d86..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_cm_sup.erl +++ /dev/null @@ -1,70 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_cm_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -init([]) -> - Banned = #{id => banned, - start => {emqx_banned, start_link, []}, - restart => permanent, - shutdown => 1000, - type => worker, - modules => [emqx_banned]}, - Flapping = #{id => flapping, - start => {emqx_flapping, start_link, []}, - restart => permanent, - shutdown => 1000, - type => worker, - modules => [emqx_flapping]}, - %% Channel locker - Locker = #{id => locker, - start => {emqx_cm_locker, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [emqx_cm_locker] - }, - %% Channel registry - Registry = #{id => registry, - start => {emqx_cm_registry, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [emqx_cm_registry] - }, - %% Channel Manager - Manager = #{id => manager, - start => {emqx_cm, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [emqx_cm] - }, - SupFlags = #{strategy => one_for_one, - intensity => 100, - period => 10 - }, - {ok, {SupFlags, [Banned, Flapping, Locker, Registry, Manager]}}. - diff --git a/_build/emqx/lib/emqx/src/emqx_connection.erl b/_build/emqx/lib/emqx/src/emqx_connection.erl deleted file mode 100644 index e54495a715..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_connection.erl +++ /dev/null @@ -1,741 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% MQTT/TCP|TLS Connection --module(emqx_connection). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[MQTT]"). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - -%% API --export([ start_link/3 - , stop/1 - ]). - --export([ info/1 - , stats/1 - ]). - --export([call/2]). - -%% Callback --export([init/4]). - -%% Sys callbacks --export([ system_continue/3 - , system_terminate/4 - , system_code_change/4 - , system_get_state/1 - ]). - -%% Internal callback --export([wakeup_from_hib/2]). - -%% Export for CT --export([set_field/3]). - --import(emqx_misc, - [ maybe_apply/2 - , start_timer/2 - ]). - --record(state, { - %% TCP/TLS Transport - transport :: esockd:transport(), - %% TCP/TLS Socket - socket :: esockd:socket(), - %% Peername of the connection - peername :: emqx_types:peername(), - %% Sockname of the connection - sockname :: emqx_types:peername(), - %% Sock State - sockstate :: emqx_types:sockstate(), - %% The {active, N} option - active_n :: pos_integer(), - %% Limiter - limiter :: maybe(emqx_limiter:limiter()), - %% Limit Timer - limit_timer :: maybe(reference()), - %% Parse State - parse_state :: emqx_frame:parse_state(), - %% Serialize function - serialize :: emqx_frame:serialize_fun(), - %% Channel State - channel :: emqx_channel:channel(), - %% GC State - gc_state :: maybe(emqx_gc:gc_state()), - %% Stats Timer - stats_timer :: disabled | maybe(reference()), - %% Idle Timeout - idle_timeout :: integer(), - %% Idle Timer - idle_timer :: maybe(reference()) - }). - --type(state() :: #state{}). - --define(ACTIVE_N, 100). --define(INFO_KEYS, [socktype, peername, sockname, sockstate, active_n]). --define(CONN_STATS, [recv_pkt, recv_msg, send_pkt, send_msg]). --define(SOCK_STATS, [recv_oct, recv_cnt, send_oct, send_cnt, send_pend]). - --define(ENABLED(X), (X =/= undefined)). - --dialyzer({no_match, [info/2]}). --dialyzer({nowarn_function, [ init/4 - , init_state/3 - , run_loop/2 - , system_terminate/4 - ]}). - --spec(start_link(esockd:transport(), esockd:socket(), proplists:proplist()) - -> {ok, pid()}). -start_link(Transport, Socket, Options) -> - Args = [self(), Transport, Socket, Options], - CPid = proc_lib:spawn_link(?MODULE, init, Args), - {ok, CPid}. - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -%% @doc Get infos of the connection/channel. --spec(info(pid()|state()) -> emqx_types:infos()). -info(CPid) when is_pid(CPid) -> - call(CPid, info); -info(State = #state{channel = Channel}) -> - ChanInfo = emqx_channel:info(Channel), - SockInfo = maps:from_list( - info(?INFO_KEYS, State)), - ChanInfo#{sockinfo => SockInfo}. - -info(Keys, State) when is_list(Keys) -> - [{Key, info(Key, State)} || Key <- Keys]; -info(socktype, #state{transport = Transport, socket = Socket}) -> - Transport:type(Socket); -info(peername, #state{peername = Peername}) -> - Peername; -info(sockname, #state{sockname = Sockname}) -> - Sockname; -info(sockstate, #state{sockstate = SockSt}) -> - SockSt; -info(active_n, #state{active_n = ActiveN}) -> - ActiveN; -info(stats_timer, #state{stats_timer = StatsTimer}) -> - StatsTimer; -info(limit_timer, #state{limit_timer = LimitTimer}) -> - LimitTimer; -info(limiter, #state{limiter = Limiter}) -> - maybe_apply(fun emqx_limiter:info/1, Limiter). - -%% @doc Get stats of the connection/channel. --spec(stats(pid()|state()) -> emqx_types:stats()). -stats(CPid) when is_pid(CPid) -> - call(CPid, stats); -stats(#state{transport = Transport, - socket = Socket, - channel = Channel}) -> - SockStats = case Transport:getstat(Socket, ?SOCK_STATS) of - {ok, Ss} -> Ss; - {error, _} -> [] - end, - ConnStats = emqx_pd:get_counters(?CONN_STATS), - ChanStats = emqx_channel:stats(Channel), - ProcStats = emqx_misc:proc_stats(), - lists:append([SockStats, ConnStats, ChanStats, ProcStats]). - -call(Pid, Req) -> - gen_server:call(Pid, Req, infinity). - -stop(Pid) -> - gen_server:stop(Pid). - -%%-------------------------------------------------------------------- -%% callbacks -%%-------------------------------------------------------------------- - -init(Parent, Transport, RawSocket, Options) -> - case Transport:wait(RawSocket) of - {ok, Socket} -> - run_loop(Parent, init_state(Transport, Socket, Options)); - {error, Reason} -> - ok = Transport:fast_close(RawSocket), - exit_on_sock_error(Reason) - end. - -init_state(Transport, Socket, Options) -> - {ok, Peername} = Transport:ensure_ok_or_exit(peername, [Socket]), - {ok, Sockname} = Transport:ensure_ok_or_exit(sockname, [Socket]), - Peercert = Transport:ensure_ok_or_exit(peercert, [Socket]), - ConnInfo = #{socktype => Transport:type(Socket), - peername => Peername, - sockname => Sockname, - peercert => Peercert, - conn_mod => ?MODULE - }, - Zone = proplists:get_value(zone, Options), - ActiveN = proplists:get_value(active_n, Options, ?ACTIVE_N), - PubLimit = emqx_zone:publish_limit(Zone), - Limiter = emqx_limiter:init([{pub_limit, PubLimit}|Options]), - FrameOpts = emqx_zone:mqtt_frame_options(Zone), - ParseState = emqx_frame:initial_parse_state(FrameOpts), - Serialize = emqx_frame:serialize_fun(), - Channel = emqx_channel:init(ConnInfo, Options), - GcState = emqx_zone:init_gc_state(Zone), - StatsTimer = emqx_zone:stats_timer(Zone), - IdleTimeout = emqx_zone:idle_timeout(Zone), - IdleTimer = start_timer(IdleTimeout, idle_timeout), - #state{transport = Transport, - socket = Socket, - peername = Peername, - sockname = Sockname, - sockstate = idle, - active_n = ActiveN, - limiter = Limiter, - parse_state = ParseState, - serialize = Serialize, - channel = Channel, - gc_state = GcState, - stats_timer = StatsTimer, - idle_timeout = IdleTimeout, - idle_timer = IdleTimer - }. - -run_loop(Parent, State = #state{transport = Transport, - socket = Socket, - peername = Peername, - channel = Channel}) -> - emqx_logger:set_metadata_peername(esockd:format(Peername)), - emqx_misc:tune_heap_size(emqx_zone:oom_policy( - emqx_channel:info(zone, Channel))), - case activate_socket(State) of - {ok, NState} -> hibernate(Parent, NState); - {error, Reason} -> - ok = Transport:fast_close(Socket), - exit_on_sock_error(Reason) - end. - -exit_on_sock_error(Reason) when Reason =:= einval; - Reason =:= enotconn; - Reason =:= closed -> - erlang:exit(normal); -exit_on_sock_error(timeout) -> - erlang:exit({shutdown, ssl_upgrade_timeout}); -exit_on_sock_error(Reason) -> - erlang:exit({shutdown, Reason}). - -%%-------------------------------------------------------------------- -%% Recv Loop - -recvloop(Parent, State = #state{idle_timeout = IdleTimeout}) -> - receive - {system, From, Request} -> - sys:handle_system_msg(Request, From, Parent, ?MODULE, [], State); - {'EXIT', Parent, Reason} -> - terminate(Reason, State); - Msg -> - process_msg([Msg], Parent, ensure_stats_timer(IdleTimeout, State)) - after - IdleTimeout -> - hibernate(Parent, cancel_stats_timer(State)) - end. - -hibernate(Parent, State) -> - proc_lib:hibernate(?MODULE, wakeup_from_hib, [Parent, State]). - -%% Maybe do something here later. -wakeup_from_hib(Parent, State) -> recvloop(Parent, State). - -%%-------------------------------------------------------------------- -%% Ensure/cancel stats timer - --compile({inline, [ensure_stats_timer/2]}). -ensure_stats_timer(Timeout, State = #state{stats_timer = undefined}) -> - State#state{stats_timer = start_timer(Timeout, emit_stats)}; -ensure_stats_timer(_Timeout, State) -> State. - --compile({inline, [cancel_stats_timer/1]}). -cancel_stats_timer(State = #state{stats_timer = TRef}) when is_reference(TRef) -> - ok = emqx_misc:cancel_timer(TRef), - State#state{stats_timer = undefined}; -cancel_stats_timer(State) -> State. - -%%-------------------------------------------------------------------- -%% Process next Msg - -process_msg([], Parent, State) -> recvloop(Parent, State); - -process_msg([Msg|More], Parent, State) -> - case catch handle_msg(Msg, State) of - ok -> - process_msg(More, Parent, State); - {ok, NState} -> - process_msg(More, Parent, NState); - {ok, Msgs, NState} -> - process_msg(append_msg(More, Msgs), Parent, NState); - {stop, Reason} -> - terminate(Reason, State); - {stop, Reason, NState} -> - terminate(Reason, NState); - {'EXIT', Reason} -> - terminate(Reason, State) - end. - --compile({inline, [append_msg/2]}). -append_msg([], Msgs) when is_list(Msgs) -> - Msgs; -append_msg([], Msg) -> [Msg]; -append_msg(Q, Msgs) when is_list(Msgs) -> - lists:append(Q, Msgs); -append_msg(Q, Msg) -> - lists:append(Q, [Msg]). - -%%-------------------------------------------------------------------- -%% Handle a Msg - -handle_msg({'$gen_call', From, Req}, State) -> - case handle_call(From, Req, State) of - {reply, Reply, NState} -> - gen_server:reply(From, Reply), - {ok, NState}; - {stop, Reason, Reply, NState} -> - gen_server:reply(From, Reply), - stop(Reason, NState) - end; - -handle_msg({Inet, _Sock, Data}, State) when Inet == tcp; Inet == ssl -> - ?LOG(debug, "RECV ~0p", [Data]), - Oct = iolist_size(Data), - emqx_pd:inc_counter(incoming_bytes, Oct), - ok = emqx_metrics:inc('bytes.received', Oct), - parse_incoming(Data, State); - -handle_msg({incoming, Packet = ?CONNECT_PACKET(ConnPkt)}, - State = #state{idle_timer = IdleTimer}) -> - ok = emqx_misc:cancel_timer(IdleTimer), - Serialize = emqx_frame:serialize_fun(ConnPkt), - NState = State#state{serialize = Serialize, - idle_timer = undefined - }, - handle_incoming(Packet, NState); - -handle_msg({incoming, ?PACKET(?PINGREQ)}, State) -> - handle_outgoing(?PACKET(?PINGRESP), State); - -handle_msg({incoming, Packet}, State) -> - handle_incoming(Packet, State); - -handle_msg({outgoing, Packets}, State) -> - handle_outgoing(Packets, State); - -handle_msg({Error, _Sock, Reason}, State) - when Error == tcp_error; Error == ssl_error -> - handle_info({sock_error, Reason}, State); - -handle_msg({Closed, _Sock}, State) - when Closed == tcp_closed; Closed == ssl_closed -> - handle_info({sock_closed, Closed}, close_socket(State)); - -handle_msg({Passive, _Sock}, State) - when Passive == tcp_passive; Passive == ssl_passive -> - %% In Stats - Pubs = emqx_pd:reset_counter(incoming_pubs), - Bytes = emqx_pd:reset_counter(incoming_bytes), - InStats = #{cnt => Pubs, oct => Bytes}, - %% Ensure Rate Limit - NState = ensure_rate_limit(InStats, State), - %% Run GC and Check OOM - NState1 = check_oom(run_gc(InStats, NState)), - handle_info(activate_socket, NState1); - -handle_msg(Deliver = {deliver, _Topic, _Msg}, - State = #state{active_n = ActiveN}) -> - Delivers = [Deliver|emqx_misc:drain_deliver(ActiveN)], - with_channel(handle_deliver, [Delivers], State); - -%% Something sent -handle_msg({inet_reply, _Sock, ok}, State = #state{active_n = ActiveN}) -> - case emqx_pd:get_counter(outgoing_pubs) > ActiveN of - true -> - Pubs = emqx_pd:reset_counter(outgoing_pubs), - Bytes = emqx_pd:reset_counter(outgoing_bytes), - OutStats = #{cnt => Pubs, oct => Bytes}, - {ok, check_oom(run_gc(OutStats, State))}; - false -> ok - end; - -handle_msg({inet_reply, _Sock, {error, Reason}}, State) -> - handle_info({sock_error, Reason}, State); - -handle_msg({connack, ConnAck}, State) -> - handle_outgoing(ConnAck, State); - -handle_msg({close, Reason}, State) -> - ?LOG(debug, "Force to close the socket due to ~p", [Reason]), - handle_info({sock_closed, Reason}, close_socket(State)); - -handle_msg({event, connected}, State = #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:register_channel(ClientId, info(State), stats(State)); - -handle_msg({event, disconnected}, State = #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:set_chan_info(ClientId, info(State)), - emqx_cm:connection_closed(ClientId), - {ok, State}; - -handle_msg({event, _Other}, State = #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:set_chan_info(ClientId, info(State)), - emqx_cm:set_chan_stats(ClientId, stats(State)), - {ok, State}; - -handle_msg({timeout, TRef, TMsg}, State) -> - handle_timeout(TRef, TMsg, State); - -handle_msg(Shutdown = {shutdown, _Reason}, State) -> - stop(Shutdown, State); - -handle_msg(Msg, State) -> - handle_info(Msg, State). - -%%-------------------------------------------------------------------- -%% Terminate - -terminate(Reason, State = #state{channel = Channel}) -> - ?LOG(debug, "Terminated due to ~p", [Reason]), - emqx_channel:terminate(Reason, Channel), - close_socket(State), - exit(Reason). - -%%-------------------------------------------------------------------- -%% Sys callbacks - -system_continue(Parent, _Debug, State) -> - recvloop(Parent, State). - -system_terminate(Reason, _Parent, _Debug, State) -> - terminate(Reason, State). - -system_code_change(State, _Mod, _OldVsn, _Extra) -> - {ok, State}. - -system_get_state(State) -> {ok, State}. - -%%-------------------------------------------------------------------- -%% Handle call - -handle_call(_From, info, State) -> - {reply, info(State), State}; - -handle_call(_From, stats, State) -> - {reply, stats(State), State}; - -handle_call(_From, Req, State = #state{channel = Channel}) -> - case emqx_channel:handle_call(Req, Channel) of - {reply, Reply, NChannel} -> - {reply, Reply, State#state{channel = NChannel}}; - {shutdown, Reason, Reply, NChannel} -> - shutdown(Reason, Reply, State#state{channel = NChannel}); - {shutdown, Reason, Reply, OutPacket, NChannel} -> - NState = State#state{channel = NChannel}, - ok = handle_outgoing(OutPacket, NState), - shutdown(Reason, Reply, NState) - end. - -%%-------------------------------------------------------------------- -%% Handle timeout - -handle_timeout(_TRef, idle_timeout, State) -> - shutdown(idle_timeout, State); - -handle_timeout(_TRef, limit_timeout, State) -> - NState = State#state{sockstate = idle, - limit_timer = undefined - }, - handle_info(activate_socket, NState); - -handle_timeout(_TRef, emit_stats, State = - #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:set_chan_stats(ClientId, stats(State)), - {ok, State#state{stats_timer = undefined}}; - -handle_timeout(TRef, keepalive, State = #state{transport = Transport, - socket = Socket, - channel = Channel})-> - case emqx_channel:info(conn_state, Channel) of - disconnected -> {ok, State}; - _ -> - case Transport:getstat(Socket, [recv_oct]) of - {ok, [{recv_oct, RecvOct}]} -> - handle_timeout(TRef, {keepalive, RecvOct}, State); - {error, Reason} -> - handle_info({sock_error, Reason}, State) - end - end; - -handle_timeout(TRef, Msg, State) -> - with_channel(handle_timeout, [TRef, Msg], State). - -%%-------------------------------------------------------------------- -%% Parse incoming data - --compile({inline, [parse_incoming/2]}). -parse_incoming(Data, State) -> - {Packets, NState} = parse_incoming(Data, [], State), - {ok, next_incoming_msgs(Packets), NState}. - -parse_incoming(<<>>, Packets, State) -> - {Packets, State}; - -parse_incoming(Data, Packets, State = #state{parse_state = ParseState}) -> - try emqx_frame:parse(Data, ParseState) of - {more, NParseState} -> - {Packets, State#state{parse_state = NParseState}}; - {ok, Packet, Rest, NParseState} -> - NState = State#state{parse_state = NParseState}, - parse_incoming(Rest, [Packet|Packets], NState) - catch - error:Reason:Stk -> - ?LOG(error, "~nParse failed for ~0p~n~0p~nFrame data:~0p", - [Reason, Stk, Data]), - {[{frame_error, Reason}|Packets], State} - end. - --compile({inline, [next_incoming_msgs/1]}). -next_incoming_msgs([Packet]) -> - {incoming, Packet}; -next_incoming_msgs(Packets) -> - [{incoming, Packet} || Packet <- lists:reverse(Packets)]. - -%%-------------------------------------------------------------------- -%% Handle incoming packet - -handle_incoming(Packet, State) when is_record(Packet, mqtt_packet) -> - ok = inc_incoming_stats(Packet), - ?LOG(debug, "RECV ~s", [emqx_packet:format(Packet)]), - with_channel(handle_in, [Packet], State); - -handle_incoming(FrameError, State) -> - with_channel(handle_in, [FrameError], State). - -%%-------------------------------------------------------------------- -%% With Channel - -with_channel(Fun, Args, State = #state{channel = Channel}) -> - case erlang:apply(emqx_channel, Fun, Args ++ [Channel]) of - ok -> {ok, State}; - {ok, NChannel} -> - {ok, State#state{channel = NChannel}}; - {ok, Replies, NChannel} -> - {ok, next_msgs(Replies), State#state{channel = NChannel}}; - {shutdown, Reason, NChannel} -> - shutdown(Reason, State#state{channel = NChannel}); - {shutdown, Reason, Packet, NChannel} -> - NState = State#state{channel = NChannel}, - ok = handle_outgoing(Packet, NState), - shutdown(Reason, NState) - end. - -%%-------------------------------------------------------------------- -%% Handle outgoing packets - -handle_outgoing(Packets, State) when is_list(Packets) -> - send(lists:map(serialize_and_inc_stats_fun(State), Packets), State); - -handle_outgoing(Packet, State) -> - send((serialize_and_inc_stats_fun(State))(Packet), State). - -serialize_and_inc_stats_fun(#state{serialize = Serialize}) -> - fun(Packet) -> - case Serialize(Packet) of - <<>> -> ?LOG(warning, "~s is discarded due to the frame is too large!", - [emqx_packet:format(Packet)]), - ok = emqx_metrics:inc('delivery.dropped.too_large'), - ok = emqx_metrics:inc('delivery.dropped'), - <<>>; - Data -> ?LOG(debug, "SEND ~s", [emqx_packet:format(Packet)]), - ok = inc_outgoing_stats(Packet), - Data - end - end. - -%%-------------------------------------------------------------------- -%% Send data - --spec(send(iodata(), state()) -> ok). -send(IoData, #state{transport = Transport, socket = Socket}) -> - Oct = iolist_size(IoData), - ok = emqx_metrics:inc('bytes.sent', Oct), - emqx_pd:inc_counter(outgoing_bytes, Oct), - case Transport:async_send(Socket, IoData) of - ok -> ok; - Error = {error, _Reason} -> - %% Send an inet_reply to postpone handling the error - self() ! {inet_reply, Socket, Error}, - ok - end. - -%%-------------------------------------------------------------------- -%% Handle Info - -handle_info(activate_socket, State = #state{sockstate = OldSst}) -> - case activate_socket(State) of - {ok, NState = #state{sockstate = NewSst}} -> - if OldSst =/= NewSst -> - {ok, {event, NewSst}, NState}; - true -> {ok, NState} - end; - {error, Reason} -> - handle_info({sock_error, Reason}, State) - end; - -handle_info({sock_error, Reason}, State) -> - ?LOG(debug, "Socket error: ~p", [Reason]), - handle_info({sock_closed, Reason}, close_socket(State)); - -handle_info(Info, State) -> - with_channel(handle_info, [Info], State). - -%%-------------------------------------------------------------------- -%% Ensure rate limit - -ensure_rate_limit(Stats, State = #state{limiter = Limiter}) -> - case ?ENABLED(Limiter) andalso emqx_limiter:check(Stats, Limiter) of - false -> State; - {ok, Limiter1} -> - State#state{limiter = Limiter1}; - {pause, Time, Limiter1} -> - ?LOG(warning, "Pause ~pms due to rate limit", [Time]), - TRef = start_timer(Time, limit_timeout), - State#state{sockstate = blocked, - limiter = Limiter1, - limit_timer = TRef - } - end. - -%%-------------------------------------------------------------------- -%% Run GC and Check OOM - -run_gc(Stats, State = #state{gc_state = GcSt}) -> - case ?ENABLED(GcSt) andalso emqx_gc:run(Stats, GcSt) of - false -> State; - {_IsGC, GcSt1} -> - State#state{gc_state = GcSt1} - end. - -check_oom(State = #state{channel = Channel}) -> - Zone = emqx_channel:info(zone, Channel), - OomPolicy = emqx_zone:oom_policy(Zone), - case ?ENABLED(OomPolicy) andalso emqx_misc:check_oom(OomPolicy) of - Shutdown = {shutdown, _Reason} -> - erlang:send(self(), Shutdown); - _Other -> ok - end, - State. - -%%-------------------------------------------------------------------- -%% Activate Socket - --compile({inline, [activate_socket/1]}). -activate_socket(State = #state{sockstate = closed}) -> - {ok, State}; -activate_socket(State = #state{sockstate = blocked}) -> - {ok, State}; -activate_socket(State = #state{transport = Transport, - socket = Socket, - active_n = N}) -> - case Transport:setopts(Socket, [{active, N}]) of - ok -> {ok, State#state{sockstate = running}}; - Error -> Error - end. - -%%-------------------------------------------------------------------- -%% Close Socket - -close_socket(State = #state{sockstate = closed}) -> State; -close_socket(State = #state{transport = Transport, socket = Socket}) -> - ok = Transport:fast_close(Socket), - State#state{sockstate = closed}. - -%%-------------------------------------------------------------------- -%% Inc incoming/outgoing stats - --compile({inline, [inc_incoming_stats/1]}). -inc_incoming_stats(Packet = ?PACKET(Type)) -> - emqx_pd:inc_counter(recv_pkt, 1), - if - Type == ?PUBLISH -> - emqx_pd:inc_counter(recv_msg, 1), - emqx_pd:inc_counter(incoming_pubs, 1); - true -> ok - end, - emqx_metrics:inc_recv(Packet). - --compile({inline, [inc_outgoing_stats/1]}). -inc_outgoing_stats(Packet = ?PACKET(Type)) -> - emqx_pd:inc_counter(send_pkt, 1), - if - Type == ?PUBLISH -> - emqx_pd:inc_counter(send_msg, 1), - emqx_pd:inc_counter(outgoing_pubs, 1); - true -> ok - end, - emqx_metrics:inc_sent(Packet). - -%%-------------------------------------------------------------------- -%% Helper functions - --compile({inline, [next_msgs/1]}). -next_msgs(Packet) when is_record(Packet, mqtt_packet) -> - {outgoing, Packet}; -next_msgs(Event) when is_tuple(Event) -> - Event; -next_msgs(More) when is_list(More) -> - More. - --compile({inline, [shutdown/2, shutdown/3]}). -shutdown(Reason, State) -> - stop({shutdown, Reason}, State). - -shutdown(Reason, Reply, State) -> - stop({shutdown, Reason}, Reply, State). - --compile({inline, [stop/2, stop/3]}). -stop(Reason, State) -> - {stop, Reason, State}. - -stop(Reason, Reply, State) -> - {stop, Reason, Reply, State}. - -%%-------------------------------------------------------------------- -%% For CT tests -%%-------------------------------------------------------------------- - -set_field(Name, Value, State) -> - Pos = emqx_misc:index_of(Name, record_info(fields, state)), - setelement(Pos+1, State, Value). - diff --git a/_build/emqx/lib/emqx/src/emqx_ctl.erl b/_build/emqx/lib/emqx/src/emqx_ctl.erl deleted file mode 100644 index 45cf345438..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_ctl.erl +++ /dev/null @@ -1,234 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_ctl). - --behaviour(gen_server). - --include("types.hrl"). --include("logger.hrl"). - --logger_header("[Ctl]"). - --export([start_link/0, stop/0]). - --export([ register_command/2 - , register_command/3 - , unregister_command/1 - ]). - --export([ run_command/1 - , run_command/2 - , lookup_command/1 - , get_commands/0 - ]). - --export([ print/1 - , print/2 - , usage/1 - , usage/2 - ]). - -%% Exports mainly for test cases --export([ format/1 - , format/2 - , format_usage/1 - , format_usage/2 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --record(state, {seq = 0}). - --type(cmd() :: atom()). --type(cmd_params() :: string()). --type(cmd_descr() :: string()). --type(cmd_usage() :: {cmd_params(), cmd_descr()}). - --define(SERVER, ?MODULE). --define(CMD_TAB, emqx_command). - --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - --spec(stop() -> ok). -stop() -> gen_server:stop(?SERVER). - --spec(register_command(cmd(), {module(), atom()}) -> ok). -register_command(Cmd, MF) when is_atom(Cmd) -> - register_command(Cmd, MF, []). - --spec(register_command(cmd(), {module(), atom()}, list()) -> ok). -register_command(Cmd, MF, Opts) when is_atom(Cmd) -> - call({register_command, Cmd, MF, Opts}). - --spec(unregister_command(cmd()) -> ok). -unregister_command(Cmd) when is_atom(Cmd) -> - cast({unregister_command, Cmd}). - -call(Req) -> gen_server:call(?SERVER, Req). - -cast(Msg) -> gen_server:cast(?SERVER, Msg). - --spec(run_command(list(string())) -> ok | {error, term()}). -run_command([]) -> - run_command(help, []); -run_command([Cmd | Args]) -> - run_command(list_to_atom(Cmd), Args). - --spec(run_command(cmd(), list(string())) -> ok | {error, term()}). -run_command(help, []) -> help(); -run_command(Cmd, Args) when is_atom(Cmd) -> - case lookup_command(Cmd) of - [{Mod, Fun}] -> - try Mod:Fun(Args) of - _ -> ok - catch - _:Reason:Stacktrace -> - ?ERROR("CMD Error:~0p, Stacktrace:~0p", [Reason, Stacktrace]), - {error, Reason} - end; - [] -> - help(), {error, cmd_not_found} - end. - --spec(lookup_command(cmd()) -> [{module(), atom()}]). -lookup_command(Cmd) when is_atom(Cmd) -> - case ets:match(?CMD_TAB, {{'_', Cmd}, '$1', '_'}) of - [El] -> El; - [] -> [] - end. - --spec(get_commands() -> list({cmd(), module(), atom()})). -get_commands() -> - [{Cmd, M, F} || {{_Seq, Cmd}, {M, F}, _Opts} <- ets:tab2list(?CMD_TAB)]. - -help() -> - case ets:tab2list(?CMD_TAB) of - [] -> - print("No commands available.~n"); - Cmds -> - print("Usage: ~s~n", [?MODULE]), - lists:foreach(fun({_, {Mod, Cmd}, _}) -> - print("~110..-s~n", [""]), Mod:Cmd(usage) - end, Cmds) - end. - --spec(print(io:format()) -> ok). -print(Msg) -> - io:format(format(Msg)). - --spec(print(io:format(), [term()]) -> ok). -print(Format, Args) -> - io:format(format(Format, Args)). - --spec(usage([cmd_usage()]) -> ok). -usage(UsageList) -> - io:format(format_usage(UsageList)). - --spec(usage(cmd_params(), cmd_descr()) -> ok). -usage(CmdParams, Desc) -> - io:format(format_usage(CmdParams, Desc)). - --spec(format(io:format()) -> string()). -format(Msg) -> - lists:flatten(io_lib:format("~s", [Msg])). - --spec(format(io:format(), [term()]) -> string()). -format(Format, Args) -> - lists:flatten(io_lib:format(Format, Args)). - --spec(format_usage([cmd_usage()]) -> [string()]). -format_usage(UsageList) -> - lists:map( - fun({CmdParams, Desc}) -> - format_usage(CmdParams, Desc) - end, UsageList). - --spec(format_usage(cmd_params(), cmd_descr()) -> string()). -format_usage(CmdParams, Desc) -> - CmdLines = split_cmd(CmdParams), - DescLines = split_cmd(Desc), - lists:foldl(fun({CmdStr, DescStr}, Usage) -> - Usage ++ format("~-70s# ~s~n", [CmdStr, DescStr]) - end, "", zip_cmd(CmdLines, DescLines)). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - ok = emqx_tables:new(?CMD_TAB, [protected, ordered_set]), - {ok, #state{seq = 0}}. - -handle_call({register_command, Cmd, MF, Opts}, _From, State = #state{seq = Seq}) -> - case ets:match(?CMD_TAB, {{'$1', Cmd}, '_', '_'}) of - [] -> ets:insert(?CMD_TAB, {{Seq, Cmd}, MF, Opts}); - [[OriginSeq] | _] -> - ?LOG(warning, "CMD ~s is overidden by ~p", [Cmd, MF]), - true = ets:insert(?CMD_TAB, {{OriginSeq, Cmd}, MF, Opts}) - end, - {reply, ok, next_seq(State)}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({unregister_command, Cmd}, State) -> - ets:match_delete(?CMD_TAB, {{'_', Cmd}, '_', '_'}), - noreply(State); - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - noreply(State). - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - noreply(State). - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%------------------------------------------------------------------------------ -%% Internal Function -%%------------------------------------------------------------------------------ - -noreply(State) -> - {noreply, State, hibernate}. - -next_seq(State = #state{seq = Seq}) -> - State#state{seq = Seq + 1}. - -split_cmd(CmdStr) -> - Lines = string:split(CmdStr, "\n", all), - [L || L <- Lines, L =/= []]. - -zip_cmd([X | Xs], [Y | Ys]) -> [{X, Y} | zip_cmd(Xs, Ys)]; -zip_cmd([X | Xs], []) -> [{X, ""} | zip_cmd(Xs, [])]; -zip_cmd([], [Y | Ys]) -> [{"", Y} | zip_cmd([], Ys)]; -zip_cmd([], []) -> []. - diff --git a/_build/emqx/lib/emqx/src/emqx_flapping.erl b/_build/emqx/lib/emqx/src/emqx_flapping.erl deleted file mode 100644 index 36323d90fe..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_flapping.erl +++ /dev/null @@ -1,164 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_flapping). - --behaviour(gen_server). - --include("emqx.hrl"). --include("types.hrl"). --include("logger.hrl"). - --logger_header("[Flapping]"). - --export([start_link/0, stop/0]). - -%% API --export([detect/1]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - -%% Tab --define(FLAPPING_TAB, ?MODULE). -%% Default Policy --define(FLAPPING_THRESHOLD, 30). --define(FLAPPING_DURATION, 60000). --define(FLAPPING_BANNED_INTERVAL, 300000). --define(DEFAULT_DETECT_POLICY, - #{threshold => ?FLAPPING_THRESHOLD, - duration => ?FLAPPING_DURATION, - banned_interval => ?FLAPPING_BANNED_INTERVAL - }). - --record(flapping, { - clientid :: emqx_types:clientid(), - peerhost :: emqx_types:peerhost(), - started_at :: pos_integer(), - detect_cnt :: pos_integer() - }). - --opaque(flapping() :: #flapping{}). - --export_type([flapping/0]). - --spec(start_link() -> emqx_types:startlink_ret()). -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - -stop() -> gen_server:stop(?MODULE). - -%% @doc Detect flapping when a MQTT client disconnected. --spec(detect(emqx_types:clientinfo()) -> boolean()). -detect(Client) -> detect(Client, get_policy()). - -detect(#{clientid := ClientId, peerhost := PeerHost}, Policy = #{threshold := Threshold}) -> - try ets:update_counter(?FLAPPING_TAB, ClientId, {#flapping.detect_cnt, 1}) of - Cnt when Cnt < Threshold -> false; - _Cnt -> case ets:take(?FLAPPING_TAB, ClientId) of - [Flapping] -> - ok = gen_server:cast(?MODULE, {detected, Flapping, Policy}), - true; - [] -> false - end - catch - error:badarg -> - %% Create a flapping record. - Flapping = #flapping{clientid = ClientId, - peerhost = PeerHost, - started_at = erlang:system_time(millisecond), - detect_cnt = 1 - }, - true = ets:insert(?FLAPPING_TAB, Flapping), - false - end. - --compile({inline, [get_policy/0, now_diff/1]}). - -get_policy() -> - emqx:get_env(flapping_detect_policy, ?DEFAULT_DETECT_POLICY). - -now_diff(TS) -> erlang:system_time(millisecond) - TS. - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - ok = emqx_tables:new(?FLAPPING_TAB, [public, set, - {keypos, 2}, - {read_concurrency, true}, - {write_concurrency, true} - ]), - {ok, ensure_timer(#{}), hibernate}. - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({detected, #flapping{clientid = ClientId, - peerhost = PeerHost, - started_at = StartedAt, - detect_cnt = DetectCnt}, - #{duration := Duration, banned_interval := Interval}}, State) -> - case now_diff(StartedAt) < Duration of - true -> %% Flapping happened:( - ?LOG(error, "Flapping detected: ~s(~s) disconnected ~w times in ~wms", - [ClientId, inet:ntoa(PeerHost), DetectCnt, Duration]), - Now = erlang:system_time(second), - Banned = #banned{who = {clientid, ClientId}, - by = <<"flapping detector">>, - reason = <<"flapping is detected">>, - at = Now, - until = Now + Interval}, - alarm_handler:set_alarm({{flapping_detected, ClientId}, Banned}), - emqx_banned:create(Banned); - false -> - ?LOG(warning, "~s(~s) disconnected ~w times in ~wms", - [ClientId, inet:ntoa(PeerHost), DetectCnt, Interval]) - end, - {noreply, State}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({timeout, TRef, expired_detecting}, State = #{expired_timer := TRef}) -> - Timestamp = erlang:system_time(millisecond) - maps:get(duration, get_policy()), - MatchSpec = [{{'_', '_', '_', '$1', '_'},[{'<', '$1', Timestamp}], [true]}], - ets:select_delete(?FLAPPING_TAB, MatchSpec), - {noreply, ensure_timer(State), hibernate}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -ensure_timer(State) -> - Timeout = maps:get(duration, get_policy()), - TRef = emqx_misc:start_timer(Timeout, expired_detecting), - State#{expired_timer => TRef}. \ No newline at end of file diff --git a/_build/emqx/lib/emqx/src/emqx_frame.erl b/_build/emqx/lib/emqx/src/emqx_frame.erl deleted file mode 100644 index 1c27548f7a..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_frame.erl +++ /dev/null @@ -1,749 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_frame). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). - --export([ initial_parse_state/0 - , initial_parse_state/1 - ]). - --export([ parse/1 - , parse/2 - , serialize_fun/0 - , serialize_fun/1 - , serialize/1 - , serialize/2 - ]). - --export_type([ options/0 - , parse_state/0 - , parse_result/0 - , serialize_fun/0 - ]). - --type(options() :: #{strict_mode => boolean(), - max_size => 1..?MAX_PACKET_SIZE, - version => emqx_types:version() - }). - --type(parse_state() :: {none, options()} | cont_fun()). - --type(parse_result() :: {more, cont_fun()} - | {ok, emqx_types:packet(), binary(), parse_state()}). - --type(cont_fun() :: fun((binary()) -> parse_result())). - --type(serialize_fun() :: fun((emqx_types:packet()) -> iodata())). - --define(none(Options), {none, Options}). - --define(DEFAULT_OPTIONS, - #{strict_mode => false, - max_size => ?MAX_PACKET_SIZE, - version => ?MQTT_PROTO_V4 - }). - --dialyzer({no_match, [serialize_utf8_string/2]}). - -%%-------------------------------------------------------------------- -%% Init Parse State -%%-------------------------------------------------------------------- - --spec(initial_parse_state() -> {none, options()}). -initial_parse_state() -> - initial_parse_state(#{}). - --spec(initial_parse_state(options()) -> {none, options()}). -initial_parse_state(Options) when is_map(Options) -> - ?none(merge_opts(Options)). - -%% @pivate -merge_opts(Options) -> - maps:merge(?DEFAULT_OPTIONS, Options). - -%%-------------------------------------------------------------------- -%% Parse MQTT Frame -%%-------------------------------------------------------------------- - --spec(parse(binary()) -> parse_result()). -parse(Bin) -> - parse(Bin, initial_parse_state()). - --spec(parse(binary(), parse_state()) -> parse_result()). -parse(<<>>, {none, Options}) -> - {more, fun(Bin) -> parse(Bin, {none, Options}) end}; -parse(<>, - {none, Options = #{strict_mode := StrictMode}}) -> - %% Validate header if strict mode. - StrictMode andalso validate_header(Type, Dup, QoS, Retain), - Header = #mqtt_packet_header{type = Type, - dup = bool(Dup), - qos = QoS, - retain = bool(Retain) - }, - Header1 = case fixqos(Type, QoS) of - QoS -> Header; - FixedQoS -> Header#mqtt_packet_header{qos = FixedQoS} - end, - parse_remaining_len(Rest, Header1, Options); -parse(Bin, Cont) when is_binary(Bin), is_function(Cont) -> - Cont(Bin). - -parse_remaining_len(<<>>, Header, Options) -> - {more, fun(Bin) -> parse_remaining_len(Bin, Header, Options) end}; -parse_remaining_len(Rest, Header, Options) -> - parse_remaining_len(Rest, Header, 1, 0, Options). - -parse_remaining_len(_Bin, _Header, _Multiplier, Length, #{max_size := MaxSize}) - when Length > MaxSize -> - error(frame_too_large); -parse_remaining_len(<<>>, Header, Multiplier, Length, Options) -> - {more, fun(Bin) -> parse_remaining_len(Bin, Header, Multiplier, Length, Options) end}; -%% Match DISCONNECT without payload -parse_remaining_len(<<0:8, Rest/binary>>, Header = #mqtt_packet_header{type = ?DISCONNECT}, 1, 0, Options) -> - Packet = packet(Header, #mqtt_packet_disconnect{reason_code = ?RC_SUCCESS}), - {ok, Packet, Rest, ?none(Options)}; -%% Match PINGREQ. -parse_remaining_len(<<0:8, Rest/binary>>, Header, 1, 0, Options) -> - parse_frame(Rest, Header, 0, Options); -%% Match PUBACK, PUBREC, PUBREL, PUBCOMP, UNSUBACK... -parse_remaining_len(<<0:1, 2:7, Rest/binary>>, Header, 1, 0, Options) -> - parse_frame(Rest, Header, 2, Options); -parse_remaining_len(<<1:1, Len:7, Rest/binary>>, Header, Multiplier, Value, Options) -> - parse_remaining_len(Rest, Header, Multiplier * ?HIGHBIT, Value + Len * Multiplier, Options); -parse_remaining_len(<<0:1, Len:7, Rest/binary>>, Header, Multiplier, Value, - Options = #{max_size := MaxSize}) -> - FrameLen = Value + Len * Multiplier, - if - FrameLen > MaxSize -> error(frame_too_large); - true -> parse_frame(Rest, Header, FrameLen, Options) - end. - -parse_frame(Bin, Header, 0, Options) -> - {ok, packet(Header), Bin, ?none(Options)}; - -parse_frame(Bin, Header, Length, Options) -> - case Bin of - <> -> - case parse_packet(Header, FrameBin, Options) of - {Variable, Payload} -> - {ok, packet(Header, Variable, Payload), Rest, ?none(Options)}; - Variable = #mqtt_packet_connect{proto_ver = Ver} -> - {ok, packet(Header, Variable), Rest, ?none(Options#{version := Ver})}; - Variable -> - {ok, packet(Header, Variable), Rest, ?none(Options)} - end; - TooShortBin -> - {more, fun(BinMore) -> - parse_frame(<>, Header, Length, Options) - end} - end. - --compile({inline, [packet/1, packet/2, packet/3]}). -packet(Header) -> - #mqtt_packet{header = Header}. -packet(Header, Variable) -> - #mqtt_packet{header = Header, variable = Variable}. -packet(Header, Variable, Payload) -> - #mqtt_packet{header = Header, variable = Variable, payload = Payload}. - -parse_packet(#mqtt_packet_header{type = ?CONNECT}, FrameBin, _Options) -> - {ProtoName, Rest} = parse_utf8_string(FrameBin), - <> = Rest, - % Note: Crash when reserved flag doesn't equal to 0, there is no strict - % compliance with the MQTT5.0. - <> = Rest1, - - {Properties, Rest3} = parse_properties(Rest2, ProtoVer), - {ClientId, Rest4} = parse_utf8_string(Rest3), - ConnPacket = #mqtt_packet_connect{proto_name = ProtoName, - proto_ver = ProtoVer, - is_bridge = (BridgeTag =:= 8), - clean_start = bool(CleanStart), - will_flag = bool(WillFlag), - will_qos = WillQoS, - will_retain = bool(WillRetain), - keepalive = KeepAlive, - properties = Properties, - clientid = ClientId - }, - {ConnPacket1, Rest5} = parse_will_message(ConnPacket, Rest4), - {Username, Rest6} = parse_utf8_string(Rest5, bool(UsernameFlag)), - {Passsword, <<>>} = parse_utf8_string(Rest6, bool(PasswordFlag)), - ConnPacket1#mqtt_packet_connect{username = Username, password = Passsword}; - -parse_packet(#mqtt_packet_header{type = ?CONNACK}, - <>, #{version := Ver}) -> - {Properties, <<>>} = parse_properties(Rest, Ver), - #mqtt_packet_connack{ack_flags = AckFlags, - reason_code = ReasonCode, - properties = Properties - }; - -parse_packet(#mqtt_packet_header{type = ?PUBLISH, qos = QoS}, Bin, - #{strict_mode := StrictMode, version := Ver}) -> - {TopicName, Rest} = parse_utf8_string(Bin), - {PacketId, Rest1} = case QoS of - ?QOS_0 -> {undefined, Rest}; - _ -> parse_packet_id(Rest) - end, - (PacketId =/= undefined) andalso - StrictMode andalso validate_packet_id(PacketId), - {Properties, Payload} = parse_properties(Rest1, Ver), - Publish = #mqtt_packet_publish{topic_name = TopicName, - packet_id = PacketId, - properties = Properties - }, - {Publish, Payload}; - -parse_packet(#mqtt_packet_header{type = PubAck}, <>, #{strict_mode := StrictMode}) - when ?PUBACK =< PubAck, PubAck =< ?PUBCOMP -> - StrictMode andalso validate_packet_id(PacketId), - #mqtt_packet_puback{packet_id = PacketId, reason_code = 0}; - -parse_packet(#mqtt_packet_header{type = PubAck}, <>, - #{strict_mode := StrictMode, version := Ver = ?MQTT_PROTO_V5}) - when ?PUBACK =< PubAck, PubAck =< ?PUBCOMP -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, <<>>} = parse_properties(Rest, Ver), - #mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties - }; - -parse_packet(#mqtt_packet_header{type = ?SUBSCRIBE}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - TopicFilters = parse_topic_filters(subscribe, Rest1), - ok = validate_subqos([QoS || {_, #{qos := QoS}} <- TopicFilters]), - #mqtt_packet_subscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters - }; - -parse_packet(#mqtt_packet_header{type = ?SUBACK}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - ReasonCodes = parse_reason_codes(Rest1), - #mqtt_packet_suback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes - }; - -parse_packet(#mqtt_packet_header{type = ?UNSUBSCRIBE}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - TopicFilters = parse_topic_filters(unsubscribe, Rest1), - #mqtt_packet_unsubscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters - }; - -parse_packet(#mqtt_packet_header{type = ?UNSUBACK}, <>, - #{strict_mode := StrictMode}) -> - StrictMode andalso validate_packet_id(PacketId), - #mqtt_packet_unsuback{packet_id = PacketId}; - -parse_packet(#mqtt_packet_header{type = ?UNSUBACK}, <>, - #{strict_mode := StrictMode, version := Ver}) -> - StrictMode andalso validate_packet_id(PacketId), - {Properties, Rest1} = parse_properties(Rest, Ver), - ReasonCodes = parse_reason_codes(Rest1), - #mqtt_packet_unsuback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes - }; - -parse_packet(#mqtt_packet_header{type = ?DISCONNECT}, <>, - #{version := ?MQTT_PROTO_V5}) -> - {Properties, <<>>} = parse_properties(Rest, ?MQTT_PROTO_V5), - #mqtt_packet_disconnect{reason_code = ReasonCode, - properties = Properties - }; - -parse_packet(#mqtt_packet_header{type = ?AUTH}, <>, - #{version := ?MQTT_PROTO_V5}) -> - {Properties, <<>>} = parse_properties(Rest, ?MQTT_PROTO_V5), - #mqtt_packet_auth{reason_code = ReasonCode, properties = Properties}. - -parse_will_message(Packet = #mqtt_packet_connect{will_flag = true, - proto_ver = Ver}, Bin) -> - {Props, Rest} = parse_properties(Bin, Ver), - {Topic, Rest1} = parse_utf8_string(Rest), - {Payload, Rest2} = parse_binary_data(Rest1), - {Packet#mqtt_packet_connect{will_props = Props, - will_topic = Topic, - will_payload = Payload - }, Rest2}; -parse_will_message(Packet, Bin) -> {Packet, Bin}. - --compile({inline, [parse_packet_id/1]}). -parse_packet_id(<>) -> - {PacketId, Rest}. - -parse_properties(Bin, Ver) when Ver =/= ?MQTT_PROTO_V5 -> - {#{}, Bin}; -%% TODO: version mess? -parse_properties(<<>>, ?MQTT_PROTO_V5) -> - {#{}, <<>>}; -parse_properties(<<0, Rest/binary>>, ?MQTT_PROTO_V5) -> - {#{}, Rest}; -parse_properties(Bin, ?MQTT_PROTO_V5) -> - {Len, Rest} = parse_variable_byte_integer(Bin), - <> = Rest, - {parse_property(PropsBin, #{}), Rest1}. - -parse_property(<<>>, Props) -> - Props; -parse_property(<<16#01, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Payload-Format-Indicator' => Val}); -parse_property(<<16#02, Val:32/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Message-Expiry-Interval' => Val}); -parse_property(<<16#03, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Content-Type' => Val}); -parse_property(<<16#08, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Response-Topic' => Val}); -parse_property(<<16#09, Len:16/big, Val:Len/binary, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Correlation-Data' => Val}); -parse_property(<<16#0B, Bin/binary>>, Props) -> - {Val, Rest} = parse_variable_byte_integer(Bin), - parse_property(Rest, Props#{'Subscription-Identifier' => Val}); -parse_property(<<16#11, Val:32/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Session-Expiry-Interval' => Val}); -parse_property(<<16#12, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Assigned-Client-Identifier' => Val}); -parse_property(<<16#13, Val:16, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Server-Keep-Alive' => Val}); -parse_property(<<16#15, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Authentication-Method' => Val}); -parse_property(<<16#16, Len:16/big, Val:Len/binary, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Authentication-Data' => Val}); -parse_property(<<16#17, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Request-Problem-Information' => Val}); -parse_property(<<16#18, Val:32, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Will-Delay-Interval' => Val}); -parse_property(<<16#19, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Request-Response-Information' => Val}); -parse_property(<<16#1A, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Response-Information' => Val}); -parse_property(<<16#1C, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Server-Reference' => Val}); -parse_property(<<16#1F, Bin/binary>>, Props) -> - {Val, Rest} = parse_utf8_string(Bin), - parse_property(Rest, Props#{'Reason-String' => Val}); -parse_property(<<16#21, Val:16/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Receive-Maximum' => Val}); -parse_property(<<16#22, Val:16/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Topic-Alias-Maximum' => Val}); -parse_property(<<16#23, Val:16/big, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Topic-Alias' => Val}); -parse_property(<<16#24, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Maximum-QoS' => Val}); -parse_property(<<16#25, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Retain-Available' => Val}); -parse_property(<<16#26, Bin/binary>>, Props) -> - {Pair, Rest} = parse_utf8_pair(Bin), - case maps:find('User-Property', Props) of - {ok, UserProps} -> - UserProps1 = lists:append(UserProps, [Pair]), - parse_property(Rest, Props#{'User-Property' := UserProps1}); - error -> - parse_property(Rest, Props#{'User-Property' => [Pair]}) - end; -parse_property(<<16#27, Val:32, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Maximum-Packet-Size' => Val}); -parse_property(<<16#28, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Wildcard-Subscription-Available' => Val}); -parse_property(<<16#29, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Subscription-Identifier-Available' => Val}); -parse_property(<<16#2A, Val, Bin/binary>>, Props) -> - parse_property(Bin, Props#{'Shared-Subscription-Available' => Val}). - -parse_variable_byte_integer(Bin) -> - parse_variable_byte_integer(Bin, 1, 0). -parse_variable_byte_integer(<<1:1, Len:7, Rest/binary>>, Multiplier, Value) -> - parse_variable_byte_integer(Rest, Multiplier * ?HIGHBIT, Value + Len * Multiplier); -parse_variable_byte_integer(<<0:1, Len:7, Rest/binary>>, Multiplier, Value) -> - {Value + Len * Multiplier, Rest}. - -parse_topic_filters(subscribe, Bin) -> - [{Topic, #{rh => Rh, rap => Rap, nl => Nl, qos => QoS}} - || <> <= Bin]; - -parse_topic_filters(unsubscribe, Bin) -> - [Topic || <> <= Bin]. - -parse_reason_codes(Bin) -> - [Code || <> <= Bin]. - -parse_utf8_pair(<>) -> - {{Key, Val}, Rest}. - -parse_utf8_string(Bin, false) -> - {undefined, Bin}; -parse_utf8_string(Bin, true) -> - parse_utf8_string(Bin). - -parse_utf8_string(<>) -> - {Str, Rest}. - -parse_binary_data(<>) -> - {Data, Rest}. - -%%-------------------------------------------------------------------- -%% Serialize MQTT Packet -%%-------------------------------------------------------------------- - -serialize_fun() -> serialize_fun(?DEFAULT_OPTIONS). - -serialize_fun(#mqtt_packet_connect{proto_ver = ProtoVer, properties = ConnProps}) -> - MaxSize = get_property('Maximum-Packet-Size', ConnProps, ?MAX_PACKET_SIZE), - serialize_fun(#{version => ProtoVer, max_size => MaxSize}); - -serialize_fun(#{version := Ver, max_size := MaxSize}) -> - fun(Packet) -> - IoData = serialize(Packet, Ver), - case is_too_large(IoData, MaxSize) of - true -> <<>>; - false -> IoData - end - end. - --spec(serialize(emqx_types:packet()) -> iodata()). -serialize(Packet) -> serialize(Packet, ?MQTT_PROTO_V4). - --spec(serialize(emqx_types:packet(), emqx_types:version()) -> iodata()). -serialize(#mqtt_packet{header = Header, - variable = Variable, - payload = Payload}, Ver) -> - serialize(Header, serialize_variable(Variable, Ver), serialize_payload(Payload)). - -serialize(#mqtt_packet_header{type = Type, - dup = Dup, - qos = QoS, - retain = Retain - }, VariableBin, PayloadBin) - when ?CONNECT =< Type andalso Type =< ?AUTH -> - Len = iolist_size(VariableBin) + iolist_size(PayloadBin), - [<>, - serialize_remaining_len(Len), VariableBin, PayloadBin]. - -serialize_variable(#mqtt_packet_connect{ - proto_name = ProtoName, - proto_ver = ProtoVer, - is_bridge = IsBridge, - clean_start = CleanStart, - will_flag = WillFlag, - will_qos = WillQoS, - will_retain = WillRetain, - keepalive = KeepAlive, - properties = Properties, - clientid = ClientId, - will_props = WillProps, - will_topic = WillTopic, - will_payload = WillPayload, - username = Username, - password = Password}, _Ver) -> - [serialize_binary_data(ProtoName), - <<(case IsBridge of - true -> 16#80 + ProtoVer; - false -> ProtoVer - end):8, - (flag(Username)):1, - (flag(Password)):1, - (flag(WillRetain)):1, - WillQoS:2, - (flag(WillFlag)):1, - (flag(CleanStart)):1, - 0:1, - KeepAlive:16/big-unsigned-integer>>, - serialize_properties(Properties, ProtoVer), - serialize_utf8_string(ClientId), - case WillFlag of - true -> [serialize_properties(WillProps, ProtoVer), - serialize_utf8_string(WillTopic), - serialize_binary_data(WillPayload)]; - false -> <<>> - end, - serialize_utf8_string(Username, true), - serialize_utf8_string(Password, true)]; - -serialize_variable(#mqtt_packet_connack{ack_flags = AckFlags, - reason_code = ReasonCode, - properties = Properties}, Ver) -> - [AckFlags, ReasonCode, serialize_properties(Properties, Ver)]; - -serialize_variable(#mqtt_packet_publish{topic_name = TopicName, - packet_id = PacketId, - properties = Properties}, Ver) -> - [serialize_utf8_string(TopicName), - if - PacketId =:= undefined -> <<>>; - true -> <> - end, - serialize_properties(Properties, Ver)]; - -serialize_variable(#mqtt_packet_puback{packet_id = PacketId}, Ver) - when Ver == ?MQTT_PROTO_V3; Ver == ?MQTT_PROTO_V4 -> - <>; -serialize_variable(#mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode, - properties = Properties - }, - Ver = ?MQTT_PROTO_V5) -> - [<>, ReasonCode, - serialize_properties(Properties, Ver)]; - -serialize_variable(#mqtt_packet_subscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_topic_filters(subscribe, TopicFilters, Ver)]; - -serialize_variable(#mqtt_packet_suback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_reason_codes(ReasonCodes)]; - -serialize_variable(#mqtt_packet_unsubscribe{packet_id = PacketId, - properties = Properties, - topic_filters = TopicFilters}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_topic_filters(unsubscribe, TopicFilters, Ver)]; - -serialize_variable(#mqtt_packet_unsuback{packet_id = PacketId, - properties = Properties, - reason_codes = ReasonCodes}, Ver) -> - [<>, serialize_properties(Properties, Ver), - serialize_reason_codes(ReasonCodes)]; - -serialize_variable(#mqtt_packet_disconnect{}, Ver) - when Ver == ?MQTT_PROTO_V3; Ver == ?MQTT_PROTO_V4 -> - <<>>; - -serialize_variable(#mqtt_packet_disconnect{reason_code = ReasonCode, - properties = Properties}, - Ver = ?MQTT_PROTO_V5) -> - [ReasonCode, serialize_properties(Properties, Ver)]; -serialize_variable(#mqtt_packet_disconnect{}, _Ver) -> - <<>>; - -serialize_variable(#mqtt_packet_auth{reason_code = ReasonCode, - properties = Properties}, - Ver = ?MQTT_PROTO_V5) -> - [ReasonCode, serialize_properties(Properties, Ver)]; - -serialize_variable(PacketId, ?MQTT_PROTO_V3) when is_integer(PacketId) -> - <>; -serialize_variable(PacketId, ?MQTT_PROTO_V4) when is_integer(PacketId) -> - <>; -serialize_variable(undefined, _Ver) -> - <<>>. - -serialize_payload(undefined) -> <<>>; -serialize_payload(Bin) -> Bin. - -serialize_properties(_Props, Ver) when Ver =/= ?MQTT_PROTO_V5 -> - <<>>; -serialize_properties(Props, ?MQTT_PROTO_V5) -> - serialize_properties(Props). - -serialize_properties(undefined) -> - <<0>>; -serialize_properties(Props) when map_size(Props) == 0 -> - <<0>>; -serialize_properties(Props) when is_map(Props) -> - Bin = << <<(serialize_property(Prop, Val))/binary>> || {Prop, Val} <- maps:to_list(Props) >>, - [serialize_variable_byte_integer(byte_size(Bin)), Bin]. - -serialize_property(_, undefined) -> - <<>>; -serialize_property('Payload-Format-Indicator', Val) -> - <<16#01, Val>>; -serialize_property('Message-Expiry-Interval', Val) -> - <<16#02, Val:32/big>>; -serialize_property('Content-Type', Val) -> - <<16#03, (serialize_utf8_string(Val))/binary>>; -serialize_property('Response-Topic', Val) -> - <<16#08, (serialize_utf8_string(Val))/binary>>; -serialize_property('Correlation-Data', Val) -> - <<16#09, (byte_size(Val)):16, Val/binary>>; -serialize_property('Subscription-Identifier', Val) -> - <<16#0B, (serialize_variable_byte_integer(Val))/binary>>; -serialize_property('Session-Expiry-Interval', Val) -> - <<16#11, Val:32/big>>; -serialize_property('Assigned-Client-Identifier', Val) -> - <<16#12, (serialize_utf8_string(Val))/binary>>; -serialize_property('Server-Keep-Alive', Val) -> - <<16#13, Val:16/big>>; -serialize_property('Authentication-Method', Val) -> - <<16#15, (serialize_utf8_string(Val))/binary>>; -serialize_property('Authentication-Data', Val) -> - <<16#16, (iolist_size(Val)):16, Val/binary>>; -serialize_property('Request-Problem-Information', Val) -> - <<16#17, Val>>; -serialize_property('Will-Delay-Interval', Val) -> - <<16#18, Val:32/big>>; -serialize_property('Request-Response-Information', Val) -> - <<16#19, Val>>; -serialize_property('Response-Information', Val) -> - <<16#1A, (serialize_utf8_string(Val))/binary>>; -serialize_property('Server-Reference', Val) -> - <<16#1C, (serialize_utf8_string(Val))/binary>>; -serialize_property('Reason-String', Val) -> - <<16#1F, (serialize_utf8_string(Val))/binary>>; -serialize_property('Receive-Maximum', Val) -> - <<16#21, Val:16/big>>; -serialize_property('Topic-Alias-Maximum', Val) -> - <<16#22, Val:16/big>>; -serialize_property('Topic-Alias', Val) -> - <<16#23, Val:16/big>>; -serialize_property('Maximum-QoS', Val) -> - <<16#24, Val>>; -serialize_property('Retain-Available', Val) -> - <<16#25, Val>>; -serialize_property('User-Property', {Key, Val}) -> - <<16#26, (serialize_utf8_pair({Key, Val}))/binary>>; -serialize_property('User-Property', Props) when is_list(Props) -> - << <<(serialize_property('User-Property', {Key, Val}))/binary>> - || {Key, Val} <- Props >>; -serialize_property('Maximum-Packet-Size', Val) -> - <<16#27, Val:32/big>>; -serialize_property('Wildcard-Subscription-Available', Val) -> - <<16#28, Val>>; -serialize_property('Subscription-Identifier-Available', Val) -> - <<16#29, Val>>; -serialize_property('Shared-Subscription-Available', Val) -> - <<16#2A, Val>>. - -serialize_topic_filters(subscribe, TopicFilters, ?MQTT_PROTO_V5) -> - << <<(serialize_utf8_string(Topic))/binary, - ?RESERVED:2, Rh:2, (flag(Rap)):1,(flag(Nl)):1, QoS:2 >> - || {Topic, #{rh := Rh, rap := Rap, nl := Nl, qos := QoS}} <- TopicFilters >>; - -serialize_topic_filters(subscribe, TopicFilters, _Ver) -> - << <<(serialize_utf8_string(Topic))/binary, ?RESERVED:6, QoS:2>> - || {Topic, #{qos := QoS}} <- TopicFilters >>; - -serialize_topic_filters(unsubscribe, TopicFilters, _Ver) -> - << <<(serialize_utf8_string(Topic))/binary>> || Topic <- TopicFilters >>. - -serialize_reason_codes(undefined) -> - <<>>; -serialize_reason_codes(ReasonCodes) when is_list(ReasonCodes) -> - << <> || Code <- ReasonCodes >>. - -serialize_utf8_pair({Name, Value}) -> - << (serialize_utf8_string(Name))/binary, (serialize_utf8_string(Value))/binary >>. - -serialize_binary_data(Bin) -> - [<<(byte_size(Bin)):16/big-unsigned-integer>>, Bin]. - -serialize_utf8_string(undefined, false) -> - error(utf8_string_undefined); -serialize_utf8_string(undefined, true) -> - <<>>; -serialize_utf8_string(String, _AllowNull) -> - serialize_utf8_string(String). - -serialize_utf8_string(String) -> - StringBin = unicode:characters_to_binary(String), - Len = byte_size(StringBin), - true = (Len =< 16#ffff), - <>. - -serialize_remaining_len(I) -> - serialize_variable_byte_integer(I). - -serialize_variable_byte_integer(N) when N =< ?LOWBITS -> - <<0:1, N:7>>; -serialize_variable_byte_integer(N) -> - <<1:1, (N rem ?HIGHBIT):7, (serialize_variable_byte_integer(N div ?HIGHBIT))/binary>>. - -%% Is the frame too large? --spec(is_too_large(iodata(), pos_integer()) -> boolean()). -is_too_large(IoData, MaxSize) -> - iolist_size(IoData) >= MaxSize. - -get_property(_Key, undefined, Default) -> - Default; -get_property(Key, Props, Default) -> - maps:get(Key, Props, Default). - -%% Validate header if sctrict mode. See: mqtt-v5.0: 2.1.3 Flags -validate_header(?CONNECT, 0, 0, 0) -> ok; -validate_header(?CONNACK, 0, 0, 0) -> ok; -validate_header(?PUBLISH, 0, ?QOS_0, _) -> ok; -validate_header(?PUBLISH, _, ?QOS_1, _) -> ok; -validate_header(?PUBLISH, 0, ?QOS_2, _) -> ok; -validate_header(?PUBACK, 0, 0, 0) -> ok; -validate_header(?PUBREC, 0, 0, 0) -> ok; -validate_header(?PUBREL, 0, 1, 0) -> ok; -validate_header(?PUBCOMP, 0, 0, 0) -> ok; -validate_header(?SUBSCRIBE, 0, 1, 0) -> ok; -validate_header(?SUBACK, 0, 0, 0) -> ok; -validate_header(?UNSUBSCRIBE, 0, 1, 0) -> ok; -validate_header(?UNSUBACK, 0, 0, 0) -> ok; -validate_header(?PINGREQ, 0, 0, 0) -> ok; -validate_header(?PINGRESP, 0, 0, 0) -> ok; -validate_header(?DISCONNECT, 0, 0, 0) -> ok; -validate_header(?AUTH, 0, 0, 0) -> ok; -validate_header(_Type, _Dup, _QoS, _Rt) -> error(bad_frame_header). - --compile({inline, [validate_packet_id/1]}). -validate_packet_id(0) -> error(bad_packet_id); -validate_packet_id(_) -> ok. - -validate_subqos([3|_]) -> error(bad_subqos); -validate_subqos([_|T]) -> validate_subqos(T); -validate_subqos([]) -> ok. - -bool(0) -> false; -bool(1) -> true. - -flag(undefined) -> ?RESERVED; -flag(false) -> 0; -flag(true) -> 1; -flag(X) when is_integer(X) -> X; -flag(B) when is_binary(B) -> 1. - -fixqos(?PUBREL, 0) -> 1; -fixqos(?SUBSCRIBE, 0) -> 1; -fixqos(?UNSUBSCRIBE, 0) -> 1; -fixqos(_Type, QoS) -> QoS. - diff --git a/_build/emqx/lib/emqx/src/emqx_gc.erl b/_build/emqx/lib/emqx/src/emqx_gc.erl deleted file mode 100644 index 3bf826f736..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_gc.erl +++ /dev/null @@ -1,116 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%%-------------------------------------------------------------------- -%% @doc -%% This module manages an opaque collection of statistics data used to -%% force garbage collection on `self()' process when hitting thresholds. -%% Namely: -%% (1) Total number of messages passed through -%% (2) Total data volume passed through -%% @end -%%-------------------------------------------------------------------- - --module(emqx_gc). - --include("types.hrl"). - --export([ init/1 - , run/2 - , run/3 - , info/1 - , reset/1 - ]). - --export_type([opts/0, gc_state/0]). - --type(opts() :: #{count => integer(), - bytes => integer()}). - --type(st() :: #{cnt => {integer(), integer()}, - oct => {integer(), integer()}}). - --opaque(gc_state() :: {gc_state, st()}). - --define(GCS(St), {gc_state, St}). - --define(disabled, disabled). --define(ENABLED(X), (is_integer(X) andalso X > 0)). - -%% @doc Initialize force GC state. --spec(init(opts()) -> gc_state()). -init(#{count := Count, bytes := Bytes}) -> - Cnt = [{cnt, {Count, Count}} || ?ENABLED(Count)], - Oct = [{oct, {Bytes, Bytes}} || ?ENABLED(Bytes)], - ?GCS(maps:from_list(Cnt ++ Oct)). - -%% @doc Try to run GC based on reduntions of count or bytes. --spec(run(#{cnt := pos_integer(), oct := pos_integer()}, gc_state()) - -> {boolean(), gc_state()}). -run(#{cnt := Cnt, oct := Oct}, GcSt) -> - run(Cnt, Oct, GcSt). - --spec(run(pos_integer(), pos_integer(), gc_state()) - -> {boolean(), gc_state()}). -run(Cnt, Oct, ?GCS(St)) -> - {Res, St1} = do_run([{cnt, Cnt}, {oct, Oct}], St), - {Res, ?GCS(St1)}. - -do_run([], St) -> - {false, St}; -do_run([{K, N}|T], St) -> - case dec(K, N, St) of - {true, St1} -> - erlang:garbage_collect(), - {true, do_reset(St1)}; - {false, St1} -> - do_run(T, St1) - end. - -%% @doc Info of GC state. --spec(info(maybe(gc_state())) -> maybe(map())). -info(?GCS(St)) -> St. - -%% @doc Reset counters to zero. --spec(reset(maybe(gc_state())) -> gc_state()). -reset(?GCS(St)) -> - ?GCS(do_reset(St)). - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - --spec(dec(cnt | oct, pos_integer(), st()) -> {boolean(), st()}). -dec(Key, Num, St) -> - case maps:get(Key, St, ?disabled) of - ?disabled -> - {false, St}; - {Init, Remain} when Remain > Num -> - {false, maps:put(Key, {Init, Remain - Num}, St)}; - _ -> - {true, St} - end. - -do_reset(St) -> - do_reset(cnt, do_reset(oct, St)). - -%% Reset counters to zero. -do_reset(Key, St) -> - case maps:get(Key, St, ?disabled) of - ?disabled -> St; - {Init, _} -> maps:put(Key, {Init, Init}, St) - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_gen_mod.erl b/_build/emqx/lib/emqx/src/emqx_gen_mod.erl deleted file mode 100644 index 26a3c13cb9..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_gen_mod.erl +++ /dev/null @@ -1,23 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_gen_mod). - --callback(load(Opts :: any()) -> ok | {error, term()}). - --callback(unload(State :: term()) -> term()). - --callback(description() -> any()). diff --git a/_build/emqx/lib/emqx/src/emqx_global_gc.erl b/_build/emqx/lib/emqx/src/emqx_global_gc.erl deleted file mode 100644 index da953e347a..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_global_gc.erl +++ /dev/null @@ -1,102 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_global_gc). - --behaviour(gen_server). - --include("types.hrl"). - --export([start_link/0, stop/0]). - --export([run/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - -%% 5 minutes -%% -define(DEFAULT_INTERVAL, 300000). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - --spec(run() -> {ok, timer:time()}). -run() -> gen_server:call(?MODULE, run, infinity). - --spec(stop() -> ok). -stop() -> gen_server:stop(?MODULE). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - {ok, ensure_timer(#{timer => undefined})}. - -handle_call(run, _From, State) -> - {Time, ok} = timer:tc(fun run_gc/0), - {reply, {ok, Time div 1000}, State, hibernate}; - -handle_call(_Req, _From, State) -> - {reply, ignored, State}. - -handle_cast(_Msg, State) -> - {noreply, State}. - -handle_info({timeout, TRef, run}, State = #{timer := TRef}) -> - ok = run_gc(), - {noreply, ensure_timer(State), hibernate}; - -handle_info(_Info, State) -> - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internel function -%%-------------------------------------------------------------------- - -ensure_timer(State) -> - case emqx:get_env(global_gc_interval) of - undefined -> State; - Interval -> TRef = emqx_misc:start_timer(timer:seconds(Interval), run), - State#{timer := TRef} - end. - -run_gc() -> lists:foreach(fun do_gc/1, processes()). - -do_gc(Pid) -> - is_waiting(Pid) andalso garbage_collect(Pid). - --compile({inline, [is_waiting/1]}). -is_waiting(Pid) -> - {status, waiting} == process_info(Pid, status). - diff --git a/_build/emqx/lib/emqx/src/emqx_guid.erl b/_build/emqx/lib/emqx/src/emqx_guid.erl deleted file mode 100644 index 77f8c1e410..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_guid.erl +++ /dev/null @@ -1,135 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc Generate global unique id for mqtt message. -%% -%% -------------------------------------------------------- -%% | Timestamp | NodeID + PID | Sequence | -%% |<------- 64bits ------->|<--- 48bits --->|<- 16bits ->| -%% -------------------------------------------------------- -%% -%% 1. Timestamp: erlang:system_time if Erlang >= R18, otherwise os:timestamp -%% 2. NodeId: encode node() to 2 bytes integer -%% 3. Pid: encode pid to 4 bytes integer -%% 4. Sequence: 2 bytes sequence in one process -%% -%% @end - --module(emqx_guid). - --export([ gen/0 - , new/0 - , timestamp/1 - , to_hexstr/1 - , from_hexstr/1 - , to_base62/1 - , from_base62/1 - ]). - --define(MAX_SEQ, 16#FFFF). - --type(guid() :: <<_:128>>). - -%% @doc Generate a global unique id. --spec(gen() -> guid()). -gen() -> - Guid = case get(guid) of - undefined -> new(); - {_Ts, NPid, Seq} -> next(NPid, Seq) - end, - put(guid, Guid), bin(Guid). - -new() -> - {ts(), npid(), 0}. - --spec(timestamp(guid()) -> integer()). -timestamp(<>) -> - Ts. - -next(NPid, Seq) when Seq >= ?MAX_SEQ -> - {ts(), NPid, 0}; -next(NPid, Seq) -> - {ts(), NPid, Seq + 1}. - -bin({Ts, NPid, Seq}) -> - <>. - -ts() -> erlang:system_time(micro_seconds). - -%% Copied from https://hub.fastgit.org/okeuday/uuid.git. -npid() -> - <> = - crypto:hash(sha, erlang:list_to_binary(erlang:atom_to_list(node()))), - - % later, when the pid format changes, handle the different format - ExternalTermFormatVersion = 131, - PidExtType = 103, - <> = erlang:term_to_binary(self()), - % 72 bits for the Erlang pid - <> = binary:part(PidBin, erlang:byte_size(PidBin), -9), - - % reduce the 160 bit NodeData checksum to 16 bits - NodeByte1 = ((((((((NodeD01 bxor NodeD02) - bxor NodeD03) - bxor NodeD04) - bxor NodeD05) - bxor NodeD06) - bxor NodeD07) - bxor NodeD08) - bxor NodeD09) - bxor NodeD10, - NodeByte2 = (((((((((NodeD11 bxor NodeD12) - bxor NodeD13) - bxor NodeD14) - bxor NodeD15) - bxor NodeD16) - bxor NodeD17) - bxor NodeD18) - bxor NodeD19) - bxor NodeD20) - bxor PidCR1, - - % reduce the Erlang pid to 32 bits - PidByte1 = PidID1 bxor PidSR4, - PidByte2 = PidID2 bxor PidSR3, - PidByte3 = PidID3 bxor PidSR2, - PidByte4 = PidID4 bxor PidSR1, - - <> = <>, - NPid. - -to_hexstr(<>) -> - list_to_binary(integer_to_list(I, 16)). - -from_hexstr(S) -> - I = list_to_integer(binary_to_list(S), 16), <>. - -to_base62(<>) -> - emqx_base62:encode(I). - -from_base62(S) -> - I = binary_to_integer( emqx_base62:decode(S)), - <>. diff --git a/_build/emqx/lib/emqx/src/emqx_hooks.erl b/_build/emqx/lib/emqx/src/emqx_hooks.erl deleted file mode 100644 index 273071d75c..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_hooks.erl +++ /dev/null @@ -1,264 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_hooks). - --behaviour(gen_server). - --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Hooks]"). - --export([ start_link/0 - , stop/0 - ]). - -%% Hooks API --export([ add/2 - , add/3 - , add/4 - , del/2 - , run/2 - , run_fold/3 - , lookup/1 - ]). - -%% gen_server Function Exports --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --export_type([ hookpoint/0 - , action/0 - , filter/0 - ]). - -%% Multiple callbacks can be registered on a hookpoint. -%% The execution order depends on the priority value: -%% - Callbacks with greater priority values will be run before -%% the ones with lower priority values. e.g. A Callback with -%% priority = 2 precedes the callback with priority = 1. -%% - The execution order is the adding order of callbacks if they have -%% equal priority values. - --type(hookpoint() :: atom()). --type(action() :: function() | {function(), [term()]} | mfargs()). --type(filter() :: function() | mfargs()). - --record(callback, { - action :: action(), - filter :: maybe(filter()), - priority :: integer() - }). - --record(hook, { - name :: hookpoint(), - callbacks :: list(#callback{}) - }). - --define(TAB, ?MODULE). --define(SERVER, ?MODULE). - --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?SERVER}, - ?MODULE, [], [{hibernate_after, 1000}]). - --spec(stop() -> ok). -stop() -> - gen_server:stop(?SERVER, normal, infinity). - -%%-------------------------------------------------------------------- -%% Hooks API -%%-------------------------------------------------------------------- - -%% @doc Register a callback --spec(add(hookpoint(), action() | #callback{}) -> ok_or_error(already_exists)). -add(HookPoint, Callback) when is_record(Callback, callback) -> - gen_server:call(?SERVER, {add, HookPoint, Callback}, infinity); -add(HookPoint, Action) when is_function(Action); is_tuple(Action) -> - add(HookPoint, #callback{action = Action, priority = 0}). - --spec(add(hookpoint(), action(), filter() | integer() | list()) - -> ok_or_error(already_exists)). -add(HookPoint, Action, InitArgs) when is_function(Action), is_list(InitArgs) -> - add(HookPoint, #callback{action = {Action, InitArgs}, priority = 0}); -add(HookPoint, Action, Filter) when is_function(Filter); is_tuple(Filter) -> - add(HookPoint, #callback{action = Action, filter = Filter, priority = 0}); -add(HookPoint, Action, Priority) when is_integer(Priority) -> - add(HookPoint, #callback{action = Action, priority = Priority}). - --spec(add(hookpoint(), action(), filter(), integer()) - -> ok_or_error(already_exists)). -add(HookPoint, Action, Filter, Priority) when is_integer(Priority) -> - add(HookPoint, #callback{action = Action, filter = Filter, priority = Priority}). - -%% @doc Unregister a callback. --spec(del(hookpoint(), function() | {module(), atom()}) -> ok). -del(HookPoint, Action) -> - gen_server:cast(?SERVER, {del, HookPoint, Action}). - -%% @doc Run hooks. --spec(run(atom(), list(Arg::term())) -> ok). -run(HookPoint, Args) -> - do_run(lookup(HookPoint), Args). - -%% @doc Run hooks with Accumulator. --spec(run_fold(atom(), list(Arg::term()), Acc::term()) -> Acc::term()). -run_fold(HookPoint, Args, Acc) -> - do_run_fold(lookup(HookPoint), Args, Acc). - -do_run([#callback{action = Action, filter = Filter} | Callbacks], Args) -> - case filter_passed(Filter, Args) andalso safe_execute(Action, Args) of - %% stop the hook chain and return - stop -> ok; - %% continue the hook chain, in following cases: - %% - the filter validation failed with 'false' - %% - the callback returns any term other than 'stop' - _ -> do_run(Callbacks, Args) - end; -do_run([], _Args) -> - ok. - -do_run_fold([#callback{action = Action, filter = Filter} | Callbacks], Args, Acc) -> - Args1 = Args ++ [Acc], - case filter_passed(Filter, Args1) andalso safe_execute(Action, Args1) of - %% stop the hook chain - stop -> Acc; - %% stop the hook chain with NewAcc - {stop, NewAcc} -> NewAcc; - %% continue the hook chain with NewAcc - {ok, NewAcc} -> do_run_fold(Callbacks, Args, NewAcc); - %% continue the hook chain, in following cases: - %% - the filter validation failed with 'false' - %% - the callback returns any term other than 'stop' or {'stop', NewAcc} - _ -> do_run_fold(Callbacks, Args, Acc) - end; -do_run_fold([], _Args, Acc) -> - Acc. - --spec(filter_passed(filter(), Args::term()) -> true | false). -filter_passed(undefined, _Args) -> true; -filter_passed(Filter, Args) -> - execute(Filter, Args). - -safe_execute(Fun, Args) -> - try execute(Fun, Args) of - Result -> Result - catch - _:Reason:Stacktrace -> - ?LOG(error, "Failed to execute ~0p: ~0p", [Fun, {Reason, Stacktrace}]), - ok - end. - -%% @doc execute a function. -execute(Fun, Args) when is_function(Fun) -> - erlang:apply(Fun, Args); -execute({Fun, InitArgs}, Args) when is_function(Fun) -> - erlang:apply(Fun, Args ++ InitArgs); -execute({M, F, A}, Args) -> - erlang:apply(M, F, Args ++ A). - -%% @doc Lookup callbacks. --spec(lookup(hookpoint()) -> [#callback{}]). -lookup(HookPoint) -> - case ets:lookup(?TAB, HookPoint) of - [#hook{callbacks = Callbacks}] -> - Callbacks; - [] -> [] - end. - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - ok = emqx_tables:new(?TAB, [{keypos, #hook.name}, {read_concurrency, true}]), - {ok, #{}}. - -handle_call({add, HookPoint, Callback = #callback{action = Action}}, _From, State) -> - Reply = case lists:keymember(Action, #callback.action, Callbacks = lookup(HookPoint)) of - true -> - {error, already_exists}; - false -> - insert_hook(HookPoint, add_callback(Callback, Callbacks)) - end, - {reply, Reply, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({del, HookPoint, Action}, State) -> - case del_callback(Action, lookup(HookPoint)) of - [] -> - ets:delete(?TAB, HookPoint); - Callbacks -> - insert_hook(HookPoint, Callbacks) - end, - {noreply, State}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected msg: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%------------------------------------------------------------------------------ -%% Internal functions -%%------------------------------------------------------------------------------ - -insert_hook(HookPoint, Callbacks) -> - ets:insert(?TAB, #hook{name = HookPoint, callbacks = Callbacks}), ok. - -add_callback(C, Callbacks) -> - add_callback(C, Callbacks, []). - -add_callback(C, [], Acc) -> - lists:reverse([C|Acc]); -add_callback(C1 = #callback{priority = P1}, [C2 = #callback{priority = P2}|More], Acc) - when P1 =< P2 -> - add_callback(C1, More, [C2|Acc]); -add_callback(C1, More, Acc) -> - lists:append(lists:reverse(Acc), [C1 | More]). - -del_callback(Action, Callbacks) -> - del_callback(Action, Callbacks, []). - -del_callback(_Action, [], Acc) -> - lists:reverse(Acc); -del_callback(Action, [#callback{action = Action} | Callbacks], Acc) -> - del_callback(Action, Callbacks, Acc); -del_callback(Action = {M, F}, [#callback{action = {M, F, _A}} | Callbacks], Acc) -> - del_callback(Action, Callbacks, Acc); -del_callback(Func, [#callback{action = {Func, _A}} | Callbacks], Acc) -> - del_callback(Func, Callbacks, Acc); -del_callback(Action, [Callback | Callbacks], Acc) -> - del_callback(Action, Callbacks, [Callback | Acc]). - diff --git a/_build/emqx/lib/emqx/src/emqx_inflight.erl b/_build/emqx/lib/emqx/src/emqx_inflight.erl deleted file mode 100644 index 61b5c3e2e4..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_inflight.erl +++ /dev/null @@ -1,127 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_inflight). - --compile(inline). - -%% APIs --export([ new/0 - , new/1 - , contain/2 - , lookup/2 - , insert/3 - , update/3 - , resize/2 - , delete/2 - , values/1 - , to_list/1 - , to_list/2 - , size/1 - , max_size/1 - , is_full/1 - , is_empty/1 - , window/1 - ]). - --export_type([inflight/0]). - --type(key() :: term()). - --type(max_size() :: pos_integer()). - --opaque(inflight() :: {inflight, max_size(), gb_trees:tree()}). - --define(Inflight(Tree), {inflight, _MaxSize, Tree}). - --define(Inflight(MaxSize, Tree), {inflight, MaxSize, (Tree)}). - --spec(new() -> inflight()). -new() -> new(0). - --spec(new(non_neg_integer()) -> inflight()). -new(MaxSize) when MaxSize >= 0 -> - ?Inflight(MaxSize, gb_trees:empty()). - --spec(contain(key(), inflight()) -> boolean()). -contain(Key, ?Inflight(Tree)) -> - gb_trees:is_defined(Key, Tree). - --spec(lookup(key(), inflight()) -> {value, term()} | none). -lookup(Key, ?Inflight(Tree)) -> - gb_trees:lookup(Key, Tree). - --spec(insert(key(), Val :: term(), inflight()) -> inflight()). -insert(Key, Val, ?Inflight(MaxSize, Tree)) -> - ?Inflight(MaxSize, gb_trees:insert(Key, Val, Tree)). - --spec(delete(key(), inflight()) -> inflight()). -delete(Key, ?Inflight(MaxSize, Tree)) -> - ?Inflight(MaxSize, gb_trees:delete(Key, Tree)). - --spec(update(key(), Val :: term(), inflight()) -> inflight()). -update(Key, Val, ?Inflight(MaxSize, Tree)) -> - ?Inflight(MaxSize, gb_trees:update(Key, Val, Tree)). - --spec(resize(integer(), inflight()) -> inflight()). -resize(MaxSize, ?Inflight(Tree)) -> - ?Inflight(MaxSize, Tree). - --spec(is_full(inflight()) -> boolean()). -is_full(?Inflight(0, _Tree)) -> - false; -is_full(?Inflight(MaxSize, Tree)) -> - MaxSize =< gb_trees:size(Tree). - --spec(is_empty(inflight()) -> boolean()). -is_empty(?Inflight(Tree)) -> - gb_trees:is_empty(Tree). - --spec(smallest(inflight()) -> {key(), term()}). -smallest(?Inflight(Tree)) -> - gb_trees:smallest(Tree). - --spec(largest(inflight()) -> {key(), term()}). -largest(?Inflight(Tree)) -> - gb_trees:largest(Tree). - --spec(values(inflight()) -> list()). -values(?Inflight(Tree)) -> - gb_trees:values(Tree). - --spec(to_list(inflight()) -> list({key(), term()})). -to_list(?Inflight(Tree)) -> - gb_trees:to_list(Tree). - --spec(to_list(fun(), inflight()) -> list({key(), term()})). -to_list(SortFun, ?Inflight(Tree)) -> - lists:sort(SortFun, gb_trees:to_list(Tree)). - --spec(window(inflight()) -> list()). -window(Inflight = ?Inflight(Tree)) -> - case gb_trees:is_empty(Tree) of - true -> []; - false -> [Key || {Key, _Val} <- [smallest(Inflight), largest(Inflight)]] - end. - --spec(size(inflight()) -> non_neg_integer()). -size(?Inflight(Tree)) -> - gb_trees:size(Tree). - --spec(max_size(inflight()) -> non_neg_integer()). -max_size(?Inflight(MaxSize, _Tree)) -> - MaxSize. - diff --git a/_build/emqx/lib/emqx/src/emqx_json.erl b/_build/emqx/lib/emqx/src/emqx_json.erl deleted file mode 100644 index e8f5436968..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_json.erl +++ /dev/null @@ -1,90 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_json). - --compile(inline). - --export([ encode/1 - , encode/2 - , safe_encode/1 - , safe_encode/2 -]). - --compile({inline, - [ encode/1 - , encode/2 - ]}). - --export([ decode/1 - , decode/2 - , safe_decode/1 - , safe_decode/2 -]). - --compile({inline, - [ decode/1 - , decode/2 - ]}). - --spec(encode(jsx:json_term()) -> jsx:json_text()). -encode(Term) -> - jsx:encode(Term). - --spec(encode(jsx:json_term(), jsx_to_json:config()) - -> jsx:json_text()). -encode(Term, Opts) -> - jsx:encode(Term, Opts). - --spec(safe_encode(jsx:json_term()) - -> {ok, jsx:json_text()} | {error, Reason :: term()}). -safe_encode(Term) -> - safe_encode(Term, []). - --spec(safe_encode(jsx:json_term(), jsx_to_json:config()) - -> {ok, jsx:json_text()} | {error, Reason :: term()}). -safe_encode(Term, Opts) -> - try encode(Term, Opts) of - Json -> {ok, Json} - catch - error:Reason -> - {error, Reason} - end. - --spec(decode(jsx:json_text()) -> jsx:json_term()). -decode(Json) -> - jsx:decode(Json). - --spec(decode(jsx:json_text(), jsx_to_json:config()) - -> jsx:json_term()). -decode(Json, Opts) -> - jsx:decode(Json, Opts). - --spec(safe_decode(jsx:json_text()) - -> {ok, jsx:json_term()} | {error, Reason :: term()}). -safe_decode(Json) -> - safe_decode(Json, []). - --spec(safe_decode(jsx:json_text(), jsx_to_json:config()) - -> {ok, jsx:json_term()} | {error, Reason :: term()}). -safe_decode(Json, Opts) -> - try decode(Json, Opts) of - Term -> {ok, Term} - catch - error:Reason -> - {error, Reason} - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_keepalive.erl b/_build/emqx/lib/emqx/src/emqx_keepalive.erl deleted file mode 100644 index daa8e52211..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_keepalive.erl +++ /dev/null @@ -1,73 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_keepalive). - --export([ init/1 - , info/1 - , info/2 - , check/2 - ]). - --export_type([keepalive/0]). - --record(keepalive, { - interval :: pos_integer(), - statval :: non_neg_integer(), - repeat :: non_neg_integer() - }). - --opaque(keepalive() :: #keepalive{}). - -%% @doc Init keepalive. --spec(init(Interval :: non_neg_integer()) -> keepalive()). -init(Interval) when Interval > 0 -> - #keepalive{interval = Interval, - statval = 0, - repeat = 0}. - -%% @doc Get Info of the keepalive. --spec(info(keepalive()) -> emqx_types:infos()). -info(#keepalive{interval = Interval, - statval = StatVal, - repeat = Repeat}) -> - #{interval => Interval, - statval => StatVal, - repeat => Repeat - }. - --spec(info(interval|statval|repeat, keepalive()) - -> non_neg_integer()). -info(interval, #keepalive{interval = Interval}) -> - Interval; -info(statval, #keepalive{statval = StatVal}) -> - StatVal; -info(repeat, #keepalive{repeat = Repeat}) -> - Repeat. - -%% @doc Check keepalive. --spec(check(non_neg_integer(), keepalive()) - -> {ok, keepalive()} | {error, timeout}). -check(NewVal, KeepAlive = #keepalive{statval = OldVal, - repeat = Repeat}) -> - if - NewVal =/= OldVal -> - {ok, KeepAlive#keepalive{statval = NewVal, repeat = 0}}; - Repeat < 1 -> - {ok, KeepAlive#keepalive{repeat = Repeat + 1}}; - true -> {error, timeout} - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_kernel_sup.erl b/_build/emqx/lib/emqx/src/emqx_kernel_sup.erl deleted file mode 100644 index a1ba9cfe4b..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_kernel_sup.erl +++ /dev/null @@ -1,55 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_kernel_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -init([]) -> - {ok, {{one_for_one, 10, 100}, - [child_spec(emqx_global_gc, worker), - child_spec(emqx_pool_sup, supervisor), - child_spec(emqx_hooks, worker), - child_spec(emqx_stats, worker), - child_spec(emqx_metrics, worker), - child_spec(emqx_ctl, worker), - child_spec(emqx_zone, worker)]}}. - -child_spec(M, worker) -> - #{id => M, - start => {M, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [M] - }; - -child_spec(M, supervisor) -> - #{id => M, - start => {M, start_link, []}, - restart => permanent, - shutdown => infinity, - type => supervisor, - modules => [M] - }. - diff --git a/_build/emqx/lib/emqx/src/emqx_limiter.erl b/_build/emqx/lib/emqx/src/emqx_limiter.erl deleted file mode 100644 index ee456bc450..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_limiter.erl +++ /dev/null @@ -1,72 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_limiter). - --include("types.hrl"). - --export([init/1, info/1, check/2]). - --import(emqx_misc, [maybe_apply/2]). - --record(limiter, { - %% Publish Limit - pub_limit :: maybe(esockd_rate_limit:bucket()), - %% Rate Limit - rate_limit :: maybe(esockd_rate_limit:bucket()) - }). - --type(limiter() :: #limiter{}). - --export_type([limiter/0]). - --define(ENABLED(Rl), (Rl =/= undefined)). - --spec(init(proplists:proplist()) -> maybe(limiter())). -init(Options) -> - Pl = proplists:get_value(pub_limit, Options), - Rl = proplists:get_value(rate_limit, Options), - case ?ENABLED(Pl) or ?ENABLED(Rl) of - true -> #limiter{pub_limit = init_limit(Pl), - rate_limit = init_limit(Rl) - }; - false -> undefined - end. - -init_limit(Rl) -> - maybe_apply(fun esockd_rate_limit:new/1, Rl). - -info(#limiter{pub_limit = Pl, rate_limit = Rl}) -> - #{pub_limit => info(Pl), rate_limit => info(Rl)}; - -info(Rl) -> - maybe_apply(fun esockd_rate_limit:info/1, Rl). - -check(#{cnt := Cnt, oct := Oct}, Limiter = #limiter{pub_limit = Pl, - rate_limit = Rl}) -> - do_check([{#limiter.pub_limit, Cnt, Pl} || ?ENABLED(Pl)] ++ - [{#limiter.rate_limit, Oct, Rl} || ?ENABLED(Rl)], Limiter). - -do_check([], Limiter) -> - {ok, Limiter}; -do_check([{Pos, Cnt, Rl}|More], Limiter) -> - case esockd_rate_limit:check(Cnt, Rl) of - {0, Rl1} -> - do_check(More, setelement(Pos, Limiter, Rl1)); - {Pause, Rl1} -> - {pause, Pause, setelement(Pos, Limiter, Rl1)} - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_listeners.erl b/_build/emqx/lib/emqx/src/emqx_listeners.erl deleted file mode 100644 index ce256d147b..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_listeners.erl +++ /dev/null @@ -1,183 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc Start/Stop MQTT listeners. --module(emqx_listeners). - --include("emqx_mqtt.hrl"). - -%% APIs --export([ start/0 - , restart/0 - , stop/0 - ]). - --export([ start_listener/1 - , start_listener/3 - , stop_listener/1 - , stop_listener/3 - , restart_listener/1 - , restart_listener/3 - ]). - --type(listener() :: {esockd:proto(), esockd:listen_on(), [esockd:option()]}). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Start all listeners. --spec(start() -> ok). -start() -> - lists:foreach(fun start_listener/1, emqx:get_env(listeners, [])). - --spec(start_listener(listener()) -> ok). -start_listener({Proto, ListenOn, Options}) -> - case start_listener(Proto, ListenOn, Options) of - {ok, _} -> io:format("Start mqtt:~s listener on ~s successfully.~n", - [Proto, format(ListenOn)]); - {error, Reason} -> - io:format(standard_error, "Failed to start mqtt:~s listener on ~s - ~0p~n!", - [Proto, format(ListenOn), Reason]), - error(Reason) - end. - -%% Start MQTT/TCP listener --spec(start_listener(esockd:proto(), esockd:listen_on(), [esockd:option()]) - -> {ok, pid()} | {error, term()}). -start_listener(tcp, ListenOn, Options) -> - start_mqtt_listener('mqtt:tcp', ListenOn, Options); - -%% Start MQTT/TLS listener -start_listener(Proto, ListenOn, Options) when Proto == ssl; Proto == tls -> - start_mqtt_listener('mqtt:ssl', ListenOn, Options); - -%% Start MQTT/WS listener -start_listener(Proto, ListenOn, Options) when Proto == http; Proto == ws -> - start_http_listener(fun cowboy:start_clear/3, 'mqtt:ws', ListenOn, - ranch_opts(Options), ws_opts(Options)); - -%% Start MQTT/WSS listener -start_listener(Proto, ListenOn, Options) when Proto == https; Proto == wss -> - start_http_listener(fun cowboy:start_tls/3, 'mqtt:wss', ListenOn, - ranch_opts(Options), ws_opts(Options)). - -start_mqtt_listener(Name, ListenOn, Options) -> - SockOpts = esockd:parse_opt(Options), - esockd:open(Name, ListenOn, merge_default(SockOpts), - {emqx_connection, start_link, [Options -- SockOpts]}). - -start_http_listener(Start, Name, ListenOn, RanchOpts, ProtoOpts) -> - Start(ws_name(Name, ListenOn), with_port(ListenOn, RanchOpts), ProtoOpts). - -mqtt_path(Options) -> - proplists:get_value(mqtt_path, Options, "/mqtt"). - -ws_opts(Options) -> - WsPaths = [{mqtt_path(Options), emqx_ws_connection, Options}], - Dispatch = cowboy_router:compile([{'_', WsPaths}]), - ProxyProto = proplists:get_value(proxy_protocol, Options, false), - #{env => #{dispatch => Dispatch}, proxy_header => ProxyProto}. - -ranch_opts(Options) -> - NumAcceptors = proplists:get_value(acceptors, Options, 4), - MaxConnections = proplists:get_value(max_connections, Options, 1024), - TcpOptions = proplists:get_value(tcp_options, Options, []), - RanchOpts = #{num_acceptors => NumAcceptors, - max_connections => MaxConnections, - socket_opts => TcpOptions}, - case proplists:get_value(ssl_options, Options) of - undefined -> RanchOpts; - SslOptions -> RanchOpts#{socket_opts => TcpOptions ++ SslOptions} - end. - -with_port(Port, Opts = #{socket_opts := SocketOption}) when is_integer(Port) -> - Opts#{socket_opts => [{port, Port}| SocketOption]}; -with_port({Addr, Port}, Opts = #{socket_opts := SocketOption}) -> - Opts#{socket_opts => [{ip, Addr}, {port, Port}| SocketOption]}. - -%% @doc Restart all listeners --spec(restart() -> ok). -restart() -> - lists:foreach(fun restart_listener/1, emqx:get_env(listeners, [])). - --spec(restart_listener(listener()) -> any()). -restart_listener({Proto, ListenOn, Options}) -> - restart_listener(Proto, ListenOn, Options). - --spec(restart_listener(esockd:proto(), esockd:listen_on(), [esockd:option()]) -> any()). -restart_listener(tcp, ListenOn, _Options) -> - esockd:reopen('mqtt:tcp', ListenOn); -restart_listener(Proto, ListenOn, _Options) when Proto == ssl; Proto == tls -> - esockd:reopen('mqtt:ssl', ListenOn); -restart_listener(Proto, ListenOn, Options) when Proto == http; Proto == ws -> - cowboy:stop_listener(ws_name('mqtt:ws', ListenOn)), - start_listener(Proto, ListenOn, Options); -restart_listener(Proto, ListenOn, Options) when Proto == https; Proto == wss -> - cowboy:stop_listener(ws_name('mqtt:wss', ListenOn)), - start_listener(Proto, ListenOn, Options); -restart_listener(Proto, ListenOn, _Opts) -> - esockd:reopen(Proto, ListenOn). - -%% @doc Stop all listeners. --spec(stop() -> ok). -stop() -> - lists:foreach(fun stop_listener/1, emqx:get_env(listeners, [])). - --spec(stop_listener(listener()) -> ok | {error, term()}). -stop_listener({Proto, ListenOn, Opts}) -> - StopRet = stop_listener(Proto, ListenOn, Opts), - case StopRet of - ok -> io:format("Stop mqtt:~s listener on ~s successfully.~n", - [Proto, format(ListenOn)]); - {error, Reason} -> - io:format(standard_error, "Failed to stop mqtt:~s listener on ~s - ~p~n.", - [Proto, format(ListenOn), Reason]) - end, - StopRet. - --spec(stop_listener(esockd:proto(), esockd:listen_on(), [esockd:option()]) - -> ok | {error, term()}). -stop_listener(tcp, ListenOn, _Opts) -> - esockd:close('mqtt:tcp', ListenOn); -stop_listener(Proto, ListenOn, _Opts) when Proto == ssl; Proto == tls -> - esockd:close('mqtt:ssl', ListenOn); -stop_listener(Proto, ListenOn, _Opts) when Proto == http; Proto == ws -> - cowboy:stop_listener(ws_name('mqtt:ws', ListenOn)); -stop_listener(Proto, ListenOn, _Opts) when Proto == https; Proto == wss -> - cowboy:stop_listener(ws_name('mqtt:wss', ListenOn)); -stop_listener(Proto, ListenOn, _Opts) -> - esockd:close(Proto, ListenOn). - -merge_default(Options) -> - case lists:keytake(tcp_options, 1, Options) of - {value, {tcp_options, TcpOpts}, Options1} -> - [{tcp_options, emqx_misc:merge_opts(?MQTT_SOCKOPTS, TcpOpts)} | Options1]; - false -> - [{tcp_options, ?MQTT_SOCKOPTS} | Options] - end. - -format(Port) when is_integer(Port) -> - io_lib:format("0.0.0.0:~w", [Port]); -format({Addr, Port}) when is_list(Addr) -> - io_lib:format("~s:~w", [Addr, Port]); -format({Addr, Port}) when is_tuple(Addr) -> - io_lib:format("~s:~w", [inet:ntoa(Addr), Port]). - -ws_name(Name, {_Addr, Port}) -> - ws_name(Name, Port); -ws_name(Name, Port) -> - list_to_atom(lists:concat([Name, ":", Port])). diff --git a/_build/emqx/lib/emqx/src/emqx_logger.erl b/_build/emqx/lib/emqx/src/emqx_logger.erl deleted file mode 100644 index f250c7e938..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_logger.erl +++ /dev/null @@ -1,239 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_logger). - --compile({no_auto_import, [error/1]}). - -%% Logs --export([ debug/1 - , debug/2 - , debug/3 - , info/1 - , info/2 - , info/3 - , warning/1 - , warning/2 - , warning/3 - , error/1 - , error/2 - , error/3 - , critical/1 - , critical/2 - , critical/3 - ]). - -%% Configs --export([ set_metadata_peername/1 - , set_metadata_clientid/1 - , set_proc_metadata/1 - , set_primary_log_level/1 - , set_log_handler_level/2 - , set_log_level/1 - , set_all_log_handlers_level/1 - ]). - --export([ get_primary_log_level/0 - , get_log_handlers/0 - , get_log_handler/1 - ]). - --export([parse_transform/2]). - --type(peername_str() :: list()). --type(logger_dst() :: file:filename() | console | unknown). --type(logger_handler_info() :: {logger:handler_id(), logger:level(), logger_dst()}). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- --spec(debug(unicode:chardata()) -> ok). -debug(Msg) -> - logger:debug(Msg). - --spec(debug(io:format(), [term()]) -> ok). -debug(Format, Args) -> - logger:debug(Format, Args). - --spec(debug(logger:metadata(), io:format(), [term()]) -> ok). -debug(Metadata, Format, Args) when is_map(Metadata) -> - logger:debug(Format, Args, Metadata). - - --spec(info(unicode:chardata()) -> ok). -info(Msg) -> - logger:info(Msg). - --spec(info(io:format(), [term()]) -> ok). -info(Format, Args) -> - logger:info(Format, Args). - --spec(info(logger:metadata(), io:format(), [term()]) -> ok). -info(Metadata, Format, Args) when is_map(Metadata) -> - logger:info(Format, Args, Metadata). - - --spec(warning(unicode:chardata()) -> ok). -warning(Msg) -> - logger:warning(Msg). - --spec(warning(io:format(), [term()]) -> ok). -warning(Format, Args) -> - logger:warning(Format, Args). - --spec(warning(logger:metadata(), io:format(), [term()]) -> ok). -warning(Metadata, Format, Args) when is_map(Metadata) -> - logger:warning(Format, Args, Metadata). - - --spec(error(unicode:chardata()) -> ok). -error(Msg) -> - logger:error(Msg). --spec(error(io:format(), [term()]) -> ok). -error(Format, Args) -> - logger:error(Format, Args). --spec(error(logger:metadata(), io:format(), [term()]) -> ok). -error(Metadata, Format, Args) when is_map(Metadata) -> - logger:error(Format, Args, Metadata). - - --spec(critical(unicode:chardata()) -> ok). -critical(Msg) -> - logger:critical(Msg). - --spec(critical(io:format(), [term()]) -> ok). -critical(Format, Args) -> - logger:critical(Format, Args). - --spec(critical(logger:metadata(), io:format(), [term()]) -> ok). -critical(Metadata, Format, Args) when is_map(Metadata) -> - logger:critical(Format, Args, Metadata). - --spec(set_metadata_clientid(emqx_types:clientid()) -> ok). -set_metadata_clientid(<<>>) -> - ok; -set_metadata_clientid(ClientId) -> - set_proc_metadata(#{clientid => ClientId}). - --spec(set_metadata_peername(peername_str()) -> ok). -set_metadata_peername(Peername) -> - set_proc_metadata(#{peername => Peername}). - --spec(set_proc_metadata(logger:metadata()) -> ok). -set_proc_metadata(Meta) -> - logger:update_process_metadata(Meta). - --spec(get_primary_log_level() -> logger:level()). -get_primary_log_level() -> - #{level := Level} = logger:get_primary_config(), - Level. - --spec(set_primary_log_level(logger:level()) -> ok | {error, term()}). -set_primary_log_level(Level) -> - logger:set_primary_config(level, Level). - --spec(get_log_handlers() -> [logger_handler_info()]). -get_log_handlers() -> - lists:map(fun log_hanlder_info/1, logger:get_handler_config()). - --spec(get_log_handler(logger:handler_id()) -> logger_handler_info()). -get_log_handler(HandlerId) -> - {ok, Conf} = logger:get_handler_config(HandlerId), - log_hanlder_info(Conf). - --spec(set_log_handler_level(logger:handler_id(), logger:level()) -> ok | {error, term()}). -set_log_handler_level(HandlerId, Level) -> - logger:set_handler_config(HandlerId, level, Level). - -%% @doc Set both the primary and all handlers level in one command --spec(set_log_level(logger:handler_id()) -> ok | {error, term()}). -set_log_level(Level) -> - case set_primary_log_level(Level) of - ok -> set_all_log_handlers_level(Level); - {error, Error} -> {error, {primary_logger_level, Error}} - end. - -%% @doc The parse transform for prefixing a module-specific logger header to the logs. -%% The logger header can be specified by "-logger_header(Header)", where Header -%% must be a string (list). -%% @end -parse_transform(AST, _Opts) -> - trans(AST, "", []). - -%%-------------------------------------------------------------------- -%% Internal Functions -%%-------------------------------------------------------------------- - -log_hanlder_info(#{id := Id, level := Level, module := logger_std_h, - config := #{type := Type}}) when Type =:= standard_io; - Type =:= standard_error -> - {Id, Level, console}; -log_hanlder_info(#{id := Id, level := Level, module := logger_std_h, - config := Config = #{type := file}}) -> - {Id, Level, maps:get(file, Config, atom_to_list(Id))}; - -log_hanlder_info(#{id := Id, level := Level, module := logger_disk_log_h, - config := #{file := Filename}}) -> - {Id, Level, Filename}; -log_hanlder_info(#{id := Id, level := Level, module := _OtherModule}) -> - {Id, Level, unknown}. - -%% set level for all log handlers in one command -set_all_log_handlers_level(Level) -> - set_all_log_handlers_level(get_log_handlers(), Level, []). - -set_all_log_handlers_level([{ID, Level, _Dst} | List], NewLevel, ChangeHistory) -> - case set_log_handler_level(ID, NewLevel) of - ok -> set_all_log_handlers_level(List, NewLevel, [{ID, Level} | ChangeHistory]); - {error, Error} -> - rollback(ChangeHistory), - {error, {handlers_logger_level, {ID, Error}}} - end; -set_all_log_handlers_level([], _NewLevel, _NewHanlder) -> - ok. - -rollback([{ID, Level} | List]) -> - emqx_logger:set_log_handler_level(ID, Level), - rollback(List); -rollback([]) -> ok. - -%% @doc The following parse-transforms stripped off the module attribute named -%% `-logger_header(Header)` (if there's one) from the source code, and then -%% generate a function named '$logger_header'/0, which returns the logger header. -%% @end -trans([], LogHeader, ResAST) -> - lists:reverse([header_fun(LogHeader) | ResAST]); -trans([{eof, L} | AST], LogHeader, ResAST) -> - lists:reverse([{eof, L}, header_fun(LogHeader) | ResAST]) ++ AST; -trans([{attribute, _, module, _Mod} = M | AST], Header, ResAST) -> - trans(AST, Header, [export_header_fun(), M | ResAST]); -trans([{attribute, _, logger_header, Header} | AST], _, ResAST) -> - io_lib:printable_list(Header) orelse erlang:error({invalid_string, Header}), - trans(AST, Header, ResAST); -trans([F | AST], LogHeader, ResAST) -> - trans(AST, LogHeader, [F | ResAST]). - -export_header_fun() -> - {attribute,erl_anno:new(0),export,[{'$logger_header',0}]}. - -header_fun(LogHeader) -> - L = erl_anno:new(0), - {function,L,'$logger_header',0, - [{clause,L, - [], [], [{string,L,pad(LogHeader)}]}]}. - -pad("") -> ""; -pad(Str) -> Str ++ " ". diff --git a/_build/emqx/lib/emqx/src/emqx_logger_formatter.erl b/_build/emqx/lib/emqx/src/emqx_logger_formatter.erl deleted file mode 100644 index 2528a63b5f..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_logger_formatter.erl +++ /dev/null @@ -1,363 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2013-2019. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%% -%% %CopyrightEnd% -%% - -%% This file is copied from lib/kernel/src/logger_formatter.erl, and -%% modified for a more concise time format other than the default RFC3339. - --module(emqx_logger_formatter). - --export([format/2]). - --export([check_config/1]). - --define(DEFAULT_FORMAT_TEMPLATE_SINGLE, [time," ",level,": ",msg,"\n"]). - --define(FormatP, "~0tp"). - --define(IS_STRING(String), - (is_list(String) orelse is_binary(String))). - -%%-------------------------------------------------------------------- -%% Types - --type(config() :: #{chars_limit => pos_integer() | unlimited, - depth => pos_integer() | unlimited, - max_size => pos_integer() | unlimited, - report_cb => logger:report_cb(), - quit => template()}). - --type(template() :: [metakey() | {metakey(),template(),template()} | string()]). - --type(metakey() :: atom() | [atom()]). - -%%-------------------------------------------------------------------- -%% API - --spec format(LogEvent,Config) -> unicode:chardata() when - LogEvent :: logger:log_event(), - Config :: config(). -format(#{level:=Level,msg:=Msg0,meta:=Meta},Config0) - when is_map(Config0) -> - Config = add_default_config(Config0), - Template = maps:get(template,Config), - {BT,AT0} = lists:splitwith(fun(msg) -> false; (_) -> true end, Template), - {DoMsg,AT} = - case AT0 of - [msg|Rest] -> {true,Rest}; - _ ->{false,AT0} - end, - B = do_format(Level,Meta,BT,Config), - A = do_format(Level,Meta,AT,Config), - MsgStr = - if DoMsg -> - Config1 = - case maps:get(chars_limit,Config) of - unlimited -> - Config; - Size0 -> - Size = - case Size0 - string:length([B,A]) of - S when S>=0 -> S; - _ -> 0 - end, - Config#{chars_limit=>Size} - end, - format_msg(Msg0,Meta,Config1); - true -> - "" - end, - truncate([B,MsgStr,A],maps:get(max_size,Config)). - -do_format(Level,Data,[level|Format],Config) -> - [to_string(level,Level,Config)|do_format(Level,Data,Format,Config)]; -do_format(Level,Data,[{Key,IfExist,Else}|Format],Config) -> - String = - case value(Key,Data) of - {ok,Value} -> do_format(Level,Data#{Key=>Value},IfExist,Config); - error -> do_format(Level,Data,Else,Config) - end, - [String|do_format(Level,Data,Format,Config)]; -do_format(Level,Data,[Key|Format],Config) - when is_atom(Key) orelse - (is_list(Key) andalso is_atom(hd(Key))) -> - String = - case value(Key,Data) of - {ok,Value} -> to_string(Key,Value,Config); - error -> "" - end, - [String|do_format(Level,Data,Format,Config)]; -do_format(Level,Data,[Str|Format],Config) -> - [Str|do_format(Level,Data,Format,Config)]; -do_format(_Level,_Data,[],_Config) -> - []. - -value(Key,Meta) when is_map_key(Key,Meta) -> - {ok,maps:get(Key,Meta)}; -value([Key|Keys],Meta) when is_map_key(Key,Meta) -> - value(Keys,maps:get(Key,Meta)); -value([],Value) -> - {ok,Value}; -value(_,_) -> - error. - -to_string(time,Time,Config) -> - format_time(Time,Config); -to_string(mfa,MFA,Config) -> - format_mfa(MFA,Config); -to_string(_,Value,Config) -> - to_string(Value,Config). - -to_string(X,_) when is_atom(X) -> - atom_to_list(X); -to_string(X,_) when is_integer(X) -> - integer_to_list(X); -to_string(X,_) when is_pid(X) -> - pid_to_list(X); -to_string(X,_) when is_reference(X) -> - ref_to_list(X); -to_string(X,_) when is_list(X) -> - case printable_list(lists:flatten(X)) of - true -> X; - _ -> io_lib:format(?FormatP,[X]) - end; -to_string(X,_) -> - io_lib:format(?FormatP,[X]). - -printable_list([]) -> - false; -printable_list(X) -> - io_lib:printable_list(X). - -format_msg({string,Chardata},Meta,Config) -> - format_msg({"~ts",[Chardata]},Meta,Config); -format_msg({report,_}=Msg,Meta,#{report_cb:=Fun}=Config) - when is_function(Fun,1); is_function(Fun,2) -> - format_msg(Msg,Meta#{report_cb=>Fun},maps:remove(report_cb,Config)); -format_msg({report,Report},#{report_cb:=Fun}=Meta,Config) when is_function(Fun,1) -> - try Fun(Report) of - {Format,Args} when is_list(Format), is_list(Args) -> - format_msg({Format,Args},maps:remove(report_cb,Meta),Config); - Other -> - format_msg({"REPORT_CB/1 ERROR: ~0tp; Returned: ~0tp", - [Report,Other]},Meta,Config) - catch C:R:S -> - format_msg({"REPORT_CB/1 CRASH: ~0tp; Reason: ~0tp", - [Report,{C,R,logger:filter_stacktrace(?MODULE,S)}]},Meta,Config) - end; -format_msg({report,Report},#{report_cb:=Fun}=Meta,Config) when is_function(Fun,2) -> - try Fun(Report,maps:with([depth,chars_limit,single_line],Config)) of - Chardata when ?IS_STRING(Chardata) -> - try chardata_to_list(Chardata) % already size limited by report_cb - catch _:_ -> - format_msg({"REPORT_CB/2 ERROR: ~0tp; Returned: ~0tp", - [Report,Chardata]},Meta,Config) - end; - Other -> - format_msg({"REPORT_CB/2 ERROR: ~0tp; Returned: ~0tp", - [Report,Other]},Meta,Config) - catch C:R:S -> - format_msg({"REPORT_CB/2 CRASH: ~0tp; Reason: ~0tp", - [Report,{C,R,logger:filter_stacktrace(?MODULE,S)}]}, - Meta,Config) - end; -format_msg({report,Report},Meta,Config) -> - format_msg({report,Report}, - Meta#{report_cb=>fun logger:format_report/1}, - Config); -format_msg(Msg,_Meta,#{depth:=Depth,chars_limit:=CharsLimit}) -> - Opts = chars_limit_to_opts(CharsLimit), - do_format_msg(Msg, Depth, Opts). - -chars_limit_to_opts(unlimited) -> []; -chars_limit_to_opts(CharsLimit) -> [{chars_limit,CharsLimit}]. - -do_format_msg({Format0,Args},Depth,Opts) -> - try - Format1 = io_lib:scan_format(Format0, Args), - Format = reformat(Format1, Depth), - io_lib:build_text(Format,Opts) - catch C:R:S -> - FormatError = "FORMAT ERROR: ~0tp - ~0tp", - case Format0 of - FormatError -> - %% already been here - avoid failing cyclically - erlang:raise(C,R,S); - _ -> - do_format_msg({FormatError,[Format0,Args]},Depth,Opts) - end - end. - -reformat(Format,unlimited) -> - Format; -reformat([#{control_char:=C}=M|T], Depth) when C =:= $p -> - [limit_depth(M#{width => 0}, Depth)|reformat(T, Depth)]; -reformat([#{control_char:=C}=M|T], Depth) when C =:= $P -> - [M#{width => 0}|reformat(T, Depth)]; -reformat([#{control_char:=C}=M|T], Depth) when C =:= $p; C =:= $w -> - [limit_depth(M, Depth)|reformat(T, Depth)]; -reformat([H|T], Depth) -> - [H|reformat(T, Depth)]; -reformat([], _) -> - []. - -limit_depth(M0, unlimited) -> - M0; -limit_depth(#{control_char:=C0, args:=Args}=M0, Depth) -> - C = C0 - ($a - $A), %To uppercase. - M0#{control_char:=C,args:=Args++[Depth]}. - -chardata_to_list(Chardata) -> - case unicode:characters_to_list(Chardata,unicode) of - List when is_list(List) -> - List; - Error -> - throw(Error) - end. - -truncate(String,unlimited) -> - String; -truncate(String,Size) -> - Length = string:length(String), - if Length>Size -> - case lists:reverse(lists:flatten(String)) of - [$\n|_] -> - string:slice(String,0,Size-4)++"...\n"; - _ -> - string:slice(String,0,Size-3)++"..." - end; - true -> - String - end. - -%% Convert microseconds-timestamp into local datatime string in milliseconds -format_time(SysTime,#{}) - when is_integer(SysTime) -> - Ms = SysTime rem 1000000 div 1000, - {Date, _Time = {H, Mi, S}} = calendar:system_time_to_local_time(SysTime, microsecond), - format_time({Date, {H, Mi, S, Ms}}). -format_time({{Y, M, D}, {H, Mi, S, Ms}}) -> - io_lib:format("~b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b.~3..0b", [Y, M, D, H, Mi, S, Ms]). - -format_mfa({M,F,A},_) when is_atom(M), is_atom(F), is_integer(A) -> - atom_to_list(M)++":"++atom_to_list(F)++"/"++integer_to_list(A); -format_mfa({M,F,A},Config) when is_atom(M), is_atom(F), is_list(A) -> - format_mfa({M,F,length(A)},Config); -format_mfa(MFA,Config) -> - to_string(MFA,Config). - -%% Ensure that all valid configuration parameters exist in the final -%% configuration map -add_default_config(Config0) -> - Default = - #{chars_limit=>unlimited, - error_logger_notice_header=>info}, - MaxSize = get_max_size(maps:get(max_size,Config0,undefined)), - Depth = get_depth(maps:get(depth,Config0,undefined)), - add_default_template(maps:merge(Default,Config0#{max_size=>MaxSize, - depth=>Depth})). - -add_default_template(#{template:=_}=Config) -> - Config; -add_default_template(Config) -> - Config#{template=>?DEFAULT_FORMAT_TEMPLATE_SINGLE}. - -get_max_size(undefined) -> - unlimited; -get_max_size(S) -> - max(10,S). - -get_depth(undefined) -> - error_logger:get_format_depth(); -get_depth(S) -> - max(5,S). - --spec check_config(Config) -> ok | {error,term()} when - Config :: config(). -check_config(Config) when is_map(Config) -> - do_check_config(maps:to_list(Config)); -check_config(Config) -> - {error,{invalid_formatter_config,?MODULE,Config}}. - -do_check_config([{Type,L}|Config]) when Type == chars_limit; - Type == depth; - Type == max_size -> - case check_limit(L) of - ok -> do_check_config(Config); - error -> {error,{invalid_formatter_config,?MODULE,{Type,L}}} - end; -do_check_config([{error_logger_notice_header,ELNH}|Config]) when ELNH == info; - ELNH == notice -> - do_check_config(Config); -do_check_config([{report_cb,RCB}|Config]) when is_function(RCB,1); - is_function(RCB,2) -> - do_check_config(Config); -do_check_config([{template,T}|Config]) -> - case check_template(T) of - ok -> do_check_config(Config); - error -> {error,{invalid_formatter_template,?MODULE,T}} - end; - -do_check_config([C|_]) -> - {error,{invalid_formatter_config,?MODULE,C}}; -do_check_config([]) -> - ok. - -check_limit(L) when is_integer(L), L>0 -> - ok; -check_limit(unlimited) -> - ok; -check_limit(_) -> - error. - -check_template([Key|T]) when is_atom(Key) -> - check_template(T); -check_template([Key|T]) when is_list(Key), is_atom(hd(Key)) -> - case lists:all(fun(X) when is_atom(X) -> true; - (_) -> false - end, - Key) of - true -> - check_template(T); - false -> - error - end; -check_template([{Key,IfExist,Else}|T]) - when is_atom(Key) orelse - (is_list(Key) andalso is_atom(hd(Key))) -> - case check_template(IfExist) of - ok -> - case check_template(Else) of - ok -> - check_template(T); - error -> - error - end; - error -> - error - end; -check_template([Str|T]) when is_list(Str) -> - case io_lib:printable_unicode_list(Str) of - true -> check_template(T); - false -> error - end; -check_template([]) -> - ok; -check_template(_) -> - error. diff --git a/_build/emqx/lib/emqx/src/emqx_message.erl b/_build/emqx/lib/emqx/src/emqx_message.erl deleted file mode 100644 index decbb0c187..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_message.erl +++ /dev/null @@ -1,307 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_message). - --compile(inline). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("types.hrl"). - -%% Create --export([ make/2 - , make/3 - , make/4 - , make/6 - , make/7 - ]). - -%% Fields --export([ id/1 - , qos/1 - , from/1 - , topic/1 - , payload/1 - , timestamp/1 - ]). - -%% Flags --export([ is_sys/1 - , clean_dup/1 - , get_flag/2 - , get_flag/3 - , get_flags/1 - , set_flag/2 - , set_flag/3 - , set_flags/2 - , unset_flag/2 - ]). - -%% Headers --export([ get_headers/1 - , get_header/2 - , get_header/3 - , set_header/3 - , set_headers/2 - , remove_header/2 - ]). - --export([ is_expired/1 - , update_expiry/1 - ]). - --export([ to_packet/2 - , to_map/1 - , to_list/1 - ]). - --export([format/1]). - --spec(make(emqx_topic:topic(), emqx_types:payload()) -> emqx_types:message()). -make(Topic, Payload) -> - make(undefined, Topic, Payload). - --spec(make(emqx_types:clientid(), - emqx_topic:topic(), - emqx_types:payload()) -> emqx_types:message()). -make(From, Topic, Payload) -> - make(From, ?QOS_0, Topic, Payload). - --spec(make(emqx_types:clientid(), - emqx_types:qos(), - emqx_topic:topic(), - emqx_types:payload()) -> emqx_types:message()). -make(From, QoS, Topic, Payload) when ?QOS_0 =< QoS, QoS =< ?QOS_2 -> - Now = erlang:system_time(millisecond), - #message{id = emqx_guid:gen(), - qos = QoS, - from = From, - topic = Topic, - payload = Payload, - timestamp = Now - }. - --spec(make(emqx_types:clientid(), - emqx_types:qos(), - emqx_topic:topic(), - emqx_types:payload(), - emqx_types:flags(), - emqx_types:headers()) -> emqx_types:message()). -make(From, QoS, Topic, Payload, Flags, Headers) - when ?QOS_0 =< QoS, QoS =< ?QOS_2, - is_map(Flags), is_map(Headers) -> - Now = erlang:system_time(millisecond), - #message{id = emqx_guid:gen(), - qos = QoS, - from = From, - flags = Flags, - headers = Headers, - topic = Topic, - payload = Payload, - timestamp = Now - }. - --spec(make(MsgId :: binary(), - emqx_types:clientid(), - emqx_types:qos(), - emqx_topic:topic(), - emqx_types:payload(), - emqx_types:flags(), - emqx_types:headers()) -> emqx_types:message()). -make(MsgId, From, QoS, Topic, Payload, Flags, Headers) - when ?QOS_0 =< QoS, QoS =< ?QOS_2, - is_map(Flags), is_map(Headers) -> - Now = erlang:system_time(millisecond), - #message{id = MsgId, - qos = QoS, - from = From, - flags = Flags, - headers = Headers, - topic = Topic, - payload = Payload, - timestamp = Now - }. - --spec(id(emqx_types:message()) -> maybe(binary())). -id(#message{id = Id}) -> Id. - --spec(qos(emqx_types:message()) -> emqx_types:qos()). -qos(#message{qos = QoS}) -> QoS. - --spec(from(emqx_types:message()) -> atom() | binary()). -from(#message{from = From}) -> From. - --spec(topic(emqx_types:message()) -> emqx_types:topic()). -topic(#message{topic = Topic}) -> Topic. - --spec(payload(emqx_types:message()) -> emqx_types:payload()). -payload(#message{payload = Payload}) -> Payload. - --spec(timestamp(emqx_types:message()) -> integer()). -timestamp(#message{timestamp = TS}) -> TS. - --spec(is_sys(emqx_types:message()) -> boolean()). -is_sys(#message{flags = #{sys := true}}) -> - true; -is_sys(#message{topic = <<"$SYS/", _/binary>>}) -> - true; -is_sys(_Msg) -> false. - --spec(clean_dup(emqx_types:message()) -> emqx_types:message()). -clean_dup(Msg = #message{flags = Flags = #{dup := true}}) -> - Msg#message{flags = Flags#{dup => false}}; -clean_dup(Msg) -> Msg. - --spec(set_flags(map(), emqx_types:message()) -> emqx_types:message()). -set_flags(New, Msg = #message{flags = Old}) when is_map(New) -> - Msg#message{flags = maps:merge(Old, New)}. - --spec(get_flag(emqx_types:flag(), emqx_types:message()) -> boolean()). -get_flag(Flag, Msg) -> - get_flag(Flag, Msg, false). - -get_flag(Flag, #message{flags = Flags}, Default) -> - maps:get(Flag, Flags, Default). - --spec(get_flags(emqx_types:message()) -> maybe(map())). -get_flags(#message{flags = Flags}) -> Flags. - --spec(set_flag(emqx_types:flag(), emqx_types:message()) -> emqx_types:message()). -set_flag(Flag, Msg = #message{flags = Flags}) when is_atom(Flag) -> - Msg#message{flags = maps:put(Flag, true, Flags)}. - --spec(set_flag(emqx_types:flag(), boolean() | integer(), emqx_types:message()) - -> emqx_types:message()). -set_flag(Flag, Val, Msg = #message{flags = Flags}) when is_atom(Flag) -> - Msg#message{flags = maps:put(Flag, Val, Flags)}. - --spec(unset_flag(emqx_types:flag(), emqx_types:message()) -> emqx_types:message()). -unset_flag(Flag, Msg = #message{flags = Flags}) -> - case maps:is_key(Flag, Flags) of - true -> Msg#message{flags = maps:remove(Flag, Flags)}; - false -> Msg - end. - --spec(set_headers(map(), emqx_types:message()) -> emqx_types:message()). -set_headers(New, Msg = #message{headers = Old}) when is_map(New) -> - Msg#message{headers = maps:merge(Old, New)}. - --spec(get_headers(emqx_types:message()) -> maybe(map())). -get_headers(Msg) -> Msg#message.headers. - --spec(get_header(term(), emqx_types:message()) -> term()). -get_header(Hdr, Msg) -> - get_header(Hdr, Msg, undefined). --spec(get_header(term(), emqx_types:message(), term()) -> term()). -get_header(Hdr, #message{headers = Headers}, Default) -> - maps:get(Hdr, Headers, Default). - --spec(set_header(term(), term(), emqx_types:message()) -> emqx_types:message()). -set_header(Hdr, Val, Msg = #message{headers = Headers}) -> - Msg#message{headers = maps:put(Hdr, Val, Headers)}. - --spec(remove_header(term(), emqx_types:message()) -> emqx_types:message()). -remove_header(Hdr, Msg = #message{headers = Headers}) -> - case maps:is_key(Hdr, Headers) of - true -> Msg#message{headers = maps:remove(Hdr, Headers)}; - false -> Msg - end. - --spec(is_expired(emqx_types:message()) -> boolean()). -is_expired(#message{headers = #{properties := #{'Message-Expiry-Interval' := Interval}}, - timestamp = CreatedAt}) -> - elapsed(CreatedAt) > timer:seconds(Interval); -is_expired(_Msg) -> false. - --spec(update_expiry(emqx_types:message()) -> emqx_types:message()). -update_expiry(Msg = #message{headers = #{properties := Props = #{'Message-Expiry-Interval' := Interval}}, - timestamp = CreatedAt}) -> - case elapsed(CreatedAt) of - Elapsed when Elapsed > 0 -> - Interval1 = max(1, Interval - (Elapsed div 1000)), - set_header(properties, Props#{'Message-Expiry-Interval' => Interval1}, Msg); - _ -> Msg - end; -update_expiry(Msg) -> Msg. - -%% @doc Message to PUBLISH Packet. --spec(to_packet(emqx_types:packet_id(), emqx_types:message()) - -> emqx_types:packet()). -to_packet(PacketId, Msg = #message{qos = QoS, headers = Headers, - topic = Topic, payload = Payload}) -> - #mqtt_packet{header = #mqtt_packet_header{type = ?PUBLISH, - dup = get_flag(dup, Msg), - qos = QoS, - retain = get_flag(retain, Msg) - }, - variable = #mqtt_packet_publish{topic_name = Topic, - packet_id = PacketId, - properties = filter_pub_props(maps:get(properties, Headers, #{})) - }, - payload = Payload - }. - -filter_pub_props(Props) -> - maps:with(['Payload-Format-Indicator', - 'Message-Expiry-Interval', - 'Response-Topic', - 'Correlation-Data', - 'User-Property', - 'Subscription-Identifier', - 'Content-Type' - ], Props). - -%% @doc Message to map --spec(to_map(emqx_types:message()) -> map()). -to_map(#message{ - id = Id, - qos = QoS, - from = From, - flags = Flags, - headers = Headers, - topic = Topic, - payload = Payload, - timestamp = Timestamp - }) -> - #{id => Id, - qos => QoS, - from => From, - flags => Flags, - headers => Headers, - topic => Topic, - payload => Payload, - timestamp => Timestamp - }. - -%% @doc Message to tuple list --spec(to_list(emqx_types:message()) -> list()). -to_list(Msg) -> - lists:zip(record_info(fields, message), tl(tuple_to_list(Msg))). - -%% MilliSeconds -elapsed(Since) -> - max(0, erlang:system_time(millisecond) - Since). - -format(#message{id = Id, qos = QoS, topic = Topic, from = From, flags = Flags, headers = Headers}) -> - io_lib:format("Message(Id=~s, QoS=~w, Topic=~s, From=~p, Flags=~s, Headers=~s)", - [Id, QoS, Topic, From, format(flags, Flags), format(headers, Headers)]). - -format(flags, Flags) -> - io_lib:format("~p", [[Flag || {Flag, true} <- maps:to_list(Flags)]]); -format(headers, Headers) -> - io_lib:format("~p", [Headers]). - diff --git a/_build/emqx/lib/emqx/src/emqx_metrics.erl b/_build/emqx/lib/emqx/src/emqx_metrics.erl deleted file mode 100644 index 2a5a827497..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_metrics.erl +++ /dev/null @@ -1,550 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_metrics). - --behavior(gen_server). - --include("logger.hrl"). --include("types.hrl"). --include("emqx_mqtt.hrl"). - --logger_header("[Metrics]"). - --export([ start_link/0 - , stop/0 - ]). - --export([ new/1 - , new/2 - , ensure/1 - , ensure/2 - , all/0 - ]). - --export([ val/1 - , inc/1 - , inc/2 - , dec/1 - , dec/2 - , set/2 - ]). - --export([ trans/2 - , trans/3 - , commit/0 - ]). - -%% Inc received/sent metrics --export([ inc_recv/1 - , inc_sent/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --export_type([metric_idx/0]). - --compile({inline, [inc/1, inc/2, dec/1, dec/2]}). --compile({inline, [inc_recv/1, inc_sent/1]}). - --opaque(metric_idx() :: 1..1024). - --type(metric_name() :: atom() | string() | binary()). - --define(MAX_SIZE, 1024). --define(RESERVED_IDX, 512). --define(TAB, ?MODULE). --define(SERVER, ?MODULE). - -%% Bytes sent and received --define(BYTES_METRICS, - [{counter, 'bytes.received'}, % Total bytes received - {counter, 'bytes.sent'} % Total bytes sent - ]). - -%% Packets sent and received --define(PACKET_METRICS, - [{counter, 'packets.received'}, % All Packets received - {counter, 'packets.sent'}, % All Packets sent - {counter, 'packets.connect.received'}, % CONNECT Packets received - {counter, 'packets.connack.sent'}, % CONNACK Packets sent - {counter, 'packets.connack.error'}, % CONNACK error sent - {counter, 'packets.connack.auth_error'}, % CONNACK auth_error sent - {counter, 'packets.publish.received'}, % PUBLISH packets received - {counter, 'packets.publish.sent'}, % PUBLISH packets sent - {counter, 'packets.publish.inuse'}, % PUBLISH packet_id inuse - {counter, 'packets.publish.error'}, % PUBLISH failed for error - {counter, 'packets.publish.auth_error'}, % PUBLISH failed for auth error - {counter, 'packets.publish.dropped'}, % PUBLISH(QoS2) packets dropped - {counter, 'packets.puback.received'}, % PUBACK packets received - {counter, 'packets.puback.sent'}, % PUBACK packets sent - {counter, 'packets.puback.inuse'}, % PUBACK packet_id inuse - {counter, 'packets.puback.missed'}, % PUBACK packets missed - {counter, 'packets.pubrec.received'}, % PUBREC packets received - {counter, 'packets.pubrec.sent'}, % PUBREC packets sent - {counter, 'packets.pubrec.inuse'}, % PUBREC packet_id inuse - {counter, 'packets.pubrec.missed'}, % PUBREC packets missed - {counter, 'packets.pubrel.received'}, % PUBREL packets received - {counter, 'packets.pubrel.sent'}, % PUBREL packets sent - {counter, 'packets.pubrel.missed'}, % PUBREL packets missed - {counter, 'packets.pubcomp.received'}, % PUBCOMP packets received - {counter, 'packets.pubcomp.sent'}, % PUBCOMP packets sent - {counter, 'packets.pubcomp.inuse'}, % PUBCOMP packet_id inuse - {counter, 'packets.pubcomp.missed'}, % PUBCOMP packets missed - {counter, 'packets.subscribe.received'}, % SUBSCRIBE Packets received - {counter, 'packets.subscribe.error'}, % SUBSCRIBE error - {counter, 'packets.subscribe.auth_error'}, % SUBSCRIBE failed for not auth - {counter, 'packets.suback.sent'}, % SUBACK packets sent - {counter, 'packets.unsubscribe.received'}, % UNSUBSCRIBE Packets received - {counter, 'packets.unsubscribe.error'}, % UNSUBSCRIBE error - {counter, 'packets.unsuback.sent'}, % UNSUBACK Packets sent - {counter, 'packets.pingreq.received'}, % PINGREQ packets received - {counter, 'packets.pingresp.sent'}, % PINGRESP Packets sent - {counter, 'packets.disconnect.received'}, % DISCONNECT Packets received - {counter, 'packets.disconnect.sent'}, % DISCONNECT Packets sent - {counter, 'packets.auth.received'}, % Auth Packets received - {counter, 'packets.auth.sent'} % Auth Packets sent - ]). - -%% Messages sent/received and pubsub --define(MESSAGE_METRICS, - [{counter, 'messages.received'}, % All Messages received - {counter, 'messages.sent'}, % All Messages sent - {counter, 'messages.qos0.received'}, % QoS0 Messages received - {counter, 'messages.qos0.sent'}, % QoS0 Messages sent - {counter, 'messages.qos1.received'}, % QoS1 Messages received - {counter, 'messages.qos1.sent'}, % QoS1 Messages sent - {counter, 'messages.qos2.received'}, % QoS2 Messages received - {counter, 'messages.qos2.sent'}, % QoS2 Messages sent - %% PubSub Metrics - {counter, 'messages.publish'}, % Messages Publish - {counter, 'messages.dropped'}, % Messages dropped due to no subscribers - {counter, 'messages.dropped.expired'}, % QoS2 Messages expired - {counter, 'messages.dropped.no_subscribers'}, % Messages dropped - {counter, 'messages.forward'}, % Messages forward - {gauge, 'messages.retained'}, % Messages retained - {gauge, 'messages.delayed'}, % Messages delayed - {counter, 'messages.delivered'}, % Messages delivered - {counter, 'messages.acked'} % Messages acked - ]). - -%% Delivery metrics --define(DELIVERY_METRICS, - [{counter, 'delivery.dropped'}, - {counter, 'delivery.dropped.no_local'}, - {counter, 'delivery.dropped.too_large'}, - {counter, 'delivery.dropped.qos0_msg'}, - {counter, 'delivery.dropped.queue_full'}, - {counter, 'delivery.dropped.expired'} - ]). - -%% Client Lifecircle metrics --define(CLIENT_METRICS, - [{counter, 'client.connect'}, - {counter, 'client.connack'}, - {counter, 'client.connected'}, - {counter, 'client.authenticate'}, - {counter, 'client.auth.anonymous'}, - {counter, 'client.check_acl'}, - {counter, 'client.subscribe'}, - {counter, 'client.unsubscribe'}, - {counter, 'client.disconnected'} - ]). - -%% Session Lifecircle metrics --define(SESSION_METRICS, - [{counter, 'session.created'}, - {counter, 'session.resumed'}, - {counter, 'session.takeovered'}, - {counter, 'session.discarded'}, - {counter, 'session.terminated'} - ]). - --record(state, {next_idx = 1}). - --record(metric, {name, type, idx}). - -%% @doc Start the metrics server. --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - --spec(stop() -> ok). -stop() -> gen_server:stop(?SERVER). - -%%-------------------------------------------------------------------- -%% Metrics API -%%-------------------------------------------------------------------- - --spec(new(metric_name()) -> ok). -new(Name) -> - new(counter, Name). - --spec(new(gauge|counter, metric_name()) -> ok). -new(gauge, Name) -> - create(gauge, Name); -new(counter, Name) -> - create(counter, Name). - --spec(ensure(metric_name()) -> ok). -ensure(Name) -> - ensure(counter, Name). - --spec(ensure(gauge|counter, metric_name()) -> ok). -ensure(Type, Name) when Type =:= gauge; Type =:= counter -> - case ets:lookup(?TAB, Name) of - [] -> create(Type, Name); - _ -> ok - end. - -%% @private -create(Type, Name) -> - case gen_server:call(?SERVER, {create, Type, Name}) of - {ok, _Idx} -> ok; - {error, Reason} -> error(Reason) - end. - -%% @doc Get all metrics --spec(all() -> [{metric_name(), non_neg_integer()}]). -all() -> - CRef = persistent_term:get(?MODULE), - [{Name, counters:get(CRef, Idx)} - || #metric{name = Name, idx = Idx} <- ets:tab2list(?TAB)]. - -%% @doc Get metric value --spec(val(metric_name()) -> maybe(non_neg_integer())). -val(Name) -> - case ets:lookup(?TAB, Name) of - [#metric{idx = Idx}] -> - CRef = persistent_term:get(?MODULE), - counters:get(CRef, Idx); - [] -> undefined - end. - -%% @doc Increase counter --spec(inc(metric_name()) -> ok). -inc(Name) -> - inc(Name, 1). - -%% @doc Increase metric value --spec(inc(metric_name(), pos_integer()) -> ok). -inc(Name, Value) -> - update_counter(Name, Value). - -%% @doc Decrease metric value --spec(dec(metric_name()) -> ok). -dec(Name) -> - dec(Name, 1). - -%% @doc Decrease metric value --spec(dec(metric_name(), pos_integer()) -> ok). -dec(Name, Value) -> - update_counter(Name, -Value). - -%% @doc Set metric value --spec(set(metric_name(), integer()) -> ok). -set(Name, Value) -> - CRef = persistent_term:get(?MODULE), - Idx = ets:lookup_element(?TAB, Name, 4), - counters:put(CRef, Idx, Value). - --spec(trans(inc | dec, metric_name()) -> ok). -trans(Op, Name) when Op =:= inc; Op =:= dec -> - trans(Op, Name, 1). - --spec(trans(inc | dec, metric_name(), pos_integer()) -> ok). -trans(inc, Name, Value) -> - cache(Name, Value); -trans(dec, Name, Value) -> - cache(Name, -Value). - --spec(cache(metric_name(), integer()) -> ok). -cache(Name, Value) -> - put('$metrics', case get('$metrics') of - undefined -> - #{Name => Value}; - Metrics -> - maps:update_with(Name, fun(Cnt) -> Cnt + Value end, Value, Metrics) - end), - ok. - --spec(commit() -> ok). -commit() -> - case get('$metrics') of - undefined -> ok; - Metrics -> - _ = erase('$metrics'), - lists:foreach(fun update_counter/1, maps:to_list(Metrics)) - end. - -update_counter({Name, Value}) -> - update_counter(Name, Value). - -update_counter(Name, Value) -> - CRef = persistent_term:get(?MODULE), - CIdx = case reserved_idx(Name) of - Idx when is_integer(Idx) -> Idx; - undefined -> - ets:lookup_element(?TAB, Name, 4) - end, - counters:add(CRef, CIdx, Value). - -%%-------------------------------------------------------------------- -%% Inc received/sent metrics -%%-------------------------------------------------------------------- - -%% @doc Inc packets received. --spec(inc_recv(emqx_types:packet()) -> ok). -inc_recv(Packet) -> - inc('packets.received'), - do_inc_recv(Packet). - -do_inc_recv(?PACKET(?CONNECT)) -> - inc('packets.connect.received'); -do_inc_recv(?PUBLISH_PACKET(QoS)) -> - inc('messages.received'), - case QoS of - ?QOS_0 -> inc('messages.qos0.received'); - ?QOS_1 -> inc('messages.qos1.received'); - ?QOS_2 -> inc('messages.qos2.received'); - _other -> ok - end, - inc('packets.publish.received'); -do_inc_recv(?PACKET(?PUBACK)) -> - inc('packets.puback.received'); -do_inc_recv(?PACKET(?PUBREC)) -> - inc('packets.pubrec.received'); -do_inc_recv(?PACKET(?PUBREL)) -> - inc('packets.pubrel.received'); -do_inc_recv(?PACKET(?PUBCOMP)) -> - inc('packets.pubcomp.received'); -do_inc_recv(?PACKET(?SUBSCRIBE)) -> - inc('packets.subscribe.received'); -do_inc_recv(?PACKET(?UNSUBSCRIBE)) -> - inc('packets.unsubscribe.received'); -do_inc_recv(?PACKET(?PINGREQ)) -> - inc('packets.pingreq.received'); -do_inc_recv(?PACKET(?DISCONNECT)) -> - inc('packets.disconnect.received'); -do_inc_recv(?PACKET(?AUTH)) -> - inc('packets.auth.received'); -do_inc_recv(_Packet) -> ok. - -%% @doc Inc packets sent. Will not count $SYS PUBLISH. --spec(inc_sent(emqx_types:packet()) -> ok). -inc_sent(?PUBLISH_PACKET(_QoS, <<"$SYS/", _/binary>>, _, _)) -> - ok; -inc_sent(Packet) -> - inc('packets.sent'), - do_inc_sent(Packet). - -do_inc_sent(?CONNACK_PACKET(ReasonCode)) -> - (ReasonCode == ?RC_SUCCESS) orelse inc('packets.connack.error'), - (ReasonCode == ?RC_NOT_AUTHORIZED) andalso inc('packets.connack.auth_error'), - (ReasonCode == ?RC_BAD_USER_NAME_OR_PASSWORD) andalso inc('packets.connack.auth_error'), - inc('packets.connack.sent'); - -do_inc_sent(?PUBLISH_PACKET(QoS)) -> - inc('messages.sent'), - case QoS of - ?QOS_0 -> inc('messages.qos0.sent'); - ?QOS_1 -> inc('messages.qos1.sent'); - ?QOS_2 -> inc('messages.qos2.sent'); - _other -> ok - end, - inc('packets.publish.sent'); -do_inc_sent(?PUBACK_PACKET(_PacketId, ReasonCode)) -> - (ReasonCode >= ?RC_UNSPECIFIED_ERROR) andalso inc('packets.publish.error'), - (ReasonCode == ?RC_NOT_AUTHORIZED) andalso inc('packets.publish.auth_error'), - inc('packets.puback.sent'); -do_inc_sent(?PUBREC_PACKET(_PacketId, ReasonCode)) -> - (ReasonCode >= ?RC_UNSPECIFIED_ERROR) andalso inc('packets.publish.error'), - (ReasonCode == ?RC_NOT_AUTHORIZED) andalso inc('packets.publish.auth_error'), - inc('packets.pubrec.sent'); -do_inc_sent(?PACKET(?PUBREL)) -> - inc('packets.pubrel.sent'); -do_inc_sent(?PACKET(?PUBCOMP)) -> - inc('packets.pubcomp.sent'); -do_inc_sent(?PACKET(?SUBACK)) -> - inc('packets.suback.sent'); -do_inc_sent(?PACKET(?UNSUBACK)) -> - inc('packets.unsuback.sent'); -do_inc_sent(?PACKET(?PINGRESP)) -> - inc('packets.pingresp.sent'); -do_inc_sent(?PACKET(?DISCONNECT)) -> - inc('packets.disconnect.sent'); -do_inc_sent(?PACKET(?AUTH)) -> - inc('packets.auth.sent'); -do_inc_sent(_Packet) -> ok. - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - % Create counters array - CRef = counters:new(?MAX_SIZE, [write_concurrency]), - ok = persistent_term:put(?MODULE, CRef), - % Create index mapping table - ok = emqx_tables:new(?TAB, [{keypos, 2}, {read_concurrency, true}]), - Metrics = lists:append([?BYTES_METRICS, - ?PACKET_METRICS, - ?MESSAGE_METRICS, - ?DELIVERY_METRICS, - ?CLIENT_METRICS, - ?SESSION_METRICS - ]), - % Store reserved indices - ok = lists:foreach(fun({Type, Name}) -> - Idx = reserved_idx(Name), - Metric = #metric{name = Name, type = Type, idx = Idx}, - true = ets:insert(?TAB, Metric), - ok = counters:put(CRef, Idx, 0) - end, Metrics), - {ok, #state{next_idx = ?RESERVED_IDX + 1}, hibernate}. - -handle_call({create, Type, Name}, _From, State = #state{next_idx = ?MAX_SIZE}) -> - ?LOG(error, "Failed to create ~s:~s for index exceeded.", [Type, Name]), - {reply, {error, metric_index_exceeded}, State}; - -handle_call({create, Type, Name}, _From, State = #state{next_idx = NextIdx}) -> - case ets:lookup(?TAB, Name) of - [#metric{idx = Idx}] -> - ?LOG(info, "~s already exists.", [Name]), - {reply, {ok, Idx}, State}; - [] -> - Metric = #metric{name = Name, type = Type, idx = NextIdx}, - true = ets:insert(?TAB, Metric), - {reply, {ok, NextIdx}, State#state{next_idx = NextIdx + 1}} - end; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -reserved_idx('bytes.received') -> 01; -reserved_idx('bytes.sent') -> 02; -%% Reserved indices of packet's metrics -reserved_idx('packets.received') -> 10; -reserved_idx('packets.sent') -> 11; -reserved_idx('packets.connect.received') -> 12; -reserved_idx('packets.connack.sent') -> 13; -reserved_idx('packets.connack.error') -> 14; -reserved_idx('packets.connack.auth_error') -> 15; -reserved_idx('packets.publish.received') -> 16; -reserved_idx('packets.publish.sent') -> 17; -reserved_idx('packets.publish.inuse') -> 18; -reserved_idx('packets.publish.error') -> 19; -reserved_idx('packets.publish.auth_error') -> 20; -reserved_idx('packets.puback.received') -> 21; -reserved_idx('packets.puback.sent') -> 22; -reserved_idx('packets.puback.inuse') -> 23; -reserved_idx('packets.puback.missed') -> 24; -reserved_idx('packets.pubrec.received') -> 25; -reserved_idx('packets.pubrec.sent') -> 26; -reserved_idx('packets.pubrec.inuse') -> 27; -reserved_idx('packets.pubrec.missed') -> 28; -reserved_idx('packets.pubrel.received') -> 29; -reserved_idx('packets.pubrel.sent') -> 30; -reserved_idx('packets.pubrel.missed') -> 31; -reserved_idx('packets.pubcomp.received') -> 32; -reserved_idx('packets.pubcomp.sent') -> 33; -reserved_idx('packets.pubcomp.inuse') -> 34; -reserved_idx('packets.pubcomp.missed') -> 35; -reserved_idx('packets.subscribe.received') -> 36; -reserved_idx('packets.subscribe.error') -> 37; -reserved_idx('packets.subscribe.auth_error') -> 38; -reserved_idx('packets.suback.sent') -> 39; -reserved_idx('packets.unsubscribe.received') -> 40; -reserved_idx('packets.unsubscribe.error') -> 41; -reserved_idx('packets.unsuback.sent') -> 42; -reserved_idx('packets.pingreq.received') -> 43; -reserved_idx('packets.pingresp.sent') -> 44; -reserved_idx('packets.disconnect.received') -> 45; -reserved_idx('packets.disconnect.sent') -> 46; -reserved_idx('packets.auth.received') -> 47; -reserved_idx('packets.auth.sent') -> 48; -reserved_idx('packets.publish.dropped') -> 49; -%% Reserved indices of message's metrics -reserved_idx('messages.received') -> 100; -reserved_idx('messages.sent') -> 101; -reserved_idx('messages.qos0.received') -> 102; -reserved_idx('messages.qos0.sent') -> 103; -reserved_idx('messages.qos1.received') -> 104; -reserved_idx('messages.qos1.sent') -> 105; -reserved_idx('messages.qos2.received') -> 106; -reserved_idx('messages.qos2.sent') -> 107; -reserved_idx('messages.publish') -> 108; -reserved_idx('messages.dropped') -> 109; -reserved_idx('messages.dropped.expired') -> 110; -reserved_idx('messages.dropped.no_subscribers') -> 111; -reserved_idx('messages.forward') -> 112; -reserved_idx('messages.retained') -> 113; -reserved_idx('messages.delayed') -> 114; -reserved_idx('messages.delivered') -> 115; -reserved_idx('messages.acked') -> 116; -reserved_idx('delivery.expired') -> 117; -reserved_idx('delivery.dropped') -> 118; -reserved_idx('delivery.dropped.no_local') -> 119; -reserved_idx('delivery.dropped.too_large') -> 120; -reserved_idx('delivery.dropped.qos0_msg') -> 121; -reserved_idx('delivery.dropped.queue_full') -> 122; -reserved_idx('delivery.dropped.expired') -> 123; - -reserved_idx('client.connect') -> 200; -reserved_idx('client.connack') -> 201; -reserved_idx('client.connected') -> 202; -reserved_idx('client.authenticate') -> 203; -reserved_idx('client.enhanced_authenticate') -> 204; -reserved_idx('client.auth.anonymous') -> 205; -reserved_idx('client.check_acl') -> 206; -reserved_idx('client.subscribe') -> 207; -reserved_idx('client.unsubscribe') -> 208; -reserved_idx('client.disconnected') -> 209; - -reserved_idx('session.created') -> 220; -reserved_idx('session.resumed') -> 221; -reserved_idx('session.takeovered') -> 222; -reserved_idx('session.discarded') -> 223; -reserved_idx('session.terminated') -> 224; - -reserved_idx(_) -> undefined. - diff --git a/_build/emqx/lib/emqx/src/emqx_misc.erl b/_build/emqx/lib/emqx/src/emqx_misc.erl deleted file mode 100644 index 88e3c91a6d..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_misc.erl +++ /dev/null @@ -1,235 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_misc). - --compile(inline). - --include("types.hrl"). --include("logger.hrl"). - --export([ merge_opts/2 - , maybe_apply/2 - , compose/1 - , compose/2 - , run_fold/3 - , pipeline/3 - , start_timer/2 - , start_timer/3 - , cancel_timer/1 - , drain_deliver/0 - , drain_deliver/1 - , drain_down/1 - , check_oom/1 - , check_oom/2 - , tune_heap_size/1 - , proc_name/2 - , proc_stats/0 - , proc_stats/1 - , rand_seed/0 - , now_to_secs/1 - , now_to_ms/1 - , index_of/2 - ]). - -%% @doc Merge options --spec(merge_opts(Opts, Opts) -> Opts when Opts :: proplists:proplist()). -merge_opts(Defaults, Options) -> - lists:foldl( - fun({Opt, Val}, Acc) -> - lists:keystore(Opt, 1, Acc, {Opt, Val}); - (Opt, Acc) -> - lists:usort([Opt | Acc]) - end, Defaults, Options). - -%% @doc Apply a function to a maybe argument. --spec(maybe_apply(fun((maybe(A)) -> maybe(A)), maybe(A)) - -> maybe(A) when A :: any()). -maybe_apply(_Fun, undefined) -> undefined; -maybe_apply(Fun, Arg) when is_function(Fun) -> - erlang:apply(Fun, [Arg]). - --spec(compose(list(F)) -> G - when F :: fun((any()) -> any()), - G :: fun((any()) -> any())). -compose([F|More]) -> compose(F, More). - --spec(compose(F, G|[Gs]) -> C - when F :: fun((X1) -> X2), - G :: fun((X2) -> X3), - Gs :: [fun((Xn) -> Xn1)], - C :: fun((X1) -> Xm), - X3 :: any(), Xn :: any(), Xn1 :: any(), Xm :: any()). -compose(F, G) when is_function(G) -> fun(X) -> G(F(X)) end; -compose(F, [G]) -> compose(F, G); -compose(F, [G|More]) -> compose(compose(F, G), More). - -%% @doc RunFold -run_fold([], Acc, _State) -> - Acc; -run_fold([Fun|More], Acc, State) -> - run_fold(More, Fun(Acc, State), State). - -%% @doc Pipeline -pipeline([], Input, State) -> - {ok, Input, State}; - -pipeline([Fun|More], Input, State) -> - case apply_fun(Fun, Input, State) of - ok -> pipeline(More, Input, State); - {ok, NState} -> - pipeline(More, Input, NState); - {ok, Output, NState} -> - pipeline(More, Output, NState); - {error, Reason} -> - {error, Reason, State}; - {error, Reason, NState} -> - {error, Reason, NState} - end. - --compile({inline, [apply_fun/3]}). -apply_fun(Fun, Input, State) -> - case erlang:fun_info(Fun, arity) of - {arity, 1} -> Fun(Input); - {arity, 2} -> Fun(Input, State) - end. - --spec(start_timer(integer(), term()) -> reference()). -start_timer(Interval, Msg) -> - start_timer(Interval, self(), Msg). - --spec(start_timer(integer(), pid() | atom(), term()) -> reference()). -start_timer(Interval, Dest, Msg) -> - erlang:start_timer(erlang:ceil(Interval), Dest, Msg). - --spec(cancel_timer(maybe(reference())) -> ok). -cancel_timer(Timer) when is_reference(Timer) -> - case erlang:cancel_timer(Timer) of - false -> - receive {timeout, Timer, _} -> ok after 0 -> ok end; - _ -> ok - end; -cancel_timer(_) -> ok. - -%% @doc Drain delivers -drain_deliver() -> - drain_deliver(-1). - -drain_deliver(N) when is_integer(N) -> - drain_deliver(N, []). - -drain_deliver(0, Acc) -> - lists:reverse(Acc); -drain_deliver(N, Acc) -> - receive - Deliver = {deliver, _Topic, _Msg} -> - drain_deliver(N-1, [Deliver|Acc]) - after 0 -> - lists:reverse(Acc) - end. - -%% @doc Drain process 'DOWN' events. --spec(drain_down(pos_integer()) -> list(pid())). -drain_down(Cnt) when Cnt > 0 -> - drain_down(Cnt, []). - -drain_down(0, Acc) -> - lists:reverse(Acc); -drain_down(Cnt, Acc) -> - receive - {'DOWN', _MRef, process, Pid, _Reason} -> - drain_down(Cnt-1, [Pid|Acc]) - after 0 -> - lists:reverse(Acc) - end. - -%% @doc Check process's mailbox and heapsize against OOM policy, -%% return `ok | {shutdown, Reason}' accordingly. -%% `ok': There is nothing out of the ordinary. -%% `shutdown': Some numbers (message queue length hit the limit), -%% hence shutdown for greater good (system stability). --spec(check_oom(emqx_types:oom_policy()) -> ok | {shutdown, term()}). -check_oom(Policy) -> - check_oom(self(), Policy). - --spec(check_oom(pid(), emqx_types:oom_policy()) -> ok | {shutdown, term()}). -check_oom(Pid, #{message_queue_len := MaxQLen, - max_heap_size := MaxHeapSize}) -> - case process_info(Pid, [message_queue_len, total_heap_size]) of - undefined -> ok; - [{message_queue_len, QLen}, {total_heap_size, HeapSize}] -> - do_check_oom([{QLen, MaxQLen, message_queue_too_long}, - {HeapSize, MaxHeapSize, proc_heap_too_large} - ]) - end. - -do_check_oom([]) -> ok; -do_check_oom([{Val, Max, Reason}|Rest]) -> - case is_integer(Max) andalso (0 < Max) andalso (Max < Val) of - true -> {shutdown, Reason}; - false -> do_check_oom(Rest) - end. - -tune_heap_size(#{max_heap_size := MaxHeapSize}) -> - %% If set to zero, the limit is disabled. - erlang:process_flag(max_heap_size, #{size => MaxHeapSize, - kill => false, - error_logger => true - }); -tune_heap_size(undefined) -> ok. - --spec(proc_name(atom(), pos_integer()) -> atom()). -proc_name(Mod, Id) -> - list_to_atom(lists:concat([Mod, "_", Id])). - -%% Get Proc's Stats. --spec(proc_stats() -> emqx_types:stats()). -proc_stats() -> proc_stats(self()). - --spec(proc_stats(pid()) -> emqx_types:stats()). -proc_stats(Pid) -> - case process_info(Pid, [message_queue_len, - heap_size, - total_heap_size, - reductions, - memory]) of - undefined -> []; - [{message_queue_len, Len}|ProcStats] -> - [{mailbox_len, Len}|ProcStats] - end. - -rand_seed() -> - rand:seed(exsplus, erlang:timestamp()). - --spec(now_to_secs(erlang:timestamp()) -> pos_integer()). -now_to_secs({MegaSecs, Secs, _MicroSecs}) -> - MegaSecs * 1000000 + Secs. - --spec(now_to_ms(erlang:timestamp()) -> pos_integer()). -now_to_ms({MegaSecs, Secs, MicroSecs}) -> - (MegaSecs * 1000000 + Secs) * 1000 + round(MicroSecs/1000). - -%% lists:index_of/2 -index_of(E, L) -> - index_of(E, 1, L). - -index_of(_E, _I, []) -> - error(badarg); -index_of(E, I, [E|_]) -> - I; -index_of(E, I, [_|L]) -> - index_of(E, I+1, L). - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_acl_internal.erl b/_build/emqx/lib/emqx/src/emqx_mod_acl_internal.erl deleted file mode 100644 index 770f90c83e..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_acl_internal.erl +++ /dev/null @@ -1,120 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_acl_internal). - --behaviour(emqx_gen_mod). - --include("emqx.hrl"). --include("logger.hrl"). - --logger_header("[ACL_INTERNAL]"). - -%% APIs --export([check_acl/5]). - -%% emqx_gen_mod callbacks --export([ load/1 - , unload/1 - , reload/1 - , description/0 - ]). - --type(acl_rules() :: #{publish => [emqx_access_rule:rule()], - subscribe => [emqx_access_rule:rule()]}). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -load(_Env) -> - Rules = rules_from_file(emqx:get_env(acl_file)), - emqx_hooks:add('client.check_acl', {?MODULE, check_acl, [Rules]}, -1). - -unload(_Env) -> - emqx_hooks:del('client.check_acl', {?MODULE, check_acl}). - -reload(_Env) -> - emqx_acl_cache:is_enabled() andalso ( - lists:foreach( - fun(Pid) -> erlang:send(Pid, clean_acl_cache) end, - emqx_cm:all_channels())), - unload([]), load([]). - -description() -> - "EMQ X Internal ACL Module". -%%-------------------------------------------------------------------- -%% ACL callbacks -%%-------------------------------------------------------------------- - -%% @doc Check ACL --spec(check_acl(emqx_types:clientinfo(), emqx_types:pubsub(), emqx_topic:topic(), - emqx_access_rule:acl_result(), acl_rules()) - -> {ok, allow} | {ok, deny} | ok). -check_acl(Client, PubSub, Topic, _AclResult, Rules) -> - case match(Client, Topic, lookup(PubSub, Rules)) of - {matched, allow} -> {ok, allow}; - {matched, deny} -> {ok, deny}; - nomatch -> ok - end. - -%%-------------------------------------------------------------------- -%% Internal Functions -%%-------------------------------------------------------------------- -lookup(PubSub, Rules) -> - maps:get(PubSub, Rules, []). - -match(_Client, _Topic, []) -> - nomatch; -match(Client, Topic, [Rule|Rules]) -> - case emqx_access_rule:match(Client, Topic, Rule) of - nomatch -> - match(Client, Topic, Rules); - {matched, AllowDeny} -> - {matched, AllowDeny} - end. - --spec(rules_from_file(file:filename()) -> map()). -rules_from_file(AclFile) -> - case file:consult(AclFile) of - {ok, Terms} -> - Rules = [emqx_access_rule:compile(Term) || Term <- Terms], - #{publish => [Rule || Rule <- Rules, filter(publish, Rule)], - subscribe => [Rule || Rule <- Rules, filter(subscribe, Rule)]}; - {error, eacces} -> - ?LOG(alert, "Insufficient permissions to read the ~s file", [AclFile]), - #{}; - {error, enoent} -> - ?LOG(alert, "The ~s file does not exist", [AclFile]), - #{}; - {error, Reason} -> - ?LOG(alert, "Failed to read ~s: ~p", [AclFile, Reason]), - #{} - end. - -filter(_PubSub, {allow, all}) -> - true; -filter(_PubSub, {deny, all}) -> - true; -filter(publish, {_AllowDeny, _Who, publish, _Topics}) -> - true; -filter(_PubSub, {_AllowDeny, _Who, pubsub, _Topics}) -> - true; -filter(subscribe, {_AllowDeny, _Who, subscribe, _Topics}) -> - true; -filter(_PubSub, {_AllowDeny, _Who, _, _Topics}) -> - false. - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_delayed.erl b/_build/emqx/lib/emqx/src/emqx_mod_delayed.erl deleted file mode 100644 index b4ea28e776..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_delayed.erl +++ /dev/null @@ -1,191 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_delayed). - --behaviour(gen_server). --behaviour(emqx_gen_mod). - --include_lib("emqx/include/emqx.hrl"). --include_lib("emqx/include/logger.hrl"). - -%% emqx_gen_mod callbacks --export([ load/1 - , unload/1 - , description/0 - ]). - --export([ start_link/0 - , on_message_publish/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --record(delayed_message, - { key - , msg - }). - --define(TAB, ?MODULE). --define(SERVER, ?MODULE). --define(MAX_INTERVAL, 4294967). - -%%-------------------------------------------------------------------- -%% Load/Unload -%%-------------------------------------------------------------------- - --spec(load(list()) -> ok). -load(_Env) -> - emqx_mod_sup:start_child(?MODULE, worker), - emqx:hook('message.publish', {?MODULE, on_message_publish, []}). - --spec(unload(list()) -> ok). -unload(_Env) -> - emqx:unhook('message.publish', {?MODULE, on_message_publish}), - emqx_mod_sup:stop_child(?MODULE). - -description() -> - "EMQ X Delayed Publish Module". -%%-------------------------------------------------------------------- -%% Hooks -%%-------------------------------------------------------------------- - -on_message_publish(Msg = #message{id = Id, topic = <<"$delayed/", Topic/binary>>, timestamp = Ts}) -> - [Delay, Topic1] = binary:split(Topic, <<"/">>), - PubAt = case binary_to_integer(Delay) of - Interval when Interval < ?MAX_INTERVAL -> - Interval + erlang:round(Ts / 1000); - Timestamp -> - %% Check malicious timestamp? - case (Timestamp - erlang:round(Ts / 1000)) > ?MAX_INTERVAL of - true -> error(invalid_delayed_timestamp); - false -> Timestamp - end - end, - PubMsg = Msg#message{topic = Topic1}, - Headers = PubMsg#message.headers, - ok = store(#delayed_message{key = {PubAt, Id}, msg = PubMsg}), - {stop, PubMsg#message{headers = Headers#{allow_publish => false}}}; - -on_message_publish(Msg) -> - {ok, Msg}. - -%%-------------------------------------------------------------------- -%% Start delayed publish server -%%-------------------------------------------------------------------- - --spec(start_link() -> emqx_types:startlink_ret()). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - --spec(store(#delayed_message{}) -> ok). -store(DelayedMsg) -> - gen_server:call(?SERVER, {store, DelayedMsg}, infinity). - -%%-------------------------------------------------------------------- -%% gen_server callback -%%-------------------------------------------------------------------- - -init([]) -> - ok = ekka_mnesia:create_table(?TAB, [ - {type, ordered_set}, - {disc_copies, [node()]}, - {local_content, true}, - {record_name, delayed_message}, - {attributes, record_info(fields, delayed_message)}]), - ok = ekka_mnesia:copy_table(?TAB, disc_copies), - {ok, ensure_publish_timer(#{timer => undefined, publish_at => 0})}. - -handle_call({store, DelayedMsg = #delayed_message{key = Key}}, _From, State) -> - ok = mnesia:dirty_write(?TAB, DelayedMsg), - emqx_metrics:set('messages.delayed', delayed_count()), - {reply, ok, ensure_publish_timer(Key, State)}; - -handle_call(Req, _From, State) -> - ?LOG(error, "[Delayed] Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "[Delayed] Unexpected cast: ~p", [Msg]), - {noreply, State}. - -%% Do Publish... -handle_info({timeout, TRef, do_publish}, State = #{timer := TRef}) -> - DeletedKeys = do_publish(mnesia:dirty_first(?TAB), os:system_time(seconds)), - lists:foreach(fun(Key) -> mnesia:dirty_delete(?TAB, Key) end, DeletedKeys), - emqx_metrics:set('messages.delayed', delayed_count()), - {noreply, ensure_publish_timer(State#{timer := undefined, publish_at := 0})}; - -handle_info(Info, State) -> - ?LOG(error, "[Delayed] Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{timer := TRef}) -> - emqx_misc:cancel_timer(TRef). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -%% Ensure publish timer -ensure_publish_timer(State) -> - ensure_publish_timer(mnesia:dirty_first(?TAB), State). - -ensure_publish_timer('$end_of_table', State) -> - State#{timer := undefined, publish_at := 0}; -ensure_publish_timer({Ts, _Id}, State = #{timer := undefined}) -> - ensure_publish_timer(Ts, os:system_time(seconds), State); -ensure_publish_timer({Ts, _Id}, State = #{timer := TRef, publish_at := PubAt}) - when Ts < PubAt -> - ok = emqx_misc:cancel_timer(TRef), - ensure_publish_timer(Ts, os:system_time(seconds), State); -ensure_publish_timer(_Key, State) -> - State. - -ensure_publish_timer(Ts, Now, State) -> - Interval = max(1, Ts - Now), - TRef = emqx_misc:start_timer(timer:seconds(Interval), do_publish), - State#{timer := TRef, publish_at := Now + Interval}. - -do_publish(Key, Now) -> - do_publish(Key, Now, []). - -%% Do publish -do_publish('$end_of_table', _Now, Acc) -> - Acc; -do_publish({Ts, _Id}, Now, Acc) when Ts > Now -> - Acc; -do_publish(Key = {Ts, _Id}, Now, Acc) when Ts =< Now -> - case mnesia:dirty_read(?TAB, Key) of - [] -> ok; - [#delayed_message{msg = Msg}] -> - emqx_pool:async_submit(fun emqx_broker:publish/1, [Msg]) - end, - do_publish(mnesia:dirty_next(?TAB, Key), Now, [Key|Acc]). - --spec(delayed_count() -> non_neg_integer()). -delayed_count() -> mnesia:table_info(?TAB, size). - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_presence.erl b/_build/emqx/lib/emqx/src/emqx_mod_presence.erl deleted file mode 100644 index f5aa2279ea..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_presence.erl +++ /dev/null @@ -1,130 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_presence). - --behaviour(emqx_gen_mod). - --include("emqx.hrl"). --include("logger.hrl"). - --logger_header("[Presence]"). - -%% emqx_gen_mod callbacks --export([ load/1 - , unload/1 - , description/0 - ]). - --export([ on_client_connected/3 - , on_client_disconnected/4 - ]). - --ifdef(TEST). --export([reason/1]). --endif. - -load(Env) -> - emqx_hooks:add('client.connected', {?MODULE, on_client_connected, [Env]}), - emqx_hooks:add('client.disconnected', {?MODULE, on_client_disconnected, [Env]}). - -unload(_Env) -> - emqx_hooks:del('client.connected', {?MODULE, on_client_connected}), - emqx_hooks:del('client.disconnected', {?MODULE, on_client_disconnected}). - -description() -> - "EMQ X Presence Module". -%%-------------------------------------------------------------------- -%% Callbacks -%%-------------------------------------------------------------------- - -on_client_connected(ClientInfo = #{clientid := ClientId}, ConnInfo, Env) -> - Presence = connected_presence(ClientInfo, ConnInfo), - case emqx_json:safe_encode(Presence) of - {ok, Payload} -> - emqx_broker:safe_publish( - make_msg(qos(Env), topic(connected, ClientId), Payload)); - {error, _Reason} -> - ?LOG(error, "Failed to encode 'connected' presence: ~p", [Presence]) - end. - -on_client_disconnected(_ClientInfo = #{clientid := ClientId, username := Username}, - Reason, _ConnInfo = #{disconnected_at := DisconnectedAt}, Env) -> - Presence = #{clientid => ClientId, - username => Username, - reason => reason(Reason), - disconnected_at => DisconnectedAt, - ts => erlang:system_time(millisecond) - }, - case emqx_json:safe_encode(Presence) of - {ok, Payload} -> - emqx_broker:safe_publish( - make_msg(qos(Env), topic(disconnected, ClientId), Payload)); - {error, _Reason} -> - ?LOG(error, "Failed to encode 'disconnected' presence: ~p", [Presence]) - end. - -%%-------------------------------------------------------------------- -%% Helper functions -%%-------------------------------------------------------------------- - -connected_presence(#{peerhost := PeerHost, - sockport := SockPort, - clientid := ClientId, - username := Username - }, - #{clean_start := CleanStart, - proto_name := ProtoName, - proto_ver := ProtoVer, - keepalive := Keepalive, - connected_at := ConnectedAt, - expiry_interval := ExpiryInterval - }) -> - #{clientid => ClientId, - username => Username, - ipaddress => ntoa(PeerHost), - sockport => SockPort, - proto_name => ProtoName, - proto_ver => ProtoVer, - keepalive => Keepalive, - connack => 0, %% Deprecated? - clean_start => CleanStart, - expiry_interval => ExpiryInterval, - connected_at => ConnectedAt, - ts => erlang:system_time(millisecond) - }. - -make_msg(QoS, Topic, Payload) -> - emqx_message:set_flag( - sys, emqx_message:make( - ?MODULE, QoS, Topic, iolist_to_binary(Payload))). - -topic(connected, ClientId) -> - emqx_topic:systop(iolist_to_binary(["clients/", ClientId, "/connected"])); -topic(disconnected, ClientId) -> - emqx_topic:systop(iolist_to_binary(["clients/", ClientId, "/disconnected"])). - -qos(Env) -> proplists:get_value(qos, Env, 0). - --compile({inline, [reason/1]}). -reason(Reason) when is_atom(Reason) -> Reason; -reason({shutdown, Reason}) when is_atom(Reason) -> Reason; -reason({Error, _}) when is_atom(Error) -> Error; -reason(_) -> internal_error. - --compile({inline, [ntoa/1]}). -ntoa(IpAddr) -> iolist_to_binary(inet:ntoa(IpAddr)). - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_rewrite.erl b/_build/emqx/lib/emqx/src/emqx_mod_rewrite.erl deleted file mode 100644 index 9702b73501..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_rewrite.erl +++ /dev/null @@ -1,98 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_rewrite). - --behaviour(emqx_gen_mod). - --include_lib("emqx.hrl"). --include_lib("emqx_mqtt.hrl"). - --ifdef(TEST). --export([ compile/1 - , match_and_rewrite/2 - ]). --endif. - -%% APIs --export([ rewrite_subscribe/4 - , rewrite_unsubscribe/4 - , rewrite_publish/2 - ]). - -%% emqx_gen_mod callbacks --export([ load/1 - , unload/1 - , description/0 - ]). - -%%-------------------------------------------------------------------- -%% Load/Unload -%%-------------------------------------------------------------------- - -load(RawRules) -> - Rules = compile(RawRules), - emqx_hooks:add('client.subscribe', {?MODULE, rewrite_subscribe, [Rules]}), - emqx_hooks:add('client.unsubscribe', {?MODULE, rewrite_unsubscribe, [Rules]}), - emqx_hooks:add('message.publish', {?MODULE, rewrite_publish, [Rules]}). - -rewrite_subscribe(_ClientInfo, _Properties, TopicFilters, Rules) -> - {ok, [{match_and_rewrite(Topic, Rules), Opts} || {Topic, Opts} <- TopicFilters]}. - -rewrite_unsubscribe(_ClientInfo, _Properties, TopicFilters, Rules) -> - {ok, [{match_and_rewrite(Topic, Rules), Opts} || {Topic, Opts} <- TopicFilters]}. - -rewrite_publish(Message = #message{topic = Topic}, Rules) -> - {ok, Message#message{topic = match_and_rewrite(Topic, Rules)}}. - -unload(_) -> - emqx_hooks:del('client.subscribe', {?MODULE, rewrite_subscribe}), - emqx_hooks:del('client.unsubscribe', {?MODULE, rewrite_unsubscribe}), - emqx_hooks:del('message.publish', {?MODULE, rewrite_publish}). - -description() -> - "EMQ X Topic Rewrite Module". -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -compile(Rules) -> - lists:map(fun({rewrite, Topic, Re, Dest}) -> - {ok, MP} = re:compile(Re), - {rewrite, Topic, MP, Dest} - end, Rules). - -match_and_rewrite(Topic, []) -> - Topic; - -match_and_rewrite(Topic, [{rewrite, Filter, MP, Dest} | Rules]) -> - case emqx_topic:match(Topic, Filter) of - true -> rewrite(Topic, MP, Dest); - false -> match_and_rewrite(Topic, Rules) - end. - -rewrite(Topic, MP, Dest) -> - case re:run(Topic, MP, [{capture, all_but_first, list}]) of - {match, Captured} -> - Vars = lists:zip(["\\$" ++ integer_to_list(I) - || I <- lists:seq(1, length(Captured))], Captured), - iolist_to_binary(lists:foldl( - fun({Var, Val}, Acc) -> - re:replace(Acc, Var, Val, [global]) - end, Dest, Vars)); - nomatch -> Topic - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_subscription.erl b/_build/emqx/lib/emqx/src/emqx_mod_subscription.erl deleted file mode 100644 index b6d04528b8..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_subscription.erl +++ /dev/null @@ -1,65 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_subscription). - --behaviour(emqx_gen_mod). - --include_lib("emqx.hrl"). --include_lib("emqx_mqtt.hrl"). - -%% emqx_gen_mod callbacks --export([ load/1 - , unload/1 - , description/0 - ]). - -%% APIs --export([on_client_connected/3]). - -%%-------------------------------------------------------------------- -%% Load/Unload Hook -%%-------------------------------------------------------------------- - -load(Topics) -> - emqx_hooks:add('client.connected', {?MODULE, on_client_connected, [Topics]}). - -on_client_connected(#{clientid := ClientId, username := Username}, _ConnInfo = #{proto_ver := ProtoVer}, Topics) -> - Replace = fun(Topic) -> - rep(<<"%u">>, Username, rep(<<"%c">>, ClientId, Topic)) - end, - TopicFilters = case ProtoVer of - ?MQTT_PROTO_V5 -> [{Replace(Topic), SubOpts} || {Topic, SubOpts} <- Topics]; - _ -> [{Replace(Topic), #{qos => Qos}} || {Topic, #{qos := Qos}} <- Topics] - end, - self() ! {subscribe, TopicFilters}. - -unload(_) -> - emqx_hooks:del('client.connected', {?MODULE, on_client_connected}). - -description() -> - "EMQ X Subscription Module". -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -rep(<<"%c">>, ClientId, Topic) -> - emqx_topic:feed_var(<<"%c">>, ClientId, Topic); -rep(<<"%u">>, undefined, Topic) -> - Topic; -rep(<<"%u">>, Username, Topic) -> - emqx_topic:feed_var(<<"%u">>, Username, Topic). - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_sup.erl b/_build/emqx/lib/emqx/src/emqx_mod_sup.erl deleted file mode 100644 index b5512013c8..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_sup.erl +++ /dev/null @@ -1,63 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_sup). - --behaviour(supervisor). - --include("types.hrl"). - --export([ start_link/0 - , start_child/1 - , start_child/2 - , stop_child/1 - ]). - --export([init/1]). - -%% Helper macro for declaring children of supervisor --define(CHILD(Mod, Type), #{id => Mod, - start => {Mod, start_link, []}, - restart => permanent, - shutdown => 5000, - type => Type, - modules => [Mod]}). - --spec(start_link() -> startlink_ret()). -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -start_child(ChildSpec) when is_map(ChildSpec) -> - supervisor:start_child(?MODULE, ChildSpec). - -start_child(Mod, Type) when is_atom(Mod) andalso is_atom(Type) -> - supervisor:start_child(?MODULE, ?CHILD(Mod, Type)). - --spec(stop_child(any()) -> ok | {error, term()}). -stop_child(ChildId) -> - case supervisor:terminate_child(?MODULE, ChildId) of - ok -> supervisor:delete_child(?MODULE, ChildId); - Error -> Error - end. - -%%-------------------------------------------------------------------- -%% Supervisor callbacks -%%-------------------------------------------------------------------- - -init([]) -> - ok = emqx_tables:new(emqx_modules, [set, public, {write_concurrency, true}]), - {ok, {{one_for_one, 10, 100}, []}}. - diff --git a/_build/emqx/lib/emqx/src/emqx_mod_topic_metrics.erl b/_build/emqx/lib/emqx/src/emqx_mod_topic_metrics.erl deleted file mode 100644 index 66fac6ee4a..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mod_topic_metrics.erl +++ /dev/null @@ -1,378 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mod_topic_metrics). - --behaviour(gen_server). --behaviour(emqx_gen_mod). - --include("emqx.hrl"). --include("logger.hrl"). --include("emqx_mqtt.hrl"). - --logger_header("[TOPIC_METRICS]"). - --export([ load/1 - , unload/1 - , description/0 - ]). - --export([ on_message_publish/1 - , on_message_delivered/2 - , on_message_dropped/3 - ]). - -%% API functions --export([ start_link/0 - , stop/0 - ]). - --export([ inc/2 - , inc/3 - , val/2 - , rate/2 - , metrics/1 - , register/1 - , unregister/1 - , unregister_all/0 - , is_registered/1 - , all_registered_topics/0 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_info/2 - , handle_cast/2 - , terminate/2 - ]). - --define(CRefID(Topic), {?MODULE, Topic}). - --define(MAX_TOPICS, 512). --define(TAB, ?MODULE). - --define(TOPIC_METRICS, - ['messages.in', - 'messages.out', - 'messages.qos0.in', - 'messages.qos0.out', - 'messages.qos1.in', - 'messages.qos1.out', - 'messages.qos2.in', - 'messages.qos2.out', - 'messages.dropped' - ]). - --define(TICKING_INTERVAL, 1). - --record(speed, { - last = 0 :: number(), - tick = 1 :: number(), - last_v = 0 :: number(), - acc = 0 :: number(), - samples = [] :: list() - }). - --record(state, { - speeds :: #{{binary(), atom()} => #speed{}} - }). - -%%------------------------------------------------------------------------------ -%% APIs -%%------------------------------------------------------------------------------ - -load(_Env) -> - emqx_mod_sup:start_child(?MODULE, worker), - emqx:hook('message.publish', {?MODULE, on_message_publish, []}), - emqx:hook('message.dropped', {?MODULE, on_message_dropped, []}), - emqx:hook('message.delivered', {?MODULE, on_message_delivered, []}). - -unload(_Env) -> - emqx:unhook('message.publish', {?MODULE, on_message_publish}), - emqx:unhook('message.dropped', {?MODULE, on_message_dropped}), - emqx:unhook('message.delivered', {?MODULE, on_message_delivered}), - emqx_mod_sup:stop_child(?MODULE). - -description() -> - "EMQ X Topic Metrics Module". - -on_message_publish(#message{topic = Topic, qos = QoS}) -> - case is_registered(Topic) of - true -> - inc(Topic, 'messages.in'), - case QoS of - ?QOS_0 -> inc(Topic, 'messages.qos0.in'); - ?QOS_1 -> inc(Topic, 'messages.qos1.in'); - ?QOS_2 -> inc(Topic, 'messages.qos2.in') - end; - false -> - ok - end. - -on_message_delivered(_, #message{topic = Topic, qos = QoS}) -> - case is_registered(Topic) of - true -> - inc(Topic, 'messages.out'), - case QoS of - ?QOS_0 -> inc(Topic, 'messages.qos0.out'); - ?QOS_1 -> inc(Topic, 'messages.qos1.out'); - ?QOS_2 -> inc(Topic, 'messages.qos2.out') - end; - false -> - ok - end. - -on_message_dropped(#message{topic = Topic}, _, _) -> - case is_registered(Topic) of - true -> - inc(Topic, 'messages.dropped'); - false -> - ok - end. - -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - -stop() -> - gen_server:stop(?MODULE). - -inc(Topic, Metric) -> - inc(Topic, Metric, 1). - -inc(Topic, Metric, Val) -> - case get_counters(Topic) of - {error, not_found} -> - {error, not_found}; - CRef -> - counters:add(CRef, metrics_idx(Metric), Val) - end. - -val(Topic, Metric) -> - case ets:lookup(?TAB, Topic) of - [] -> - {error, not_found}; - [{Topic, CRef}] -> - counters:get(CRef, metrics_idx(Metric)) - end. - -rate(Topic, Metric) -> - gen_server:call(?MODULE, {get_rate, Topic, Metric}). - -metrics(Topic) -> - case ets:lookup(?TAB, Topic) of - [] -> - {error, not_found}; - [{Topic, CRef}] -> - lists:foldl(fun(Metric, Acc) -> - [{to_count(Metric), counters:get(CRef, metrics_idx(Metric))}, - {to_rate(Metric), rate(Topic, Metric)} | Acc] - end, [], ?TOPIC_METRICS) - end. - -register(Topic) when is_binary(Topic) -> - gen_server:call(?MODULE, {register, Topic}). - -unregister(Topic) when is_binary(Topic) -> - gen_server:call(?MODULE, {unregister, Topic}). - -unregister_all() -> - gen_server:call(?MODULE, {unregister, all}). - -is_registered(Topic) -> - ets:member(?TAB, Topic). - -all_registered_topics() -> - [Topic || {Topic, _CRef} <- ets:tab2list(?TAB)]. - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - erlang:process_flag(trap_exit, true), - ok = emqx_tables:new(?TAB, [{read_concurrency, true}]), - erlang:send_after(timer:seconds(?TICKING_INTERVAL), self(), ticking), - {ok, #state{speeds = #{}}, hibernate}. - -handle_call({register, Topic}, _From, State = #state{speeds = Speeds}) -> - case is_registered(Topic) of - true -> - {reply, {error, already_existed}, State}; - false -> - case number_of_registered_topics() < ?MAX_TOPICS of - true -> - CRef = counters:new(counters_size(), [write_concurrency]), - true = ets:insert(?TAB, {Topic, CRef}), - [counters:put(CRef, Idx, 0) || Idx <- lists:seq(1, counters_size())], - NSpeeds = lists:foldl(fun(Metric, Acc) -> - maps:put({Topic, Metric}, #speed{}, Acc) - end, Speeds, ?TOPIC_METRICS), - {reply, ok, State#state{speeds = NSpeeds}}; - false -> - {reply, {error, quota_exceeded}, State} - end - end; - -handle_call({unregister, all}, _From, State) -> - [delete_counters(Topic) || {Topic, _CRef} <- ets:tab2list(?TAB)], - {reply, ok, State#state{speeds = #{}}}; - -handle_call({unregister, Topic}, _From, State = #state{speeds = Speeds}) -> - case is_registered(Topic) of - false -> - {reply, ok, State}; - true -> - ok = delete_counters(Topic), - {reply, ok, State#state{speeds = maps:remove(Topic, Speeds)}} - end; - -handle_call({get_rate, Topic}, _From, State = #state{speeds = Speeds}) -> - case is_registered(Topic) of - false -> - {reply, {error, not_found}, State}; - true -> - lists:foldl(fun(Metric, Acc) -> - Speed = maps:get({Topic, Metric}, Speeds), - [{Metric, Speed#speed.last} | Acc] - end, [], ?TOPIC_METRICS) - end; - -handle_call({get_rate, Topic, Metric}, _From, State = #state{speeds = Speeds}) -> - case is_registered(Topic) of - false -> - {reply, {error, not_found}, State}; - true -> - case maps:get({Topic, Metric}, Speeds, undefined) of - undefined -> - {reply, {error, not_found}, State}; - #speed{last = Last} -> - {reply, Last, State} - end - end. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(ticking, State = #state{speeds = Speeds}) -> - NSpeeds = maps:map( - fun({Topic, Metric}, Speed) -> - case val(Topic, Metric) of - {error, not_found} -> maps:remove(Topic, Speeds); - Val -> calculate_speed(Val, Speed) - end - end, Speeds), - erlang:send_after(timer:seconds(5), self(), ticking), - {noreply, State#state{speeds = NSpeeds}}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -%%------------------------------------------------------------------------------ -%% Internal Functions -%%------------------------------------------------------------------------------ - -metrics_idx('messages.in') -> 01; -metrics_idx('messages.out') -> 02; -metrics_idx('messages.qos0.in') -> 03; -metrics_idx('messages.qos0.out') -> 04; -metrics_idx('messages.qos1.in') -> 05; -metrics_idx('messages.qos1.out') -> 06; -metrics_idx('messages.qos2.in') -> 07; -metrics_idx('messages.qos2.out') -> 08; -metrics_idx('messages.dropped') -> 09. - -to_count('messages.in') -> - 'messages.in.count'; -to_count('messages.out') -> - 'messages.out.count'; -to_count('messages.qos0.in') -> - 'messages.qos0.in.count'; -to_count('messages.qos0.out') -> - 'messages.qos0.out.count'; -to_count('messages.qos1.in') -> - 'messages.qos1.in.count'; -to_count('messages.qos1.out') -> - 'messages.qos1.out.count'; -to_count('messages.qos2.in') -> - 'messages.qos2.in.count'; -to_count('messages.qos2.out') -> - 'messages.qos2.out.count'; -to_count('messages.dropped') -> - 'messages.dropped.count'. - -to_rate('messages.in') -> - 'messages.in.rate'; -to_rate('messages.out') -> - 'messages.out.rate'; -to_rate('messages.qos0.in') -> - 'messages.qos0.in.rate'; -to_rate('messages.qos0.out') -> - 'messages.qos0.out.rate'; -to_rate('messages.qos1.in') -> - 'messages.qos1.in.rate'; -to_rate('messages.qos1.out') -> - 'messages.qos1.out.rate'; -to_rate('messages.qos2.in') -> - 'messages.qos2.in.rate'; -to_rate('messages.qos2.out') -> - 'messages.qos2.out.rate'; -to_rate('messages.dropped') -> - 'messages.dropped.rate'. - -delete_counters(Topic) -> - true = ets:delete(?TAB, Topic), - ok. - -get_counters(Topic) -> - case ets:lookup(?TAB, Topic) of - [] -> {error, not_found}; - [{Topic, CRef}] -> CRef - end. - -counters_size() -> - length(?TOPIC_METRICS). - -number_of_registered_topics() -> - proplists:get_value(size, ets:info(?TAB)). - -calculate_speed(CurVal, #speed{last_v = LastVal, tick = Tick, acc = Acc, samples = Samples}) -> - %% calculate the current speed based on the last value of the counter - CurSpeed = (CurVal - LastVal) / ?TICKING_INTERVAL, - - %% calculate the average speed in last 5 seconds - case Tick =< 5 of - true -> - Acc1 = Acc + CurSpeed, - #speed{last = Acc1 / Tick, - last_v = CurVal, - acc = Acc1, - samples = Samples ++ [CurSpeed], - tick = Tick + 1}; - false -> - [FirstSpeed | Speeds] = Samples, - Acc1 = Acc + CurSpeed - FirstSpeed, - #speed{last = Acc1 / Tick, - last_v = CurVal, - acc = Acc1, - samples = Speeds ++ [CurSpeed], - tick = Tick} - end. diff --git a/_build/emqx/lib/emqx/src/emqx_modules.erl b/_build/emqx/lib/emqx/src/emqx_modules.erl deleted file mode 100644 index 55fb440011..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_modules.erl +++ /dev/null @@ -1,169 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_modules). - --include("logger.hrl"). - --logger_header("[Modules]"). - --export([ list/0 - , load/0 - , load/1 - , unload/0 - , unload/1 - , reload/1 - , find_module/1 - , load_module/2 - ]). - -%% @doc List all available plugins --spec(list() -> [{atom(), boolean()}]). -list() -> - ets:tab2list(?MODULE). - -%% @doc Load all the extended modules. --spec(load() -> ok). -load() -> - case emqx:get_env(modules_loaded_file) of - undefined -> ok; - File -> - load_modules(File) - end. - -load(ModuleName) -> - case find_module(ModuleName) of - [] -> - ?LOG(alert, "Module ~s not found, cannot load it", [ModuleName]), - {error, not_found}; - [{ModuleName, true}] -> - ?LOG(notice, "Module ~s is already started", [ModuleName]), - {error, already_started}; - [{ModuleName, false}] -> - emqx_modules:load_module(ModuleName, true) - end. - -%% @doc Unload all the extended modules. --spec(unload() -> ok). -unload() -> - case emqx:get_env(modules_loaded_file) of - undefined -> ignore; - File -> - unload_modules(File) - end. - -unload(ModuleName) -> - case find_module(ModuleName) of - [] -> - ?LOG(alert, "Module ~s not found, cannot load it", [ModuleName]), - {error, not_found}; - [{ModuleName, false}] -> - ?LOG(error, "Module ~s is not started", [ModuleName]), - {error, not_started}; - [{ModuleName, true}] -> - unload_module(ModuleName, true) - end. - -reload(emqx_mod_acl_internal) -> - Modules = emqx:get_env(modules, []), - Env = proplists:get_value(emqx_mod_acl_internal, Modules, undefined), - case emqx_mod_acl_internal:reload(Env) of - ok -> - ?LOG(info, "Reload ~s module successfully.", [emqx_mod_acl_internal]); - {error, Error} -> - ?LOG(error, "Reload module ~s failed, cannot start for ~0p", [emqx_mod_acl_internal, Error]) - end; -reload(_) -> - ignore. - -find_module(ModuleName) -> - ets:lookup(?MODULE, ModuleName). - -filter_module(ModuleNames) -> - filter_module(ModuleNames, emqx:get_env(modules, [])). -filter_module([], Acc) -> - Acc; -filter_module([{ModuleName, true} | ModuleNames], Acc) -> - filter_module(ModuleNames, lists:keydelete(ModuleName, 1, Acc)); -filter_module([{_, false} | ModuleNames], Acc) -> - filter_module(ModuleNames, Acc). - -load_modules(File) -> - case file:consult(File) of - {ok, ModuleNames} -> - lists:foreach(fun({ModuleName, _}) -> - ets:insert(?MODULE, {ModuleName, false}) - end, filter_module(ModuleNames)), - lists:foreach(fun load_module/1, ModuleNames); - {error, Error} -> - ?LOG(alert, "Failed to read: ~p, error: ~p", [File, Error]) - end. - -load_module({ModuleName, true}) -> - emqx_modules:load_module(ModuleName, false); -load_module({ModuleName, false}) -> - ets:insert(?MODULE, {ModuleName, false}); -load_module(ModuleName) -> - load_module({ModuleName, true}). - -load_module(ModuleName, Persistent) -> - Modules = emqx:get_env(modules, []), - Env = proplists:get_value(ModuleName, Modules, undefined), - case ModuleName:load(Env) of - ok -> - ets:insert(?MODULE, {ModuleName, true}), - write_loaded(Persistent), - ?LOG(info, "Load ~s module successfully.", [ModuleName]); - {error, Error} -> - ?LOG(error, "Load module ~s failed, cannot load for ~0p", [ModuleName, Error]), - {error, Error} - end. - -unload_modules(File) -> - case file:consult(File) of - {ok, ModuleNames} -> - lists:foreach(fun unload_module/1, ModuleNames); - {error, Error} -> - ?LOG(alert, "Failed to read: ~p, error: ~p", [File, Error]) - end. -unload_module({ModuleName, true}) -> - unload_module(ModuleName, false); -unload_module({ModuleName, false}) -> - ets:insert(?MODULE, {ModuleName, false}); -unload_module(ModuleName) -> - unload_module({ModuleName, true}). - -unload_module(ModuleName, Persistent) -> - Modules = emqx:get_env(modules, []), - Env = proplists:get_value(ModuleName, Modules, undefined), - case ModuleName:unload(Env) of - ok -> - ets:insert(?MODULE, {ModuleName, false}), - write_loaded(Persistent), - ?LOG(info, "Unload ~s module successfully.", [ModuleName]); - {error, Error} -> - ?LOG(error, "Unload module ~s failed, cannot unload for ~0p", [ModuleName, Error]) - end. - -write_loaded(true) -> - FilePath = emqx:get_env(modules_loaded_file), - case file:write_file(FilePath, [io_lib:format("~p.~n", [Name]) || Name <- list()]) of - ok -> ok; - {error, Error} -> - ?LOG(error, "Write File ~p Error: ~p", [FilePath, Error]), - {error, Error} - end; -write_loaded(false) -> ok. diff --git a/_build/emqx/lib/emqx/src/emqx_mountpoint.erl b/_build/emqx/lib/emqx/src/emqx_mountpoint.erl deleted file mode 100644 index 8dfc23b303..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mountpoint.erl +++ /dev/null @@ -1,79 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_mountpoint). - --include("emqx.hrl"). --include("types.hrl"). - --export([ mount/2 - , unmount/2 - ]). - --export([replvar/2]). - --export_type([mountpoint/0]). - --type(mountpoint() :: binary()). - --spec(mount(maybe(mountpoint()), Any) -> Any - when Any :: emqx_types:topic() - | emqx_types:message() - | emqx_types:topic_filters()). -mount(undefined, Any) -> - Any; -mount(MountPoint, Topic) when is_binary(Topic) -> - prefix(MountPoint, Topic); -mount(MountPoint, Msg = #message{topic = Topic}) -> - Msg#message{topic = prefix(MountPoint, Topic)}; -mount(MountPoint, TopicFilters) when is_list(TopicFilters) -> - [{prefix(MountPoint, Topic), SubOpts} || {Topic, SubOpts} <- TopicFilters]. - -%% @private --compile({inline, [prefix/2]}). -prefix(MountPoint, Topic) -> - <>. - --spec(unmount(maybe(mountpoint()), Any) -> Any - when Any :: emqx_types:topic() - | emqx_types:message()). -unmount(undefined, Any) -> - Any; -unmount(MountPoint, Topic) when is_binary(Topic) -> - case string:prefix(Topic, MountPoint) of - nomatch -> Topic; - Topic1 -> Topic1 - end; -unmount(MountPoint, Msg = #message{topic = Topic}) -> - case string:prefix(Topic, MountPoint) of - nomatch -> Msg; - Topic1 -> Msg#message{topic = Topic1} - end. - --spec(replvar(maybe(mountpoint()), map()) -> maybe(mountpoint())). -replvar(undefined, _Vars) -> - undefined; -replvar(MountPoint, #{clientid := ClientId, username := Username}) -> - lists:foldl(fun feed_var/2, MountPoint, - [{<<"%c">>, ClientId}, {<<"%u">>, Username}]). - -feed_var({<<"%c">>, ClientId}, MountPoint) -> - emqx_topic:feed_var(<<"%c">>, ClientId, MountPoint); -feed_var({<<"%u">>, undefined}, MountPoint) -> - MountPoint; -feed_var({<<"%u">>, Username}, MountPoint) -> - emqx_topic:feed_var(<<"%u">>, Username, MountPoint). - diff --git a/_build/emqx/lib/emqx/src/emqx_mqtt_caps.erl b/_build/emqx/lib/emqx/src/emqx_mqtt_caps.erl deleted file mode 100644 index f29d599151..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mqtt_caps.erl +++ /dev/null @@ -1,160 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc MQTTv5 Capabilities --module(emqx_mqtt_caps). - --include("emqx_mqtt.hrl"). --include("types.hrl"). - --export([ check_pub/2 - , check_sub/3 - ]). - --export([ get_caps/1 - , get_caps/2 - , get_caps/3 - ]). - --export([default_caps/0]). - --export([default/0]). - --export_type([caps/0]). - --type(caps() :: #{max_packet_size => integer(), - max_clientid_len => integer(), - max_topic_alias => integer(), - max_topic_levels => integer(), - max_qos_allowed => emqx_types:qos(), - retain_available => boolean(), - wildcard_subscription => boolean(), - subscription_identifiers => boolean(), - shared_subscription => boolean() - }). - --define(UNLIMITED, 0). - --define(PUBCAP_KEYS, [max_topic_levels, - max_qos_allowed, - retain_available - ]). - --define(SUBCAP_KEYS, [max_topic_levels, - max_qos_allowed, - wildcard_subscription, - shared_subscription - ]). - --define(DEFAULT_CAPS, #{max_packet_size => ?MAX_PACKET_SIZE, - max_clientid_len => ?MAX_CLIENTID_LEN, - max_topic_alias => ?MAX_TOPIC_AlIAS, - max_topic_levels => ?UNLIMITED, - max_qos_allowed => ?QOS_2, - retain_available => true, - wildcard_subscription => true, - subscription_identifiers => true, - shared_subscription => true - }). - --spec(check_pub(emqx_types:zone(), - #{qos := emqx_types:qos(), - retain := boolean(), - topic := emqx_topic:topic()}) - -> ok_or_error(emqx_types:reason_code())). -check_pub(Zone, Flags) when is_map(Flags) -> - do_check_pub(case maps:take(topic, Flags) of - {Topic, Flags1} -> - Flags1#{topic_levels => emqx_topic:levels(Topic)}; - error -> - Flags - end, get_caps(Zone, publish)). - -do_check_pub(#{topic_levels := Levels}, #{max_topic_levels := Limit}) - when Limit > 0, Levels > Limit -> - {error, ?RC_TOPIC_NAME_INVALID}; -do_check_pub(#{qos := QoS}, #{max_qos_allowed := MaxQoS}) - when QoS > MaxQoS -> - {error, ?RC_QOS_NOT_SUPPORTED}; -do_check_pub(#{retain := true}, #{retain_available := false}) -> - {error, ?RC_RETAIN_NOT_SUPPORTED}; -do_check_pub(_Flags, _Caps) -> ok. - --spec(check_sub(emqx_types:zone(), - emqx_types:topic(), - emqx_types:subopts()) - -> ok_or_error(emqx_types:reason_code())). -check_sub(Zone, Topic, SubOpts) -> - Caps = get_caps(Zone, subscribe), - Flags = lists:foldl( - fun(max_topic_levels, Map) -> - Map#{topic_levels => emqx_topic:levels(Topic)}; - (wildcard_subscription, Map) -> - Map#{is_wildcard => emqx_topic:wildcard(Topic)}; - (shared_subscription, Map) -> - Map#{is_shared => maps:is_key(share, SubOpts)}; - (_Key, Map) -> Map %% Ignore - end, #{}, maps:keys(Caps)), - do_check_sub(Flags, Caps). - -do_check_sub(#{topic_levels := Levels}, #{max_topic_levels := Limit}) - when Limit > 0, Levels > Limit -> - {error, ?RC_TOPIC_FILTER_INVALID}; -do_check_sub(#{is_wildcard := true}, #{wildcard_subscription := false}) -> - {error, ?RC_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED}; -do_check_sub(#{is_shared := true}, #{shared_subscription := false}) -> - {error, ?RC_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED}; -do_check_sub(_Flags, _Caps) -> ok. - -default_caps() -> - ?DEFAULT_CAPS. - -get_caps(Zone, Cap, Def) -> - emqx_zone:get_env(Zone, Cap, Def). - -get_caps(Zone, publish) -> - with_env(Zone, '$mqtt_pub_caps', - fun() -> - filter_caps(?PUBCAP_KEYS, get_caps(Zone)) - end); - -get_caps(Zone, subscribe) -> - with_env(Zone, '$mqtt_sub_caps', - fun() -> - filter_caps(?SUBCAP_KEYS, get_caps(Zone)) - end). - -get_caps(Zone) -> - with_env(Zone, '$mqtt_caps', - fun() -> - maps:map(fun(Cap, Def) -> - emqx_zone:get_env(Zone, Cap, Def) - end, ?DEFAULT_CAPS) - end). - -filter_caps(Keys, Caps) -> - maps:filter(fun(Key, _Val) -> lists:member(Key, Keys) end, Caps). - --spec(default() -> caps()). -default() -> ?DEFAULT_CAPS. - -with_env(Zone, Key, InitFun) -> - case emqx_zone:get_env(Zone, Key) of - undefined -> Caps = InitFun(), - ok = emqx_zone:set_env(Zone, Key, Caps), - Caps; - ZoneCaps -> ZoneCaps - end. diff --git a/_build/emqx/lib/emqx/src/emqx_mqtt_props.erl b/_build/emqx/lib/emqx/src/emqx_mqtt_props.erl deleted file mode 100644 index 7acea67612..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mqtt_props.erl +++ /dev/null @@ -1,197 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc MQTT5 Properties --module(emqx_mqtt_props). - --include("emqx_mqtt.hrl"). - --export([ id/1 - , name/1 - , filter/2 - , validate/1 - , new/0 - ]). - -%% For tests --export([all/0]). - --export([ set/3 - , get/3 - ]). - --type(prop_name() :: atom()). --type(prop_id() :: pos_integer()). - --define(PROPS_TABLE, - #{16#01 => {'Payload-Format-Indicator', 'Byte', [?PUBLISH]}, - 16#02 => {'Message-Expiry-Interval', 'Four-Byte-Integer', [?PUBLISH]}, - 16#03 => {'Content-Type', 'UTF8-Encoded-String', [?PUBLISH]}, - 16#08 => {'Response-Topic', 'UTF8-Encoded-String', [?PUBLISH]}, - 16#09 => {'Correlation-Data', 'Binary-Data', [?PUBLISH]}, - 16#0B => {'Subscription-Identifier', 'Variable-Byte-Integer', [?PUBLISH, ?SUBSCRIBE]}, - 16#11 => {'Session-Expiry-Interval', 'Four-Byte-Integer', [?CONNECT, ?CONNACK, ?DISCONNECT]}, - 16#12 => {'Assigned-Client-Identifier', 'UTF8-Encoded-String', [?CONNACK]}, - 16#13 => {'Server-Keep-Alive', 'Two-Byte-Integer', [?CONNACK]}, - 16#15 => {'Authentication-Method', 'UTF8-Encoded-String', [?CONNECT, ?CONNACK, ?AUTH]}, - 16#16 => {'Authentication-Data', 'Binary-Data', [?CONNECT, ?CONNACK, ?AUTH]}, - 16#17 => {'Request-Problem-Information', 'Byte', [?CONNECT]}, - 16#18 => {'Will-Delay-Interval', 'Four-Byte-Integer', ['WILL']}, - 16#19 => {'Request-Response-Information', 'Byte', [?CONNECT]}, - 16#1A => {'Response-Information', 'UTF8-Encoded-String', [?CONNACK]}, - 16#1C => {'Server-Reference', 'UTF8-Encoded-String', [?CONNACK, ?DISCONNECT]}, - 16#1F => {'Reason-String', 'UTF8-Encoded-String', [?CONNACK, ?DISCONNECT, ?PUBACK, - ?PUBREC, ?PUBREL, ?PUBCOMP, - ?SUBACK, ?UNSUBACK, ?AUTH]}, - 16#21 => {'Receive-Maximum', 'Two-Byte-Integer', [?CONNECT, ?CONNACK]}, - 16#22 => {'Topic-Alias-Maximum', 'Two-Byte-Integer', [?CONNECT, ?CONNACK]}, - 16#23 => {'Topic-Alias', 'Two-Byte-Integer', [?PUBLISH]}, - 16#24 => {'Maximum-QoS', 'Byte', [?CONNACK]}, - 16#25 => {'Retain-Available', 'Byte', [?CONNACK]}, - 16#26 => {'User-Property', 'UTF8-String-Pair', 'ALL'}, - 16#27 => {'Maximum-Packet-Size', 'Four-Byte-Integer', [?CONNECT, ?CONNACK]}, - 16#28 => {'Wildcard-Subscription-Available', 'Byte', [?CONNACK]}, - 16#29 => {'Subscription-Identifier-Available', 'Byte', [?CONNACK]}, - 16#2A => {'Shared-Subscription-Available', 'Byte', [?CONNACK]} - }). - --spec(id(prop_name()) -> prop_id()). -id('Payload-Format-Indicator') -> 16#01; -id('Message-Expiry-Interval') -> 16#02; -id('Content-Type') -> 16#03; -id('Response-Topic') -> 16#08; -id('Correlation-Data') -> 16#09; -id('Subscription-Identifier') -> 16#0B; -id('Session-Expiry-Interval') -> 16#11; -id('Assigned-Client-Identifier') -> 16#12; -id('Server-Keep-Alive') -> 16#13; -id('Authentication-Method') -> 16#15; -id('Authentication-Data') -> 16#16; -id('Request-Problem-Information') -> 16#17; -id('Will-Delay-Interval') -> 16#18; -id('Request-Response-Information') -> 16#19; -id('Response-Information') -> 16#1A; -id('Server-Reference') -> 16#1C; -id('Reason-String') -> 16#1F; -id('Receive-Maximum') -> 16#21; -id('Topic-Alias-Maximum') -> 16#22; -id('Topic-Alias') -> 16#23; -id('Maximum-QoS') -> 16#24; -id('Retain-Available') -> 16#25; -id('User-Property') -> 16#26; -id('Maximum-Packet-Size') -> 16#27; -id('Wildcard-Subscription-Available') -> 16#28; -id('Subscription-Identifier-Available') -> 16#29; -id('Shared-Subscription-Available') -> 16#2A; -id(Name) -> error({bad_property, Name}). - --spec(name(prop_id()) -> prop_name()). -name(16#01) -> 'Payload-Format-Indicator'; -name(16#02) -> 'Message-Expiry-Interval'; -name(16#03) -> 'Content-Type'; -name(16#08) -> 'Response-Topic'; -name(16#09) -> 'Correlation-Data'; -name(16#0B) -> 'Subscription-Identifier'; -name(16#11) -> 'Session-Expiry-Interval'; -name(16#12) -> 'Assigned-Client-Identifier'; -name(16#13) -> 'Server-Keep-Alive'; -name(16#15) -> 'Authentication-Method'; -name(16#16) -> 'Authentication-Data'; -name(16#17) -> 'Request-Problem-Information'; -name(16#18) -> 'Will-Delay-Interval'; -name(16#19) -> 'Request-Response-Information'; -name(16#1A) -> 'Response-Information'; -name(16#1C) -> 'Server-Reference'; -name(16#1F) -> 'Reason-String'; -name(16#21) -> 'Receive-Maximum'; -name(16#22) -> 'Topic-Alias-Maximum'; -name(16#23) -> 'Topic-Alias'; -name(16#24) -> 'Maximum-QoS'; -name(16#25) -> 'Retain-Available'; -name(16#26) -> 'User-Property'; -name(16#27) -> 'Maximum-Packet-Size'; -name(16#28) -> 'Wildcard-Subscription-Available'; -name(16#29) -> 'Subscription-Identifier-Available'; -name(16#2A) -> 'Shared-Subscription-Available'; -name(Id) -> error({unsupported_property, Id}). - --spec(filter(emqx_types:packet_type(), emqx_types:properties()) - -> emqx_types:properties()). -filter(PacketType, Props) when is_map(Props), - PacketType >= ?CONNECT, - PacketType =< ?AUTH -> - F = fun(Name, _) -> - case maps:find(id(Name), ?PROPS_TABLE) of - {ok, {Name, _Type, 'ALL'}} -> - true; - {ok, {Name, _Type, AllowedTypes}} -> - lists:member(PacketType, AllowedTypes); - error -> false - end - end, - maps:filter(F, Props). - --spec(validate(emqx_types:properties()) -> ok). -validate(Props) when is_map(Props) -> - lists:foreach(fun validate_prop/1, maps:to_list(Props)). - -validate_prop(Prop = {Name, Val}) -> - case maps:find(id(Name), ?PROPS_TABLE) of - {ok, {Name, Type, _}} -> - validate_value(Type, Val) - orelse error({bad_property_value, Prop}); - error -> - error({bad_property, Name}) - end. - -validate_value('Byte', Val) -> - is_integer(Val) andalso Val =< 16#FF; -validate_value('Two-Byte-Integer', Val) -> - is_integer(Val) andalso 0 =< Val andalso Val =< 16#FFFF; -validate_value('Four-Byte-Integer', Val) -> - is_integer(Val) andalso 0 =< Val andalso Val =< 16#FFFFFFFF; -validate_value('Variable-Byte-Integer', Val) -> - is_integer(Val) andalso 0 =< Val andalso Val =< 16#7FFFFFFF; -validate_value('UTF8-String-Pair', {Name, Val}) -> - validate_value('UTF8-Encoded-String', Name) - andalso validate_value('UTF8-Encoded-String', Val); -validate_value('UTF8-String-Pair', Pairs) when is_list(Pairs) -> - lists:foldl(fun(Pair, OK) -> - OK andalso validate_value('UTF8-String-Pair', Pair) - end, true, Pairs); -validate_value('UTF8-Encoded-String', Val) -> - is_binary(Val); -validate_value('Binary-Data', Val) -> - is_binary(Val); -validate_value(_Type, _Val) -> false. - --spec(new() -> map()). -new() -> - #{}. - --spec(all() -> map()). -all() -> ?PROPS_TABLE. - -set(Name, Value, undefined) -> - #{Name => Value}; -set(Name, Value, Props) -> - Props#{Name => Value}. - -get(_Name, undefined, Default) -> - Default; -get(Name, Props, Default) -> - maps:get(Name, Props, Default). - diff --git a/_build/emqx/lib/emqx/src/emqx_mqueue.erl b/_build/emqx/lib/emqx/src/emqx_mqueue.erl deleted file mode 100644 index f77a1d98f9..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_mqueue.erl +++ /dev/null @@ -1,196 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%%-------------------------------------------------------------------- -%% @doc A Simple in-memory message queue. -%% -%% Notice that MQTT is not a (on-disk) persistent messaging queue. -%% It assumes that clients should be online in most of the time. -%% -%% This module implements a simple in-memory queue for MQTT persistent session. -%% -%% If the broker restarts or crashes, all queued messages will be lost. -%% -%% Concept of Message Queue and Inflight Window: -%% -%% |<----------------- Max Len ----------------->| -%% ----------------------------------------------- -%% IN -> | Messages Queue | Inflight Window | -> Out -%% ----------------------------------------------- -%% |<--- Win Size --->| -%% -%% -%% 1. Inflight Window is to store the messages -%% that are delivered but still awaiting for puback. -%% -%% 2. Messages are enqueued to tail when the inflight window is full. -%% -%% 3. QoS=0 messages are only enqueued when `store_qos0' is given `true` -%% in init options -%% -%% 4. If the queue is full, drop the oldest one -%% unless `max_len' is set to `0' which implies (`infinity'). -%% -%% @end -%%-------------------------------------------------------------------- - --module(emqx_mqueue). - --include("emqx.hrl"). --include("types.hrl"). --include("emqx_mqtt.hrl"). - --export([ init/1 - , info/1 - , info/2 - ]). - --export([ is_empty/1 - , len/1 - , max_len/1 - , in/2 - , out/1 - , stats/1 - , dropped/1 - ]). - --export_type([mqueue/0, options/0]). - --type(topic() :: emqx_topic:topic()). --type(priority() :: infinity | integer()). --type(pq() :: emqx_pqueue:q()). --type(count() :: non_neg_integer()). --type(p_table() :: ?NO_PRIORITY_TABLE | #{topic() := priority()}). --type(options() :: #{max_len := count(), - priorities => p_table(), - default_priority => highest | lowest, - store_qos0 => boolean() - }). --type(message() :: emqx_types:message()). - --type(stat() :: {len, non_neg_integer()} - | {max_len, non_neg_integer()} - | {dropped, non_neg_integer()}). - --define(PQUEUE, emqx_pqueue). --define(LOWEST_PRIORITY, 0). --define(HIGHEST_PRIORITY, infinity). --define(MAX_LEN_INFINITY, 0). --define(INFO_KEYS, [store_qos0, max_len, len, dropped]). - --record(mqueue, { - store_qos0 = false :: boolean(), - max_len = ?MAX_LEN_INFINITY :: count(), - len = 0 :: count(), - dropped = 0 :: count(), - p_table = ?NO_PRIORITY_TABLE :: p_table(), - default_p = ?LOWEST_PRIORITY :: priority(), - q = ?PQUEUE:new() :: pq() - }). - --type(mqueue() :: #mqueue{}). - --spec(init(options()) -> mqueue()). -init(Opts = #{max_len := MaxLen0, store_qos0 := QoS_0}) -> - MaxLen = case (is_integer(MaxLen0) andalso MaxLen0 > ?MAX_LEN_INFINITY) of - true -> MaxLen0; - false -> ?MAX_LEN_INFINITY - end, - #mqueue{max_len = MaxLen, - store_qos0 = QoS_0, - p_table = get_opt(priorities, Opts, ?NO_PRIORITY_TABLE), - default_p = get_priority_opt(Opts) - }. - --spec(info(mqueue()) -> emqx_types:infos()). -info(MQ) -> - maps:from_list([{Key, info(Key, MQ)} || Key <- ?INFO_KEYS]). - --spec(info(atom(), mqueue()) -> term()). -info(store_qos0, #mqueue{store_qos0 = True}) -> - True; -info(max_len, #mqueue{max_len = MaxLen}) -> - MaxLen; -info(len, #mqueue{len = Len}) -> - Len; -info(dropped, #mqueue{dropped = Dropped}) -> - Dropped. - -is_empty(#mqueue{len = Len}) -> Len =:= 0. - -len(#mqueue{len = Len}) -> Len. - -max_len(#mqueue{max_len = MaxLen}) -> MaxLen. - -%% @doc Return number of dropped messages. --spec(dropped(mqueue()) -> count()). -dropped(#mqueue{dropped = Dropped}) -> Dropped. - -%% @doc Stats of the mqueue --spec(stats(mqueue()) -> [stat()]). -stats(#mqueue{max_len = MaxLen, dropped = Dropped} = MQ) -> - [{len, len(MQ)}, {max_len, MaxLen}, {dropped, Dropped}]. - -%% @doc Enqueue a message. --spec(in(message(), mqueue()) -> {maybe(message()), mqueue()}). -in(Msg = #message{qos = ?QOS_0}, MQ = #mqueue{store_qos0 = false}) -> - {_Dropped = Msg, MQ}; -in(Msg = #message{topic = Topic}, MQ = #mqueue{default_p = Dp, - p_table = PTab, - q = Q, - len = Len, - max_len = MaxLen, - dropped = Dropped - } = MQ) -> - Priority = get_priority(Topic, PTab, Dp), - PLen = ?PQUEUE:plen(Priority, Q), - case MaxLen =/= ?MAX_LEN_INFINITY andalso PLen =:= MaxLen of - true -> - %% reached max length, drop the oldest message - {{value, DroppedMsg}, Q1} = ?PQUEUE:out(Priority, Q), - Q2 = ?PQUEUE:in(Msg, Priority, Q1), - {DroppedMsg, MQ#mqueue{q = Q2, dropped = Dropped + 1}}; - false -> - {_DroppedMsg = undefined, MQ#mqueue{len = Len + 1, q = ?PQUEUE:in(Msg, Priority, Q)}} - end. - --spec(out(mqueue()) -> {empty | {value, message()}, mqueue()}). -out(MQ = #mqueue{len = 0, q = Q}) -> - 0 = ?PQUEUE:len(Q), %% assert, in this case, ?PQUEUE:len should be very cheap - {empty, MQ}; -out(MQ = #mqueue{q = Q, len = Len}) -> - {R, Q1} = ?PQUEUE:out(Q), - {R, MQ#mqueue{q = Q1, len = Len - 1}}. - -get_opt(Key, Opts, Default) -> - case maps:get(Key, Opts, Default) of - undefined -> Default; - X -> X - end. - -get_priority_opt(Opts) -> - case get_opt(default_priority, Opts, ?LOWEST_PRIORITY) of - lowest -> ?LOWEST_PRIORITY; - highest -> ?HIGHEST_PRIORITY; - N when is_integer(N) -> N - end. - -%% MICRO-OPTIMIZATION: When there is no priority table defined (from config), -%% disregard default priority from config, always use lowest (?LOWEST_PRIORITY=0) -%% because the lowest priority in emqx_pqueue is a fallback to queue:queue() -%% while the highest 'infinity' is a [{infinity, queue:queue()}] -get_priority(_Topic, ?NO_PRIORITY_TABLE, _) -> ?LOWEST_PRIORITY; -get_priority(Topic, PTab, Dp) -> maps:get(Topic, PTab, Dp). diff --git a/_build/emqx/lib/emqx/src/emqx_os_mon.erl b/_build/emqx/lib/emqx/src/emqx_os_mon.erl deleted file mode 100644 index 6f10a7cfe2..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_os_mon.erl +++ /dev/null @@ -1,178 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_os_mon). - --behaviour(gen_server). - --include("logger.hrl"). - --logger_header("[OS_MON]"). - --export([start_link/1]). - --export([ get_cpu_check_interval/0 - , set_cpu_check_interval/1 - , get_cpu_high_watermark/0 - , set_cpu_high_watermark/1 - , get_cpu_low_watermark/0 - , set_cpu_low_watermark/1 - , get_mem_check_interval/0 - , set_mem_check_interval/1 - , get_sysmem_high_watermark/0 - , set_sysmem_high_watermark/1 - , get_procmem_high_watermark/0 - , set_procmem_high_watermark/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --include("emqx.hrl"). - --define(OS_MON, ?MODULE). - -start_link(Opts) -> - gen_server:start_link({local, ?OS_MON}, ?MODULE, [Opts], []). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -get_cpu_check_interval() -> - call(get_cpu_check_interval). - -set_cpu_check_interval(Seconds) -> - call({set_cpu_check_interval, Seconds}). - -get_cpu_high_watermark() -> - call(get_cpu_high_watermark). - -set_cpu_high_watermark(Float) -> - call({set_cpu_high_watermark, Float}). - -get_cpu_low_watermark() -> - call(get_cpu_low_watermark). - -set_cpu_low_watermark(Float) -> - call({set_cpu_low_watermark, Float}). - -get_mem_check_interval() -> - memsup:get_check_interval() div 1000. - -set_mem_check_interval(Seconds) -> - memsup:set_check_interval(Seconds div 60). - -get_sysmem_high_watermark() -> - memsup:get_sysmem_high_watermark() / 100. - -set_sysmem_high_watermark(Float) -> - memsup:set_sysmem_high_watermark(Float). - -get_procmem_high_watermark() -> - memsup:get_procmem_high_watermark() / 100. - -set_procmem_high_watermark(Float) -> - memsup:set_procmem_high_watermark(Float). - -call(Req) -> - gen_server:call(?OS_MON, Req, infinity). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Opts]) -> - set_mem_check_interval(proplists:get_value(mem_check_interval, Opts, 60)), - set_sysmem_high_watermark(proplists:get_value(sysmem_high_watermark, Opts, 0.70)), - set_procmem_high_watermark(proplists:get_value(procmem_high_watermark, Opts, 0.05)), - {ok, ensure_check_timer(#{cpu_high_watermark => proplists:get_value(cpu_high_watermark, Opts, 0.80), - cpu_low_watermark => proplists:get_value(cpu_low_watermark, Opts, 0.60), - cpu_check_interval => proplists:get_value(cpu_check_interval, Opts, 60), - timer => undefined, - is_cpu_alarm_set => false})}. - -handle_call(get_cpu_check_interval, _From, State) -> - {reply, maps:get(cpu_check_interval, State, undefined), State}; - -handle_call({set_cpu_check_interval, Seconds}, _From, State) -> - {reply, ok, State#{cpu_check_interval := Seconds}}; - -handle_call(get_cpu_high_watermark, _From, State) -> - {reply, maps:get(cpu_high_watermark, State, undefined), State}; - -handle_call({set_cpu_high_watermark, Float}, _From, State) -> - {reply, ok, State#{cpu_high_watermark := Float}}; - -handle_call(get_cpu_low_watermark, _From, State) -> - {reply, maps:get(cpu_low_watermark, State, undefined), State}; - -handle_call({set_cpu_low_watermark, Float}, _From, State) -> - {reply, ok, State#{cpu_low_watermark := Float}}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({timeout, Timer, check}, State = #{timer := Timer, - cpu_high_watermark := CPUHighWatermark, - cpu_low_watermark := CPULowWatermark, - is_cpu_alarm_set := IsCPUAlarmSet}) -> - NState = - case emqx_vm:cpu_util() of %% TODO: should be improved? - 0 -> State#{timer := undefined}; - Busy when Busy / 100 >= CPUHighWatermark -> - alarm_handler:set_alarm({cpu_high_watermark, Busy}), - ensure_check_timer(State#{is_cpu_alarm_set := true}); - Busy when Busy / 100 < CPULowWatermark -> - case IsCPUAlarmSet of - true -> alarm_handler:clear_alarm(cpu_high_watermark); - false -> ok - end, - ensure_check_timer(State#{is_cpu_alarm_set := false}); - _Busy -> ensure_check_timer(State) - end, - {noreply, NState}; - -handle_info(Info, State) -> - ?LOG(error, "unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{timer := Timer}) -> - emqx_misc:cancel_timer(Timer). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -ensure_check_timer(State = #{cpu_check_interval := Interval}) -> - case erlang:system_info(system_architecture) of - "x86_64-pc-linux-musl" -> State; - _ -> State#{timer := emqx_misc:start_timer(timer:seconds(Interval), check)} - end. diff --git a/_build/emqx/lib/emqx/src/emqx_packet.erl b/_build/emqx/lib/emqx/src/emqx_packet.erl deleted file mode 100644 index 015f95e0d3..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_packet.erl +++ /dev/null @@ -1,499 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_packet). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). - -%% Header APIs --export([ type/1 - , type_name/1 - , dup/1 - , qos/1 - , retain/1 - ]). - -%% Field APIs --export([ proto_name/1 - , proto_ver/1 - , info/2 - , set_props/2 - ]). - -%% Check API --export([ check/1 - , check/2 - ]). - --export([ to_message/2 - , to_message/3 - , will_msg/1 - ]). - --export([format/1]). - --type(connect() :: #mqtt_packet_connect{}). --type(publish() :: #mqtt_packet_publish{}). --type(subscribe() :: #mqtt_packet_subscribe{}). --type(unsubscribe() :: #mqtt_packet_unsubscribe{}). - -%%-------------------------------------------------------------------- -%% MQTT Packet Type and Flags. -%%-------------------------------------------------------------------- - -%% @doc MQTT packet type. --spec(type(emqx_types:packet()) -> emqx_types:packet_type()). -type(#mqtt_packet{header = #mqtt_packet_header{type = Type}}) -> - Type. - -%% @doc Name of MQTT packet type. --spec(type_name(emqx_types:packet()) -> atom()). -type_name(Packet) when is_record(Packet, mqtt_packet) -> - lists:nth(type(Packet), ?TYPE_NAMES). - -%% @doc Dup flag of MQTT packet. --spec(dup(emqx_types:packet()) -> boolean()). -dup(#mqtt_packet{header = #mqtt_packet_header{dup = Dup}}) -> - Dup. - -%% @doc QoS of MQTT packet type. --spec(qos(emqx_types:packet()) -> emqx_types:qos()). -qos(#mqtt_packet{header = #mqtt_packet_header{qos = QoS}}) -> - QoS. - -%% @doc Retain flag of MQTT packet. --spec(retain(emqx_types:packet()) -> boolean()). -retain(#mqtt_packet{header = #mqtt_packet_header{retain = Retain}}) -> - Retain. - -%%-------------------------------------------------------------------- -%% Protocol name and version of MQTT CONNECT Packet. -%%-------------------------------------------------------------------- - -%% @doc Protocol name of the CONNECT Packet. --spec(proto_name(emqx_types:packet()|connect()) -> binary()). -proto_name(?CONNECT_PACKET(ConnPkt)) -> - proto_name(ConnPkt); -proto_name(#mqtt_packet_connect{proto_name = Name}) -> - Name. - -%% @doc Protocol version of the CONNECT Packet. --spec(proto_ver(emqx_types:packet()|connect()) -> emqx_types:version()). -proto_ver(?CONNECT_PACKET(ConnPkt)) -> - proto_ver(ConnPkt); -proto_ver(#mqtt_packet_connect{proto_ver = Ver}) -> - Ver. - -%%-------------------------------------------------------------------- -%% Field Info -%%-------------------------------------------------------------------- - -info(proto_name, #mqtt_packet_connect{proto_name = Name}) -> - Name; -info(proto_ver, #mqtt_packet_connect{proto_ver = Ver}) -> - Ver; -info(is_bridge, #mqtt_packet_connect{is_bridge = IsBridge}) -> - IsBridge; -info(clean_start, #mqtt_packet_connect{clean_start = CleanStart}) -> - CleanStart; -info(will_flag, #mqtt_packet_connect{will_flag = WillFlag}) -> - WillFlag; -info(will_qos, #mqtt_packet_connect{will_qos = WillQoS}) -> - WillQoS; -info(will_retain, #mqtt_packet_connect{will_retain = WillRetain}) -> - WillRetain; -info(keepalive, #mqtt_packet_connect{keepalive = KeepAlive}) -> - KeepAlive; -info(properties, #mqtt_packet_connect{properties = Props}) -> - Props; -info(clientid, #mqtt_packet_connect{clientid = ClientId}) -> - ClientId; -info(will_props, #mqtt_packet_connect{will_props = WillProps}) -> - WillProps; -info(will_topic, #mqtt_packet_connect{will_topic = WillTopic}) -> - WillTopic; -info(will_payload, #mqtt_packet_connect{will_payload = Payload}) -> - Payload; -info(username, #mqtt_packet_connect{username = Username}) -> - Username; -info(password, #mqtt_packet_connect{password = Password}) -> - Password; - -info(ack_flags, #mqtt_packet_connack{ack_flags = Flags}) -> - Flags; -info(reason_code, #mqtt_packet_connack{reason_code = RC}) -> - RC; -info(properties, #mqtt_packet_connack{properties = Props}) -> - Props; - -info(topic_name, #mqtt_packet_publish{topic_name = Topic}) -> - Topic; -info(packet_id, #mqtt_packet_publish{packet_id = PacketId}) -> - PacketId; -info(properties, #mqtt_packet_publish{properties = Props}) -> - Props; - -info(packet_id, #mqtt_packet_puback{packet_id = PacketId}) -> - PacketId; -info(reason_code, #mqtt_packet_puback{reason_code = RC}) -> - RC; -info(properties, #mqtt_packet_puback{properties = Props}) -> - Props; - -info(packet_id, #mqtt_packet_subscribe{packet_id = PacketId}) -> - PacketId; -info(properties, #mqtt_packet_subscribe{properties = Props}) -> - Props; -info(topic_filters, #mqtt_packet_subscribe{topic_filters = Topics}) -> - Topics; - -info(packet_id, #mqtt_packet_suback{packet_id = PacketId}) -> - PacketId; -info(properties, #mqtt_packet_suback{properties = Props}) -> - Props; -info(reason_codes, #mqtt_packet_suback{reason_codes = RCs}) -> - RCs; - -info(packet_id, #mqtt_packet_unsubscribe{packet_id = PacketId}) -> - PacketId; -info(properties, #mqtt_packet_unsubscribe{properties = Props}) -> - Props; -info(topic_filters, #mqtt_packet_unsubscribe{topic_filters = Topics}) -> - Topics; - -info(packet_id, #mqtt_packet_unsuback{packet_id = PacketId}) -> - PacketId; -info(properties, #mqtt_packet_unsuback{properties = Props}) -> - Props; -info(reason_codes, #mqtt_packet_unsuback{reason_codes = RCs}) -> - RCs; - -info(reason_code, #mqtt_packet_disconnect{reason_code = RC}) -> - RC; -info(properties, #mqtt_packet_disconnect{properties = Props}) -> - Props; - -info(reason_code, #mqtt_packet_auth{reason_code = RC}) -> - RC; -info(properties, #mqtt_packet_auth{properties = Props}) -> - Props. - -set_props(Props, #mqtt_packet_connect{} = Pkt) -> - Pkt#mqtt_packet_connect{properties = Props}; - -set_props(Props, #mqtt_packet_connack{} = Pkt) -> - Pkt#mqtt_packet_connack{properties = Props}; - -set_props(Props, #mqtt_packet_publish{} = Pkt) -> - Pkt#mqtt_packet_publish{properties = Props}; - -set_props(Props, #mqtt_packet_puback{} = Pkt) -> - Pkt#mqtt_packet_puback{properties = Props}; - -set_props(Props, #mqtt_packet_subscribe{} = Pkt) -> - Pkt#mqtt_packet_subscribe{properties = Props}; - -set_props(Props, #mqtt_packet_suback{} = Pkt) -> - Pkt#mqtt_packet_suback{properties = Props}; - -set_props(Props, #mqtt_packet_unsubscribe{} = Pkt) -> - Pkt#mqtt_packet_unsubscribe{properties = Props}; - -set_props(Props, #mqtt_packet_unsuback{} = Pkt) -> - Pkt#mqtt_packet_unsuback{properties = Props}; - -set_props(Props, #mqtt_packet_disconnect{} = Pkt) -> - Pkt#mqtt_packet_disconnect{properties = Props}; - -set_props(Props, #mqtt_packet_auth{} = Pkt) -> - Pkt#mqtt_packet_auth{properties = Props}. - -%%-------------------------------------------------------------------- -%% Check MQTT Packet -%%-------------------------------------------------------------------- - -%% @doc Check PubSub Packet. --spec(check(emqx_types:packet()|publish()|subscribe()|unsubscribe()) - -> ok | {error, emqx_types:reason_code()}). -check(#mqtt_packet{variable = PubPkt}) when is_record(PubPkt, mqtt_packet_publish) -> - check(PubPkt); - -check(#mqtt_packet{variable = SubPkt}) when is_record(SubPkt, mqtt_packet_subscribe) -> - check(SubPkt); - -check(#mqtt_packet{variable = UnsubPkt}) when is_record(UnsubPkt, mqtt_packet_unsubscribe) -> - check(UnsubPkt); - -%% A Topic Alias of 0 is not permitted. -check(#mqtt_packet_publish{topic_name = <<>>, properties = #{'Topic-Alias':= 0}}) -> - {error, ?RC_PROTOCOL_ERROR}; -check(#mqtt_packet_publish{topic_name = <<>>, properties = #{'Topic-Alias':= _Alias}}) -> - ok; -check(#mqtt_packet_publish{topic_name = <<>>, properties = #{}}) -> - {error, ?RC_PROTOCOL_ERROR}; -check(#mqtt_packet_publish{topic_name = TopicName, properties = Props}) -> - try emqx_topic:validate(name, TopicName) of - true -> check_pub_props(Props) - catch - error:_Error -> - {error, ?RC_TOPIC_NAME_INVALID} - end; - -check(#mqtt_packet_subscribe{properties = #{'Subscription-Identifier' := I}}) - when I =< 0; I >= 16#FFFFFFF -> - {error, ?RC_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED}; - -check(#mqtt_packet_subscribe{topic_filters = []}) -> - {error, ?RC_TOPIC_FILTER_INVALID}; - -check(#mqtt_packet_subscribe{topic_filters = TopicFilters}) -> - try validate_topic_filters(TopicFilters) - catch - error:_Error -> - {error, ?RC_TOPIC_FILTER_INVALID} - end; - -check(#mqtt_packet_unsubscribe{topic_filters = []}) -> - {error, ?RC_TOPIC_FILTER_INVALID}; - -check(#mqtt_packet_unsubscribe{topic_filters = TopicFilters}) -> - try validate_topic_filters(TopicFilters) - catch - error:_Error -> - {error, ?RC_TOPIC_FILTER_INVALID} - end. - -check_pub_props(#{'Topic-Alias' := 0}) -> - {error, ?RC_TOPIC_ALIAS_INVALID}; - -check_pub_props(#{'Subscription-Identifier' := 0}) -> - {error, ?RC_PROTOCOL_ERROR}; - -check_pub_props(#{'Response-Topic' := ResponseTopic}) -> - try emqx_topic:validate(name, ResponseTopic) of - true -> ok - catch - error:_Error -> - {error, ?RC_PROTOCOL_ERROR} - end; -check_pub_props(_Props) -> ok. - -%% @doc Check CONNECT Packet. --spec(check(emqx_types:packet()|connect(), Opts :: map()) - -> ok | {error, emqx_types:reason_code()}). -check(?CONNECT_PACKET(ConnPkt), Opts) -> - check(ConnPkt, Opts); -check(ConnPkt, Opts) when is_record(ConnPkt, mqtt_packet_connect) -> - run_checks([fun check_proto_ver/2, - fun check_client_id/2, - fun check_conn_props/2, - fun check_will_msg/2], ConnPkt, Opts). - -check_proto_ver(#mqtt_packet_connect{proto_ver = Ver, - proto_name = Name}, _Opts) -> - case proplists:get_value(Ver, ?PROTOCOL_NAMES) of - Name -> ok; - _Other -> {error, ?RC_UNSUPPORTED_PROTOCOL_VERSION} - end. - -%% MQTT3.1 does not allow null clientId -check_client_id(#mqtt_packet_connect{proto_ver = ?MQTT_PROTO_V3, - clientid = <<>>}, _Opts) -> - {error, ?RC_CLIENT_IDENTIFIER_NOT_VALID}; -%% Issue#599: Null clientId and clean_start = false -check_client_id(#mqtt_packet_connect{clientid = <<>>, - clean_start = false}, _Opts) -> - {error, ?RC_CLIENT_IDENTIFIER_NOT_VALID}; -check_client_id(#mqtt_packet_connect{clientid = <<>>, - clean_start = true}, _Opts) -> - ok; -check_client_id(#mqtt_packet_connect{clientid = ClientId}, - #{max_clientid_len := MaxLen} = _Opts) -> - case (1 =< (Len = byte_size(ClientId))) andalso (Len =< MaxLen) of - true -> ok; - false -> {error, ?RC_CLIENT_IDENTIFIER_NOT_VALID} - end. - -check_conn_props(#mqtt_packet_connect{properties = undefined}, _Opts) -> - ok; -check_conn_props(#mqtt_packet_connect{properties = #{'Receive-Maximum' := 0}}, _Opts) -> - {error, ?RC_PROTOCOL_ERROR}; -check_conn_props(#mqtt_packet_connect{properties = #{'Request-Response-Information' := ReqRespInfo}}, _Opts) - when ReqRespInfo =/= 0, ReqRespInfo =/= 1 -> - {error, ?RC_PROTOCOL_ERROR}; -check_conn_props(#mqtt_packet_connect{properties = #{'Request-Problem-Information' := ReqProInfo}}, _Opts) - when ReqProInfo =/= 0, ReqProInfo =/= 1 -> - {error, ?RC_PROTOCOL_ERROR}; -check_conn_props(_ConnPkt, _Opts) -> ok. - -check_will_msg(#mqtt_packet_connect{will_flag = false}, _Caps) -> - ok; -check_will_msg(#mqtt_packet_connect{will_retain = true}, - _Opts = #{mqtt_retain_available := false}) -> - {error, ?RC_RETAIN_NOT_SUPPORTED}; -check_will_msg(#mqtt_packet_connect{will_qos = WillQoS}, - _Opts = #{max_qos_allowed := MaxQoS}) when WillQoS > MaxQoS -> - {error, ?RC_QOS_NOT_SUPPORTED}; -check_will_msg(#mqtt_packet_connect{will_topic = WillTopic}, _Opts) -> - try emqx_topic:validate(name, WillTopic) of - true -> ok - catch error:_Error -> - {error, ?RC_TOPIC_NAME_INVALID} - end. - -run_checks([], _Packet, _Options) -> - ok; -run_checks([Check|More], Packet, Options) -> - case Check(Packet, Options) of - ok -> run_checks(More, Packet, Options); - Error = {error, _Reason} -> Error - end. - -%% @doc Validate MQTT Packet -%% @private -validate_topic_filters(TopicFilters) -> - lists:foreach( - fun({TopicFilter, _SubOpts}) -> - emqx_topic:validate(TopicFilter); - (TopicFilter) -> - emqx_topic:validate(TopicFilter) - end, TopicFilters). - --spec(to_message(emqx_types:packet(), emqx_types:clientid()) -> emqx_types:message()). -to_message(Packet, ClientId) -> - to_message(Packet, ClientId, #{}). - -%% @doc Transform Publish Packet to Message. --spec(to_message(emqx_types:packet(), emqx_types:clientid(), map()) -> emqx_types:message()). -to_message(#mqtt_packet{ - header = #mqtt_packet_header{ - type = ?PUBLISH, - retain = Retain, - qos = QoS, - dup = Dup}, - variable = #mqtt_packet_publish{ - topic_name = Topic, - properties = Props}, - payload = Payload - }, ClientId, Headers) -> - Msg = emqx_message:make(ClientId, QoS, Topic, Payload), - Msg#message{flags = #{dup => Dup, retain => Retain}, - headers = Headers#{properties => Props}}. - --spec(will_msg(#mqtt_packet_connect{}) -> emqx_types:message()). -will_msg(#mqtt_packet_connect{will_flag = false}) -> - undefined; -will_msg(#mqtt_packet_connect{clientid = ClientId, - username = Username, - will_retain = Retain, - will_qos = QoS, - will_topic = Topic, - will_props = Props, - will_payload = Payload}) -> - Msg = emqx_message:make(ClientId, QoS, Topic, Payload), - Msg#message{flags = #{dup => false, retain => Retain}, - headers = #{username => Username, properties => Props}}. - -%% @doc Format packet --spec(format(emqx_types:packet()) -> iolist()). -format(#mqtt_packet{header = Header, variable = Variable, payload = Payload}) -> - format_header(Header, format_variable(Variable, Payload)). - -format_header(#mqtt_packet_header{type = Type, - dup = Dup, - qos = QoS, - retain = Retain}, S) -> - S1 = if - S == undefined -> <<>>; - true -> [", ", S] - end, - io_lib:format("~s(Q~p, R~p, D~p~s)", - [lists:nth(Type, ?TYPE_NAMES), QoS, i(Retain), i(Dup), S1]). - -format_variable(undefined, _) -> - undefined; -format_variable(Variable, undefined) -> - format_variable(Variable); -format_variable(Variable, Payload) -> - io_lib:format("~s, Payload=~0p", [format_variable(Variable), Payload]). - -format_variable(#mqtt_packet_connect{ - proto_ver = ProtoVer, - proto_name = ProtoName, - will_retain = WillRetain, - will_qos = WillQoS, - will_flag = WillFlag, - clean_start = CleanStart, - keepalive = KeepAlive, - clientid = ClientId, - will_topic = WillTopic, - will_payload = WillPayload, - username = Username, - password = Password}) -> - Format = "ClientId=~s, ProtoName=~s, ProtoVsn=~p, CleanStart=~s, KeepAlive=~p, Username=~s, Password=~s", - Args = [ClientId, ProtoName, ProtoVer, CleanStart, KeepAlive, Username, format_password(Password)], - {Format1, Args1} = if - WillFlag -> {Format ++ ", Will(Q~p, R~p, Topic=~s, Payload=~0p)", - Args ++ [WillQoS, i(WillRetain), WillTopic, WillPayload]}; - true -> {Format, Args} - end, - io_lib:format(Format1, Args1); - -format_variable(#mqtt_packet_disconnect - {reason_code = ReasonCode}) -> - io_lib:format("ReasonCode=~p", [ReasonCode]); - -format_variable(#mqtt_packet_connack{ack_flags = AckFlags, - reason_code = ReasonCode}) -> - io_lib:format("AckFlags=~p, ReasonCode=~p", [AckFlags, ReasonCode]); - -format_variable(#mqtt_packet_publish{topic_name = TopicName, - packet_id = PacketId}) -> - io_lib:format("Topic=~s, PacketId=~p", [TopicName, PacketId]); - -format_variable(#mqtt_packet_puback{packet_id = PacketId, - reason_code = ReasonCode}) -> - io_lib:format("PacketId=~p, ReasonCode=~p", [PacketId, ReasonCode]); - -format_variable(#mqtt_packet_subscribe{packet_id = PacketId, - topic_filters = TopicFilters}) -> - io_lib:format("PacketId=~p, TopicFilters=~0p", [PacketId, TopicFilters]); - -format_variable(#mqtt_packet_unsubscribe{packet_id = PacketId, - topic_filters = Topics}) -> - io_lib:format("PacketId=~p, TopicFilters=~0p", [PacketId, Topics]); - -format_variable(#mqtt_packet_suback{packet_id = PacketId, - reason_codes = ReasonCodes}) -> - io_lib:format("PacketId=~p, ReasonCodes=~p", [PacketId, ReasonCodes]); - -format_variable(#mqtt_packet_unsuback{packet_id = PacketId}) -> - io_lib:format("PacketId=~p", [PacketId]); - -format_variable(#mqtt_packet_auth{reason_code = ReasonCode}) -> - io_lib:format("ReasonCode=~p", [ReasonCode]); - -format_variable(PacketId) when is_integer(PacketId) -> - io_lib:format("PacketId=~p", [PacketId]). - -format_password(undefined) -> undefined; -format_password(_Password) -> '******'. - -i(true) -> 1; -i(false) -> 0; -i(I) when is_integer(I) -> I. - diff --git a/_build/emqx/lib/emqx/src/emqx_pd.erl b/_build/emqx/lib/emqx/src/emqx_pd.erl deleted file mode 100644 index 8754ac090e..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_pd.erl +++ /dev/null @@ -1,52 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc The utility functions for erlang process dictionary. --module(emqx_pd). - --include("types.hrl"). - --export([ get_counters/1 - , get_counter/1 - , inc_counter/2 - , reset_counter/1 - ]). - --compile({inline, - [ get_counters/1 - , get_counter/1 - , inc_counter/2 - , reset_counter/1 - ]}). - --type(key() :: term()). - --spec(get_counters(list(key())) -> list({key(), number()})). -get_counters(Keys) when is_list(Keys) -> - [{Key, emqx_pd:get_counter(Key)} || Key <- Keys]. - --spec(get_counter(key()) -> number()). -get_counter(Key) -> - case get(Key) of undefined -> 0; Cnt -> Cnt end. - --spec(inc_counter(key(), number()) -> maybe(number())). -inc_counter(Key, Inc) -> - put(Key, get_counter(Key) + Inc). - --spec(reset_counter(key()) -> number()). -reset_counter(Key) -> - case put(Key, 0) of undefined -> 0; Cnt -> Cnt end. - diff --git a/_build/emqx/lib/emqx/src/emqx_plugins.erl b/_build/emqx/lib/emqx/src/emqx_plugins.erl deleted file mode 100644 index faa6abae38..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_plugins.erl +++ /dev/null @@ -1,377 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_plugins). - --include("emqx.hrl"). --include("logger.hrl"). - --logger_header("[Plugins]"). - --export([init/0]). - --export([ load/0 - , load/1 - , unload/0 - , unload/1 - , reload/1 - , list/0 - , find_plugin/1 - , generate_configs/1 - , apply_configs/1 - ]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --dialyzer({no_match, [ plugin_loaded/2 - , plugin_unloaded/2 - ]}). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Init plugins' config --spec(init() -> ok). -init() -> - case emqx:get_env(plugins_etc_dir) of - undefined -> ok; - PluginsEtc -> - CfgFiles = [filename:join(PluginsEtc, File) || - File <- filelib:wildcard("*.config", PluginsEtc)], - lists:foreach(fun init_config/1, CfgFiles) - end. - -%% @doc Load all plugins when the broker started. --spec(load() -> list() | {error, term()}). -load() -> - load_expand_plugins(), - case emqx:get_env(plugins_loaded_file) of - undefined -> ignore; %% No plugins available - File -> - ensure_file(File), - with_loaded_file(File, fun(Names) -> load_plugins(Names, false) end) - end. - -%% @doc Load a Plugin --spec(load(atom()) -> ok | {error, term()}). -load(PluginName) when is_atom(PluginName) -> - case {lists:member(PluginName, names(plugin)), lists:member(PluginName, names(started_app))} of - {false, _} -> - ?LOG(alert, "Plugin ~s not found, cannot load it", [PluginName]), - {error, not_found}; - {_, true} -> - ?LOG(notice, "Plugin ~s is already started", [PluginName]), - {error, already_started}; - {_, false} -> - load_plugin(PluginName, true) - end. - -%% @doc Unload all plugins before broker stopped. --spec(unload() -> list() | {error, term()}). -unload() -> - case emqx:get_env(plugins_loaded_file) of - undefined -> ignore; - File -> - with_loaded_file(File, fun stop_plugins/1) - end. - -%% @doc UnLoad a Plugin --spec(unload(atom()) -> ok | {error, term()}). -unload(PluginName) when is_atom(PluginName) -> - case {lists:member(PluginName, names(plugin)), lists:member(PluginName, names(started_app))} of - {false, _} -> - ?LOG(error, "Plugin ~s is not found, cannot unload it", [PluginName]), - {error, not_found}; - {_, false} -> - ?LOG(error, "Plugin ~s is not started", [PluginName]), - {error, not_started}; - {_, _} -> - unload_plugin(PluginName, true) - end. - -reload(PluginName) when is_atom(PluginName)-> - case {lists:member(PluginName, names(plugin)), lists:member(PluginName, names(started_app))} of - {false, _} -> - ?LOG(error, "Plugin ~s is not found, cannot reload it", [PluginName]), - {error, not_found}; - {_, false} -> - load(PluginName); - {_, true} -> - case unload(PluginName) of - ok -> load(PluginName); - {error, Reason} -> {error, Reason} - end - end. - -%% @doc List all available plugins --spec(list() -> [emqx_types:plugin()]). -list() -> - StartedApps = names(started_app), - lists:map(fun({Name, _, [Type| _]}) -> - Plugin = plugin(Name, Type), - case lists:member(Name, StartedApps) of - true -> Plugin#plugin{active = true}; - false -> Plugin - end - end, lists:sort(ekka_boot:all_module_attributes(emqx_plugin))). - -find_plugin(Name) -> - find_plugin(Name, list()). - -find_plugin(Name, Plugins) -> - lists:keyfind(Name, 2, Plugins). - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -init_config(CfgFile) -> - {ok, [AppsEnv]} = file:consult(CfgFile), - lists:foreach(fun({App, Envs}) -> - [application:set_env(App, Par, Val) || {Par, Val} <- Envs] - end, AppsEnv). - -load_expand_plugins() -> - case emqx:get_env(expand_plugins_dir) of - undefined -> ok; - ExpandPluginsDir -> - Plugins = filelib:wildcard("*", ExpandPluginsDir), - lists:foreach(fun(Plugin) -> - PluginDir = filename:join(ExpandPluginsDir, Plugin), - case filelib:is_dir(PluginDir) of - true -> load_expand_plugin(PluginDir); - false -> ok - end - end, Plugins) - end. - -load_expand_plugin(PluginDir) -> - init_expand_plugin_config(PluginDir), - Ebin = filename:join([PluginDir, "ebin"]), - code:add_patha(Ebin), - Modules = filelib:wildcard(filename:join([Ebin, "*.beam"])), - lists:foreach(fun(Mod) -> - Module = list_to_atom(filename:basename(Mod, ".beam")), - code:load_file(Module) - end, Modules), - case filelib:wildcard(Ebin ++ "/*.app") of - [App|_] -> application:load(list_to_atom(filename:basename(App, ".app"))); - _ -> ?LOG(alert, "Plugin not found."), - {error, load_app_fail} - end. - -init_expand_plugin_config(PluginDir) -> - Priv = PluginDir ++ "/priv", - Etc = PluginDir ++ "/etc", - Schema = filelib:wildcard(Priv ++ "/*.schema"), - Conf = case filelib:wildcard(Etc ++ "/*.conf") of - [] -> []; - [Conf1] -> cuttlefish_conf:file(Conf1) - end, - AppsEnv = cuttlefish_generator:map(cuttlefish_schema:files(Schema), Conf), - lists:foreach(fun({AppName, Envs}) -> - [application:set_env(AppName, Par, Val) || {Par, Val} <- Envs] - end, AppsEnv). - -ensure_file(File) -> - case filelib:is_file(File) of false -> write_loaded([]); true -> ok end. - -with_loaded_file(File, SuccFun) -> - case read_loaded(File) of - {ok, Names0} -> - Names = filter_plugins(Names0), - SuccFun(Names); - {error, Error} -> - ?LOG(alert, "Failed to read: ~p, error: ~p", [File, Error]), - {error, Error} - end. - -filter_plugins(Names) -> - lists:filtermap(fun(Name1) when is_atom(Name1) -> {true, Name1}; - ({Name1, true}) -> {true, Name1}; - ({_Name1, false}) -> false - end, Names). - -load_plugins(Names, Persistent) -> - Plugins = list(), NotFound = Names -- names(Plugins), - case NotFound of - [] -> ok; - NotFound -> ?LOG(alert, "Cannot find plugins: ~p", [NotFound]) - end, - NeedToLoad = Names -- NotFound -- names(started_app), - lists:foreach(fun(Name) -> - Plugin = find_plugin(Name, Plugins), - load_plugin(Plugin#plugin.name, Persistent) - end, NeedToLoad). - -generate_configs(App) -> - ConfigFile = filename:join([emqx:get_env(plugins_etc_dir), App]) ++ ".config", - ConfFile = filename:join([emqx:get_env(plugins_etc_dir), App]) ++ ".conf", - SchemaFile = filename:join([code:priv_dir(App), App]) ++ ".schema", - case {filelib:is_file(ConfigFile), filelib:is_file(ConfFile) andalso filelib:is_file(SchemaFile)} of - {true, _} -> - {ok, [Configs]} = file:consult(ConfigFile), - Configs; - {_, true} -> - Schema = cuttlefish_schema:files([SchemaFile]), - Conf = cuttlefish_conf:file(ConfFile), - cuttlefish_generator:map(Schema, Conf); - {false, false} -> - error(no_avaliable_configuration) - end. - -apply_configs([]) -> - ok; -apply_configs([{App, Config} | More]) -> - lists:foreach(fun({Key, _}) -> application:unset_env(App, Key) end, application:get_all_env(App)), - lists:foreach(fun({Key, Val}) -> application:set_env(App, Key, Val) end, Config), - apply_configs(More). - -%% Stop plugins -stop_plugins(Names) -> - [stop_app(App) || App <- Names], - ok. - -plugin(AppName, Type) -> - case application:get_all_key(AppName) of - {ok, Attrs} -> - Descr = proplists:get_value(description, Attrs, ""), - #plugin{name = AppName, descr = Descr, type = plugin_type(Type)}; - undefined -> error({plugin_not_found, AppName}) - end. - -load_plugin(Name, Persistent) -> - try - Configs = ?MODULE:generate_configs(Name), - ?MODULE:apply_configs(Configs), - case load_app(Name) of - ok -> - start_app(Name, fun(App) -> plugin_loaded(App, Persistent) end); - {error, Error0} -> - {error, Error0} - end - catch _ : Error : Stacktrace -> - ?LOG(alert, "Plugin ~s load failed with ~p", [Name, {Error, Stacktrace}]), - {error, parse_config_file_failed} - end. - -load_app(App) -> - case application:load(App) of - ok -> - ok; - {error, {already_loaded, App}} -> - ok; - {error, Error} -> - {error, Error} - end. - -start_app(App, SuccFun) -> - case application:ensure_all_started(App) of - {ok, Started} -> - ?LOG(info, "Started plugins: ~p", [Started]), - ?LOG(info, "Load plugin ~s successfully", [App]), - SuccFun(App), - ok; - {error, {ErrApp, Reason}} -> - ?LOG(error, "Load plugin ~s failed, cannot start plugin ~s for ~0p", [App, ErrApp, Reason]), - {error, {ErrApp, Reason}} - end. - -unload_plugin(App, Persistent) -> - case stop_app(App) of - ok -> - plugin_unloaded(App, Persistent), ok; - {error, Reason} -> - {error, Reason} - end. - -stop_app(App) -> - case application:stop(App) of - ok -> - ?LOG(info, "Stop plugin ~s successfully", [App]), ok; - {error, {not_started, App}} -> - ?LOG(error, "Plugin ~s is not started", [App]), ok; - {error, Reason} -> - ?LOG(error, "Stop plugin ~s error: ~p", [App]), {error, Reason} - end. - -names(plugin) -> - names(list()); - -names(started_app) -> - [Name || {Name, _Descr, _Ver} <- application:which_applications()]; - -names(Plugins) -> - [Name || #plugin{name = Name} <- Plugins]. - -plugin_loaded(_Name, false) -> - ok; -plugin_loaded(Name, true) -> - case read_loaded() of - {ok, Names} -> - case lists:member(Name, Names) of - false -> - %% write file if plugin is loaded - write_loaded(lists:append(Names, [{Name, true}])); - true -> - ignore - end; - {error, Error} -> - ?LOG(error, "Cannot read loaded plugins: ~p", [Error]) - end. - -plugin_unloaded(_Name, false) -> - ok; -plugin_unloaded(Name, true) -> - case read_loaded() of - {ok, Names0} -> - Names = filter_plugins(Names0), - case lists:member(Name, Names) of - true -> - write_loaded(lists:delete(Name, Names)); - false -> - ?LOG(error, "Cannot find ~s in loaded_file", [Name]) - end; - {error, Error} -> - ?LOG(error, "Cannot read loaded_plugins: ~p", [Error]) - end. - -read_loaded() -> - case emqx:get_env(plugins_loaded_file) of - undefined -> {error, not_found}; - File -> read_loaded(File) - end. - -read_loaded(File) -> file:consult(File). - -write_loaded(AppNames) -> - FilePath = emqx:get_env(plugins_loaded_file), - case file:write_file(FilePath, [io_lib:format("~p.~n", [Name]) || Name <- AppNames]) of - ok -> ok; - {error, Error} -> - ?LOG(error, "Write File ~p Error: ~p", [FilePath, Error]), - {error, Error} - end. - -plugin_type(auth) -> auth; -plugin_type(protocol) -> protocol; -plugin_type(backend) -> backend; -plugin_type(bridge) -> bridge; -plugin_type(_) -> feature. diff --git a/_build/emqx/lib/emqx/src/emqx_pmon.erl b/_build/emqx/lib/emqx/src/emqx_pmon.erl deleted file mode 100644 index 99105f6e0b..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_pmon.erl +++ /dev/null @@ -1,96 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_pmon). - --compile({no_auto_import, [monitor/3]}). - --export([new/0]). - --export([ monitor/2 - , monitor/3 - , demonitor/2 - ]). - --export([ find/2 - , erase/2 - , erase_all/2 - ]). - --export([count/1]). - --export_type([pmon/0]). - --opaque(pmon() :: {?MODULE, map()}). - --define(PMON(Map), {?MODULE, Map}). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - --spec(new() -> pmon()). -new() -> ?PMON(maps:new()). - --spec(monitor(pid(), pmon()) -> pmon()). -monitor(Pid, PMon) -> - ?MODULE:monitor(Pid, undefined, PMon). - --spec(monitor(pid(), term(), pmon()) -> pmon()). -monitor(Pid, Val, PMon = ?PMON(Map)) -> - case maps:is_key(Pid, Map) of - true -> PMon; - false -> - Ref = erlang:monitor(process, Pid), - ?PMON(maps:put(Pid, {Ref, Val}, Map)) - end. - --spec(demonitor(pid(), pmon()) -> pmon()). -demonitor(Pid, PMon = ?PMON(Map)) -> - case maps:find(Pid, Map) of - {ok, {Ref, _Val}} -> - %% flush - _ = erlang:demonitor(Ref, [flush]), - ?PMON(maps:remove(Pid, Map)); - error -> PMon - end. - --spec(find(pid(), pmon()) -> error | {ok, term()}). -find(Pid, ?PMON(Map)) -> - case maps:find(Pid, Map) of - {ok, {_Ref, Val}} -> - {ok, Val}; - error -> error - end. - --spec(erase(pid(), pmon()) -> pmon()). -erase(Pid, ?PMON(Map)) -> - ?PMON(maps:remove(Pid, Map)). - --spec(erase_all([pid()], pmon()) -> {[{pid(), term()}], pmon()}). -erase_all(Pids, PMon0) -> - lists:foldl( - fun(Pid, {Acc, PMon}) -> - case find(Pid, PMon) of - {ok, Val} -> - {[{Pid, Val}|Acc], erase(Pid, PMon)}; - error -> {Acc, PMon} - end - end, {[], PMon0}, Pids). - --spec(count(pmon()) -> non_neg_integer()). -count(?PMON(Map)) -> maps:size(Map). - diff --git a/_build/emqx/lib/emqx/src/emqx_pool.erl b/_build/emqx/lib/emqx/src/emqx_pool.erl deleted file mode 100644 index 49a7c2cace..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_pool.erl +++ /dev/null @@ -1,138 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_pool). - --behaviour(gen_server). - --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Pool]"). - -%% APIs --export([start_link/2]). - --export([ submit/1 - , submit/2 - , async_submit/1 - , async_submit/2 - ]). - --ifdef(TEST). --export([worker/0]). --endif. - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --define(POOL, ?MODULE). - --type(task() :: fun() | mfa() | {fun(), Args :: list(any())}). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Start pool. --spec(start_link(atom(), pos_integer()) -> startlink_ret()). -start_link(Pool, Id) -> - gen_server:start_link({local, emqx_misc:proc_name(?MODULE, Id)}, - ?MODULE, [Pool, Id], [{hibernate_after, 1000}]). - -%% @doc Submit work to the pool. --spec(submit(task()) -> any()). -submit(Task) -> - call({submit, Task}). - --spec(submit(fun(), list(any())) -> any()). -submit(Fun, Args) -> - call({submit, {Fun, Args}}). - -%% @private -call(Req) -> - gen_server:call(worker(), Req, infinity). - -%% @doc Submit work to the pool asynchronously. --spec(async_submit(task()) -> ok). -async_submit(Task) -> - cast({async_submit, Task}). - --spec(async_submit(fun(), list(any())) -> ok). -async_submit(Fun, Args) -> - cast({async_submit, {Fun, Args}}). - -%% @private -cast(Msg) -> - gen_server:cast(worker(), Msg). - -%% @private -worker() -> - gproc_pool:pick_worker(?POOL). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Pool, Id]) -> - true = gproc_pool:connect_worker(Pool, {Pool, Id}), - {ok, #{pool => Pool, id => Id}}. - -handle_call({submit, Task}, _From, State) -> - {reply, catch run(Task), State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({async_submit, Task}, State) -> - try run(Task) - catch _:Error:Stacktrace -> - ?LOG(error, "Error: ~0p, ~0p", [Error, Stacktrace]) - end, - {noreply, State}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{pool := Pool, id := Id}) -> - gproc_pool:disconnect_worker(Pool, {Pool, Id}). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -run({M, F, A}) -> - erlang:apply(M, F, A); -run({F, A}) when is_function(F), is_list(A) -> - erlang:apply(F, A); -run(Fun) when is_function(Fun) -> - Fun(). - diff --git a/_build/emqx/lib/emqx/src/emqx_pool_sup.erl b/_build/emqx/lib/emqx/src/emqx_pool_sup.erl deleted file mode 100644 index 080cd842bd..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_pool_sup.erl +++ /dev/null @@ -1,85 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_pool_sup). - --behaviour(supervisor). - --include("types.hrl"). - --export([spec/1, spec/2]). - --export([ start_link/0 - , start_link/3 - , start_link/4 - ]). - --export([init/1]). - --define(POOL, emqx_pool). - --spec(spec(list()) -> supervisor:child_spec()). -spec(Args) -> - spec(pool_sup, Args). - --spec(spec(any(), list()) -> supervisor:child_spec()). -spec(ChildId, Args) -> - #{id => ChildId, - start => {?MODULE, start_link, Args}, - restart => transient, - shutdown => infinity, - type => supervisor, - modules => [?MODULE]}. - -%% @doc Start the default pool supervisor. -start_link() -> - start_link(?POOL, random, {?POOL, start_link, []}). - --spec(start_link(atom() | tuple(), atom(), mfargs()) - -> {ok, pid()} | {error, term()}). -start_link(Pool, Type, MFA) -> - start_link(Pool, Type, emqx_vm:schedulers(), MFA). - --spec(start_link(atom() | tuple(), atom(), pos_integer(), mfargs()) - -> {ok, pid()} | {error, term()}). -start_link(Pool, Type, Size, MFA) -> - supervisor:start_link(?MODULE, [Pool, Type, Size, MFA]). - -init([Pool, Type, Size, {M, F, Args}]) -> - ok = ensure_pool(Pool, Type, [{size, Size}]), - {ok, {{one_for_one, 10, 3600}, [ - begin - ensure_pool_worker(Pool, {Pool, I}, I), - #{id => {M, I}, - start => {M, F, [Pool, I | Args]}, - restart => transient, - shutdown => 5000, - type => worker, - modules => [M]} - end || I <- lists:seq(1, Size)]}}. - -ensure_pool(Pool, Type, Opts) -> - try gproc_pool:new(Pool, Type, Opts) - catch - error:exists -> ok - end. - -ensure_pool_worker(Pool, Name, Slot) -> - try gproc_pool:add_worker(Pool, Name, Slot) - catch - error:exists -> ok - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_pqueue.erl b/_build/emqx/lib/emqx/src/emqx_pqueue.erl deleted file mode 100644 index 85c89866dc..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_pqueue.erl +++ /dev/null @@ -1,269 +0,0 @@ -%% The contents of this file are subject to the Mozilla Public License -%% Version 1.1 (the "License"); you may not use this file except in -%% compliance with the License. You may obtain a copy of the License -%% at http://www.mozilla.org/MPL/ -%% -%% Software distributed under the License is distributed on an "AS IS" -%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See -%% the License for the specific language governing rights and -%% limitations under the License. -%% -%% The Original Code is RabbitMQ. -%% -%% The Initial Developer of the Original Code is GoPivotal, Inc. -%% Copyright (c) 2007-2015 Pivotal Software, Inc. All rights reserved. -%% - -%% Priority queues have essentially the same interface as ordinary -%% queues, except that a) there is an in/3 that takes a priority, and -%% b) we have only implemented the core API we need. -%% -%% Priorities should be integers - the higher the value the higher the -%% priority - but we don't actually check that. -%% -%% in/2 inserts items with priority 0. -%% -%% We optimise the case where a priority queue is being used just like -%% an ordinary queue. When that is the case we represent the priority -%% queue as an ordinary queue. We could just call into the 'queue' -%% module for that, but for efficiency we implement the relevant -%% functions directly in here, thus saving on inter-module calls and -%% eliminating a level of boxing. -%% -%% When the queue contains items with non-zero priorities, it is -%% represented as a sorted kv list with the inverted Priority as the -%% key and an ordinary queue as the value. Here again we use our own -%% ordinary queue implemention for efficiency, often making recursive -%% calls into the same function knowing that ordinary queues represent -%% a base case. - --module(emqx_pqueue). - --export([ new/0 - , is_queue/1 - , is_empty/1 - , len/1 - , plen/2 - , to_list/1 - , from_list/1 - , in/2 - , in/3 - , out/1 - , out/2 - , out_p/1 - , join/2 - , filter/2 - , fold/3 - , highest/1 - ]). - --export_type([q/0]). - -%%---------------------------------------------------------------------------- - --type(priority() :: integer() | 'infinity'). --type(squeue() :: {queue, [any()], [any()], non_neg_integer()}). --type(pqueue() :: squeue() | {pqueue, [{priority(), squeue()}]}). --type(q() :: pqueue()). - -%%---------------------------------------------------------------------------- - --spec(new() -> pqueue()). -new() -> - {queue, [], [], 0}. - --spec(is_queue(any()) -> boolean()). -is_queue({queue, R, F, L}) when is_list(R), is_list(F), is_integer(L) -> - true; -is_queue({pqueue, Queues}) when is_list(Queues) -> - lists:all(fun ({infinity, Q}) -> is_queue(Q); - ({P, Q}) -> is_integer(P) andalso is_queue(Q) - end, Queues); -is_queue(_) -> - false. - --spec(is_empty(pqueue()) -> boolean()). -is_empty({queue, [], [], 0}) -> - true; -is_empty(_) -> - false. - --spec(len(pqueue()) -> non_neg_integer()). -len({queue, _R, _F, L}) -> - L; -len({pqueue, Queues}) -> - lists:sum([len(Q) || {_, Q} <- Queues]). - --spec(plen(priority(), pqueue()) -> non_neg_integer()). -plen(0, {queue, _R, _F, L}) -> - L; -plen(_, {queue, _R, _F, _}) -> - 0; -plen(P, {pqueue, Queues}) -> - case lists:keysearch(maybe_negate_priority(P), 1, Queues) of - {value, {_, Q}} -> len(Q); - false -> 0 - end. - --spec(to_list(pqueue()) -> [{priority(), any()}]). -to_list({queue, In, Out, _Len}) when is_list(In), is_list(Out) -> - [{0, V} || V <- Out ++ lists:reverse(In, [])]; -to_list({pqueue, Queues}) -> - [{maybe_negate_priority(P), V} || {P, Q} <- Queues, - {0, V} <- to_list(Q)]. - --spec(from_list([{priority(), any()}]) -> pqueue()). -from_list(L) -> - lists:foldl(fun ({P, E}, Q) -> in(E, P, Q) end, new(), L). - --spec(in(any(), pqueue()) -> pqueue()). -in(Item, Q) -> - in(Item, 0, Q). - --spec(in(any(), priority(), pqueue()) -> pqueue()). -in(X, 0, {queue, [_] = In, [], 1}) -> - {queue, [X], In, 2}; -in(X, 0, {queue, In, Out, Len}) when is_list(In), is_list(Out) -> - {queue, [X|In], Out, Len + 1}; -in(X, Priority, _Q = {queue, [], [], 0}) -> - in(X, Priority, {pqueue, []}); -in(X, Priority, Q = {queue, _, _, _}) -> - in(X, Priority, {pqueue, [{0, Q}]}); -in(X, Priority, {pqueue, Queues}) -> - P = maybe_negate_priority(Priority), - {pqueue, case lists:keysearch(P, 1, Queues) of - {value, {_, Q}} -> - lists:keyreplace(P, 1, Queues, {P, in(X, Q)}); - false when P == infinity -> - [{P, {queue, [X], [], 1}} | Queues]; - false -> - case Queues of - [{infinity, InfQueue} | Queues1] -> - [{infinity, InfQueue} | - lists:keysort(1, [{P, {queue, [X], [], 1}} | Queues1])]; - _ -> - lists:keysort(1, [{P, {queue, [X], [], 1}} | Queues]) - end - end}. - --spec(out(pqueue()) -> {empty | {value, any()}, pqueue()}). -out({queue, [], [], 0} = Q) -> - {empty, Q}; -out({queue, [V], [], 1}) -> - {{value, V}, {queue, [], [], 0}}; -out({queue, [Y|In], [], Len}) -> - [V|Out] = lists:reverse(In, []), - {{value, V}, {queue, [Y], Out, Len - 1}}; -out({queue, In, [V], Len}) when is_list(In) -> - {{value,V}, r2f(In, Len - 1)}; -out({queue, In,[V|Out], Len}) when is_list(In) -> - {{value, V}, {queue, In, Out, Len - 1}}; -out({pqueue, [{P, Q} | Queues]}) -> - {R, Q1} = out(Q), - NewQ = case is_empty(Q1) of - true -> case Queues of - [] -> {queue, [], [], 0}; - [{0, OnlyQ}] -> OnlyQ; - [_|_] -> {pqueue, Queues} - end; - false -> {pqueue, [{P, Q1} | Queues]} - end, - {R, NewQ}. - --spec(out_p(pqueue()) -> {empty | {value, any(), priority()}, pqueue()}). -out_p({queue, _, _, _} = Q) -> add_p(out(Q), 0); -out_p({pqueue, [{P, _} | _]} = Q) -> add_p(out(Q), maybe_negate_priority(P)). - -out(0, {queue, _, _, _} = Q) -> - out(Q); -out(Priority, {queue, _, _, _}) -> - erlang:error(badarg, [Priority]); -out(Priority, {pqueue, Queues}) -> - P = maybe_negate_priority(Priority), - case lists:keysearch(P, 1, Queues) of - {value, {_, Q}} -> - {R, Q1} = out(Q), - Queues1 = case is_empty(Q1) of - true -> lists:keydelete(P, 1, Queues); - false -> lists:keyreplace(P, 1, Queues, {P, Q1}) - end, - {R, case Queues1 of - [] -> {queue, [], [], 0}; - [{0, OnlyQ}] -> OnlyQ; - [_|_] -> {pqueue, Queues1} - end}; - false -> - {empty, {pqueue, Queues}} - end. - -add_p(R, P) -> case R of - {empty, Q} -> {empty, Q}; - {{value, V}, Q} -> {{value, V, P}, Q} - end. - --spec(join(pqueue(), pqueue()) -> pqueue()). -join(A, {queue, [], [], 0}) -> - A; -join({queue, [], [], 0}, B) -> - B; -join({queue, AIn, AOut, ALen}, {queue, BIn, BOut, BLen}) -> - {queue, BIn, AOut ++ lists:reverse(AIn, BOut), ALen + BLen}; -join(A = {queue, _, _, _}, {pqueue, BPQ}) -> - {Pre, Post} = - lists:splitwith(fun ({P, _}) -> P < 0 orelse P == infinity end, BPQ), - Post1 = case Post of - [] -> [ {0, A} ]; - [ {0, ZeroQueue} | Rest ] -> [ {0, join(A, ZeroQueue)} | Rest ]; - _ -> [ {0, A} | Post ] - end, - {pqueue, Pre ++ Post1}; -join({pqueue, APQ}, B = {queue, _, _, _}) -> - {Pre, Post} = - lists:splitwith(fun ({P, _}) -> P < 0 orelse P == infinity end, APQ), - Post1 = case Post of - [] -> [ {0, B} ]; - [ {0, ZeroQueue} | Rest ] -> [ {0, join(ZeroQueue, B)} | Rest ]; - _ -> [ {0, B} | Post ] - end, - {pqueue, Pre ++ Post1}; -join({pqueue, APQ}, {pqueue, BPQ}) -> - {pqueue, merge(APQ, BPQ, [])}. - -merge([], BPQ, Acc) -> - lists:reverse(Acc, BPQ); -merge(APQ, [], Acc) -> - lists:reverse(Acc, APQ); -merge([{P, A}|As], [{P, B}|Bs], Acc) -> - merge(As, Bs, [ {P, join(A, B)} | Acc ]); -merge([{PA, A}|As], Bs = [{PB, _}|_], Acc) when PA < PB orelse PA == infinity -> - merge(As, Bs, [ {PA, A} | Acc ]); -merge(As = [{_, _}|_], [{PB, B}|Bs], Acc) -> - merge(As, Bs, [ {PB, B} | Acc ]). - --spec(filter(fun ((any()) -> boolean()), pqueue()) -> pqueue()). -filter(Pred, Q) -> fold(fun(V, P, Acc) -> - case Pred(V) of - true -> in(V, P, Acc); - false -> Acc - end - end, new(), Q). - --spec(fold(fun ((any(), priority(), A) -> A), A, pqueue()) -> A). -fold(Fun, Init, Q) -> case out_p(Q) of - {empty, _Q} -> Init; - {{value, V, P}, Q1} -> fold(Fun, Fun(V, P, Init), Q1) - end. - --spec(highest(pqueue()) -> priority() | 'empty'). -highest({queue, [], [], 0}) -> empty; -highest({queue, _, _, _}) -> 0; -highest({pqueue, [{P, _} | _]}) -> maybe_negate_priority(P). - -r2f([], 0) -> {queue, [], [], 0}; -r2f([_] = R, 1) -> {queue, [], R, 1}; -r2f([X,Y], 2) -> {queue, [X], [Y], 2}; -r2f([X,Y|R], L) -> {queue, [X,Y], lists:reverse(R, []), L}. - -maybe_negate_priority(infinity) -> infinity; -maybe_negate_priority(P) -> -P. - diff --git a/_build/emqx/lib/emqx/src/emqx_psk.erl b/_build/emqx/lib/emqx/src/emqx_psk.erl deleted file mode 100644 index f1170d2d92..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_psk.erl +++ /dev/null @@ -1,40 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_psk). - --include("logger.hrl"). - --logger_header("[PSK]"). - -%% SSL PSK Callbacks --export([lookup/3]). - --type psk_identity() :: string(). --type psk_user_state() :: term(). - --spec lookup(psk, psk_identity(), psk_user_state()) -> {ok, SharedSecret :: binary()} | error. -lookup(psk, ClientPSKID, _UserState) -> - try emqx_hooks:run_fold('tls_handshake.psk_lookup', [ClientPSKID], not_found) of - SharedSecret when is_binary(SharedSecret) -> {ok, SharedSecret}; - Error -> - ?LOG(error, "Look PSK for PSKID ~p error: ~p", [ClientPSKID, Error]), - error - catch - Except:Error:Stacktrace -> - ?LOG(error, "Lookup PSK failed, ~0p: ~0p", [{Except,Error}, Stacktrace]), - error - end. diff --git a/_build/emqx/lib/emqx/src/emqx_reason_codes.erl b/_build/emqx/lib/emqx/src/emqx_reason_codes.erl deleted file mode 100644 index 8e96df165e..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_reason_codes.erl +++ /dev/null @@ -1,185 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc MQTT5 reason codes --module(emqx_reason_codes). - --include("emqx_mqtt.hrl"). - --export([ name/1 - , name/2 - , text/1 - , text/2 - ]). - --export([ frame_error/1 - , connack_error/1 - ]). - --export([compat/2]). - -name(I, Ver) when Ver >= ?MQTT_PROTO_V5 -> - name(I); -name(0, _Ver) -> connection_accepted; -name(1, _Ver) -> unacceptable_protocol_version; -name(2, _Ver) -> client_identifier_not_valid; -name(3, _Ver) -> server_unavaliable; -name(4, _Ver) -> malformed_username_or_password; -name(5, _Ver) -> unauthorized_client; -name(_, _Ver) -> unknown_error. - -name(16#00) -> success; -name(16#01) -> granted_qos1; -name(16#02) -> granted_qos2; -name(16#04) -> disconnect_with_will_message; -name(16#10) -> no_matching_subscribers; -name(16#11) -> no_subscription_existed; -name(16#18) -> continue_authentication; -name(16#19) -> re_authenticate; -name(16#80) -> unspecified_error; -name(16#81) -> malformed_packet; -name(16#82) -> protocol_error; -name(16#83) -> implementation_specific_error; -name(16#84) -> unsupported_protocol_version; -name(16#85) -> client_identifier_not_valid; -name(16#86) -> bad_username_or_password; -name(16#87) -> not_authorized; -name(16#88) -> server_unavailable; -name(16#89) -> server_busy; -name(16#8A) -> banned; -name(16#8B) -> server_shutting_down; -name(16#8C) -> bad_authentication_method; -name(16#8D) -> keepalive_timeout; -name(16#8E) -> session_taken_over; -name(16#8F) -> topic_filter_invalid; -name(16#90) -> topic_name_invalid; -name(16#91) -> packet_identifier_inuse; -name(16#92) -> packet_identifier_not_found; -name(16#93) -> receive_maximum_exceeded; -name(16#94) -> topic_alias_invalid; -name(16#95) -> packet_too_large; -name(16#96) -> message_rate_too_high; -name(16#97) -> quota_exceeded; -name(16#98) -> administrative_action; -name(16#99) -> payload_format_invalid; -name(16#9A) -> retain_not_supported; -name(16#9B) -> qos_not_supported; -name(16#9C) -> use_another_server; -name(16#9D) -> server_moved; -name(16#9E) -> shared_subscriptions_not_supported; -name(16#9F) -> connection_rate_exceeded; -name(16#A0) -> maximum_connect_time; -name(16#A1) -> subscription_identifiers_not_supported; -name(16#A2) -> wildcard_subscriptions_not_supported; -name(_Code) -> unknown_error. - -text(I, Ver) when Ver >= ?MQTT_PROTO_V5 -> - text(I); -text(0, _Ver) -> <<"Connection accepted">>; -text(1, _Ver) -> <<"unacceptable_protocol_version">>; -text(2, _Ver) -> <<"client_identifier_not_valid">>; -text(3, _Ver) -> <<"server_unavaliable">>; -text(4, _Ver) -> <<"malformed_username_or_password">>; -text(5, _Ver) -> <<"unauthorized_client">>; -text(_, _Ver) -> <<"unknown_error">>. - -text(16#00) -> <<"Success">>; -text(16#01) -> <<"Granted QoS 1">>; -text(16#02) -> <<"Granted QoS 2">>; -text(16#04) -> <<"Disconnect with Will Message">>; -text(16#10) -> <<"No matching subscribers">>; -text(16#11) -> <<"No subscription existed">>; -text(16#18) -> <<"Continue authentication">>; -text(16#19) -> <<"Re-authenticate">>; -text(16#80) -> <<"Unspecified error">>; -text(16#81) -> <<"Malformed Packet">>; -text(16#82) -> <<"Protocol Error">>; -text(16#83) -> <<"Implementation specific error">>; -text(16#84) -> <<"Unsupported Protocol Version">>; -text(16#85) -> <<"Client Identifier not valid">>; -text(16#86) -> <<"Bad User Name or Password">>; -text(16#87) -> <<"Not authorized">>; -text(16#88) -> <<"Server unavailable">>; -text(16#89) -> <<"Server busy">>; -text(16#8A) -> <<"Banned">>; -text(16#8B) -> <<"Server shutting down">>; -text(16#8C) -> <<"Bad authentication method">>; -text(16#8D) -> <<"Keep Alive timeout">>; -text(16#8E) -> <<"Session taken over">>; -text(16#8F) -> <<"Topic Filter invalid">>; -text(16#90) -> <<"Topic Name invalid">>; -text(16#91) -> <<"Packet Identifier in use">>; -text(16#92) -> <<"Packet Identifier not found">>; -text(16#93) -> <<"Receive Maximum exceeded">>; -text(16#94) -> <<"Topic Alias invalid">>; -text(16#95) -> <<"Packet too large">>; -text(16#96) -> <<"Message rate too high">>; -text(16#97) -> <<"Quota exceeded">>; -text(16#98) -> <<"Administrative action">>; -text(16#99) -> <<"Payload format invalid">>; -text(16#9A) -> <<"Retain not supported">>; -text(16#9B) -> <<"QoS not supported">>; -text(16#9C) -> <<"Use another server">>; -text(16#9D) -> <<"Server moved">>; -text(16#9E) -> <<"Shared Subscriptions not supported">>; -text(16#9F) -> <<"Connection rate exceeded">>; -text(16#A0) -> <<"Maximum connect time">>; -text(16#A1) -> <<"Subscription Identifiers not supported">>; -text(16#A2) -> <<"Wildcard Subscriptions not supported">>; -text(_Code) -> <<"Unknown error">>. - -compat(connack, 16#80) -> ?CONNACK_PROTO_VER; -compat(connack, 16#81) -> ?CONNACK_PROTO_VER; -compat(connack, 16#82) -> ?CONNACK_PROTO_VER; -compat(connack, 16#83) -> ?CONNACK_PROTO_VER; -compat(connack, 16#84) -> ?CONNACK_PROTO_VER; -compat(connack, 16#85) -> ?CONNACK_INVALID_ID; -compat(connack, 16#86) -> ?CONNACK_CREDENTIALS; -compat(connack, 16#87) -> ?CONNACK_AUTH; -compat(connack, 16#88) -> ?CONNACK_SERVER; -compat(connack, 16#89) -> ?CONNACK_SERVER; -compat(connack, 16#8A) -> ?CONNACK_AUTH; -compat(connack, 16#8B) -> ?CONNACK_SERVER; -compat(connack, 16#8C) -> ?CONNACK_AUTH; -compat(connack, 16#90) -> ?CONNACK_SERVER; -compat(connack, 16#97) -> ?CONNACK_SERVER; -compat(connack, 16#9C) -> ?CONNACK_SERVER; -compat(connack, 16#9D) -> ?CONNACK_SERVER; -compat(connack, 16#9F) -> ?CONNACK_SERVER; - -compat(suback, Code) when Code =< ?QOS_2 -> Code; -compat(suback, Code) when Code >= 16#80 -> 16#80; - -compat(unsuback, _Code) -> undefined; -compat(_Other, _Code) -> undefined. - -frame_error(frame_too_large) -> ?RC_PACKET_TOO_LARGE; -frame_error(_) -> ?RC_MALFORMED_PACKET. - -connack_error(protocol_error) -> ?RC_PROTOCOL_ERROR; -connack_error(client_identifier_not_valid) -> ?RC_CLIENT_IDENTIFIER_NOT_VALID; -connack_error(bad_username_or_password) -> ?RC_BAD_USER_NAME_OR_PASSWORD; -connack_error(bad_clientid_or_password) -> ?RC_BAD_USER_NAME_OR_PASSWORD; -connack_error(username_or_password_undefined) -> ?RC_BAD_USER_NAME_OR_PASSWORD; -connack_error(password_error) -> ?RC_BAD_USER_NAME_OR_PASSWORD; -connack_error(not_authorized) -> ?RC_NOT_AUTHORIZED; -connack_error(server_unavailable) -> ?RC_SERVER_UNAVAILABLE; -connack_error(server_busy) -> ?RC_SERVER_BUSY; -connack_error(banned) -> ?RC_BANNED; -connack_error(bad_authentication_method) -> ?RC_BAD_AUTHENTICATION_METHOD; -%% TODO: ??? -connack_error(_) -> ?RC_NOT_AUTHORIZED. - diff --git a/_build/emqx/lib/emqx/src/emqx_router.erl b/_build/emqx/lib/emqx/src/emqx_router.erl deleted file mode 100644 index cc358758f6..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_router.erl +++ /dev/null @@ -1,256 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_router). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). --include_lib("ekka/include/ekka.hrl"). - --logger_header("[Router]"). - -%% Mnesia bootstrap --export([mnesia/1]). - --boot_mnesia({mnesia, [boot]}). --copy_mnesia({mnesia, [copy]}). - --export([start_link/2]). - -%% Route APIs --export([ add_route/1 - , add_route/2 - , do_add_route/1 - , do_add_route/2 - ]). - --export([ delete_route/1 - , delete_route/2 - , do_delete_route/1 - , do_delete_route/2 - ]). - --export([ match_routes/1 - , lookup_routes/1 - , has_routes/1 - ]). - --export([print_routes/1]). - --export([topics/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --type(group() :: binary()). - --type(dest() :: node() | {group(), node()}). - --define(ROUTE_TAB, emqx_route). - -%%-------------------------------------------------------------------- -%% Mnesia bootstrap -%%-------------------------------------------------------------------- - -mnesia(boot) -> - ok = ekka_mnesia:create_table(?ROUTE_TAB, [ - {type, bag}, - {ram_copies, [node()]}, - {record_name, route}, - {attributes, record_info(fields, route)}, - {storage_properties, [{ets, [{read_concurrency, true}, - {write_concurrency, true}]}]}]); -mnesia(copy) -> - ok = ekka_mnesia:copy_table(?ROUTE_TAB). - -%%-------------------------------------------------------------------- -%% Start a router -%%-------------------------------------------------------------------- - --spec(start_link(atom(), pos_integer()) -> startlink_ret()). -start_link(Pool, Id) -> - gen_server:start_link({local, emqx_misc:proc_name(?MODULE, Id)}, - ?MODULE, [Pool, Id], [{hibernate_after, 1000}]). - -%%-------------------------------------------------------------------- -%% Route APIs -%%-------------------------------------------------------------------- - --spec(add_route(emqx_topic:topic()) -> ok | {error, term()}). -add_route(Topic) when is_binary(Topic) -> - add_route(Topic, node()). - --spec(add_route(emqx_topic:topic(), dest()) -> ok | {error, term()}). -add_route(Topic, Dest) when is_binary(Topic) -> - call(pick(Topic), {add_route, Topic, Dest}). - --spec(do_add_route(emqx_topic:topic()) -> ok | {error, term()}). -do_add_route(Topic) when is_binary(Topic) -> - do_add_route(Topic, node()). - --spec(do_add_route(emqx_topic:topic(), dest()) -> ok | {error, term()}). -do_add_route(Topic, Dest) when is_binary(Topic) -> - Route = #route{topic = Topic, dest = Dest}, - case lists:member(Route, lookup_routes(Topic)) of - true -> ok; - false -> - ok = emqx_router_helper:monitor(Dest), - case emqx_topic:wildcard(Topic) of - true -> trans(fun insert_trie_route/1, [Route]); - false -> insert_direct_route(Route) - end - end. - -%% @doc Match routes --spec(match_routes(emqx_topic:topic()) -> [emqx_types:route()]). -match_routes(Topic) when is_binary(Topic) -> - case match_trie(Topic) of - [] -> lookup_routes(Topic); - Matched -> - lists:append([lookup_routes(To) || To <- [Topic | Matched]]) - end. - -%% @private -%% Optimize: routing table will be replicated to all router nodes. -match_trie(Topic) -> - case emqx_trie:empty() of - true -> []; - false -> mnesia:ets(fun emqx_trie:match/1, [Topic]) - end. - --spec(lookup_routes(emqx_topic:topic()) -> [emqx_types:route()]). -lookup_routes(Topic) -> - ets:lookup(?ROUTE_TAB, Topic). - --spec(has_routes(emqx_topic:topic()) -> boolean()). -has_routes(Topic) when is_binary(Topic) -> - ets:member(?ROUTE_TAB, Topic). - --spec(delete_route(emqx_topic:topic()) -> ok | {error, term()}). -delete_route(Topic) when is_binary(Topic) -> - delete_route(Topic, node()). - --spec(delete_route(emqx_topic:topic(), dest()) -> ok | {error, term()}). -delete_route(Topic, Dest) when is_binary(Topic) -> - call(pick(Topic), {delete_route, Topic, Dest}). - --spec(do_delete_route(emqx_topic:topic()) -> ok | {error, term()}). -do_delete_route(Topic) when is_binary(Topic) -> - do_delete_route(Topic, node()). - --spec(do_delete_route(emqx_topic:topic(), dest()) -> ok | {error, term()}). -do_delete_route(Topic, Dest) -> - Route = #route{topic = Topic, dest = Dest}, - case emqx_topic:wildcard(Topic) of - true -> trans(fun delete_trie_route/1, [Route]); - false -> delete_direct_route(Route) - end. - --spec(topics() -> list(emqx_topic:topic())). -topics() -> - mnesia:dirty_all_keys(?ROUTE_TAB). - -%% @doc Print routes to a topic --spec(print_routes(emqx_topic:topic()) -> ok). -print_routes(Topic) -> - lists:foreach(fun(#route{topic = To, dest = Dest}) -> - io:format("~s -> ~s~n", [To, Dest]) - end, match_routes(Topic)). - -call(Router, Msg) -> - gen_server:call(Router, Msg, infinity). - -pick(Topic) -> - gproc_pool:pick_worker(router_pool, Topic). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Pool, Id]) -> - true = gproc_pool:connect_worker(Pool, {Pool, Id}), - {ok, #{pool => Pool, id => Id}}. - -handle_call({add_route, Topic, Dest}, _From, State) -> - Ok = do_add_route(Topic, Dest), - {reply, Ok, State}; - -handle_call({delete_route, Topic, Dest}, _From, State) -> - Ok = do_delete_route(Topic, Dest), - {reply, Ok, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{pool := Pool, id := Id}) -> - gproc_pool:disconnect_worker(Pool, {Pool, Id}). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -insert_direct_route(Route) -> - mnesia:async_dirty(fun mnesia:write/3, [?ROUTE_TAB, Route, sticky_write]). - -insert_trie_route(Route = #route{topic = Topic}) -> - case mnesia:wread({?ROUTE_TAB, Topic}) of - [] -> emqx_trie:insert(Topic); - _ -> ok - end, - mnesia:write(?ROUTE_TAB, Route, sticky_write). - -delete_direct_route(Route) -> - mnesia:async_dirty(fun mnesia:delete_object/3, [?ROUTE_TAB, Route, sticky_write]). - -delete_trie_route(Route = #route{topic = Topic}) -> - case mnesia:wread({?ROUTE_TAB, Topic}) of - [Route] -> %% Remove route and trie - ok = mnesia:delete_object(?ROUTE_TAB, Route, sticky_write), - emqx_trie:delete(Topic); - [_|_] -> %% Remove route only - mnesia:delete_object(?ROUTE_TAB, Route, sticky_write); - [] -> ok - end. - -%% @private --spec(trans(function(), list(any())) -> ok | {error, term()}). -trans(Fun, Args) -> - case mnesia:transaction(Fun, Args) of - {atomic, Ok} -> Ok; - {aborted, Reason} -> {error, Reason} - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_router_helper.erl b/_build/emqx/lib/emqx/src/emqx_router_helper.erl deleted file mode 100644 index ba5cc5543f..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_router_helper.erl +++ /dev/null @@ -1,178 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_router_helper). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Router Helper]"). - -%% Mnesia bootstrap --export([mnesia/1]). - --boot_mnesia({mnesia, [boot]}). --copy_mnesia({mnesia, [copy]}). - -%% API --export([ start_link/0 - , monitor/1 - ]). - -%% Internal export --export([stats_fun/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --record(routing_node, {name, const = unused}). - --define(ROUTE, emqx_route). --define(ROUTING_NODE, emqx_routing_node). --define(LOCK, {?MODULE, cleanup_routes}). - --dialyzer({nowarn_function, [cleanup_routes/1]}). - -%%-------------------------------------------------------------------- -%% Mnesia bootstrap -%%-------------------------------------------------------------------- - -mnesia(boot) -> - ok = ekka_mnesia:create_table(?ROUTING_NODE, [ - {type, set}, - {ram_copies, [node()]}, - {record_name, routing_node}, - {attributes, record_info(fields, routing_node)}, - {storage_properties, [{ets, [{read_concurrency, true}]}]}]); - -mnesia(copy) -> - ok = ekka_mnesia:copy_table(?ROUTING_NODE). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -%% @doc Starts the router helper --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - -%% @doc Monitor routing node --spec(monitor(node() | {binary(), node()}) -> ok). -monitor({_Group, Node}) -> - monitor(Node); -monitor(Node) when is_atom(Node) -> - case ekka:is_member(Node) - orelse ets:member(?ROUTING_NODE, Node) of - true -> ok; - false -> mnesia:dirty_write(?ROUTING_NODE, #routing_node{name = Node}) - end. - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - ok = ekka:monitor(membership), - {ok, _} = mnesia:subscribe({table, ?ROUTING_NODE, simple}), - Nodes = lists:foldl( - fun(Node, Acc) -> - case ekka:is_member(Node) of - true -> Acc; - false -> true = erlang:monitor_node(Node, true), - [Node | Acc] - end - end, [], mnesia:dirty_all_keys(?ROUTING_NODE)), - ok = emqx_stats:update_interval(route_stats, fun ?MODULE:stats_fun/0), - {ok, #{nodes => Nodes}, hibernate}. - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({mnesia_table_event, {write, {?ROUTING_NODE, Node, _}, _}}, State = #{nodes := Nodes}) -> - case ekka:is_member(Node) orelse lists:member(Node, Nodes) of - true -> {noreply, State}; - false -> - true = erlang:monitor_node(Node, true), - {noreply, State#{nodes := [Node | Nodes]}} - end; - -handle_info({mnesia_table_event, {delete, {?ROUTING_NODE, _Node}, _}}, State) -> - %% ignore - {noreply, State}; - -handle_info({mnesia_table_event, Event}, State) -> - ?LOG(error, "Unexpected mnesia_table_event: ~p", [Event]), - {noreply, State}; - -handle_info({nodedown, Node}, State = #{nodes := Nodes}) -> - global:trans({?LOCK, self()}, - fun() -> - mnesia:transaction(fun cleanup_routes/1, [Node]) - end), - ok = mnesia:dirty_delete(?ROUTING_NODE, Node), - {noreply, State#{nodes := lists:delete(Node, Nodes)}, hibernate}; - -handle_info({membership, {mnesia, down, Node}}, State) -> - handle_info({nodedown, Node}, State); - -handle_info({membership, _Event}, State) -> - {noreply, State}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok = ekka:unmonitor(membership), - emqx_stats:cancel_update(route_stats), - mnesia:unsubscribe({table, ?ROUTING_NODE, simple}). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -stats_fun() -> - case ets:info(?ROUTE, size) of - undefined -> ok; - Size -> - emqx_stats:setstat('routes.count', 'routes.max', Size), - emqx_stats:setstat('topics.count', 'topics.max', Size) - end. - -cleanup_routes(Node) -> - Patterns = [#route{_ = '_', dest = Node}, - #route{_ = '_', dest = {'_', Node}}], - [mnesia:delete_object(?ROUTE, Route, write) - || Pat <- Patterns, Route <- mnesia:match_object(?ROUTE, Pat, write)]. - diff --git a/_build/emqx/lib/emqx/src/emqx_router_sup.erl b/_build/emqx/lib/emqx/src/emqx_router_sup.erl deleted file mode 100644 index 9060e58bf3..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_router_sup.erl +++ /dev/null @@ -1,41 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_router_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -init([]) -> - %% Router helper - Helper = #{id => helper, - start => {emqx_router_helper, start_link, []}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [emqx_router_helper]}, - - %% Router pool - RouterPool = emqx_pool_sup:spec([router_pool, hash, - {emqx_router, start_link, []}]), - {ok, {{one_for_all, 0, 1}, [Helper, RouterPool]}}. - diff --git a/_build/emqx/lib/emqx/src/emqx_rpc.erl b/_build/emqx/lib/emqx/src/emqx_rpc.erl deleted file mode 100644 index 727eb458b6..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_rpc.erl +++ /dev/null @@ -1,74 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc wrap gen_rpc? --module(emqx_rpc). - --export([ call/4 - , call/5 - , cast/4 - , cast/5 - , multicall/4 - , multicall/5 - ]). - --compile({inline, - [ rpc_node/1 - , rpc_nodes/1 - ]}). - --define(RPC, gen_rpc). - --define(DefaultClientNum, 1). - -call(Node, Mod, Fun, Args) -> - filter_result(?RPC:call(rpc_node(Node), Mod, Fun, Args)). - -call(Key, Node, Mod, Fun, Args) -> - filter_result(?RPC:call(rpc_node({Key, Node}), Mod, Fun, Args)). - -multicall(Nodes, Mod, Fun, Args) -> - filter_result(?RPC:multicall(rpc_nodes(Nodes), Mod, Fun, Args)). - -multicall(Key, Nodes, Mod, Fun, Args) -> - filter_result(?RPC:multicall(rpc_nodes([{Key, Node} || Node <- Nodes]), Mod, Fun, Args)). - -cast(Node, Mod, Fun, Args) -> - filter_result(?RPC:cast(rpc_node(Node), Mod, Fun, Args)). - -cast(Key, Node, Mod, Fun, Args) -> - filter_result(?RPC:cast(rpc_node({Key, Node}), Mod, Fun, Args)). - -rpc_node(Node) when is_atom(Node) -> - ClientNum = application:get_env(gen_rpc, tcp_client_num, ?DefaultClientNum), - {Node, rand:uniform(ClientNum)}; -rpc_node({Key, Node}) when is_atom(Node) -> - ClientNum = application:get_env(gen_rpc, tcp_client_num, ?DefaultClientNum), - {Node, erlang:phash2(Key, ClientNum) + 1}. - -rpc_nodes(Nodes) -> - rpc_nodes(Nodes, []). - -rpc_nodes([], Acc) -> - Acc; -rpc_nodes([Node | Nodes], Acc) -> - rpc_nodes(Nodes, [rpc_node(Node) | Acc]). - -filter_result({Error, Reason}) - when Error =:= badrpc; Error =:= badtcp -> - {badrpc, Reason}; -filter_result(Delivery) -> - Delivery. diff --git a/_build/emqx/lib/emqx/src/emqx_sequence.erl b/_build/emqx/lib/emqx/src/emqx_sequence.erl deleted file mode 100644 index d0823cd820..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_sequence.erl +++ /dev/null @@ -1,73 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_sequence). - --export([ create/1 - , nextval/2 - , currval/2 - , reclaim/2 - , delete/1 - ]). - --export_type([seqid/0]). - --type(key() :: term()). - --type(name() :: atom()). - --type(seqid() :: non_neg_integer()). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Create a sequence. --spec(create(name()) -> ok). -create(Name) -> - emqx_tables:new(Name, [public, set, {write_concurrency, true}]). - -%% @doc Next value of the sequence. --spec(nextval(name(), key()) -> seqid()). -nextval(Name, Key) -> - ets:update_counter(Name, Key, {2, 1}, {Key, 0}). - -%% @doc Current value of the sequence. --spec(currval(name(), key()) -> seqid()). -currval(Name, Key) -> - try ets:lookup_element(Name, Key, 2) - catch - error:badarg -> 0 - end. - -%% @doc Reclaim a sequence id. --spec(reclaim(name(), key()) -> seqid()). -reclaim(Name, Key) -> - try ets:update_counter(Name, Key, {2, -1, 0, 0}) of - 0 -> ets:delete_object(Name, {Key, 0}), 0; - I -> I - catch - error:badarg -> 0 - end. - -%% @doc Delete the sequence. --spec(delete(name()) -> boolean()). -delete(Name) -> - case ets:info(Name, name) of - Name -> ets:delete(Name); - undefined -> false - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_session.erl b/_build/emqx/lib/emqx/src/emqx_session.erl deleted file mode 100644 index 88664e0283..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_session.erl +++ /dev/null @@ -1,698 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%%-------------------------------------------------------------------- -%% @doc -%% A stateful interaction between a Client and a Server. Some Sessions -%% last only as long as the Network Connection, others can span multiple -%% consecutive Network Connections between a Client and a Server. -%% -%% The Session State in the Server consists of: -%% -%% The existence of a Session, even if the rest of the Session State is empty. -%% -%% The Clients subscriptions, including any Subscription Identifiers. -%% -%% QoS 1 and QoS 2 messages which have been sent to the Client, but have not -%% been completely acknowledged. -%% -%% QoS 1 and QoS 2 messages pending transmission to the Client and OPTIONALLY -%% QoS 0 messages pending transmission to the Client. -%% -%% QoS 2 messages which have been received from the Client, but have not been -%% completely acknowledged.The Will Message and the Will Delay Interval -%% -%% If the Session is currently not connected, the time at which the Session -%% will end and Session State will be discarded. -%% @end -%%-------------------------------------------------------------------- - -%% MQTT Session --module(emqx_session). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Session]"). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --export([init/2]). - --export([ info/1 - , info/2 - , stats/1 - ]). - --export([ subscribe/4 - , unsubscribe/4 - ]). - --export([ publish/3 - , puback/2 - , pubrec/2 - , pubrel/2 - , pubcomp/2 - ]). - --export([ deliver/2 - , enqueue/2 - , retry/1 - , terminate/3 - ]). - --export([ takeover/1 - , resume/2 - , replay/1 - ]). - --export([expire/2]). - -%% Export for CT --export([set_field/3]). - --export_type([session/0]). - --import(emqx_zone, [get_env/3]). - --record(session, { - %% Client’s Subscriptions. - subscriptions :: map(), - %% Max subscriptions allowed - max_subscriptions :: non_neg_integer(), - %% Upgrade QoS? - upgrade_qos :: boolean(), - %% Client <- Broker: QoS1/2 messages sent to the client but - %% have not been unacked. - inflight :: emqx_inflight:inflight(), - %% All QoS1/2 messages published to when client is disconnected, - %% or QoS1/2 messages pending transmission to the Client. - %% - %% Optionally, QoS0 messages pending transmission to the Client. - mqueue :: emqx_mqueue:mqueue(), - %% Next packet id of the session - next_pkt_id = 1 :: emqx_types:packet_id(), - %% Retry interval for redelivering QoS1/2 messages (Unit: millsecond) - retry_interval :: timeout(), - %% Client -> Broker: QoS2 messages received from the client, but - %% have not been completely acknowledged - awaiting_rel :: map(), - %% Maximum number of awaiting QoS2 messages allowed - max_awaiting_rel :: non_neg_integer(), - %% Awaiting PUBREL Timeout (Unit: millsecond) - await_rel_timeout :: timeout(), - %% Created at - created_at :: pos_integer() - }). - --type(session() :: #session{}). - --type(publish() :: {maybe(emqx_types:packet_id()), emqx_types:message()}). - --type(pubrel() :: {pubrel, emqx_types:packet_id()}). - --type(replies() :: list(publish() | pubrel())). - --define(INFO_KEYS, [subscriptions, - upgrade_qos, - retry_interval, - await_rel_timeout, - created_at - ]). - --define(STATS_KEYS, [subscriptions_cnt, - subscriptions_max, - inflight_cnt, - inflight_max, - mqueue_len, - mqueue_max, - mqueue_dropped, - next_pkt_id, - awaiting_rel_cnt, - awaiting_rel_max - ]). - --define(DEFAULT_BATCH_N, 1000). - - -%%-------------------------------------------------------------------- -%% Init a Session -%%-------------------------------------------------------------------- - --spec(init(emqx_types:clientinfo(), emqx_types:conninfo()) -> session()). -init(#{zone := Zone}, #{receive_maximum := MaxInflight}) -> - #session{max_subscriptions = get_env(Zone, max_subscriptions, 0), - subscriptions = #{}, - upgrade_qos = get_env(Zone, upgrade_qos, false), - inflight = emqx_inflight:new(MaxInflight), - mqueue = init_mqueue(Zone), - next_pkt_id = 1, - retry_interval = timer:seconds(get_env(Zone, retry_interval, 0)), - awaiting_rel = #{}, - max_awaiting_rel = get_env(Zone, max_awaiting_rel, 100), - await_rel_timeout = timer:seconds(get_env(Zone, await_rel_timeout, 300)), - created_at = erlang:system_time(millisecond) - }. - -%% @private init mq -init_mqueue(Zone) -> - emqx_mqueue:init(#{max_len => get_env(Zone, max_mqueue_len, 1000), - store_qos0 => get_env(Zone, mqueue_store_qos0, true), - priorities => get_env(Zone, mqueue_priorities, none), - default_priority => get_env(Zone, mqueue_default_priority, lowest) - }). - -%%-------------------------------------------------------------------- -%% Info, Stats -%%-------------------------------------------------------------------- - -%% @doc Get infos of the session. --spec(info(session()) -> emqx_types:infos()). -info(Session) -> - maps:from_list(info(?INFO_KEYS, Session)). - -info(Keys, Session) when is_list(Keys) -> - [{Key, info(Key, Session)} || Key <- Keys]; -info(subscriptions, #session{subscriptions = Subs}) -> - Subs; -info(subscriptions_cnt, #session{subscriptions = Subs}) -> - maps:size(Subs); -info(subscriptions_max, #session{max_subscriptions = MaxSubs}) -> - MaxSubs; -info(upgrade_qos, #session{upgrade_qos = UpgradeQoS}) -> - UpgradeQoS; -info(inflight, #session{inflight = Inflight}) -> - Inflight; -info(inflight_cnt, #session{inflight = Inflight}) -> - emqx_inflight:size(Inflight); -info(inflight_max, #session{inflight = Inflight}) -> - emqx_inflight:max_size(Inflight); -info(retry_interval, #session{retry_interval = Interval}) -> - Interval div 1000; -info(mqueue, #session{mqueue = MQueue}) -> - MQueue; -info(mqueue_len, #session{mqueue = MQueue}) -> - emqx_mqueue:len(MQueue); -info(mqueue_max, #session{mqueue = MQueue}) -> - emqx_mqueue:max_len(MQueue); -info(mqueue_dropped, #session{mqueue = MQueue}) -> - emqx_mqueue:dropped(MQueue); -info(next_pkt_id, #session{next_pkt_id = PacketId}) -> - PacketId; -info(awaiting_rel, #session{awaiting_rel = AwaitingRel}) -> - AwaitingRel; -info(awaiting_rel_cnt, #session{awaiting_rel = AwaitingRel}) -> - maps:size(AwaitingRel); -info(awaiting_rel_max, #session{max_awaiting_rel = Max}) -> - Max; -info(await_rel_timeout, #session{await_rel_timeout = Timeout}) -> - Timeout div 1000; -info(created_at, #session{created_at = CreatedAt}) -> - CreatedAt. - -%% @doc Get stats of the session. --spec(stats(session()) -> emqx_types:stats()). -stats(Session) -> info(?STATS_KEYS, Session). - -%%-------------------------------------------------------------------- -%% Client -> Broker: SUBSCRIBE -%%-------------------------------------------------------------------- - --spec(subscribe(emqx_types:clientinfo(), emqx_types:topic(), - emqx_types:subopts(), session()) - -> {ok, session()} | {error, emqx_types:reason_code()}). -subscribe(ClientInfo = #{clientid := ClientId}, TopicFilter, SubOpts, - Session = #session{subscriptions = Subs}) -> - IsNew = not maps:is_key(TopicFilter, Subs), - case IsNew andalso is_subscriptions_full(Session) of - false -> - ok = emqx_broker:subscribe(TopicFilter, ClientId, SubOpts), - ok = emqx_hooks:run('session.subscribed', - [ClientInfo, TopicFilter, SubOpts#{is_new => IsNew}]), - {ok, Session#session{subscriptions = maps:put(TopicFilter, SubOpts, Subs)}}; - true -> {error, ?RC_QUOTA_EXCEEDED} - end. - --compile({inline, [is_subscriptions_full/1]}). -is_subscriptions_full(#session{max_subscriptions = 0}) -> - false; -is_subscriptions_full(#session{subscriptions = Subs, - max_subscriptions = MaxLimit}) -> - maps:size(Subs) >= MaxLimit. - -%%-------------------------------------------------------------------- -%% Client -> Broker: UNSUBSCRIBE -%%-------------------------------------------------------------------- - --spec(unsubscribe(emqx_types:clientinfo(), emqx_types:topic(), emqx_types:subopts(), session()) - -> {ok, session()} | {error, emqx_types:reason_code()}). -unsubscribe(ClientInfo, TopicFilter, UnSubOpts, Session = #session{subscriptions = Subs}) -> - case maps:find(TopicFilter, Subs) of - {ok, SubOpts} -> - ok = emqx_broker:unsubscribe(TopicFilter), - ok = emqx_hooks:run('session.unsubscribed', [ClientInfo, TopicFilter, maps:merge(SubOpts, UnSubOpts)]), - {ok, Session#session{subscriptions = maps:remove(TopicFilter, Subs)}}; - error -> - {error, ?RC_NO_SUBSCRIPTION_EXISTED} - end. - -%%-------------------------------------------------------------------- -%% Client -> Broker: PUBLISH -%%-------------------------------------------------------------------- - --spec(publish(emqx_types:packet_id(), emqx_types:message(), session()) - -> {ok, emqx_types:publish_result(), session()} - | {error, emqx_types:reason_code()}). -publish(PacketId, Msg = #message{qos = ?QOS_2, timestamp = Ts}, - Session = #session{awaiting_rel = AwaitingRel}) -> - case is_awaiting_full(Session) of - false -> - case maps:is_key(PacketId, AwaitingRel) of - false -> - Results = emqx_broker:publish(Msg), - AwaitingRel1 = maps:put(PacketId, Ts, AwaitingRel), - {ok, Results, Session#session{awaiting_rel = AwaitingRel1}}; - true -> - {error, ?RC_PACKET_IDENTIFIER_IN_USE} - end; - true -> {error, ?RC_RECEIVE_MAXIMUM_EXCEEDED} - end; - -%% Publish QoS0/1 directly -publish(_PacketId, Msg, Session) -> - {ok, emqx_broker:publish(Msg), Session}. - --compile({inline, [is_awaiting_full/1]}). -is_awaiting_full(#session{max_awaiting_rel = 0}) -> - false; -is_awaiting_full(#session{awaiting_rel = AwaitingRel, - max_awaiting_rel = MaxLimit}) -> - maps:size(AwaitingRel) >= MaxLimit. - -%%-------------------------------------------------------------------- -%% Client -> Broker: PUBACK -%%-------------------------------------------------------------------- - --spec(puback(emqx_types:packet_id(), session()) - -> {ok, emqx_types:message(), session()} - | {ok, emqx_types:message(), replies(), session()} - | {error, emqx_types:reason_code()}). -puback(PacketId, Session = #session{inflight = Inflight}) -> - case emqx_inflight:lookup(PacketId, Inflight) of - {value, {Msg, _Ts}} when is_record(Msg, message) -> - Inflight1 = emqx_inflight:delete(PacketId, Inflight), - return_with(Msg, dequeue(Session#session{inflight = Inflight1})); - {value, {_Pubrel, _Ts}} -> - {error, ?RC_PACKET_IDENTIFIER_IN_USE}; - none -> - {error, ?RC_PACKET_IDENTIFIER_NOT_FOUND} - end. - --compile({inline, [return_with/2]}). -return_with(Msg, {ok, Session}) -> - {ok, Msg, Session}; -return_with(Msg, {ok, Publishes, Session}) -> - {ok, Msg, Publishes, Session}. - -%%-------------------------------------------------------------------- -%% Client -> Broker: PUBREC -%%-------------------------------------------------------------------- - --spec(pubrec(emqx_types:packet_id(), session()) - -> {ok, emqx_types:message(), session()} - | {error, emqx_types:reason_code()}). -pubrec(PacketId, Session = #session{inflight = Inflight}) -> - case emqx_inflight:lookup(PacketId, Inflight) of - {value, {Msg, _Ts}} when is_record(Msg, message) -> - Inflight1 = emqx_inflight:update(PacketId, with_ts(pubrel), Inflight), - {ok, Msg, Session#session{inflight = Inflight1}}; - {value, {pubrel, _Ts}} -> - {error, ?RC_PACKET_IDENTIFIER_IN_USE}; - none -> - {error, ?RC_PACKET_IDENTIFIER_NOT_FOUND} - end. - -%%-------------------------------------------------------------------- -%% Client -> Broker: PUBREL -%%-------------------------------------------------------------------- - --spec(pubrel(emqx_types:packet_id(), session()) - -> {ok, session()} | {error, emqx_types:reason_code()}). -pubrel(PacketId, Session = #session{awaiting_rel = AwaitingRel}) -> - case maps:take(PacketId, AwaitingRel) of - {_Ts, AwaitingRel1} -> - {ok, Session#session{awaiting_rel = AwaitingRel1}}; - error -> - {error, ?RC_PACKET_IDENTIFIER_NOT_FOUND} - end. - -%%-------------------------------------------------------------------- -%% Client -> Broker: PUBCOMP -%%-------------------------------------------------------------------- - --spec(pubcomp(emqx_types:packet_id(), session()) - -> {ok, session()} | {ok, replies(), session()} - | {error, emqx_types:reason_code()}). -pubcomp(PacketId, Session = #session{inflight = Inflight}) -> - case emqx_inflight:lookup(PacketId, Inflight) of - {value, {pubrel, _Ts}} -> - Inflight1 = emqx_inflight:delete(PacketId, Inflight), - dequeue(Session#session{inflight = Inflight1}); - {value, _Other} -> - {error, ?RC_PACKET_IDENTIFIER_IN_USE}; - none -> - {error, ?RC_PACKET_IDENTIFIER_NOT_FOUND} - end. - -%%-------------------------------------------------------------------- -%% Dequeue Msgs -%%-------------------------------------------------------------------- - -dequeue(Session = #session{inflight = Inflight, mqueue = Q}) -> - case emqx_mqueue:is_empty(Q) of - true -> {ok, Session}; - false -> - {Msgs, Q1} = dequeue(batch_n(Inflight), [], Q), - deliver(Msgs, [], Session#session{mqueue = Q1}) - end. - -dequeue(0, Msgs, Q) -> - {lists:reverse(Msgs), Q}; - -dequeue(Cnt, Msgs, Q) -> - case emqx_mqueue:out(Q) of - {empty, _Q} -> dequeue(0, Msgs, Q); - {{value, Msg}, Q1} -> - case emqx_message:is_expired(Msg) of - true -> ok = inc_expired_cnt(delivery), - dequeue(Cnt, Msgs, Q1); - false -> dequeue(acc_cnt(Msg, Cnt), [Msg|Msgs], Q1) - end - end. - --compile({inline, [acc_cnt/2]}). -acc_cnt(#message{qos = ?QOS_0}, Cnt) -> Cnt; -acc_cnt(_Msg, Cnt) -> Cnt - 1. - -%%-------------------------------------------------------------------- -%% Broker -> Client: Deliver -%%-------------------------------------------------------------------- - --spec(deliver(list(emqx_types:deliver()), session()) - -> {ok, session()} | {ok, replies(), session()}). -deliver([Deliver], Session) -> %% Optimize - Enrich = enrich_fun(Session), - deliver_msg(Enrich(Deliver), Session); - -deliver(Delivers, Session) -> - Msgs = lists:map(enrich_fun(Session), Delivers), - deliver(Msgs, [], Session). - -deliver([], Publishes, Session) -> - {ok, lists:reverse(Publishes), Session}; - -deliver([Msg|More], Acc, Session) -> - case deliver_msg(Msg, Session) of - {ok, Session1} -> - deliver(More, Acc, Session1); - {ok, [Publish], Session1} -> - deliver(More, [Publish|Acc], Session1) - end. - -deliver_msg(Msg = #message{qos = ?QOS_0}, Session) -> - {ok, [{undefined, maybe_ack(Msg)}], Session}; - -deliver_msg(Msg = #message{qos = QoS}, Session = - #session{next_pkt_id = PacketId, inflight = Inflight}) - when QoS =:= ?QOS_1 orelse QoS =:= ?QOS_2 -> - case emqx_inflight:is_full(Inflight) of - true -> - Session1 = case maybe_nack(Msg) of - true -> Session; - false -> enqueue(Msg, Session) - end, - {ok, Session1}; - false -> - Publish = {PacketId, maybe_ack(Msg)}, - Session1 = await(PacketId, Msg, Session), - {ok, [Publish], next_pkt_id(Session1)} - end. - --spec(enqueue(list(emqx_types:deliver())|emqx_types:message(), - session()) -> session()). -enqueue([Deliver], Session) -> %% Optimize - Enrich = enrich_fun(Session), - enqueue(Enrich(Deliver), Session); - -enqueue(Delivers, Session) when is_list(Delivers) -> - Msgs = lists:map(enrich_fun(Session), Delivers), - lists:foldl(fun enqueue/2, Session, Msgs); - -enqueue(Msg, Session = #session{mqueue = Q}) when is_record(Msg, message) -> - {Dropped, NewQ} = emqx_mqueue:in(Msg, Q), - (Dropped =/= undefined) andalso log_dropped(Dropped, Session), - Session#session{mqueue = NewQ}. - -log_dropped(Msg = #message{qos = QoS}, #session{mqueue = Q}) -> - case (QoS == ?QOS_0) andalso (not emqx_mqueue:info(store_qos0, Q)) of - true -> - ok = emqx_metrics:inc('delivery.dropped.qos0_msg'), - ?LOG(warning, "Dropped qos0 msg: ~s", [emqx_message:format(Msg)]); - false -> - ok = emqx_metrics:inc('delivery.dropped.queue_full'), - ?LOG(warning, "Dropped msg due to mqueue is full: ~s", - [emqx_message:format(Msg)]) - end. - -enrich_fun(Session = #session{subscriptions = Subs}) -> - fun({deliver, Topic, Msg}) -> - enrich_subopts(get_subopts(Topic, Subs), Msg, Session) - end. - -maybe_ack(Msg) -> - case emqx_shared_sub:is_ack_required(Msg) of - true -> emqx_shared_sub:maybe_ack(Msg); - false -> Msg - end. - -maybe_nack(Msg) -> - emqx_shared_sub:is_ack_required(Msg) - andalso (ok == emqx_shared_sub:maybe_nack_dropped(Msg)). - -get_subopts(Topic, SubMap) -> - case maps:find(Topic, SubMap) of - {ok, #{nl := Nl, qos := QoS, rap := Rap, subid := SubId}} -> - [{nl, Nl}, {qos, QoS}, {rap, Rap}, {subid, SubId}]; - {ok, #{nl := Nl, qos := QoS, rap := Rap}} -> - [{nl, Nl}, {qos, QoS}, {rap, Rap}]; - error -> [] - end. - -enrich_subopts([], Msg, _Session) -> Msg; -enrich_subopts([{nl, 1}|Opts], Msg, Session) -> - enrich_subopts(Opts, emqx_message:set_flag(nl, Msg), Session); -enrich_subopts([{nl, 0}|Opts], Msg, Session) -> - enrich_subopts(Opts, Msg, Session); -enrich_subopts([{qos, SubQoS}|Opts], Msg = #message{qos = PubQoS}, - Session = #session{upgrade_qos = true}) -> - enrich_subopts(Opts, Msg#message{qos = max(SubQoS, PubQoS)}, Session); -enrich_subopts([{qos, SubQoS}|Opts], Msg = #message{qos = PubQoS}, - Session = #session{upgrade_qos = false}) -> - enrich_subopts(Opts, Msg#message{qos = min(SubQoS, PubQoS)}, Session); -enrich_subopts([{rap, 1}|Opts], Msg, Session) -> - enrich_subopts(Opts, Msg, Session); -enrich_subopts([{rap, 0}|Opts], Msg = #message{headers = #{retained := true}}, Session) -> - enrich_subopts(Opts, Msg, Session); -enrich_subopts([{rap, 0}|Opts], Msg, Session) -> - enrich_subopts(Opts, emqx_message:set_flag(retain, false, Msg), Session); -enrich_subopts([{subid, SubId}|Opts], Msg, Session) -> - Props = emqx_message:get_header(properties, Msg, #{}), - Msg1 = emqx_message:set_header(properties, Props#{'Subscription-Identifier' => SubId}, Msg), - enrich_subopts(Opts, Msg1, Session). - -%%-------------------------------------------------------------------- -%% Awaiting ACK for QoS1/QoS2 Messages -%%-------------------------------------------------------------------- - -await(PacketId, Msg, Session = #session{inflight = Inflight}) -> - Inflight1 = emqx_inflight:insert(PacketId, with_ts(Msg), Inflight), - Session#session{inflight = Inflight1}. - -%%-------------------------------------------------------------------- -%% Retry Delivery -%%-------------------------------------------------------------------- - --spec(retry(session()) -> {ok, session()} | {ok, replies(), timeout(), session()}). -retry(Session = #session{inflight = Inflight}) -> - case emqx_inflight:is_empty(Inflight) of - true -> {ok, Session}; - false -> retry_delivery(emqx_inflight:to_list(sort_fun(), Inflight), - [], erlang:system_time(millisecond), Session) - end. - -retry_delivery([], Acc, _Now, Session = #session{retry_interval = Interval}) -> - {ok, lists:reverse(Acc), Interval, Session}; - -retry_delivery([{PacketId, {Msg, Ts}}|More], Acc, Now, Session = - #session{retry_interval = Interval, inflight = Inflight}) -> - case (Age = age(Now, Ts)) >= Interval of - true -> - {Acc1, Inflight1} = retry_delivery(PacketId, Msg, Now, Acc, Inflight), - retry_delivery(More, Acc1, Now, Session#session{inflight = Inflight1}); - false -> - {ok, lists:reverse(Acc), Interval - max(0, Age), Session} - end. - -retry_delivery(PacketId, Msg, Now, Acc, Inflight) when is_record(Msg, message) -> - case emqx_message:is_expired(Msg) of - true -> - ok = inc_expired_cnt(delivery), - {Acc, emqx_inflight:delete(PacketId, Inflight)}; - false -> - Msg1 = emqx_message:set_flag(dup, true, Msg), - Inflight1 = emqx_inflight:update(PacketId, {Msg1, Now}, Inflight), - {[{PacketId, Msg1}|Acc], Inflight1} - end; - -retry_delivery(PacketId, pubrel, Now, Acc, Inflight) -> - Inflight1 = emqx_inflight:update(PacketId, {pubrel, Now}, Inflight), - {[{pubrel, PacketId}|Acc], Inflight1}. - -%%-------------------------------------------------------------------- -%% Expire Awaiting Rel -%%-------------------------------------------------------------------- - --spec(expire(awaiting_rel, session()) -> {ok, session()} | {ok, timeout(), session()}). -expire(awaiting_rel, Session = #session{awaiting_rel = AwaitingRel}) -> - case maps:size(AwaitingRel) of - 0 -> {ok, Session}; - _ -> expire_awaiting_rel(erlang:system_time(millisecond), Session) - end. - -expire_awaiting_rel(Now, Session = #session{awaiting_rel = AwaitingRel, - await_rel_timeout = Timeout}) -> - NotExpired = fun(_PacketId, Ts) -> age(Now, Ts) < Timeout end, - AwaitingRel1 = maps:filter(NotExpired, AwaitingRel), - ExpiredCnt = maps:size(AwaitingRel) - maps:size(AwaitingRel1), - (ExpiredCnt > 0) andalso inc_expired_cnt(message, ExpiredCnt), - NSession = Session#session{awaiting_rel = AwaitingRel1}, - case maps:size(AwaitingRel1) of - 0 -> {ok, NSession}; - _ -> {ok, Timeout, NSession} - end. - -%%-------------------------------------------------------------------- -%% Takeover, Resume and Replay -%%-------------------------------------------------------------------- - --spec(takeover(session()) -> ok). -takeover(#session{subscriptions = Subs}) -> - lists:foreach(fun emqx_broker:unsubscribe/1, maps:keys(Subs)). - --spec(resume(emqx_types:clientinfo(), session()) -> ok). -resume(ClientInfo = #{clientid := ClientId}, Session = #session{subscriptions = Subs}) -> - lists:foreach(fun({TopicFilter, SubOpts}) -> - ok = emqx_broker:subscribe(TopicFilter, ClientId, SubOpts) - end, maps:to_list(Subs)), - ok = emqx_metrics:inc('session.resumed'), - emqx_hooks:run('session.resumed', [ClientInfo, info(Session)]). - --spec(replay(session()) -> {ok, replies(), session()}). -replay(Session = #session{inflight = Inflight}) -> - Pubs = lists:map(fun({PacketId, {pubrel, _Ts}}) -> - {pubrel, PacketId}; - ({PacketId, {Msg, _Ts}}) -> - {PacketId, emqx_message:set_flag(dup, true, Msg)} - end, emqx_inflight:to_list(Inflight)), - case dequeue(Session) of - {ok, NSession} -> {ok, Pubs, NSession}; - {ok, More, NSession} -> - {ok, lists:append(Pubs, More), NSession} - end. - --spec(terminate(emqx_types:clientinfo(), Reason :: term(), session()) -> ok). -terminate(ClientInfo, discarded, Session) -> - run_hook('session.discarded', [ClientInfo, info(Session)]); -terminate(ClientInfo, takeovered, Session) -> - run_hook('session.takeovered', [ClientInfo, info(Session)]); -terminate(ClientInfo, Reason, Session) -> - run_hook('session.terminated', [ClientInfo, Reason, info(Session)]). - --compile({inline, [run_hook/2]}). -run_hook(Name, Args) -> - ok = emqx_metrics:inc(Name), emqx_hooks:run(Name, Args). - -%%-------------------------------------------------------------------- -%% Inc message/delivery expired counter -%%-------------------------------------------------------------------- - --compile({inline, [inc_expired_cnt/1, inc_expired_cnt/2]}). - -inc_expired_cnt(K) -> inc_expired_cnt(K, 1). - -inc_expired_cnt(delivery, N) -> - ok = emqx_metrics:inc('delivery.dropped', N), - emqx_metrics:inc('delivery.dropped.expired', N); - -inc_expired_cnt(message, N) -> - ok = emqx_metrics:inc('messages.dropped', N), - emqx_metrics:inc('messages.dropped.expired', N). - -%%-------------------------------------------------------------------- -%% Next Packet Id -%%-------------------------------------------------------------------- - --compile({inline, [next_pkt_id/1]}). - -next_pkt_id(Session = #session{next_pkt_id = 16#FFFF}) -> - Session#session{next_pkt_id = 1}; - -next_pkt_id(Session = #session{next_pkt_id = Id}) -> - Session#session{next_pkt_id = Id + 1}. - -%%-------------------------------------------------------------------- -%% Helper functions -%%-------------------------------------------------------------------- - --compile({inline, [sort_fun/0, batch_n/1, with_ts/1, age/2]}). - -sort_fun() -> - fun({_, {_, Ts1}}, {_, {_, Ts2}}) -> Ts1 =< Ts2 end. - -batch_n(Inflight) -> - case emqx_inflight:max_size(Inflight) of - 0 -> ?DEFAULT_BATCH_N; - Sz -> Sz - emqx_inflight:size(Inflight) - end. - -with_ts(Msg) -> - {Msg, erlang:system_time(millisecond)}. - -age(Now, Ts) -> Now - Ts. - -%%-------------------------------------------------------------------- -%% For CT tests -%%-------------------------------------------------------------------- - -set_field(Name, Value, Session) -> - Pos = emqx_misc:index_of(Name, record_info(fields, session)), - setelement(Pos+1, Session, Value). - diff --git a/_build/emqx/lib/emqx/src/emqx_shared_sub.erl b/_build/emqx/lib/emqx/src/emqx_shared_sub.erl deleted file mode 100644 index 3563b1513a..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_shared_sub.erl +++ /dev/null @@ -1,384 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_shared_sub). - --behaviour(gen_server). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Shared Sub]"). - -%% Mnesia bootstrap --export([mnesia/1]). - --boot_mnesia({mnesia, [boot]}). --copy_mnesia({mnesia, [copy]}). - -%% APIs --export([start_link/0]). - --export([ subscribe/3 - , unsubscribe/3 - ]). - --export([dispatch/3]). - --export([ maybe_ack/1 - , maybe_nack_dropped/1 - , nack_no_connection/1 - , is_ack_required/1 - ]). - -%% for testing --export([subscribers/2]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --define(SERVER, ?MODULE). --define(TAB, emqx_shared_subscription). --define(SHARED_SUBS, emqx_shared_subscriber). --define(ALIVE_SUBS, emqx_alive_shared_subscribers). --define(SHARED_SUB_QOS1_DISPATCH_TIMEOUT_SECONDS, 5). --define(ack, shared_sub_ack). --define(nack(Reason), {shared_sub_nack, Reason}). --define(IS_LOCAL_PID(Pid), (is_pid(Pid) andalso node(Pid) =:= node())). --define(no_ack, no_ack). - --record(state, {pmon}). - --record(emqx_shared_subscription, {group, topic, subpid}). - -%%-------------------------------------------------------------------- -%% Mnesia bootstrap -%%-------------------------------------------------------------------- - -mnesia(boot) -> - ok = ekka_mnesia:create_table(?TAB, [ - {type, bag}, - {ram_copies, [node()]}, - {record_name, emqx_shared_subscription}, - {attributes, record_info(fields, emqx_shared_subscription)}]); - -mnesia(copy) -> - ok = ekka_mnesia:copy_table(?TAB). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - --spec(subscribe(emqx_topic:group(), emqx_topic:topic(), pid()) -> ok). -subscribe(Group, Topic, SubPid) when is_pid(SubPid) -> - gen_server:call(?SERVER, {subscribe, Group, Topic, SubPid}). - --spec(unsubscribe(emqx_topic:group(), emqx_topic:topic(), pid()) -> ok). -unsubscribe(Group, Topic, SubPid) when is_pid(SubPid) -> - gen_server:call(?SERVER, {unsubscribe, Group, Topic, SubPid}). - -record(Group, Topic, SubPid) -> - #emqx_shared_subscription{group = Group, topic = Topic, subpid = SubPid}. - --spec(dispatch(emqx_topic:group(), emqx_topic:topic(), emqx_types:delivery()) - -> emqx_types:deliver_result()). -dispatch(Group, Topic, Delivery) -> - dispatch(Group, Topic, Delivery, _FailedSubs = []). - -dispatch(Group, Topic, Delivery = #delivery{message = Msg}, FailedSubs) -> - #message{from = ClientId} = Msg, - case pick(strategy(), ClientId, Group, Topic, FailedSubs) of - false -> - {error, no_subscribers}; - {Type, SubPid} -> - case do_dispatch(SubPid, Topic, Msg, Type) of - ok -> - ok; - {error, _Reason} -> - %% Failed to dispatch to this sub, try next. - dispatch(Group, Topic, Delivery, [SubPid | FailedSubs]) - end - end. - --spec(strategy() -> random | round_robin | sticky | hash). -strategy() -> - emqx:get_env(shared_subscription_strategy, round_robin). - --spec(ack_enabled() -> boolean()). -ack_enabled() -> - emqx:get_env(shared_dispatch_ack_enabled, false). - -do_dispatch(SubPid, Topic, Msg, _Type) when SubPid =:= self() -> - %% Deadlock otherwise - _ = erlang:send(SubPid, {deliver, Topic, Msg}), - ok; -do_dispatch(SubPid, Topic, Msg, Type) -> - dispatch_per_qos(SubPid, Topic, Msg, Type). - -%% return either 'ok' (when everything is fine) or 'error' -dispatch_per_qos(SubPid, Topic, #message{qos = ?QOS_0} = Msg, _Type) -> - %% For QoS 0 message, send it as regular dispatch - _ = erlang:send(SubPid, {deliver, Topic, Msg}), - ok; -dispatch_per_qos(SubPid, Topic, Msg, retry) -> - %% Retry implies all subscribers nack:ed, send again without ack - _ = erlang:send(SubPid, {deliver, Topic, Msg}), - ok; -dispatch_per_qos(SubPid, Topic, Msg, fresh) -> - case ack_enabled() of - true -> - dispatch_with_ack(SubPid, Topic, Msg); - false -> - _ = erlang:send(SubPid, {deliver, Topic, Msg}), - ok - end. - -dispatch_with_ack(SubPid, Topic, Msg) -> - %% For QoS 1/2 message, expect an ack - Ref = erlang:monitor(process, SubPid), - Sender = self(), - _ = erlang:send(SubPid, {deliver, Topic, with_ack_ref(Msg, {Sender, Ref})}), - Timeout = case Msg#message.qos of - ?QOS_1 -> timer:seconds(?SHARED_SUB_QOS1_DISPATCH_TIMEOUT_SECONDS); - ?QOS_2 -> infinity - end, - try - receive - {Ref, ?ack} -> - ok; - {Ref, ?nack(Reason)} -> - %% the receive session may nack this message when its queue is full - {error, Reason}; - {'DOWN', Ref, process, SubPid, Reason} -> - {error, Reason} - after - Timeout -> - {error, timeout} - end - after - _ = erlang:demonitor(Ref, [flush]) - end. - -with_ack_ref(Msg, SenderRef) -> - emqx_message:set_headers(#{shared_dispatch_ack => SenderRef}, Msg). - -without_ack_ref(Msg) -> - emqx_message:set_headers(#{shared_dispatch_ack => ?no_ack}, Msg). - -get_ack_ref(Msg) -> - emqx_message:get_header(shared_dispatch_ack, Msg, ?no_ack). - --spec(is_ack_required(emqx_types:message()) -> boolean()). -is_ack_required(Msg) -> ?no_ack =/= get_ack_ref(Msg). - -%% @doc Negative ack dropped message due to inflight window or message queue being full. --spec(maybe_nack_dropped(emqx_types:message()) -> ok). -maybe_nack_dropped(Msg) -> - case get_ack_ref(Msg) of - ?no_ack -> ok; - {Sender, Ref} -> nack(Sender, Ref, dropped) - end. - -%% @doc Negative ack message due to connection down. -%% Assuming this function is always called when ack is required -%% i.e is_ack_required returned true. --spec(nack_no_connection(emqx_types:message()) -> ok). -nack_no_connection(Msg) -> - {Sender, Ref} = get_ack_ref(Msg), - nack(Sender, Ref, no_connection). - --spec(nack(pid(), reference(), dropped | no_connection) -> ok). -nack(Sender, Ref, Reason) -> - erlang:send(Sender, {Ref, ?nack(Reason)}), - ok. - --spec(maybe_ack(emqx_types:message()) -> emqx_types:message()). -maybe_ack(Msg) -> - case get_ack_ref(Msg) of - ?no_ack -> - Msg; - {Sender, Ref} -> - erlang:send(Sender, {Ref, ?ack}), - without_ack_ref(Msg) - end. - -pick(sticky, ClientId, Group, Topic, FailedSubs) -> - Sub0 = erlang:get({shared_sub_sticky, Group, Topic}), - case is_active_sub(Sub0, FailedSubs) of - true -> - %% the old subscriber is still alive - %% keep using it for sticky strategy - {fresh, Sub0}; - false -> - %% randomly pick one for the first message - {Type, Sub} = do_pick(random, ClientId, Group, Topic, [Sub0 | FailedSubs]), - %% stick to whatever pick result - erlang:put({shared_sub_sticky, Group, Topic}, Sub), - {Type, Sub} - end; -pick(Strategy, ClientId, Group, Topic, FailedSubs) -> - do_pick(Strategy, ClientId, Group, Topic, FailedSubs). - -do_pick(Strategy, ClientId, Group, Topic, FailedSubs) -> - All = subscribers(Group, Topic), - case All -- FailedSubs of - [] when FailedSubs =:= [] -> - %% Genuinely no subscriber - false; - [] -> - %% All offline? pick one anyway - {retry, pick_subscriber(Group, Topic, Strategy, ClientId, All)}; - Subs -> - %% More than one available - {fresh, pick_subscriber(Group, Topic, Strategy, ClientId, Subs)} - end. - -pick_subscriber(_Group, _Topic, _Strategy, _ClientId, [Sub]) -> Sub; -pick_subscriber(Group, Topic, Strategy, ClientId, Subs) -> - Nth = do_pick_subscriber(Group, Topic, Strategy, ClientId, length(Subs)), - lists:nth(Nth, Subs). - -do_pick_subscriber(_Group, _Topic, random, _ClientId, Count) -> - rand:uniform(Count); -do_pick_subscriber(_Group, _Topic, hash, ClientId, Count) -> - 1 + erlang:phash2(ClientId) rem Count; -do_pick_subscriber(Group, Topic, round_robin, _ClientId, Count) -> - Rem = case erlang:get({shared_sub_round_robin, Group, Topic}) of - undefined -> 0; - N -> (N + 1) rem Count - end, - _ = erlang:put({shared_sub_round_robin, Group, Topic}, Rem), - Rem + 1. - -subscribers(Group, Topic) -> - ets:select(?TAB, [{{emqx_shared_subscription, Group, Topic, '$1'}, [], ['$1']}]). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - {ok, _} = mnesia:subscribe({table, ?TAB, simple}), - {atomic, PMon} = mnesia:transaction(fun init_monitors/0), - ok = emqx_tables:new(?SHARED_SUBS, [protected, bag]), - ok = emqx_tables:new(?ALIVE_SUBS, [protected, set, {read_concurrency, true}]), - {ok, update_stats(#state{pmon = PMon})}. - -init_monitors() -> - mnesia:foldl( - fun(#emqx_shared_subscription{subpid = SubPid}, Mon) -> - emqx_pmon:monitor(SubPid, Mon) - end, emqx_pmon:new(), ?TAB). - -handle_call({subscribe, Group, Topic, SubPid}, _From, State = #state{pmon = PMon}) -> - mnesia:dirty_write(?TAB, record(Group, Topic, SubPid)), - case ets:member(?SHARED_SUBS, {Group, Topic}) of - true -> ok; - false -> ok = emqx_router:do_add_route(Topic, {Group, node()}) - end, - ok = maybe_insert_alive_tab(SubPid), - true = ets:insert(?SHARED_SUBS, {{Group, Topic}, SubPid}), - {reply, ok, update_stats(State#state{pmon = emqx_pmon:monitor(SubPid, PMon)})}; - -handle_call({unsubscribe, Group, Topic, SubPid}, _From, State) -> - mnesia:dirty_delete_object(?TAB, record(Group, Topic, SubPid)), - true = ets:delete_object(?SHARED_SUBS, {{Group, Topic}, SubPid}), - case ets:member(?SHARED_SUBS, {Group, Topic}) of - true -> ok; - false -> ok = emqx_router:do_delete_route(Topic, {Group, node()}) - end, - {reply, ok, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({mnesia_table_event, {write, NewRecord, _}}, State = #state{pmon = PMon}) -> - #emqx_shared_subscription{subpid = SubPid} = NewRecord, - {noreply, update_stats(State#state{pmon = emqx_pmon:monitor(SubPid, PMon)})}; - -handle_info({mnesia_table_event, {delete_object, OldRecord, _}}, State = #state{pmon = PMon}) -> - #emqx_shared_subscription{subpid = SubPid} = OldRecord, - {noreply, update_stats(State#state{pmon = emqx_pmon:demonitor(SubPid, PMon)})}; - -handle_info({mnesia_table_event, _Event}, State) -> - {noreply, State}; - -handle_info({'DOWN', _MRef, process, SubPid, _Reason}, State = #state{pmon = PMon}) -> - ?LOG(info, "Shared subscriber down: ~p", [SubPid]), - cleanup_down(SubPid), - {noreply, update_stats(State#state{pmon = emqx_pmon:erase(SubPid, PMon)})}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - mnesia:unsubscribe({table, ?TAB, simple}). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -%% keep track of alive remote pids -maybe_insert_alive_tab(Pid) when ?IS_LOCAL_PID(Pid) -> ok; -maybe_insert_alive_tab(Pid) when is_pid(Pid) -> ets:insert(?ALIVE_SUBS, {Pid}), ok. - -cleanup_down(SubPid) -> - ?IS_LOCAL_PID(SubPid) orelse ets:delete(?ALIVE_SUBS, SubPid), - lists:foreach( - fun(Record = #emqx_shared_subscription{topic = Topic, group = Group}) -> - ok = mnesia:dirty_delete_object(?TAB, Record), - true = ets:delete_object(?SHARED_SUBS, {{Group, Topic}, SubPid}), - case ets:member(?SHARED_SUBS, {Group, Topic}) of - true -> ok; - false -> ok = emqx_router:do_delete_route(Topic, {Group, node()}) - end - end, mnesia:dirty_match_object(#emqx_shared_subscription{_ = '_', subpid = SubPid})). - -update_stats(State) -> - emqx_stats:setstat('subscriptions.shared.count', 'subscriptions.shared.max', ets:info(?TAB, size)), - State. - -%% Return 'true' if the subscriber process is alive AND not in the failed list -is_active_sub(Pid, FailedSubs) -> - is_alive_sub(Pid) andalso not lists:member(Pid, FailedSubs). - -%% erlang:is_process_alive/1 does not work with remote pid. -is_alive_sub(Pid) when ?IS_LOCAL_PID(Pid) -> - erlang:is_process_alive(Pid); -is_alive_sub(Pid) -> - [] =/= ets:lookup(?ALIVE_SUBS, Pid). - diff --git a/_build/emqx/lib/emqx/src/emqx_stats.erl b/_build/emqx/lib/emqx/src/emqx_stats.erl deleted file mode 100644 index a6d53cfeb5..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_stats.erl +++ /dev/null @@ -1,277 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_stats). - --behaviour(gen_server). - --include("emqx.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Stats]"). - -%% APIs --export([ start_link/0 - , start_link/1 - , stop/0 - ]). - -%% Stats API. --export([ getstats/0 - , getstat/1 - , setstat/2 - , setstat/3 - , statsfun/1 - , statsfun/2 - ]). - --export([ update_interval/2 - , update_interval/3 - , cancel_update/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --export_type([stats/0]). - --record(update, {name, countdown, interval, func}). - --record(state, { - timer :: maybe(reference()), - updates :: [#update{}], - tick_ms :: timeout() - }). - --type(stats() :: list({atom(), non_neg_integer()})). - -%% Connection stats --define(CONNECTION_STATS, - ['connections.count', %% Count of Concurrent Connections - 'connections.max' %% Maximum Number of Concurrent Connections - ]). - -%% Channel stats --define(CHANNEL_STATS, - ['channels.count', %% Count of Concurrent Channels - 'channels.max' %% Maximum Number of Concurrent Channels - ]). - -%% Session stats --define(SESSION_STATS, - ['sessions.count', %% Count of Concurrent Sessions - 'sessions.max' %% Maximum Number of Concurrent Sessions - ]). - -%% PubSub stats --define(PUBSUB_STATS, - ['topics.count', - 'topics.max', - 'suboptions.count', - 'suboptions.max', - 'subscribers.count', - 'subscribers.max', - 'subscriptions.count', - 'subscriptions.max', - 'subscriptions.shared.count', - 'subscriptions.shared.max' - ]). - -%% Route stats --define(ROUTE_STATS, - ['routes.count', - 'routes.max' - ]). - -%% Retained stats --define(RETAINED_STATS, - ['retained.count', - 'retained.max' - ]). - --define(TAB, ?MODULE). --define(SERVER, ?MODULE). - --type(opts() :: #{tick_ms := timeout()}). - -%% @doc Start stats server --spec(start_link() -> startlink_ret()). -start_link() -> - start_link(#{tick_ms => timer:seconds(1)}). - --spec(start_link(opts()) -> startlink_ret()). -start_link(Opts) -> - gen_server:start_link({local, ?SERVER}, ?MODULE, Opts, []). - --spec(stop() -> ok). -stop() -> - gen_server:call(?SERVER, stop, infinity). - -%% @doc Generate stats fun. --spec(statsfun(Stat :: atom()) -> fun()). -statsfun(Stat) -> - fun(Val) -> setstat(Stat, Val) end. - --spec(statsfun(Stat :: atom(), MaxStat :: atom()) -> fun()). -statsfun(Stat, MaxStat) -> - fun(Val) -> setstat(Stat, MaxStat, Val) end. - -%% @doc Get all statistics. --spec(getstats() -> stats()). -getstats() -> - case ets:info(?TAB, name) of - undefined -> []; - _ -> ets:tab2list(?TAB) - end. - -%% @doc Get stats by name. --spec(getstat(atom()) -> maybe(non_neg_integer())). -getstat(Name) -> - case ets:lookup(?TAB, Name) of - [{Name, Val}] -> Val; - [] -> undefined - end. - -%% @doc Set stats --spec(setstat(Stat :: atom(), Val :: pos_integer()) -> boolean()). -setstat(Stat, Val) when is_integer(Val) -> - safe_update_element(Stat, Val). - -%% @doc Set stats with max value. --spec(setstat(Stat :: atom(), MaxStat :: atom(), - Val :: pos_integer()) -> ok). -setstat(Stat, MaxStat, Val) when is_integer(Val) -> - cast({setstat, Stat, MaxStat, Val}). - --spec(update_interval(atom(), fun()) -> ok). -update_interval(Name, UpFun) -> - update_interval(Name, 1, UpFun). - --spec(update_interval(atom(), pos_integer(), fun()) -> ok). -update_interval(Name, Secs, UpFun) when is_integer(Secs), Secs >= 1 -> - cast({update_interval, rec(Name, Secs, UpFun)}). - --spec(cancel_update(atom()) -> ok). -cancel_update(Name) -> - cast({cancel_update, Name}). - -rec(Name, Secs, UpFun) -> - #update{name = Name, countdown = Secs, interval = Secs, func = UpFun}. - -cast(Msg) -> gen_server:cast(?SERVER, Msg). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init(#{tick_ms := TickMs}) -> - ok = emqx_tables:new(?TAB, [public, set, {write_concurrency, true}]), - Stats = lists:append([?CONNECTION_STATS, - ?CHANNEL_STATS, - ?SESSION_STATS, - ?PUBSUB_STATS, - ?ROUTE_STATS, - ?RETAINED_STATS - ]), - true = ets:insert(?TAB, [{Name, 0} || Name <- Stats]), - {ok, start_timer(#state{updates = [], tick_ms = TickMs}), hibernate}. - -start_timer(#state{tick_ms = Ms} = State) -> - State#state{timer = emqx_misc:start_timer(Ms, tick)}. - -handle_call(stop, _From, State) -> - {stop, normal, ok, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast({setstat, Stat, MaxStat, Val}, State) -> - try ets:lookup_element(?TAB, MaxStat, 2) of - MaxVal when Val > MaxVal -> - ets:update_element(?TAB, MaxStat, {2, Val}); - _ -> ok - catch - error:badarg -> - ets:insert(?TAB, {MaxStat, Val}) - end, - safe_update_element(Stat, Val), - {noreply, State}; - -handle_cast({update_interval, Update = #update{name = Name}}, - State = #state{updates = Updates}) -> - NState = case lists:keyfind(Name, #update.name, Updates) of - #update{} -> - ?LOG(warning, "Duplicated update: ~s", [Name]), - State; - false -> State#state{updates = [Update|Updates]} - end, - {noreply, NState}; - -handle_cast({cancel_update, Name}, State = #state{updates = Updates}) -> - Updates1 = lists:keydelete(Name, #update.name, Updates), - {noreply, State#state{updates = Updates1}}; - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({timeout, TRef, tick}, State = #state{timer = TRef, updates = Updates}) -> - Updates1 = lists:foldl( - fun(Update = #update{name = Name, countdown = C, interval = I, - func = UpFun}, Acc) when C =< 0 -> - try UpFun() - catch - _:Error -> - ?LOG(error, "Update ~s failed: ~0p", [Name, Error]) - end, - [Update#update{countdown = I} | Acc]; - (Update = #update{countdown = C}, Acc) -> - [Update#update{countdown = C - 1} | Acc] - end, [], Updates), - {noreply, start_timer(State#state{updates = Updates1}), hibernate}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #state{timer = TRef}) -> - emqx_misc:cancel_timer(TRef). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -safe_update_element(Key, Val) -> - try ets:update_element(?TAB, Key, {2, Val}) of - false -> - ets:insert_new(?TAB, {Key, Val}); - true -> true - catch - error:badarg -> - ?LOG(warning, "Failed to update ~0p to ~0p", [Key, Val]) - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_sup.erl b/_build/emqx/lib/emqx/src/emqx_sup.erl deleted file mode 100644 index c0aa3a2a84..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_sup.erl +++ /dev/null @@ -1,103 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_sup). - --behaviour(supervisor). - --include("types.hrl"). - --export([ start_link/0 - , start_child/1 - , start_child/2 - , stop_child/1 - ]). - --export([init/1]). - --type(startchild_ret() :: {ok, supervisor:child()} - | {ok, supervisor:child(), term()} - | {error, term()}). - --define(SUP, ?MODULE). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - --spec(start_link() -> startlink_ret()). -start_link() -> - supervisor:start_link({local, ?SUP}, ?MODULE, []). - --spec(start_child(supervisor:child_spec()) -> startchild_ret()). -start_child(ChildSpec) when is_map(ChildSpec) -> - supervisor:start_child(?SUP, ChildSpec). - --spec(start_child(module(), worker | supervisor) -> startchild_ret()). -start_child(Mod, Type) -> - start_child(child_spec(Mod, Type)). - --spec(stop_child(supervisor:child_id()) -> ok | {error, term()}). -stop_child(ChildId) -> - case supervisor:terminate_child(?SUP, ChildId) of - ok -> supervisor:delete_child(?SUP, ChildId); - Error -> Error - end. - -%%-------------------------------------------------------------------- -%% Supervisor callbacks -%%-------------------------------------------------------------------- - -init([]) -> - KernelSup = child_spec(emqx_kernel_sup, supervisor), - RouterSup = child_spec(emqx_router_sup, supervisor), - BrokerSup = child_spec(emqx_broker_sup, supervisor), - CMSup = child_spec(emqx_cm_sup, supervisor), - SysSup = child_spec(emqx_sys_sup, supervisor), - ModSup = child_spec(emqx_mod_sup, supervisor), - Childs = [KernelSup] ++ - [RouterSup || emqx_boot:is_enabled(router)] ++ - [BrokerSup || emqx_boot:is_enabled(broker)] ++ - [CMSup || emqx_boot:is_enabled(broker)] ++ - [SysSup] ++ [ModSup], - SupFlags = #{strategy => one_for_all, - intensity => 0, - period => 1 - }, - {ok, {SupFlags, Childs}}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -child_spec(Mod, supervisor) -> - #{id => Mod, - start => {Mod, start_link, []}, - restart => permanent, - shutdown => infinity, - type => supervisor, - modules => [Mod] - }; - -child_spec(Mod, worker) -> - #{id => Mod, - start => {Mod, start_link, []}, - restart => permanent, - shutdown => 15000, - type => worker, - modules => [Mod] - }. - diff --git a/_build/emqx/lib/emqx/src/emqx_sys.erl b/_build/emqx/lib/emqx/src/emqx_sys.erl deleted file mode 100644 index 38387b3ce2..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_sys.erl +++ /dev/null @@ -1,222 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_sys). - --behaviour(gen_server). - --include("emqx.hrl"). --include("types.hrl"). --include("logger.hrl"). - --logger_header("[SYS]"). - --export([ start_link/0 - , stop/0 - ]). - --export([ version/0 - , uptime/0 - , datetime/0 - , sysdescr/0 - , sys_interval/0 - , sys_heatbeat_interval/0 - ]). - --export([info/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - ]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --import(emqx_topic, [systop/1]). --import(emqx_misc, [start_timer/2]). - --record(state, - { start_time :: erlang:timestamp() - , heartbeat :: maybe(reference()) - , ticker :: maybe(reference()) - , version :: binary() - , sysdescr :: binary() - }). - --define(APP, emqx). --define(SYS, ?MODULE). - --define(INFO_KEYS, - [ version % Broker version - , uptime % Broker uptime - , datetime % Broker local datetime - , sysdescr % Broker description - ]). - -%%------------------------------------------------------------------------------ -%% APIs -%%------------------------------------------------------------------------------ - --spec(start_link() -> {ok, pid()} | ignore | {error, any()}). -start_link() -> - gen_server:start_link({local, ?SYS}, ?MODULE, [], []). - -stop() -> - gen_server:stop(?SYS). - -%% @doc Get sys version --spec(version() -> string()). -version() -> - {ok, Version} = application:get_key(?APP, vsn), Version. - -%% @doc Get sys description --spec(sysdescr() -> string()). -sysdescr() -> - {ok, Descr} = application:get_key(?APP, description), Descr. - -%% @doc Get sys uptime --spec(uptime() -> string()). -uptime() -> - gen_server:call(?SYS, uptime). - -%% @doc Get sys datetime --spec(datetime() -> string()). -datetime() -> - {{Y, M, D}, {H, MM, S}} = calendar:local_time(), - lists:flatten( - io_lib:format( - "~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Y, M, D, H, MM, S])). - -%% @doc Get sys interval --spec(sys_interval() -> pos_integer()). -sys_interval() -> - emqx:get_env(broker_sys_interval, 60000). - -%% @doc Get sys heatbeat interval --spec(sys_heatbeat_interval() -> pos_integer()). -sys_heatbeat_interval() -> - emqx:get_env(broker_sys_heartbeat, 30000). - -%% @doc Get sys info --spec(info() -> list(tuple())). -info() -> - [{version, version()}, - {sysdescr, sysdescr()}, - {uptime, uptime()}, - {datetime, datetime()}]. - -%%------------------------------------------------------------------------------ -%% gen_server callbacks -%%------------------------------------------------------------------------------ - -init([]) -> - State = #state{start_time = erlang:timestamp(), - version = iolist_to_binary(version()), - sysdescr = iolist_to_binary(sysdescr())}, - {ok, heartbeat(tick(State))}. - -heartbeat(State) -> - State#state{heartbeat = start_timer(sys_heatbeat_interval(), heartbeat)}. -tick(State) -> - State#state{ticker = start_timer(sys_interval(), tick)}. - -handle_call(uptime, _From, State) -> - {reply, uptime(State), State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({timeout, TRef, heartbeat}, State = #state{heartbeat = TRef}) -> - publish(uptime, iolist_to_binary(uptime(State))), - publish(datetime, iolist_to_binary(datetime())), - {noreply, heartbeat(State)}; - -handle_info({timeout, TRef, tick}, State = #state{ticker = TRef, version = Version, sysdescr = Descr}) -> - publish(version, Version), - publish(sysdescr, Descr), - publish(brokers, ekka_mnesia:running_nodes()), - publish(stats, emqx_stats:getstats()), - publish(metrics, emqx_metrics:all()), - {noreply, tick(State), hibernate}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #state{heartbeat = TRef1, ticker = TRef2}) -> - lists:foreach(fun emqx_misc:cancel_timer/1, [TRef1, TRef2]). - -%%----------------------------------------------------------------------------- -%% Internal functions -%%----------------------------------------------------------------------------- - -uptime(#state{start_time = Ts}) -> - Secs = timer:now_diff(erlang:timestamp(), Ts) div 1000000, - lists:flatten(uptime(seconds, Secs)). -uptime(seconds, Secs) when Secs < 60 -> - [integer_to_list(Secs), " seconds"]; -uptime(seconds, Secs) -> - [uptime(minutes, Secs div 60), integer_to_list(Secs rem 60), " seconds"]; -uptime(minutes, M) when M < 60 -> - [integer_to_list(M), " minutes, "]; -uptime(minutes, M) -> - [uptime(hours, M div 60), integer_to_list(M rem 60), " minutes, "]; -uptime(hours, H) when H < 24 -> - [integer_to_list(H), " hours, "]; -uptime(hours, H) -> - [uptime(days, H div 24), integer_to_list(H rem 24), " hours, "]; -uptime(days, D) -> - [integer_to_list(D), " days, "]. - -publish(uptime, Uptime) -> - safe_publish(systop(uptime), Uptime); -publish(datetime, Datetime) -> - safe_publish(systop(datetime), Datetime); -publish(version, Version) -> - safe_publish(systop(version), #{retain => true}, Version); -publish(sysdescr, Descr) -> - safe_publish(systop(sysdescr), #{retain => true}, Descr); -publish(brokers, Nodes) -> - Payload = string:join([atom_to_list(N) || N <- Nodes], ","), - safe_publish(<<"$SYS/brokers">>, #{retain => true}, Payload); -publish(stats, Stats) -> - [safe_publish(systop(lists:concat(['stats/', Stat])), integer_to_binary(Val)) - || {Stat, Val} <- Stats, is_atom(Stat), is_integer(Val)]; -publish(metrics, Metrics) -> - [safe_publish(systop(metric_topic(Name)), integer_to_binary(Val)) - || {Name, Val} <- Metrics, is_atom(Name), is_integer(Val)]. - -metric_topic(Name) -> - lists:concat(["metrics/", string:replace(atom_to_list(Name), ".", "/", all)]). - -safe_publish(Topic, Payload) -> - safe_publish(Topic, #{}, Payload). -safe_publish(Topic, Flags, Payload) -> - emqx_broker:safe_publish( - emqx_message:set_flags( - maps:merge(#{sys => true}, Flags), - emqx_message:make(?SYS, Topic, iolist_to_binary(Payload)))). diff --git a/_build/emqx/lib/emqx/src/emqx_sys_mon.erl b/_build/emqx/lib/emqx/src/emqx_sys_mon.erl deleted file mode 100644 index 0eabb1253f..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_sys_mon.erl +++ /dev/null @@ -1,194 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_sys_mon). - --behavior(gen_server). - --include("types.hrl"). --include("logger.hrl"). - --logger_header("[SYSMON]"). - --export([start_link/1]). - -%% compress unused warning --export([procinfo/1]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --type(option() :: {long_gc, non_neg_integer()} - | {long_schedule, non_neg_integer()} - | {large_heap, non_neg_integer()} - | {busy_port, boolean()} - | {busy_dist_port, boolean()}). - --define(SYSMON, ?MODULE). - -%% @doc Start the system monitor. --spec(start_link(list(option())) -> startlink_ret()). -start_link(Opts) -> - gen_server:start_link({local, ?SYSMON}, ?MODULE, [Opts], []). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Opts]) -> - erlang:system_monitor(self(), parse_opt(Opts)), - emqx_logger:set_proc_metadata(#{sysmon => true}), - - %% Monitor cluster partition event - ekka:monitor(partition, fun handle_partition_event/1), - - {ok, start_timer(#{timer => undefined, events => []})}. - -start_timer(State) -> - State#{timer := emqx_misc:start_timer(timer:seconds(2), reset)}. - -parse_opt(Opts) -> - parse_opt(Opts, []). -parse_opt([], Acc) -> - Acc; -parse_opt([{long_gc, 0}|Opts], Acc) -> - parse_opt(Opts, Acc); -parse_opt([{long_gc, Ms}|Opts], Acc) when is_integer(Ms) -> - parse_opt(Opts, [{long_gc, Ms}|Acc]); -parse_opt([{long_schedule, 0}|Opts], Acc) -> - parse_opt(Opts, Acc); -parse_opt([{long_schedule, Ms}|Opts], Acc) when is_integer(Ms) -> - parse_opt(Opts, [{long_schedule, Ms}|Acc]); -parse_opt([{large_heap, Size}|Opts], Acc) when is_integer(Size) -> - parse_opt(Opts, [{large_heap, Size}|Acc]); -parse_opt([{busy_port, true}|Opts], Acc) -> - parse_opt(Opts, [busy_port|Acc]); -parse_opt([{busy_port, false}|Opts], Acc) -> - parse_opt(Opts, Acc); -parse_opt([{busy_dist_port, true}|Opts], Acc) -> - parse_opt(Opts, [busy_dist_port|Acc]); -parse_opt([{busy_dist_port, false}|Opts], Acc) -> - parse_opt(Opts, Acc); -parse_opt([_Opt|Opts], Acc) -> - parse_opt(Opts, Acc). - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({monitor, Pid, long_gc, Info}, State) -> - suppress({long_gc, Pid}, - fun() -> - WarnMsg = io_lib:format("long_gc warning: pid = ~p, info: ~p", [Pid, Info]), - ?LOG(warning, "~s~n~p", [WarnMsg, procinfo(Pid)]), - safe_publish(long_gc, WarnMsg) - end, State); - -handle_info({monitor, Pid, long_schedule, Info}, State) when is_pid(Pid) -> - suppress({long_schedule, Pid}, - fun() -> - WarnMsg = io_lib:format("long_schedule warning: pid = ~p, info: ~p", [Pid, Info]), - ?LOG(warning, "~s~n~p", [WarnMsg, procinfo(Pid)]), - safe_publish(long_schedule, WarnMsg) - end, State); - -handle_info({monitor, Port, long_schedule, Info}, State) when is_port(Port) -> - suppress({long_schedule, Port}, - fun() -> - WarnMsg = io_lib:format("long_schedule warning: port = ~p, info: ~p", [Port, Info]), - ?LOG(warning, "~s~n~p", [WarnMsg, erlang:port_info(Port)]), - safe_publish(long_schedule, WarnMsg) - end, State); - -handle_info({monitor, Pid, large_heap, Info}, State) -> - suppress({large_heap, Pid}, - fun() -> - WarnMsg = io_lib:format("large_heap warning: pid = ~p, info: ~p", [Pid, Info]), - ?LOG(warning, "~s~n~p", [WarnMsg, procinfo(Pid)]), - safe_publish(large_heap, WarnMsg) - end, State); - -handle_info({monitor, SusPid, busy_port, Port}, State) -> - suppress({busy_port, Port}, - fun() -> - WarnMsg = io_lib:format("busy_port warning: suspid = ~p, port = ~p", [SusPid, Port]), - ?LOG(warning, "~s~n~p~n~p", [WarnMsg, procinfo(SusPid), erlang:port_info(Port)]), - safe_publish(busy_port, WarnMsg) - end, State); - -handle_info({monitor, SusPid, busy_dist_port, Port}, State) -> - suppress({busy_dist_port, Port}, - fun() -> - WarnMsg = io_lib:format("busy_dist_port warning: suspid = ~p, port = ~p", [SusPid, Port]), - ?LOG(warning, "~s~n~p~n~p", [WarnMsg, procinfo(SusPid), erlang:port_info(Port)]), - safe_publish(busy_dist_port, WarnMsg) - end, State); - -handle_info({timeout, _Ref, reset}, State) -> - {noreply, State#{events := []}, hibernate}; - -handle_info(Info, State) -> - ?LOG(error, "Unexpected Info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{timer := TRef}) -> - emqx_misc:cancel_timer(TRef). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal Functions -%%-------------------------------------------------------------------- - -handle_partition_event({partition, {occurred, Node}}) -> - alarm_handler:set_alarm({partitioned, Node}); -handle_partition_event({partition, {healed, _Node}}) -> - alarm_handler:clear_alarm(partitioned). - -suppress(Key, SuccFun, State = #{events := Events}) -> - case lists:member(Key, Events) of - true -> - {noreply, State}; - false -> - SuccFun(), - {noreply, State#{events := [Key|Events]}} - end. - -procinfo(Pid) -> - case {emqx_vm:get_process_info(Pid), emqx_vm:get_process_gc_info(Pid)} of - {undefined, _} -> undefined; - {_, undefined} -> undefined; - {Info, GcInfo} -> Info ++ GcInfo - end. - -safe_publish(Event, WarnMsg) -> - Topic = emqx_topic:systop(lists:concat(['sysmon/', Event])), - emqx_broker:safe_publish(sysmon_msg(Topic, iolist_to_binary(WarnMsg))). - -sysmon_msg(Topic, Payload) -> - Msg = emqx_message:make(?SYSMON, Topic, Payload), - emqx_message:set_flag(sys, Msg). diff --git a/_build/emqx/lib/emqx/src/emqx_sys_sup.erl b/_build/emqx/lib/emqx/src/emqx_sys_sup.erl deleted file mode 100644 index 9b6e46db61..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_sys_sup.erl +++ /dev/null @@ -1,52 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_sys_sup). - --behaviour(supervisor). - --export([start_link/0]). - --export([init/1]). - -start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, []). - -init([]) -> - Childs = [child_spec(emqx_sys), - child_spec(emqx_sys_mon, [config(sysmon)]), - child_spec(emqx_os_mon, [config(os_mon)]), - child_spec(emqx_vm_mon, [config(vm_mon)])], - {ok, {{one_for_one, 10, 100}, Childs}}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -child_spec(Mod) -> - child_spec(Mod, []). - -child_spec(Mod, Args) -> - #{id => Mod, - start => {Mod, start_link, Args}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [Mod] - }. - -config(Name) -> emqx:get_env(Name, []). - diff --git a/_build/emqx/lib/emqx/src/emqx_tables.erl b/_build/emqx/lib/emqx/src/emqx_tables.erl deleted file mode 100644 index 82ea7b042e..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_tables.erl +++ /dev/null @@ -1,65 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_tables). - --export([ new/1 - , new/2 - ]). - --export([ lookup_value/2 - , lookup_value/3 - ]). - --export([delete/1]). - -%% Create an ets table. --spec(new(atom()) -> ok). -new(Tab) -> - new(Tab, []). - -%% Create a named_table ets. --spec(new(atom(), list()) -> ok). -new(Tab, Opts) -> - case ets:info(Tab, name) of - undefined -> - _ = ets:new(Tab, lists:usort([named_table | Opts])), - ok; - Tab -> ok - end. - -%% KV lookup --spec(lookup_value(ets:tab(), term()) -> any()). -lookup_value(Tab, Key) -> - lookup_value(Tab, Key, undefined). - --spec(lookup_value(ets:tab(), term(), any()) -> any()). -lookup_value(Tab, Key, Def) -> - try ets:lookup_element(Tab, Key, 2) - catch - error:badarg -> Def - end. - -%% Delete the ets table. --spec(delete(ets:tab()) -> ok). -delete(Tab) -> - case ets:info(Tab, name) of - undefined -> ok; - Tab -> - ets:delete(Tab), - ok - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_topic.erl b/_build/emqx/lib/emqx/src/emqx_topic.erl deleted file mode 100644 index cda057f062..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_topic.erl +++ /dev/null @@ -1,221 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_topic). - -%% APIs --export([ match/2 - , validate/1 - , validate/2 - , levels/1 - , tokens/1 - , words/1 - , wildcard/1 - , join/1 - , prepend/2 - , feed_var/3 - , systop/1 - , parse/1 - , parse/2 - ]). - --export_type([ group/0 - , topic/0 - , word/0 - ]). - --type(group() :: binary()). --type(topic() :: binary()). --type(word() :: '' | '+' | '#' | binary()). --type(words() :: list(word())). - --define(MAX_TOPIC_LEN, 4096). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - -%% @doc Is wildcard topic? --spec(wildcard(topic() | words()) -> true | false). -wildcard(Topic) when is_binary(Topic) -> - wildcard(words(Topic)); -wildcard([]) -> - false; -wildcard(['#'|_]) -> - true; -wildcard(['+'|_]) -> - true; -wildcard([_H|T]) -> - wildcard(T). - -%% @doc Match Topic name with filter. --spec(match(Name, Filter) -> boolean() when - Name :: topic() | words(), - Filter :: topic() | words()). -match(<<$$, _/binary>>, <<$+, _/binary>>) -> - false; -match(<<$$, _/binary>>, <<$#, _/binary>>) -> - false; -match(Name, Filter) when is_binary(Name), is_binary(Filter) -> - match(words(Name), words(Filter)); -match([], []) -> - true; -match([H|T1], [H|T2]) -> - match(T1, T2); -match([_H|T1], ['+'|T2]) -> - match(T1, T2); -match(_, ['#']) -> - true; -match([_H1|_], [_H2|_]) -> - false; -match([_H1|_], []) -> - false; -match([], [_H|_T2]) -> - false. - -%% @doc Validate topic name or filter --spec(validate(topic() | {name | filter, topic()}) -> true). -validate(Topic) when is_binary(Topic) -> - validate(filter, Topic); -validate({Type, Topic}) when Type =:= name; Type =:= filter -> - validate(Type, Topic). - --spec(validate(name | filter, topic()) -> true). -validate(_, <<>>) -> - error(empty_topic); -validate(_, Topic) when is_binary(Topic) andalso (size(Topic) > ?MAX_TOPIC_LEN) -> - error(topic_too_long); -validate(filter, Topic) when is_binary(Topic) -> - validate2(words(Topic)); -validate(name, Topic) when is_binary(Topic) -> - Words = words(Topic), - validate2(Words) - andalso (not wildcard(Words)) - orelse error(topic_name_error). - -validate2([]) -> - true; -validate2(['#']) -> % end with '#' - true; -validate2(['#'|Words]) when length(Words) > 0 -> - error('topic_invalid_#'); -validate2([''|Words]) -> - validate2(Words); -validate2(['+'|Words]) -> - validate2(Words); -validate2([W|Words]) -> - validate3(W) andalso validate2(Words). - -validate3(<<>>) -> - true; -validate3(<>) when C == $#; C == $+; C == 0 -> - error('topic_invalid_char'); -validate3(<<_/utf8, Rest/binary>>) -> - validate3(Rest). - -%% @doc Prepend a topic prefix. -%% Ensured to have only one / between prefix and suffix. -prepend(undefined, W) -> bin(W); -prepend(<<>>, W) -> bin(W); -prepend(Parent0, W) -> - Parent = bin(Parent0), - case binary:last(Parent) of - $/ -> <>; - _ -> <> - end. - -bin('') -> <<>>; -bin('+') -> <<"+">>; -bin('#') -> <<"#">>; -bin(B) when is_binary(B) -> B; -bin(L) when is_list(L) -> list_to_binary(L). - --spec(levels(topic()) -> pos_integer()). -levels(Topic) when is_binary(Topic) -> - length(tokens(Topic)). - --compile({inline, [tokens/1]}). -%% @doc Split topic to tokens. --spec(tokens(topic()) -> list(binary())). -tokens(Topic) -> - binary:split(Topic, <<"/">>, [global]). - -%% @doc Split Topic Path to Words --spec(words(topic()) -> words()). -words(Topic) when is_binary(Topic) -> - [word(W) || W <- tokens(Topic)]. - -word(<<>>) -> ''; -word(<<"+">>) -> '+'; -word(<<"#">>) -> '#'; -word(Bin) -> Bin. - -%% @doc '$SYS' Topic. --spec(systop(atom()|string()|binary()) -> topic()). -systop(Name) when is_atom(Name); is_list(Name) -> - iolist_to_binary(lists:concat(["$SYS/brokers/", node(), "/", Name])); -systop(Name) when is_binary(Name) -> - iolist_to_binary(["$SYS/brokers/", atom_to_list(node()), "/", Name]). - --spec(feed_var(binary(), binary(), binary()) -> binary()). -feed_var(Var, Val, Topic) -> - feed_var(Var, Val, words(Topic), []). -feed_var(_Var, _Val, [], Acc) -> - join(lists:reverse(Acc)); -feed_var(Var, Val, [Var|Words], Acc) -> - feed_var(Var, Val, Words, [Val|Acc]); -feed_var(Var, Val, [W|Words], Acc) -> - feed_var(Var, Val, Words, [W|Acc]). - --spec(join(list(binary())) -> binary()). -join([]) -> - <<>>; -join([W]) -> - bin(W); -join(Words) -> - {_, Bin} = lists:foldr( - fun(W, {true, Tail}) -> - {false, <>}; - (W, {false, Tail}) -> - {false, <>} - end, {true, <<>>}, [bin(W) || W <- Words]), - Bin. - --spec(parse(topic() | {topic(), map()}) -> {topic(), #{share => binary()}}). -parse(TopicFilter) when is_binary(TopicFilter) -> - parse(TopicFilter, #{}); -parse({TopicFilter, Options}) when is_binary(TopicFilter) -> - parse(TopicFilter, Options). - --spec(parse(topic(), map()) -> {topic(), map()}). -parse(TopicFilter = <<"$queue/", _/binary>>, #{share := _Group}) -> - error({invalid_topic_filter, TopicFilter}); -parse(TopicFilter = <<"$share/", _/binary>>, #{share := _Group}) -> - error({invalid_topic_filter, TopicFilter}); -parse(<<"$queue/", TopicFilter/binary>>, Options) -> - parse(TopicFilter, Options#{share => <<"$queue">>}); -parse(TopicFilter = <<"$share/", Rest/binary>>, Options) -> - case binary:split(Rest, <<"/">>) of - [_Any] -> error({invalid_topic_filter, TopicFilter}); - [ShareName, Filter] -> - case binary:match(ShareName, [<<"+">>, <<"#">>]) of - nomatch -> parse(Filter, Options#{share => ShareName}); - _ -> error({invalid_topic_filter, TopicFilter}) - end - end; -parse(TopicFilter, Options) -> - {TopicFilter, Options}. - diff --git a/_build/emqx/lib/emqx/src/emqx_tracer.erl b/_build/emqx/lib/emqx/src/emqx_tracer.erl deleted file mode 100644 index befb02b963..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_tracer.erl +++ /dev/null @@ -1,155 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_tracer). - --include("emqx.hrl"). --include("logger.hrl"). - --logger_header("[Tracer]"). - -%% APIs --export([ trace/2 - , start_trace/3 - , lookup_traces/0 - , stop_trace/1 - ]). - --type(trace_who() :: {clientid | topic, binary() | list()}). - --define(TRACER, ?MODULE). --define(FORMAT, {emqx_logger_formatter, - #{template => - [time," [",level,"] ", - {clientid, - [{peername, - [clientid,"@",peername," "], - [clientid, " "]}], - [{peername, - [peername," "], - []}]}, - msg,"\n"]}}). --define(TOPIC_TRACE_ID(T), "trace_topic_"++T). --define(CLIENT_TRACE_ID(C), "trace_clientid_"++C). --define(TOPIC_TRACE(T), {topic,T}). --define(CLIENT_TRACE(C), {clientid,C}). - --define(is_log_level(L), - L =:= emergency orelse - L =:= alert orelse - L =:= critical orelse - L =:= error orelse - L =:= warning orelse - L =:= notice orelse - L =:= info orelse - L =:= debug). - --dialyzer({nowarn_function, [install_trace_handler/3]}). - -%%------------------------------------------------------------------------------ -%% APIs -%%------------------------------------------------------------------------------ -trace(publish, #message{topic = <<"$SYS/", _/binary>>}) -> - %% Do not trace '$SYS' publish - ignore; -trace(publish, #message{from = From, topic = Topic, payload = Payload}) - when is_binary(From); is_atom(From) -> - emqx_logger:info(#{topic => Topic, mfa => {?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY} }, "PUBLISH to ~s: ~0p", [Topic, Payload]). - -%% @doc Start to trace clientid or topic. --spec(start_trace(trace_who(), logger:level() | all, string()) -> ok | {error, term()}). -start_trace(Who, all, LogFile) -> - start_trace(Who, debug, LogFile); -start_trace(Who, Level, LogFile) -> - case ?is_log_level(Level) of - true -> - #{level := PrimaryLevel} = logger:get_primary_config(), - try logger:compare_levels(Level, PrimaryLevel) of - lt -> - {error, io_lib:format("Cannot trace at a log level (~s) lower than the primary log level (~s)", [Level, PrimaryLevel])}; - _GtOrEq -> - install_trace_handler(Who, Level, LogFile) - catch - _:Error -> - {error, Error} - end; - false -> {error, {invalid_log_level, Level}} - end. - -%% @doc Stop tracing clientid or topic. --spec(stop_trace(trace_who()) -> ok | {error, term()}). -stop_trace(Who) -> - uninstall_trance_handler(Who). - -%% @doc Lookup all traces --spec(lookup_traces() -> [{Who :: trace_who(), LogFile :: string()}]). -lookup_traces() -> - lists:foldl(fun filter_traces/2, [], emqx_logger:get_log_handlers()). - -install_trace_handler(Who, Level, LogFile) -> - case logger:add_handler(handler_id(Who), logger_disk_log_h, - #{level => Level, - formatter => ?FORMAT, - filesync_repeat_interval => no_repeat, - config => #{type => halt, file => LogFile}, - filter_default => stop, - filters => [{meta_key_filter, - {fun filter_by_meta_key/2, Who}}]}) - of - ok -> - ?LOG(info, "Start trace for ~p", [Who]); - {error, Reason} -> - ?LOG(error, "Start trace for ~p failed, error: ~p", [Who, Reason]), - {error, Reason} - end. - -uninstall_trance_handler(Who) -> - case logger:remove_handler(handler_id(Who)) of - ok -> - ?LOG(info, "Stop trace for ~p", [Who]); - {error, Reason} -> - ?LOG(error, "Stop trace for ~p failed, error: ~p", [Who, Reason]), - {error, Reason} - end. - -filter_traces({Id, Level, Dst}, Acc) -> - case atom_to_list(Id) of - ?TOPIC_TRACE_ID(T)-> - [{?TOPIC_TRACE(T), {Level,Dst}} | Acc]; - ?CLIENT_TRACE_ID(C) -> - [{?CLIENT_TRACE(C), {Level,Dst}} | Acc]; - _ -> Acc - end. - -handler_id(?TOPIC_TRACE(Topic)) -> - list_to_atom(?TOPIC_TRACE_ID(str(Topic))); -handler_id(?CLIENT_TRACE(ClientId)) -> - list_to_atom(?CLIENT_TRACE_ID(str(ClientId))). - -filter_by_meta_key(#{meta:=Meta}=LogEvent, {MetaKey, MetaValue}) -> - case maps:find(MetaKey, Meta) of - {ok, MetaValue} -> LogEvent; - {ok, Topic} when MetaKey =:= topic -> - case emqx_topic:match(Topic, MetaValue) of - true -> LogEvent; - false -> ignore - end; - _ -> ignore - end. - -str(Bin) when is_binary(Bin) -> binary_to_list(Bin); -str(Atom) when is_atom(Atom) -> atom_to_list(Atom); -str(Str) when is_list(Str) -> Str. diff --git a/_build/emqx/lib/emqx/src/emqx_trie.erl b/_build/emqx/lib/emqx/src/emqx_trie.erl deleted file mode 100644 index 4189c02708..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_trie.erl +++ /dev/null @@ -1,213 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_trie). - --include("emqx.hrl"). - -%% Mnesia bootstrap --export([mnesia/1]). - --boot_mnesia({mnesia, [boot]}). --copy_mnesia({mnesia, [copy]}). - -%% Trie APIs --export([ insert/1 - , match/1 - , lookup/1 - , delete/1 - ]). - --export([empty/0]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --type(triple() :: {root | binary(), emqx_topic:word(), binary()}). - -%% Mnesia tables --define(TRIE_TAB, emqx_trie). --define(TRIE_NODE_TAB, emqx_trie_node). - -%%-------------------------------------------------------------------- -%% Mnesia bootstrap -%%-------------------------------------------------------------------- - -%% @doc Create or replicate trie tables. --spec(mnesia(boot | copy) -> ok). -mnesia(boot) -> - %% Optimize storage - StoreProps = [{ets, [{read_concurrency, true}, - {write_concurrency, true}]}], - %% Trie table - ok = ekka_mnesia:create_table(?TRIE_TAB, [ - {ram_copies, [node()]}, - {record_name, trie}, - {attributes, record_info(fields, trie)}, - {storage_properties, StoreProps}]), - %% Trie node table - ok = ekka_mnesia:create_table(?TRIE_NODE_TAB, [ - {ram_copies, [node()]}, - {record_name, trie_node}, - {attributes, record_info(fields, trie_node)}, - {storage_properties, StoreProps}]); - -mnesia(copy) -> - %% Copy trie table - ok = ekka_mnesia:copy_table(?TRIE_TAB), - %% Copy trie_node table - ok = ekka_mnesia:copy_table(?TRIE_NODE_TAB). - -%%-------------------------------------------------------------------- -%% Trie APIs -%%-------------------------------------------------------------------- - -%% @doc Insert a topic filter into the trie. --spec(insert(emqx_topic:topic()) -> ok). -insert(Topic) when is_binary(Topic) -> - case mnesia:wread({?TRIE_NODE_TAB, Topic}) of - [#trie_node{topic = Topic}] -> - ok; - [TrieNode = #trie_node{topic = undefined}] -> - write_trie_node(TrieNode#trie_node{topic = Topic}); - [] -> - %% Add trie path - ok = lists:foreach(fun add_path/1, triples(Topic)), - %% Add last node - write_trie_node(#trie_node{node_id = Topic, topic = Topic}) - end. - -%% @doc Find trie nodes that match the topic name. --spec(match(emqx_topic:topic()) -> list(emqx_topic:topic())). -match(Topic) when is_binary(Topic) -> - TrieNodes = match_node(root, emqx_topic:words(Topic)), - [Name || #trie_node{topic = Name} <- TrieNodes, Name =/= undefined]. - -%% @doc Lookup a trie node. --spec(lookup(NodeId :: binary()) -> [#trie_node{}]). -lookup(NodeId) -> - mnesia:read(?TRIE_NODE_TAB, NodeId). - -%% @doc Delete a topic filter from the trie. --spec(delete(emqx_topic:topic()) -> ok). -delete(Topic) when is_binary(Topic) -> - case mnesia:wread({?TRIE_NODE_TAB, Topic}) of - [#trie_node{edge_count = 0}] -> - ok = mnesia:delete({?TRIE_NODE_TAB, Topic}), - delete_path(lists:reverse(triples(Topic))); - [TrieNode] -> - write_trie_node(TrieNode#trie_node{topic = undefined}); - [] -> ok - end. - -%% @doc Is the trie empty? --spec(empty() -> boolean()). -empty() -> - ets:info(?TRIE_TAB, size) == 0. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -%% @doc Topic to triples. --spec(triples(emqx_topic:topic()) -> list(triple())). -triples(Topic) when is_binary(Topic) -> - triples(emqx_topic:words(Topic), root, []). - -triples([], _Parent, Acc) -> - lists:reverse(Acc); -triples([W|Words], Parent, Acc) -> - Node = join(Parent, W), - triples(Words, Node, [{Parent, W, Node}|Acc]). - -join(root, W) -> - emqx_topic:join([W]); -join(Parent, W) -> - emqx_topic:join([Parent, W]). - -%% @private -%% @doc Add a path to the trie. -add_path({Node, Word, Child}) -> - Edge = #trie_edge{node_id = Node, word = Word}, - case mnesia:wread({?TRIE_NODE_TAB, Node}) of - [TrieNode = #trie_node{edge_count = Count}] -> - case mnesia:wread({?TRIE_TAB, Edge}) of - [] -> - ok = write_trie_node(TrieNode#trie_node{edge_count = Count + 1}), - write_trie(#trie{edge = Edge, node_id = Child}); - [_] -> ok - end; - [] -> - ok = write_trie_node(#trie_node{node_id = Node, edge_count = 1}), - write_trie(#trie{edge = Edge, node_id = Child}) - end. - -%% @private -%% @doc Match node with word or '+'. -match_node(root, [NodeId = <<$$, _/binary>>|Words]) -> - match_node(NodeId, Words, []); - -match_node(NodeId, Words) -> - match_node(NodeId, Words, []). - -match_node(NodeId, [], ResAcc) -> - mnesia:read(?TRIE_NODE_TAB, NodeId) ++ 'match_#'(NodeId, ResAcc); - -match_node(NodeId, [W|Words], ResAcc) -> - lists:foldl(fun(WArg, Acc) -> - case mnesia:read(?TRIE_TAB, #trie_edge{node_id = NodeId, word = WArg}) of - [#trie{node_id = ChildId}] -> match_node(ChildId, Words, Acc); - [] -> Acc - end - end, 'match_#'(NodeId, ResAcc), [W, '+']). - -%% @private -%% @doc Match node with '#'. -'match_#'(NodeId, ResAcc) -> - case mnesia:read(?TRIE_TAB, #trie_edge{node_id = NodeId, word = '#'}) of - [#trie{node_id = ChildId}] -> - mnesia:read(?TRIE_NODE_TAB, ChildId) ++ ResAcc; - [] -> ResAcc - end. - -%% @private -%% @doc Delete paths from the trie. -delete_path([]) -> - ok; -delete_path([{NodeId, Word, _} | RestPath]) -> - ok = mnesia:delete({?TRIE_TAB, #trie_edge{node_id = NodeId, word = Word}}), - case mnesia:wread({?TRIE_NODE_TAB, NodeId}) of - [#trie_node{edge_count = 1, topic = undefined}] -> - ok = mnesia:delete({?TRIE_NODE_TAB, NodeId}), - delete_path(RestPath); - [TrieNode = #trie_node{edge_count = 1, topic = _}] -> - write_trie_node(TrieNode#trie_node{edge_count = 0}); - [TrieNode = #trie_node{edge_count = C}] -> - write_trie_node(TrieNode#trie_node{edge_count = C-1}); - [] -> - mnesia:abort({node_not_found, NodeId}) - end. - -%% @private -write_trie(Trie) -> - mnesia:write(?TRIE_TAB, Trie, write). - -%% @private -write_trie_node(TrieNode) -> - mnesia:write(?TRIE_NODE_TAB, TrieNode, write). - diff --git a/_build/emqx/lib/emqx/src/emqx_types.erl b/_build/emqx/lib/emqx/src/emqx_types.erl deleted file mode 100644 index 718b757a5f..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_types.erl +++ /dev/null @@ -1,209 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_types). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("types.hrl"). - --export_type([ ver/0 - , qos/0 - , qos_name/0 - ]). - --export_type([ zone/0 - , pubsub/0 - , topic/0 - , subid/0 - ]). - --export_type([ socktype/0 - , sockstate/0 - , conninfo/0 - , clientinfo/0 - , clientid/0 - , username/0 - , password/0 - , peerhost/0 - , peername/0 - , protocol/0 - ]). - --export_type([ connack/0 - , subopts/0 - , reason_code/0 - , alias_id/0 - , topic_aliases/0 - , properties/0 - ]). - --export_type([ packet_id/0 - , packet_type/0 - , packet/0 - ]). - --export_type([ subscription/0 - , subscriber/0 - , topic_filters/0 - ]). - --export_type([ payload/0 - , message/0 - , flag/0 - , flags/0 - , headers/0 - ]). - --export_type([ deliver/0 - , delivery/0 - , publish_result/0 - , deliver_result/0 - ]). - --export_type([ route/0 - , route_entry/0 - ]). - --export_type([ alarm/0 - , plugin/0 - , banned/0 - , command/0 - ]). - --export_type([ caps/0 - , attrs/0 - , infos/0 - , stats/0 - ]). - --export_type([oom_policy/0]). - --type(ver() :: ?MQTT_PROTO_V3 - | ?MQTT_PROTO_V4 - | ?MQTT_PROTO_V5 - | non_neg_integer()). - --type(qos() :: ?QOS_0 | ?QOS_1 | ?QOS_2). --type(qos_name() :: qos0 | at_most_once | - qos1 | at_least_once | - qos2 | exactly_once). - --type(zone() :: emqx_zone:zone()). --type(pubsub() :: publish | subscribe). --type(topic() :: emqx_topic:topic()). --type(subid() :: binary() | atom()). - --type(socktype() :: tcp | udp | ssl | proxy | atom()). --type(sockstate() :: idle | running | blocked | closed). --type(conninfo() :: #{socktype := socktype(), - sockname := peername(), - peername := peername(), - peercert := nossl | undefined | esockd_peercert:peercert(), - conn_mod := module(), - proto_name := binary(), - proto_ver := ver(), - clean_start := boolean(), - clientid := clientid(), - username := username(), - conn_props := properties(), - connected := boolean(), - connected_at := non_neg_integer(), - keepalive := 0..16#FFFF, - receive_maximum := non_neg_integer(), - expiry_interval := non_neg_integer(), - atom() => term() - }). --type(clientinfo() :: #{zone := zone(), - protocol := protocol(), - peerhost := peerhost(), - sockport := non_neg_integer(), - clientid := clientid(), - username := username(), - is_bridge := boolean(), - is_superuser := boolean(), - mountpoint := maybe(binary()), - ws_cookie => maybe(list()), - password => maybe(binary()), - auth_result => auth_result(), - anonymous => boolean(), - cn => binary(), - dn => binary(), - atom() => term() - }). --type(clientid() :: binary()|atom()). --type(username() :: maybe(binary())). --type(password() :: maybe(binary())). --type(peerhost() :: inet:ip_address()). --type(peername() :: {inet:ip_address(), inet:port_number()}). --type(protocol() :: mqtt | 'mqtt-sn' | coap | lwm2m | stomp | none | atom()). --type(auth_result() :: success - | client_identifier_not_valid - | bad_username_or_password - | bad_clientid_or_password - | not_authorized - | server_unavailable - | server_busy - | banned - | bad_authentication_method). - --type(packet_type() :: ?RESERVED..?AUTH). --type(connack() :: ?CONNACK_ACCEPT..?CONNACK_AUTH). --type(subopts() :: #{rh := 0 | 1 | 2, - rap := 0 | 1, - nl := 0 | 1, - qos := qos(), - share => binary(), - atom() => term() - }). --type(reason_code() :: 0..16#FF). --type(packet_id() :: 1..16#FFFF). --type(alias_id() :: 0..16#FFFF). --type(topic_aliases() :: #{inbound => maybe(map()), - outbound => maybe(map())}). --type(properties() :: #{atom() => term()}). --type(topic_filters() :: list({topic(), subopts()})). --type(packet() :: #mqtt_packet{}). - --type(subscription() :: #subscription{}). --type(subscriber() :: {pid(), subid()}). --type(payload() :: binary() | iodata()). --type(message() :: #message{}). --type(flag() :: atom()). --type(flags() :: #{flag() := boolean()}). --type(headers() :: map()). --type(banned() :: #banned{}). --type(deliver() :: {deliver, topic(), message()}). --type(delivery() :: #delivery{}). --type(deliver_result() :: ok | {error, term()}). --type(publish_result() :: [{node(), topic(), deliver_result()} | - {share, topic(), deliver_result()}]). --type(route() :: #route{}). --type(sub_group() :: tuple() | binary()). --type(route_entry() :: {topic(), node()} | {topic, sub_group()}). --type(alarm() :: #alarm{}). --type(plugin() :: #plugin{}). --type(command() :: #command{}). - --type(caps() :: emqx_mqtt_caps:caps()). --type(attrs() :: #{atom() => term()}). --type(infos() :: #{atom() => term()}). --type(stats() :: [{atom(), term()}]). - --type(oom_policy() :: #{message_queue_len => non_neg_integer(), - max_heap_size => non_neg_integer() - }). - diff --git a/_build/emqx/lib/emqx/src/emqx_vm.erl b/_build/emqx/lib/emqx/src/emqx_vm.erl deleted file mode 100644 index 539b8b91b7..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_vm.erl +++ /dev/null @@ -1,471 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_vm). - --export([ schedulers/0 - , scheduler_usage/1 - , system_info_keys/0 - , get_system_info/0 - , get_system_info/1 - , get_memory/0 - , mem_info/0 - , loads/0 - ]). - --export([ process_info_keys/0 - , get_process_info/0 - , get_process_info/1 - , process_gc_info_keys/0 - , get_process_gc_info/0 - , get_process_gc_info/1 - , get_process_group_leader_info/1 - , get_process_limit/0 - ]). - --export([ get_ets_list/0 - , get_ets_info/0 - , get_ets_info/1 - , get_ets_object/0 - , get_ets_object/1 - ]). - --export([ get_port_types/0 - , get_port_info/0 - , get_port_info/1 - ]). - --export([cpu_util/0]). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - --define(UTIL_ALLOCATORS, [temp_alloc, - eheap_alloc, - binary_alloc, - ets_alloc, - driver_alloc, - sl_alloc, - ll_alloc, - fix_alloc, - std_alloc - ]). - --define(PROCESS_INFO_KEYS, [initial_call, - current_function, - registered_name, - status, - message_queue_len, - group_leader, - priority, - trap_exit, - reductions, - %%binary, - last_calls, - catchlevel, - trace, - suspending, - sequential_trace_token, - error_handler - ]). - --define(PROCESS_GC_KEYS, [memory, - total_heap_size, - heap_size, - stack_size, - min_heap_size - ]). - --define(SYSTEM_INFO_KEYS, [allocated_areas, - allocator, - alloc_util_allocators, - build_type, - check_io, - compat_rel, - creation, - debug_compiled, - dist, - dist_ctrl, - driver_version, - elib_malloc, - dist_buf_busy_limit, - %fullsweep_after, % included in garbage_collection - garbage_collection, - %global_heaps_size, % deprecated - heap_sizes, - heap_type, - info, - kernel_poll, - loaded, - logical_processors, - logical_processors_available, - logical_processors_online, - machine, - %min_heap_size, % included in garbage_collection - %min_bin_vheap_size, % included in garbage_collection - modified_timing_level, - multi_scheduling, - multi_scheduling_blockers, - otp_release, - port_count, - process_count, - process_limit, - scheduler_bind_type, - scheduler_bindings, - scheduler_id, - schedulers, - schedulers_online, - smp_support, - system_version, - system_architecture, - threads, - thread_pool_size, - trace_control_word, - update_cpu_info, - version, - wordsize - ]). - --define(SOCKET_OPTS, [active, - broadcast, - buffer, - delay_send, - dontroute, - exit_on_close, - header, - high_watermark, - ipv6_v6only, - keepalive, - linger, - low_watermark, - mode, - nodelay, - packet, - packet_size, - priority, - read_packets, - recbuf, - reuseaddr, - send_timeout, - send_timeout_close, - sndbuf, - tos - ]). - -schedulers() -> - erlang:system_info(schedulers). - -loads() -> - [{load1, ftos(avg1()/256)}, - {load5, ftos(avg5()/256)}, - {load15, ftos(avg15()/256)} - ]. - -system_info_keys() -> ?SYSTEM_INFO_KEYS. - -get_system_info() -> - [{Key, format_system_info(Key, get_system_info(Key))} || Key <- ?SYSTEM_INFO_KEYS]. - -get_system_info(Key) -> - try erlang:system_info(Key) catch error:badarg-> undefined end. - -format_system_info(allocated_areas, List) -> - [convert_allocated_areas(Value) || Value <- List]; -format_system_info(allocator, {_,_,_,List}) -> - List; -format_system_info(dist_ctrl, List) -> - lists:map(fun({Node, Socket}) -> - {ok, Stats} = inet:getstat(Socket), {Node, Stats} - end, List); -format_system_info(driver_version, Value) -> - list_to_binary(Value); -format_system_info(machine, Value) -> - list_to_binary(Value); -format_system_info(otp_release, Value) -> - list_to_binary(Value); -format_system_info(scheduler_bindings, Value) -> - tuple_to_list(Value); -format_system_info(system_version, Value) -> - list_to_binary(Value); -format_system_info(system_architecture, Value) -> - list_to_binary(Value); -format_system_info(version, Value) -> - list_to_binary(Value); -format_system_info(_, Value) -> - Value. - -convert_allocated_areas({Key, Value1, Value2}) -> - {Key, [Value1, Value2]}; -convert_allocated_areas({Key, Value}) -> - {Key, Value}. - -mem_info() -> - Dataset = memsup:get_system_memory_data(), - Total = proplists:get_value(total_memory, Dataset), - Free = proplists:get_value(free_memory, Dataset), - [{total_memory, Total}, {used_memory, Total - Free}]. - -ftos(F) -> - S = io_lib:format("~.2f", [F]), S. - -%%%% erlang vm scheduler_usage fun copied from recon -scheduler_usage(Interval) when is_integer(Interval) -> - %% We start and stop the scheduler_wall_time system flag - %% if it wasn't in place already. Usually setting the flag - %% should have a CPU impact(make it higher) only when under low usage. - FormerFlag = erlang:system_flag(scheduler_wall_time, true), - First = erlang:statistics(scheduler_wall_time), - timer:sleep(Interval), - Last = erlang:statistics(scheduler_wall_time), - erlang:system_flag(scheduler_wall_time, FormerFlag), - scheduler_usage_diff(First, Last). - -scheduler_usage_diff(First, Last) -> - lists:map(fun({{I, A0, T0},{I, A1, T1}}) -> - {I, (A1 - A0)/(T1 - T0)} - end, lists:zip(lists:sort(First), lists:sort(Last))). - -get_memory()-> - [{Key, get_memory(Key, current)} || Key <- [used, allocated, unused, usage]] ++ erlang:memory(). - -get_memory(used, Keyword) -> - lists:sum(lists:map(fun({_, Prop}) -> - container_size(Prop, Keyword, blocks_size) - end, util_alloc())); -get_memory(allocated, Keyword) -> - lists:sum(lists:map(fun({_, Prop})-> - container_size(Prop, Keyword, carriers_size) - end, util_alloc())); -get_memory(unused, Keyword) -> - get_memory(allocated, Keyword) - get_memory(used, Keyword); -get_memory(usage, Keyword) -> - get_memory(used, Keyword) / get_memory(allocated, Keyword). - -util_alloc()-> - alloc(?UTIL_ALLOCATORS). - -alloc()-> - {_Mem, Allocs} = snapshot_int(), - Allocs. -alloc(Type) -> - [{{T, Instance}, Props} || {{T, Instance}, Props} <- alloc(), lists:member(T, Type)]. - -snapshot_int() -> - {erlang:memory(), allocators()}. - -allocators() -> - UtilAllocators = erlang:system_info(alloc_util_allocators), - Allocators = [sys_alloc, mseg_alloc|UtilAllocators], - [{{A, N},lists:sort(proplists:delete(versions, Props))} || - A <- Allocators, Allocs <- [erlang:system_info({allocator, A})], - Allocs =/= false, {_, N, Props} <- Allocs]. - -container_size(Prop, Keyword, Container) -> - Sbcs = container_value(Prop, Keyword, sbcs, Container), - Mbcs = container_value(Prop, Keyword, mbcs, Container), - Sbcs+Mbcs. - -container_value(Prop, Keyword, Type, Container) when is_atom(Keyword)-> - container_value(Prop, 2, Type, Container); -container_value(Props, Pos, mbcs = Type, Container) when is_integer(Pos)-> - Pool = case proplists:get_value(mbcs_pool, Props) of - PoolProps when PoolProps =/= undefined -> - element(Pos, lists:keyfind(Container, 1, PoolProps)); - _ -> - 0 - end, - TypeProps = proplists:get_value(Type, Props), - Pool + element(Pos, lists:keyfind(Container, 1, TypeProps)); - -container_value(Props, Pos, Type, Container) -> - TypeProps = proplists:get_value(Type, Props), - element(Pos, lists:keyfind(Container, 1, TypeProps)). - -process_info_keys() -> - ?PROCESS_INFO_KEYS. - -get_process_info() -> - get_process_info(self()). -get_process_info(Pid) when is_pid(Pid) -> - process_info(Pid, ?PROCESS_INFO_KEYS). - -process_gc_info_keys() -> - ?PROCESS_GC_KEYS. - -get_process_gc_info() -> - get_process_gc_info(self()). -get_process_gc_info(Pid) when is_pid(Pid) -> - process_info(Pid, ?PROCESS_GC_KEYS). - -get_process_group_leader_info(LeaderPid) when is_pid(LeaderPid) -> - [{Key, Value}|| {Key, Value} <- process_info(LeaderPid), lists:member(Key, ?PROCESS_INFO_KEYS)]. - -get_process_limit() -> - erlang:system_info(process_limit). - -get_ets_list() -> - ets:all(). - -get_ets_info() -> - [get_ets_info(Tab) || Tab <- ets:all()]. - -get_ets_info(Tab) -> - case ets:info(Tab) of - undefined -> - []; - Entries when is_list(Entries) -> - mapping(Entries) - end. - -get_ets_object() -> - [{Tab, get_ets_object(Tab)} || Tab <- ets:all()]. - -get_ets_object(Tab) -> - TabInfo = ets:info(Tab), - Size = proplists:get_value(size, TabInfo), - NameTab = proplists:get_value(named_table, TabInfo), - if (Size == 0) or (NameTab == false) -> - []; - true -> - ets:tab2list(Tab) - end. - -get_port_types() -> - lists:usort(fun({KA, VA},{KB, VB})-> {VA, KB} >{VB, KA} end, - ports_type_count([Type || {_Port, Type} <- ports_type_list()])). - -get_port_info() -> - [get_port_info(Port) ||Port <- erlang:ports()]. - -get_port_info(PortTerm) -> - Port = transform_port(PortTerm), - [port_info(Port, Type) || Type <- [meta, signals, io, memory_used, specific]]. - -port_info(Port, meta) -> - {meta, List} = port_info_type(Port, meta, [id, name, os_pid]), - case port_info(Port, registered_name) of - [] -> {meta, List}; - Name -> {meta, [Name | List]} - end; - -port_info(PortTerm, signals) -> - port_info_type(PortTerm, signals, [connected, links, monitors]); - -port_info(PortTerm, io) -> - port_info_type(PortTerm, io, [input, output]); - -port_info(PortTerm, memory_used) -> - port_info_type(PortTerm, memory_used, [memory, queue_size]); - -port_info(PortTerm, specific) -> - Port = transform_port(PortTerm), - Props = case erlang:port_info(Port, name) of - {_, Type} when Type =:= "udp_inet"; - Type =:= "tcp_inet"; - Type =:= "sctp_inet" -> - try inet:getstat(Port) of - {ok, Stats} -> [{statistics, Stats}]; - {error, _} -> [] - catch - _Error:_Reason -> [] - end ++ - try inet:peername(Port) of - {ok, Peer} -> [{peername, Peer}]; - _ -> [] - catch - _Error:_Reason -> [] - end ++ - try inet:sockname(Port) of - {ok, Local} -> [{sockname, Local}]; - {error, _} -> [] - catch - _Error:_Reason -> [] - end ++ - try inet:getopts(Port, ?SOCKET_OPTS ) of - {ok, Opts} -> [{options, Opts}]; - {error, _} -> [] - catch - _Error:_Reason -> [] - end; - {_, "efile"} -> - []; - _ -> - [] - end, - {specific, Props}; -port_info(PortTerm, Key) when is_atom(Key) -> - Port = transform_port(PortTerm), - erlang:port_info(Port, Key). - -port_info_type(PortTerm, Type, Keys) -> - Port = transform_port(PortTerm), - {Type, [erlang:port_info(Port, Key) || Key <- Keys]}. - -transform_port(Port) when is_port(Port) -> Port; -transform_port("#Port<0." ++ Id) -> - N = list_to_integer(lists:sublist(Id, length(Id) - 1)), - transform_port(N); -transform_port(N) when is_integer(N) -> - Name = iolist_to_binary(atom_to_list(node())), - NameLen = iolist_size(Name), - Vsn = binary:last(term_to_binary(self())), - Bin = <<131, 102, 100, NameLen:2/unit:8, Name:NameLen/binary, N:4/unit:8, Vsn:8>>, - binary_to_term(Bin). - -ports_type_list() -> - [{Port, PortType} || Port <- erlang:ports(), - {_, PortType} <- [erlang:port_info(Port, name)]]. - -ports_type_count(Types) -> - DictTypes = lists:foldl(fun(Type, Acc)-> - dict:update_counter(Type, 1, Acc) - end, dict:new(), Types), - dict:to_list(DictTypes). - -mapping(Entries) -> - mapping(Entries, []). -mapping([], Acc) -> Acc; -mapping([{owner, V}|Entries], Acc) when is_pid(V) -> - OwnerInfo = process_info(V), - Owner = proplists:get_value(registered_name, OwnerInfo, undefined), - mapping(Entries, [{owner, Owner}|Acc]); -mapping([{Key, Value}|Entries], Acc) -> - mapping(Entries, [{Key, Value}|Acc]). - -avg1() -> - compat_windows(fun cpu_sup:avg1/0). - -avg5() -> - compat_windows(fun cpu_sup:avg5/0). - -avg15() -> - compat_windows(fun cpu_sup:avg15/0). - -cpu_util() -> - compat_windows(fun cpu_sup:util/0). - -compat_windows(Fun) -> - case os:type() of - {win32, nt} -> 0; - _Type -> - case catch Fun() of - Val when is_number(Val) -> Val; - _Error -> 0 - end - end. - diff --git a/_build/emqx/lib/emqx/src/emqx_vm_mon.erl b/_build/emqx/lib/emqx/src/emqx_vm_mon.erl deleted file mode 100644 index b4d1c60085..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_vm_mon.erl +++ /dev/null @@ -1,146 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_vm_mon). - --behaviour(gen_server). - --include("logger.hrl"). - -%% APIs --export([start_link/1]). - --export([ get_check_interval/0 - , set_check_interval/1 - , get_process_high_watermark/0 - , set_process_high_watermark/1 - , get_process_low_watermark/0 - , set_process_low_watermark/1 - ]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --define(VM_MON, ?MODULE). - -start_link(Opts) -> - gen_server:start_link({local, ?VM_MON}, ?MODULE, [Opts], []). - -%%-------------------------------------------------------------------- -%% API -%%-------------------------------------------------------------------- - -get_check_interval() -> - call(get_check_interval). - -set_check_interval(Seconds) -> - call({set_check_interval, Seconds}). - -get_process_high_watermark() -> - call(get_process_high_watermark). - -set_process_high_watermark(Float) -> - call({set_process_high_watermark, Float}). - -get_process_low_watermark() -> - call(get_process_low_watermark). - -set_process_low_watermark(Float) -> - call({set_process_low_watermark, Float}). - -call(Req) -> - gen_server:call(?VM_MON, Req, infinity). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([Opts]) -> - {ok, ensure_check_timer(#{check_interval => proplists:get_value(check_interval, Opts, 30), - process_high_watermark => proplists:get_value(process_high_watermark, Opts, 0.70), - process_low_watermark => proplists:get_value(process_low_watermark, Opts, 0.50), - timer => undefined, - is_process_alarm_set => false})}. - -handle_call(get_check_interval, _From, State) -> - {reply, maps:get(check_interval, State, undefined), State}; - -handle_call({set_check_interval, Seconds}, _From, State) -> - {reply, ok, State#{check_interval := Seconds}}; - -handle_call(get_process_high_watermark, _From, State) -> - {reply, maps:get(process_high_watermark, State, undefined), State}; - -handle_call({set_process_high_watermark, Float}, _From, State) -> - {reply, ok, State#{process_high_watermark := Float}}; - -handle_call(get_process_low_watermark, _From, State) -> - {reply, maps:get(process_low_watermark, State, undefined), State}; - -handle_call({set_process_low_watermark, Float}, _From, State) -> - {reply, ok, State#{process_low_watermark := Float}}; - -handle_call(Req, _From, State) -> - ?LOG(error, "[VM_MON] Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "[VM_MON] Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info({timeout, Timer, check}, - State = #{timer := Timer, - process_high_watermark := ProcHighWatermark, - process_low_watermark := ProcLowWatermark, - is_process_alarm_set := IsProcessAlarmSet}) -> - ProcessCount = erlang:system_info(process_count), - NState = case ProcessCount / erlang:system_info(process_limit) of - Percent when Percent >= ProcHighWatermark -> - alarm_handler:set_alarm({too_many_processes, ProcessCount}), - State#{is_process_alarm_set := true}; - Percent when Percent < ProcLowWatermark -> - case IsProcessAlarmSet of - true -> alarm_handler:clear_alarm(too_many_processes); - false -> ok - end, - State#{is_process_alarm_set := false}; - _Precent -> State - end, - {noreply, ensure_check_timer(NState)}; - -handle_info(Info, State) -> - ?LOG(error, "[VM_MON] Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, #{timer := Timer}) -> - emqx_misc:cancel_timer(Timer). - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -ensure_check_timer(State = #{check_interval := Interval}) -> - State#{timer := emqx_misc:start_timer(timer:seconds(Interval), check)}. - diff --git a/_build/emqx/lib/emqx/src/emqx_ws_connection.erl b/_build/emqx/lib/emqx/src/emqx_ws_connection.erl deleted file mode 100644 index 25eb8ff6ca..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_ws_connection.erl +++ /dev/null @@ -1,667 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% MQTT/WS|WSS Connection --module(emqx_ws_connection). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[MQTT/WS]"). - --ifdef(TEST). --compile(export_all). --compile(nowarn_export_all). --endif. - -%% API --export([ info/1 - , stats/1 - ]). - --export([call/2]). - -%% WebSocket callbacks --export([ init/2 - , websocket_init/1 - , websocket_handle/2 - , websocket_info/2 - , websocket_close/2 - , terminate/3 - ]). - -%% Export for CT --export([set_field/3]). - --import(emqx_misc, - [ maybe_apply/2 - , start_timer/2 - ]). - --record(state, { - %% Peername of the ws connection - peername :: emqx_types:peername(), - %% Sockname of the ws connection - sockname :: emqx_types:peername(), - %% Sock state - sockstate :: emqx_types:sockstate(), - %% Simulate the active_n opt - active_n :: pos_integer(), - %% Limiter - limiter :: maybe(emqx_limiter:limiter()), - %% Limit Timer - limit_timer :: maybe(reference()), - %% Parse State - parse_state :: emqx_frame:parse_state(), - %% Serialize Fun - serialize :: emqx_frame:serialize_fun(), - %% Channel - channel :: emqx_channel:channel(), - %% GC State - gc_state :: maybe(emqx_gc:gc_state()), - %% Postponed Packets|Cmds|Events - postponed :: list(emqx_types:packet()|ws_cmd()|tuple()), - %% Stats Timer - stats_timer :: disabled | maybe(reference()), - %% Idle Timeout - idle_timeout :: timeout(), - %% Idle Timer - idle_timer :: maybe(reference()) - }). - --type(state() :: #state{}). - --type(ws_cmd() :: {active, boolean()}|close). - --define(ACTIVE_N, 100). --define(INFO_KEYS, [socktype, peername, sockname, sockstate, active_n]). --define(SOCK_STATS, [recv_oct, recv_cnt, send_oct, send_cnt]). --define(CONN_STATS, [recv_pkt, recv_msg, send_pkt, send_msg]). - --define(ENABLED(X), (X =/= undefined)). - --dialyzer({no_match, [info/2]}). --dialyzer({nowarn_function, [websocket_init/1]}). - -%%-------------------------------------------------------------------- -%% Info, Stats -%%-------------------------------------------------------------------- - --spec(info(pid()|state()) -> emqx_types:infos()). -info(WsPid) when is_pid(WsPid) -> - call(WsPid, info); -info(State = #state{channel = Channel}) -> - ChanInfo = emqx_channel:info(Channel), - SockInfo = maps:from_list( - info(?INFO_KEYS, State)), - ChanInfo#{sockinfo => SockInfo}. - -info(Keys, State) when is_list(Keys) -> - [{Key, info(Key, State)} || Key <- Keys]; -info(socktype, _State) -> ws; -info(peername, #state{peername = Peername}) -> - Peername; -info(sockname, #state{sockname = Sockname}) -> - Sockname; -info(sockstate, #state{sockstate = SockSt}) -> - SockSt; -info(active_n, #state{active_n = ActiveN}) -> - ActiveN; -info(limiter, #state{limiter = Limiter}) -> - maybe_apply(fun emqx_limiter:info/1, Limiter); -info(channel, #state{channel = Channel}) -> - emqx_channel:info(Channel); -info(gc_state, #state{gc_state = GcSt}) -> - maybe_apply(fun emqx_gc:info/1, GcSt); -info(postponed, #state{postponed = Postponed}) -> - Postponed; -info(stats_timer, #state{stats_timer = TRef}) -> - TRef; -info(idle_timeout, #state{idle_timeout = Timeout}) -> - Timeout; -info(idle_timer, #state{idle_timer = TRef}) -> - TRef. - --spec(stats(pid()|state()) -> emqx_types:stats()). -stats(WsPid) when is_pid(WsPid) -> - call(WsPid, stats); -stats(#state{channel = Channel}) -> - SockStats = emqx_pd:get_counters(?SOCK_STATS), - ConnStats = emqx_pd:get_counters(?CONN_STATS), - ChanStats = emqx_channel:stats(Channel), - ProcStats = emqx_misc:proc_stats(), - lists:append([SockStats, ConnStats, ChanStats, ProcStats]). - -%% kick|discard|takeover --spec(call(pid(), Req :: term()) -> Reply :: term()). -call(WsPid, Req) when is_pid(WsPid) -> - Mref = erlang:monitor(process, WsPid), - WsPid ! {call, {self(), Mref}, Req}, - receive - {Mref, Reply} -> - erlang:demonitor(Mref, [flush]), - Reply; - {'DOWN', Mref, _, _, Reason} -> - exit(Reason) - after 5000 -> - erlang:demonitor(Mref, [flush]), - exit(timeout) - end. - -%%-------------------------------------------------------------------- -%% WebSocket callbacks -%%-------------------------------------------------------------------- - -init(Req, Opts) -> - %% WS Transport Idle Timeout - IdleTimeout = proplists:get_value(idle_timeout, Opts, 7200000), - DeflateOptions = maps:from_list(proplists:get_value(deflate_options, Opts, [])), - MaxFrameSize = case proplists:get_value(max_frame_size, Opts, 0) of - 0 -> infinity; - I -> I - end, - Compress = proplists:get_value(compress, Opts, false), - WsOpts = #{compress => Compress, - deflate_opts => DeflateOptions, - max_frame_size => MaxFrameSize, - idle_timeout => IdleTimeout - }, - case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req) of - undefined -> - %% TODO: why not reply 500??? - {cowboy_websocket, Req, [Req, Opts], WsOpts}; - [<<"mqtt", Vsn/binary>>] -> - Resp = cowboy_req:set_resp_header( - <<"sec-websocket-protocol">>, <<"mqtt", Vsn/binary>>, Req), - {cowboy_websocket, Resp, [Req, Opts], WsOpts}; - _ -> - {ok, cowboy_req:reply(400, Req), WsOpts} - end. - -websocket_init([Req, Opts]) -> - Peername = case proplists:get_bool(proxy_protocol, Opts) - andalso maps:get(proxy_header, Req) of - #{src_address := SrcAddr, src_port := SrcPort} -> - {SrcAddr, SrcPort}; - _ -> - cowboy_req:peer(Req) - end, - Sockname = cowboy_req:sock(Req), - Peercert = cowboy_req:cert(Req), - WsCookie = try cowboy_req:parse_cookies(Req) - catch - error:badarg -> - ?LOG(error, "Illegal cookie"), - undefined; - Error:Reason -> - ?LOG(error, "Failed to parse cookie, Error: ~0p, Reason ~0p", - [Error, Reason]), - undefined - end, - ConnInfo = #{socktype => ws, - peername => Peername, - sockname => Sockname, - peercert => Peercert, - ws_cookie => WsCookie, - conn_mod => ?MODULE - }, - Zone = proplists:get_value(zone, Opts), - PubLimit = emqx_zone:publish_limit(Zone), - Limiter = emqx_limiter:init([{pub_limit, PubLimit}|Opts]), - ActiveN = proplists:get_value(active_n, Opts, ?ACTIVE_N), - FrameOpts = emqx_zone:mqtt_frame_options(Zone), - ParseState = emqx_frame:initial_parse_state(FrameOpts), - Serialize = emqx_frame:serialize_fun(), - Channel = emqx_channel:init(ConnInfo, Opts), - GcState = emqx_zone:init_gc_state(Zone), - StatsTimer = emqx_zone:stats_timer(Zone), - %% MQTT Idle Timeout - IdleTimeout = emqx_zone:idle_timeout(Zone), - IdleTimer = start_timer(IdleTimeout, idle_timeout), - emqx_misc:tune_heap_size(emqx_zone:oom_policy(Zone)), - emqx_logger:set_metadata_peername(esockd:format(Peername)), - {ok, #state{peername = Peername, - sockname = Sockname, - sockstate = running, - active_n = ActiveN, - limiter = Limiter, - parse_state = ParseState, - serialize = Serialize, - channel = Channel, - gc_state = GcState, - postponed = [], - stats_timer = StatsTimer, - idle_timeout = IdleTimeout, - idle_timer = IdleTimer - }, hibernate}. - -websocket_handle({binary, Data}, State) when is_list(Data) -> - websocket_handle({binary, iolist_to_binary(Data)}, State); - -websocket_handle({binary, Data}, State) -> - ?LOG(debug, "RECV ~0p", [Data]), - ok = inc_recv_stats(1, iolist_size(Data)), - NState = ensure_stats_timer(State), - return(parse_incoming(Data, NState)); - -%% Pings should be replied with pongs, cowboy does it automatically -%% Pongs can be safely ignored. Clause here simply prevents crash. -websocket_handle(Frame, State) when Frame =:= ping; Frame =:= pong -> - return(State); - -websocket_handle({Frame, _}, State) when Frame =:= ping; Frame =:= pong -> - return(State); - -websocket_handle({Frame, _}, State) -> - %% TODO: should not close the ws connection - ?LOG(error, "Unexpected frame - ~p", [Frame]), - shutdown(unexpected_ws_frame, State). - -websocket_info({call, From, Req}, State) -> - handle_call(From, Req, State); - -websocket_info({cast, rate_limit}, State) -> - Stats = #{cnt => emqx_pd:reset_counter(incoming_pubs), - oct => emqx_pd:reset_counter(incoming_bytes) - }, - NState = postpone({check_gc, Stats}, State), - return(ensure_rate_limit(Stats, NState)); - -websocket_info({cast, Msg}, State) -> - handle_info(Msg, State); - -websocket_info({incoming, Packet = ?CONNECT_PACKET(ConnPkt)}, State) -> - Serialize = emqx_frame:serialize_fun(ConnPkt), - NState = State#state{serialize = Serialize}, - handle_incoming(Packet, cancel_idle_timer(NState)); - -websocket_info({incoming, ?PACKET(?PINGREQ)}, State) -> - return(enqueue(?PACKET(?PINGRESP), State)); - -websocket_info({incoming, Packet}, State) -> - handle_incoming(Packet, State); - -websocket_info({outgoing, Packets}, State) -> - return(enqueue(Packets, State)); - -websocket_info({check_gc, Stats}, State) -> - return(check_oom(run_gc(Stats, State))); - -websocket_info(Deliver = {deliver, _Topic, _Msg}, - State = #state{active_n = ActiveN}) -> - Delivers = [Deliver|emqx_misc:drain_deliver(ActiveN)], - with_channel(handle_deliver, [Delivers], State); - -websocket_info({timeout, TRef, limit_timeout}, - State = #state{limit_timer = TRef}) -> - NState = State#state{sockstate = running, - limit_timer = undefined - }, - return(enqueue({active, true}, NState)); - -websocket_info({timeout, TRef, Msg}, State) when is_reference(TRef) -> - handle_timeout(TRef, Msg, State); - -websocket_info({shutdown, Reason}, State) -> - shutdown(Reason, State); - -websocket_info({stop, Reason}, State) -> - shutdown(Reason, State); - -websocket_info(Info, State) -> - handle_info(Info, State). - -websocket_close({_, ReasonCode, _Payload}, State) when is_integer(ReasonCode) -> - websocket_close(ReasonCode, State); -websocket_close(Reason, State) -> - ?LOG(debug, "Websocket closed due to ~p~n", [Reason]), - handle_info({sock_closed, Reason}, State). - -terminate(Reason, _Req, #state{channel = Channel}) -> - ?LOG(debug, "Terminated due to ~p", [Reason]), - emqx_channel:terminate(Reason, Channel). - -%%-------------------------------------------------------------------- -%% Handle call -%%-------------------------------------------------------------------- - -handle_call(From, info, State) -> - gen_server:reply(From, info(State)), - return(State); - -handle_call(From, stats, State) -> - gen_server:reply(From, stats(State)), - return(State); - -handle_call(From, Req, State = #state{channel = Channel}) -> - case emqx_channel:handle_call(Req, Channel) of - {reply, Reply, NChannel} -> - gen_server:reply(From, Reply), - return(State#state{channel = NChannel}); - {shutdown, Reason, Reply, NChannel} -> - gen_server:reply(From, Reply), - shutdown(Reason, State#state{channel = NChannel}); - {shutdown, Reason, Reply, Packet, NChannel} -> - gen_server:reply(From, Reply), - NState = State#state{channel = NChannel}, - shutdown(Reason, enqueue(Packet, NState)) - end. - -%%-------------------------------------------------------------------- -%% Handle Info -%%-------------------------------------------------------------------- - -handle_info({connack, ConnAck}, State) -> - return(enqueue(ConnAck, State)); - -handle_info({close, Reason}, State) -> - ?LOG(debug, "Force to close the socket due to ~p", [Reason]), - return(enqueue({close, Reason}, State)); - -handle_info({event, connected}, State = #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - ok = emqx_cm:register_channel(ClientId, info(State), stats(State)), - return(State); - -handle_info({event, disconnected}, State = #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:set_chan_info(ClientId, info(State)), - emqx_cm:connection_closed(ClientId), - return(State); - -handle_info({event, _Other}, State = #state{channel = Channel}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:set_chan_info(ClientId, info(State)), - emqx_cm:set_chan_stats(ClientId, stats(State)), - return(State); - -handle_info(Info, State) -> - with_channel(handle_info, [Info], State). - -%%-------------------------------------------------------------------- -%% Handle timeout -%%-------------------------------------------------------------------- - -handle_timeout(TRef, idle_timeout, State = #state{idle_timer = TRef}) -> - shutdown(idle_timeout, State); - -handle_timeout(TRef, keepalive, State) when is_reference(TRef) -> - RecvOct = emqx_pd:get_counter(recv_oct), - handle_timeout(TRef, {keepalive, RecvOct}, State); - -handle_timeout(TRef, emit_stats, State = #state{channel = Channel, - stats_timer = TRef}) -> - ClientId = emqx_channel:info(clientid, Channel), - emqx_cm:set_chan_stats(ClientId, stats(State)), - return(State#state{stats_timer = undefined}); - -handle_timeout(TRef, TMsg, State) -> - with_channel(handle_timeout, [TRef, TMsg], State). - -%%-------------------------------------------------------------------- -%% Ensure rate limit -%%-------------------------------------------------------------------- - -ensure_rate_limit(Stats, State = #state{limiter = Limiter}) -> - case ?ENABLED(Limiter) andalso emqx_limiter:check(Stats, Limiter) of - false -> State; - {ok, Limiter1} -> - State#state{limiter = Limiter1}; - {pause, Time, Limiter1} -> - ?LOG(warning, "Pause ~pms due to rate limit", [Time]), - TRef = start_timer(Time, limit_timeout), - NState = State#state{sockstate = blocked, - limiter = Limiter1, - limit_timer = TRef - }, - enqueue({active, false}, NState) - end. - -%%-------------------------------------------------------------------- -%% Run GC, Check OOM -%%-------------------------------------------------------------------- - -run_gc(Stats, State = #state{gc_state = GcSt}) -> - case ?ENABLED(GcSt) andalso emqx_gc:run(Stats, GcSt) of - false -> State; - {_IsGC, GcSt1} -> - State#state{gc_state = GcSt1} - end. - -check_oom(State = #state{channel = Channel}) -> - OomPolicy = emqx_zone:oom_policy(emqx_channel:info(zone, Channel)), - case ?ENABLED(OomPolicy) andalso emqx_misc:check_oom(OomPolicy) of - Shutdown = {shutdown, _Reason} -> - postpone(Shutdown, State); - _Other -> State - end. - -%%-------------------------------------------------------------------- -%% Parse incoming data -%%-------------------------------------------------------------------- - -parse_incoming(<<>>, State) -> - State; - -parse_incoming(Data, State = #state{parse_state = ParseState}) -> - try emqx_frame:parse(Data, ParseState) of - {more, NParseState} -> - State#state{parse_state = NParseState}; - {ok, Packet, Rest, NParseState} -> - NState = State#state{parse_state = NParseState}, - parse_incoming(Rest, postpone({incoming, Packet}, NState)) - catch - error:Reason:Stk -> - ?LOG(error, "~nParse failed for ~0p~n~0p~nFrame data: ~0p", - [Reason, Stk, Data]), - FrameError = {frame_error, Reason}, - postpone({incoming, FrameError}, State) - end. - -%%-------------------------------------------------------------------- -%% Handle incoming packet -%%-------------------------------------------------------------------- - -handle_incoming(Packet, State = #state{active_n = ActiveN}) - when is_record(Packet, mqtt_packet) -> - ?LOG(debug, "RECV ~s", [emqx_packet:format(Packet)]), - ok = inc_incoming_stats(Packet), - NState = case emqx_pd:get_counter(incoming_pubs) > ActiveN of - true -> postpone({cast, rate_limit}, State); - false -> State - end, - with_channel(handle_in, [Packet], NState); - -handle_incoming(FrameError, State) -> - with_channel(handle_in, [FrameError], State). - -%%-------------------------------------------------------------------- -%% With Channel -%%-------------------------------------------------------------------- - -with_channel(Fun, Args, State = #state{channel = Channel}) -> - case erlang:apply(emqx_channel, Fun, Args ++ [Channel]) of - ok -> return(State); - {ok, NChannel} -> - return(State#state{channel = NChannel}); - {ok, Replies, NChannel} -> - return(postpone(Replies, State#state{channel= NChannel})); - {shutdown, Reason, NChannel} -> - shutdown(Reason, State#state{channel = NChannel}); - {shutdown, Reason, Packet, NChannel} -> - NState = State#state{channel = NChannel}, - shutdown(Reason, postpone(Packet, NState)) - end. - -%%-------------------------------------------------------------------- -%% Handle outgoing packets -%%-------------------------------------------------------------------- - -handle_outgoing(Packets, State = #state{active_n = ActiveN}) -> - IoData = lists:map(serialize_and_inc_stats_fun(State), Packets), - Oct = iolist_size(IoData), - ok = inc_sent_stats(length(Packets), Oct), - NState = case emqx_pd:get_counter(outgoing_pubs) > ActiveN of - true -> - Stats = #{cnt => emqx_pd:reset_counter(outgoing_pubs), - oct => emqx_pd:reset_counter(outgoing_bytes) - }, - postpone({check_gc, Stats}, State); - false -> State - end, - {{binary, IoData}, ensure_stats_timer(NState)}. - -serialize_and_inc_stats_fun(#state{serialize = Serialize}) -> - fun(Packet) -> - case Serialize(Packet) of - <<>> -> ?LOG(warning, "~s is discarded due to the frame is too large.", - [emqx_packet:format(Packet)]), - ok = emqx_metrics:inc('delivery.dropped.too_large'), - ok = emqx_metrics:inc('delivery.dropped'), - <<>>; - Data -> ?LOG(debug, "SEND ~s", [emqx_packet:format(Packet)]), - ok = inc_outgoing_stats(Packet), - Data - end - end. - -%%-------------------------------------------------------------------- -%% Inc incoming/outgoing stats -%%-------------------------------------------------------------------- - --compile({inline, - [ inc_recv_stats/2 - , inc_incoming_stats/1 - , inc_outgoing_stats/1 - , inc_sent_stats/2 - ]}). - -inc_recv_stats(Cnt, Oct) -> - emqx_pd:inc_counter(incoming_bytes, Oct), - emqx_pd:inc_counter(recv_cnt, Cnt), - emqx_pd:inc_counter(recv_oct, Oct), - emqx_metrics:inc('bytes.received', Oct). - -inc_incoming_stats(Packet = ?PACKET(Type)) -> - emqx_pd:inc_counter(recv_pkt, 1), - if Type == ?PUBLISH -> - emqx_pd:inc_counter(recv_msg, 1), - emqx_pd:inc_counter(incoming_pubs, 1); - true -> ok - end, - emqx_metrics:inc_recv(Packet). - -inc_outgoing_stats(Packet = ?PACKET(Type)) -> - emqx_pd:inc_counter(send_pkt, 1), - if Type == ?PUBLISH -> - emqx_pd:inc_counter(send_msg, 1), - emqx_pd:inc_counter(outgoing_pubs, 1); - true -> ok - end, - emqx_metrics:inc_sent(Packet). - -inc_sent_stats(Cnt, Oct) -> - emqx_pd:inc_counter(outgoing_bytes, Oct), - emqx_pd:inc_counter(send_cnt, Cnt), - emqx_pd:inc_counter(send_oct, Oct), - emqx_metrics:inc('bytes.sent', Oct). - -%%-------------------------------------------------------------------- -%% Helper functions -%%-------------------------------------------------------------------- - --compile({inline, [cancel_idle_timer/1, ensure_stats_timer/1]}). - -%%-------------------------------------------------------------------- -%% Cancel idle timer - -cancel_idle_timer(State = #state{idle_timer = IdleTimer}) -> - ok = emqx_misc:cancel_timer(IdleTimer), - State#state{idle_timer = undefined}. - -%%-------------------------------------------------------------------- -%% Ensure stats timer - -ensure_stats_timer(State = #state{idle_timeout = Timeout, - stats_timer = undefined}) -> - State#state{stats_timer = start_timer(Timeout, emit_stats)}; -ensure_stats_timer(State) -> State. - --compile({inline, [postpone/2, enqueue/2, return/1, shutdown/2]}). - -%%-------------------------------------------------------------------- -%% Postpone the packet, cmd or event - -postpone(Packet, State) when is_record(Packet, mqtt_packet) -> - enqueue(Packet, State); -postpone(Event, State) when is_tuple(Event) -> - enqueue(Event, State); -postpone(More, State) when is_list(More) -> - lists:foldl(fun postpone/2, State, More). - -enqueue([Packet], State = #state{postponed = Postponed}) -> - State#state{postponed = [Packet|Postponed]}; -enqueue(Packets, State = #state{postponed = Postponed}) - when is_list(Packets) -> - State#state{postponed = lists:reverse(Packets) ++ Postponed}; -enqueue(Other, State = #state{postponed = Postponed}) -> - State#state{postponed = [Other|Postponed]}. - -shutdown(Reason, State = #state{postponed = Postponed}) -> - return(State#state{postponed = [{shutdown, Reason}|Postponed]}). - -return(State = #state{postponed = []}) -> - {ok, State}; -return(State = #state{postponed = Postponed}) -> - {Packets, Cmds, Events} = classify(Postponed, [], [], []), - ok = lists:foreach(fun trigger/1, Events), - State1 = State#state{postponed = []}, - case {Packets, Cmds} of - {[], []} -> {ok, State1}; - {[], Cmds} -> {Cmds, State1}; - {Packets, Cmds} -> - {Frame, State2} = handle_outgoing(Packets, State1), - {[Frame|Cmds], State2} - end. - -classify([], Packets, Cmds, Events) -> - {Packets, Cmds, Events}; -classify([Packet|More], Packets, Cmds, Events) - when is_record(Packet, mqtt_packet) -> - classify(More, [Packet|Packets], Cmds, Events); -classify([Cmd = {active, _}|More], Packets, Cmds, Events) -> - classify(More, Packets, [Cmd|Cmds], Events); -classify([Cmd = {shutdown, _Reason}|More], Packets, Cmds, Events) -> - classify(More, Packets, [Cmd|Cmds], Events); -classify([Cmd = close|More], Packets, Cmds, Events) -> - classify(More, Packets, [Cmd|Cmds], Events); -classify([Cmd = {close, _Reason}|More], Packets, Cmds, Events) -> - classify(More, Packets, [Cmd|Cmds], Events); -classify([Event|More], Packets, Cmds, Events) -> - classify(More, Packets, Cmds, [Event|Events]). - -trigger(Event) -> erlang:send(self(), Event). - -%%-------------------------------------------------------------------- -%% For CT tests -%%-------------------------------------------------------------------- - -set_field(Name, Value, State) -> - Pos = emqx_misc:index_of(Name, record_info(fields, state)), - setelement(Pos+1, State, Value). - diff --git a/_build/emqx/lib/emqx/src/emqx_zone.erl b/_build/emqx/lib/emqx/src/emqx_zone.erl deleted file mode 100644 index 311ccaa772..0000000000 --- a/_build/emqx/lib/emqx/src/emqx_zone.erl +++ /dev/null @@ -1,285 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_zone). - --behaviour(gen_server). - --include("emqx.hrl"). --include("emqx_mqtt.hrl"). --include("logger.hrl"). --include("types.hrl"). - --logger_header("[Zone]"). - --compile({inline, - [ idle_timeout/1 - , publish_limit/1 - , mqtt_frame_options/1 - , mqtt_strict_mode/1 - , max_packet_size/1 - , mountpoint/1 - , use_username_as_clientid/1 - , stats_timer/1 - , enable_stats/1 - , enable_acl/1 - , enable_ban/1 - , enable_flapping_detect/1 - , ignore_loop_deliver/1 - , server_keepalive/1 - , keepalive_backoff/1 - , max_inflight/1 - , session_expiry_interval/1 - , force_gc_policy/1 - , force_shutdown_policy/1 - , response_information/1 - , get_env/2 - , get_env/3 - ]}). - -%% APIs --export([start_link/0, stop/0]). - -%% Zone Option API --export([ idle_timeout/1 - , publish_limit/1 - , mqtt_frame_options/1 - , mqtt_strict_mode/1 - , max_packet_size/1 - , mountpoint/1 - , use_username_as_clientid/1 - , stats_timer/1 - , enable_stats/1 - , enable_acl/1 - , enable_ban/1 - , enable_flapping_detect/1 - , ignore_loop_deliver/1 - , server_keepalive/1 - , keepalive_backoff/1 - , max_inflight/1 - , session_expiry_interval/1 - , force_gc_policy/1 - , force_shutdown_policy/1 - , response_information/1 - ]). - --export([ init_gc_state/1 - , oom_policy/1 - ]). - -%% Zone API --export([ get_env/2 - , get_env/3 - , set_env/3 - , unset_env/2 - , unset_all_env/0 - ]). - --export([force_reload/0]). - -%% gen_server callbacks --export([ init/1 - , handle_call/3 - , handle_cast/2 - , handle_info/2 - , terminate/2 - , code_change/3 - ]). - --import(emqx_misc, [maybe_apply/2]). - --export_type([zone/0]). - --type(zone() :: atom()). - --define(TAB, ?MODULE). --define(SERVER, ?MODULE). --define(DEFAULT_IDLE_TIMEOUT, 30000). --define(KEY(Zone, Key), {?MODULE, Zone, Key}). - --spec(start_link() -> startlink_ret()). -start_link() -> - gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). - --spec(stop() -> ok). -stop() -> - gen_server:stop(?SERVER). - --spec(init_gc_state(zone()) -> maybe(emqx_gc:gc_state())). -init_gc_state(Zone) -> - maybe_apply(fun emqx_gc:init/1, force_gc_policy(Zone)). - --spec(oom_policy(zone()) -> emqx_types:oom_policy()). -oom_policy(Zone) -> force_shutdown_policy(Zone). - -%%-------------------------------------------------------------------- -%% Zone Options API -%%-------------------------------------------------------------------- - --spec(idle_timeout(zone()) -> pos_integer()). -idle_timeout(Zone) -> - get_env(Zone, idle_timeout, ?DEFAULT_IDLE_TIMEOUT). - --spec(publish_limit(zone()) -> maybe(esockd_rate_limit:config())). -publish_limit(Zone) -> - get_env(Zone, publish_limit). - --spec(mqtt_frame_options(zone()) -> emqx_frame:options()). -mqtt_frame_options(Zone) -> - #{strict_mode => mqtt_strict_mode(Zone), - max_size => max_packet_size(Zone) - }. - --spec(mqtt_strict_mode(zone()) -> boolean()). -mqtt_strict_mode(Zone) -> - get_env(Zone, strict_mode, false). - --spec(max_packet_size(zone()) -> integer()). -max_packet_size(Zone) -> - get_env(Zone, max_packet_size, ?MAX_PACKET_SIZE). - --spec(mountpoint(zone()) -> maybe(emqx_mountpoint:mountpoint())). -mountpoint(Zone) -> get_env(Zone, mountpoint). - --spec(use_username_as_clientid(zone()) -> boolean()). -use_username_as_clientid(Zone) -> - get_env(Zone, use_username_as_clientid, false). - --spec(stats_timer(zone()) -> undefined | disabled). -stats_timer(Zone) -> - case enable_stats(Zone) of true -> undefined; false -> disabled end. - --spec(enable_stats(zone()) -> boolean()). -enable_stats(Zone) -> - get_env(Zone, enable_stats, true). - --spec(enable_acl(zone()) -> boolean()). -enable_acl(Zone) -> - get_env(Zone, enable_acl, true). - --spec(enable_ban(zone()) -> boolean()). -enable_ban(Zone) -> - get_env(Zone, enable_ban, false). - --spec(enable_flapping_detect(zone()) -> boolean()). -enable_flapping_detect(Zone) -> - get_env(Zone, enable_flapping_detect, false). - --spec(ignore_loop_deliver(zone()) -> boolean()). -ignore_loop_deliver(Zone) -> - get_env(Zone, ignore_loop_deliver, false). - --spec(server_keepalive(zone()) -> maybe(pos_integer())). -server_keepalive(Zone) -> - get_env(Zone, server_keepalive). - --spec(keepalive_backoff(zone()) -> float()). -keepalive_backoff(Zone) -> - get_env(Zone, keepalive_backoff, 0.75). - --spec(max_inflight(zone()) -> 0..65535). -max_inflight(Zone) -> - get_env(Zone, max_inflight, 65535). - --spec(session_expiry_interval(zone()) -> non_neg_integer()). -session_expiry_interval(Zone) -> - get_env(Zone, session_expiry_interval, 0). - --spec(force_gc_policy(zone()) -> maybe(emqx_gc:opts())). -force_gc_policy(Zone) -> - get_env(Zone, force_gc_policy). - --spec(force_shutdown_policy(zone()) -> maybe(emqx_oom:opts())). -force_shutdown_policy(Zone) -> - get_env(Zone, force_shutdown_policy). - --spec(response_information(zone()) -> string()). -response_information(Zone) -> - get_env(Zone, response_information). - -%%-------------------------------------------------------------------- -%% APIs -%%-------------------------------------------------------------------- - --spec(get_env(maybe(zone()), atom()) -> maybe(term())). -get_env(undefined, Key) -> emqx:get_env(Key); -get_env(Zone, Key) -> - get_env(Zone, Key, undefined). - --spec(get_env(maybe(zone()), atom(), term()) -> maybe(term())). -get_env(undefined, Key, Def) -> - emqx:get_env(Key, Def); -get_env(Zone, Key, Def) -> - try persistent_term:get(?KEY(Zone, Key)) - catch error:badarg -> - emqx:get_env(Key, Def) - end. - --spec(set_env(zone(), atom(), term()) -> ok). -set_env(Zone, Key, Val) -> - persistent_term:put(?KEY(Zone, Key), Val). - --spec(unset_env(zone(), atom()) -> boolean()). -unset_env(Zone, Key) -> - persistent_term:erase(?KEY(Zone, Key)). - --spec(unset_all_env() -> ok). -unset_all_env() -> - [unset_env(Zone, Key) || {?KEY(Zone, Key), _Val} <- persistent_term:get()], - ok. - --spec(force_reload() -> ok). -force_reload() -> - gen_server:call(?SERVER, force_reload). - -%%-------------------------------------------------------------------- -%% gen_server callbacks -%%-------------------------------------------------------------------- - -init([]) -> - _ = do_reload(), - {ok, #{}}. - -handle_call(force_reload, _From, State) -> - _ = do_reload(), - {reply, ok, State}; - -handle_call(Req, _From, State) -> - ?LOG(error, "Unexpected call: ~p", [Req]), - {reply, ignored, State}. - -handle_cast(Msg, State) -> - ?LOG(error, "Unexpected cast: ~p", [Msg]), - {noreply, State}. - -handle_info(Info, State) -> - ?LOG(error, "Unexpected info: ~p", [Info]), - {noreply, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%-------------------------------------------------------------------- -%% Internal functions -%%-------------------------------------------------------------------- - -do_reload() -> - [persistent_term:put(?KEY(Zone, Key), Val) - || {Zone, Opts} <- emqx:get_env(zones, []), {Key, Val} <- Opts]. - diff --git a/_build/emqx/lib/emqx/vars b/_build/emqx/lib/emqx/vars deleted file mode 100644 index 359c27c223..0000000000 --- a/_build/emqx/lib/emqx/vars +++ /dev/null @@ -1,8 +0,0 @@ -%% vars here are for test only, not intended for release - -{platform_bin_dir, "bin"}. -{platform_data_dir, "data"}. -{platform_etc_dir, "etc"}. -{platform_lib_dir, "lib"}. -{platform_log_dir, "log"}. -{platform_plugins_dir, "plugins"}. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/.github/workflows/run_test_cases.yaml b/_build/emqx/lib/emqx_bridge_mqtt/.github/workflows/run_test_cases.yaml deleted file mode 100644 index b8e7225704..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/.github/workflows/run_test_cases.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Run test cases - -on: [push, pull_request] - -jobs: - run_test_cases: - runs-on: ubuntu-latest - - container: - image: erlang:22.1 - - steps: - - uses: actions/checkout@v1 - - name: run test cases - run: | - make xref - make eunit - make ct - make cover - - uses: actions/upload-artifact@v1 - if: always() - with: - name: logs - path: _build/test/logs - - uses: actions/upload-artifact@v1 - with: - name: cover - path: _build/test/cover - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/.gitignore b/_build/emqx/lib/emqx_bridge_mqtt/.gitignore deleted file mode 100644 index bf9523be59..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/.gitignore +++ /dev/null @@ -1,21 +0,0 @@ -.eunit -deps -*.o -*.beam -*.plt -erl_crash.dump -ebin/*.beam -rel -_build -.concrete/DEV_MODE -.rebar -.erlang.mk -data -ebin -emqx_bridge_mqtt.d -*.rendered -.rebar3/ -*.coverdata -rebar.lock -.DS_Store -Mnesia.*/ \ No newline at end of file diff --git a/_build/emqx/lib/emqx_bridge_mqtt/LICENSE b/_build/emqx/lib/emqx_bridge_mqtt/LICENSE deleted file mode 100644 index 70a976fe33..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2019, GilbertWong . - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/Makefile b/_build/emqx/lib/emqx_bridge_mqtt/Makefile deleted file mode 100644 index b2cc9cbed0..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -## shallow clone for speed - -REBAR_GIT_CLONE_OPTIONS += --depth 1 -export REBAR_GIT_CLONE_OPTIONS - -REBAR = rebar3 - -CT_NODE_NAME = emqxct@127.0.0.1 - -all: compile - -compile: unlock - $(REBAR) compile - -clean: distclean - -ct: compile - $(REBAR) as test ct -v --readable=false --name $(CT_NODE_NAME) - -eunit: compile - $(REBAR) as test eunit - -unlock: - $(REBAR) unlock - -xref: - $(REBAR) xref - -cover: - $(REBAR) cover - -distclean: - @rm -rf _build - @rm -f data/app.*.config data/vm.*.args rebar.lock - -CUTTLEFISH_SCRIPT = _build/default/lib/cuttlefish/cuttlefish - -$(CUTTLEFISH_SCRIPT): - @${REBAR} get-deps - @if [ ! -f cuttlefish ]; then make -C _build/default/lib/cuttlefish; fi - -app.config: $(CUTTLEFISH_SCRIPT) - $(verbose) $(CUTTLEFISH_SCRIPT) -l info -e etc/ -c etc/emqx_bridge_mqtt.conf -i priv/emqx_bridge_mqtt.schema -d data diff --git a/_build/emqx/lib/emqx_bridge_mqtt/README.md b/_build/emqx/lib/emqx_bridge_mqtt/README.md deleted file mode 100644 index 6656aa36fc..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/README.md +++ /dev/null @@ -1,265 +0,0 @@ -# EMQ Bridge MQTT - -The concept of **Bridge** means that EMQ X supports forwarding messages -of one of its own topics to another MQTT Broker in some way. - -**Bridge** differs from **Cluster** in that the bridge does not -replicate the topic trie and routing tables and only forwards MQTT -messages based on bridging rules. - -At present, the bridging methods supported by EMQ X are as follows: - -- RPC bridge: RPC Bridge only supports message forwarding and does not - support subscribing to the topic of remote nodes to synchronize - data; -- MQTT Bridge: MQTT Bridge supports both forwarding and data - synchronization through subscription topic. - -These concepts are shown below: - -![bridge](docs/images/bridge.png) - -In addition, the EMQ X message broker supports multi-node bridge mode interconnection - -``` - --------- --------- --------- -Publisher --> | Node1 | --Bridge Forward--> | Node2 | --Bridge Forward--> | Node3 | --> Subscriber - --------- --------- --------- -``` - -In EMQ X, bridge is configured by modifying `etc/emqx.conf`. EMQ X distinguishes between different bridges based on different names. E.g - -``` -## Bridge address: node name for local bridge, host:port for remote. -bridge.mqtt.aws.address = 127.0.0.1:1883 -``` - -This configuration declares a bridge named `aws` and specifies that it is bridged to the MQTT broker of 127.0.0.1:1883 by MQTT mode. - -In case of creating multiple bridges, it is convenient to replicate all configuration items of the first bridge, and modify the bridge name and other configuration items if necessary (such as bridge.$name.address, where $name refers to the name of bridge) - -The next two sections describe how to create a bridge in RPC and MQTT mode respectively and create a forwarding rule that forwards the messages from sensors. Assuming that two EMQ X nodes are running on two hosts: - - -| Name | Node | MQTT Port | -|------|-------------------|-----------| -| emqx1| emqx1@192.168.1.1.| 1883 | -| emqx2| emqx2@192.168.1.2 | 1883 | - - -## EMQ X RPC Bridge Configuration - -The following is the basic configuration of RPC bridging. A simplest RPC bridging only requires the following three items - -``` -## Bridge Address: Use node name (nodename@host) for rpc bridging, and host:port for mqtt connection -bridge.mqtt.emqx2.address = emqx2@192.168.1.2 - -## Forwarding topics of the message -bridge.mqtt.emqx2.forwards = sensor1/#,sensor2/# - -## bridged mountpoint -bridge.mqtt.emqx2.mountpoint = bridge/emqx2/${node}/ -``` - -If the messages received by the local node emqx1 matches the topic `sersor1/#` or `sensor2/#`, these messages will be forwarded to the `sensor1/#` or `sensor2/#` topic of the remote node emqx2. - -`forwards` is used to specify topics. Messages of the in `forwards` specified topics on local node are forwarded to the remote node. - -`mountpoint` is used to add a topic prefix when forwarding a message. To use `mountpoint`, the `forwards` directive must be set. In the above example, a message with the topic `sensor1/hello` received by the local node will be forwarded to the remote node with the topic `bridge/emqx2/emqx1@192.168.1.1/sensor1/hello`. - -Limitations of RPC bridging: - -1. The RPC bridge of emqx can only forward local messages to the remote node, and cannot synchronize the messages of the remote node to the local node; - -2. RPC bridge can only bridge two EMQ X broker together and cannot bridge EMQ X broker to other MQTT brokers. - -## EMQ X MQTT Bridge Configuration - -EMQ X 3.0 officially introduced MQTT bridge, so that EMQ X can bridge any MQTT broker. Because of the characteristics of the MQTT protocol, EMQ X can subscribe to the remote mqtt broker's topic through MQTT bridge, and then synchronize the remote MQTT broker's message to the local. - -EMQ X MQTT bridging principle: Create an MQTT client on the EMQ X broker, and connect this MQTT client to the remote MQTT broker. Therefore, in the MQTT bridge configuration, following fields may be set for the EMQ X to connect to the remote broker as an mqtt client - -``` -## Bridge Address: Use node name for rpc bridging, use host:port for mqtt connection -bridge.mqtt.emqx2.address = 192.168.1.2:1883 - -## Bridged Protocol Version -## Enumeration value: mqttv3 | mqttv4 | mqttv5 -bridge.mqtt.emqx2.proto_ver = mqttv4 - -## mqtt client's clientid -bridge.mqtt.emqx2.clientid = bridge_emq - -## mqtt client's clean_start field -## Note: Some MQTT Brokers need to set the clean_start value as `true` -bridge.mqtt.emqx2.clean_start = true - -## mqtt client's username field -bridge.mqtt.emqx2.username = user - -## mqtt client's password field -bridge.mqtt.emqx2.password = passwd - -## Whether the mqtt client uses ssl to connect to a remote serve or not -bridge.mqtt.emqx2.ssl = off - -## CA Certificate of Client SSL Connection (PEM format) -bridge.mqtt.emqx2.cacertfile = etc/certs/cacert.pem - -## SSL certificate of Client SSL connection -bridge.mqtt.emqx2.certfile = etc/certs/client-cert.pem - -## Key file of Client SSL connection -bridge.mqtt.emqx2.keyfile = etc/certs/client-key.pem - -## SSL encryption -bridge.mqtt.emqx2.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384 - -## TTLS PSK password -## Note 'listener.ssl.external.ciphers' and 'listener.ssl.external.psk_ciphers' cannot be configured at the same time -## -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -## bridge.mqtt.emqx2.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## Client's heartbeat interval -bridge.mqtt.emqx2.keepalive = 60s - -## Supported TLS version -bridge.mqtt.emqx2.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## Forwarding topics of the message -bridge.mqtt.emqx2.forwards = sensor1/#,sensor2/# - -## Bridged mountpoint -bridge.mqtt.emqx2.mountpoint = bridge/emqx2/${node}/ - -## Subscription topic for bridging -bridge.mqtt.emqx2.subscription.1.topic = cmd/topic1 - -## Subscription qos for bridging -bridge.mqtt.emqx2.subscription.1.qos = 1 - -## Subscription topic for bridging -bridge.mqtt.emqx2.subscription.2.topic = cmd/topic2 - -## Subscription qos for bridging -bridge.mqtt.emqx2.subscription.2.qos = 1 - -## Bridging reconnection interval -## Default: 30s -bridge.mqtt.emqx2.reconnect_interval = 30s - -## QoS1 message retransmission interval -bridge.mqtt.emqx2.retry_interval = 20s - -## Inflight Size. -bridge.mqtt.emqx2.max_inflight_batches = 32 -``` - -## Bridge Cache Configuration - -The bridge of EMQ X has a message caching mechanism. The caching mechanism is applicable to both RPC bridging and MQTT bridging. When the bridge is disconnected (such as when the network connection is unstable), the messages with a topic specified in `forwards` can be cached to the local message queue. Until the bridge is restored, these messages are re-forwarded to the remote node. The configuration of the cache queue is as follows - -``` -## emqx_bridge internal number of messages used for batch -bridge.mqtt.emqx2.queue.batch_count_limit = 32 - -## emqx_bridge internal number of message bytes used for batch -bridge.mqtt.emqx2.queue.batch_bytes_limit = 1000MB - -## The path for placing replayq queue. If it is not specified, then replayq will run in `mem-only` mode and messages will not be cached on disk. -bridge.mqtt.emqx2.queue.replayq_dir = data/emqx_emqx2_bridge/ - -## Replayq data segment size -bridge.mqtt.emqx2.queue.replayq_seg_bytes = 10MB -``` - -`bridge.mqtt.emqx2.queue.replayq_dir` is a configuration parameter for specifying the path of the bridge storage queue. - -`bridge.mqtt.emqx2.queue.replayq_seg_bytes` is used to specify the size of the largest single file of the message queue that is cached on disk. If the message queue size exceeds the specified value, a new file is created to store the message queue. - -## CLI for EMQ X Bridge MQTT - -CLI for EMQ X Bridge MQTT: - -``` bash -$ cd emqx1/ && ./bin/emqx_ctl bridges -bridges list # List bridges -bridges start # Start a bridge -bridges stop # Stop a bridge -bridges forwards # Show a bridge forward topic -bridges add-forward # Add bridge forward topic -bridges del-forward # Delete bridge forward topic -bridges subscriptions # Show a bridge subscriptions topic -bridges add-subscription # Add bridge subscriptions topic -``` - -List all bridge states - -``` bash -$ ./bin/emqx_ctl bridges list -name: emqx status: Stopped $ ./bin/emqx_ctl bridges list -name: emqx status: Stopped -``` - -Start the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges start emqx -Start bridge successfully. -``` - -Stop the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges stop emqx -Stop bridge successfully. -``` -List the forwarding topics for the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges forwards emqx -topic: topic1/# -topic: topic2/# -``` - -Add a forwarding topic for the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges add-forwards emqx topic3/# -Add-forward topic successfully. -``` - -Delete the forwarding topic for the specified bridge - - -``` bash -$ ./bin/emqx_ctl bridges del-forwards emqx topic3/# -Del-forward topic successfully. -``` - -List subscriptions for the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges subscriptions emqx -topic: cmd/topic1, qos: 1 -topic: cmd/topic2, qos: 1 -``` - -Add a subscription topic for the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges add-subscription emqx cmd/topic3 1 -Add-subscription topic successfully. -``` - -Delete the subscription topic for the specified bridge - -``` bash -$ ./bin/emqx_ctl bridges del-subscription emqx cmd/topic3 -Del-subscription topic successfully. -``` - -Note: In case of creating multiple bridges, it is convenient to replicate all configuration items of the first bridge, and modify the bridge name and other configuration items if necessary. - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/docs/guide.rst b/_build/emqx/lib/emqx_bridge_mqtt/docs/guide.rst deleted file mode 100644 index 73350ca1fd..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/docs/guide.rst +++ /dev/null @@ -1,286 +0,0 @@ - -EMQ Bridge MQTT -=============== - -The concept of **Bridge** means that EMQ X supports forwarding messages -of one of its own topics to another MQTT Broker in some way. - -**Bridge** differs from **Cluster** in that the bridge does not -replicate the topic trie and routing tables and only forwards MQTT -messages based on bridging rules. - -At present, the bridging methods supported by EMQ X are as follows: - - -* RPC bridge: RPC Bridge only supports message forwarding and does not - support subscribing to the topic of remote nodes to synchronize - data; -* MQTT Bridge: MQTT Bridge supports both forwarding and data - synchronization through subscription topic. - -These concepts are shown below: - - -.. image:: images/bridge.png - :target: images/bridge.png - :alt: bridge - - -In addition, the EMQ X message broker supports multi-node bridge mode interconnection - -.. code-block:: - - --------- --------- --------- - Publisher --> | Node1 | --Bridge Forward--> | Node2 | --Bridge Forward--> | Node3 | --> Subscriber - --------- --------- --------- - -In EMQ X, bridge is configured by modifying ``etc/emqx.conf``. EMQ X distinguishes between different bridges based on different names. E.g - -.. code-block:: - - ## Bridge address: node name for local bridge, host:port for remote. - bridge.mqtt.aws.address = 127.0.0.1:1883 - -This configuration declares a bridge named ``aws`` and specifies that it is bridged to the MQTT broker of 127.0.0.1:1883 by MQTT mode. - -In case of creating multiple bridges, it is convenient to replicate all configuration items of the first bridge, and modify the bridge name and other configuration items if necessary (such as bridge.$name.address, where $name refers to the name of bridge) - -The next two sections describe how to create a bridge in RPC and MQTT mode respectively and create a forwarding rule that forwards the messages from sensors. Assuming that two EMQ X nodes are running on two hosts: - -.. list-table:: - :header-rows: 1 - - * - Name - - Node - - MQTT Port - * - emqx1 - - emqx1@192.168.1.1. - - 1883 - * - emqx2 - - emqx2@192.168.1.2 - - 1883 - - -EMQ X RPC Bridge Configuration ------------------------------- - -The following is the basic configuration of RPC bridging. A simplest RPC bridging only requires the following three items - -.. code-block:: - - ## Bridge Address: Use node name (nodename@host) for rpc bridging, and host:port for mqtt connection - bridge.mqtt.emqx2.address = emqx2@192.168.1.2 - - ## Forwarding topics of the message - bridge.mqtt.emqx2.forwards = sensor1/#,sensor2/# - - ## bridged mountpoint - bridge.mqtt.emqx2.mountpoint = bridge/emqx2/${node}/ - -If the messages received by the local node emqx1 matches the topic ``sersor1/#`` or ``sensor2/#``\ , these messages will be forwarded to the ``sensor1/#`` or ``sensor2/#`` topic of the remote node emqx2. - -``forwards`` is used to specify topics. Messages of the in ``forwards`` specified topics on local node are forwarded to the remote node. - -``mountpoint`` is used to add a topic prefix when forwarding a message. To use ``mountpoint``\ , the ``forwards`` directive must be set. In the above example, a message with the topic ``sensor1/hello`` received by the local node will be forwarded to the remote node with the topic ``bridge/emqx2/emqx1@192.168.1.1/sensor1/hello``. - -Limitations of RPC bridging: - - -#. - The RPC bridge of emqx can only forward local messages to the remote node, and cannot synchronize the messages of the remote node to the local node; - -#. - RPC bridge can only bridge two EMQ X broker together and cannot bridge EMQ X broker to other MQTT brokers. - -EMQ X MQTT Bridge Configuration -------------------------------- - -EMQ X 3.0 officially introduced MQTT bridge, so that EMQ X can bridge any MQTT broker. Because of the characteristics of the MQTT protocol, EMQ X can subscribe to the remote mqtt broker's topic through MQTT bridge, and then synchronize the remote MQTT broker's message to the local. - -EMQ X MQTT bridging principle: Create an MQTT client on the EMQ X broker, and connect this MQTT client to the remote MQTT broker. Therefore, in the MQTT bridge configuration, following fields may be set for the EMQ X to connect to the remote broker as an mqtt client - -.. code-block:: - - ## Bridge Address: Use node name for rpc bridging, use host:port for mqtt connection - bridge.mqtt.emqx2.address = 192.168.1.2:1883 - - ## Bridged Protocol Version - ## Enumeration value: mqttv3 | mqttv4 | mqttv5 - bridge.mqtt.emqx2.proto_ver = mqttv4 - - ## mqtt client's clientid - bridge.mqtt.emqx2.clientid = bridge_emq - - ## mqtt client's clean_start field - ## Note: Some MQTT Brokers need to set the clean_start value as `true` - bridge.mqtt.emqx2.clean_start = true - - ## mqtt client's username field - bridge.mqtt.emqx2.username = user - - ## mqtt client's password field - bridge.mqtt.emqx2.password = passwd - - ## Whether the mqtt client uses ssl to connect to a remote serve or not - bridge.mqtt.emqx2.ssl = off - - ## CA Certificate of Client SSL Connection (PEM format) - bridge.mqtt.emqx2.cacertfile = etc/certs/cacert.pem - - ## SSL certificate of Client SSL connection - bridge.mqtt.emqx2.certfile = etc/certs/client-cert.pem - - ## Key file of Client SSL connection - bridge.mqtt.emqx2.keyfile = etc/certs/client-key.pem - - ## SSL encryption - bridge.mqtt.emqx2.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384 - - ## TTLS PSK password - ## Note 'listener.ssl.external.ciphers' and 'listener.ssl.external.psk_ciphers' cannot be configured at the same time - ## - ## See 'https://tools.ietf.org/html/rfc4279#section-2'. - ## bridge.mqtt.emqx2.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - - ## Client's heartbeat interval - bridge.mqtt.emqx2.keepalive = 60s - - ## Supported TLS version - bridge.mqtt.emqx2.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - - ## Forwarding topics of the message - bridge.mqtt.emqx2.forwards = sensor1/#,sensor2/# - - ## Bridged mountpoint - bridge.mqtt.emqx2.mountpoint = bridge/emqx2/${node}/ - - ## Subscription topic for bridging - bridge.mqtt.emqx2.subscription.1.topic = cmd/topic1 - - ## Subscription qos for bridging - bridge.mqtt.emqx2.subscription.1.qos = 1 - - ## Subscription topic for bridging - bridge.mqtt.emqx2.subscription.2.topic = cmd/topic2 - - ## Subscription qos for bridging - bridge.mqtt.emqx2.subscription.2.qos = 1 - - ## Bridging reconnection interval - ## Default: 30s - bridge.mqtt.emqx2.reconnect_interval = 30s - - ## QoS1 message retransmission interval - bridge.mqtt.emqx2.retry_interval = 20s - - ## Inflight Size. - bridge.mqtt.emqx2.max_inflight_batches = 32 - -Bridge Cache Configuration --------------------------- - -The bridge of EMQ X has a message caching mechanism. The caching mechanism is applicable to both RPC bridging and MQTT bridging. When the bridge is disconnected (such as when the network connection is unstable), the messages with a topic specified in ``forwards`` can be cached to the local message queue. Until the bridge is restored, these messages are re-forwarded to the remote node. The configuration of the cache queue is as follows - -.. code-block:: - - ## emqx_bridge internal number of messages used for batch - bridge.mqtt.emqx2.queue.batch_count_limit = 32 - - ## emqx_bridge internal number of message bytes used for batch - bridge.mqtt.emqx2.queue.batch_bytes_limit = 1000MB - - ## The path for placing replayq queue. If it is not specified, then replayq will run in `mem-only` mode and messages will not be cached on disk. - bridge.mqtt.emqx2.queue.replayq_dir = data/emqx_emqx2_bridge/ - - ## Replayq data segment size - bridge.mqtt.emqx2.queue.replayq_seg_bytes = 10MB - -``bridge.mqtt.emqx2.queue.replayq_dir`` is a configuration parameter for specifying the path of the bridge storage queue. - -``bridge.mqtt.emqx2.queue.replayq_seg_bytes`` is used to specify the size of the largest single file of the message queue that is cached on disk. If the message queue size exceeds the specified value, a new file is created to store the message queue. - -CLI for EMQ X Bridge MQTT -------------------------- - -CLI for EMQ X Bridge MQTT: - -.. code-block:: bash - - $ cd emqx1/ && ./bin/emqx_ctl bridges - bridges list # List bridges - bridges start # Start a bridge - bridges stop # Stop a bridge - bridges forwards # Show a bridge forward topic - bridges add-forward # Add bridge forward topic - bridges del-forward # Delete bridge forward topic - bridges subscriptions # Show a bridge subscriptions topic - bridges add-subscription # Add bridge subscriptions topic - -List all bridge states - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges list - name: emqx status: Stopped $ ./bin/emqx_ctl bridges list - name: emqx status: Stopped - -Start the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges start emqx - Start bridge successfully. - -Stop the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges stop emqx - Stop bridge successfully. - -List the forwarding topics for the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges forwards emqx - topic: topic1/# - topic: topic2/# - -Add a forwarding topic for the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges add-forwards emqx topic3/# - Add-forward topic successfully. - -Delete the forwarding topic for the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges del-forwards emqx topic3/# - Del-forward topic successfully. - -List subscriptions for the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges subscriptions emqx - topic: cmd/topic1, qos: 1 - topic: cmd/topic2, qos: 1 - -Add a subscription topic for the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges add-subscription emqx cmd/topic3 1 - Add-subscription topic successfully. - -Delete the subscription topic for the specified bridge - -.. code-block:: bash - - $ ./bin/emqx_ctl bridges del-subscription emqx cmd/topic3 - Del-subscription topic successfully. - -Note: In case of creating multiple bridges, it is convenient to replicate all configuration items of the first bridge, and modify the bridge name and other configuration items if necessary. - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/docs/images/bridge.png b/_build/emqx/lib/emqx_bridge_mqtt/docs/images/bridge.png deleted file mode 100644 index 9bb9c024c9..0000000000 Binary files a/_build/emqx/lib/emqx_bridge_mqtt/docs/images/bridge.png and /dev/null differ diff --git a/_build/emqx/lib/emqx_bridge_mqtt/etc/emqx_bridge_mqtt.conf b/_build/emqx/lib/emqx_bridge_mqtt/etc/emqx_bridge_mqtt.conf deleted file mode 100644 index 54c2ac1c0c..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/etc/emqx_bridge_mqtt.conf +++ /dev/null @@ -1,169 +0,0 @@ -##==================================================================== -## Configuration for EMQ X MQTT Broker Bridge -##==================================================================== - -##-------------------------------------------------------------------- -## Bridges to aws -##-------------------------------------------------------------------- - -## Bridge address: node name for local bridge, host:port for remote. -## -## Value: String -## Example: emqx@127.0.0.1, 127.0.0.1:1883 -bridge.mqtt.aws.address = 127.0.0.1:1883 - -## Protocol version of the bridge. -## -## Value: Enum -## - mqttv5 -## - mqttv4 -## - mqttv3 -bridge.mqtt.aws.proto_ver = mqttv4 - -## Start type of the bridge. -## -## Value: enum -## manual -## auto -bridge.mqtt.aws.start_type = manual - -## Whether to enable bridge mode for mqtt bridge -## -## This option is prepared for the mqtt broker which does not -## support bridge_mode such as the mqtt-plugin of the rabbitmq -## -## Value: boolean -bridge.mqtt.aws.bridge_mode = true - -## The ClientId of a remote bridge. -## -## Value: String -bridge.mqtt.aws.clientid = bridge_aws - -## The Clean start flag of a remote bridge. -## -## Value: boolean -## Default: true -## -## NOTE: Some IoT platforms require clean_start -## must be set to 'true' -bridge.mqtt.aws.clean_start = true - -## The username for a remote bridge. -## -## Value: String -bridge.mqtt.aws.username = user - -## The password for a remote bridge. -## -## Value: String -bridge.mqtt.aws.password = passwd - -## Topics that need to be forward to AWS IoTHUB -## -## Value: String -## Example: topic1/#,topic2/# -bridge.mqtt.aws.forwards = topic1/#,topic2/# - -## Forward messages to the mountpoint of an AWS IoTHUB -## -## Value: String -bridge.mqtt.aws.forward_mountpoint = bridge/aws/${node}/ - -## Need to subscribe to AWS topics -## -## Value: String -## bridge.mqtt.aws.subscription.1.topic = cmd/topic1 - -## Need to subscribe to AWS topics QoS. -## -## Value: Number -## bridge.mqtt.aws.subscription.1.qos = 1 - -## A mountpoint that receives messages from AWS IoTHUB -## -## Value: String -## bridge.mqtt.aws.receive_mountpoint = receive/aws/ - - -## Bribge to remote server via SSL. -## -## Value: on | off -bridge.mqtt.aws.ssl = off - -## PEM-encoded CA certificates of the bridge. -## -## Value: File -bridge.mqtt.aws.cacertfile = {{ platform_etc_dir }}/certs/cacert.pem - -## Client SSL Certfile of the bridge. -## -## Value: File -bridge.mqtt.aws.certfile = {{ platform_etc_dir }}/certs/client-cert.pem - -## Client SSL Keyfile of the bridge. -## -## Value: File -bridge.mqtt.aws.keyfile = {{ platform_etc_dir }}/certs/client-key.pem - -## SSL Ciphers used by the bridge. -## -## Value: String -bridge.mqtt.aws.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384 - -## Ciphers for TLS PSK. -## Note that 'bridge.${BridgeName}.ciphers' and 'bridge.${BridgeName}.psk_ciphers' cannot -## be configured at the same time. -## See 'https://tools.ietf.org/html/rfc4279#section-2'. -bridge.mqtt.aws.psk_ciphers = PSK-AES128-CBC-SHA,PSK-AES256-CBC-SHA,PSK-3DES-EDE-CBC-SHA,PSK-RC4-SHA - -## Ping interval of a down bridge. -## -## Value: Duration -## Default: 10 seconds -bridge.mqtt.aws.keepalive = 60s - -## TLS versions used by the bridge. -## -## Value: String -bridge.mqtt.aws.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## Bridge reconnect time. -## -## Value: Duration -## Default: 30 seconds -bridge.mqtt.aws.reconnect_interval = 30s - -## Retry interval for bridge QoS1 message delivering. -## -## Value: Duration -bridge.mqtt.aws.retry_interval = 20s - -## Publish messages in batches, only RPC Bridge supports -## -## Value: Integer -## default: 32 -bridge.mqtt.aws.batch_size = 32 - -## Inflight size. -## -## Value: Integer -bridge.mqtt.aws.max_inflight_size = 32 - -## Base directory for replayq to store messages on disk -## If this config entry is missing or set to undefined, -## replayq works in a mem-only manner. -## -## Value: String -bridge.mqtt.aws.queue.replayq_dir = {{ platform_data_dir }}/emqx_aws_bridge/ - -## Replayq segment size -## -## Value: Bytesize -bridge.mqtt.aws.queue.replayq_seg_bytes = 10MB - -## Replayq max total size -## -## Value: Bytesize -bridge.mqtt.aws.queue.max_total_size = 5GB - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/include/emqx_bridge_mqtt.hrl b/_build/emqx/lib/emqx_bridge_mqtt/include/emqx_bridge_mqtt.hrl deleted file mode 100644 index 4bc9ede147..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/include/emqx_bridge_mqtt.hrl +++ /dev/null @@ -1,18 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --define(APP, emqx_bridge_mqtt). - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/priv/emqx_bridge_mqtt.schema b/_build/emqx/lib/emqx_bridge_mqtt/priv/emqx_bridge_mqtt.schema deleted file mode 100644 index 9e91fa0102..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/priv/emqx_bridge_mqtt.schema +++ /dev/null @@ -1,241 +0,0 @@ -%%-*- mode: erlang -*- -%%-------------------------------------------------------------------- -%% Bridges -%%-------------------------------------------------------------------- -{mapping, "bridge.mqtt.$name.address", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.proto_ver", "emqx_bridge_mqtt.bridges", [ - {datatype, {enum, [mqttv3, mqttv4, mqttv5]}} -]}. - -{mapping, "bridge.mqtt.$name.bridge_mode", "emqx_bridge_mqtt.bridges", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "bridge.mqtt.$name.start_type", "emqx_bridge_mqtt.bridges", [ - {datatype, {enum, [manual, auto]}}, - {default, auto} -]}. - -{mapping, "bridge.mqtt.$name.clientid", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.clean_start", "emqx_bridge_mqtt.bridges", [ - {default, true}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "bridge.mqtt.$name.username", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.password", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.forwards", "emqx_bridge_mqtt.bridges", [ - {datatype, string}, - {default, ""} -]}. - -{mapping, "bridge.mqtt.$name.forward_mountpoint", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.subscription.$id.topic", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.subscription.$id.qos", "emqx_bridge_mqtt.bridges", [ - {datatype, integer} -]}. - -{mapping, "bridge.mqtt.$name.receive_mountpoint", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.ssl", "emqx_bridge_mqtt.bridges", [ - {datatype, flag}, - {default, off} -]}. - -{mapping, "bridge.mqtt.$name.cacertfile", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.certfile", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.keyfile", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.ciphers", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.psk_ciphers", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.keepalive", "emqx_bridge_mqtt.bridges", [ - {default, "10s"}, - {datatype, {duration, s}} -]}. - -{mapping, "bridge.mqtt.$name.tls_versions", "emqx_bridge_mqtt.bridges", [ - {datatype, string}, - {default, "tlsv1,tlsv1.1,tlsv1.2"} -]}. - -{mapping, "bridge.mqtt.$name.reconnect_interval", "emqx_bridge_mqtt.bridges", [ - {default, "30s"}, - {datatype, {duration, ms}} -]}. - -{mapping, "bridge.mqtt.$name.retry_interval", "emqx_bridge_mqtt.bridges", [ - {default, "20s"}, - {datatype, {duration, ms}} -]}. - -{mapping, "bridge.mqtt.$name.max_inflight_size", "emqx_bridge_mqtt.bridges", [ - {default, 0}, - {datatype, integer} - ]}. - -{mapping, "bridge.mqtt.$name.batch_size", "emqx_bridge_mqtt.bridges", [ - {default, 0}, - {datatype, integer} -]}. - -{mapping, "bridge.mqtt.$name.queue.replayq_dir", "emqx_bridge_mqtt.bridges", [ - {datatype, string} -]}. - -{mapping, "bridge.mqtt.$name.queue.replayq_seg_bytes", "emqx_bridge_mqtt.bridges", [ - {datatype, bytesize} -]}. - -{mapping, "bridge.mqtt.$name.queue.max_total_size", "emqx_bridge_mqtt.bridges", [ - {datatype, bytesize} -]}. - -{translation, "emqx_bridge_mqtt.bridges", fun(Conf) -> - - MapPSKCiphers = fun(PSKCiphers) -> - lists:map( - fun("PSK-AES128-CBC-SHA") -> {psk, aes_128_cbc, sha}; - ("PSK-AES256-CBC-SHA") -> {psk, aes_256_cbc, sha}; - ("PSK-3DES-EDE-CBC-SHA") -> {psk, '3des_ede_cbc', sha}; - ("PSK-RC4-SHA") -> {psk, rc4_128, sha} - end, PSKCiphers) - end, - - Split = fun(undefined) -> undefined; (S) -> string:tokens(S, ",") end, - - IsSsl = fun(cacertfile) -> true; - (certfile) -> true; - (keyfile) -> true; - (ciphers) -> true; - (psk_ciphers) -> true; - (tls_versions) -> true; - (_Opt) -> false - end, - - Parse = fun(tls_versions, Vers) -> - [{versions, [list_to_atom(S) || S <- Split(Vers)]}]; - (ciphers, Ciphers) -> - [{ciphers, Split(Ciphers)}]; - (psk_ciphers, Ciphers) -> - [{ciphers, MapPSKCiphers(Split(Ciphers))}, {user_lookup_fun, {fun emqx_psk:lookup/3, <<>>}}]; - (Opt, Val) -> - [{Opt, Val}] - end, - - Merge = fun(forwards, Val, Opts) -> - [{forwards, string:tokens(Val, ",")}|Opts]; - (Opt, Val, Opts) -> - case IsSsl(Opt) of - true -> - SslOpts = Parse(Opt, Val) ++ proplists:get_value(ssl_opts, Opts, []), - lists:ukeymerge(1, [{ssl_opts, SslOpts}], lists:usort(Opts)); - false -> - [{Opt, Val}|Opts] - end - end, - Queue = fun(Name) -> - Configs = cuttlefish_variable:filter_by_prefix("bridge.mqtt." ++ Name ++ ".queue", Conf), - - QOpts = [{list_to_atom(QOpt), QValue}|| {[_, _, _, "queue", QOpt], QValue} <- Configs], - maps:from_list(QOpts) - end, - Subscriptions = fun(Name) -> - Configs = cuttlefish_variable:filter_by_prefix("bridge.mqtt." ++ Name ++ ".subscription", Conf), - lists:zip([Topic || {_, Topic} <- lists:sort([{I, Topic} || {[_, _, _, "subscription", I, "topic"], Topic} <- Configs])], - [QoS || {_, QoS} <- lists:sort([{I, QoS} || {[_, _, _, "subscription", I, "qos"], QoS} <- Configs])]) - end, - IsNodeAddr = fun(Addr) -> - case string:tokens(Addr, "@") of - [_NodeName, _Hostname] -> true; - _ -> false - end - end, - ConnMod = fun(Name) -> - - [AddrConfig] = cuttlefish_variable:filter_by_prefix("bridge.mqtt." ++ Name ++ ".address", Conf), - {_, Addr} = AddrConfig, - - Subs = Subscriptions(Name), - case IsNodeAddr(Addr) of - true when Subs =/= [] -> - error({"subscriptions are not supported when bridging between emqx nodes", Name, Subs}); - true -> - emqx_bridge_rpc; - false -> - emqx_bridge_mqtt - end - end, - - %% to be backward compatible - Translate = - fun Tr(queue, Q, Cfg) -> - NewQ = maps:fold(Tr, #{}, Q), - Cfg#{queue => NewQ}; - Tr(address, Addr0, Cfg) -> - Addr = case IsNodeAddr(Addr0) of - true -> list_to_atom(Addr0); - false -> Addr0 - end, - Cfg#{address => Addr}; - Tr(reconnect_interval, Ms, Cfg) -> - Cfg#{reconnect_delay_ms => Ms}; - Tr(proto_ver, Ver, Cfg) -> - Cfg#{proto_ver => - case Ver of - mqttv3 -> v3; - mqttv4 -> v4; - mqttv5 -> v5; - _ -> v4 - end}; - Tr(Key, Value, Cfg) -> - Cfg#{Key => Value} - end, - C = lists:foldl( - fun({["bridge", "mqtt", Name, Opt], Val}, Acc) -> - %% e.g #{aws => [{OptKey, OptVal}]} - Init = [{list_to_atom(Opt), Val}, - {connect_module, ConnMod(Name)}, - {subscriptions, Subscriptions(Name)}, - {queue, Queue(Name)}], - maps:update_with(list_to_atom(Name), fun(Opts) -> Merge(list_to_atom(Opt), Val, Opts) end, Init, Acc); - (_, Acc) -> Acc - end, #{}, lists:usort(cuttlefish_variable:filter_by_prefix("bridge.mqtt", Conf))), - C1 = maps:map(fun(Bn, Bc) -> - maps:to_list(maps:fold(Translate, #{}, maps:from_list(Bc))) - end, C), - maps:to_list(C1) -end}. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/rebar.config b/_build/emqx/lib/emqx_bridge_mqtt/rebar.config deleted file mode 100644 index f761e0167e..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/rebar.config +++ /dev/null @@ -1,32 +0,0 @@ -{deps, - [{replayq, {git, "https://hub.fastgit.org/emqx/replayq", {tag, "v0.1.2"}}}, - {ecpool, {git, "https://hub.fastgit.org/emqx/ecpool", {tag, "v0.4.2"}}}, - {emqtt, {git, "https://hub.fastgit.org/emqx/emqtt", {tag, "1.2.0"}}} - ]}. - -{edoc_opts, [{preprocess, true}]}. -{erl_opts, [warn_unused_vars, - warn_shadow_vars, - warn_unused_import, - warn_obsolete_guard, - debug_info, - {parse_transform}]}. - -{xref_checks, [undefined_function_calls, undefined_functions, - locals_not_used, deprecated_function_calls, - warnings_as_errors, deprecated_functions]}. -{cover_enabled, true}. -{cover_opts, [verbose]}. -{cover_export_enabled, true}. - -{shell, [ - % {config, "config/sys.config"}, - {apps, [emqx, emqx_bridge_mqtt]} -]}. - -{profiles, - [{test, - [{deps, - [{emqx_ct_helpers, {git, "https://hub.fastgit.org/emqx/emqx-ct-helpers", {tag, "1.2.2"}}}]} - ]} -]}. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/rebar.config.script b/_build/emqx/lib/emqx_bridge_mqtt/rebar.config.script deleted file mode 100644 index ad03f723bd..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/rebar.config.script +++ /dev/null @@ -1,48 +0,0 @@ -%%-*- mode: erlang -*- -%% emqx_management rebar.config.script - -CONFIG1 = case os:getenv("TRAVIS") of - "true" -> - JobId = os:getenv("TRAVIS_JOB_ID"), - [{coveralls_service_job_id, JobId}, - {coveralls_coverdata, "_build/test/cover/*.coverdata"}, - {coveralls_service_name , "travis-ci"} | CONFIG]; - _ -> - CONFIG - end, - -DEPS = case lists:keyfind(deps, 1, CONFIG1) of - {_, Deps} -> Deps; - _ -> [] - end, - -CUR_BRANCH = case os:getenv("GITHUB_RUN_ID") of - false -> - os:cmd("git branch | grep -e '^*' | cut -d' ' -f 2") -- "\n"; - _ -> - re:replace(os:getenv("GITHUB_REF"), ".*/", "", [global, {return ,list}]) - end, - -MATCH_BRANCH = fun (BranchName) -> - case re:run(BranchName, "^release|develop|master", [{capture, none}]) of - match -> BranchName; - _ -> case re:run(BranchName, "^[v]?[0-9]\.[0-9]\.([0-9]|(rc|beta|alpha)\.[0-9])", [{capture, none}]) of - match -> BranchName; - _ -> "develop" - end - end - end, - -BRANCH = MATCH_BRANCH(CUR_BRANCH), - -UrlPrefix = "https://hub.fastgit.org/emqx/", - -EMQX_DEP = {emqx, {git, UrlPrefix ++ "emqx", {branch, BRANCH}}}, - -EMQX_RULE_ENGINE = {emqx_rule_engine, {git, UrlPrefix ++ "emqx-rule-engine", {branch, BRANCH}}}, - -NewDeps = [EMQX_DEP, EMQX_RULE_ENGINE | DEPS], - -CONFIG2 = lists:keystore(deps, 1, CONFIG1, {deps, NewDeps}), - -CONFIG2. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_connect.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_connect.erl deleted file mode 100644 index 5086ca5746..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_connect.erl +++ /dev/null @@ -1,74 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_bridge_connect). - --export([start/2]). - --export_type([config/0, connection/0]). - --optional_callbacks([ensure_subscribed/3, ensure_unsubscribed/2]). - -%% map fields depend on implementation --type(config() :: map()). --type(connection() :: term()). --type(batch() :: emqx_protal:batch()). --type(ack_ref() :: emqx_bridge_worker:ack_ref()). --type(topic() :: emqx_topic:topic()). --type(qos() :: emqx_mqtt_types:qos()). - --include_lib("emqx/include/logger.hrl"). - --logger_header("[Bridge Connect]"). - -%% establish the connection to remote node/cluster -%% protal worker (the caller process) should be expecting -%% a message {disconnected, conn_ref()} when disconnected. --callback start(config()) -> {ok, connection()} | {error, any()}. - -%% send to remote node/cluster -%% bridge worker (the caller process) should be expecting -%% a message {batch_ack, reference()} when batch is acknowledged by remote node/cluster --callback send(connection(), batch()) -> {ok, ack_ref()} | {ok, integer()} | {error, any()}. - -%% called when owner is shutting down. --callback stop(connection()) -> ok. - --callback ensure_subscribed(connection(), topic(), qos()) -> ok. - --callback ensure_unsubscribed(connection(), topic()) -> ok. - -start(Module, Config) -> - case Module:start(Config) of - {ok, Conn} -> - {ok, Conn}; - {error, Reason} -> - Config1 = obfuscate(Config), - ?LOG(error, "Failed to connect with module=~p\n" - "config=~p\nreason:~p", [Module, Config1, Reason]), - {error, Reason} - end. - -obfuscate(Map) -> - maps:fold(fun(K, V, Acc) -> - case is_sensitive(K) of - true -> [{K, '***'} | Acc]; - false -> [{K, V} | Acc] - end - end, [], Map). - -is_sensitive(password) -> true; -is_sensitive(_) -> false. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.app.src b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.app.src deleted file mode 100644 index 2eaf45236f..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.app.src +++ /dev/null @@ -1,14 +0,0 @@ -{application, emqx_bridge_mqtt, - [{description, "EMQ X Bridge to MQTT Broker"}, - {vsn, "git"}, - {modules, []}, - {registered, []}, - {applications, [kernel,stdlib,replayq,emqtt]}, - {mod, {emqx_bridge_mqtt_app, []}}, - {env, []}, - {licenses, ["Apache-2.0"]}, - {maintainers, ["EMQ X Team "]}, - {links, [{"Homepage", "https://emqx.io/"}, - {"Github", "https://hub.fastgit.org/emqx/emqx-bridge-mqtt"} - ]} - ]}. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.app.src.script b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.app.src.script deleted file mode 100644 index d49efe8a0f..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.app.src.script +++ /dev/null @@ -1,25 +0,0 @@ -%%-*- mode: erlang -*- -%% .app.src.script - -RemoveLeadingV = - fun(Tag) -> - case re:run(Tag, "v\[0-9\]+\.\[0-9\]+\.*") of - nomatch -> - Tag; - {match, _} -> - %% if it is a version number prefixed by 'v' then remove the 'v' - "v" ++ Vsn = Tag, - Vsn - end - end, - -case os:getenv("EMQX_DEPS_DEFAULT_VSN") of - false -> CONFIG; % env var not defined - [] -> CONFIG; % env var set to empty string - Tag -> - [begin - AppConf0 = lists:keystore(vsn, 1, AppConf, {vsn, RemoveLeadingV(Tag)}), - {application, App, AppConf0} - end || Conf = {application, App, AppConf} <- CONFIG] -end. - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.erl deleted file mode 100644 index 1242ba2353..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt.erl +++ /dev/null @@ -1,154 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc This module implements EMQX Bridge transport layer on top of MQTT protocol - --module(emqx_bridge_mqtt). - --behaviour(emqx_bridge_connect). - -%% behaviour callbacks --export([ start/1 - , send/2 - , stop/1 - ]). - -%% optional behaviour callbacks --export([ ensure_subscribed/3 - , ensure_unsubscribed/2 - ]). - --include_lib("emqx/include/emqx_mqtt.hrl"). - --define(ACK_REF(ClientPid, PktId), {ClientPid, PktId}). - -%% Messages towards ack collector process --define(REF_IDS(Ref, Ids), {Ref, Ids}). - -%%-------------------------------------------------------------------- -%% emqx_bridge_connect callbacks -%%-------------------------------------------------------------------- - -start(Config = #{address := Address}) -> - Parent = self(), - Mountpoint = maps:get(receive_mountpoint, Config, undefined), - Handlers = make_hdlr(Parent, Mountpoint), - {Host, Port} = case string:tokens(Address, ":") of - [H] -> {H, 1883}; - [H, P] -> {H, list_to_integer(P)} - end, - ClientConfig = Config#{msg_handler => Handlers, - host => Host, - port => Port, - force_ping => true - }, - case emqtt:start_link(ClientConfig) of - {ok, Pid} -> - case emqtt:connect(Pid) of - {ok, _} -> - try - subscribe_remote_topics(Pid, maps:get(subscriptions, Config, [])), - {ok, #{client_pid => Pid}} - catch - throw : Reason -> - ok = stop(#{client_pid => Pid}), - {error, Reason} - end; - {error, Reason} -> - ok = stop(#{client_pid => Pid}), - {error, Reason} - end; - {error, Reason} -> - {error, Reason} - end. - -stop(#{client_pid := Pid}) -> - safe_stop(Pid, fun() -> emqtt:stop(Pid) end, 1000), - ok. - -ensure_subscribed(#{client_pid := Pid}, Topic, QoS) when is_pid(Pid) -> - case emqtt:subscribe(Pid, Topic, QoS) of - {ok, _, _} -> ok; - Error -> Error - end; -ensure_subscribed(_Conn, _Topic, _QoS) -> - %% return ok for now, next re-connect should should call start with new topic added to config - ok. - -ensure_unsubscribed(#{client_pid := Pid}, Topic) when is_pid(Pid) -> - case emqtt:unsubscribe(Pid, Topic) of - {ok, _, _} -> ok; - Error -> Error - end; -ensure_unsubscribed(_, _) -> - %% return ok for now, next re-connect should should call start with this topic deleted from config - ok. - -safe_stop(Pid, StopF, Timeout) -> - MRef = monitor(process, Pid), - unlink(Pid), - try - StopF() - catch - _ : _ -> - ok - end, - receive - {'DOWN', MRef, _, _, _} -> - ok - after - Timeout -> - exit(Pid, kill) - end. - -send(Conn, Msgs) -> - send(Conn, Msgs, undefined). -send(_Conn, [], PktId) -> - {ok, PktId}; -send(#{client_pid := ClientPid} = Conn, [Msg | Rest], _PktId) -> - case emqtt:publish(ClientPid, Msg) of - {ok, PktId} -> - send(Conn, Rest, PktId); - {error, Reason} -> - %% NOTE: There is no partial sucess of a batch and recover from the middle - %% only to retry all messages in one batch - {error, Reason} - end. - -handle_puback(Parent, #{packet_id := PktId, reason_code := RC}) -> - RC =:= ?RC_SUCCESS orelse error({puback_error_code, RC}), - Parent ! {batch_ack, PktId}, - ok. - -handle_publish(Msg, Mountpoint) -> - emqx_broker:publish(emqx_bridge_msg:to_broker_msg(Msg, Mountpoint)). - -handle_disconnected(Parent, Reason) -> - Parent ! {disconnected, self(), Reason}. - -make_hdlr(Parent, Mountpoint) -> - #{puback => fun(Ack) -> handle_puback(Parent, Ack) end, - publish => fun(Msg) -> handle_publish(Msg, Mountpoint) end, - disconnected => fun(Reason) -> handle_disconnected(Parent, Reason) end - }. - -subscribe_remote_topics(ClientPid, Subscriptions) -> - lists:foreach(fun({Topic, Qos}) -> - case emqtt:subscribe(ClientPid, Topic, Qos) of - {ok, _, _} -> ok; - Error -> throw(Error) - end - end, Subscriptions). diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_actions.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_actions.erl deleted file mode 100644 index 64d101cc99..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_actions.erl +++ /dev/null @@ -1,538 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc This module implements EMQX Bridge transport layer on top of MQTT protocol - --module(emqx_bridge_mqtt_actions). - --include_lib("emqx/include/emqx.hrl"). --include_lib("emqx/include/logger.hrl"). - --import(emqx_rule_utils, [str/1]). - --export([ on_resource_create/2 - , on_get_resource_status/2 - , on_resource_destroy/2 - ]). - -%% Callbacks of ecpool Worker --export([connect/1]). - --export([subscriptions/1]). - --export([on_action_create_data_to_mqtt_broker/2]). - --define(RESOURCE_TYPE_MQTT, 'bridge_mqtt'). --define(RESOURCE_TYPE_RPC, 'bridge_rpc'). - --define(RESOURCE_CONFIG_SPEC_MQTT, #{ - address => #{ - order => 1, - type => string, - required => true, - default => <<"127.0.0.1:1883">>, - title => #{en => <<" Broker Address">>, - zh => <<"远程 broker 地址"/utf8>>}, - description => #{en => <<"The MQTT Remote Address">>, - zh => <<"远程 MQTT Broker 的地址"/utf8>>} - }, - proto_ver => #{ - order => 2, - type => string, - required => false, - default => <<"mqttv4">>, - enum => [<<"mqttv3">>, <<"mqttv4">>, <<"mqttv5">>], - title => #{en => <<"Protocol Version">>, - zh => <<"协议版本"/utf8>>}, - description => #{en => <<"MQTTT Protocol version">>, - zh => <<"MQTT 协议版本"/utf8>>} - }, - disk_cache => #{ - order => 3, - type => string, - required => false, - default => <<"off">>, - enum => [<<"on">>, <<"off">>], - title => #{en => <<"Disk Cache">>, - zh => <<"磁盘缓存"/utf8>>}, - description => #{en => <<"The flag which determines whether messages" - "can be cached on local disk when bridge is" - "disconnected">>, - zh => <<"当桥接断开时用于控制是否将消息缓存到本地磁" - "盘队列上"/utf8>>} - }, - pool_size => #{ - order => 4, - type => number, - required => true, - default => 8, - title => #{en => <<"Pool Size">>, - zh => <<"连接池大小"/utf8>>}, - description => #{en => <<"MQTT Connection Pool Size">>, - zh => <<"连接池大小"/utf8>>} - }, - clientid => #{ - order => 5, - type => string, - required => false, - default => <<"client">>, - title => #{en => <<"ClientId">>, - zh => <<"客户端 Id"/utf8>>}, - description => #{en => <<"ClientId for connecting to remote MQTT broker">>, - zh => <<"连接远程 Broker 的 ClientId"/utf8>>} - }, - append => #{ - order => 6, - type => boolean, - required => false, - default => true, - title => #{en => <<"Append GUID">>, - zh => <<"附加 GUID"/utf8>>}, - description => #{en => <<"Append GUID to MQTT ClientId?">>, - zh => <<"是否将GUID附加到 MQTT ClientId 后"/utf8>>} - }, - username => #{ - order => 7, - type => string, - required => false, - default => <<"user">>, - title => #{en => <<"Username">>, zh => <<"用户名"/utf8>>}, - description => #{en => <<"Username for connecting to remote MQTT Broker">>, - zh => <<"连接远程 Broker 的用户名"/utf8>>} - }, - password => #{ - order => 8, - type => string, - required => false, - default => <<"passwd">>, - title => #{en => <<"Password">>, - zh => <<"密码"/utf8>>}, - description => #{en => <<"Password for connecting to remote MQTT Broker">>, - zh => <<"连接远程 Broker 的密码"/utf8>>} - }, - mountpoint => #{ - order => 9, - type => string, - required => true, - default => <<"bridge/aws/${node}/">>, - title => #{en => <<"Bridge MountPoint">>, - zh => <<"桥接挂载点"/utf8>>}, - description => #{ - en => <<"MountPoint for bridge topic:
      " - "Example: The topic of messages sent to `topic1` on local node" - "will be transformed to `bridge/aws/${node}/topic1`">>, - zh => <<"桥接主题的挂载点:
      " - "示例: 本地节点向 `topic1` 发消息,远程桥接节点的主题" - "会变换为 `bridge/aws/${node}/topic1`"/utf8>> - } - }, - keepalive => #{ - order => 10, - type => string, - required => true, - default => <<"60s">> , - title => #{en => <<"Keepalive">>, - zh => <<"心跳间隔"/utf8>>}, - description => #{en => <<"Keepalive">>, - zh => <<"心跳间隔"/utf8>>} - }, - reconnect_interval => #{ - order => 11, - type => string, - required => false, - default => <<"30s">>, - title => #{en => <<"Reconnect Interval">>, - zh => <<"重连间隔"/utf8>>}, - description => #{en => <<"Reconnect interval of bridge:
      ">>, - zh => <<"重连间隔"/utf8>>} - }, - retry_interval => #{ - order => 12, - type => string, - required => false, - default => <<"20s">>, - title => #{en => <<"Retry interval">>, - zh => <<"重传间隔"/utf8>>}, - description => #{en => <<"Retry interval for bridge QoS1 message delivering">>, - zh => <<"消息重传间隔"/utf8>>} - }, - bridge_mode => #{ - order => 13, - type => boolean, - required => false, - default => true, - title => #{en => <<"Bridge Mode">>, - zh => <<"桥接模式"/utf8>>}, - description => #{en => <<"Bridge mode for MQTT bridge connection">>, - zh => <<"MQTT 连接是否为桥接模式"/utf8>>} - }, - ssl => #{ - order => 14, - type => string, - required => true, - default => <<"off">>, - enum => [<<"on">>, <<"off">>], - title => #{en => <<"Bridge SSL">>, - zh => <<"Bridge SSL"/utf8>>}, - description => #{en => <<"Switch which used to enable ssl connection of the bridge">>, - zh => <<"是否启用 Bridge SSL 连接"/utf8>>} - }, - cacertfile => #{ - order => 15, - type => string, - required => false, - default => <<"etc/certs/cacert.pem">>, - title => #{en => <<"CA certificates">>, - zh => <<"CA 证书"/utf8>>}, - description => #{en => <<"The file path of the CA certificates">>, - zh => <<"CA 证书路径"/utf8>>} - }, - certfile => #{ - order => 16, - type => string, - required => false, - default => <<"etc/certs/client-cert.pem">>, - title => #{en => <<"SSL Certfile">>, - zh => <<"SSL 客户端证书"/utf8>>}, - description => #{en => <<"The file path of the client certfile">>, - zh => <<"客户端证书路径"/utf8>>} - }, - keyfile => #{ - order => 17, - type => string, - required => false, - default => <<"etc/certs/client-key.pem">>, - title => #{en => <<"SSL Keyfile">>, - zh => <<"SSL 密钥文件"/utf8>>}, - description => #{en => <<"The file path of the client keyfile">>, - zh => <<"客户端密钥路径"/utf8>>} - }, - ciphers => #{ - order => 18, - type => string, - required => false, - default => <<"ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384">>, - title => #{en => <<"SSL Ciphers">>, - zh => <<"SSL 加密算法"/utf8>>}, - description => #{en => <<"SSL Ciphers">>, - zh => <<"SSL 加密算法"/utf8>>} - } - }). - --define(RESOURCE_CONFIG_SPEC_RPC, #{ - address => #{ - order => 1, - type => string, - required => true, - default => <<"emqx2@127.0.0.1">>, - title => #{en => <<"EMQ X Node Name">>, - zh => <<"EMQ X 节点名称"/utf8>>}, - description => #{en => <<"EMQ X Remote Node Name">>, - zh => <<"远程 EMQ X 节点名称 "/utf8>>} - }, - mountpoint => #{ - order => 2, - type => string, - required => true, - default => <<"bridge/aws/${node}/">>, - title => #{en => <<"Bridge MountPoint">>, - zh => <<"桥接挂载点"/utf8>>}, - description => #{en => <<"MountPoint for bridge topic
      " - "Example: The topic of messages sent to `topic1` on local node" - "will be transformed to `bridge/aws/${node}/topic1`">>, - zh => <<"桥接主题的挂载点
      " - "示例: 本地节点向 `topic1` 发消息,远程桥接节点的主题" - "会变换为 `bridge/aws/${node}/topic1`"/utf8>>} - }, - pool_size => #{ - order => 3, - type => number, - required => true, - default => 8, - title => #{en => <<"Pool Size">>, - zh => <<"连接池大小"/utf8>>}, - description => #{en => <<"MQTT/RPC Connection Pool Size">>, - zh => <<"连接池大小"/utf8>>} - }, - reconnect_interval => #{ - order => 4, - type => string, - required => false, - default => <<"30s">>, - title => #{en => <<"Reconnect Interval">>, - zh => <<"重连间隔"/utf8>>}, - description => #{en => <<"Reconnect Interval of bridge">>, - zh => <<"重连间隔"/utf8>>} - }, - batch_size => #{ - order => 5, - type => number, - required => false, - default => 32, - title => #{en => <<"Batch Size">>, - zh => <<"批处理大小"/utf8>>}, - description => #{en => <<"Batch Size">>, - zh => <<"批处理大小"/utf8>>} - }, - disk_cache => #{ - order => 6, - type => string, - required => false, - default => <<"off">>, - enum => [<<"on">>, <<"off">>], - title => #{en => <<"Disk Cache">>, - zh => <<"磁盘缓存"/utf8>>}, - description => #{en => <<"The flag which determines whether messages" - "can be cached on local disk when bridge is" - "disconnected">>, - zh => <<"当桥接断开时用于控制是否将消息缓存到本地磁" - "盘队列上"/utf8>>} - } - }). - --define(ACTION_PARAM_RESOURCE, #{ - type => string, - required => true, - title => #{en => <<"Resource ID">>, zh => <<"资源 ID"/utf8>>}, - description => #{en => <<"Bind a resource to this action">>, - zh => <<"给动作绑定一个资源"/utf8>>} - }). - --resource_type(#{ - name => ?RESOURCE_TYPE_MQTT, - create => on_resource_create, - status => on_get_resource_status, - destroy => on_resource_destroy, - params => ?RESOURCE_CONFIG_SPEC_MQTT, - title => #{en => <<"MQTT Bridge">>, zh => <<"MQTT Bridge"/utf8>>}, - description => #{en => <<"MQTT Message Bridge">>, zh => <<"MQTT 消息桥接"/utf8>>} - }). - --resource_type(#{ - name => ?RESOURCE_TYPE_RPC, - create => on_resource_create, - status => on_get_resource_status, - destroy => on_resource_destroy, - params => ?RESOURCE_CONFIG_SPEC_RPC, - title => #{en => <<"EMQX Bridge">>, zh => <<"EMQX Bridge"/utf8>>}, - description => #{en => <<"EMQ X RPC Bridge">>, zh => <<"EMQ X RPC 消息桥接"/utf8>>} - }). - --rule_action(#{ - name => data_to_mqtt_broker, - for => 'message.publish', - types => [?RESOURCE_TYPE_MQTT, ?RESOURCE_TYPE_RPC], - create => on_action_create_data_to_mqtt_broker, - params => #{'$resource' => ?ACTION_PARAM_RESOURCE, - payload_tmpl => #{ - order => 1, - type => string, - input => textarea, - required => false, - default => <<"">>, - title => #{en => <<"Payload Template">>, - zh => <<"消息内容模板"/utf8>>}, - description => #{en => <<"The payload template, variable interpolation is supported. If using empty template (default), then the payload will be all the available vars in JOSN format">>, - zh => <<"消息内容模板,支持变量。若使用空模板(默认),消息内容为 JSON 格式的所有字段"/utf8>>} - }}, - title => #{en => <<"Data bridge to MQTT Broker">>, - zh => <<"桥接数据到 MQTT Broker"/utf8>>}, - description => #{en => <<"Bridge Data to MQTT Broker">>, - zh => <<"桥接数据到 MQTT Broker"/utf8>>} - }). - -on_resource_create(ResId, Params) -> - ?LOG(info, "Initiating Resource ~p, ResId: ~p", [?RESOURCE_TYPE_MQTT, ResId]), - {ok, _} = application:ensure_all_started(ecpool), - PoolName = pool_name(ResId), - Options = options(Params, PoolName), - start_resource(ResId, PoolName, Options), - case test_resource_status(PoolName) of - true -> ok; - false -> - on_resource_destroy(ResId, #{<<"pool">> => PoolName}), - error({{?RESOURCE_TYPE_MQTT, ResId}, connection_failed}) - end, - #{<<"pool">> => PoolName}. - -start_resource(ResId, PoolName, Options) -> - case ecpool:start_sup_pool(PoolName, ?MODULE, Options) of - {ok, _} -> - ?LOG(info, "Initiated Resource ~p Successfully, ResId: ~p", [?RESOURCE_TYPE_MQTT, ResId]); - {error, {already_started, _Pid}} -> - on_resource_destroy(ResId, #{<<"pool">> => PoolName}), - start_resource(ResId, PoolName, Options); - {error, Reason} -> - ?LOG(error, "Initiate Resource ~p failed, ResId: ~p, ~p", [?RESOURCE_TYPE_MQTT, ResId, Reason]), - on_resource_destroy(ResId, #{<<"pool">> => PoolName}), - error({{?RESOURCE_TYPE_MQTT, ResId}, create_failed}) - end. - -test_resource_status(PoolName) -> - IsConnected = fun(Worker) -> - case ecpool_worker:client(Worker) of - {ok, Bridge} -> - try emqx_bridge_worker:status(Bridge) of - connected -> true; - _ -> false - catch _Error:_Reason -> - false - end; - {error, _} -> - false - end - end, - Status = [IsConnected(Worker) || {_WorkerName, Worker} <- ecpool:workers(PoolName)], - lists:any(fun(St) -> St =:= true end, Status). - --spec(on_get_resource_status(ResId::binary(), Params::map()) -> Status::map()). -on_get_resource_status(_ResId, #{<<"pool">> := PoolName}) -> - IsAlive = test_resource_status(PoolName), - #{is_alive => IsAlive}. - -on_resource_destroy(ResId, #{<<"pool">> := PoolName}) -> - ?LOG(info, "Destroying Resource ~p, ResId: ~p", [?RESOURCE_TYPE_MQTT, ResId]), - case ecpool:stop_sup_pool(PoolName) of - ok -> - ?LOG(info, "Destroyed Resource ~p Successfully, ResId: ~p", [?RESOURCE_TYPE_MQTT, ResId]); - {error, Reason} -> - ?LOG(error, "Destroy Resource ~p failed, ResId: ~p, ~p", [?RESOURCE_TYPE_MQTT, ResId, Reason]), - error({{?RESOURCE_TYPE_MQTT, ResId}, destroy_failed}) - end. - -on_action_create_data_to_mqtt_broker(_Id, #{<<"pool">> := PoolName, - <<"payload_tmpl">> := PayloadTmpl}) -> - ?LOG(info, "Initiating Action ~p.", [?FUNCTION_NAME]), - PayloadTks = emqx_rule_utils:preproc_tmpl(PayloadTmpl), - fun(Msg, _Env = #{id := Id, clientid := From, flags := Flags, - topic := Topic, timestamp := TimeStamp}) -> - BrokerMsg = #message{id = Id, - qos = 1, - from = From, - flags = Flags, - topic = Topic, - payload = format_data(PayloadTks, Msg), - timestamp = TimeStamp}, - ecpool:with_client(PoolName, fun(BridgePid) -> - BridgePid ! {deliver, rule_engine, BrokerMsg} - end) - end. - -format_data([], Msg) -> - emqx_json:encode(Msg); - -format_data(Tokens, Msg) -> - emqx_rule_utils:proc_tmpl(Tokens, Msg). - -tls_versions() -> - ['tlsv1.2','tlsv1.1', tlsv1]. - -ciphers(Ciphers) -> - string:tokens(str(Ciphers), ", "). - -subscriptions(Subscriptions) -> - scan_binary(<<"[", Subscriptions/binary, "].">>). - -is_node_addr(Addr0) -> - Addr = binary_to_list(Addr0), - case string:tokens(Addr, "@") of - [_NodeName, _Hostname] -> true; - _ -> false - end. - -scan_binary(Bin) -> - TermString = binary_to_list(Bin), - scan_string(TermString). - -scan_string(TermString) -> - {ok, Tokens, _} = erl_scan:string(TermString), - {ok, Term} = erl_parse:parse_term(Tokens), - Term. - -connect(Options) when is_list(Options) -> - connect(maps:from_list(Options)); -connect(Options = #{disk_cache := DiskCache, ecpool_worker_id := Id, pool_name := Pool}) -> - Options0 = case DiskCache of - true -> - DataDir = filename:join([emqx:get_env(data_dir), replayq]), - QueueOption = #{replayq_dir => DataDir}, - Options#{queue => QueueOption}; - false -> - Options - end, - Options1 = case maps:is_key(append, Options0) of - false -> Options0; - true -> - case maps:get(append, Options0, false) of - true -> - ClientId = lists:concat([str(maps:get(clientid, Options0)), "_", str(emqx_guid:to_hexstr(emqx_guid:gen()))]), - Options0#{clientid => ClientId}; - false -> - Options0 - end - end, - Options2 = maps:without([ecpool_worker_id, pool_name, append], Options1), - emqx_bridge_worker:start_link(name(Pool, Id), Options2). -name(Pool, Id) -> - list_to_atom(atom_to_list(Pool) ++ ":" ++ integer_to_list(Id)). -pool_name(ResId) -> - list_to_atom("bridge_mqtt:" ++ str(ResId)). - -options(Options, PoolName) -> - GetD = fun(Key, Default) -> maps:get(Key, Options, Default) end, - Get = fun(Key) -> GetD(Key, undefined) end, - Address = Get(<<"address">>), - [{max_inflight_batches, 32}, - {forward_mountpoint, str(Get(<<"mountpoint">>))}, - {disk_cache, cuttlefish_flag:parse(str(Get(<<"disk_cache">>)))}, - {start_type, auto}, - {reconnect_delay_ms, cuttlefish_duration:parse(str(Get(<<"reconnect_interval">>)), ms)}, - {if_record_metrics, false}, - {pool_size, GetD(<<"pool_size">>, 1)}, - {pool_name, PoolName} - ] ++ case is_node_addr(Address) of - true -> - [{address, binary_to_atom(Get(<<"address">>), utf8)}, - {connect_module, emqx_bridge_rpc}, - {batch_size, Get(<<"batch_size">>)}]; - false -> - [{address, binary_to_list(Address)}, - {bridge_mode, GetD(<<"bridge_mode">>, true)}, - {clean_start, true}, - {clientid, str(Get(<<"clientid">>))}, - {append, Get(<<"append">>)}, - {connect_module, emqx_bridge_mqtt}, - {keepalive, cuttlefish_duration:parse(str(Get(<<"keepalive">>)), s)}, - {username, str(Get(<<"username">>))}, - {password, str(Get(<<"password">>))}, - {proto_ver, mqtt_ver(Get(<<"proto_ver">>))}, - {retry_interval, cuttlefish_duration:parse(str(Get(<<"retry_interval">>)), ms)}, - {ssl, cuttlefish_flag:parse(str(Get(<<"ssl">>)))}, - {ssl_opts, [{versions, tls_versions()}, - {ciphers, ciphers(Get(<<"ciphers">>))}, - {keyfile, str(Get(<<"keyfile">>))}, - {certfile, str(Get(<<"certfile">>))}, - {cacertfile, str(Get(<<"cacertfile">>))} - ]}] - end. - -mqtt_ver(ProtoVer) -> - case ProtoVer of - <<"mqttv3">> -> v3; - <<"mqttv4">> -> v4; - <<"mqttv5">> -> v5; - _ -> v4 - end. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_app.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_app.erl deleted file mode 100644 index 2c0a0b9a9a..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_app.erl +++ /dev/null @@ -1,33 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_bridge_mqtt_app). - --emqx_plugin(bridge). - --behaviour(application). - --export([start/2, stop/1]). - -start(_StartType, _StartArgs) -> - emqx_ctl:register_command(bridges, {emqx_bridge_mqtt_cli, cli}, []), - emqx_bridge_worker:register_metrics(), - emqx_bridge_mqtt_sup:start_link(). - -stop(_State) -> - emqx_ctl:unregister_command(bridges), - ok. - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_cli.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_cli.erl deleted file mode 100644 index 1ee5a90c60..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_cli.erl +++ /dev/null @@ -1,98 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_bridge_mqtt_cli). - --include("emqx_bridge_mqtt.hrl"). - --import(lists, [foreach/2]). - --export([cli/1]). - -cli(["list"]) -> - foreach(fun({Name, State0}) -> - State = case State0 of - connected -> <<"Running">>; - _ -> <<"Stopped">> - end, - emqx_ctl:print("name: ~s status: ~s~n", [Name, State]) - end, emqx_bridge_mqtt_sup:bridges()); - -cli(["start", Name]) -> - emqx_ctl:print("~s.~n", [try emqx_bridge_worker:ensure_started(Name) of - ok -> <<"Start bridge successfully">>; - connected -> <<"Bridge already started">>; - _ -> <<"Start bridge failed">> - catch - _Error:_Reason -> - <<"Start bridge failed">> - end]); - -cli(["stop", Name]) -> - emqx_ctl:print("~s.~n", [try emqx_bridge_worker:ensure_stopped(Name) of - ok -> <<"Stop bridge successfully">>; - _ -> <<"Stop bridge failed">> - catch - _Error:_Reason -> - <<"Stop bridge failed">> - end]); - -cli(["forwards", Name]) -> - foreach(fun(Topic) -> - emqx_ctl:print("topic: ~s~n", [Topic]) - end, emqx_bridge_worker:get_forwards(Name)); - -cli(["add-forward", Name, Topic]) -> - case emqx_bridge_worker:ensure_forward_present(Name, iolist_to_binary(Topic)) of - ok -> emqx_ctl:print("Add-forward topic successfully.~n"); - {error, Reason} -> emqx_ctl:print("Add-forward failed reason: ~p.~n", [Reason]) - end; - -cli(["del-forward", Name, Topic]) -> - case emqx_bridge_worker:ensure_forward_absent(Name, iolist_to_binary(Topic)) of - ok -> emqx_ctl:print("Del-forward topic successfully.~n"); - {error, Reason} -> emqx_ctl:print("Del-forward failed reason: ~p.~n", [Reason]) - end; - -cli(["subscriptions", Name]) -> - foreach(fun({Topic, Qos}) -> - emqx_ctl:print("topic: ~s, qos: ~p~n", [Topic, Qos]) - end, emqx_bridge_worker:get_subscriptions(Name)); - -cli(["add-subscription", Name, Topic, Qos]) -> - case emqx_bridge_worker:ensure_subscription_present(Name, Topic, list_to_integer(Qos)) of - ok -> emqx_ctl:print("Add-subscription topic successfully.~n"); - {error, Reason} -> emqx_ctl:print("Add-subscription failed reason: ~p.~n", [Reason]) - end; - -cli(["del-subscription", Name, Topic]) -> - case emqx_bridge_worker:ensure_subscription_absent(Name, Topic) of - ok -> emqx_ctl:print("Del-subscription topic successfully.~n"); - {error, Reason} -> emqx_ctl:print("Del-subscription failed reason: ~p.~n", [Reason]) - end; - -cli(_) -> - emqx_ctl:usage([{"bridges list", "List bridges"}, - {"bridges start ", "Start a bridge"}, - {"bridges stop ", "Stop a bridge"}, - {"bridges forwards ", "Show a bridge forward topic"}, - {"bridges add-forward ", "Add bridge forward topic"}, - {"bridges del-forward ", "Delete bridge forward topic"}, - {"bridges subscriptions ", "Show a bridge subscriptions topic"}, - {"bridges add-subscription ", "Add bridge subscriptions topic"}, - {"bridges del-subscription ", "Delete bridge subscriptions topic"}]). - - diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_sup.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_sup.erl deleted file mode 100644 index 92d8e40838..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_mqtt_sup.erl +++ /dev/null @@ -1,84 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_bridge_mqtt_sup). --behaviour(supervisor). - --include("emqx_bridge_mqtt.hrl"). --include_lib("emqx/include/logger.hrl"). - --logger_header("[Bridge]"). - -%% APIs --export([ start_link/0 - , start_link/1 - ]). - --export([ create_bridge/2 - , drop_bridge/1 - , bridges/0 - , is_bridge_exist/1 - ]). - -%% supervisor callbacks --export([init/1]). - --define(SUP, ?MODULE). --define(WORKER_SUP, emqx_bridge_worker_sup). - -start_link() -> start_link(?SUP). - -start_link(Name) -> - supervisor:start_link({local, Name}, ?MODULE, Name). - -init(?SUP) -> - BridgesConf = application:get_env(?APP, bridges, []), - BridgeSpec = lists:map(fun bridge_spec/1, BridgesConf), - SupFlag = #{strategy => one_for_one, - intensity => 100, - period => 10}, - {ok, {SupFlag, BridgeSpec}}. - -bridge_spec({Name, Config}) -> - #{id => Name, - start => {emqx_bridge_worker, start_link, [Name, Config]}, - restart => permanent, - shutdown => 5000, - type => worker, - modules => [emqx_bridge_worker]}. - --spec(bridges() -> [{node(), map()}]). -bridges() -> - [{Name, emqx_bridge_worker:status(Pid)} || {Name, Pid, _, _} <- supervisor:which_children(?SUP)]. - --spec(is_bridge_exist(atom() | pid()) -> boolean()). -is_bridge_exist(Id) -> - case supervisor:get_childspec(?SUP, Id) of - {ok, _ChildSpec} -> true; - {error, _Error} -> false - end. - -create_bridge(Id, Config) -> - supervisor:start_child(?SUP, bridge_spec({Id, Config})). - -drop_bridge(Id) -> - case supervisor:terminate_child(?SUP, Id) of - ok -> - supervisor:delete_child(?SUP, Id); - {error, Error} -> - ?LOG(error, "Delete bridge failed, error : ~p", [Error]), - {error, Error} - end. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_msg.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_msg.erl deleted file mode 100644 index 84bd90c5ac..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_msg.erl +++ /dev/null @@ -1,97 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --module(emqx_bridge_msg). - --export([ to_binary/1 - , from_binary/1 - , to_export/3 - , to_broker_msgs/1 - , to_broker_msg/1 - , to_broker_msg/2 - , estimate_size/1 - ]). - --export_type([msg/0]). - --include_lib("emqx/include/emqx.hrl"). - --include_lib("emqx_bridge_mqtt/include/emqx_bridge_mqtt.hrl"). --include_lib("emqtt/include/emqtt.hrl"). - - --type msg() :: emqx_types:message(). --type exp_msg() :: emqx_types:message() | #mqtt_msg{}. - -%% @doc Make export format: -%% 1. Mount topic to a prefix -%% 2. Fix QoS to 1 -%% @end -%% Shame that we have to know the callback module here -%% would be great if we can get rid of #mqtt_msg{} record -%% and use #message{} in all places. --spec to_export(emqx_bridge_rpc | emqx_bridge_worker, - undefined | binary(), msg()) -> exp_msg(). -to_export(emqx_bridge_mqtt, Mountpoint, - #message{topic = Topic, - payload = Payload, - flags = Flags - }) -> - Retain = maps:get(retain, Flags, false), - #mqtt_msg{qos = ?QOS_1, - retain = Retain, - topic = topic(Mountpoint, Topic), - payload = Payload}; -to_export(_Module, Mountpoint, - #message{topic = Topic} = Msg) -> - Msg#message{topic = topic(Mountpoint, Topic), qos = 1}. - -%% @doc Make `binary()' in order to make iodata to be persisted on disk. --spec to_binary(msg()) -> binary(). -to_binary(Msg) -> term_to_binary(Msg). - -%% @doc Unmarshal binary into `msg()'. --spec from_binary(binary()) -> msg(). -from_binary(Bin) -> binary_to_term(Bin). - -%% @doc Estimate the size of a message. -%% Count only the topic length + payload size --spec estimate_size(msg()) -> integer(). -estimate_size(#message{topic = Topic, payload = Payload}) -> - size(Topic) + size(Payload). - -%% @doc By message/batch receiver, transform received batch into -%% messages to deliver to local brokers. -to_broker_msgs(Batch) -> lists:map(fun to_broker_msg/1, Batch). - -to_broker_msg(#message{} = Msg) -> - %% internal format from another EMQX node via rpc - Msg; -to_broker_msg(Msg) -> - to_broker_msg(Msg, undefined). -to_broker_msg(#{qos := QoS, dup := Dup, retain := Retain, topic := Topic, - properties := Props, payload := Payload}, Mountpoint) -> - %% published from remote node over a MQTT connection - set_headers(Props, - emqx_message:set_flags(#{dup => Dup, retain => Retain}, - emqx_message:make(bridge, QoS, topic(Mountpoint, Topic), Payload))). - -set_headers(undefined, Msg) -> - Msg; -set_headers(Val, Msg) -> - emqx_message:set_headers(Val, Msg). -topic(undefined, Topic) -> Topic; -topic(Prefix, Topic) -> emqx_topic:prepend(Prefix, Topic). diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_rpc.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_rpc.erl deleted file mode 100644 index 92ef0c60a6..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_rpc.erl +++ /dev/null @@ -1,99 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc This module implements EMQX Bridge transport layer based on gen_rpc. - --module(emqx_bridge_rpc). - --behaviour(emqx_bridge_connect). - -%% behaviour callbacks --export([ start/1 - , send/2 - , stop/1 - ]). - -%% Internal exports --export([ handle_send/1 - , heartbeat/2 - ]). - --type ack_ref() :: emqx_bridge_worker:ack_ref(). --type batch() :: emqx_bridge_worker:batch(). - --define(HEARTBEAT_INTERVAL, timer:seconds(1)). - --define(RPC, emqx_rpc). - -start(#{address := Remote}) -> - case poke(Remote) of - ok -> - Pid = proc_lib:spawn_link(?MODULE, heartbeat, [self(), Remote]), - {ok, #{client_pid => Pid, address => Remote}}; - Error -> - Error - end. - -stop(#{client_pid := Pid}) when is_pid(Pid) -> - Ref = erlang:monitor(process, Pid), - unlink(Pid), - Pid ! stop, - receive - {'DOWN', Ref, process, Pid, _Reason} -> - ok - after - 1000 -> - exit(Pid, kill) - end, - ok. - -%% @doc Callback for `emqx_bridge_connect' behaviour --spec send(node(), batch()) -> {ok, ack_ref()} | {error, any()}. -send(#{address := Remote}, Batch) -> - case ?RPC:call(Remote, ?MODULE, handle_send, [Batch]) of - ok -> - Ref = make_ref(), - self() ! {batch_ack, Ref}, - {ok, Ref}; - {badrpc, Reason} -> {error, Reason} - end. - -%% @doc Handle send on receiver side. --spec handle_send(batch()) -> ok. -handle_send(Batch) -> - lists:foreach(fun(Msg) -> emqx_broker:publish(Msg) end, Batch). - -%% @hidden Heartbeat loop -heartbeat(Parent, RemoteNode) -> - Interval = ?HEARTBEAT_INTERVAL, - receive - stop -> exit(normal) - after - Interval -> - case poke(RemoteNode) of - ok -> - ?MODULE:heartbeat(Parent, RemoteNode); - {error, Reason} -> - Parent ! {disconnected, self(), Reason}, - exit(normal) - end - end. - -poke(Node) -> - case ?RPC:call(Node, erlang, node, []) of - Node -> ok; - {badrpc, Reason} -> {error, Reason} - end. diff --git a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_worker.erl b/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_worker.erl deleted file mode 100644 index 2078fe41af..0000000000 --- a/_build/emqx/lib/emqx_bridge_mqtt/src/emqx_bridge_worker.erl +++ /dev/null @@ -1,595 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - -%% @doc Bridge works in two layers (1) batching layer (2) transport layer -%% The `bridge' batching layer collects local messages in batches and sends over -%% to remote MQTT node/cluster via `connetion' transport layer. -%% In case `REMOTE' is also an EMQX node, `connection' is recommended to be -%% the `gen_rpc' based implementation `emqx_bridge_rpc'. Otherwise `connection' -%% has to be `emqx_bridge_mqtt'. -%% -%% ``` -%% +------+ +--------+ -%% | EMQX | | REMOTE | -%% | | | | -%% | (bridge) <==(connection)==> | | -%% | | | | -%% | | | | -%% +------+ +--------+ -%% ''' -%% -%% -%% This module implements 2 kinds of APIs with regards to batching and -%% messaging protocol. (1) A `gen_statem' based local batch collector; -%% (2) APIs for incoming remote batches/messages. -%% -%% Batch collector state diagram -%% -%% [idle] --(0) --> [connecting] --(2)--> [connected] -%% | ^ | -%% | | | -%% '--(1)---'--------(3)------' -%% -%% (0): auto or manual start -%% (1): retry timeout -%% (2): successfuly connected to remote node/cluster -%% (3): received {disconnected, Reason} OR -%% failed to send to remote node/cluster. -%% -%% NOTE: A bridge worker may subscribe to multiple (including wildcard) -%% local topics, and the underlying `emqx_bridge_connect' may subscribe to -%% multiple remote topics, however, worker/connections are not designed -%% to support automatic load-balancing, i.e. in case it can not keep up -%% with the amount of messages comming in, administrator should split and -%% balance topics between worker/connections manually. -%% -%% NOTES: -%% * Local messages are all normalised to QoS-1 when exporting to remote - --module(emqx_bridge_worker). --behaviour(gen_statem). - -%% APIs --export([ start_link/1 - , start_link/2 - , register_metrics/0 - , stop/1 - ]). - -%% gen_statem callbacks --export([ terminate/3 - , code_change/4 - , init/1 - , callback_mode/0 - ]). - -%% state functions --export([ idle/3 - , connected/3 - ]). - -%% management APIs --export([ ensure_started/1 - , ensure_stopped/1 - , ensure_stopped/2 - , status/1 - ]). - --export([ get_forwards/1 - , ensure_forward_present/2 - , ensure_forward_absent/2 - ]). - --export([ get_subscriptions/1 - , ensure_subscription_present/3 - , ensure_subscription_absent/2 - ]). - --export_type([ config/0 - , batch/0 - , ack_ref/0 - ]). - --type id() :: atom() | string() | pid(). --type qos() :: emqx_mqtt_types:qos(). --type config() :: map(). --type batch() :: [emqx_bridge_msg:exp_msg()]. --type ack_ref() :: term(). --type topic() :: emqx_topic:topic(). - --include_lib("emqx/include/logger.hrl"). --include_lib("emqx/include/emqx_mqtt.hrl"). - --logger_header("[Bridge]"). - -%% same as default in-flight limit for emqtt --define(DEFAULT_BATCH_SIZE, 32). --define(DEFAULT_RECONNECT_DELAY_MS, timer:seconds(5)). --define(DEFAULT_SEG_BYTES, (1 bsl 20)). --define(DEFAULT_MAX_TOTAL_SIZE, (1 bsl 31)). --define(NO_BRIDGE_HANDLER, undefined). - -%% @doc Start a bridge worker. Supported configs: -%% start_type: 'manual' (default) or 'auto', when manual, bridge will stay -%% at 'idle' state until a manual call to start it. -%% connect_module: The module which implements emqx_bridge_connect behaviour -%% and work as message batch transport layer -%% reconnect_delay_ms: Delay in milli-seconds for the bridge worker to retry -%% in case of transportation failure. -%% max_inflight_batches: Max number of batches allowed to send-ahead before -%% receiving confirmation from remote node/cluster -%% mountpoint: The topic mount point for messages sent to remote node/cluster -%% `undefined', `<<>>' or `""' to disable -%% forwards: Local topics to subscribe. -%% queue.batch_bytes_limit: Max number of bytes to collect in a batch for each -%% send call towards emqx_bridge_connect -%% queue.batch_count_limit: Max number of messages to collect in a batch for -%% each send call towards emqx_bridge_connect -%% queue.replayq_dir: Directory where replayq should persist messages -%% queue.replayq_seg_bytes: Size in bytes for each replayq segment file -%% -%% Find more connection specific configs in the callback modules -%% of emqx_bridge_connect behaviour. -start_link(Config) when is_list(Config) -> - start_link(maps:from_list(Config)); -start_link(Config) -> - gen_statem:start_link(?MODULE, Config, []). - -start_link(Name, Config) when is_list(Config) -> - start_link(Name, maps:from_list(Config)); -start_link(Name, Config) -> - Name1 = name(Name), - gen_statem:start_link({local, Name1}, ?MODULE, Config#{name => Name1}, []). - -ensure_started(Name) -> - gen_statem:call(name(Name), ensure_started). - -%% @doc Manually stop bridge worker. State idempotency ensured. -ensure_stopped(Id) -> - ensure_stopped(Id, 1000). - -ensure_stopped(Id, Timeout) -> - Pid = case id(Id) of - P when is_pid(P) -> P; - N -> whereis(N) - end, - case Pid of - undefined -> - ok; - _ -> - MRef = monitor(process, Pid), - unlink(Pid), - _ = gen_statem:call(id(Id), ensure_stopped, Timeout), - receive - {'DOWN', MRef, _, _, _} -> - ok - after - Timeout -> - exit(Pid, kill) - end - end. - -stop(Pid) -> gen_statem:stop(Pid). - -status(Pid) when is_pid(Pid) -> - gen_statem:call(Pid, status); -status(Id) -> - gen_statem:call(name(Id), status). - -%% @doc Return all forwards (local subscriptions). --spec get_forwards(id()) -> [topic()]. -get_forwards(Id) -> gen_statem:call(id(Id), get_forwards, timer:seconds(1000)). - -%% @doc Return all subscriptions (subscription over mqtt connection to remote broker). --spec get_subscriptions(id()) -> [{emqx_topic:topic(), qos()}]. -get_subscriptions(Id) -> gen_statem:call(id(Id), get_subscriptions). - -%% @doc Add a new forward (local topic subscription). --spec ensure_forward_present(id(), topic()) -> ok. -ensure_forward_present(Id, Topic) -> - gen_statem:call(id(Id), {ensure_present, forwards, topic(Topic)}). - -%% @doc Ensure a forward topic is deleted. --spec ensure_forward_absent(id(), topic()) -> ok. -ensure_forward_absent(Id, Topic) -> - gen_statem:call(id(Id), {ensure_absent, forwards, topic(Topic)}). - -%% @doc Ensure subscribed to remote topic. -%% NOTE: only applicable when connection module is emqx_bridge_mqtt -%% return `{error, no_remote_subscription_support}' otherwise. --spec ensure_subscription_present(id(), topic(), qos()) -> ok | {error, any()}. -ensure_subscription_present(Id, Topic, QoS) -> - gen_statem:call(id(Id), {ensure_present, subscriptions, {topic(Topic), QoS}}). - -%% @doc Ensure unsubscribed from remote topic. -%% NOTE: only applicable when connection module is emqx_bridge_mqtt --spec ensure_subscription_absent(id(), topic()) -> ok. -ensure_subscription_absent(Id, Topic) -> - gen_statem:call(id(Id), {ensure_absent, subscriptions, topic(Topic)}). - -callback_mode() -> [state_functions]. - -%% @doc Config should be a map(). -init(Config) -> - erlang:process_flag(trap_exit, true), - ConnectModule = maps:get(connect_module, Config), - Subscriptions = maps:get(subscriptions, Config, []), - Forwards = maps:get(forwards, Config, []), - Queue = open_replayq(Config), - State = init_opts(Config), - Topics = [iolist_to_binary(T) || T <- Forwards], - Subs = check_subscriptions(Subscriptions), - ConnectConfig = get_conn_cfg(Config), - ConnectFun = fun(SubsX) -> - emqx_bridge_connect:start(ConnectModule, ConnectConfig#{subscriptions => SubsX}) - end, - self() ! idle, - {ok, idle, State#{connect_module => ConnectModule, - connect_fun => ConnectFun, - forwards => Topics, - subscriptions => Subs, - replayq => Queue - }}. - -init_opts(Config) -> - IfRecordMetrics = maps:get(if_record_metrics, Config, true), - ReconnDelayMs = maps:get(reconnect_delay_ms, Config, ?DEFAULT_RECONNECT_DELAY_MS), - StartType = maps:get(start_type, Config, manual), - BridgeHandler = maps:get(bridge_handler, Config, ?NO_BRIDGE_HANDLER), - Mountpoint = maps:get(forward_mountpoint, Config, undefined), - ReceiveMountpoint = maps:get(receive_mountpoint, Config, undefined), - MaxInflightSize = maps:get(max_inflight_batches, Config, ?DEFAULT_BATCH_SIZE), - BatchSize = maps:get(batch_size, Config, ?DEFAULT_BATCH_SIZE), - Name = maps:get(name, Config, undefined), - #{start_type => StartType, - reconnect_delay_ms => ReconnDelayMs, - batch_size => BatchSize, - mountpoint => format_mountpoint(Mountpoint), - receive_mountpoint => ReceiveMountpoint, - inflight => [], - max_inflight => MaxInflightSize, - connection => undefined, - bridge_handler => BridgeHandler, - if_record_metrics => IfRecordMetrics, - name => Name}. - -open_replayq(Config) -> - QCfg = maps:get(queue, Config, #{}), - Dir = maps:get(replayq_dir, QCfg, undefined), - SegBytes = maps:get(replayq_seg_bytes, QCfg, ?DEFAULT_SEG_BYTES), - MaxTotalSize = maps:get(max_total_size, QCfg, ?DEFAULT_MAX_TOTAL_SIZE), - QueueConfig = case Dir =:= undefined orelse Dir =:= "" of - true -> #{mem_only => true}; - false -> #{dir => Dir, seg_bytes => SegBytes, max_total_size => MaxTotalSize} - end, - replayq:open(QueueConfig#{sizer => fun emqx_bridge_msg:estimate_size/1, - marshaller => fun msg_marshaller/1}). - -check_subscriptions(Subscriptions) -> - lists:map(fun({Topic, QoS}) -> - Topic1 = iolist_to_binary(Topic), - true = emqx_topic:validate({filter, Topic1}), - {Topic1, QoS} - end, Subscriptions). - -get_conn_cfg(Config) -> - maps:without([connect_module, - queue, - reconnect_delay_ms, - forwards, - mountpoint, - name - ], Config). - -code_change(_Vsn, State, Data, _Extra) -> - {ok, State, Data}. - -terminate(_Reason, _StateName, #{replayq := Q} = State) -> - _ = disconnect(State), - _ = replayq:close(Q), - ok. - -%% ensure_started will be deprecated in the future -idle({call, From}, ensure_started, State) -> - case do_connect(State) of - {ok, State1} -> - {next_state, connected, State1, [{reply, From, ok}, {state_timeout, 0, connected}]}; - {error, Reason} -> - {keep_state_and_data, [{reply, From, {error, Reason}}]} - end; -%% @doc Standing by for manual start. -idle(info, idle, #{start_type := manual}) -> - keep_state_and_data; -%% @doc Standing by for auto start. -idle(info, idle, #{start_type := auto} = State) -> - connecting(State); -idle(state_timeout, reconnect, State) -> - connecting(State); - -idle(info, {batch_ack, Ref}, State) -> - case do_ack(State, Ref) of - {ok, NewState} -> - {keep_state, NewState}; - _ -> - keep_state_and_data - end; - -idle(Type, Content, State) -> - common(idle, Type, Content, State). - -connecting(#{reconnect_delay_ms := ReconnectDelayMs} = State) -> - case do_connect(State) of - {ok, State1} -> - {next_state, connected, State1, {state_timeout, 0, connected}}; - _ -> - {keep_state_and_data, {state_timeout, ReconnectDelayMs, reconnect}} - end. - -connected(state_timeout, connected, #{inflight := Inflight} = State) -> - case retry_inflight(State, Inflight) of - {ok, NewState} -> - {keep_state, NewState, {next_event, internal, maybe_send}}; - {error, NewState} -> - {keep_state, NewState} - end; -connected(internal, maybe_send, State) -> - {_, NewState} = pop_and_send(State), - {keep_state, NewState}; - -connected(info, {disconnected, Conn, Reason}, - #{connection := Connection, name := Name, reconnect_delay_ms := ReconnectDelayMs} = State) -> - case Conn =:= maps:get(client_pid, Connection, undefined) of - true -> - ?LOG(info, "Bridge ~p diconnected~nreason=~p", [Name, Reason]), - {next_state, idle, State#{connection => undefined}, {state_timeout, ReconnectDelayMs, reconnect}}; - false -> - keep_state_and_data - end; -connected(info, {batch_ack, Ref}, State) -> - case do_ack(State, Ref) of - {ok, NewState} -> - {keep_state, NewState, {next_event, internal, maybe_send}}; - _ -> - keep_state_and_data - end; -connected(Type, Content, State) -> - common(connected, Type, Content, State). - -%% Common handlers -common(StateName, {call, From}, status, _State) -> - {keep_state_and_data, [{reply, From, StateName}]}; -common(_StateName, {call, From}, ensure_started, _State) -> - {keep_state_and_data, [{reply, From, connected}]}; -common(_StateName, {call, From}, ensure_stopped, _State) -> - {stop_and_reply, {shutdown, manual}, [{reply, From, ok}]}; -common(_StateName, {call, From}, get_forwards, #{forwards := Forwards}) -> - {keep_state_and_data, [{reply, From, Forwards}]}; -common(_StateName, {call, From}, get_subscriptions, #{subscriptions := Subs}) -> - {keep_state_and_data, [{reply, From, Subs}]}; -common(_StateName, {call, From}, {ensure_present, What, Topic}, State) -> - {Result, NewState} = ensure_present(What, Topic, State), - {keep_state, NewState, [{reply, From, Result}]}; -common(_StateName, {call, From}, {ensure_absent, What, Topic}, State) -> - {Result, NewState} = ensure_absent(What, Topic, State), - {keep_state, NewState, [{reply, From, Result}]}; -common(_StateName, info, {deliver, _, Msg}, #{replayq := Q, if_record_metrics := IfRecordMetric} = State) -> - bridges_metrics_inc(IfRecordMetric, 'bridge.mqtt.message_received'), - NewQ = replayq:append(Q, collect([Msg])), - {keep_state, State#{replayq => NewQ}, {next_event, internal, maybe_send}}; -common(_StateName, info, {'EXIT', _, _}, State) -> - {keep_state, State}; -common(StateName, Type, Content, #{name := Name} = State) -> - ?LOG(notice, "Bridge ~p discarded ~p type event at state ~p:~p", - [Name, Type, StateName, Content]), - {keep_state, State}. - -eval_bridge_handler(State = #{bridge_handler := ?NO_BRIDGE_HANDLER}, _Msg) -> - State; -eval_bridge_handler(State = #{bridge_handler := Handler}, Msg) -> - Handler(Msg), - State. - -ensure_present(Key, Topic, State) -> - Topics = maps:get(Key, State), - case is_topic_present(Topic, Topics) of - true -> - {ok, State}; - false -> - R = do_ensure_present(Key, Topic, State), - {R, State#{Key := lists:usort([Topic | Topics])}} - end. - -ensure_absent(Key, Topic, State) -> - Topics = maps:get(Key, State), - case is_topic_present(Topic, Topics) of - true -> - R = do_ensure_absent(Key, Topic, State), - {R, State#{Key := ensure_topic_absent(Topic, Topics)}}; - false -> - {ok, State} - end. - -ensure_topic_absent(_Topic, []) -> []; -ensure_topic_absent(Topic, [{_, _} | _] = L) -> lists:keydelete(Topic, 1, L); -ensure_topic_absent(Topic, L) -> lists:delete(Topic, L). - -is_topic_present({Topic, _QoS}, Topics) -> - is_topic_present(Topic, Topics); -is_topic_present(Topic, Topics) -> - lists:member(Topic, Topics) orelse false =/= lists:keyfind(Topic, 1, Topics). - -do_connect(#{forwards := Forwards, - subscriptions := Subs, - connect_fun := ConnectFun, - name := Name} = State) -> - ok = subscribe_local_topics(Forwards, Name), - case ConnectFun(Subs) of - {ok, Conn} -> - ?LOG(info, "Bridge ~p is connecting......", [Name]), - {ok, eval_bridge_handler(State#{connection => Conn}, connected)}; - {error, Reason} -> - {error, Reason, State} - end. - -do_ensure_present(forwards, Topic, #{name := Name}) -> - subscribe_local_topic(Topic, Name); -do_ensure_present(subscriptions, _Topic, #{connection := undefined}) -> - {error, no_connection}; -do_ensure_present(subscriptions, _Topic, #{connect_module := emqx_bridge_rpc}) -> - {error, no_remote_subscription_support}; -do_ensure_present(subscriptions, {Topic, QoS}, #{connect_module := ConnectModule, - connection := Conn}) -> - ConnectModule:ensure_subscribed(Conn, Topic, QoS). - -do_ensure_absent(forwards, Topic, _) -> - do_unsubscribe(Topic); -do_ensure_absent(subscriptions, _Topic, #{connection := undefined}) -> - {error, no_connection}; -do_ensure_absent(subscriptions, _Topic, #{connect_module := emqx_bridge_rpc}) -> - {error, no_remote_subscription_support}; -do_ensure_absent(subscriptions, Topic, #{connect_module := ConnectModule, - connection := Conn}) -> - ConnectModule:ensure_unsubscribed(Conn, Topic). - -collect(Acc) -> - receive - {deliver, _, Msg} -> - collect([Msg | Acc]) - after - 0 -> - lists:reverse(Acc) - end. - -%% Retry all inflight (previously sent but not acked) batches. -retry_inflight(State, []) -> {ok, State}; -retry_inflight(State, [#{q_ack_ref := QAckRef, batch := Batch} | Inflight]) -> - case do_send(State#{inflight := Inflight}, QAckRef, Batch) of - {ok, State1} -> retry_inflight(State1, Inflight); - {error, State1} -> {error, State1} - end. - -pop_and_send(#{inflight := Inflight, max_inflight := Max } = State) when length(Inflight) >= Max -> - {ok, State}; -pop_and_send(#{replayq := Q, connect_module := Module} = State) -> - case replayq:is_empty(Q) of - true -> - {ok, State}; - false -> - BatchSize = case Module of - emqx_bridge_rpc -> maps:get(batch_size, State); - _ -> 1 - end, - Opts = #{count_limit => BatchSize, bytes_limit => 999999999}, - {Q1, QAckRef, Batch} = replayq:pop(Q, Opts), - do_send(State#{replayq := Q1}, QAckRef, Batch) - end. - -%% Assert non-empty batch because we have a is_empty check earlier. -do_send(#{inflight := Inflight, - connect_module := Module, - connection := Connection, - mountpoint := Mountpoint, - if_record_metrics := IfRecordMetrics} = State, QAckRef, Batch) -> - ExportMsg = fun(Message) -> - bridges_metrics_inc(IfRecordMetrics, 'bridge.mqtt.message_sent'), - emqx_bridge_msg:to_export(Module, Mountpoint, Message) - end, - case Module:send(Connection, [ExportMsg(M) || M <- Batch]) of - {ok, Ref} -> - {ok, State#{inflight := Inflight ++ [#{q_ack_ref => QAckRef, - send_ack_ref => Ref, - batch => Batch}]}}; - {error, Reason} -> - ?LOG(info, "Batch produce failed~p", [Reason]), - {error, State} - end. - - -do_ack(#{inflight := []} = State, Ref) -> - ?LOG(error, "Can't be found from the inflight:~p", [Ref]), - {ok, State}; - -do_ack(#{inflight := [#{send_ack_ref := Ref, - q_ack_ref := QAckRef}| Rest], replayq := Q} = State, Ref) -> - ok = replayq:ack(Q, QAckRef), - {ok, State#{inflight => Rest}}; - -do_ack(#{inflight := [#{q_ack_ref := QAckRef, - batch := Batch}| Rest], replayq := Q} = State, Ref) -> - ok = replayq:ack(Q, QAckRef), - NewQ = replayq:append(Q, Batch), - do_ack(State#{replayq => NewQ, inflight => Rest}, Ref). - -subscribe_local_topics(Topics, Name) -> - lists:foreach(fun(Topic) -> subscribe_local_topic(Topic, Name) end, Topics). - -subscribe_local_topic(Topic, Name) -> - do_subscribe(Topic, Name). - -topic(T) -> iolist_to_binary(T). - -validate(RawTopic) -> - Topic = topic(RawTopic), - try emqx_topic:validate(Topic) of - _Success -> Topic - catch - error:Reason -> - error({bad_topic, Topic, Reason}) - end. - -do_subscribe(RawTopic, Name) -> - TopicFilter = validate(RawTopic), - {Topic, SubOpts} = emqx_topic:parse(TopicFilter, #{qos => ?QOS_1}), - emqx_broker:subscribe(Topic, Name, SubOpts). - -do_unsubscribe(RawTopic) -> - TopicFilter = validate(RawTopic), - {Topic, _SubOpts} = emqx_topic:parse(TopicFilter), - emqx_broker:unsubscribe(Topic). - -disconnect(#{connection := Conn, - connect_module := Module - } = State) when Conn =/= undefined -> - Module:stop(Conn), - State0 = State#{connection => undefined}, - eval_bridge_handler(State0, disconnected); -disconnect(State) -> - eval_bridge_handler(State, disconnected). - -%% Called only when replayq needs to dump it to disk. -msg_marshaller(Bin) when is_binary(Bin) -> emqx_bridge_msg:from_binary(Bin); -msg_marshaller(Msg) -> emqx_bridge_msg:to_binary(Msg). - -format_mountpoint(undefined) -> - undefined; -format_mountpoint(Prefix) -> - binary:replace(iolist_to_binary(Prefix), <<"${node}">>, atom_to_binary(node(), utf8)). - -name(Id) -> list_to_atom(lists:concat([?MODULE, "_", Id])). - -id(Pid) when is_pid(Pid) -> Pid; -id(Name) -> name(Name). - -register_metrics() -> - lists:foreach(fun emqx_metrics:ensure/1, - ['bridge.mqtt.message_sent', - 'bridge.mqtt.message_received' - ]). - -bridges_metrics_inc(true, Metric) -> - emqx_metrics:inc(Metric); -bridges_metrics_inc(_IsRecordMetric, _Metric) -> - ok. diff --git a/_build/emqx/lib/emqx_dashboard/.github/workflows/run_test_cases.yaml b/_build/emqx/lib/emqx_dashboard/.github/workflows/run_test_cases.yaml deleted file mode 100644 index b8e7225704..0000000000 --- a/_build/emqx/lib/emqx_dashboard/.github/workflows/run_test_cases.yaml +++ /dev/null @@ -1,29 +0,0 @@ -name: Run test cases - -on: [push, pull_request] - -jobs: - run_test_cases: - runs-on: ubuntu-latest - - container: - image: erlang:22.1 - - steps: - - uses: actions/checkout@v1 - - name: run test cases - run: | - make xref - make eunit - make ct - make cover - - uses: actions/upload-artifact@v1 - if: always() - with: - name: logs - path: _build/test/logs - - uses: actions/upload-artifact@v1 - with: - name: cover - path: _build/test/cover - diff --git a/_build/emqx/lib/emqx_dashboard/.gitignore b/_build/emqx/lib/emqx_dashboard/.gitignore deleted file mode 100644 index d19e1b7d5e..0000000000 --- a/_build/emqx/lib/emqx_dashboard/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -.eunit -deps -*.o -*.beam -*.plt -erl_crash.dump -ebin -rel/example_project -.concrete/DEV_MODE -.rebar -.erlang.mk/ -ct.coverdata -logs/ -test/ct.cover.spec -data/ -.DS_Store -emqx_dashboard.d -cover/ -eunit.coverdata -.DS_Store -erlang.mk -rebar.lock -_build/ -*.conf.rendered -.rebar3/ diff --git a/_build/emqx/lib/emqx_dashboard/LICENSE b/_build/emqx/lib/emqx_dashboard/LICENSE deleted file mode 100644 index 8dada3edaf..0000000000 --- a/_build/emqx/lib/emqx_dashboard/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/_build/emqx/lib/emqx_dashboard/Makefile b/_build/emqx/lib/emqx_dashboard/Makefile deleted file mode 100644 index bb8fb570fa..0000000000 --- a/_build/emqx/lib/emqx_dashboard/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -## shallow clone for speed - -REBAR_GIT_CLONE_OPTIONS += --depth 1 -export REBAR_GIT_CLONE_OPTIONS - -REBAR = rebar3 -all: compile - -compile: - $(REBAR) compile - -clean: distclean - -ct: compile - $(REBAR) as test ct -v - -eunit: compile - $(REBAR) as test eunit - -xref: - $(REBAR) xref - -cover: - $(REBAR) cover - -distclean: - @rm -rf _build - @rm -f data/app.*.config data/vm.*.args rebar.lock diff --git a/_build/emqx/lib/emqx_dashboard/README.md b/_build/emqx/lib/emqx_dashboard/README.md deleted file mode 100644 index e9e50a7c96..0000000000 --- a/_build/emqx/lib/emqx_dashboard/README.md +++ /dev/null @@ -1,88 +0,0 @@ - -emqx-dashboard -============== - -Dashboard for the EMQ X Broker. - -REST API --------- - -The prefix of REST API is '/api/v4/'. - -Method | Path | Description --------|---------------------------------------|------------------------------------ -GET | /nodes/ | A list of nodes in the cluster -GET | /nodes/:node | Lookup a node in the cluster -GET | /brokers/ | A list of brokers in the cluster -GET | /brokers/:node | Get broker info of a node -GET | /metrics/ | A list of metrics of all nodes in the cluster -GET | /nodes/:node/metrics/ | A list of metrics of a node -GET | /stats/ | A list of stats of all nodes in the cluster -GET | /nodes/:node/stats/ | A list of stats of a node -GET | /nodes/:node/clients/ | A list of clients on a node -GET | /listeners/ | A list of listeners in the cluster -GET | /nodes/:node/listeners | A list of listeners on the node -GET | /nodes/:node/sessions/ | A list of sessions on a node -GET | /subscriptions/:clientid | A list of subscriptions of a client -GET | /nodes/:node/subscriptions/:clientid | A list of subscriptions of a client on the node -GET | /nodes/:node/subscriptions/ | A list of subscriptions on a node -PUT | /clients/:clientid/clean_acl_cache | Clean ACL cache of a client -GET | /configs/ | Get all configs -GET | /nodes/:node/configs/ | Get all configs of a node -GET | /nodes/:node/plugin_configs/:plugin | Get configurations of a plugin on the node -DELETE | /clients/:clientid | Kick out a client -GET | /alarms/:node | List alarms of a node -GET | /alarms/ | List all alarms -GET | /plugins/ | List all plugins in the cluster -GET | /nodes/:node/plugins/ | List all plugins on a node -GET | /routes/ | List routes -POST | /nodes/:node/plugins/:plugin/load | Load a plugin -GET | /clients/:clientid | Lookup a client in the cluster -GET | nodes/:node/clients/:clientid | Lookup a client on node -GET | nodes/:node/sessions/:clientid | Lookup a session in the cluster -GET | nodes/:node/sessions/:clientid | Lookup a session on the node -POST | /mqtt/publish | Publish a MQTT message -POST | /mqtt/subscribe | Subscribe a topic -POST | /nodes/:node/plugins/:plugin/unload | Unload a plugin -POST | /mqtt/unsubscribe | Unsubscribe a topic -PUT | /configs/:app | Update config of an application in the cluster -PUT | /nodes/:node/configs/:app | Update config of an application on a node -PUT | /nodes/:node/plugin_configs/:plugin | Update configurations of a plugin on the node - -Build ------ - -make && make ct - -Configurtion ------------- - -``` -dashboard.listener = 18083 - -dashboard.listener.acceptors = 2 - -dashboard.listener.max_clients = 512 -``` - -Load Plugin ------------ - -``` -./bin/emqx_ctl plugins load emqx_dashboard -``` - -Login ------ - -URL: http://host:18083 - -Username: admin - -Password: public - -License -------- - -Apache License Version 2.0 - diff --git a/_build/emqx/lib/emqx_dashboard/etc/emqx_dashboard.conf b/_build/emqx/lib/emqx_dashboard/etc/emqx_dashboard.conf deleted file mode 100644 index 7c2125b4ce..0000000000 --- a/_build/emqx/lib/emqx_dashboard/etc/emqx_dashboard.conf +++ /dev/null @@ -1,129 +0,0 @@ -##-------------------------------------------------------------------- -## EMQ X Dashboard -##-------------------------------------------------------------------- - -## Default user's login name. -## -## Value: String -dashboard.default_user.login = admin - -## Default user's password. -## -## Value: String -dashboard.default_user.password = public - -##-------------------------------------------------------------------- -## HTTP Listener - -## The port that the Dashboard HTTP listener will bind. -## -## Value: Port -## -## Examples: 18083 -dashboard.listener.http = 18083 - -## The acceptor pool for external Dashboard HTTP listener. -## -## Value: Number -dashboard.listener.http.acceptors = 4 - -## Maximum number of concurrent Dashboard HTTP connections. -## -## Value: Number -dashboard.listener.http.max_clients = 512 - -## Set up the socket for IPv6. -## -## Value: false | true -dashboard.listener.http.inet6 = false - -## Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -## -## Value: false | true -dashboard.listener.http.ipv6_v6only = false - -##-------------------------------------------------------------------- -## HTTPS Listener - -## The port that the Dashboard HTTPS listener will bind. -## -## Value: Port -## -## Examples: 18084 -## dashboard.listener.https = 18084 - -## The acceptor pool for external Dashboard HTTPS listener. -## -## Value: Number -## dashboard.listener.https.acceptors = 2 - -## Maximum number of concurrent Dashboard HTTPS connections. -## -## Value: Number -## dashboard.listener.https.max_clients = 512 - -## Set up the socket for IPv6. -## -## Value: false | true -## dashboard.listener.https.inet6 = false - -## Listen on IPv4 and IPv6 (false) or only on IPv6 (true). Use with inet6. -## -## Value: false | true -## dashboard.listener.https.ipv6_v6only = false - -## Path to the file containing the user's private PEM-encoded key. -## -## Value: File -## dashboard.listener.https.keyfile = etc/certs/key.pem - -## Path to a file containing the user certificate. -## -## Value: File -## dashboard.listener.https.certfile = etc/certs/cert.pem - -## Path to the file containing PEM-encoded CA certificates. -## -## Value: File -## dashboard.listener.https.cacertfile = etc/certs/cacert.pem - -## See: 'listener.ssl..dhfile' in emq.conf -## -## Value: File -## dashboard.listener.https.dhfile = {{ platform_etc_dir }}/certs/dh-params.pem - -## See: 'listener.ssl..vefify' in emq.conf -## -## Value: vefify_peer | verify_none -## dashboard.listener.https.verify = verify_peer - -## See: 'listener.ssl..fail_if_no_peer_cert' in emq.conf -## -## Value: false | true -## dashboard.listener.https.fail_if_no_peer_cert = true - -## TLS versions only to protect from POODLE attack. -## -## Value: String, seperated by ',' -## dashboard.listener.https.tls_versions = tlsv1.2,tlsv1.1,tlsv1 - -## See: 'listener.ssl..ciphers' in emq.conf -## -## Value: Ciphers -## dashboard.listener.https.ciphers = ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-RSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES256-SHA384,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-DES-CBC3-SHA,ECDH-ECDSA-AES256-GCM-SHA384,ECDH-RSA-AES256-GCM-SHA384,ECDH-ECDSA-AES256-SHA384,ECDH-RSA-AES256-SHA384,DHE-DSS-AES256-GCM-SHA384,DHE-DSS-AES256-SHA256,AES256-GCM-SHA384,AES256-SHA256,ECDHE-ECDSA-AES128-GCM-SHA256,ECDHE-RSA-AES128-GCM-SHA256,ECDHE-ECDSA-AES128-SHA256,ECDHE-RSA-AES128-SHA256,ECDH-ECDSA-AES128-GCM-SHA256,ECDH-RSA-AES128-GCM-SHA256,ECDH-ECDSA-AES128-SHA256,ECDH-RSA-AES128-SHA256,DHE-DSS-AES128-GCM-SHA256,DHE-DSS-AES128-SHA256,AES128-GCM-SHA256,AES128-SHA256,ECDHE-ECDSA-AES256-SHA,ECDHE-RSA-AES256-SHA,DHE-DSS-AES256-SHA,ECDH-ECDSA-AES256-SHA,ECDH-RSA-AES256-SHA,AES256-SHA,ECDHE-ECDSA-AES128-SHA,ECDHE-RSA-AES128-SHA,DHE-DSS-AES128-SHA,ECDH-ECDSA-AES128-SHA,ECDH-RSA-AES128-SHA,AES128-SHA - -## See: 'listener.ssl..secure_renegotiate' in emq.conf -## -## Value: on | off -## dashboard.listener.https.secure_renegotiate = off - -## See: 'listener.ssl..reuse_sessions' in emq.conf -## -## Value: on | off -## dashboard.listener.https.reuse_sessions = on - -## See: 'listener.ssl..honor_cipher_order' in emq.conf -## -## Value: on | off -## dashboard.listener.https.honor_cipher_order = on - diff --git a/_build/emqx/lib/emqx_dashboard/include/emqx_dashboard.hrl b/_build/emqx/lib/emqx_dashboard/include/emqx_dashboard.hrl deleted file mode 100644 index 73b64de77b..0000000000 --- a/_build/emqx/lib/emqx_dashboard/include/emqx_dashboard.hrl +++ /dev/null @@ -1,21 +0,0 @@ -%%-------------------------------------------------------------------- -%% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved. -%% -%% Licensed under the Apache License, Version 2.0 (the "License"); -%% you may not use this file except in compliance with the License. -%% You may obtain a copy of the License at -%% -%% http://www.apache.org/licenses/LICENSE-2.0 -%% -%% Unless required by applicable law or agreed to in writing, software -%% distributed under the License is distributed on an "AS IS" BASIS, -%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -%% See the License for the specific language governing permissions and -%% limitations under the License. -%%-------------------------------------------------------------------- - --record(mqtt_admin, {username, password, tags}). - --type(mqtt_admin() :: #mqtt_admin{}). - --define(EMPTY_KEY(Key), ((Key == undefined) orelse (Key == <<>>))). diff --git a/_build/emqx/lib/emqx_dashboard/priv/emqx_dashboard.schema b/_build/emqx/lib/emqx_dashboard/priv/emqx_dashboard.schema deleted file mode 100644 index fcc8f3489b..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/emqx_dashboard.schema +++ /dev/null @@ -1,151 +0,0 @@ -%%-*- mode: erlang -*- -%% emqx_dashboard config mapping - -{mapping, "dashboard.default_user.login", "emqx_dashboard.default_user_username", [ - {datatype, string} -]}. - -{mapping, "dashboard.default_user.password", "emqx_dashboard.default_user_passwd", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.http", "emqx_dashboard.listeners", [ - {datatype, integer} -]}. - -{mapping, "dashboard.listener.http.acceptors", "emqx_dashboard.listeners", [ - {default, 4}, - {datatype, integer} -]}. - -{mapping, "dashboard.listener.http.max_clients", "emqx_dashboard.listeners", [ - {default, 512}, - {datatype, integer} -]}. - -{mapping, "dashboard.listener.http.access.$id", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.http.inet6", "emqx_dashboard.listeners", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "dashboard.listener.http.ipv6_v6only", "emqx_dashboard.listeners", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "dashboard.listener.https", "emqx_dashboard.listeners", [ - {datatype, integer} -]}. - -{mapping, "dashboard.listener.https.acceptors", "emqx_dashboard.listeners", [ - {default, 8}, - {datatype, integer} -]}. - -{mapping, "dashboard.listener.https.max_clients", "emqx_dashboard.listeners", [ - {default, 64}, - {datatype, integer} -]}. - -{mapping, "dashboard.listener.https.inet6", "emqx_dashboard.listeners", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "dashboard.listener.https.ipv6_v6only", "emqx_dashboard.listeners", [ - {default, false}, - {datatype, {enum, [true, false]}} -]}. - -{mapping, "dashboard.listener.https.tls_versions", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.dhfile", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.keyfile", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.certfile", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.cacertfile", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.verify", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.fail_if_no_peer_cert", "emqx_dashboard.listeners", [ - {datatype, {enum, [true, false]}} -]}. - -{mapping, "dashboard.listener.https.ciphers", "emqx_dashboard.listeners", [ - {datatype, string} -]}. - -{mapping, "dashboard.listener.https.secure_renegotiate", "emqx_dashboard.listeners", [ - {datatype, flag} -]}. - -{mapping, "dashboard.listener.https.reuse_sessions", "emqx_dashboard.listeners", [ - {default, on}, - {datatype, flag} -]}. - -{mapping, "dashboard.listener.https.honor_cipher_order", "emqx_dashboard.listeners", [ - {datatype, flag} -]}. - -{translation, "emqx_dashboard.listeners", fun(Conf) -> - Filter = fun(Opts) -> [{K, V} || {K, V} <- Opts, V =/= undefined] end, - LisOpts = fun(Prefix) -> - Filter([{num_acceptors, cuttlefish:conf_get(Prefix ++ ".acceptors", Conf)}, - {max_connections, cuttlefish:conf_get(Prefix ++ ".max_clients", Conf)}, - {inet6, cuttlefish:conf_get(Prefix ++ ".inet6", Conf)}, - {ipv6_v6only, cuttlefish:conf_get(Prefix ++ ".ipv6_v6only", Conf)}]) - end, - - SplitFun = fun(undefined) -> undefined; (S) -> string:tokens(S, ",") end, - - SslOpts = fun(Prefix) -> - Versions = case SplitFun(cuttlefish:conf_get(Prefix ++ ".tls_versions", Conf, undefined)) of - undefined -> undefined; - L -> [list_to_atom(V) || V <- L] - end, - Filter([{versions, Versions}, - {ciphers, SplitFun(cuttlefish:conf_get(Prefix ++ ".ciphers", Conf, undefined))}, - {dhfile, cuttlefish:conf_get(Prefix ++ ".dhfile", Conf, undefined)}, - {keyfile, cuttlefish:conf_get(Prefix ++ ".keyfile", Conf, undefined)}, - {certfile, cuttlefish:conf_get(Prefix ++ ".certfile", Conf, undefined)}, - {cacertfile, cuttlefish:conf_get(Prefix ++ ".cacertfile", Conf, undefined)}, - {verify, cuttlefish:conf_get(Prefix ++ ".verify", Conf, undefined)}, - {fail_if_no_peer_cert, cuttlefish:conf_get(Prefix ++ ".fail_if_no_peer_cert", Conf, undefined)}, - {secure_renegotiate, cuttlefish:conf_get(Prefix ++ ".secure_renegotiate", Conf, undefined)}, - {reuse_sessions, cuttlefish:conf_get(Prefix ++ ".reuse_sessions", Conf, undefined)}, - {honor_cipher_order, cuttlefish:conf_get(Prefix ++ ".honor_cipher_order", Conf, undefined)}]) - end, - lists:append( - lists:map( - fun(Proto) -> - Prefix = "dashboard.listener." ++ atom_to_list(Proto), - case cuttlefish:conf_get(Prefix, Conf, undefined) of - undefined -> []; - Port -> - [{Proto, Port, case Proto of - http -> LisOpts(Prefix); - https -> LisOpts(Prefix) ++ SslOpts(Prefix) - end}] - end - end, [http, https])) -end}. - diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/index.html b/_build/emqx/lib/emqx_dashboard/priv/www/index.html deleted file mode 100644 index ab62f41c7b..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/index.html +++ /dev/null @@ -1,3 +0,0 @@ -Dashboard
      \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/app.12f4f66ae641529e280c71b264d96730.css b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/app.12f4f66ae641529e280c71b264d96730.css deleted file mode 100644 index 32e69d406a..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/app.12f4f66ae641529e280c71b264d96730.css +++ /dev/null @@ -1 +0,0 @@ -.login-view{width:100%;height:100%;background-color:#181818}.login-view .el-card{width:420px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.login-view .el-card .el-card__header{font-size:16px}.login-view .error input{border:2px solid #e0b4b4}.login-view .login-footer{margin-top:40px;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center}.home-view{box-sizing:border-box;min-height:100%}.home-view .home-content{margin:0 32px 0 212px;padding:60px 0 20px}.left-bar{position:fixed;top:0;bottom:0;width:180px;z-index:1002;overflow-y:auto;overflow-x:hidden;padding-top:140px;padding-bottom:45px;background-color:#242327;box-shadow:0 0 15px #0b0b0b}.left-bar .iconfont{margin-right:8px;font-size:18px}.left-bar .bar-title{position:fixed;top:0;z-index:1003;width:180px;border-bottom:1px solid #2b2c30;color:#fff!important;background-color:#242327;text-align:center;padding:24px 0}.left-bar .bar-title h3{font-size:18px;margin:0;color:#fff}.left-bar .bar-title img{width:60px;height:60px;margin-bottom:8px}.left-bar .bar-footer{position:fixed;bottom:0;width:180px;z-index:1003;padding-left:20px;height:47px;line-height:47px;background:inherit;border-top:1px solid #2b2c30;color:#fff!important}.left-bar .bar-footer span{font-size:16px;font-weight:bolder;margin-right:12px;vertical-align:middle}.left-bar .bar-footer a{font-weight:700}.left-bar .bar-footer a img{width:20px;height:20px;border:none;vertical-align:middle}.left-bar .el-menu{width:180px;min-height:100%;border-right:none!important}.left-bar .el-submenu__title{padding-left:27px!important;height:40px;line-height:40px}.left-bar .el-submenu .el-menu-item{width:157px!important;min-width:0;margin-left:11px}.left-bar .el-menu-item{height:36px!important;line-height:36px!important;background-color:#8f8e8e;color:#929299!important;border-radius:4px;width:168px;margin-left:7px;margin-bottom:4px;margin-top:4px;transition:border-color .3s,background-color .3s,color .3s,box-shadow .3s}.left-bar .el-menu-item:hover{color:#fff!important;background-color:#393a3e!important}.left-bar .el-menu-item:hover i{color:#fff!important}.left-bar .el-menu-item.is-active{color:#fff!important;background-color:#00b173!important;box-shadow:0 0 5px 0 #02d48a}.left-bar .el-menu-item.is-active i{color:#fff!important}.left-bar .last-item{margin-bottom:72px}.left-bar .menu-dot .el-badge__content.is-fixed.is-dot{top:17px;right:0}.left-bar .submenu-dot .el-badge__content.is-fixed.is-dot{right:3px;top:14px}.topbar{height:60px;line-height:60px;padding-left:110px;position:fixed;top:0;left:0;right:0;z-index:4}.topbar .top-area{background-color:#242327;height:100%;padding:0 32px;text-align:right}.topbar .top-area .topbar-right .help-link{display:inline;line-height:32px}.topbar .top-area .topbar-right .help-link .link{display:inline-block;color:#82858f;padding:0 20px;border-right:1px solid #2b2c30;position:relative;top:3px}.topbar .top-area .topbar-right .help-link .link .icon-bangzhu{font-size:20px}.topbar .top-area .topbar-right .help-link a.active{color:#34c388}.topbar .top-area .topbar-right .el-button{width:135px;border-radius:40px;border-width:2px;margin-left:20px;font-size:14px;font-weight:400;line-height:15px;background:transparent}.topbar .top-area .topbar-right .el-button.enterprise-btn{color:#34c388;border-color:#34c388}.topbar .top-area .topbar-right .el-button.enterprise-btn .icon-arrow{position:relative;top:1px}.topbar .top-area .topbar-right .el-button.github-btn{color:#adafb4;border-color:#adafb4}.topbar .top-area .topbar-right .el-button .iconfont{margin-left:5px}.topbar .top-area .topbar-right .el-button--medium{padding:9px 20px}.overview-view *{padding:0;margin:0;box-sizing:border-box}.overview-view .el-select .el-input__inner{padding-left:10px}.overview-view .card-box{position:relative;margin-top:74px}.overview-view .card-box .card-title{position:absolute;height:24px;line-height:24px;width:100%;top:-34px;left:0;font-size:16px}.overview-view .card-box .el-table{margin-top:0}.overview-view .card-box .el-table .caret-wrapper{left:-8px}.overview-view .card-box .el-table--medium td,.overview-view .card-box .stats-table.el-table--medium th{padding:4px 0}@media screen and (max-width:1280px){.overview-view .card-box .el-col-6{width:50%!important;margin-top:10px!important}}@media screen and (max-width:740px){.overview-view .card-box .el-col-6{width:100%!important;margin-top:10px!important}}.overview-view .card-box .broker-card.el-row{overflow-x:auto}.overview-view .card-box .broker-card .el-col .card-item{height:90px;min-width:250px;line-height:90px;padding:18px 20px 0;border-radius:4px}.overview-view .card-box .broker-card .el-col .card-item .icon{float:left;width:54px;height:54px;line-height:50px;text-align:center;border:2px solid;border-radius:50%}.overview-view .card-box .broker-card .el-col .card-item .icon i{font-size:26px}.overview-view .card-box .broker-card .el-col .card-item .desc{line-height:normal;float:right;text-align:right;height:70px}.overview-view .card-box .broker-card .el-col .card-item .desc h3{font-size:14px;font-weight:700}.overview-view .card-box .broker-card .el-col .card-item .desc p{margin-top:12px;max-width:150px}.overview-view span{line-height:10px}.overview-view .box-card,.overview-view .el-row{margin-top:20px}.overview-view .iconfont{position:relative}.data-view .el-table{margin-top:24px}.data-view .el-row{margin-top:20px}.data-view .el-input{width:240px}.data-view .search-btn{margin-left:8px}.data-view .el-breadcrumb{margin-top:10px;margin-bottom:20px}.data-view .el-pagination .el-select .el-input .el-input__inner{height:22px}.data-view .el-select .el-input .el-select__caret{line-height:12px}.data-view .search-card{margin-top:24px;border:none}.data-view .search-card .el-card__body{padding:5px 12px}.data-view .search-card .el-input,.data-view .search-card .el-select{width:100%}.data-view .search-card .el-input--medium .el-input__inner{height:32px!important}.data-view .search-card .col-share{position:absolute;bottom:-13px}.data-view .search-card .col-oper{float:right;position:relative;top:1px;margin-bottom:10px}.data-view .search-card .col-oper .show-more{margin:0 10px;font-size:12px}.data-view .search-card .form-item-row{margin-top:0}.data-view .search-card .form-item-row .el-select.comparator .el-input--medium .el-input__inner,.data-view .search-card .form-item-row .el-select.match .el-input--medium .el-input__inner{border-radius:4px 0 0 4px}.data-view .search-card .form-item-row .el-input__inner{border-radius:0 4px 4px 0}.data-view .search-card .el-select .el-input .el-select__caret{line-height:36px}.data-view .custom-pagination{margin-top:10px}.data-view .custom-pagination a{transition:all .3s ease;color:#fff;margin-right:10px;background:#42d885;display:inline-block;border-radius:4px;padding:5px 8px}.data-view .custom-pagination a:hover{color:#fff}.data-view .custom-pagination a.disabled{transition:all .3s ease;color:#606266;background:transparent;cursor:not-allowed}.clients-view .client-oper{float:right;margin-top:-32px;color:#adafb4}.clients-view .client-oper .connect-btn{border:1px solid;background:transparent;margin-left:20px;min-width:80px;font-size:14px;font-weight:400}.clients-view .client-oper .connect-btn.disconnected{border-color:#ff6d6d;color:#ff6d6d}.clients-view .client-oper .connect-btn.connected{border-color:#adafb4;color:#adafb4}.clients-view .client-oper .connect-btn:hover{background:transparent!important}.clients-view .el-card.tabs-card{border-radius:0 0 4px 4px}.clients-view .el-card .el-card__body{padding:10px 36px}.clients-view .card-subtitle{font-size:16px;margin:24px 0}.clients-basic .clients-basic-form .form-item-desc{color:#5f6067;margin-left:20px;font-size:14px}.clients-basic .clients-basic-form .el-form-item__content{color:#f8f8f8}.clients-basic .clients-basic-form .el-form-item{margin-bottom:12px}.clients-basic .view-more{margin:24px 0;font-size:14px}.clients-subscriptions .oper-btn-group{text-align:right;margin:24px 0}.clients-subscriptions .client-sub-table{margin-bottom:24px}.clients-subscriptions .el-select--public{width:100%}.clients-subscriptions .el-select--public .el-input__inner{height:32px!important;line-height:32px!important}.rules-view .el-table{margin-top:24px}.rules-view .status-wrapper{padding:0;list-style-type:none}.rules-view .status-wrapper .status-item{padding:2px 6px}.rules-view .status-wrapper .status-item>span{margin-right:12px}.rules-view span[type=info]{padding-right:20px}.rules-view span[type=info]>span{margin-left:6px;color:#333;font-weight:600;border-bottom:1px dashed #d8d8d8}.rules-view span[type=info]>span:hover{font-weight:800}.rule-actions .status-wrapper .status-item,.rule-actions .status-wrapper .title{margin-bottom:10px}.rule-actions .status-wrapper .key{width:120px;display:inline-block}.rule-actions .action-item{margin:2px auto}.rule-actions .action-card{font-size:14px;margin-bottom:24px}.rule-actions .action-card .action-body,.rule-actions .action-card .action-footer{padding:20px}.rule-actions .action-card .filed-item{margin-bottom:16px}.rule-actions .action-card .filed-item:last-child{margin-bottom:0}.rule-actions .action-card .filed-item .title{margin-right:10px}.rule-actions .action-card .action-oper{text-align:right;position:relative}.rule-actions .action-card .action-oper .delete-btn{margin-bottom:40px}.rule-actions .action-card .action-oper .fallbacks{position:absolute;right:0;bottom:0}.rule-actions .action-card .action-oper .fallbacks .el-button [class*=el-icon-]+span{margin-left:0}.rule-actions .action-card:last-child{margin-bottom:0}.rule-actions .el-table__expanded-cell{padding:6px;font-size:12px}.action-dialog .action-tips{padding:20px auto;font-size:13px}.action-dialog .resource-item .el-form-item__label{width:100%;text-align:left;padding-right:0}.action-dialog .el-form-item__content{clear:both}.action-dialog .el-select{width:100%}.resource-dialog .el-form{padding:20px}.resource-dialog .el-input--medium .el-input__inner{height:35px;line-height:35px}.resource-dialog .block__title{padding-left:10px;margin-left:10px;border-left:4px solid #34c388;margin-bottom:20px}.resource-dialog .el-select{width:100%}.resource-dialog .divide{margin:25px auto;border-bottom:1px solid #d8d8d8;clear:both}.resource-dialog .el-form-item__content{clear:both}.rule-create .page-title .el-breadcrumb{text-transform:none}.rule-create .el-card{margin-top:24px;min-height:150px;padding:20px;overflow:visible}.rule-create .el-card .config-null{text-align:center;margin:20px auto}.rule-create .toggle-btn{cursor:pointer;margin-top:4px;width:auto}.rule-create .show-guess{line-height:1.4}.rule-create .show-guess p{font-size:13px;margin-bottom:4px}.rule-create .show-guess p .notice{color:#ff6d6d}.rule-create .form-block--wrapper{margin-bottom:50px;padding-bottom:24px}.rule-create .form-block--wrapper .form-block__title{margin-bottom:30px;padding-left:10px;border-left:4px solid #34c388}.rule-create .form-block--wrapper .form-block__title .form-block__title-tips{font-size:12px;display:inline-block;margin-left:4px}.rule-create .form-block--wrapper .form-block__body{padding-left:20px}.rule-create .sql-tips{padding:20px 0;border-radius:4px;font-size:15px;max-height:480px}.rule-create .sql-tips .title{padding:0 20px 12px}.rule-create .sql-tips .el-scrollbar__wrap{overflow-x:hidden}.rule-create .sql-tips .doc-wrapper{max-height:400px;padding:0 20px}.rule-create .sql-tips p{font-size:13px;margin-bottom:4px}.rule-create .sql-tips li{font-size:13px;margin:8px 12px}.rule-create .sql-tips code,.rule-create .sql-tips span{font-size:12px;margin-bottom:12px}.rule-create .code{line-height:1.4;padding:6px;border-radius:4px;margin-bottom:12px}.rule-create .code.text{line-height:1.8}.rule-create .test-btn{margin-top:12px}.code-sql{line-height:18px!important;margin-bottom:44px}.code-sql.rawsql .el-form-item__content{height:420px}.code-sql.payload .el-form-item__content{height:200px}.code-sql .el-form-item__content{line-height:18px!important}.code-sql .payload-type{width:100%;text-align:right;padding:2px 4px;margin-bottom:12px}.code-sql .payload-type .el-radio__label{font-size:13px}.code-sql.is-error .code-sql__editor,.code-sql.is-error .monaco-container{border-color:#ff6d6d}#nprogress{pointer-events:none}#nprogress .bar{background:#29d;position:fixed;z-index:1031;top:0;left:0;width:100%;height:2px}#nprogress .peg{display:block;position:absolute;right:0;width:100px;height:100%;box-shadow:0 0 10px #29d,0 0 5px #29d;opacity:1;transform:rotate(3deg) translateY(-4px)}#nprogress .spinner{display:block;position:fixed;z-index:1031;top:15px;right:15px}#nprogress .spinner-icon{width:18px;height:18px;box-sizing:border-box;border:2px solid transparent;border-top-color:#29d;border-left-color:#29d;border-radius:50%;animation:nprogress-spinner .4s linear infinite}.nprogress-custom-parent{overflow:hidden;position:relative}.nprogress-custom-parent #nprogress .bar,.nprogress-custom-parent #nprogress .spinner{position:absolute}@keyframes nprogress-spinner{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.monaco-view{height:100%;position:relative}.monaco-editor .accessibilityHelpWidget{padding:10px;vertical-align:middle;overflow:scroll}.monaco-aria-container{position:absolute;left:-999em}.monaco-editor .bracket-match{box-sizing:border-box}.monaco-menu .monaco-action-bar.vertical .action-label.hover{background-color:#eee}.monaco-editor .monaco-editor-overlaymessage{padding-bottom:8px}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.monaco-editor .monaco-editor-overlaymessage.fadeIn{animation:fadeIn .15s ease-out}@keyframes fadeOut{0%{opacity:1}to{opacity:0}}.monaco-editor .monaco-editor-overlaymessage.fadeOut{animation:fadeOut .1s ease-out}.monaco-editor .monaco-editor-overlaymessage .message{padding:1px 4px}.monaco-editor .monaco-editor-overlaymessage .anchor{width:0!important;height:0!important;border:8px solid transparent;z-index:1000;position:absolute}.monaco-editor .lightbulb-glyph{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;height:16px;width:20px;padding-left:2px}.monaco-editor .lightbulb-glyph:hover{cursor:pointer}.monaco-editor.vs .lightbulb-glyph{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS42NzA4IDguNjU4MDZDMTEuMzMxOSA4Ljk5MTYgMTEuMDcxNiA5LjM2Mjc4IDEwLjg4ODYgOS43NzE3MkMxMC43MTA1IDEwLjE3OTIgMTAuNjIxIDEwLjYyMTkgMTAuNjIxIDExLjEwMDlWMTIuNzAxMkMxMC42MjEgMTIuODgwNyAxMC41ODcyIDEzLjA1MDMgMTAuNTE4OSAxMy4yMDkxQzEwLjQ1MTMgMTMuMzY2MSAxMC4zNTg2IDEzLjUwMzggMTAuMjQwNyAxMy42MjEzQzEwLjEyMjggMTMuNzM4OCA5Ljk4NDY0IDEzLjgzMTEgOS44MjcyMyAxMy44OTg0QzkuNjY4MDYgMTMuOTY2MyA5LjQ5ODA2IDE0IDkuMzE4MjMgMTRINy43MTIwNUM3LjUzMjIzIDE0IDcuMzYyMjMgMTMuOTY2MyA3LjIwMzA2IDEzLjg5ODRDNy4wNDU2NCAxMy44MzExIDYuOTA3NTMgMTMuNzM4OCA2Ljc4OTYxIDEzLjYyMTNDNi42NzE2OCAxMy41MDM4IDYuNTc4OTUgMTMuMzY2MSA2LjUxMTQxIDEzLjIwOTFDNi40NDMxMSAxMy4wNTAzIDYuNDA5MjcgMTIuODgwNyA2LjQwOTI3IDEyLjcwMTJWMTEuMTAwOUM2LjQwOTI3IDEwLjYyMiA2LjMxNzcyIDEwLjE3OTUgNi4xMzU1MyA5Ljc3MjA5QzUuOTU2ODMgOS4zNjMzNiA1LjY5ODMyIDguOTkxNTYgNS4zNTk1MyA4LjY1ODA2QzQuOTI0NjggOC4yMjkwMyA0LjU4ODk2IDcuNzUwMDMgNC4zNTM2MSA3LjIyMTM0QzQuMTE3NTYgNi42OTEwNyA0IDYuMTE2NzIgNCA1LjQ5OTUzQzQgNS4wODY2NCA0LjA1MzQyIDQuNjg4MDIgNC4xNjA0OCA0LjMwMzk3QzQuMjY3MjggMy45MjA4OSA0LjQxOTA3IDMuNTYyODYgNC42MTU5NSAzLjIzMDE4QzQuODEyNTcgMi44OTM3NyA1LjA0Nzc3IDIuNTg5MTEgNS4zMjE0NiAyLjMxNjQxQzUuNTk1MDMgMi4wNDM4MyA1Ljg5ODU4IDEuODA5NTMgNi4yMzE5NSAxLjYxMzY0QzYuNTY5NzkgMS40MTc2NCA2LjkzMTQ2IDEuMjY2MiA3LjMxNTc4IDEuMTU5ODNDNy43MDEwNiAxLjA1MzIgOC4xMDA5NCAxIDguNTE1MTQgMUM4LjkyOTM0IDEgOS4zMjkyMyAxLjA1MzIgOS43MTQ1MSAxLjE1OTgzQzEwLjA5ODggMS4yNjYyIDEwLjQ1OCAxLjQxNzM5IDEwLjc5MTggMS42MTM1MUMxMS4xMjk0IDEuODA5MzggMTEuNDM1MSAyLjA0MzcgMTEuNzA4OCAyLjMxNjQxQzExLjk4MjUgMi41ODkxIDEyLjIxNzcgMi44OTM3NiAxMi40MTQzIDMuMjMwMTZDMTIuNjExMiAzLjU2Mjg1IDEyLjc2MyAzLjkyMDg4IDEyLjg2OTggNC4zMDM5N0MxMi45NzY5IDQuNjg4MDIgMTMuMDMwMyA1LjA4NjY0IDEzLjAzMDMgNS40OTk1M0MxMy4wMzAzIDYuMTE2NzIgMTIuOTEyNyA2LjY5MTA3IDEyLjY3NjcgNy4yMjEzNEMxMi40NDEzIDcuNzUwMDMgMTIuMTA1NiA4LjIyOTAzIDExLjY3MDggOC42NTgwNlpNOS42MjE2MiAxMC41SDcuNDA4NjdWMTIuNzAxMkM3LjQwODY3IDEyLjc4MjMgNy40MzcyIDEyLjg1MTIgNy40OTg4OCAxMi45MTI3QzcuNTYwNTggMTIuOTc0MSA3LjYzMDA3IDEzLjAwMjggNy43MTIwNSAxMy4wMDI4SDkuMzE4MjNDOS40MDAyMiAxMy4wMDI4IDkuNDY5NzEgMTIuOTc0MSA5LjUzMTQgMTIuOTEyN0M5LjU5MzA5IDEyLjg1MTIgOS42MjE2MiAxMi43ODIzIDkuNjIxNjIgMTIuNzAxMlYxMC41WiIgZmlsbD0iI0ZGQ0MwMCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjY3MDggOC42NTgwNkMxMS4zMzE5IDguOTkxNiAxMS4wNzE2IDkuMzYyNzggMTAuODg4NiA5Ljc3MTcyQzEwLjcxMDUgMTAuMTc5MiAxMC42MjEgMTAuNjIxOSAxMC42MjEgMTEuMTAwOVYxMi43MDEyQzEwLjYyMSAxMi44ODA3IDEwLjU4NzIgMTMuMDUwMyAxMC41MTg5IDEzLjIwOTFDMTAuNDUxMyAxMy4zNjYxIDEwLjM1ODYgMTMuNTAzOCAxMC4yNDA3IDEzLjYyMTNDMTAuMTIyOCAxMy43Mzg4IDkuOTg0NjQgMTMuODMxMSA5LjgyNzIzIDEzLjg5ODRDOS42NjgwNiAxMy45NjYzIDkuNDk4MDYgMTQgOS4zMTgyMyAxNEg3LjcxMjA1QzcuNTMyMjMgMTQgNy4zNjIyMyAxMy45NjYzIDcuMjAzMDYgMTMuODk4NEM3LjA0NTY0IDEzLjgzMTEgNi45MDc1MyAxMy43Mzg4IDYuNzg5NjEgMTMuNjIxM0M2LjY3MTY4IDEzLjUwMzggNi41Nzg5NSAxMy4zNjYxIDYuNTExNDEgMTMuMjA5MUM2LjQ0MzExIDEzLjA1MDMgNi40MDkyNyAxMi44ODA3IDYuNDA5MjcgMTIuNzAxMlYxMS4xMDA5QzYuNDA5MjcgMTAuNjIyIDYuMzE3NzIgMTAuMTc5NSA2LjEzNTUzIDkuNzcyMDlDNS45NTY4MyA5LjM2MzM2IDUuNjk4MzIgOC45OTE1NiA1LjM1OTUzIDguNjU4MDZDNC45MjQ2OCA4LjIyOTAzIDQuNTg4OTYgNy43NTAwMyA0LjM1MzYxIDcuMjIxMzRDNC4xMTc1NiA2LjY5MTA3IDQgNi4xMTY3MiA0IDUuNDk5NTNDNCA1LjA4NjY0IDQuMDUzNDIgNC42ODgwMiA0LjE2MDQ4IDQuMzAzOTdDNC4yNjcyOCAzLjkyMDg5IDQuNDE5MDcgMy41NjI4NiA0LjYxNTk1IDMuMjMwMThDNC44MTI1NyAyLjg5Mzc3IDUuMDQ3NzcgMi41ODkxMSA1LjMyMTQ2IDIuMzE2NDFDNS41OTUwMyAyLjA0MzgzIDUuODk4NTggMS44MDk1MyA2LjIzMTk1IDEuNjEzNjRDNi41Njk3OSAxLjQxNzY0IDYuOTMxNDYgMS4yNjYyIDcuMzE1NzggMS4xNTk4M0M3LjcwMTA2IDEuMDUzMiA4LjEwMDk0IDEgOC41MTUxNCAxQzguOTI5MzQgMSA5LjMyOTIzIDEuMDUzMiA5LjcxNDUxIDEuMTU5ODNDMTAuMDk4OCAxLjI2NjIgMTAuNDU4IDEuNDE3MzkgMTAuNzkxOCAxLjYxMzUxQzExLjEyOTQgMS44MDkzOCAxMS40MzUxIDIuMDQzNyAxMS43MDg4IDIuMzE2NDFDMTEuOTgyNSAyLjU4OTEgMTIuMjE3NyAyLjg5Mzc2IDEyLjQxNDMgMy4yMzAxNkMxMi42MTEyIDMuNTYyODUgMTIuNzYzIDMuOTIwODggMTIuODY5OCA0LjMwMzk3QzEyLjk3NjkgNC42ODgwMiAxMy4wMzAzIDUuMDg2NjQgMTMuMDMwMyA1LjQ5OTUzQzEzLjAzMDMgNi4xMTY3MiAxMi45MTI3IDYuNjkxMDcgMTIuNjc2NyA3LjIyMTM0QzEyLjQ0MTMgNy43NTAwMyAxMi4xMDU2IDguMjI5MDMgMTEuNjcwOCA4LjY1ODA2Wk05LjYyMTYyIDEwLjVINy40MDg2N1YxMi43MDEyQzcuNDA4NjcgMTIuNzgyMyA3LjQzNzIgMTIuODUxMiA3LjQ5ODg4IDEyLjkxMjdDNy41NjA1OCAxMi45NzQxIDcuNjMwMDcgMTMuMDAyOCA3LjcxMjA1IDEzLjAwMjhIOS4zMTgyM0M5LjQwMDIyIDEzLjAwMjggOS40Njk3MSAxMi45NzQxIDkuNTMxNCAxMi45MTI3QzkuNTkzMDkgMTIuODUxMiA5LjYyMTYyIDEyLjc4MjMgOS42MjE2MiAxMi43MDEyVjEwLjVaIiBmaWxsPSIjRERCMTAwIi8+Cjwvc3ZnPgo=") 50% no-repeat}.monaco-editor.vs .lightbulb-glyph.autofixable{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMiA5QzEwLjMzMDQgOSA5IDEwLjMzMDQgOSAxMkM5IDEzLjY2OTYgMTAuMzMwNCAxNSAxMiAxNUMxMy42Njk2IDE1IDE1IDEzLjY2OTYgMTUgMTJDMTUgMTAuMzMwNCAxMy42Njk2IDkgMTIgOVpNMTEuMjAyOCAxMi40NzEyTDEwLjcwNCAxNEwxMiAxMy4wMjRMMTMuMzA1NCAxNEwxMi43OTcyIDEyLjQ3MTJMMTQgMTEuNjM5NEgxMi41MzYxTDEyIDEwTDExLjQ3MzIgMTEuNjM5NEgxMEwxMS4yMDI4IDEyLjQ3MTJaIiBmaWxsPSIjMDA3QUNDIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTEuMTcwOCA4LjA4NDc0QzkuODUwODEgOC4zNTkxMSA4Ljc3Njg3IDkuMjc2ODQgOC4yODY5NiAxMC41SDYuNDA4NjdWMTIuNzAxMkM2LjQwODY3IDEyLjc4MjMgNi40MzcyIDEyLjg1MTIgNi40OTg4OCAxMi45MTI3QzYuNTYwNTggMTIuOTc0MSA2LjYzMDA3IDEzLjAwMjggNi43MTIwNSAxMy4wMDI4SDguMTI0ODdDOC4yMTM2NCAxMy4zNTEzIDguMzQ3NzMgMTMuNjgwOSA4LjUyMDU5IDEzLjk4NTFDOC40NTQ2MiAxMy45OTUxIDguMzg3MTUgMTQgOC4zMTgyMyAxNEg2LjcxMjA1QzYuNTMyMjMgMTQgNi4zNjIyMyAxMy45NjYzIDYuMjAzMDYgMTMuODk4NEM2LjA0NTY0IDEzLjgzMTEgNS45MDc1MyAxMy43Mzg4IDUuNzg5NjEgMTMuNjIxM0M1LjY3MTY4IDEzLjUwMzggNS41Nzg5NSAxMy4zNjYxIDUuNTExNDEgMTMuMjA5MUM1LjQ0MzExIDEzLjA1MDMgNS40MDkyNyAxMi44ODA3IDUuNDA5MjcgMTIuNzAxMlYxMS4xMDA5QzUuNDA5MjcgMTAuNjIyIDUuMzE3NzIgMTAuMTc5NSA1LjEzNTUzIDkuNzcyMDlDNC45NTY4MyA5LjM2MzM2IDQuNjk4MzIgOC45OTE1NiA0LjM1OTUzIDguNjU4MDZDMy45MjQ2OCA4LjIyOTAzIDMuNTg4OTYgNy43NTAwMyAzLjM1MzYxIDcuMjIxMzRDMy4xMTc1NiA2LjY5MTA3IDMgNi4xMTY3MiAzIDUuNDk5NTNDMyA1LjA4NjY0IDMuMDUzNDIgNC42ODgwMiAzLjE2MDQ4IDQuMzAzOTdDMy4yNjcyOCAzLjkyMDg5IDMuNDE5MDcgMy41NjI4NiAzLjYxNTk1IDMuMjMwMThDMy44MTI1NyAyLjg5Mzc3IDQuMDQ3NzcgMi41ODkxMSA0LjMyMTQ2IDIuMzE2NDFDNC41OTUwMyAyLjA0MzgzIDQuODk4NTggMS44MDk1MyA1LjIzMTk1IDEuNjEzNjRDNS41Njk3OSAxLjQxNzY0IDUuOTMxNDYgMS4yNjYyIDYuMzE1NzggMS4xNTk4M0M2LjcwMTA2IDEuMDUzMiA3LjEwMDk0IDEgNy41MTUxNCAxQzcuOTI5MzQgMSA4LjMyOTIzIDEuMDUzMiA4LjcxNDUxIDEuMTU5ODNDOS4wOTg4MyAxLjI2NjIgOS40NTgwMyAxLjQxNzM5IDkuNzkxODMgMS42MTM1MUMxMC4xMjk0IDEuODA5MzggMTAuNDM1MSAyLjA0MzcgMTAuNzA4OCAyLjMxNjQxQzEwLjk4MjUgMi41ODkxIDExLjIxNzcgMi44OTM3NiAxMS40MTQzIDMuMjMwMTZDMTEuNjExMiAzLjU2Mjg1IDExLjc2MyAzLjkyMDg4IDExLjg2OTggNC4zMDM5N0MxMS45NzY5IDQuNjg4MDIgMTIuMDMwMyA1LjA4NjY0IDEyLjAzMDMgNS40OTk1M0MxMi4wMzAzIDYuMTE2NzIgMTEuOTEyNyA2LjY5MTA3IDExLjY3NjcgNy4yMjEzNEMxMS41NDEyIDcuNTI1NjIgMTEuMzcyNSA3LjgxMzQ0IDExLjE3MDggOC4wODQ3NFoiIGZpbGw9IiMwMDdBQ0MiLz4KPC9zdmc+Cg==") 50% no-repeat}.monaco-editor.hc-black .lightbulb-glyph,.monaco-editor.vs-dark .lightbulb-glyph{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS42NzA4IDguNjU4MDZDMTEuMzMxOSA4Ljk5MTYgMTEuMDcxNiA5LjM2Mjc4IDEwLjg4ODYgOS43NzE3MkMxMC43MTA1IDEwLjE3OTIgMTAuNjIxIDEwLjYyMTkgMTAuNjIxIDExLjEwMDlWMTIuNzAxMkMxMC42MjEgMTIuODgwNyAxMC41ODcyIDEzLjA1MDMgMTAuNTE4OSAxMy4yMDkxQzEwLjQ1MTMgMTMuMzY2MSAxMC4zNTg2IDEzLjUwMzggMTAuMjQwNyAxMy42MjEzQzEwLjEyMjggMTMuNzM4OCA5Ljk4NDY0IDEzLjgzMTEgOS44MjcyMyAxMy44OTg0QzkuNjY4MDYgMTMuOTY2MyA5LjQ5ODA2IDE0IDkuMzE4MjMgMTRINy43MTIwNUM3LjUzMjIzIDE0IDcuMzYyMjMgMTMuOTY2MyA3LjIwMzA2IDEzLjg5ODRDNy4wNDU2NCAxMy44MzExIDYuOTA3NTMgMTMuNzM4OCA2Ljc4OTYxIDEzLjYyMTNDNi42NzE2OCAxMy41MDM4IDYuNTc4OTUgMTMuMzY2MSA2LjUxMTQxIDEzLjIwOTFDNi40NDMxMSAxMy4wNTAzIDYuNDA5MjcgMTIuODgwNyA2LjQwOTI3IDEyLjcwMTJWMTEuMTAwOUM2LjQwOTI3IDEwLjYyMiA2LjMxNzcyIDEwLjE3OTUgNi4xMzU1MyA5Ljc3MjA5QzUuOTU2ODMgOS4zNjMzNiA1LjY5ODMyIDguOTkxNTYgNS4zNTk1MyA4LjY1ODA2QzQuOTI0NjggOC4yMjkwMyA0LjU4ODk2IDcuNzUwMDMgNC4zNTM2MSA3LjIyMTM0QzQuMTE3NTYgNi42OTEwNyA0IDYuMTE2NzIgNCA1LjQ5OTUzQzQgNS4wODY2NCA0LjA1MzQyIDQuNjg4MDIgNC4xNjA0OCA0LjMwMzk3QzQuMjY3MjggMy45MjA4OSA0LjQxOTA3IDMuNTYyODYgNC42MTU5NSAzLjIzMDE4QzQuODEyNTcgMi44OTM3NyA1LjA0Nzc3IDIuNTg5MTEgNS4zMjE0NiAyLjMxNjQxQzUuNTk1MDMgMi4wNDM4MyA1Ljg5ODU4IDEuODA5NTMgNi4yMzE5NSAxLjYxMzY0QzYuNTY5NzkgMS40MTc2NCA2LjkzMTQ2IDEuMjY2MiA3LjMxNTc4IDEuMTU5ODNDNy43MDEwNiAxLjA1MzIgOC4xMDA5NCAxIDguNTE1MTQgMUM4LjkyOTM0IDEgOS4zMjkyMyAxLjA1MzIgOS43MTQ1MSAxLjE1OTgzQzEwLjA5ODggMS4yNjYyIDEwLjQ1OCAxLjQxNzM5IDEwLjc5MTggMS42MTM1MUMxMS4xMjk0IDEuODA5MzggMTEuNDM1MSAyLjA0MzcgMTEuNzA4OCAyLjMxNjQxQzExLjk4MjUgMi41ODkxIDEyLjIxNzcgMi44OTM3NiAxMi40MTQzIDMuMjMwMTZDMTIuNjExMiAzLjU2Mjg1IDEyLjc2MyAzLjkyMDg4IDEyLjg2OTggNC4zMDM5N0MxMi45NzY5IDQuNjg4MDIgMTMuMDMwMyA1LjA4NjY0IDEzLjAzMDMgNS40OTk1M0MxMy4wMzAzIDYuMTE2NzIgMTIuOTEyNyA2LjY5MTA3IDEyLjY3NjcgNy4yMjEzNEMxMi40NDEzIDcuNzUwMDMgMTIuMTA1NiA4LjIyOTAzIDExLjY3MDggOC42NTgwNlpNOS42MjE2MiAxMC41SDcuNDA4NjdWMTIuNzAxMkM3LjQwODY3IDEyLjc4MjMgNy40MzcyIDEyLjg1MTIgNy40OTg4OCAxMi45MTI3QzcuNTYwNTggMTIuOTc0MSA3LjYzMDA3IDEzLjAwMjggNy43MTIwNSAxMy4wMDI4SDkuMzE4MjNDOS40MDAyMiAxMy4wMDI4IDkuNDY5NzEgMTIuOTc0MSA5LjUzMTQgMTIuOTEyN0M5LjU5MzA5IDEyLjg1MTIgOS42MjE2MiAxMi43ODIzIDkuNjIxNjIgMTIuNzAxMlYxMC41WiIgZmlsbD0iI0ZGQ0MwMCIvPgo8L3N2Zz4K") 50% no-repeat}.monaco-editor.hc-black .lightbulb-glyph.autofixable,.monaco-editor.vs-dark .lightbulb-glyph.autofixable{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMiA5QzEwLjMzMDQgOSA5IDEwLjMzMDQgOSAxMkM5IDEzLjY2OTYgMTAuMzMwNCAxNSAxMiAxNUMxMy42Njk2IDE1IDE1IDEzLjY2OTYgMTUgMTJDMTUgMTAuMzMwNCAxMy42Njk2IDkgMTIgOVpNMTEuMjAyOCAxMi40NzEyTDEwLjcwNCAxNEwxMiAxMy4wMjRMMTMuMzA1NCAxNEwxMi43OTcyIDEyLjQ3MTJMMTQgMTEuNjM5NEgxMi41MzYxTDEyIDEwTDExLjQ3MzIgMTEuNjM5NEgxMEwxMS4yMDI4IDEyLjQ3MTJaIiBmaWxsPSIjNzVCRUZGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTEuMTcwOCA4LjA4NDc0QzkuODUwODEgOC4zNTkxMSA4Ljc3Njg3IDkuMjc2ODQgOC4yODY5NiAxMC41SDYuNDA4NjdWMTIuNzAxMkM2LjQwODY3IDEyLjc4MjMgNi40MzcyIDEyLjg1MTIgNi40OTg4OCAxMi45MTI3QzYuNTYwNTggMTIuOTc0MSA2LjYzMDA3IDEzLjAwMjggNi43MTIwNSAxMy4wMDI4SDguMTI0ODdDOC4yMTM2NCAxMy4zNTEzIDguMzQ3NzMgMTMuNjgwOSA4LjUyMDU5IDEzLjk4NTFDOC40NTQ2MiAxMy45OTUxIDguMzg3MTUgMTQgOC4zMTgyMyAxNEg2LjcxMjA1QzYuNTMyMjMgMTQgNi4zNjIyMyAxMy45NjYzIDYuMjAzMDYgMTMuODk4NEM2LjA0NTY0IDEzLjgzMTEgNS45MDc1MyAxMy43Mzg4IDUuNzg5NjEgMTMuNjIxM0M1LjY3MTY4IDEzLjUwMzggNS41Nzg5NSAxMy4zNjYxIDUuNTExNDEgMTMuMjA5MUM1LjQ0MzExIDEzLjA1MDMgNS40MDkyNyAxMi44ODA3IDUuNDA5MjcgMTIuNzAxMlYxMS4xMDA5QzUuNDA5MjcgMTAuNjIyIDUuMzE3NzIgMTAuMTc5NSA1LjEzNTUzIDkuNzcyMDlDNC45NTY4MyA5LjM2MzM2IDQuNjk4MzIgOC45OTE1NiA0LjM1OTUzIDguNjU4MDZDMy45MjQ2OCA4LjIyOTAzIDMuNTg4OTYgNy43NTAwMyAzLjM1MzYxIDcuMjIxMzRDMy4xMTc1NiA2LjY5MTA3IDMgNi4xMTY3MiAzIDUuNDk5NTNDMyA1LjA4NjY0IDMuMDUzNDIgNC42ODgwMiAzLjE2MDQ4IDQuMzAzOTdDMy4yNjcyOCAzLjkyMDg5IDMuNDE5MDcgMy41NjI4NiAzLjYxNTk1IDMuMjMwMThDMy44MTI1NyAyLjg5Mzc3IDQuMDQ3NzcgMi41ODkxMSA0LjMyMTQ2IDIuMzE2NDFDNC41OTUwMyAyLjA0MzgzIDQuODk4NTggMS44MDk1MyA1LjIzMTk1IDEuNjEzNjRDNS41Njk3OSAxLjQxNzY0IDUuOTMxNDYgMS4yNjYyIDYuMzE1NzggMS4xNTk4M0M2LjcwMTA2IDEuMDUzMiA3LjEwMDk0IDEgNy41MTUxNCAxQzcuOTI5MzQgMSA4LjMyOTIzIDEuMDUzMiA4LjcxNDUxIDEuMTU5ODNDOS4wOTg4MyAxLjI2NjIgOS40NTgwMyAxLjQxNzM5IDkuNzkxODMgMS42MTM1MUMxMC4xMjk0IDEuODA5MzggMTAuNDM1MSAyLjA0MzcgMTAuNzA4OCAyLjMxNjQxQzEwLjk4MjUgMi41ODkxIDExLjIxNzcgMi44OTM3NiAxMS40MTQzIDMuMjMwMTZDMTEuNjExMiAzLjU2Mjg1IDExLjc2MyAzLjkyMDg4IDExLjg2OTggNC4zMDM5N0MxMS45NzY5IDQuNjg4MDIgMTIuMDMwMyA1LjA4NjY0IDEyLjAzMDMgNS40OTk1M0MxMi4wMzAzIDYuMTE2NzIgMTEuOTEyNyA2LjY5MTA3IDExLjY3NjcgNy4yMjEzNEMxMS41NDEyIDcuNTI1NjIgMTEuMzcyNSA3LjgxMzQ0IDExLjE3MDggOC4wODQ3NFoiIGZpbGw9IiM3NUJFRkYiLz4KPC9zdmc+Cg==") 50% no-repeat}.monaco-editor .codelens-decoration{overflow:hidden;display:inline-block;text-overflow:ellipsis}.monaco-editor .codelens-decoration>a,.monaco-editor .codelens-decoration>span{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;vertical-align:sub}.monaco-editor .codelens-decoration>a{text-decoration:none}.monaco-editor .codelens-decoration>a:hover{text-decoration:underline;cursor:pointer}.monaco-editor .codelens-decoration.invisible-cl{opacity:0}@keyframes fadein{0%{opacity:0;visibility:visible}to{opacity:1}}.monaco-editor .codelens-decoration.fadein{animation:fadein .1s linear}.monaco-action-bar{text-align:right;overflow:hidden;white-space:nowrap}.monaco-action-bar .actions-container{display:-ms-flexbox;display:flex;margin:0 auto;padding:0;width:100%;-ms-flex-pack:end;justify-content:flex-end}.monaco-action-bar.vertical .actions-container{display:inline-block}.monaco-action-bar.reverse .actions-container{-ms-flex-direction:row-reverse;flex-direction:row-reverse}.monaco-action-bar .action-item{cursor:pointer;display:inline-block;transition:transform 50ms ease;position:relative}.monaco-action-bar .action-item.disabled{cursor:default}.monaco-action-bar.animated .action-item.active{transform:scale(1.272019649)}.monaco-action-bar .action-item .icon{display:inline-block}.monaco-action-bar .action-label{font-size:11px;margin-right:4px}.monaco-action-bar .action-label.octicon{font-size:15px;line-height:35px;text-align:center}.monaco-action-bar .action-item.disabled .action-label,.monaco-action-bar .action-item.disabled .action-label:hover{opacity:.4}.monaco-action-bar.vertical{text-align:left}.monaco-action-bar.vertical .action-item{display:block}.monaco-action-bar.vertical .action-label.separator{display:block;border-bottom:1px solid #bbb;padding-top:1px;margin-left:.8em;margin-right:.8em}.monaco-action-bar.animated.vertical .action-item.active{transform:translate(5px)}.secondary-actions .monaco-action-bar .action-label{margin-left:6px}.monaco-action-bar .action-item.select-container{overflow:hidden;-ms-flex:1;flex:1;max-width:170px;min-width:60px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.monaco-editor.vs .dnd-target{border-right:2px dotted #000;color:#fff}.monaco-editor.vs-dark .dnd-target{border-right:2px dotted #aeafad;color:#51504f}.monaco-editor.hc-black .dnd-target{border-right:2px dotted #fff;color:#000}.monaco-editor.hc-black.mac.mouse-default .view-lines,.monaco-editor.mouse-default .view-lines,.monaco-editor.vs-dark.mac.mouse-default .view-lines{cursor:default}.monaco-editor.hc-black.mac.mouse-copy .view-lines,.monaco-editor.mouse-copy .view-lines,.monaco-editor.vs-dark.mac.mouse-copy .view-lines{cursor:copy}.monaco-custom-checkbox{margin-left:2px;float:left;cursor:pointer;overflow:hidden;opacity:.7;width:20px;height:20px;border:1px solid transparent;padding:1px;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;-webkit-user-select:none;-moz-user-select:none;-o-user-select:none;-ms-user-select:none;user-select:none}.monaco-custom-checkbox.checked,.monaco-custom-checkbox:hover{opacity:1}.hc-black .monaco-custom-checkbox,.hc-black .monaco-custom-checkbox:hover{background:none}.monaco-custom-checkbox.monaco-simple-checkbox{height:18px;width:18px;border:1px solid transparent;border-radius:3px;margin-right:9px;margin-left:0;padding:0;opacity:1;background-size:16px!important}.monaco-custom-checkbox.monaco-simple-checkbox.checked{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNSAzLjc2MzQ1TDUuODA2ODcgMTEuOTM1MUw1LjA4NTg0IDExLjg5MjdMMSA3LjI5NjE0TDEuNzYzNDUgNi42MTc1Mkw1LjUwOTk3IDEwLjgzMjRMMTQuMzIxNCAzTDE1IDMuNzYzNDVaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=") 50% no-repeat;background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNSAzLjc2MzQ1TDUuODA2ODcgMTEuOTM1MUw1LjA4NTg0IDExLjg5MjdMMSA3LjI5NjE0TDEuNzYzNDUgNi42MTc1Mkw1LjUwOTk3IDEwLjgzMjRMMTQuMzIxNCAzTDE1IDMuNzYzNDVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=") 50% no-repeat}.vs .monaco-custom-checkbox.monaco-case-sensitive{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjQ5NSA5LjA1Mkw4LjM4NiAxMS40MDJIOS40NzdMNi4yMzcgM0g1LjIxN0wyIDExLjQwMkgzLjA5NUwzLjkzMyA5LjA1Mkg3LjQ5NVpNNS44MTEgNC40NTNMNS44NTUgNC41ODhMNy4xNzMgOC4xNjJINC4yNTVMNS41NjIgNC41ODhMNS42MDYgNC40NTNMNS42NDQgNC4yOTdMNS42NzYgNC4xNDVMNS42OTcgNC4wMTlINS43Mkw1Ljc0NCA0LjE0NUw1Ljc3MyA0LjI5N0w1LjgxMSA0LjQ1M1pNMTMuNzk1IDEwLjQ2NFYxMS40SDE0Ljc1NVY3LjQ5OEMxNC43NTUgNi43NzkgMTQuNTc1IDYuMjI2IDE0LjIxNiA1LjgzN0MxMy44NTcgNS40NDggMTMuMzI3IDUuMjU0IDEyLjYyOCA1LjI1NEMxMi40MjkgNS4yNTQgMTIuMjI3IDUuMjczIDEyLjAyMiA1LjMxQzExLjgxNyA1LjM0NyAxMS42MjIgNS4zOTQgMTEuNDM5IDUuNDUxQzExLjI1NiA1LjUwOCAxMS4wOTEgNS41NjkgMTAuOTQ0IDUuNjM2QzEwLjc5NyA1LjcwMyAxMC42ODMgNS43NjUgMTAuNjAxIDUuODI0VjYuODA4QzEwLjg2NyA2LjU3OCAxMS4xNjcgNi4zOTcgMTEuNTA1IDYuMjY4QzExLjg0MyA2LjEzOSAxMi4xOTQgNi4wNzUgMTIuNTU3IDYuMDc1QzEyLjc0NSA2LjA3NSAxMi45MTUgNi4xMDMgMTMuMDcgNi4xNkMxMy4yMjUgNi4yMTcgMTMuMzU3IDYuMzA2IDEzLjQ2NiA2LjQyN0MxMy41NzUgNi41NDggMTMuNjU5IDYuNzA2IDEzLjcxOCA2Ljg5OUMxMy43NzcgNy4wOTIgMTMuODA2IDcuMzI2IDEzLjgwNiA3LjU5OUwxMS45OTUgNy44NTFDMTEuNjUxIDcuODk4IDExLjM1NSA3Ljk3NyAxMS4xMDcgOC4wODhDMTAuODU5IDguMTk5IDEwLjY1NCA4LjMzOSAxMC40OTIgOC41MDdDMTAuMzMgOC42NzUgMTAuMjEgOC44NjggMTAuMTMyIDkuMDg3QzEwLjA1NCA5LjMwNiAxMC4wMTUgOS41NDYgMTAuMDE1IDkuODA4QzEwLjAxNSAxMC4wNTQgMTAuMDU3IDEwLjI4MyAxMC4xMzkgMTAuNDk2QzEwLjIyMSAxMC43MDkgMTAuMzQyIDEwLjg5MyAxMC41MDIgMTEuMDQ3QzEwLjY2MiAxMS4yMDEgMTAuODYyIDExLjMyMyAxMS4xIDExLjQxM0MxMS4zMzggMTEuNTAzIDExLjYxMyAxMS41NDggMTEuOTI2IDExLjU0OEMxMi4zMjggMTEuNTQ4IDEyLjY4NiAxMS40NTYgMTMuMDAxIDExLjI3QzEzLjMxNiAxMS4wODQgMTMuNTczIDEwLjgxNiAxMy43NzIgMTAuNDY0SDEzLjc5NVpNMTEuNjY3IDguNzIxQzExLjg0MyA4LjY1NyAxMi4wNjggOC42MDcgMTIuMzQxIDguNTcyTDEzLjgwNiA4LjM2N1Y4Ljk3NkMxMy44MDYgOS4yMjIgMTMuNzY1IDkuNDUxIDEzLjY4MyA5LjY2NEMxMy42MDEgOS44NzcgMTMuNDg2IDEwLjA2MyAxMy4zNCAxMC4yMjFDMTMuMTk0IDEwLjM3OSAxMy4wMTkgMTAuNTAzIDEyLjgxNiAxMC41OTNDMTIuNjEzIDEwLjY4MyAxMi4zOSAxMC43MjggMTIuMTQ4IDEwLjcyOEMxMS45NjEgMTAuNzI4IDExLjc5NSAxMC43MDMgMTEuNjUzIDEwLjY1MkMxMS41MTEgMTAuNjAxIDExLjM5MiAxMC41MyAxMS4yOTYgMTAuNDQxQzExLjIgMTAuMzUyIDExLjEyNyAxMC4yNDcgMTEuMDc2IDEwLjEyNUMxMS4wMjUgMTAuMDAzIDExIDkuODczIDExIDkuNzMyQzExIDkuNTY4IDExLjAxOCA5LjQyMSAxMS4wNTUgOS4yOTJDMTEuMDkyIDkuMTYzIDExLjE2IDkuMDUxIDExLjI1NyA4Ljk1OEMxMS4zNTQgOC44NjUgMTEuNDkxIDguNzg1IDExLjY2NyA4LjcyMVoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% no-repeat}.vs-dark .monaco-custom-checkbox.monaco-case-sensitive{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjQ5NSA5LjA1Mkw4LjM4NiAxMS40MDJIOS40NzdMNi4yMzcgM0g1LjIxN0wyIDExLjQwMkgzLjA5NUwzLjkzMyA5LjA1Mkg3LjQ5NVpNNS44MTEgNC40NTNMNS44NTUgNC41ODhMNy4xNzMgOC4xNjJINC4yNTVMNS41NjIgNC41ODhMNS42MDYgNC40NTNMNS42NDQgNC4yOTdMNS42NzYgNC4xNDVMNS42OTcgNC4wMTlINS43Mkw1Ljc0NCA0LjE0NUw1Ljc3MyA0LjI5N0w1LjgxMSA0LjQ1M1pNMTMuNzk1IDEwLjQ2NFYxMS40SDE0Ljc1NVY3LjQ5OEMxNC43NTUgNi43NzkgMTQuNTc1IDYuMjI2IDE0LjIxNiA1LjgzN0MxMy44NTcgNS40NDggMTMuMzI3IDUuMjU0IDEyLjYyOCA1LjI1NEMxMi40MjkgNS4yNTQgMTIuMjI3IDUuMjczIDEyLjAyMiA1LjMxQzExLjgxNyA1LjM0NyAxMS42MjIgNS4zOTQgMTEuNDM5IDUuNDUxQzExLjI1NiA1LjUwOCAxMS4wOTEgNS41NjkgMTAuOTQ0IDUuNjM2QzEwLjc5NyA1LjcwMyAxMC42ODMgNS43NjUgMTAuNjAxIDUuODI0VjYuODA4QzEwLjg2NyA2LjU3OCAxMS4xNjcgNi4zOTcgMTEuNTA1IDYuMjY4QzExLjg0MyA2LjEzOSAxMi4xOTQgNi4wNzUgMTIuNTU3IDYuMDc1QzEyLjc0NSA2LjA3NSAxMi45MTUgNi4xMDMgMTMuMDcgNi4xNkMxMy4yMjUgNi4yMTcgMTMuMzU3IDYuMzA2IDEzLjQ2NiA2LjQyN0MxMy41NzUgNi41NDggMTMuNjU5IDYuNzA2IDEzLjcxOCA2Ljg5OUMxMy43NzcgNy4wOTIgMTMuODA2IDcuMzI2IDEzLjgwNiA3LjU5OUwxMS45OTUgNy44NTFDMTEuNjUxIDcuODk4IDExLjM1NSA3Ljk3NyAxMS4xMDcgOC4wODhDMTAuODU5IDguMTk5IDEwLjY1NCA4LjMzOSAxMC40OTIgOC41MDdDMTAuMzMgOC42NzUgMTAuMjEgOC44NjggMTAuMTMyIDkuMDg3QzEwLjA1NCA5LjMwNiAxMC4wMTUgOS41NDYgMTAuMDE1IDkuODA4QzEwLjAxNSAxMC4wNTQgMTAuMDU3IDEwLjI4MyAxMC4xMzkgMTAuNDk2QzEwLjIyMSAxMC43MDkgMTAuMzQyIDEwLjg5MyAxMC41MDIgMTEuMDQ3QzEwLjY2MiAxMS4yMDEgMTAuODYyIDExLjMyMyAxMS4xIDExLjQxM0MxMS4zMzggMTEuNTAzIDExLjYxMyAxMS41NDggMTEuOTI2IDExLjU0OEMxMi4zMjggMTEuNTQ4IDEyLjY4NiAxMS40NTYgMTMuMDAxIDExLjI3QzEzLjMxNiAxMS4wODQgMTMuNTczIDEwLjgxNiAxMy43NzIgMTAuNDY0SDEzLjc5NVpNMTEuNjY3IDguNzIxQzExLjg0MyA4LjY1NyAxMi4wNjggOC42MDcgMTIuMzQxIDguNTcyTDEzLjgwNiA4LjM2N1Y4Ljk3NkMxMy44MDYgOS4yMjIgMTMuNzY1IDkuNDUxIDEzLjY4MyA5LjY2NEMxMy42MDEgOS44NzcgMTMuNDg2IDEwLjA2MyAxMy4zNCAxMC4yMjFDMTMuMTk0IDEwLjM3OSAxMy4wMTkgMTAuNTAzIDEyLjgxNiAxMC41OTNDMTIuNjEzIDEwLjY4MyAxMi4zOSAxMC43MjggMTIuMTQ4IDEwLjcyOEMxMS45NjEgMTAuNzI4IDExLjc5NSAxMC43MDMgMTEuNjUzIDEwLjY1MkMxMS41MTEgMTAuNjAxIDExLjM5MiAxMC41MyAxMS4yOTYgMTAuNDQxQzExLjIgMTAuMzUyIDExLjEyNyAxMC4yNDcgMTEuMDc2IDEwLjEyNUMxMS4wMjUgMTAuMDAzIDExIDkuODczIDExIDkuNzMyQzExIDkuNTY4IDExLjAxOCA5LjQyMSAxMS4wNTUgOS4yOTJDMTEuMDkyIDkuMTYzIDExLjE2IDkuMDUxIDExLjI1NyA4Ljk1OEMxMS4zNTQgOC44NjUgMTEuNDkxIDguNzg1IDExLjY2NyA4LjcyMVoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") 50% no-repeat}.hc-black .monaco-custom-checkbox.monaco-case-sensitive,.hc-black .monaco-custom-checkbox.monaco-case-sensitive:hover{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjQ5NSA5LjA1Mkw4LjM4NiAxMS40MDJIOS40NzdMNi4yMzcgM0g1LjIxN0wyIDExLjQwMkgzLjA5NUwzLjkzMyA5LjA1Mkg3LjQ5NVpNNS44MTEgNC40NTNMNS44NTUgNC41ODhMNy4xNzMgOC4xNjJINC4yNTVMNS41NjIgNC41ODhMNS42MDYgNC40NTNMNS42NDQgNC4yOTdMNS42NzYgNC4xNDVMNS42OTcgNC4wMTlINS43Mkw1Ljc0NCA0LjE0NUw1Ljc3MyA0LjI5N0w1LjgxMSA0LjQ1M1pNMTMuNzk1IDEwLjQ2NFYxMS40SDE0Ljc1NVY3LjQ5OEMxNC43NTUgNi43NzkgMTQuNTc1IDYuMjI2IDE0LjIxNiA1LjgzN0MxMy44NTcgNS40NDggMTMuMzI3IDUuMjU0IDEyLjYyOCA1LjI1NEMxMi40MjkgNS4yNTQgMTIuMjI3IDUuMjczIDEyLjAyMiA1LjMxQzExLjgxNyA1LjM0NyAxMS42MjIgNS4zOTQgMTEuNDM5IDUuNDUxQzExLjI1NiA1LjUwOCAxMS4wOTEgNS41NjkgMTAuOTQ0IDUuNjM2QzEwLjc5NyA1LjcwMyAxMC42ODMgNS43NjUgMTAuNjAxIDUuODI0VjYuODA4QzEwLjg2NyA2LjU3OCAxMS4xNjcgNi4zOTcgMTEuNTA1IDYuMjY4QzExLjg0MyA2LjEzOSAxMi4xOTQgNi4wNzUgMTIuNTU3IDYuMDc1QzEyLjc0NSA2LjA3NSAxMi45MTUgNi4xMDMgMTMuMDcgNi4xNkMxMy4yMjUgNi4yMTcgMTMuMzU3IDYuMzA2IDEzLjQ2NiA2LjQyN0MxMy41NzUgNi41NDggMTMuNjU5IDYuNzA2IDEzLjcxOCA2Ljg5OUMxMy43NzcgNy4wOTIgMTMuODA2IDcuMzI2IDEzLjgwNiA3LjU5OUwxMS45OTUgNy44NTFDMTEuNjUxIDcuODk4IDExLjM1NSA3Ljk3NyAxMS4xMDcgOC4wODhDMTAuODU5IDguMTk5IDEwLjY1NCA4LjMzOSAxMC40OTIgOC41MDdDMTAuMzMgOC42NzUgMTAuMjEgOC44NjggMTAuMTMyIDkuMDg3QzEwLjA1NCA5LjMwNiAxMC4wMTUgOS41NDYgMTAuMDE1IDkuODA4QzEwLjAxNSAxMC4wNTQgMTAuMDU3IDEwLjI4MyAxMC4xMzkgMTAuNDk2QzEwLjIyMSAxMC43MDkgMTAuMzQyIDEwLjg5MyAxMC41MDIgMTEuMDQ3QzEwLjY2MiAxMS4yMDEgMTAuODYyIDExLjMyMyAxMS4xIDExLjQxM0MxMS4zMzggMTEuNTAzIDExLjYxMyAxMS41NDggMTEuOTI2IDExLjU0OEMxMi4zMjggMTEuNTQ4IDEyLjY4NiAxMS40NTYgMTMuMDAxIDExLjI3QzEzLjMxNiAxMS4wODQgMTMuNTczIDEwLjgxNiAxMy43NzIgMTAuNDY0SDEzLjc5NVpNMTEuNjY3IDguNzIxQzExLjg0MyA4LjY1NyAxMi4wNjggOC42MDcgMTIuMzQxIDguNTcyTDEzLjgwNiA4LjM2N1Y4Ljk3NkMxMy44MDYgOS4yMjIgMTMuNzY1IDkuNDUxIDEzLjY4MyA5LjY2NEMxMy42MDEgOS44NzcgMTMuNDg2IDEwLjA2MyAxMy4zNCAxMC4yMjFDMTMuMTk0IDEwLjM3OSAxMy4wMTkgMTAuNTAzIDEyLjgxNiAxMC41OTNDMTIuNjEzIDEwLjY4MyAxMi4zOSAxMC43MjggMTIuMTQ4IDEwLjcyOEMxMS45NjEgMTAuNzI4IDExLjc5NSAxMC43MDMgMTEuNjUzIDEwLjY1MkMxMS41MTEgMTAuNjAxIDExLjM5MiAxMC41MyAxMS4yOTYgMTAuNDQxQzExLjIgMTAuMzUyIDExLjEyNyAxMC4yNDcgMTEuMDc2IDEwLjEyNUMxMS4wMjUgMTAuMDAzIDExIDkuODczIDExIDkuNzMyQzExIDkuNTY4IDExLjAxOCA5LjQyMSAxMS4wNTUgOS4yOTJDMTEuMDkyIDkuMTYzIDExLjE2IDkuMDUxIDExLjI1NyA4Ljk1OEMxMS4zNTQgOC44NjUgMTEuNDkxIDguNzg1IDExLjY2NyA4LjcyMVoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=") 50% no-repeat}.vs .monaco-custom-checkbox.monaco-preserve-case{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTguNTM0MzcgMTIuNDY3M0g3LjQzNjFMNi41Mzg1OSAxMC4wOTM2SDIuOTQ4NTRMMi4xMDQxOCAxMi40NjczSDFMNC4yNDc1NyA0SDUuMjc0OTlMOC41MzQzNyAxMi40NjczWk02LjIxMzgzIDkuMjAyMDJMNC44ODUyOCA1LjU5NDI2QzQuODQxOTggNS40NzYxNyA0Ljc5ODY4IDUuMjg3MjIgNC43NTUzOCA1LjAyNzQxSDQuNzMxNzZDNC42OTIzOSA1LjI2NzU0IDQuNjQ3MTMgNS40NTY0OSA0LjU5NTk1IDUuNTk0MjZMMy4yNzkyMSA5LjIwMjAySDYuMjEzODNaIiBmaWxsPSIjNDI0MjQyIi8+CjxwYXRoIGQ9Ik05Ljc4NjE3IDEyLjQ2NzNWNEgxMi4xOTUzQzEyLjkyNzUgNCAxMy41MDgxIDQuMTc5MTEgMTMuOTM3MiA0LjUzNzMzQzE0LjM2NjIgNC44OTU1NCAxNC41ODA4IDUuMzYyMDEgMTQuNTgwOCA1LjkzNjc0QzE0LjU4MDggNi40MTY5OCAxNC40NTA5IDYuODM0MjUgMTQuMTkxMSA3LjE4ODUzQzEzLjkzMTMgNy41NDI4MSAxMy41NzMgNy43OTQ3NCAxMy4xMTY0IDcuOTQ0MzNWNy45Njc5NUMxMy42ODcyIDguMDM0ODcgMTQuMTQzOCA4LjI1MTM3IDE0LjQ4NjMgOC42MTc0NkMxNC44Mjg4IDguOTc5NjEgMTUgOS40NTE5OSAxNSAxMC4wMzQ2QzE1IDEwLjc1ODkgMTQuNzQwMiAxMS4zNDU0IDE0LjIyMDYgMTEuNzk0MkMxMy43MDEgMTIuMjQyOSAxMy4wNDU2IDEyLjQ2NzMgMTIuMjU0MyAxMi40NjczSDkuNzg2MTdaTTEwLjc3ODIgNC44OTc1MVY3LjYzMTM4SDExLjc5MzhDMTIuMzM3IDcuNjMxMzggMTIuNzY0MSA3LjUwMTQ4IDEzLjA3NTEgNy4yNDE2N0MxMy4zODYxIDYuOTc3OTMgMTMuNTQxNSA2LjYwNzkgMTMuNTQxNSA2LjEzMTU5QzEzLjU0MTUgNS4zMDg4NyAxMy4wMDAzIDQuODk3NTEgMTEuOTE3OCA0Ljg5NzUxSDEwLjc3ODJaTTEwLjc3ODIgOC41MjI5OVYxMS41Njk4SDEyLjEyNDRDMTIuNzA3IDExLjU2OTggMTMuMTU3NyAxMS40MzIgMTMuNDc2NiAxMS4xNTY1QzEzLjc5OTQgMTAuODgwOSAxMy45NjA4IDEwLjUwMyAxMy45NjA4IDEwLjAyMjhDMTMuOTYwOCA5LjAyMjkyIDEzLjI3OTggOC41MjI5OSAxMS45MTc4IDguNTIyOTlIMTAuNzc4MloiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% no-repeat}.vs-dark .monaco-custom-checkbox.monaco-preserve-case{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTguNTM0MzcgMTIuNDY3M0g3LjQzNjFMNi41Mzg1OSAxMC4wOTM2SDIuOTQ4NTRMMi4xMDQxOCAxMi40NjczSDFMNC4yNDc1NyA0SDUuMjc0OTlMOC41MzQzNyAxMi40NjczWk02LjIxMzgzIDkuMjAyMDJMNC44ODUyOCA1LjU5NDI2QzQuODQxOTggNS40NzYxNyA0Ljc5ODY4IDUuMjg3MjIgNC43NTUzOCA1LjAyNzQxSDQuNzMxNzZDNC42OTIzOSA1LjI2NzU0IDQuNjQ3MTMgNS40NTY0OSA0LjU5NTk1IDUuNTk0MjZMMy4yNzkyMSA5LjIwMjAySDYuMjEzODNaIiBmaWxsPSIjQzVDNUM1Ii8+CjxwYXRoIGQ9Ik05Ljc4NjE3IDEyLjQ2NzNWNEgxMi4xOTUzQzEyLjkyNzUgNCAxMy41MDgxIDQuMTc5MTEgMTMuOTM3MiA0LjUzNzMzQzE0LjM2NjIgNC44OTU1NCAxNC41ODA4IDUuMzYyMDEgMTQuNTgwOCA1LjkzNjc0QzE0LjU4MDggNi40MTY5OCAxNC40NTA5IDYuODM0MjUgMTQuMTkxMSA3LjE4ODUzQzEzLjkzMTMgNy41NDI4MSAxMy41NzMgNy43OTQ3NCAxMy4xMTY0IDcuOTQ0MzNWNy45Njc5NUMxMy42ODcyIDguMDM0ODcgMTQuMTQzOCA4LjI1MTM3IDE0LjQ4NjMgOC42MTc0NkMxNC44Mjg4IDguOTc5NjEgMTUgOS40NTE5OSAxNSAxMC4wMzQ2QzE1IDEwLjc1ODkgMTQuNzQwMiAxMS4zNDU0IDE0LjIyMDYgMTEuNzk0MkMxMy43MDEgMTIuMjQyOSAxMy4wNDU2IDEyLjQ2NzMgMTIuMjU0MyAxMi40NjczSDkuNzg2MTdaTTEwLjc3ODIgNC44OTc1MVY3LjYzMTM4SDExLjc5MzhDMTIuMzM3IDcuNjMxMzggMTIuNzY0MSA3LjUwMTQ4IDEzLjA3NTEgNy4yNDE2N0MxMy4zODYxIDYuOTc3OTMgMTMuNTQxNSA2LjYwNzkgMTMuNTQxNSA2LjEzMTU5QzEzLjU0MTUgNS4zMDg4NyAxMy4wMDAzIDQuODk3NTEgMTEuOTE3OCA0Ljg5NzUxSDEwLjc3ODJaTTEwLjc3ODIgOC41MjI5OVYxMS41Njk4SDEyLjEyNDRDMTIuNzA3IDExLjU2OTggMTMuMTU3NyAxMS40MzIgMTMuNDc2NiAxMS4xNTY1QzEzLjc5OTQgMTAuODgwOSAxMy45NjA4IDEwLjUwMyAxMy45NjA4IDEwLjAyMjhDMTMuOTYwOCA5LjAyMjkyIDEzLjI3OTggOC41MjI5OSAxMS45MTc4IDguNTIyOTlIMTAuNzc4MloiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") 50% no-repeat}.hc-black .monaco-custom-checkbox.monaco-preserve-case,.hc-black .monaco-custom-checkbox.monaco-preserve-case:hover{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTguNTM0MzcgMTIuNDY3M0g3LjQzNjFMNi41Mzg1OSAxMC4wOTM2SDIuOTQ4NTRMMi4xMDQxOCAxMi40NjczSDFMNC4yNDc1NyA0SDUuMjc0OTlMOC41MzQzNyAxMi40NjczWk02LjIxMzgzIDkuMjAyMDJMNC44ODUyOCA1LjU5NDI2QzQuODQxOTggNS40NzYxNyA0Ljc5ODY4IDUuMjg3MjIgNC43NTUzOCA1LjAyNzQxSDQuNzMxNzZDNC42OTIzOSA1LjI2NzU0IDQuNjQ3MTMgNS40NTY0OSA0LjU5NTk1IDUuNTk0MjZMMy4yNzkyMSA5LjIwMjAySDYuMjEzODNaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNOS43ODYxNyAxMi40NjczVjRIMTIuMTk1M0MxMi45Mjc1IDQgMTMuNTA4MSA0LjE3OTExIDEzLjkzNzIgNC41MzczM0MxNC4zNjYyIDQuODk1NTQgMTQuNTgwOCA1LjM2MjAxIDE0LjU4MDggNS45MzY3NEMxNC41ODA4IDYuNDE2OTggMTQuNDUwOSA2LjgzNDI1IDE0LjE5MTEgNy4xODg1M0MxMy45MzEzIDcuNTQyODEgMTMuNTczIDcuNzk0NzQgMTMuMTE2NCA3Ljk0NDMzVjcuOTY3OTVDMTMuNjg3MiA4LjAzNDg3IDE0LjE0MzggOC4yNTEzNyAxNC40ODYzIDguNjE3NDZDMTQuODI4OCA4Ljk3OTYxIDE1IDkuNDUxOTkgMTUgMTAuMDM0NkMxNSAxMC43NTg5IDE0Ljc0MDIgMTEuMzQ1NCAxNC4yMjA2IDExLjc5NDJDMTMuNzAxIDEyLjI0MjkgMTMuMDQ1NiAxMi40NjczIDEyLjI1NDMgMTIuNDY3M0g5Ljc4NjE3Wk0xMC43NzgyIDQuODk3NTFWNy42MzEzOEgxMS43OTM4QzEyLjMzNyA3LjYzMTM4IDEyLjc2NDEgNy41MDE0OCAxMy4wNzUxIDcuMjQxNjdDMTMuMzg2MSA2Ljk3NzkzIDEzLjU0MTUgNi42MDc5IDEzLjU0MTUgNi4xMzE1OUMxMy41NDE1IDUuMzA4ODcgMTMuMDAwMyA0Ljg5NzUxIDExLjkxNzggNC44OTc1MUgxMC43NzgyWk0xMC43NzgyIDguNTIyOTlWMTEuNTY5OEgxMi4xMjQ0QzEyLjcwNyAxMS41Njk4IDEzLjE1NzcgMTEuNDMyIDEzLjQ3NjYgMTEuMTU2NUMxMy43OTk0IDEwLjg4MDkgMTMuOTYwOCAxMC41MDMgMTMuOTYwOCAxMC4wMjI4QzEzLjk2MDggOS4wMjI5MiAxMy4yNzk4IDguNTIyOTkgMTEuOTE3OCA4LjUyMjk5SDEwLjc3ODJaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K") 50% no-repeat}.vs .monaco-custom-checkbox.monaco-whole-word{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xIDJIMTVWM0gxVjJaTTE0IDRIMTNWMTJIMTRWNFpNMTEuMjcyIDguMzg3QzExLjE5NCA4LjA4OCAxMS4wNzMgNy44MjUgMTAuOTEyIDcuNjAxQzEwLjc1MSA3LjM3NyAxMC41NDcgNy4yIDEwLjMwMyA3LjA3MUMxMC4wNTkgNi45NDIgOS43NjkgNi44NzggOS40MzcgNi44NzhDOS4yMzkgNi44NzggOS4wNTcgNi45MDIgOC44OSA2Ljk1MUM4LjcyNSA3IDguNTc0IDcuMDY4IDguNDM3IDcuMTU2QzguMzAxIDcuMjQ0IDguMTggNy4zNSA4LjA3MiA3LjQ3NEw3Ljg5MyA3LjczMlY0LjU3OEg3VjEySDcuODkzVjExLjQyNUw4LjAxOSAxMS42QzguMTA2IDExLjcwMiA4LjIwOCAxMS43OSA4LjMyMyAxMS44NjlDOC40NCAxMS45NDcgOC41NzIgMTIuMDA5IDguNzIxIDEyLjA1NUM4Ljg3IDEyLjEwMSA5LjAzNSAxMi4xMjMgOS4yMTkgMTIuMTIzQzkuNTcyIDEyLjEyMyA5Ljg4NSAxMi4wNTIgMTAuMTU2IDExLjkxMUMxMC40MjggMTEuNzY4IDEwLjY1NSAxMS41NzMgMTAuODM4IDExLjMyNUMxMS4wMjEgMTEuMDc1IDExLjE1OSAxMC43ODIgMTEuMjUyIDEwLjQ0NkMxMS4zNDUgMTAuMTA4IDExLjM5MiA5Ljc0MyAxMS4zOTIgOS4zNDlDMTEuMzkxIDkuMDA3IDExLjM1MiA4LjY4NiAxMS4yNzIgOC4zODdaTTkuNzkzIDcuNzhDOS45NDQgNy44NTEgMTAuMDc1IDcuOTU2IDEwLjE4MyA4LjA5NEMxMC4yOTIgOC4yMzQgMTAuMzc3IDguNDA3IDEwLjQzOCA4LjYxMUMxMC40ODkgOC43ODUgMTAuNTIgOC45ODIgMTAuNTI3IDkuMTk4TDEwLjUyIDkuMzIzQzEwLjUyIDkuNjUgMTAuNDg3IDkuOTQzIDEwLjQyIDEwLjE5MkMxMC4zNTMgMTAuNDM4IDEwLjI1OSAxMC42NDUgMTAuMTQyIDEwLjgwNkMxMC4wMjUgMTAuOTY4IDkuODgyIDExLjA5MSA5LjcyMSAxMS4xNzJDOS4zOTkgMTEuMzM0IDguOTYxIDExLjMzOCA4LjY1MiAxMS4xODdDOC40OTkgMTEuMTEyIDguMzY2IDExLjAxMiA4LjI1OSAxMC44OTFDOC4xNzQgMTAuNzk1IDguMTAzIDEwLjY3NSA4LjA0MSAxMC41MjRDOC4wNDEgMTAuNTI0IDcuODYyIDEwLjA3NyA3Ljg2MiA5LjU3N0M3Ljg2MiA5LjA3NyA4LjA0MSA4LjU3NSA4LjA0MSA4LjU3NUM4LjEwMyA4LjM5OCA4LjE3NyA4LjI1NyA4LjI2NSA4LjE0NUM4LjM3OSA4LjAwMiA4LjUyMSA3Ljg4NiA4LjY4OSA3LjhDOC44NTcgNy43MTQgOS4wNTQgNy42NzEgOS4yNzYgNy42NzFDOS40NjYgNy42NzEgOS42NCA3LjcwOCA5Ljc5MyA3Ljc4Wk0xNSAxM0gxVjE0SDE1VjEzWk0yLjgxMyAxMEwyLjA4NSAxMi4wMzFIMUwxLjAyNSAxMS45NTlMMy40NjYgNC44NzMwNUg0LjQwN0w2Ljg5MiAxMi4wMzFINS44MUw1LjAzMiAxMEgyLjgxM1pNMy45MzQgNi40MjIwNUgzLjkxMkwzLjAwNyA5LjE3NTA1SDQuODQ4TDMuOTM0IDYuNDIyMDVaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=") 50% no-repeat}.vs-dark .monaco-custom-checkbox.monaco-whole-word{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xIDJIMTVWM0gxVjJaTTE0IDRIMTNWMTJIMTRWNFpNMTEuMjcyIDguMzg3QzExLjE5NCA4LjA4OCAxMS4wNzMgNy44MjUgMTAuOTEyIDcuNjAxQzEwLjc1MSA3LjM3NyAxMC41NDcgNy4yIDEwLjMwMyA3LjA3MUMxMC4wNTkgNi45NDIgOS43NjkgNi44NzggOS40MzcgNi44NzhDOS4yMzkgNi44NzggOS4wNTcgNi45MDIgOC44OSA2Ljk1MUM4LjcyNSA3IDguNTc0IDcuMDY4IDguNDM3IDcuMTU2QzguMzAxIDcuMjQ0IDguMTggNy4zNSA4LjA3MiA3LjQ3NEw3Ljg5MyA3LjczMlY0LjU3OEg3VjEySDcuODkzVjExLjQyNUw4LjAxOSAxMS42QzguMTA2IDExLjcwMiA4LjIwOCAxMS43OSA4LjMyMyAxMS44NjlDOC40NCAxMS45NDcgOC41NzIgMTIuMDA5IDguNzIxIDEyLjA1NUM4Ljg3IDEyLjEwMSA5LjAzNSAxMi4xMjMgOS4yMTkgMTIuMTIzQzkuNTcyIDEyLjEyMyA5Ljg4NSAxMi4wNTIgMTAuMTU2IDExLjkxMUMxMC40MjggMTEuNzY4IDEwLjY1NSAxMS41NzMgMTAuODM4IDExLjMyNUMxMS4wMjEgMTEuMDc1IDExLjE1OSAxMC43ODIgMTEuMjUyIDEwLjQ0NkMxMS4zNDUgMTAuMTA4IDExLjM5MiA5Ljc0MyAxMS4zOTIgOS4zNDlDMTEuMzkxIDkuMDA3IDExLjM1MiA4LjY4NiAxMS4yNzIgOC4zODdaTTkuNzkzIDcuNzhDOS45NDQgNy44NTEgMTAuMDc1IDcuOTU2IDEwLjE4MyA4LjA5NEMxMC4yOTIgOC4yMzQgMTAuMzc3IDguNDA3IDEwLjQzOCA4LjYxMUMxMC40ODkgOC43ODUgMTAuNTIgOC45ODIgMTAuNTI3IDkuMTk4TDEwLjUyIDkuMzIzQzEwLjUyIDkuNjUgMTAuNDg3IDkuOTQzIDEwLjQyIDEwLjE5MkMxMC4zNTMgMTAuNDM4IDEwLjI1OSAxMC42NDUgMTAuMTQyIDEwLjgwNkMxMC4wMjUgMTAuOTY4IDkuODgyIDExLjA5MSA5LjcyMSAxMS4xNzJDOS4zOTkgMTEuMzM0IDguOTYxIDExLjMzOCA4LjY1MiAxMS4xODdDOC40OTkgMTEuMTEyIDguMzY2IDExLjAxMiA4LjI1OSAxMC44OTFDOC4xNzQgMTAuNzk1IDguMTAzIDEwLjY3NSA4LjA0MSAxMC41MjRDOC4wNDEgMTAuNTI0IDcuODYyIDEwLjA3NyA3Ljg2MiA5LjU3N0M3Ljg2MiA5LjA3NyA4LjA0MSA4LjU3NSA4LjA0MSA4LjU3NUM4LjEwMyA4LjM5OCA4LjE3NyA4LjI1NyA4LjI2NSA4LjE0NUM4LjM3OSA4LjAwMiA4LjUyMSA3Ljg4NiA4LjY4OSA3LjhDOC44NTcgNy43MTQgOS4wNTQgNy42NzEgOS4yNzYgNy42NzFDOS40NjYgNy42NzEgOS42NCA3LjcwOCA5Ljc5MyA3Ljc4Wk0xNSAxM0gxVjE0SDE1VjEzWk0yLjgxMyAxMEwyLjA4NSAxMi4wMzFIMUwxLjAyNSAxMS45NTlMMy40NjYgNC44NzMwNUg0LjQwN0w2Ljg5MiAxMi4wMzFINS44MUw1LjAzMiAxMEgyLjgxM1pNMy45MzQgNi40MjIwNUgzLjkxMkwzLjAwNyA5LjE3NTA1SDQuODQ4TDMuOTM0IDYuNDIyMDVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=") 50% no-repeat}.hc-black .monaco-custom-checkbox.monaco-whole-word,.hc-black .monaco-custom-checkbox.monaco-whole-word:hover{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xIDJIMTVWM0gxVjJaTTE0IDRIMTNWMTJIMTRWNFpNMTEuMjcyIDguMzg3QzExLjE5NCA4LjA4OCAxMS4wNzMgNy44MjUgMTAuOTEyIDcuNjAxQzEwLjc1MSA3LjM3NyAxMC41NDcgNy4yIDEwLjMwMyA3LjA3MUMxMC4wNTkgNi45NDIgOS43NjkgNi44NzggOS40MzcgNi44NzhDOS4yMzkgNi44NzggOS4wNTcgNi45MDIgOC44OSA2Ljk1MUM4LjcyNSA3IDguNTc0IDcuMDY4IDguNDM3IDcuMTU2QzguMzAxIDcuMjQ0IDguMTggNy4zNSA4LjA3MiA3LjQ3NEw3Ljg5MyA3LjczMlY0LjU3OEg3VjEySDcuODkzVjExLjQyNUw4LjAxOSAxMS42QzguMTA2IDExLjcwMiA4LjIwOCAxMS43OSA4LjMyMyAxMS44NjlDOC40NCAxMS45NDcgOC41NzIgMTIuMDA5IDguNzIxIDEyLjA1NUM4Ljg3IDEyLjEwMSA5LjAzNSAxMi4xMjMgOS4yMTkgMTIuMTIzQzkuNTcyIDEyLjEyMyA5Ljg4NSAxMi4wNTIgMTAuMTU2IDExLjkxMUMxMC40MjggMTEuNzY4IDEwLjY1NSAxMS41NzMgMTAuODM4IDExLjMyNUMxMS4wMjEgMTEuMDc1IDExLjE1OSAxMC43ODIgMTEuMjUyIDEwLjQ0NkMxMS4zNDUgMTAuMTA4IDExLjM5MiA5Ljc0MyAxMS4zOTIgOS4zNDlDMTEuMzkxIDkuMDA3IDExLjM1MiA4LjY4NiAxMS4yNzIgOC4zODdaTTkuNzkzIDcuNzhDOS45NDQgNy44NTEgMTAuMDc1IDcuOTU2IDEwLjE4MyA4LjA5NEMxMC4yOTIgOC4yMzQgMTAuMzc3IDguNDA3IDEwLjQzOCA4LjYxMUMxMC40ODkgOC43ODUgMTAuNTIgOC45ODIgMTAuNTI3IDkuMTk4TDEwLjUyIDkuMzIzQzEwLjUyIDkuNjUgMTAuNDg3IDkuOTQzIDEwLjQyIDEwLjE5MkMxMC4zNTMgMTAuNDM4IDEwLjI1OSAxMC42NDUgMTAuMTQyIDEwLjgwNkMxMC4wMjUgMTAuOTY4IDkuODgyIDExLjA5MSA5LjcyMSAxMS4xNzJDOS4zOTkgMTEuMzM0IDguOTYxIDExLjMzOCA4LjY1MiAxMS4xODdDOC40OTkgMTEuMTEyIDguMzY2IDExLjAxMiA4LjI1OSAxMC44OTFDOC4xNzQgMTAuNzk1IDguMTAzIDEwLjY3NSA4LjA0MSAxMC41MjRDOC4wNDEgMTAuNTI0IDcuODYyIDEwLjA3NyA3Ljg2MiA5LjU3N0M3Ljg2MiA5LjA3NyA4LjA0MSA4LjU3NSA4LjA0MSA4LjU3NUM4LjEwMyA4LjM5OCA4LjE3NyA4LjI1NyA4LjI2NSA4LjE0NUM4LjM3OSA4LjAwMiA4LjUyMSA3Ljg4NiA4LjY4OSA3LjhDOC44NTcgNy43MTQgOS4wNTQgNy42NzEgOS4yNzYgNy42NzFDOS40NjYgNy42NzEgOS42NCA3LjcwOCA5Ljc5MyA3Ljc4Wk0xNSAxM0gxVjE0SDE1VjEzWk0yLjgxMyAxMEwyLjA4NSAxMi4wMzFIMUwxLjAyNSAxMS45NTlMMy40NjYgNC44NzMwNUg0LjQwN0w2Ljg5MiAxMi4wMzFINS44MUw1LjAzMiAxMEgyLjgxM1pNMy45MzQgNi40MjIwNUgzLjkxMkwzLjAwNyA5LjE3NTA1SDQuODQ4TDMuOTM0IDYuNDIyMDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K") 50% no-repeat}.vs .monaco-custom-checkbox.monaco-regex{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wMTIyIDJIMTAuOTg3OVY1LjExMzQ2TDEzLjU0ODkgMy41NTYwOUwxNC4wMzQgNC40NDA5NUwxMS40NzAyIDZMMTQuMDM0IDcuNTU5MDVMMTMuNTQ4OSA4LjQ0MzkxTDEwLjk4NzkgNi44ODY1NFYxMEgxMC4wMTIyVjYuODg2NTRMNy40NTExNCA4LjQ0MzkxTDYuOTY2MDYgNy41NTkwNUw5LjUyOTkgNkw2Ljk2NjA2IDQuNDQwOTVMNy40NTExNCAzLjU1NjA5TDEwLjAxMjIgNS4xMTM0NlYyWk0yIDEwSDZWMTRIMlYxMFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% no-repeat}.vs-dark .monaco-custom-checkbox.monaco-regex{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wMTIyIDJIMTAuOTg3OVY1LjExMzQ2TDEzLjU0ODkgMy41NTYwOUwxNC4wMzQgNC40NDA5NUwxMS40NzAyIDZMMTQuMDM0IDcuNTU5MDVMMTMuNTQ4OSA4LjQ0MzkxTDEwLjk4NzkgNi44ODY1NFYxMEgxMC4wMTIyVjYuODg2NTRMNy40NTExNCA4LjQ0MzkxTDYuOTY2MDYgNy41NTkwNUw5LjUyOTkgNkw2Ljk2NjA2IDQuNDQwOTVMNy40NTExNCAzLjU1NjA5TDEwLjAxMjIgNS4xMTM0NlYyWk0yIDEwSDZWMTRIMlYxMFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") 50% no-repeat}.hc-black .monaco-custom-checkbox.monaco-regex,.hc-black .monaco-custom-checkbox.monaco-regex:hover{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wMTIyIDJIMTAuOTg3OVY1LjExMzQ2TDEzLjU0ODkgMy41NTYwOUwxNC4wMzQgNC40NDA5NUwxMS40NzAyIDZMMTQuMDM0IDcuNTU5MDVMMTMuNTQ4OSA4LjQ0MzkxTDEwLjk4NzkgNi44ODY1NFYxMEgxMC4wMTIyVjYuODg2NTRMNy40NTExNCA4LjQ0MzkxTDYuOTY2MDYgNy41NTkwNUw5LjUyOTkgNkw2Ljk2NjA2IDQuNDQwOTVMNy40NTExNCAzLjU1NjA5TDEwLjAxMjIgNS4xMTM0NlYyWk0yIDEwSDZWMTRIMlYxMFoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=") 50% no-repeat}.monaco-checkbox .label{width:12px;height:12px;border:1px solid #000;background-color:transparent;display:inline-block}.monaco-checkbox .checkbox{position:absolute;overflow:hidden;clip:rect(0 0 0 0);height:1px;width:1px;margin:-1px;padding:0;border:0}.monaco-checkbox .checkbox:checked+.label{background-color:#000}.monaco-editor .find-widget{position:absolute;z-index:10;top:-44px;height:33px;overflow:hidden;line-height:19px;transition:top .2s linear;padding:0 4px;box-sizing:border-box}.monaco-editor .find-widget.hiddenEditor{display:none}.monaco-editor .find-widget.replaceToggled{top:-74px}.monaco-editor .find-widget.replaceToggled>.replace-part{display:-ms-flexbox;display:flex;display:-webkit-flex}.monaco-editor .find-widget.replaceToggled.visible,.monaco-editor .find-widget.visible{top:0}.monaco-editor .find-widget.multipleline{top:unset;bottom:10px}.monaco-editor .find-widget.multipleline.replaceToggled.visible,.monaco-editor .find-widget.multipleline.visible{top:0;bottom:unset}.monaco-editor .find-widget .monaco-inputbox.synthetic-focus{outline:1px solid -webkit-focus-ring-color;outline-offset:-1px}.monaco-editor .find-widget .monaco-inputbox .input{background-color:transparent;min-height:0}.monaco-editor .find-widget .monaco-findInput .input{font-size:13px}.monaco-editor .find-widget>.find-part,.monaco-editor .find-widget>.replace-part{margin:4px 0 0 17px;font-size:12px;display:-ms-flexbox;display:flex;display:-webkit-flex}.monaco-editor .find-widget>.find-part .monaco-inputbox,.monaco-editor .find-widget>.replace-part .monaco-inputbox{min-height:25px}.monaco-editor .find-widget>.replace-part .monaco-inputbox>.wrapper>.mirror{padding-right:22px}.monaco-editor .find-widget>.find-part .monaco-inputbox>.wrapper>.input,.monaco-editor .find-widget>.find-part .monaco-inputbox>.wrapper>.mirror,.monaco-editor .find-widget>.replace-part .monaco-inputbox>.wrapper>.input,.monaco-editor .find-widget>.replace-part .monaco-inputbox>.wrapper>.mirror{padding-top:2px;padding-bottom:2px}.monaco-editor .find-widget>.find-part .find-actions,.monaco-editor .find-widget>.replace-part .replace-actions{height:25px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.monaco-editor .find-widget .monaco-findInput{vertical-align:middle;display:-ms-flexbox;display:flex;display:-webkit-flex;-ms-flex:1;flex:1}.monaco-editor .find-widget .monaco-findInput .monaco-scrollable-element{width:100%}.monaco-editor .find-widget .monaco-findInput .monaco-scrollable-element .scrollbar.vertical{opacity:0}.monaco-editor .find-widget .matchesCount{margin:0 0 0 3px;padding:2px 0 0 2px;height:25px;vertical-align:middle;box-sizing:border-box;text-align:center;line-height:23px}.monaco-editor .find-widget .button,.monaco-editor .find-widget .matchesCount{display:-ms-flexbox;display:flex;display:-webkit-flex;-ms-flex:initial;flex:initial}.monaco-editor .find-widget .button{min-width:20px;width:20px;height:20px;margin-left:3px;background-position:50%;background-repeat:no-repeat;cursor:pointer}.monaco-editor .find-widget .button:not(.disabled):hover{background-color:rgba(0,0,0,.1)}.monaco-editor .find-widget .button.left{margin-left:0;margin-right:3px}.monaco-editor .find-widget .button.wide{width:auto;padding:1px 6px;top:-1px}.monaco-editor .find-widget .button.toggle{position:absolute;top:0;left:0;width:18px;height:100%;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box}.monaco-editor .find-widget .button.toggle.disabled{display:none}.monaco-editor .find-widget .previous{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy44NTM1IDYuMjkyODRMOC44NTM1NiAxLjI5Mjg1SDguMTQ2NDVMMy4xNDY0NSA2LjI5Mjg0TDMuODUzNTYgNi45OTk5NUw4IDIuODUzNTFWMTUuMDYwNkg5VjIuODUzNTFMMTMuMTQ2NCA2Ljk5OTk1TDEzLjg1MzUgNi4yOTI4NFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .find-widget .next{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjE0NjQ2IDkuNzY3ODNMOC4xNDY0NCAxNC43Njc4TDguODUzNTUgMTQuNzY3OEwxMy44NTM1IDkuNzY3ODNMMTMuMTQ2NCA5LjA2MDcyTDkgMTMuMjA3Mkw5IDEuMDAwMDZMOCAxLjAwMDA2TDggMTMuMjA3MkwzLjg1MzU2IDkuMDYwNzJMMy4xNDY0NiA5Ljc2NzgzWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .find-widget .disabled{opacity:.3;cursor:default}.monaco-editor .find-widget .monaco-checkbox{width:20px;height:20px;display:inline-block;vertical-align:middle;margin-left:3px}.monaco-editor .find-widget .monaco-checkbox .label{content:"";display:inline-block;background-repeat:no-repeat;background-position:50%;background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEgMTJMMSAxMUgxMFYxMkgxWk0xIDdIMTVWOEgxTDEgN1pNMTIgM1Y0SDFMMSAzSDEyWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K");width:20px;height:20px;border:none}.monaco-editor .find-widget .monaco-checkbox .checkbox:disabled+.label{opacity:.3;cursor:default}.monaco-editor .find-widget .monaco-checkbox .checkbox:not(:disabled)+.label{cursor:pointer}.monaco-editor .find-widget .monaco-checkbox .checkbox:not(:disabled):hover:before+.label{background-color:#ddd}.monaco-editor .find-widget .monaco-checkbox .checkbox:checked+.label{background-color:hsla(0,0%,39%,.2)}.monaco-editor .find-widget .close-fw{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04IDguNzA3MTRMMTEuNjQ2NCAxMi4zNTM2TDEyLjM1MzYgMTEuNjQ2NUw4LjcwNzExIDguMDAwMDRMMTIuMzUzNiA0LjM1MzU5TDExLjY0NjQgMy42NDY0OEw4IDcuMjkyOTNMNC4zNTM1NSAzLjY0NjQ4TDMuNjQ2NDUgNC4zNTM1OUw3LjI5Mjg5IDguMDAwMDRMMy42NDY0NSAxMS42NDY1TDQuMzUzNTUgMTIuMzUzNkw4IDguNzA3MTRaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .find-widget .expand{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDZMMTIuOTUyMSA2LjMzMzMyTDguMjg1MzkgMTFMNy42NjY2NyAxMUwzIDYuMzMzMzJMMy42MTg3MiA1LjcxNDZMNy45NzYwMyAxMC4wNzE5WiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .find-widget .collapse{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDguMDAwMDVMNS43MTQ2MSAxMi4zNTc0TDYuMzMzMzMgMTIuOTc2MUwxMSA4LjMwOTQxVjcuNjkwNjlMNi4zMzMzMyAzLjAyNDAyTDUuNzE0NjEgMy42NDI3NEwxMC4wNzE5IDguMDAwMDVaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .find-widget .replace{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjIyMSAzLjczOUw1LjQ4MiA2LjAwOEw3LjcgMy43ODRMNyAzLjA4NEw1Ljk4OCA0LjA5MUw1Ljk4IDIuNDkxQzUuOTc5MDkgMi4zNTU2NyA2LjAzMDY4IDIuMjI1MjUgNi4xMjM5MiAyLjEyNzE2QzYuMjE3MTYgMi4wMjkwOCA2LjM0NDggMS45NzA5NSA2LjQ4IDEuOTY1SDhWMUg2LjQ4QzYuMjg0OTYgMS4wMDAyNiA2LjA5MTg5IDEuMDM5MDIgNS45MTE4NiAxLjExNDA1QzUuNzMxODMgMS4xODkwOCA1LjU2ODM4IDEuMjk4OTIgNS40MzA4OCAxLjQzNzI1QzUuMjkzMzggMS41NzU1OCA1LjE4NDU1IDEuNzM5NjkgNS4xMTA2MSAxLjkyMDE4QzUuMDM2NjcgMi4xMDA2NiA0Ljk5OTA4IDIuMjkzOTYgNSAyLjQ4OVY0LjFMMy45MjcgMy4wMzNMMy4yMjEgMy43MzlaTTkuODkwMTQgNS41MzI3N0g5LjkwMTQxQzEwLjA4MzYgNS44NDQyNiAxMC4zNTIxIDYgMTAuNzA3IDZDMTEuMDk5NSA2IDExLjQxMzEgNS44MzIzNiAxMS42NDc5IDUuNDk3MDhDMTEuODgyNiA1LjE2MTggMTIgNC43MTcyOCAxMiA0LjE2MzUzQzEyIDMuNjUzMDQgMTEuODk5NSAzLjI1MDcgMTEuNjk4NiAyLjk1NjUyQzExLjQ5NzcgMi42NjIzNCAxMS4yMTEzIDIuNTE1MjUgMTAuODM5NCAyLjUxNTI1QzEwLjQzMzggMi41MTUyNSAxMC4xMjExIDIuNzA4ODUgOS45MDE0MSAzLjA5NjA0SDkuODkwMTRWMUg5VjUuOTE4ODhIOS44OTAxNFY1LjUzMjc3Wk05Ljg3NjA2IDQuNDcxNzdWNC4xMzEwOEM5Ljg3NjA2IDMuODg0NDkgOS45MzQyNyAzLjY4NDQgMTAuMDUwNyAzLjUzMDgyQzEwLjE2OSAzLjM3NzI0IDEwLjMxNzQgMy4zMDA0NSAxMC40OTU4IDMuMzAwNDVDMTAuNjg1NCAzLjMwMDQ1IDEwLjgzMSAzLjM3ODMzIDEwLjkzMjQgMy41MzQwN0MxMS4wMzU3IDMuNjg3NjUgMTEuMDg3MyAzLjkwMTggMTEuMDg3MyA0LjE3NjUxQzExLjA4NzMgNC41MDc0NiAxMS4wMzEgNC43NjM3OSAxMC45MTgzIDQuOTQ1NDlDMTAuODA3NSA1LjEyNTAzIDEwLjY1MDcgNS4yMTQ4IDEwLjQ0NzkgNS4yMTQ4QzEwLjI4MDggNS4yMTQ4IDEwLjE0MzcgNS4xNDQ0OSAxMC4wMzY2IDUuMDAzODlDOS45Mjk1OCA0Ljg2MzI5IDkuODc2MDYgNC42ODU5MiA5Ljg3NjA2IDQuNDcxNzdaTTkgMTIuNzY5MUM4Ljc0NDMyIDEyLjkyMyA4LjM3NTE1IDEzIDcuODkyNDcgMTNDNy4zMjg1NSAxMyA2Ljg3MjE2IDEyLjgyMjUgNi41MjMzIDEyLjQ2NzRDNi4xNzQ0MyAxMi4xMTI0IDYgMTEuNjU0MyA2IDExLjA5MzFDNiAxMC40NDUxIDYuMTg2MzggOS45MzQ4NCA2LjU1OTE0IDkuNTYyNEM2LjkzNDI5IDkuMTg3NDcgNy40MzQ4OSA5LjAwMDAxIDguMDYwOTMgOS4wMDAwMUM4LjQ5MzQzIDkuMDAwMDEgOC44MDY0NSA5LjA1OTYgOSA5LjE3ODc4VjEwLjE3NjlDOC43NjM0NCA5Ljk5MzE5IDguNDk5NCA5LjkwMTMyIDguMjA3ODkgOS45MDEzMkM3Ljg4MjkyIDkuOTAxMzIgNy42MjQ4NSAxMC4wMDA2IDcuNDMzNjkgMTAuMTk5M0M3LjI0NDkyIDEwLjM5NTQgNy4xNTA1NCAxMC42NjczIDcuMTUwNTQgMTEuMDE0OUM3LjE1MDU0IDExLjM1MjYgNy4yNDEzNCAxMS42MTgzIDcuNDIyOTQgMTEuODExOUM3LjYwNDU0IDEyLjAwMzEgNy44NTQyNCAxMi4wOTg3IDguMTcyMDQgMTIuMDk4N0M4LjQ1NCAxMi4wOTg3IDguNzI5OTkgMTIuMDA2OCA5IDExLjgyMzFWMTIuNzY5MVpNNCA3TDMgOFYxNEw0IDE1SDExTDEyIDE0VjhMMTEgN0g0Wk00IDhINUgxMEgxMVY5VjEzVjE0SDEwSDVINFYxM1Y5VjhaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .find-widget .replace-all{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS42MDA5IDIuNjc2ODNDMTEuNzQ3NCAyLjM2NzA4IDExLjk1NTkgMi4yMTIyIDEyLjIyNjMgMi4yMTIyQzEyLjQ3NDIgMi4yMTIyIDEyLjY2NTEgMi4zMjk4NyAxMi43OTkxIDIuNTY1MjJDMTIuOTMzIDIuODAwNTYgMTMgMy4xMjI0MyAxMyAzLjUzMDgyQzEzIDMuOTczODMgMTIuOTIxOCA0LjMyOTQ0IDEyLjc2NTMgNC41OTc2NkMxMi42MDg4IDQuODY1ODkgMTIuMzk5NyA1IDEyLjEzOCA1QzExLjkwMTQgNSAxMS43MjI0IDQuODc1NDEgMTEuNjAwOSA0LjYyNjIySDExLjU5MzRWNC45MzUxMUgxMVYxSDExLjU5MzRWMi42NzY4M0gxMS42MDA5Wk0xMS41ODQgMy43Nzc0MkMxMS41ODQgMy45NDg3MyAxMS42MTk3IDQuMDkwNjMgMTEuNjkxMSA0LjIwMzExQzExLjc2MjQgNC4zMTU2IDExLjg1MzggNC4zNzE4NCAxMS45NjUzIDQuMzcxODRDMTIuMTAwNSA0LjM3MTg0IDEyLjIwNSA0LjMwMDAyIDEyLjI3ODkgNC4xNTYzOUMxMi4zNTQgNC4wMTEwMyAxMi4zOTE1IDMuODA1OTcgMTIuMzkxNSAzLjU0MTIxQzEyLjM5MTUgMy4zMjE0NCAxMi4zNTcxIDMuMTUwMTIgMTIuMjg4MyAzLjAyNzI2QzEyLjIyMDcgMi45MDI2NiAxMi4xMjM2IDIuODQwMzYgMTEuOTk3MiAyLjg0MDM2QzExLjg3ODIgMi44NDAzNiAxMS43NzkzIDIuOTAxOCAxMS43MDA1IDMuMDI0NjZDMTEuNjIyOCAzLjE0NzUyIDExLjU4NCAzLjMwNzU5IDExLjU4NCAzLjUwNDg3VjMuNzc3NDJaTTQuMTE5NjkgNy42OTVMMiA1LjU2NzgxTDIuNjYxODggNC45MDU5NEwzLjY2NzgxIDUuOTA2MjVWNC4zOTU5NEMzLjY2Njk1IDQuMjEzMDkgMy43MDIxOSA0LjAzMTg3IDMuNzcxNSAzLjg2MjY2QzMuODQwODIgMy42OTM0NiAzLjk0Mjg2IDMuNTM5NjEgNC4wNzE3NiAzLjQwOTkyQzQuMjAwNjYgMy4yODAyMyA0LjM1MzkgMy4xNzcyNyA0LjUyMjY4IDMuMTA2OTJDNC42OTE0NiAzLjAzNjU4IDQuODcyNDYgMy4wMDAyNCA1LjA1NTMxIDNINy4zOTkwNlYzLjkwNDY5SDUuMDU1MzFDNC45Mjg1NiAzLjkxMDI2IDQuODA4OSAzLjk2NDc2IDQuNzIxNDkgNC4wNTY3MkM0LjYzNDA4IDQuMTQ4NjggNC41ODU3MSA0LjI3MDk0IDQuNTg2NTYgNC4zOTc4MUw0LjU5NDA2IDUuODk3ODFMNS41NDI4MSA0Ljk1Mzc1TDYuMTk5MDYgNS42MUw0LjExOTY5IDcuNjk1Wk05LjM1NTYgNC45MzAxN0gxMFYzLjIyMDY3QzEwIDIuNDA2ODkgOS42ODUzNCAyIDkuMDU2MDMgMkM4LjkyMDk4IDIgOC43NzA4MyAyLjAyNDIxIDguNjA1NiAyLjA3MjYzQzguNDQxODEgMi4xMjEwNCA4LjMxMjUgMi4xNzY5MSA4LjIxNzY3IDIuMjQwMjJWMi45MDUwM0M4LjQ1NDc0IDIuNzAyMDUgOC43MDQ3NCAyLjYwMDU2IDguOTY3NjcgMi42MDA1NkM5LjIyOTE3IDIuNjAwNTYgOS4zNTk5MSAyLjc1Njk4IDkuMzU5OTEgMy4wNjk4M0w4Ljc2MDc4IDMuMTczMThDOC4yNTM1OSAzLjI1ODg1IDggMy41NzkxNCA4IDQuMTM0MDhDOCA0LjM5NjY1IDguMDYxMDYgNC42MDcwOCA4LjE4MzE5IDQuNzY1MzZDOC4zMDY3NSA0LjkyMTc5IDguNDc1NTcgNSA4LjY4OTY2IDVDOC45Nzk4OSA1IDkuMTk4OTkgNC44Mzk4NSA5LjM0Njk4IDQuNTE5NTVIOS4zNTU2VjQuOTMwMTdaTTkuMzU5OTEgMy41NzU0MlYzLjc2ODE2QzkuMzU5OTEgMy45NDMyIDkuMzE5NjggNC4wODg0NSA5LjIzOTIyIDQuMjAzOTFDOS4xNTg3NiA0LjMxNzUgOS4wNTQ2IDQuMzc0MyA4LjkyNjcyIDQuMzc0M0M4LjgzNDc3IDQuMzc0MyA4Ljc2MTQ5IDQuMzQyNjQgOC43MDY5IDQuMjc5MzNDOC42NTM3NCA0LjIxNDE1IDguNjI3MTYgNC4xMzEyOCA4LjYyNzE2IDQuMDMwNzNDOC42MjcxNiAzLjgwOTEyIDguNzM3NzkgMy42Nzk3IDguOTU5MDUgMy42NDI0Nkw5LjM1OTkxIDMuNTc1NDJaTTcgMTIuOTMwMkg2LjM1NTZWMTIuNTE5Nkg2LjM0Njk4QzYuMTk4OTkgMTIuODM5OSA1Ljk3OTg5IDEzIDUuNjg5NjYgMTNDNS40NzU1NyAxMyA1LjMwNjc1IDEyLjkyMTggNS4xODMxOSAxMi43NjU0QzUuMDYxMDYgMTIuNjA3MSA1IDEyLjM5NjYgNSAxMi4xMzQxQzUgMTEuNTc5MSA1LjI1MzU5IDExLjI1ODggNS43NjA3OCAxMS4xNzMyTDYuMzU5OTEgMTEuMDY5OEM2LjM1OTkxIDEwLjc1NyA2LjIyOTE3IDEwLjYwMDYgNS45Njc2NyAxMC42MDA2QzUuNzA0NzQgMTAuNjAwNiA1LjQ1NDc0IDEwLjcwMiA1LjIxNzY3IDEwLjkwNVYxMC4yNDAyQzUuMzEyNSAxMC4xNzY5IDUuNDQxODEgMTAuMTIxIDUuNjA1NiAxMC4wNzI2QzUuNzcwODMgMTAuMDI0MiA1LjkyMDk4IDEwIDYuMDU2MDMgMTBDNi42ODUzNCAxMCA3IDEwLjQwNjkgNyAxMS4yMjA3VjEyLjkzMDJaTTYuMzU5OTEgMTEuNzY4MlYxMS41NzU0TDUuOTU5MDUgMTEuNjQyNUM1LjczNzc5IDExLjY3OTcgNS42MjcxNiAxMS44MDkxIDUuNjI3MTYgMTIuMDMwN0M1LjYyNzE2IDEyLjEzMTMgNS42NTM3NCAxMi4yMTQyIDUuNzA2OSAxMi4yNzkzQzUuNzYxNDkgMTIuMzQyNiA1LjgzNDc3IDEyLjM3NDMgNS45MjY3MiAxMi4zNzQzQzYuMDU0NiAxMi4zNzQzIDYuMTU4NzYgMTIuMzE3NSA2LjIzOTIyIDEyLjIwMzlDNi4zMTk2OCAxMi4wODg1IDYuMzU5OTEgMTEuOTQzMiA2LjM1OTkxIDExLjc2ODJaTTkuMjYxNjUgMTNDOS41ODM0MyAxMyA5LjgyOTU1IDEyLjk0MjMgMTAgMTIuODI2OFYxMi4xMTczQzkuODE5OTkgMTIuMjU1MSA5LjYzNiAxMi4zMjQgOS40NDgwMyAxMi4zMjRDOS4yMzYxNiAxMi4zMjQgOS4wNjk2OSAxMi4yNTIzIDguOTQ4NjMgMTIuMTA4OUM4LjgyNzU2IDExLjk2MzcgOC43NjcwMiAxMS43NjQ0IDguNzY3MDIgMTEuNTExMkM4Ljc2NzAyIDExLjI1MDUgOC44Mjk5NSAxMS4wNDY2IDguOTU1NzkgMTAuODk5NEM5LjA4MzIzIDEwLjc1MDUgOS4yNTUyOCAxMC42NzYgOS40NzE5MiAxMC42NzZDOS42NjYyNyAxMC42NzYgOS44NDIyOSAxMC43NDQ5IDEwIDEwLjg4MjdWMTAuMTM0MUM5Ljg3MDk3IDEwLjA0NDcgOS42NjIyOSAxMCA5LjM3Mzk1IDEwQzguOTU2NTkgMTAgOC42MjI4NiAxMC4xNDA2IDguMzcyNzYgMTAuNDIxOEM4LjEyNDI1IDEwLjcwMTEgOCAxMS4wODM4IDggMTEuNTY5OEM4IDExLjk5MDcgOC4xMTYyOSAxMi4zMzQzIDguMzQ4ODcgMTIuNjAwNkM4LjU4MTQ0IDEyLjg2NjkgOC44ODU3IDEzIDkuMjYxNjUgMTNaTTIgOUwzIDhIMTJMMTMgOVYxNEwxMiAxNUgzTDIgMTRWOVpNMyA5VjE0SDEyVjlIM1pNNiA3TDcgNkgxNEwxNSA3VjEyTDE0IDEzVjEyVjdIN0g2WiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .find-widget>.replace-part{display:none}.monaco-editor .find-widget>.replace-part>.monaco-findInput{position:relative;display:-ms-flexbox;display:flex;display:-webkit-flex;vertical-align:middle;-ms-flex:auto;flex:auto;-ms-flex-positive:0;flex-grow:0;-ms-flex-negative:0;flex-shrink:0}.monaco-editor .find-widget>.replace-part>.monaco-findInput>.controls{position:absolute;top:3px;right:2px}.monaco-editor .find-widget.reduced-find-widget .matchesCount,.monaco-editor .find-widget.reduced-find-widget .monaco-checkbox{display:none}.monaco-editor .find-widget.narrow-find-widget{max-width:257px!important}.monaco-editor .find-widget.collapsed-find-widget{max-width:170px!important}.monaco-editor .find-widget.collapsed-find-widget .button.next,.monaco-editor .find-widget.collapsed-find-widget .button.previous,.monaco-editor .find-widget.collapsed-find-widget .button.replace,.monaco-editor .find-widget.collapsed-find-widget .button.replace-all,.monaco-editor .find-widget.collapsed-find-widget>.find-part .monaco-findInput .controls{display:none}.monaco-editor .findMatch{-webkit-animation-duration:0;-webkit-animation-name:inherit!important;-moz-animation-duration:0;-moz-animation-name:inherit!important;-ms-animation-duration:0;-ms-animation-name:inherit!important;animation-duration:0;animation-name:inherit!important}.monaco-editor .find-widget .monaco-sash{width:2px!important;margin-left:-4px}.monaco-editor.hc-black .find-widget .previous,.monaco-editor.vs-dark .find-widget .previous{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy44NTM1IDYuMjkyODRMOC44NTM1NiAxLjI5Mjg1SDguMTQ2NDVMMy4xNDY0NSA2LjI5Mjg0TDMuODUzNTYgNi45OTk5NUw4IDIuODUzNTFWMTUuMDYwNkg5VjIuODUzNTFMMTMuMTQ2NCA2Ljk5OTk1TDEzLjg1MzUgNi4yOTI4NFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .find-widget .next,.monaco-editor.vs-dark .find-widget .next{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjE0NjQ2IDkuNzY3ODNMOC4xNDY0NCAxNC43Njc4TDguODUzNTUgMTQuNzY3OEwxMy44NTM1IDkuNzY3ODNMMTMuMTQ2NCA5LjA2MDcyTDkgMTMuMjA3Mkw5IDEuMDAwMDZMOCAxLjAwMDA2TDggMTMuMjA3MkwzLjg1MzU2IDkuMDYwNzJMMy4xNDY0NiA5Ljc2NzgzWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .find-widget .monaco-checkbox .label,.monaco-editor.vs-dark .find-widget .monaco-checkbox .label{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEgMTJMMSAxMUgxMFYxMkgxWk0xIDdIMTVWOEgxTDEgN1pNMTIgM1Y0SDFMMSAzSDEyWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.vs-dark .find-widget .monaco-checkbox .checkbox:not(:disabled):hover:before+.label{background-color:hsla(0,0%,100%,.1)}.monaco-editor.hc-black .find-widget .close-fw,.monaco-editor.vs-dark .find-widget .close-fw{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04IDguNzA3MTRMMTEuNjQ2NCAxMi4zNTM2TDEyLjM1MzYgMTEuNjQ2NUw4LjcwNzExIDguMDAwMDRMMTIuMzUzNiA0LjM1MzU5TDExLjY0NjQgMy42NDY0OEw4IDcuMjkyOTNMNC4zNTM1NSAzLjY0NjQ4TDMuNjQ2NDUgNC4zNTM1OUw3LjI5Mjg5IDguMDAwMDRMMy42NDY0NSAxMS42NDY1TDQuMzUzNTUgMTIuMzUzNkw4IDguNzA3MTRaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .find-widget .replace,.monaco-editor.vs-dark .find-widget .replace{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjIyMSAzLjczOUw1LjQ4MiA2LjAwOEw3LjcgMy43ODRMNyAzLjA4NEw1Ljk4OCA0LjA5MUw1Ljk4IDIuNDkxQzUuOTc5MDkgMi4zNTU2NyA2LjAzMDY4IDIuMjI1MjUgNi4xMjM5MiAyLjEyNzE2QzYuMjE3MTYgMi4wMjkwOCA2LjM0NDggMS45NzA5NSA2LjQ4IDEuOTY1SDhWMUg2LjQ4QzYuMjg0OTYgMS4wMDAyNiA2LjA5MTg5IDEuMDM5MDIgNS45MTE4NiAxLjExNDA1QzUuNzMxODMgMS4xODkwOCA1LjU2ODM4IDEuMjk4OTIgNS40MzA4OCAxLjQzNzI1QzUuMjkzMzggMS41NzU1OCA1LjE4NDU1IDEuNzM5NjkgNS4xMTA2MSAxLjkyMDE4QzUuMDM2NjcgMi4xMDA2NiA0Ljk5OTA4IDIuMjkzOTYgNSAyLjQ4OVY0LjFMMy45MjcgMy4wMzNMMy4yMjEgMy43MzlaTTkuODkwMTQgNS41MzI3N0g5LjkwMTQxQzEwLjA4MzYgNS44NDQyNiAxMC4zNTIxIDYgMTAuNzA3IDZDMTEuMDk5NSA2IDExLjQxMzEgNS44MzIzNiAxMS42NDc5IDUuNDk3MDhDMTEuODgyNiA1LjE2MTggMTIgNC43MTcyOCAxMiA0LjE2MzUzQzEyIDMuNjUzMDQgMTEuODk5NSAzLjI1MDcgMTEuNjk4NiAyLjk1NjUyQzExLjQ5NzcgMi42NjIzNCAxMS4yMTEzIDIuNTE1MjUgMTAuODM5NCAyLjUxNTI1QzEwLjQzMzggMi41MTUyNSAxMC4xMjExIDIuNzA4ODUgOS45MDE0MSAzLjA5NjA0SDkuODkwMTRWMUg5VjUuOTE4ODhIOS44OTAxNFY1LjUzMjc3Wk05Ljg3NjA2IDQuNDcxNzdWNC4xMzEwOEM5Ljg3NjA2IDMuODg0NDkgOS45MzQyNyAzLjY4NDQgMTAuMDUwNyAzLjUzMDgyQzEwLjE2OSAzLjM3NzI0IDEwLjMxNzQgMy4zMDA0NSAxMC40OTU4IDMuMzAwNDVDMTAuNjg1NCAzLjMwMDQ1IDEwLjgzMSAzLjM3ODMzIDEwLjkzMjQgMy41MzQwN0MxMS4wMzU3IDMuNjg3NjUgMTEuMDg3MyAzLjkwMTggMTEuMDg3MyA0LjE3NjUxQzExLjA4NzMgNC41MDc0NiAxMS4wMzEgNC43NjM3OSAxMC45MTgzIDQuOTQ1NDlDMTAuODA3NSA1LjEyNTAzIDEwLjY1MDcgNS4yMTQ4IDEwLjQ0NzkgNS4yMTQ4QzEwLjI4MDggNS4yMTQ4IDEwLjE0MzcgNS4xNDQ0OSAxMC4wMzY2IDUuMDAzODlDOS45Mjk1OCA0Ljg2MzI5IDkuODc2MDYgNC42ODU5MiA5Ljg3NjA2IDQuNDcxNzdaTTkgMTIuNzY5MUM4Ljc0NDMzIDEyLjkyMyA4LjM3NTE1IDEzIDcuODkyNDcgMTNDNy4zMjg1NSAxMyA2Ljg3MjE2IDEyLjgyMjUgNi41MjMzIDEyLjQ2NzRDNi4xNzQ0MyAxMi4xMTI0IDYgMTEuNjU0MyA2IDExLjA5MzFDNiAxMC40NDUxIDYuMTg2MzggOS45MzQ4NCA2LjU1OTE0IDkuNTYyNEM2LjkzNDI5IDkuMTg3NDcgNy40MzQ4OSA5LjAwMDAxIDguMDYwOTMgOS4wMDAwMUM4LjQ5MzQzIDkuMDAwMDEgOC44MDY0NSA5LjA1OTYgOSA5LjE3ODc4VjEwLjE3NjlDOC43NjM0NCA5Ljk5MzE5IDguNDk5NCA5LjkwMTMyIDguMjA3ODkgOS45MDEzMkM3Ljg4MjkyIDkuOTAxMzIgNy42MjQ4NSAxMC4wMDA2IDcuNDMzNjkgMTAuMTk5M0M3LjI0NDkyIDEwLjM5NTQgNy4xNTA1NCAxMC42NjczIDcuMTUwNTQgMTEuMDE0OUM3LjE1MDU0IDExLjM1MjYgNy4yNDEzNCAxMS42MTgzIDcuNDIyOTQgMTEuODExOUM3LjYwNDU0IDEyLjAwMzEgNy44NTQyNCAxMi4wOTg3IDguMTcyMDQgMTIuMDk4N0M4LjQ1NCAxMi4wOTg3IDguNzI5OTkgMTIuMDA2OCA5IDExLjgyMzFWMTIuNzY5MVpNNCA3TDMgOFYxNEw0IDE1SDExTDEyIDE0VjhMMTEgN0g0Wk00IDhINUgxMEgxMVY5VjEzVjE0SDEwSDVINFYxM1Y5VjhaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .find-widget .replace-all,.monaco-editor.vs-dark .find-widget .replace-all{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS42MDA5IDIuNjc2ODNDMTEuNzQ3NCAyLjM2NzA4IDExLjk1NTkgMi4yMTIyIDEyLjIyNjMgMi4yMTIyQzEyLjQ3NDIgMi4yMTIyIDEyLjY2NTEgMi4zMjk4NyAxMi43OTkxIDIuNTY1MjJDMTIuOTMzIDIuODAwNTYgMTMgMy4xMjI0MyAxMyAzLjUzMDgyQzEzIDMuOTczODMgMTIuOTIxOCA0LjMyOTQ0IDEyLjc2NTMgNC41OTc2NkMxMi42MDg4IDQuODY1ODkgMTIuMzk5NyA1IDEyLjEzOCA1QzExLjkwMTQgNSAxMS43MjI0IDQuODc1NDEgMTEuNjAwOSA0LjYyNjIySDExLjU5MzRWNC45MzUxMUgxMVYxSDExLjU5MzRWMi42NzY4M0gxMS42MDA5Wk0xMS41ODQgMy43Nzc0MkMxMS41ODQgMy45NDg3MyAxMS42MTk3IDQuMDkwNjMgMTEuNjkxMSA0LjIwMzExQzExLjc2MjQgNC4zMTU2IDExLjg1MzggNC4zNzE4NCAxMS45NjUzIDQuMzcxODRDMTIuMTAwNSA0LjM3MTg0IDEyLjIwNSA0LjMwMDAyIDEyLjI3ODkgNC4xNTYzOUMxMi4zNTQgNC4wMTEwMyAxMi4zOTE1IDMuODA1OTcgMTIuMzkxNSAzLjU0MTIxQzEyLjM5MTUgMy4zMjE0NCAxMi4zNTcxIDMuMTUwMTIgMTIuMjg4MyAzLjAyNzI2QzEyLjIyMDcgMi45MDI2NiAxMi4xMjM2IDIuODQwMzYgMTEuOTk3MiAyLjg0MDM2QzExLjg3ODIgMi44NDAzNiAxMS43NzkzIDIuOTAxOCAxMS43MDA1IDMuMDI0NjZDMTEuNjIyOCAzLjE0NzUyIDExLjU4NCAzLjMwNzU5IDExLjU4NCAzLjUwNDg3VjMuNzc3NDJaTTQuMTE5NjkgNy42OTVMMiA1LjU2NzgxTDIuNjYxODggNC45MDU5NEwzLjY2NzgxIDUuOTA2MjVWNC4zOTU5NEMzLjY2Njk1IDQuMjEzMDkgMy43MDIxOSA0LjAzMTg3IDMuNzcxNSAzLjg2MjY2QzMuODQwODIgMy42OTM0NiAzLjk0Mjg2IDMuNTM5NjEgNC4wNzE3NiAzLjQwOTkyQzQuMjAwNjYgMy4yODAyMyA0LjM1MzkgMy4xNzcyNyA0LjUyMjY4IDMuMTA2OTJDNC42OTE0NiAzLjAzNjU4IDQuODcyNDYgMy4wMDAyNCA1LjA1NTMxIDNINy4zOTkwNlYzLjkwNDY5SDUuMDU1MzFDNC45Mjg1NiAzLjkxMDI2IDQuODA4OSAzLjk2NDc2IDQuNzIxNDkgNC4wNTY3MkM0LjYzNDA4IDQuMTQ4NjggNC41ODU3MSA0LjI3MDk0IDQuNTg2NTYgNC4zOTc4MUw0LjU5NDA2IDUuODk3ODFMNS41NDI4MSA0Ljk1Mzc1TDYuMTk5MDYgNS42MUw0LjExOTY5IDcuNjk1Wk05LjM1NTYgNC45MzAxN0gxMFYzLjIyMDY3QzEwIDIuNDA2ODkgOS42ODUzNCAyIDkuMDU2MDMgMkM4LjkyMDk4IDIgOC43NzA4MyAyLjAyNDIxIDguNjA1NiAyLjA3MjYzQzguNDQxODEgMi4xMjEwNCA4LjMxMjUgMi4xNzY5MSA4LjIxNzY3IDIuMjQwMjJWMi45MDUwM0M4LjQ1NDc0IDIuNzAyMDUgOC43MDQ3NCAyLjYwMDU2IDguOTY3NjcgMi42MDA1NkM5LjIyOTE3IDIuNjAwNTYgOS4zNTk5MSAyLjc1Njk4IDkuMzU5OTEgMy4wNjk4M0w4Ljc2MDc4IDMuMTczMThDOC4yNTM1OSAzLjI1ODg1IDggMy41NzkxNCA4IDQuMTM0MDhDOCA0LjM5NjY1IDguMDYxMDYgNC42MDcwOCA4LjE4MzE5IDQuNzY1MzZDOC4zMDY3NSA0LjkyMTc5IDguNDc1NTcgNSA4LjY4OTY2IDVDOC45Nzk4OSA1IDkuMTk4OTkgNC44Mzk4NSA5LjM0Njk4IDQuNTE5NTVIOS4zNTU2VjQuOTMwMTdaTTkuMzU5OTEgMy41NzU0MlYzLjc2ODE2QzkuMzU5OTEgMy45NDMyIDkuMzE5NjggNC4wODg0NSA5LjIzOTIyIDQuMjAzOTFDOS4xNTg3NiA0LjMxNzUgOS4wNTQ2IDQuMzc0MyA4LjkyNjcyIDQuMzc0M0M4LjgzNDc3IDQuMzc0MyA4Ljc2MTQ5IDQuMzQyNjQgOC43MDY5IDQuMjc5MzNDOC42NTM3NCA0LjIxNDE1IDguNjI3MTYgNC4xMzEyOCA4LjYyNzE2IDQuMDMwNzNDOC42MjcxNiAzLjgwOTEyIDguNzM3NzkgMy42Nzk3IDguOTU5MDUgMy42NDI0Nkw5LjM1OTkxIDMuNTc1NDJaTTcgMTIuOTMwMkg2LjM1NTZWMTIuNTE5Nkg2LjM0Njk4QzYuMTk4OTkgMTIuODM5OSA1Ljk3OTg5IDEzIDUuNjg5NjYgMTNDNS40NzU1NyAxMyA1LjMwNjc1IDEyLjkyMTggNS4xODMxOSAxMi43NjU0QzUuMDYxMDYgMTIuNjA3MSA1IDEyLjM5NjYgNSAxMi4xMzQxQzUgMTEuNTc5MSA1LjI1MzU5IDExLjI1ODggNS43NjA3OCAxMS4xNzMyTDYuMzU5OTEgMTEuMDY5OEM2LjM1OTkxIDEwLjc1NyA2LjIyOTE3IDEwLjYwMDYgNS45Njc2NyAxMC42MDA2QzUuNzA0NzQgMTAuNjAwNiA1LjQ1NDc0IDEwLjcwMiA1LjIxNzY3IDEwLjkwNVYxMC4yNDAyQzUuMzEyNSAxMC4xNzY5IDUuNDQxODEgMTAuMTIxIDUuNjA1NiAxMC4wNzI2QzUuNzcwODMgMTAuMDI0MiA1LjkyMDk4IDEwIDYuMDU2MDMgMTBDNi42ODUzNCAxMCA3IDEwLjQwNjkgNyAxMS4yMjA3VjEyLjkzMDJaTTYuMzU5OTEgMTEuNzY4MlYxMS41NzU0TDUuOTU5MDUgMTEuNjQyNUM1LjczNzc5IDExLjY3OTcgNS42MjcxNiAxMS44MDkxIDUuNjI3MTYgMTIuMDMwN0M1LjYyNzE2IDEyLjEzMTMgNS42NTM3NCAxMi4yMTQyIDUuNzA2OSAxMi4yNzkzQzUuNzYxNDkgMTIuMzQyNiA1LjgzNDc3IDEyLjM3NDMgNS45MjY3MiAxMi4zNzQzQzYuMDU0NiAxMi4zNzQzIDYuMTU4NzYgMTIuMzE3NSA2LjIzOTIyIDEyLjIwMzlDNi4zMTk2OCAxMi4wODg1IDYuMzU5OTEgMTEuOTQzMiA2LjM1OTkxIDExLjc2ODJaTTkuMjYxNjUgMTNDOS41ODM0MyAxMyA5LjgyOTU1IDEyLjk0MjMgMTAgMTIuODI2OFYxMi4xMTczQzkuODE5OTkgMTIuMjU1MSA5LjYzNiAxMi4zMjQgOS40NDgwMyAxMi4zMjRDOS4yMzYxNiAxMi4zMjQgOS4wNjk2OSAxMi4yNTIzIDguOTQ4NjMgMTIuMTA4OUM4LjgyNzU2IDExLjk2MzcgOC43NjcwMiAxMS43NjQ0IDguNzY3MDIgMTEuNTExMkM4Ljc2NzAyIDExLjI1MDUgOC44Mjk5NSAxMS4wNDY2IDguOTU1NzkgMTAuODk5NEM5LjA4MzIzIDEwLjc1MDUgOS4yNTUyOCAxMC42NzYgOS40NzE5MiAxMC42NzZDOS42NjYyNyAxMC42NzYgOS44NDIyOSAxMC43NDQ5IDEwIDEwLjg4MjdWMTAuMTM0MUM5Ljg3MDk3IDEwLjA0NDcgOS42NjIyOSAxMCA5LjM3Mzk1IDEwQzguOTU2NTkgMTAgOC42MjI4NiAxMC4xNDA2IDguMzcyNzYgMTAuNDIxOEM4LjEyNDI1IDEwLjcwMTEgOCAxMS4wODM4IDggMTEuNTY5OEM4IDExLjk5MDcgOC4xMTYyOSAxMi4zMzQzIDguMzQ4ODcgMTIuNjAwNkM4LjU4MTQ0IDEyLjg2NjkgOC44ODU3IDEzIDkuMjYxNjUgMTNaTTIgOUwzIDhIMTJMMTMgOVYxNEwxMiAxNUgzTDIgMTRWOVpNMyA5VjE0SDEyVjlIM1pNNiA3TDcgNkgxNEwxNSA3VjEyTDE0IDEzVjEyVjdIN0g2WiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .find-widget .expand,.monaco-editor.vs-dark .find-widget .expand{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDZMMTIuOTUyMSA2LjMzMzMyTDguMjg1MzkgMTFMNy42NjY2NyAxMUwzIDYuMzMzMzJMMy42MTg3MiA1LjcxNDZMNy45NzYwMyAxMC4wNzE5WiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .find-widget .collapse,.monaco-editor.vs-dark .find-widget .collapse{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDguMDAwMDVMNS43MTQ2MSAxMi4zNTc0TDYuMzMzMzMgMTIuOTc2MUwxMSA4LjMwOTQxVjcuNjkwNjlMNi4zMzMzMyAzLjAyNDAyTDUuNzE0NjEgMy42NDI3NEwxMC4wNzE5IDguMDAwMDVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .find-widget .button:not(.disabled):hover,.monaco-editor.vs-dark .find-widget .button:not(.disabled):hover{background-color:hsla(0,0%,100%,.1)}.monaco-editor.hc-black .find-widget .button:before{position:relative;top:1px;left:2px}.monaco-editor.hc-black .find-widget .monaco-checkbox .checkbox:checked+.label{background-color:hsla(0,0%,100%,.1)}.monaco-sash{position:absolute;z-index:35;-ms-touch-action:none;touch-action:none}.monaco-sash.disabled{pointer-events:none}.monaco-sash.vertical{cursor:ew-resize;top:0;width:4px;height:100%}.monaco-sash.mac.vertical{cursor:col-resize}.monaco-sash.vertical.minimum{cursor:e-resize}.monaco-sash.vertical.maximum{cursor:w-resize}.monaco-sash.horizontal{cursor:ns-resize;left:0;width:100%;height:4px}.monaco-sash.mac.horizontal{cursor:row-resize}.monaco-sash.horizontal.minimum{cursor:s-resize}.monaco-sash.horizontal.maximum{cursor:n-resize}.monaco-sash:not(.disabled).orthogonal-end:after,.monaco-sash:not(.disabled).orthogonal-start:before{content:" ";height:8px;width:8px;z-index:100;display:block;cursor:all-scroll;position:absolute}.monaco-sash.orthogonal-start.vertical:before{left:-2px;top:-4px}.monaco-sash.orthogonal-end.vertical:after{left:-2px;bottom:-4px}.monaco-sash.orthogonal-start.horizontal:before{top:-2px;left:-4px}.monaco-sash.orthogonal-end.horizontal:after{top:-2px;right:-4px}.monaco-sash.disabled{cursor:default!important;pointer-events:none!important}.monaco-sash.touch.vertical{width:20px}.monaco-sash.touch.horizontal{height:20px}.monaco-sash.debug{background:cyan}.monaco-sash.debug.disabled{background:rgba(0,255,255,.2)}.monaco-sash.debug:not(.disabled).orthogonal-end:after,.monaco-sash.debug:not(.disabled).orthogonal-start:before{background:red}.monaco-findInput{position:relative}.monaco-findInput .monaco-inputbox{font-size:13px;width:100%}.monaco-findInput>.controls{position:absolute;top:3px;right:2px}.vs .monaco-findInput.disabled{background-color:#e1e1e1}.vs-dark .monaco-findInput.disabled{background-color:#333}.monaco-findInput.highlight-0 .controls{animation:monaco-findInput-highlight-0 .1s linear 0s}.monaco-findInput.highlight-1 .controls{animation:monaco-findInput-highlight-1 .1s linear 0s}.hc-black .monaco-findInput.highlight-0 .controls,.vs-dark .monaco-findInput.highlight-0 .controls{animation:monaco-findInput-highlight-dark-0 .1s linear 0s}.hc-black .monaco-findInput.highlight-1 .controls,.vs-dark .monaco-findInput.highlight-1 .controls{animation:monaco-findInput-highlight-dark-1 .1s linear 0s}@keyframes monaco-findInput-highlight-0{0%{background:rgba(253,255,0,.8)}to{background:transparent}}@keyframes monaco-findInput-highlight-1{0%{background:rgba(253,255,0,.8)}99%{background:transparent}}@keyframes monaco-findInput-highlight-dark-0{0%{background:hsla(0,0%,100%,.44)}to{background:transparent}}@keyframes monaco-findInput-highlight-dark-1{0%{background:hsla(0,0%,100%,.44)}99%{background:transparent}}.monaco-inputbox{position:relative;display:block;padding:0;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;line-height:auto!important;font-size:inherit}.monaco-inputbox.idle{border:1px solid transparent}.monaco-inputbox>.wrapper>.input,.monaco-inputbox>.wrapper>.mirror{padding:4px}.monaco-inputbox>.wrapper{position:relative;width:100%;height:100%}.monaco-inputbox>.wrapper>.input{display:inline-block;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;width:100%;height:100%;line-height:inherit;border:none;font-family:inherit;font-size:inherit;resize:none;color:inherit}.monaco-inputbox>.wrapper>input{text-overflow:ellipsis}.monaco-inputbox>.wrapper>textarea.input{display:block;-ms-overflow-style:none;overflow:-moz-scrollbars-none;scrollbar-width:none;outline:none}.monaco-inputbox>.wrapper>textarea.input::-webkit-scrollbar{display:none}.monaco-inputbox>.wrapper>.mirror{position:absolute;display:inline-block;width:100%;top:0;left:0;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;white-space:pre-wrap;visibility:hidden;word-wrap:break-word}.monaco-inputbox-container{text-align:right}.monaco-inputbox-container .monaco-inputbox-message{display:inline-block;overflow:hidden;text-align:left;width:100%;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;padding:.4em;font-size:12px;line-height:17px;min-height:34px;margin-top:-1px;word-wrap:break-word}.monaco-inputbox .monaco-action-bar{position:absolute;right:2px;top:4px}.monaco-inputbox .monaco-action-bar .action-item{margin-left:2px}.monaco-inputbox .monaco-action-bar .action-item .icon{background-repeat:no-repeat;width:16px;height:16px}.monaco-scrollable-element>.scrollbar>.up-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTEgMTEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTkuNDgwNDYsOC45NjE1bDEuMjYsLTEuMjZsLTUuMDQsLTUuMDRsLTUuNDYsNS4wNGwxLjI2LDEuMjZsNC4yLC0zLjc4bDMuNzgsMy43OHoiIGZpbGw9IiM0MjQyNDIiLz48L3N2Zz4=");cursor:pointer}.monaco-scrollable-element>.scrollbar>.down-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMSAxMSI+PHBhdGggdHJhbnNmb3JtPSJyb3RhdGUoLTE4MCA1LjQ5MDQ1OTkxODk3NTgzLDUuODExNTAwMDcyNDc5MjQ4KSIgZmlsbD0iIzQyNDI0MiIgZD0ibTkuNDgwNDYsOC45NjE1bDEuMjYsLTEuMjZsLTUuMDQsLTUuMDRsLTUuNDYsNS4wNGwxLjI2LDEuMjZsNC4yLC0zLjc4bDMuNzgsMy43OHoiLz48L3N2Zz4=");cursor:pointer}.monaco-scrollable-element>.scrollbar>.left-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMSAxMSI+PHBhdGggdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDUuNDkwNDU5OTE4OTc1ODMxLDUuNDMxMzgyMTc5MjYwMjU0KSIgZmlsbD0iIzQyNDI0MiIgZD0ibTkuNDgwNDYsOC41ODEzOGwxLjI2LC0xLjI2bC01LjA0LC01LjA0bC01LjQ2LDUuMDRsMS4yNiwxLjI2bDQuMiwtMy43OGwzLjc4LDMuNzh6Ii8+PC9zdmc+");cursor:pointer}.monaco-scrollable-element>.scrollbar>.right-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTEgMTEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggdHJhbnNmb3JtPSJyb3RhdGUoOTAgNS42MTcxNjUwODg2NTM1NjQ1LDUuNTU4MDg5NzMzMTIzNzgpICIgZmlsbD0iIzQyNDI0MiIgZD0ibTkuNjA3MTcsOC43MDgwOWwxLjI2LC0xLjI2bC01LjA0LC01LjA0bC01LjQ2LDUuMDRsMS4yNiwxLjI2bDQuMiwtMy43OGwzLjc4LDMuNzh6Ii8+PC9zdmc+");cursor:pointer}.hc-black .monaco-scrollable-element>.scrollbar>.up-arrow,.vs-dark .monaco-scrollable-element>.scrollbar>.up-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTEgMTEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTkuNDgwNDYsOC45NjE1bDEuMjYsLTEuMjZsLTUuMDQsLTUuMDRsLTUuNDYsNS4wNGwxLjI2LDEuMjZsNC4yLC0zLjc4bDMuNzgsMy43OHoiIGZpbGw9IiNFOEU4RTgiLz48L3N2Zz4=")}.hc-black .monaco-scrollable-element>.scrollbar>.down-arrow,.vs-dark .monaco-scrollable-element>.scrollbar>.down-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMSAxMSI+PHBhdGggdHJhbnNmb3JtPSJyb3RhdGUoLTE4MCA1LjQ5MDQ1OTkxODk3NTgzLDUuODExNTAwMDcyNDc5MjQ4KSIgZmlsbD0iI0U4RThFOCIgZD0ibTkuNDgwNDYsOC45NjE1bDEuMjYsLTEuMjZsLTUuMDQsLTUuMDRsLTUuNDYsNS4wNGwxLjI2LDEuMjZsNC4yLC0zLjc4bDMuNzgsMy43OHoiLz48L3N2Zz4=")}.hc-black .monaco-scrollable-element>.scrollbar>.left-arrow,.vs-dark .monaco-scrollable-element>.scrollbar>.left-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMSAxMSI+PHBhdGggdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDUuNDkwNDU5OTE4OTc1ODMxLDUuNDMxMzgyMTc5MjYwMjU0KSIgZmlsbD0iI0U4RThFOCIgZD0ibTkuNDgwNDYsOC41ODEzOGwxLjI2LC0xLjI2bC01LjA0LC01LjA0bC01LjQ2LDUuMDRsMS4yNiwxLjI2bDQuMiwtMy43OGwzLjc4LDMuNzh6Ii8+PC9zdmc+")}.hc-black .monaco-scrollable-element>.scrollbar>.right-arrow,.vs-dark .monaco-scrollable-element>.scrollbar>.right-arrow{background:url("data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTEgMTEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggdHJhbnNmb3JtPSJyb3RhdGUoOTAgNS42MTcxNjUwODg2NTM1NjQ1LDUuNTU4MDg5NzMzMTIzNzgpICIgZmlsbD0iI0U4RThFOCIgZD0ibTkuNjA3MTcsOC43MDgwOWwxLjI2LC0xLjI2bC01LjA0LC01LjA0bC01LjQ2LDUuMDRsMS4yNiwxLjI2bDQuMiwtMy43OGwzLjc4LDMuNzh6Ii8+PC9zdmc+")}.monaco-scrollable-element>.visible{opacity:1;background:transparent;transition:opacity .1s linear}.monaco-scrollable-element>.invisible{opacity:0;pointer-events:none}.monaco-scrollable-element>.invisible.fade{transition:opacity .8s linear}.monaco-scrollable-element>.shadow{position:absolute;display:none}.monaco-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:inset 0 6px 6px -6px #ddd}.monaco-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:inset 6px 0 6px -6px #ddd}.monaco-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.monaco-scrollable-element>.shadow.top.left{box-shadow:inset 6px 6px 6px -6px #ddd}.vs .monaco-scrollable-element>.scrollbar>.slider{background:hsla(0,0%,39%,.4)}.vs-dark .monaco-scrollable-element>.scrollbar>.slider{background:hsla(0,0%,47%,.4)}.hc-black .monaco-scrollable-element>.scrollbar>.slider{background:rgba(111,195,223,.6)}.monaco-scrollable-element>.scrollbar>.slider:hover{background:hsla(0,0%,39%,.7)}.hc-black .monaco-scrollable-element>.scrollbar>.slider:hover{background:rgba(111,195,223,.8)}.monaco-scrollable-element>.scrollbar>.slider.active{background:rgba(0,0,0,.6)}.vs-dark .monaco-scrollable-element>.scrollbar>.slider.active{background:hsla(0,0%,75%,.4)}.hc-black .monaco-scrollable-element>.scrollbar>.slider.active{background:#6fc3df}.vs-dark .monaco-scrollable-element .shadow.top{box-shadow:none}.vs-dark .monaco-scrollable-element .shadow.left{box-shadow:inset 6px 0 6px -6px #000}.vs-dark .monaco-scrollable-element .shadow.top.left{box-shadow:inset 6px 6px 6px -6px #000}.hc-black .monaco-scrollable-element .shadow.left,.hc-black .monaco-scrollable-element .shadow.top,.hc-black .monaco-scrollable-element .shadow.top.left{box-shadow:none}.monaco-editor .margin-view-overlays .folding{cursor:pointer;background-repeat:no-repeat;background-origin:border-box;background-position:calc(50% + 2px) 50%;background-size:auto calc(100% - 3px);opacity:0;transition:opacity .5s;background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MjEgNi4zMzMzM0w4LjI4NTM5IDExTDcuNjY2NjcgMTFMMyA2LjMzMzMzTDMuNjE4NzIgNS43MTQ2MUw3Ljk3NjAzIDEwLjA3MTlaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .margin-view-overlays .folding,.monaco-editor.vs-dark .margin-view-overlays .folding{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MjEgNi4zMzMzM0w4LjI4NTM5IDExTDcuNjY2NjcgMTFMMyA2LjMzMzMzTDMuNjE4NzIgNS43MTQ2MUw3Ljk3NjAzIDEwLjA3MTlaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .margin-view-overlays .folding{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MjEgNi4zMzMzM0w4LjI4NTM5IDExTDcuNjY2NjcgMTFMMyA2LjMzMzMzTDMuNjE4NzIgNS43MTQ2MUw3Ljk3NjAzIDEwLjA3MTlaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")}.monaco-editor .margin-view-overlays .folding.alwaysShowFoldIcons,.monaco-editor .margin-view-overlays:hover .folding{opacity:1}.monaco-editor .margin-view-overlays .folding.collapsed{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2IDEyLjM1NzNMNi4zMzMzMiAxMi45NzZMMTEgOC4zMDkzNVY3LjY5MDYzTDYuMzMzMzIgMy4wMjM5Nkw1LjcxNDYgMy42NDI2OEwxMC4wNzE5IDcuOTk5OTlaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=");opacity:1}.monaco-editor.vs-dark .margin-view-overlays .folding.collapsed{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2IDEyLjM1NzNMNi4zMzMzMiAxMi45NzZMMTEgOC4zMDkzNVY3LjY5MDY0TDYuMzMzMzIgMy4wMjM5N0w1LjcxNDYgMy42NDI2OUwxMC4wNzE5IDcuOTk5OTlaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .margin-view-overlays .folding.collapsed{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2IDEyLjM1NzNMNi4zMzMzMiAxMi45NzZMMTEgOC4zMDkzNVY3LjY5MDYzTDYuMzMzMzIgMy4wMjM5Nkw1LjcxNDYgMy42NDI2OEwxMC4wNzE5IDcuOTk5OTlaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")}.monaco-editor .inline-folded:after{color:grey;margin:.1em .2em 0;content:"\22EF";display:inline;line-height:1em;cursor:pointer}.monaco-editor .peekview-widget .head{-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;display:-ms-flexbox;display:flex}.monaco-editor .peekview-widget .head .peekview-title{display:inline-block;font-size:13px;margin-left:20px;cursor:pointer}.monaco-editor .peekview-widget .head .peekview-title .dirname:not(:empty){font-size:.9em;margin-left:.5em}.monaco-editor .peekview-widget .head .peekview-actions{-ms-flex:1;flex:1;text-align:right;padding-right:2px}.monaco-editor .peekview-widget .head .peekview-actions>.monaco-action-bar{display:inline-block}.monaco-editor .peekview-widget .head .peekview-actions>.monaco-action-bar,.monaco-editor .peekview-widget .head .peekview-actions>.monaco-action-bar>.actions-container{height:100%}.monaco-editor .peekview-widget .head .peekview-actions>.monaco-action-bar .action-item{margin-left:4px}.monaco-editor .peekview-widget .head .peekview-actions>.monaco-action-bar .action-label{width:16px;height:100%;margin:0;line-height:inherit;background-repeat:no-repeat;background-position:50%}.monaco-editor .peekview-widget .head .peekview-actions>.monaco-action-bar .action-label.octicon{margin:0}.monaco-editor .peekview-widget .head .peekview-actions .action-label.icon.close-peekview-action{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjAwMDAxIDguNzA3MDhMMTEuNjQ2NSAxMi4zNTM1TDEyLjM1MzYgMTEuNjQ2NEw4LjcwNzExIDcuOTk5OThMMTIuMzUzNiA0LjM1MzUzTDExLjY0NjUgMy42NDY0Mkw4LjAwMDAxIDcuMjkyODdMNC4zNTM1NiAzLjY0NjQyTDMuNjQ2NDUgNC4zNTM1M0w3LjI5MjkgNy45OTk5OEwzLjY0NjQ1IDExLjY0NjRMNC4zNTM1NiAxMi4zNTM1TDguMDAwMDEgOC43MDcwOFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% no-repeat}.monaco-editor .peekview-widget>.body{border-top:1px solid;position:relative}.monaco-editor.hc-black .peekview-widget .head .peekview-actions .action-label.icon.close-peekview-action,.monaco-editor.vs-dark .peekview-widget .head .peekview-actions .action-label.icon.close-peekview-action{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjAwMDAxIDguNzA3MDhMMTEuNjQ2NSAxMi4zNTM1TDEyLjM1MzYgMTEuNjQ2NEw4LjcwNzExIDcuOTk5OThMMTIuMzUzNiA0LjM1MzUzTDExLjY0NjUgMy42NDY0Mkw4LjAwMDAxIDcuMjkyODdMNC4zNTM1NiAzLjY0NjQyTDMuNjQ2NDUgNC4zNTM1M0w3LjI5MjkgNy45OTk5OEwzLjY0NjQ1IDExLjY0NjRMNC4zNTM1NiAxMi4zNTM1TDguMDAwMDEgOC43MDcwOFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") 50% no-repeat}.monaco-editor .peekview-widget .peekview-actions .icon.chevron-up{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy44NTM1IDYuMjkyOUw4Ljg1MzU2IDEuMjkyOTFIOC4xNDY0NUwzLjE0NjQ1IDYuMjkyOUwzLjg1MzU2IDcuMDAwMDFMOCAyLjg1MzU3VjE1LjA2MDdIOVYyLjg1MzU3TDEzLjE0NjQgNy4wMDAwMUwxMy44NTM1IDYuMjkyOVoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% no-repeat}.hc-black .monaco-editor .peekview-widget .peekview-actions .icon.chevron-up,.vs-dark .monaco-editor .peekview-widget .peekview-actions .icon.chevron-up{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy44NTM1IDYuMjkyOUw4Ljg1MzU2IDEuMjkyOTFIOC4xNDY0NUwzLjE0NjQ1IDYuMjkyOUwzLjg1MzU2IDcuMDAwMDFMOCAyLjg1MzU3VjE1LjA2MDdIOVYyLjg1MzU3TDEzLjE0NjQgNy4wMDAwMUwxMy44NTM1IDYuMjkyOVoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") 50% no-repeat}.monaco-editor .peekview-widget .peekview-actions .icon.chevron-down{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjE0NjQ2IDkuNzY3NzdMOC4xNDY0NCAxNC43Njc4TDguODUzNTUgMTQuNzY3OEwxMy44NTM1IDkuNzY3NzdMMTMuMTQ2NCA5LjA2MDY2TDkgMTMuMjA3MUw5IDFMOCAwLjk5OTk5OUw4IDEzLjIwNzFMMy44NTM1NiA5LjA2MDY2TDMuMTQ2NDYgOS43Njc3N1oiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% no-repeat}.hc-black .monaco-editor .peekview-widget .peekview-actions .icon.chevron-down,.vs-dark .monaco-editor .peekview-widget .peekview-actions .icon.chevron-down{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjE0NjQ2IDkuNzY3NzdMOC4xNDY0NCAxNC43Njc4TDguODUzNTUgMTQuNzY3OEwxMy44NTM1IDkuNzY3NzdMMTMuMTQ2NCA5LjA2MDY2TDkgMTMuMjA3MUw5IDFMOCAwLjk5OTk5OUw4IDEzLjIwNzFMMy44NTM1NiA5LjA2MDY2TDMuMTQ2NDYgOS43Njc3N1oiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") 50% no-repeat}::-ms-clear{display:none}.monaco-editor .editor-widget input{color:inherit}.monaco-editor{position:relative;overflow:visible;-webkit-text-size-adjust:100%;-webkit-font-feature-settings:"liga" off,"calt" off;font-feature-settings:"liga" off,"calt" off}.monaco-editor.enable-ligatures{-webkit-font-feature-settings:"liga" on,"calt" on;font-feature-settings:"liga" on,"calt" on}.monaco-editor .overflow-guard{position:relative;overflow:hidden}.monaco-editor .view-overlays{position:absolute;top:0}.monaco-editor .vs-whitespace{display:inline-block}.monaco-editor .inputarea{min-width:0;min-height:0;margin:0;padding:0;position:absolute;outline:none!important;resize:none;border:none;overflow:hidden;color:transparent;background-color:transparent}.monaco-editor .inputarea.ime-input{z-index:10}.monaco-editor .margin-view-overlays .line-numbers{position:absolute;text-align:right;display:inline-block;vertical-align:middle;box-sizing:border-box;cursor:default;height:100%}.monaco-editor .relative-current-line-number{text-align:left;display:inline-block;width:100%}.monaco-editor .margin-view-overlays .line-numbers{cursor:-webkit-image-set(url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNSIgaGVpZ2h0PSIyNSIgeD0iMHB4IiB5PSIwcHgiIHZpZXdCb3g9IjAgMCAxNSAyNSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTUgMjU7Ij48cG9seWdvbiBzdHlsZT0iZmlsbDojRkZGRkZGO3N0cm9rZTojMDAwMDAwIiBwb2ludHM9IjE0LjUsMS4yIDEuOSwxMy44IDcsMTMuOCAzLjIsMjEuNSA2LjMsMjIuNSAxMC4xLDE0LjkgMTQuNSwxOCIvPjwvc3ZnPg==") 1x,url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHg9IjBweCIgeT0iMHB4IiB3aWR0aD0iMzAiIGhlaWdodD0iNTAiIHZpZXdCb3g9IjAgMCAzMCA1MCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMzAgNTA7Ij48cG9seWdvbiBzdHlsZT0iZmlsbDojRkZGRkZGO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDoyOyIgcG9pbnRzPSIyOSwyLjQgMy44LDI3LjYgMTQsMjcuNiA2LjQsNDMgMTIuNiw0NSAyMC4yLDI5LjggMjksMzYiLz48L3N2Zz4K") 2x) 30 0,default}.monaco-editor.mac .margin-view-overlays .line-numbers{cursor:-webkit-image-set(url("data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJMYXllcl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTMgMTkiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDEzIDE5OyIgd2lkdGg9IjEzIiBoZWlnaHQ9IjE5Ij48c3R5bGUgdHlwZT0idGV4dC9jc3MiPi5zdDB7c3Ryb2tlOiNGRkZGRkY7c3Ryb2tlLW1pdGVybGltaXQ6MTA7fTwvc3R5bGU+PHRpdGxlPmZsaXBwZWQtY3Vyc29yLW1hYzwvdGl0bGU+PHBhdGggY2xhc3M9InN0MCIgZD0iTTUuMywxNi42bDEuNi00LjdIMi4xTDEyLjUsMS4ydjE0LjRMOS43LDEzbC0xLjYsNC42Yy0wLjIsMC41LTAuOCwwLjgtMS4zLDAuNkw2LDE3LjkgQzUuNCwxNy43LDUuMSwxNy4yLDUuMywxNi42eiIvPjwvc3ZnPgo=") 1x,url("data:image/svg+xml;base64,CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmlld0JveD0iMCAwIDI2IDM4IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNiAzODsiIHdpZHRoPSIyNiIgaGVpZ2h0PSIzOCI+PHN0eWxlIHR5cGU9InRleHQvY3NzIj4uc3Qwe3N0cm9rZTojRkZGRkZGO3N0cm9rZS1taXRlcmxpbWl0OjEwO308L3N0eWxlPgk8dGl0bGU+ZmxpcHBlZC1jdXJzb3ItbWFjPC90aXRsZT48cGF0aCBjbGFzcz0ic3QwIiBkPSJNMTAuNiwzMy4ybDMuMi05LjRINC4yTDI1LDIuNHYyOC44TDE5LjQsMjZsLTMuMiw5LjJjLTAuNCwxLTEuNiwxLjYtMi42LDEuMkwxMiwzNS44IEMxMC44LDM1LjQsMTAuMiwzNC40LDEwLjYsMzMuMnoiLz48L3N2Zz4K") 2x) 24 3,default}.monaco-editor .margin-view-overlays .line-numbers.lh-odd{margin-top:1px}.monaco-editor .margin-view-overlays .current-line,.monaco-editor .view-overlays .current-line{display:block;position:absolute;left:0;top:0;box-sizing:border-box}.monaco-editor .margin-view-overlays .current-line.current-line-margin.current-line-margin-both{border-right:0}.monaco-editor .lines-content .cdr{position:absolute}.monaco-editor .glyph-margin{position:absolute;top:0}.monaco-editor .lines-content .cigr,.monaco-editor .lines-content .cigra,.monaco-editor .margin-view-overlays .cgmr{position:absolute}.monaco-editor.no-user-select .lines-content,.monaco-editor.no-user-select .view-line,.monaco-editor.no-user-select .view-lines{-webkit-user-select:none;-ms-user-select:none;-moz-user-select:none;-o-user-select:none;user-select:none}.monaco-editor .view-lines{cursor:text;white-space:nowrap}.monaco-editor.hc-black.mac .view-lines,.monaco-editor.vs-dark.mac .view-lines{cursor:-webkit-image-set(url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAL0lEQVQoz2NgCD3x//9/BhBYBWdhgFVAiVW4JBFKGIa4AqD0//9D3pt4I4tAdAMAHTQ/j5Zom30AAAAASUVORK5CYII=) 1x,url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAz0lEQVRIx2NgYGBY/R8I/vx5eelX3n82IJ9FxGf6tksvf/8FiTMQAcAGQMDvSwu09abffY8QYSAScNk45G198eX//yev73/4///701eh//kZSARckrNBRvz//+8+6ZohwCzjGNjdgQxkAg7B9WADeBjIBqtJCbhRA0YNoIkBSNmaPEMoNmA0FkYNoFKhapJ6FGyAH3nauaSmPfwI0v/3OukVi0CIZ+F25KrtYcx/CTIy0e+rC7R1Z4KMICVTQQ14feVXIbR695u14+Ir4gwAAD49E54wc1kWAAAAAElFTkSuQmCC) 2x) 5 8,text}.monaco-editor .view-line{position:absolute;width:100%}.monaco-editor .lines-decorations{position:absolute;top:0;background:#fff}.monaco-editor .margin-view-overlays .cldr{position:absolute;height:100%}.monaco-editor .margin-view-overlays .cmdr{position:absolute;left:0;width:100%;height:100%}.monaco-editor .minimap.slider-mouseover .minimap-slider{opacity:0;transition:opacity .1s linear}.monaco-editor .minimap.slider-mouseover .minimap-slider.active,.monaco-editor .minimap.slider-mouseover:hover .minimap-slider{opacity:1}.monaco-editor .minimap-shadow-hidden{position:absolute;width:0}.monaco-editor .minimap-shadow-visible{position:absolute;left:-6px;width:6px}.monaco-editor .overlayWidgets{position:absolute;top:0;left:0}.monaco-editor .view-ruler{position:absolute;top:0}.monaco-editor .scroll-decoration{position:absolute;top:0;left:0;height:6px}.monaco-editor .lines-content .cslr{position:absolute}.monaco-editor .top-left-radius{border-top-left-radius:3px}.monaco-editor .bottom-left-radius{border-bottom-left-radius:3px}.monaco-editor .top-right-radius{border-top-right-radius:3px}.monaco-editor .bottom-right-radius{border-bottom-right-radius:3px}.monaco-editor.hc-black .top-left-radius{border-top-left-radius:0}.monaco-editor.hc-black .bottom-left-radius{border-bottom-left-radius:0}.monaco-editor.hc-black .top-right-radius{border-top-right-radius:0}.monaco-editor.hc-black .bottom-right-radius{border-bottom-right-radius:0}.monaco-editor .cursors-layer{position:absolute;top:0}.monaco-editor .cursors-layer>.cursor{position:absolute;cursor:text;overflow:hidden}.monaco-editor .cursors-layer.cursor-smooth-caret-animation>.cursor{transition:80ms}.monaco-editor .cursors-layer.cursor-block-outline-style>.cursor{box-sizing:border-box;background:transparent!important;border-style:solid;border-width:1px}.monaco-editor .cursors-layer.cursor-underline-style>.cursor{border-bottom-width:2px;border-bottom-style:solid;background:transparent!important;box-sizing:border-box}.monaco-editor .cursors-layer.cursor-underline-thin-style>.cursor{border-bottom-width:1px;border-bottom-style:solid;background:transparent!important;box-sizing:border-box}@keyframes monaco-cursor-smooth{0%,20%{opacity:1}60%,to{opacity:0}}@keyframes monaco-cursor-phase{0%,20%{opacity:1}90%,to{opacity:0}}@keyframes monaco-cursor-expand{0%,20%{transform:scaleY(1)}80%,to{transform:scaleY(0)}}.cursor-smooth{animation:monaco-cursor-smooth .5s ease-in-out 0s 20 alternate}.cursor-phase{animation:monaco-cursor-phase .5s ease-in-out 0s 20 alternate}.cursor-expand>.cursor{animation:monaco-cursor-expand .5s ease-in-out 0s 20 alternate}.monaco-editor .zone-widget{position:absolute;z-index:10}.monaco-editor .zone-widget .zone-widget-container{border-top-style:solid;border-bottom-style:solid;border-top-width:0;border-bottom-width:0;position:relative}.monaco-editor .zone-widget .zone-widget-container.reference-zone-widget{border-top-width:1px;border-bottom-width:1px}.monaco-editor .reference-zone-widget .inline{display:inline-block;vertical-align:top}.monaco-editor .reference-zone-widget .messages{height:100%;width:100%;text-align:center;padding:3em 0}.monaco-editor .reference-zone-widget .ref-tree{line-height:23px}.monaco-editor .reference-zone-widget .ref-tree .reference{text-overflow:ellipsis;overflow:hidden}.monaco-editor .reference-zone-widget .ref-tree .reference-file{display:-ms-inline-flexbox;display:inline-flex;width:100%;height:100%}.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .selected .reference-file{color:inherit!important}.monaco-editor .reference-zone-widget .ref-tree .reference-file .count{margin-right:12px;margin-left:auto}.monaco-editor.hc-black .reference-zone-widget .ref-tree .reference-file{font-weight:700}.monaco-icon-label{display:-ms-flexbox;display:flex;overflow:hidden;text-overflow:ellipsis}.monaco-icon-label:before{background-size:16px;background-position:0;background-repeat:no-repeat;padding-right:6px;width:16px;height:22px;display:inline-block;-webkit-font-smoothing:antialiased;vertical-align:top;-ms-flex-negative:0;flex-shrink:0}.monaco-icon-label>.monaco-icon-label-description-container{overflow:hidden;text-overflow:ellipsis}.monaco-icon-label>.monaco-icon-label-description-container>.label-name{color:inherit;white-space:pre}.monaco-icon-label>.monaco-icon-label-description-container>.label-description{opacity:.7;margin-left:.5em;font-size:.9em;white-space:pre}.monaco-icon-label.italic>.monaco-icon-label-description-container>.label-description,.monaco-icon-label.italic>.monaco-icon-label-description-container>.label-name{font-style:italic}.monaco-icon-label:after{opacity:.75;font-size:90%;font-weight:600;padding:0 12px 0 5px;margin-left:auto;text-align:center}.monaco-list:focus .selected .monaco-icon-label,.monaco-list:focus .selected .monaco-icon-label:after,.monaco-tree.focused .selected .monaco-icon-label,.monaco-tree.focused .selected .monaco-icon-label:after{color:inherit!important}.monaco-list-row.focused.selected .label-description,.monaco-list-row.selected .label-description,.monaco-tree-row.focused.selected .label-description,.monaco-tree-row.selected .label-description{opacity:.8}.monaco-count-badge{padding:3px 5px;border-radius:11px;font-size:11px;min-width:18px;min-height:18px;line-height:11px;font-weight:400;text-align:center;display:inline-block;box-sizing:border-box}.monaco-list{position:relative;height:100%;width:100%;white-space:nowrap}.monaco-list.mouse-support{-webkit-user-select:none;-moz-user-select:-moz-none;-ms-user-select:none;-o-user-select:none;user-select:none}.monaco-list>.monaco-scrollable-element{height:100%}.monaco-list-rows{position:relative;width:100%;height:100%}.monaco-list.horizontal-scrolling .monaco-list-rows{width:auto;min-width:100%}.monaco-list-row{position:absolute;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;overflow:hidden;width:100%}.monaco-list.mouse-support .monaco-list-row{cursor:pointer;-ms-touch-action:none;touch-action:none}.monaco-list-row.scrolling{display:none!important}.monaco-list.element-focused,.monaco-list.selection-multiple,.monaco-list.selection-single{outline:0!important}.monaco-drag-image{display:inline-block;padding:1px 7px;border-radius:10px;font-size:12px;position:absolute}.monaco-list-type-filter{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;position:absolute;border-radius:2px;padding:0 3px;max-width:calc(100% - 10px);text-overflow:ellipsis;overflow:hidden;text-align:right;box-sizing:border-box;cursor:all-scroll;font-size:13px;line-height:18px;height:20px;z-index:1;top:4px}.monaco-list-type-filter.dragging{transition:top .2s,left .2s}.monaco-list-type-filter.ne{right:4px}.monaco-list-type-filter.nw{left:4px}.monaco-list-type-filter>.controls{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;box-sizing:border-box;transition:width .2s;width:0}.monaco-list-type-filter.dragging>.controls,.monaco-list-type-filter:hover>.controls{width:36px}.monaco-list-type-filter>.controls>*{box-sizing:border-box;width:16px;height:16px;margin:0 0 0 2px;-ms-flex-negative:0;flex-shrink:0}.monaco-list-type-filter>.controls>.filter{-webkit-appearance:none;width:16px;height:16px;background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEgMTJMMSAxMUgxMFYxMkgxWk0xIDdIMTVWOEgxTDEgN1pNMTIgM1Y0SDFMMSAzSDEyWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K");background-position:50% 50%;cursor:pointer}.monaco-list-type-filter>.controls>.filter:checked{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTYgMTJWMTFIMTBWMTJINlpNNCA3SDEyVjhINFY3Wk0xNCAzVjRIMlYzSDE0WiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.vs-dark .monaco-list-type-filter>.controls>.filter{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEgMTJMMSAxMUgxMFYxMkgxWk0xIDdIMTVWOEgxTDEgN1pNMTIgM1Y0SDFMMSAzSDEyWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.vs-dark .monaco-list-type-filter>.controls>.filter:checked{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTYgMTJWMTFIMTBWMTJINlpNNCA3SDEyVjhINFY3Wk0xNCAzVjRIMlYzSDE0WiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.hc-black .monaco-list-type-filter>.controls>.filter{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEgMTJMMSAxMUgxMFYxMkgxWk0xIDdIMTVWOEgxTDEgN1pNMTIgM1Y0SDFMMSAzSDEyWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.hc-black .monaco-list-type-filter>.controls>.filter:checked{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTYgMTJWMTFIMTBWMTJINlpNNCA3SDEyVjhINFY3Wk0xNCAzVjRIMlYzSDE0WiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==")}.monaco-list-type-filter>.controls>.clear{border:none;background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjAwMDAxIDguNzA3MTRMMTEuNjQ2NSAxMi4zNTM2TDEyLjM1MzYgMTEuNjQ2NUw4LjcwNzExIDguMDAwMDRMMTIuMzUzNiA0LjM1MzU5TDExLjY0NjUgMy42NDY0OEw4LjAwMDAxIDcuMjkyOTNMNC4zNTM1NiAzLjY0NjQ4TDMuNjQ2NDUgNC4zNTM1OUw3LjI5MjkgOC4wMDAwNEwzLjY0NjQ1IDExLjY0NjVMNC4zNTM1NiAxMi4zNTM2TDguMDAwMDEgOC43MDcxNFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==");cursor:pointer}.hc-black .monaco-list-type-filter>.controls>.clear,.vs-dark .monaco-list-type-filter>.controls>.clear{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjAwMDAxIDguNzA3MTRMMTEuNjQ2NSAxMi4zNTM2TDEyLjM1MzYgMTEuNjQ2NUw4LjcwNzExIDguMDAwMDRMMTIuMzUzNiA0LjM1MzU5TDExLjY0NjUgMy42NDY0OEw4LjAwMDAxIDcuMjkyOTNMNC4zNTM1NiAzLjY0NjQ4TDMuNjQ2NDUgNC4zNTM1OUw3LjI5MjkgOC4wMDAwNEwzLjY0NjQ1IDExLjY0NjVMNC4zNTM1NiAxMi4zNTM2TDguMDAwMDEgOC43MDcxNFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-list-type-filter-message{position:absolute;box-sizing:border-box;width:100%;height:100%;top:0;left:0;padding:40px 1em 1em;text-align:center;white-space:normal;opacity:.7;pointer-events:none}.monaco-list-type-filter-message:empty{display:none}.monaco-list-type-filter{cursor:grab}.monaco-list-type-filter.dragging{cursor:grabbing}.monaco-tl-row{display:-ms-flexbox;display:flex;height:100%;-ms-flex-align:center;align-items:center;position:relative}.monaco-tl-indent{height:100%;position:absolute;top:0;left:18px;pointer-events:none}.hide-arrows .monaco-tl-indent{left:12px}.monaco-tl-indent>.indent-guide{display:inline-block;box-sizing:border-box;height:100%;border-left:1px solid transparent;transition:border-color .1s linear}.monaco-tl-contents,.monaco-tl-twistie{height:100%}.monaco-tl-twistie{font-size:10px;text-align:right;margin-right:6px;-ms-flex-negative:0;flex-shrink:0;width:16px}.monaco-tl-contents{-ms-flex:1;flex:1;overflow:hidden}.monaco-tl-twistie.collapsible{background-size:16px;background-position:3px 50%;background-repeat:no-repeat;background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MjEgNi4zMzMzM0w4LjI4NTM5IDExTDcuNjY2NjcgMTFMMyA2LjMzMzMzTDMuNjE4NzIgNS43MTQ2MUw3Ljk3NjAzIDEwLjA3MTlaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-tl-twistie.collapsible.collapsed:not(.loading){display:inline-block;background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2MSAxMi4zNTczTDYuMzMzMzMgMTIuOTc2TDExIDguMzA5MzVWNy42OTA2M0w2LjMzMzMzIDMuMDIzOTZMNS43MTQ2MSAzLjY0MjY4TDEwLjA3MTkgNy45OTk5OVoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.vs-dark .monaco-tl-twistie.collapsible:not(.loading){background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MjEgNi4zMzMzM0w4LjI4NTM5IDExTDcuNjY2NjcgMTFMMyA2LjMzMzMzTDMuNjE4NzIgNS43MTQ2MUw3Ljk3NjAzIDEwLjA3MTlaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.vs-dark .monaco-tl-twistie.collapsible.collapsed:not(.loading){background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2MSAxMi4zNTczTDYuMzMzMzMgMTIuOTc2TDExIDguMzA5MzVWNy42OTA2NEw2LjMzMzMzIDMuMDIzOTdMNS43MTQ2MSAzLjY0MjY5TDEwLjA3MTkgNy45OTk5OVoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.hc-black .monaco-tl-twistie.collapsible:not(.loading){background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAzIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MjEgNi4zMzMzM0w4LjI4NTM5IDExTDcuNjY2NjcgMTFMMyA2LjMzMzMzTDMuNjE4NzIgNS43MTQ2MUw3Ljk3NjAzIDEwLjA3MTlaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")}.hc-black .monaco-tl-twistie.collapsible.collapsed:not(.loading){background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2MSAxMi4zNTczTDYuMzMzMzMgMTIuOTc2TDExIDguMzA5MzVWNy42OTA2M0w2LjMzMzMzIDMuMDIzOTZMNS43MTQ2MSAzLjY0MjY4TDEwLjA3MTkgNy45OTk5OVoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=")}.monaco-tl-twistie.loading{background-image:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0nMS4wJyBzdGFuZGFsb25lPSdubycgPz4KPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZlcnNpb249JzEuMScgd2lkdGg9JzEwcHgnIGhlaWdodD0nMTBweCc+Cgk8c3R5bGU+CiAgICBjaXJjbGUgewogICAgICBhbmltYXRpb246IGJhbGwgMC42cyBsaW5lYXIgaW5maW5pdGU7CiAgICB9CgogICAgY2lyY2xlOm50aC1jaGlsZCgyKSB7IGFuaW1hdGlvbi1kZWxheTogMC4wNzVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDMpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjE1czsgfQogICAgY2lyY2xlOm50aC1jaGlsZCg0KSB7IGFuaW1hdGlvbi1kZWxheTogMC4yMjVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDUpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjNzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDYpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjM3NXM7IH0KICAgIGNpcmNsZTpudGgtY2hpbGQoNykgeyBhbmltYXRpb24tZGVsYXk6IDAuNDVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDgpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjUyNXM7IH0KCiAgICBAa2V5ZnJhbWVzIGJhbGwgewogICAgICBmcm9tIHsgb3BhY2l0eTogMTsgfQogICAgICB0byB7IG9wYWNpdHk6IDAuMzsgfQogICAgfQoJPC9zdHlsZT4KCTxnPgoJCTxjaXJjbGUgY3g9JzUnIGN5PScxJyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzcuODI4NCcgY3k9JzIuMTcxNicgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc5JyBjeT0nNScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc3LjgyODQnIGN5PSc3LjgyODQnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nNScgY3k9JzknIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nMi4xNzE2JyBjeT0nNy44Mjg0JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzEnIGN5PSc1JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzIuMTcxNicgY3k9JzIuMTcxNicgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCTwvZz4KPC9zdmc+Cg==");background-position:0}.vs-dark .monaco-tl-twistie.loading{background-image:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0nMS4wJyBzdGFuZGFsb25lPSdubycgPz4KPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZlcnNpb249JzEuMScgd2lkdGg9JzEwcHgnIGhlaWdodD0nMTBweCc+Cgk8c3R5bGU+CiAgICBjaXJjbGUgewogICAgICBhbmltYXRpb246IGJhbGwgMC42cyBsaW5lYXIgaW5maW5pdGU7CiAgICB9CgogICAgY2lyY2xlOm50aC1jaGlsZCgyKSB7IGFuaW1hdGlvbi1kZWxheTogMC4wNzVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDMpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjE1czsgfQogICAgY2lyY2xlOm50aC1jaGlsZCg0KSB7IGFuaW1hdGlvbi1kZWxheTogMC4yMjVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDUpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjNzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDYpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjM3NXM7IH0KICAgIGNpcmNsZTpudGgtY2hpbGQoNykgeyBhbmltYXRpb24tZGVsYXk6IDAuNDVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDgpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjUyNXM7IH0KCiAgICBAa2V5ZnJhbWVzIGJhbGwgewogICAgICBmcm9tIHsgb3BhY2l0eTogMTsgfQogICAgICB0byB7IG9wYWNpdHk6IDAuMzsgfQogICAgfQoJPC9zdHlsZT4KCTxnIHN0eWxlPSJmaWxsOmdyZXk7Ij4KCQk8Y2lyY2xlIGN4PSc1JyBjeT0nMScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc3LjgyODQnIGN5PScyLjE3MTYnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nOScgY3k9JzUnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nNy44Mjg0JyBjeT0nNy44Mjg0JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzUnIGN5PSc5JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzIuMTcxNicgY3k9JzcuODI4NCcgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PScxJyBjeT0nNScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PScyLjE3MTYnIGN5PScyLjE3MTYnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+Cgk8L2c+Cjwvc3ZnPgo=")}.hc-black .monaco-tl-twistie.loading{background-image:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0nMS4wJyBzdGFuZGFsb25lPSdubycgPz4KPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZlcnNpb249JzEuMScgd2lkdGg9JzEwcHgnIGhlaWdodD0nMTBweCc+Cgk8c3R5bGU+CiAgICBjaXJjbGUgewogICAgICBhbmltYXRpb246IGJhbGwgMC42cyBsaW5lYXIgaW5maW5pdGU7CiAgICB9CgogICAgY2lyY2xlOm50aC1jaGlsZCgyKSB7IGFuaW1hdGlvbi1kZWxheTogMC4wNzVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDMpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjE1czsgfQogICAgY2lyY2xlOm50aC1jaGlsZCg0KSB7IGFuaW1hdGlvbi1kZWxheTogMC4yMjVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDUpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjNzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDYpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjM3NXM7IH0KICAgIGNpcmNsZTpudGgtY2hpbGQoNykgeyBhbmltYXRpb24tZGVsYXk6IDAuNDVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDgpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjUyNXM7IH0KCiAgICBAa2V5ZnJhbWVzIGJhbGwgewogICAgICBmcm9tIHsgb3BhY2l0eTogMTsgfQogICAgICB0byB7IG9wYWNpdHk6IDAuMzsgfQogICAgfQoJPC9zdHlsZT4KCTxnIHN0eWxlPSJmaWxsOndoaXRlOyI+CgkJPGNpcmNsZSBjeD0nNScgY3k9JzEnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nNy44Mjg0JyBjeT0nMi4xNzE2JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzknIGN5PSc1JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzcuODI4NCcgY3k9JzcuODI4NCcgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc1JyBjeT0nOScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PScyLjE3MTYnIGN5PSc3LjgyODQnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nMScgY3k9JzUnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nMi4xNzE2JyBjeT0nMi4xNzE2JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJPC9nPgo8L3N2Zz4K")}.monaco-split-view2{position:relative;width:100%;height:100%}.monaco-split-view2>.sash-container{position:absolute;width:100%;height:100%;pointer-events:none}.monaco-split-view2>.sash-container>.monaco-sash{pointer-events:auto}.monaco-split-view2>.split-view-container{display:-ms-flexbox;display:flex;width:100%;height:100%;white-space:nowrap}.monaco-split-view2.vertical>.split-view-container{-ms-flex-direction:column;flex-direction:column}.monaco-split-view2.horizontal>.split-view-container{-ms-flex-direction:row;flex-direction:row}.monaco-split-view2>.split-view-container>.split-view-view{white-space:normal;-ms-flex:none;flex:none;position:relative}.monaco-split-view2>.split-view-container>.split-view-view:not(.visible){display:none}.monaco-split-view2.vertical>.split-view-container>.split-view-view{width:100%}.monaco-split-view2.horizontal>.split-view-container>.split-view-view{height:100%;display:inline-block}.monaco-split-view2.separator-border>.split-view-container>.split-view-view:not(:first-child):before{content:" ";position:absolute;top:0;left:0;z-index:5;pointer-events:none;background-color:var(--separator-border)}.monaco-split-view2.separator-border.horizontal>.split-view-container>.split-view-view:not(:first-child):before{height:100%;width:1px}.monaco-split-view2.separator-border.vertical>.split-view-container>.split-view-view:not(:first-child):before{height:1px;width:100%}.monaco-editor .goto-definition-link{text-decoration:underline;cursor:pointer}.monaco-editor .peekview-widget .head .peekview-title .severity-icon{display:inline-block;vertical-align:text-top;margin-right:4px}.monaco-editor .marker-widget{text-overflow:ellipsis;white-space:nowrap}.monaco-editor .marker-widget>.stale{opacity:.6;font-style:italic}.monaco-editor .marker-widget .title{display:inline-block;padding-right:5px}.monaco-editor .marker-widget .descriptioncontainer{position:absolute;white-space:pre;-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text;padding:8px 12px 0 20px}.monaco-editor .marker-widget .descriptioncontainer .message{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.monaco-editor .marker-widget .descriptioncontainer .message .details{padding-left:6px}.monaco-editor .marker-widget .descriptioncontainer .message .code,.monaco-editor .marker-widget .descriptioncontainer .message .source{opacity:.6}.monaco-editor .marker-widget .descriptioncontainer .filename{cursor:pointer}.monaco-keybinding{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;line-height:10px}.monaco-keybinding>.monaco-keybinding-key{display:inline-block;border:1px solid hsla(0,0%,80%,.4);border-bottom-color:hsla(0,0%,73%,.4);border-radius:3px;box-shadow:inset 0 -1px 0 hsla(0,0%,73%,.4);background-color:hsla(0,0%,87%,.4);vertical-align:middle;color:#555;font-size:11px;padding:3px 5px;margin:0 2px}.monaco-keybinding>.monaco-keybinding-key:first-child{margin-left:0}.monaco-keybinding>.monaco-keybinding-key:last-child{margin-right:0}.hc-black .monaco-keybinding>.monaco-keybinding-key,.vs-dark .monaco-keybinding>.monaco-keybinding-key{background-color:hsla(0,0%,50%,.17);color:#ccc;border:1px solid rgba(51,51,51,.6);border-bottom-color:rgba(68,68,68,.6);box-shadow:inset 0 -1px 0 rgba(68,68,68,.6)}.monaco-keybinding>.monaco-keybinding-key-separator{display:inline-block}.monaco-keybinding>.monaco-keybinding-key-chord-separator{width:6px}.monaco-quick-open-widget .monaco-list .monaco-list-row .monaco-highlighted-label .highlight,.monaco-quick-open-widget .monaco-tree .monaco-tree-row .monaco-highlighted-label .highlight{color:#0066bf}.vs-dark .monaco-quick-open-widget .monaco-list .monaco-list-row .monaco-highlighted-label .highlight,.vs-dark .monaco-quick-open-widget .monaco-tree .monaco-tree-row .monaco-highlighted-label .highlight{color:#0097fb}.hc-black .monaco-quick-open-widget .monaco-list .monaco-list-row .monaco-highlighted-label .highlight,.hc-black .monaco-quick-open-widget .monaco-tree .monaco-tree-row .monaco-highlighted-label .highlight{color:#f38518}.monaco-quick-open-widget{position:absolute;width:600px;z-index:2000;padding-bottom:6px;left:50%;margin-left:-300px}.monaco-quick-open-widget .monaco-progress-container{position:absolute;left:0;top:38px;z-index:1;height:2px}.monaco-quick-open-widget .monaco-progress-container .progress-bit{height:2px}.monaco-quick-open-widget .quick-open-input{width:588px;border:none;margin:6px}.monaco-quick-open-widget .quick-open-input .monaco-inputbox{width:100%;height:25px}.monaco-quick-open-widget .quick-open-result-count{position:absolute;left:-10000px}.monaco-quick-open-widget .quick-open-tree{line-height:22px}.monaco-quick-open-widget .quick-open-tree .monaco-tree-row>.content>.sub-content{overflow:hidden}.monaco-quick-open-widget.content-changing .quick-open-tree .monaco-scrollable-element .slider{display:none}.monaco-quick-open-widget .quick-open-tree .quick-open-entry{overflow:hidden;text-overflow:ellipsis;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;height:100%}.monaco-quick-open-widget .quick-open-tree .quick-open-entry>.quick-open-row{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon{overflow:hidden;width:16px;height:16px;margin-right:4px;display:inline-block;vertical-align:middle;-ms-flex-negative:0;flex-shrink:0}.monaco-quick-open-widget .quick-open-tree .monaco-icon-label,.monaco-quick-open-widget .quick-open-tree .monaco-icon-label .monaco-icon-label-description-container{-ms-flex:1;flex:1}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .monaco-highlighted-label span{opacity:1}.monaco-quick-open-widget .quick-open-tree .quick-open-entry-meta{opacity:.7;line-height:normal}.monaco-quick-open-widget .quick-open-tree .content.has-group-label .quick-open-entry-keybinding{margin-right:8px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry-keybinding .monaco-keybinding-key{vertical-align:text-bottom}.monaco-quick-open-widget .quick-open-tree .results-group{margin-right:18px}.monaco-quick-open-widget .quick-open-tree .focused .monaco-tree-row.focused>.content.has-actions>.results-group,.monaco-quick-open-widget .quick-open-tree .monaco-tree-row.focused>.content.has-actions>.results-group,.monaco-quick-open-widget .quick-open-tree .monaco-tree-row:hover:not(.highlighted)>.content.has-actions>.results-group{margin-right:0}.monaco-quick-open-widget .quick-open-tree .results-group-separator{border-top-width:1px;border-top-style:solid;box-sizing:border-box;margin-left:-11px;padding-left:11px}.monaco-tree .monaco-tree-row>.content.actions{position:relative;display:-ms-flexbox;display:flex}.monaco-tree .monaco-tree-row>.content.actions>.sub-content{-ms-flex:1;flex:1}.monaco-tree .monaco-tree-row>.content.actions .action-item{margin:0}.monaco-tree .monaco-tree-row>.content.actions>.primary-action-bar{line-height:22px;display:none;padding:0 .8em 0 .4em}.monaco-tree .monaco-tree-row.focused>.content.has-actions>.primary-action-bar{width:0;display:block}.monaco-tree.focused .monaco-tree-row.focused>.content.has-actions>.primary-action-bar,.monaco-tree .monaco-tree-row:hover:not(.highlighted)>.content.has-actions>.primary-action-bar,.monaco-tree .monaco-tree-row>.content.has-actions.more>.primary-action-bar{width:inherit;display:block}.monaco-tree .monaco-tree-row>.content.actions>.primary-action-bar .action-label{margin-right:.4em;margin-top:4px;background-repeat:no-repeat;width:16px;height:16px}.monaco-quick-open-widget .quick-open-tree .monaco-highlighted-label .highlight{font-weight:700}.monaco-tree{height:100%;width:100%;white-space:nowrap;-webkit-user-select:none;-moz-user-select:-moz-none;-ms-user-select:none;-o-user-select:none;user-select:none;position:relative}.monaco-tree>.monaco-scrollable-element{height:100%}.monaco-tree>.monaco-scrollable-element>.monaco-tree-wrapper{height:100%;width:100%;position:relative}.monaco-tree .monaco-tree-rows{position:absolute;width:100%;height:100%}.monaco-tree .monaco-tree-rows>.monaco-tree-row{-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;cursor:pointer;overflow:hidden;width:100%;-ms-touch-action:none;touch-action:none}.monaco-tree .monaco-tree-rows>.monaco-tree-row>.content{position:relative;height:100%}.monaco-tree-drag-image{display:inline-block;padding:1px 7px;border-radius:10px;font-size:12px;position:absolute}.monaco-tree .monaco-tree-rows>.monaco-tree-row.scrolling{display:none}.monaco-tree .monaco-tree-rows.show-twisties>.monaco-tree-row.has-children>.content:before{content:" ";position:absolute;display:block;background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2MSAxMi4zNTczTDYuMzMzMzMgMTIuOTc2TDExIDguMzA5MzVWNy42OTA2M0w2LjMzMzMzIDMuMDIzOTZMNS43MTQ2MSAzLjY0MjY4TDEwLjA3MTkgNy45OTk5OVoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==") 50% 50% no-repeat;width:16px;height:100%;top:0;left:-16px}.monaco-tree .monaco-tree-rows.show-twisties>.monaco-tree-row.expanded>.content:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAyIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MiA2LjMzMzMzTDguMjg1MzggMTFMNy42NjY2NiAxMUwzIDYuMzMzMzNMMy42MTg3MiA1LjcxNDYxTDcuOTc2MDIgMTAuMDcxOVoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-tree .monaco-tree-rows>.monaco-tree-row.has-children.loading>.content:before{background-image:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0nMS4wJyBzdGFuZGFsb25lPSdubycgPz4KPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZlcnNpb249JzEuMScgd2lkdGg9JzEwcHgnIGhlaWdodD0nMTBweCc+Cgk8c3R5bGU+CiAgICBjaXJjbGUgewogICAgICBhbmltYXRpb246IGJhbGwgMC42cyBsaW5lYXIgaW5maW5pdGU7CiAgICB9CgogICAgY2lyY2xlOm50aC1jaGlsZCgyKSB7IGFuaW1hdGlvbi1kZWxheTogMC4wNzVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDMpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjE1czsgfQogICAgY2lyY2xlOm50aC1jaGlsZCg0KSB7IGFuaW1hdGlvbi1kZWxheTogMC4yMjVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDUpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjNzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDYpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjM3NXM7IH0KICAgIGNpcmNsZTpudGgtY2hpbGQoNykgeyBhbmltYXRpb24tZGVsYXk6IDAuNDVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDgpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjUyNXM7IH0KCiAgICBAa2V5ZnJhbWVzIGJhbGwgewogICAgICBmcm9tIHsgb3BhY2l0eTogMTsgfQogICAgICB0byB7IG9wYWNpdHk6IDAuMzsgfQogICAgfQoJPC9zdHlsZT4KCTxnPgoJCTxjaXJjbGUgY3g9JzUnIGN5PScxJyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzcuODI4NCcgY3k9JzIuMTcxNicgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc5JyBjeT0nNScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc3LjgyODQnIGN5PSc3LjgyODQnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nNScgY3k9JzknIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nMi4xNzE2JyBjeT0nNy44Mjg0JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzEnIGN5PSc1JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzIuMTcxNicgY3k9JzIuMTcxNicgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCTwvZz4KPC9zdmc+Cg==")}.monaco-tree.highlighted .monaco-tree-rows>.monaco-tree-row:not(.highlighted){opacity:.3}.vs-dark .monaco-tree .monaco-tree-rows.show-twisties>.monaco-tree-row.has-children>.content:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2MSAxMi4zNTczTDYuMzMzMzMgMTIuOTc2TDExIDguMzA5MzVWNy42OTA2NEw2LjMzMzMzIDMuMDIzOTdMNS43MTQ2MSAzLjY0MjY5TDEwLjA3MTkgNy45OTk5OVoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.vs-dark .monaco-tree .monaco-tree-rows.show-twisties>.monaco-tree-row.expanded>.content:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAyIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MiA2LjMzMzMzTDguMjg1MzggMTFMNy42NjY2NiAxMUwzIDYuMzMzMzNMMy42MTg3MiA1LjcxNDYxTDcuOTc2MDIgMTAuMDcxOVoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.vs-dark .monaco-tree .monaco-tree-rows>.monaco-tree-row.has-children.loading>.content:before{background-image:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0nMS4wJyBzdGFuZGFsb25lPSdubycgPz4KPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZlcnNpb249JzEuMScgd2lkdGg9JzEwcHgnIGhlaWdodD0nMTBweCc+Cgk8c3R5bGU+CiAgICBjaXJjbGUgewogICAgICBhbmltYXRpb246IGJhbGwgMC42cyBsaW5lYXIgaW5maW5pdGU7CiAgICB9CgogICAgY2lyY2xlOm50aC1jaGlsZCgyKSB7IGFuaW1hdGlvbi1kZWxheTogMC4wNzVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDMpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjE1czsgfQogICAgY2lyY2xlOm50aC1jaGlsZCg0KSB7IGFuaW1hdGlvbi1kZWxheTogMC4yMjVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDUpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjNzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDYpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjM3NXM7IH0KICAgIGNpcmNsZTpudGgtY2hpbGQoNykgeyBhbmltYXRpb24tZGVsYXk6IDAuNDVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDgpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjUyNXM7IH0KCiAgICBAa2V5ZnJhbWVzIGJhbGwgewogICAgICBmcm9tIHsgb3BhY2l0eTogMTsgfQogICAgICB0byB7IG9wYWNpdHk6IDAuMzsgfQogICAgfQoJPC9zdHlsZT4KCTxnIHN0eWxlPSJmaWxsOmdyZXk7Ij4KCQk8Y2lyY2xlIGN4PSc1JyBjeT0nMScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc3LjgyODQnIGN5PScyLjE3MTYnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nOScgY3k9JzUnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nNy44Mjg0JyBjeT0nNy44Mjg0JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzUnIGN5PSc5JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzIuMTcxNicgY3k9JzcuODI4NCcgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PScxJyBjeT0nNScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PScyLjE3MTYnIGN5PScyLjE3MTYnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+Cgk8L2c+Cjwvc3ZnPgo=")}.hc-black .monaco-tree .monaco-tree-rows.show-twisties>.monaco-tree-row.has-children>.content:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMC4wNzE5IDcuOTk5OTlMNS43MTQ2MSAxMi4zNTczTDYuMzMzMzMgMTIuOTc2TDExIDguMzA5MzVWNy42OTA2M0w2LjMzMzMzIDMuMDIzOTZMNS43MTQ2MSAzLjY0MjY4TDEwLjA3MTkgNy45OTk5OVoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=")}.hc-black .monaco-tree .monaco-tree-rows.show-twisties>.monaco-tree-row.expanded>.content:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk3NjAyIDEwLjA3MTlMMTIuMzMzMyA1LjcxNDYxTDEyLjk1MiA2LjMzMzMzTDguMjg1MzggMTFMNy42NjY2NiAxMUwzIDYuMzMzMzNMMy42MTg3MiA1LjcxNDYxTDcuOTc2MDIgMTAuMDcxOVoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=")}.hc-black .monaco-tree .monaco-tree-rows>.monaco-tree-row.has-children.loading>.content:before{background-image:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0nMS4wJyBzdGFuZGFsb25lPSdubycgPz4KPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZlcnNpb249JzEuMScgd2lkdGg9JzEwcHgnIGhlaWdodD0nMTBweCc+Cgk8c3R5bGU+CiAgICBjaXJjbGUgewogICAgICBhbmltYXRpb246IGJhbGwgMC42cyBsaW5lYXIgaW5maW5pdGU7CiAgICB9CgogICAgY2lyY2xlOm50aC1jaGlsZCgyKSB7IGFuaW1hdGlvbi1kZWxheTogMC4wNzVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDMpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjE1czsgfQogICAgY2lyY2xlOm50aC1jaGlsZCg0KSB7IGFuaW1hdGlvbi1kZWxheTogMC4yMjVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDUpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjNzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDYpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjM3NXM7IH0KICAgIGNpcmNsZTpudGgtY2hpbGQoNykgeyBhbmltYXRpb24tZGVsYXk6IDAuNDVzOyB9CiAgICBjaXJjbGU6bnRoLWNoaWxkKDgpIHsgYW5pbWF0aW9uLWRlbGF5OiAwLjUyNXM7IH0KCiAgICBAa2V5ZnJhbWVzIGJhbGwgewogICAgICBmcm9tIHsgb3BhY2l0eTogMTsgfQogICAgICB0byB7IG9wYWNpdHk6IDAuMzsgfQogICAgfQoJPC9zdHlsZT4KCTxnIHN0eWxlPSJmaWxsOndoaXRlOyI+CgkJPGNpcmNsZSBjeD0nNScgY3k9JzEnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nNy44Mjg0JyBjeT0nMi4xNzE2JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzknIGN5PSc1JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJCTxjaXJjbGUgY3g9JzcuODI4NCcgY3k9JzcuODI4NCcgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PSc1JyBjeT0nOScgcj0nMScgc3R5bGU9J29wYWNpdHk6MC4zOycgLz4KCQk8Y2lyY2xlIGN4PScyLjE3MTYnIGN5PSc3LjgyODQnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nMScgY3k9JzUnIHI9JzEnIHN0eWxlPSdvcGFjaXR5OjAuMzsnIC8+CgkJPGNpcmNsZSBjeD0nMi4xNzE2JyBjeT0nMi4xNzE2JyByPScxJyBzdHlsZT0nb3BhY2l0eTowLjM7JyAvPgoJPC9nPgo8L3N2Zz4K")}.monaco-tree-action.collapse-all{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTkgOUg0VjEwSDlWOVoiIGZpbGw9IiM0MjQyNDIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01IDNMNiAySDEzTDE0IDNWMTBMMTMgMTFIMTFWMTNMMTAgMTRIM0wyIDEzVjZMMyA1SDVWM1pNNiA1SDEwTDExIDZWMTBIMTNWM0g2VjVaTTEwIDZIM1YxM0gxMFY2WiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K") 50% no-repeat}.vs-dark .monaco-tree-action.collapse-all{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTkgOUg0VjEwSDlWOVoiIGZpbGw9IiNDNUM1QzUiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01IDNMNiAySDEzTDE0IDNWMTBMMTMgMTFIMTFWMTNMMTAgMTRIM0wyIDEzVjZMMyA1SDVWM1pNNiA1SDEwTDExIDZWMTBIMTNWM0g2VjVaTTEwIDZIM1YxM0gxMFY2WiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K") 50% no-repeat}.hc-black .monaco-tree-action.collapse-all{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTkgOUg0VjEwSDlWOVoiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNSAzTDYgMkgxM0wxNCAzVjEwTDEzIDExSDExVjEzTDEwIDE0SDNMMiAxM1Y2TDMgNUg1VjNaTTYgNUgxMEwxMSA2VjEwSDEzVjNINlY1Wk0xMCA2SDNWMTNIMTBWNloiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=") 50% no-repeat}.monaco-progress-container{width:100%;height:5px;overflow:hidden}.monaco-progress-container .progress-bit{width:2%;height:5px;position:absolute;left:0;display:none}.monaco-progress-container.active .progress-bit{display:inherit}.monaco-progress-container.discrete .progress-bit{left:0;transition:width .1s linear}.monaco-progress-container.discrete.done .progress-bit{width:100%}.monaco-progress-container.infinite .progress-bit{animation-name:progress;animation-duration:4s;animation-iteration-count:infinite;animation-timing-function:linear;-ms-animation-name:progress;-ms-animation-duration:4s;-ms-animation-iteration-count:infinite;-ms-animation-timing-function:linear;-webkit-animation-name:progress;-webkit-animation-duration:4s;-webkit-animation-iteration-count:infinite;-webkit-animation-timing-function:linear;-moz-animation-name:progress;-moz-animation-duration:4s;-moz-animation-iteration-count:infinite;-moz-animation-timing-function:linear;will-change:transform}.monaco-editor-hover{cursor:default;position:absolute;overflow:hidden;z-index:50;-webkit-user-select:text;-ms-user-select:text;-moz-user-select:text;-o-user-select:text;user-select:text;box-sizing:initial;animation:fadein .1s linear;line-height:1.5em}.monaco-editor-hover.hidden{display:none}.monaco-editor-hover .hover-contents{padding:4px 8px}.monaco-editor-hover .markdown-hover>.hover-contents:not(.code-hover-contents){max-width:500px;word-wrap:break-word}.monaco-editor-hover p,.monaco-editor-hover ul{margin:8px 0}.monaco-editor-hover hr{margin:4px -10px -6px;height:1px}.monaco-editor-hover p:first-child,.monaco-editor-hover ul:first-child{margin-top:0}.monaco-editor-hover p:last-child,.monaco-editor-hover ul:last-child{margin-bottom:0}.monaco-editor-hover ul{padding-left:20px}.monaco-editor-hover li>p{margin-bottom:0}.monaco-editor-hover li>ul{margin-top:0}.monaco-editor-hover code{border-radius:3px;padding:0 .4em}.monaco-editor-hover .monaco-tokenized-source{white-space:pre-wrap;word-break:break-all}.monaco-editor-hover .hover-row.status-bar{font-size:12px;line-height:22px}.monaco-editor-hover .hover-row.status-bar .actions{display:-ms-flexbox;display:flex;padding:0 8px}.monaco-editor-hover .hover-row.status-bar .actions .action-container{margin-right:16px;cursor:pointer}.monaco-editor-hover .hover-row.status-bar .actions .action-container .action .icon{padding-right:4px}.colorpicker-widget{height:190px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.monaco-editor .colorpicker-hover:focus{outline:none}.colorpicker-header{display:-ms-flexbox;display:flex;height:24px;position:relative;background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAHUlEQVQYV2PYvXu3JAi7uLiAMaYAjAGTQBPYLQkAa/0Zef3qRswAAAAASUVORK5CYII=");background-size:9px 9px;-ms-interpolation-mode:nearest-neighbor;image-rendering:pixelated}.colorpicker-header .picked-color{width:216px;line-height:24px;cursor:pointer;color:#fff;-ms-flex:1;flex:1;text-align:center}.colorpicker-header .picked-color.light{color:#000}.colorpicker-header .original-color{width:74px;z-index:inherit;cursor:pointer}.colorpicker-body{display:-ms-flexbox;display:flex;padding:8px;position:relative}.colorpicker-body .saturation-wrap{overflow:hidden;height:150px;position:relative;min-width:220px;-ms-flex:1;flex:1}.colorpicker-body .saturation-box{height:150px;position:absolute}.colorpicker-body .saturation-selection{width:9px;height:9px;margin:-5px 0 0 -5px;border:1px solid #fff;border-radius:100%;box-shadow:0 0 2px rgba(0,0,0,.8);position:absolute}.colorpicker-body .strip{width:25px;height:150px}.colorpicker-body .hue-strip{position:relative;margin-left:8px;cursor:grab;background:linear-gradient(180deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red)}.colorpicker-body .opacity-strip{position:relative;margin-left:8px;cursor:grab;background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAHUlEQVQYV2PYvXu3JAi7uLiAMaYAjAGTQBPYLQkAa/0Zef3qRswAAAAASUVORK5CYII=");background-size:9px 9px;-ms-interpolation-mode:nearest-neighbor;image-rendering:pixelated}.colorpicker-body .strip.grabbing{cursor:grabbing}.colorpicker-body .slider{position:absolute;top:0;left:-2px;width:calc(100% + 4px);height:4px;box-sizing:border-box;border:1px solid hsla(0,0%,100%,.71);box-shadow:0 0 1px rgba(0,0,0,.85)}.colorpicker-body .strip .overlay{height:150px;pointer-events:none}.monaco-editor .tokens-inspect-widget{z-index:50;-webkit-user-select:text;-ms-user-select:text;-moz-user-select:text;-o-user-select:text;user-select:text;padding:10px}.tokens-inspect-separator{height:1px;border:0}.monaco-editor .tokens-inspect-widget .tm-token{font-family:monospace}.monaco-editor .tokens-inspect-widget .tm-token-length{font-weight:400;font-size:60%;float:right}.monaco-editor .tokens-inspect-widget .tm-metadata-table{width:100%}.monaco-editor .tokens-inspect-widget .tm-metadata-value{font-family:monospace;text-align:right}.monaco-editor .tokens-inspect-widget .tm-token-type{font-family:monospace}.monaco-editor .iPadShowKeyboard{width:58px;min-width:0;height:36px;min-height:0;margin:0;padding:0;position:absolute;resize:none;overflow:hidden;background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCA1MyAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNDguMDM2NCA0LjAxMDQySDQuMDA3NzlMNC4wMDc3OSAzMi4wMjg2SDQ4LjAzNjRWNC4wMTA0MlpNNC4wMDc3OSAwLjAwNzgxMjVDMS43OTcyMSAwLjAwNzgxMjUgMC4wMDUxODc5OSAxLjc5OTg0IDAuMDA1MTg3OTkgNC4wMTA0MlYzMi4wMjg2QzAuMDA1MTg3OTkgMzQuMjM5MiAxLjc5NzIxIDM2LjAzMTIgNC4wMDc3OSAzNi4wMzEySDQ4LjAzNjRDNTAuMjQ3IDM2LjAzMTIgNTIuMDM5IDM0LjIzOTIgNTIuMDM5IDMyLjAyODZWNC4wMTA0MkM1Mi4wMzkgMS43OTk4NCA1MC4yNDcgMC4wMDc4MTI1IDQ4LjAzNjQgMC4wMDc4MTI1SDQuMDA3NzlaTTguMDEwNDIgOC4wMTMwMkgxMi4wMTNWMTIuMDE1Nkg4LjAxMDQyVjguMDEzMDJaTTIwLjAxODIgOC4wMTMwMkgxNi4wMTU2VjEyLjAxNTZIMjAuMDE4MlY4LjAxMzAyWk0yNC4wMjA4IDguMDEzMDJIMjguMDIzNFYxMi4wMTU2SDI0LjAyMDhWOC4wMTMwMlpNMzYuMDI4NiA4LjAxMzAySDMyLjAyNlYxMi4wMTU2SDM2LjAyODZWOC4wMTMwMlpNNDAuMDMxMiA4LjAxMzAySDQ0LjAzMzlWMTIuMDE1Nkg0MC4wMzEyVjguMDEzMDJaTTE2LjAxNTYgMTYuMDE4Mkg4LjAxMDQyVjIwLjAyMDhIMTYuMDE1NlYxNi4wMTgyWk0yMC4wMTgyIDE2LjAxODJIMjQuMDIwOFYyMC4wMjA4SDIwLjAxODJWMTYuMDE4MlpNMzIuMDI2IDE2LjAxODJIMjguMDIzNFYyMC4wMjA4SDMyLjAyNlYxNi4wMTgyWk00NC4wMzM5IDE2LjAxODJWMjAuMDIwOEgzNi4wMjg2VjE2LjAxODJINDQuMDMzOVpNMTIuMDEzIDI0LjAyMzRIOC4wMTA0MlYyOC4wMjZIMTIuMDEzVjI0LjAyMzRaTTE2LjAxNTYgMjQuMDIzNEgzNi4wMjg2VjI4LjAyNkgxNi4wMTU2VjI0LjAyMzRaTTQ0LjAzMzkgMjQuMDIzNEg0MC4wMzEyVjI4LjAyNkg0NC4wMzM5VjI0LjAyMzRaIiBmaWxsPSIjNDI0MjQyIi8+CjwvZz4KPGRlZnM+CjxjbGlwUGF0aCBpZD0iY2xpcDAiPgo8cmVjdCB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==") 50% no-repeat;border:4px solid #f6f6f6;border-radius:4px}.monaco-editor.vs-dark .iPadShowKeyboard{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCA1MyAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNDguMDM2NCA0LjAxMDQySDQuMDA3NzlMNC4wMDc3OSAzMi4wMjg2SDQ4LjAzNjRWNC4wMTA0MlpNNC4wMDc3OSAwLjAwNzgxMjVDMS43OTcyMSAwLjAwNzgxMjUgMC4wMDUxODc5OSAxLjc5OTg0IDAuMDA1MTg3OTkgNC4wMTA0MlYzMi4wMjg2QzAuMDA1MTg3OTkgMzQuMjM5MiAxLjc5NzIxIDM2LjAzMTIgNC4wMDc3OSAzNi4wMzEySDQ4LjAzNjRDNTAuMjQ3IDM2LjAzMTIgNTIuMDM5IDM0LjIzOTIgNTIuMDM5IDMyLjAyODZWNC4wMTA0MkM1Mi4wMzkgMS43OTk4NCA1MC4yNDcgMC4wMDc4MTI1IDQ4LjAzNjQgMC4wMDc4MTI1SDQuMDA3NzlaTTguMDEwNDIgOC4wMTMwMkgxMi4wMTNWMTIuMDE1Nkg4LjAxMDQyVjguMDEzMDJaTTIwLjAxODIgOC4wMTMwMkgxNi4wMTU2VjEyLjAxNTZIMjAuMDE4MlY4LjAxMzAyWk0yNC4wMjA4IDguMDEzMDJIMjguMDIzNFYxMi4wMTU2SDI0LjAyMDhWOC4wMTMwMlpNMzYuMDI4NiA4LjAxMzAySDMyLjAyNlYxMi4wMTU2SDM2LjAyODZWOC4wMTMwMlpNNDAuMDMxMiA4LjAxMzAySDQ0LjAzMzlWMTIuMDE1Nkg0MC4wMzEyVjguMDEzMDJaTTE2LjAxNTYgMTYuMDE4Mkg4LjAxMDQyVjIwLjAyMDhIMTYuMDE1NlYxNi4wMTgyWk0yMC4wMTgyIDE2LjAxODJIMjQuMDIwOFYyMC4wMjA4SDIwLjAxODJWMTYuMDE4MlpNMzIuMDI2IDE2LjAxODJIMjguMDIzNFYyMC4wMjA4SDMyLjAyNlYxNi4wMTgyWk00NC4wMzM5IDE2LjAxODJWMjAuMDIwOEgzNi4wMjg2VjE2LjAxODJINDQuMDMzOVpNMTIuMDEzIDI0LjAyMzRIOC4wMTA0MlYyOC4wMjZIMTIuMDEzVjI0LjAyMzRaTTE2LjAxNTYgMjQuMDIzNEgzNi4wMjg2VjI4LjAyNkgxNi4wMTU2VjI0LjAyMzRaTTQ0LjAzMzkgMjQuMDIzNEg0MC4wMzEyVjI4LjAyNkg0NC4wMzM5VjI0LjAyMzRaIiBmaWxsPSIjQzVDNUM1Ii8+CjwvZz4KPGRlZnM+CjxjbGlwUGF0aCBpZD0iY2xpcDAiPgo8cmVjdCB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==") 50% no-repeat;border:4px solid #252526}.monaco-editor .detected-link,.monaco-editor .detected-link-active{text-decoration:underline;text-underline-position:under}.monaco-editor .detected-link-active{cursor:pointer}.monaco-editor .parameter-hints-widget{z-index:10;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;line-height:1.5em}.monaco-editor .parameter-hints-widget>.wrapper{max-width:440px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.monaco-editor .parameter-hints-widget.multiple{min-height:3.3em;padding:0 0 0 1.9em}.monaco-editor .parameter-hints-widget.visible{transition:left .05s ease-in-out}.monaco-editor .parameter-hints-widget p,.monaco-editor .parameter-hints-widget ul{margin:8px 0}.monaco-editor .parameter-hints-widget .body,.monaco-editor .parameter-hints-widget .monaco-scrollable-element{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.monaco-editor .parameter-hints-widget .signature{padding:4px 5px}.monaco-editor .parameter-hints-widget .docs{padding:0 10px 0 5px;white-space:pre-wrap}.monaco-editor .parameter-hints-widget .docs.empty{display:none}.monaco-editor .parameter-hints-widget .docs .markdown-docs{white-space:normal}.monaco-editor .parameter-hints-widget .docs .code{white-space:pre-wrap}.monaco-editor .parameter-hints-widget .docs code{border-radius:3px;padding:0 .4em}.monaco-editor .parameter-hints-widget .buttons{position:absolute;display:none;bottom:0;left:0}.monaco-editor .parameter-hints-widget.multiple .buttons{display:block}.monaco-editor .parameter-hints-widget.multiple .button{position:absolute;left:2px;width:16px;height:16px;background-repeat:no-repeat;cursor:pointer}.monaco-editor .parameter-hints-widget .button.previous{bottom:24px;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZmlsbD0iIzQyNDI0MiIgZD0iTTEwLjggOS41bC45LS45TDguMSA1IDQuMiA4LjZsLjkuOSAzLTIuNyAyLjcgMi43eiIvPjwvc3ZnPg==")}.monaco-editor .parameter-hints-widget .button.next{bottom:0;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZmlsbD0iIzQyNDI0MiIgZD0iTTUuMSA1bC0uOS45IDMuNiAzLjYgMy45LTMuNi0xLS45LTMgMi43TDUuMSA1eiIvPjwvc3ZnPg==")}.monaco-editor .parameter-hints-widget .overloads{position:absolute;display:none;text-align:center;bottom:14px;left:0;width:22px;height:12px;line-height:12px;opacity:.5}.monaco-editor .parameter-hints-widget.multiple .overloads{display:block}.monaco-editor .parameter-hints-widget .signature .parameter.active{font-weight:700;text-decoration:underline}.monaco-editor .parameter-hints-widget .documentation-parameter>.parameter{font-weight:700;margin-right:.5em}.monaco-editor.hc-black .parameter-hints-widget .button.previous,.monaco-editor.vs-dark .parameter-hints-widget .button.previous{background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZmlsbD0iI0U4RThFOCIgZD0iTTEwLjggOS41bC45LS45TDguMSA1IDQuMiA4LjZsLjkuOSAzLTIuNyAyLjcgMi43eiIvPjwvc3ZnPg==")}.monaco-editor.hc-black .parameter-hints-widget .button.next,.monaco-editor.vs-dark .parameter-hints-widget .button.next{background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZmlsbD0iI0U4RThFOCIgZD0iTTUuMSA1bC0uOS45IDMuNiAzLjYgMy45LTMuNi0xLS45LTMgMi43TDUuMSA1eiIvPjwvc3ZnPg==")}.monaco-quick-open-widget{font-size:13px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon,.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjQwIiB2aWV3Qm94PSIwIDAgMzAwIDQwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTQgMjYuODU3NUw0LjQ4NTUgMjZMOS40ODU1IDIzSDEwLjUxNDVMMTUuNTE0NSAyNkwxNiAyNi44NTc1VjMyLjg1NzVMMTUuNTE0NSAzMy43MTVMMTAuNTE0NSAzNi43MTVIOS40ODU1TDQuNDg1NSAzMy43MTVMNCAzMi44NTc1VjI2Ljg1NzVaTTkuNSAzNS41NTc1TDUgMzIuODU3NVYyNy42OTk4TDkuNSAzMC4xNTQzVjM1LjU1NzVaTTEwLjUgMzUuNTU3NUwxNSAzMi44NTc1VjI3LjY5OThMMTAuNSAzMC4xNTQzVjM1LjU1NzVaTTEwIDIzLjg1NzVMNS4yNTkxMyAyNi43MDJMMTAgMjkuMjg3OUwxNC43NDA5IDI2LjcwMkwxMCAyMy44NTc1WiIgZmlsbD0iI0IxODBENyIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTQgNi44NTc0OUw0LjQ4NTUgNkw5LjQ4NTUgM0gxMC41MTQ1TDE1LjUxNDUgNkwxNiA2Ljg1NzQ5VjEyLjg1NzVMMTUuNTE0NSAxMy43MTVMMTAuNTE0NSAxNi43MTVIOS40ODU1TDQuNDg1NSAxMy43MTVMNCAxMi44NTc1VjYuODU3NDlaTTkuNSAxNS41NTc1TDUgMTIuODU3NVY3LjY5OTc1TDkuNSAxMC4xNTQzVjE1LjU1NzVaTTEwLjUgMTUuNTU3NUwxNSAxMi44NTc1VjcuNjk5NzVMMTAuNSAxMC4xNTQzVjE1LjU1NzVaTTEwIDMuODU3NDlMNS4yNTkxMyA2LjcwMjAxTDEwIDkuMjg3OTRMMTQuNzQwOSA2LjcwMjAxTDEwIDMuODU3NDlaIiBmaWxsPSIjNjUyRDkwIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMjMgMjguMzk0NEwyMy41NTI4IDI3LjVMMzAuNTUyOCAyNEgzMS40NDcyTDM2LjQ0NzIgMjYuNUwzNyAyNy4zOTQ0VjMxLjg5NDRMMzYuNDQ3MiAzMi43ODg5TDI5LjQ0NzIgMzYuMjg4OUgyOC41NTI4TDIzLjU1MjggMzMuNzg4OUwyMyAzMi44OTQ0VjI4LjM5NDRaTTI4LjUgMzUuMTQ0NEwyNCAzMi44OTQ0VjI5LjE3MDlMMjguNSAzMS4yMTY0VjM1LjE0NDRaTTI5LjUgMzUuMTQ0NEwzNiAzMS44OTQ0VjI4LjE3OTVMMjkuNSAzMS4yMTI5VjM1LjE0NDRaTTMxIDI0Ljg5NDRMMjQuMzM3MyAyOC4yMjU4TDI4Ljk5NzIgMzAuMzQ0TDM1LjY3MDYgMjcuMjI5N0wzMSAyNC44OTQ0WiIgZmlsbD0iIzc1QkVGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTIzIDguMzk0NDNMMjMuNTUyOCA3LjVMMzAuNTUyOCA0SDMxLjQ0NzJMMzYuNDQ3MiA2LjVMMzcgNy4zOTQ0M1YxMS44OTQ0TDM2LjQ0NzIgMTIuNzg4OUwyOS40NDcyIDE2LjI4ODlIMjguNTUyOEwyMy41NTI4IDEzLjc4ODlMMjMgMTIuODk0NFY4LjM5NDQzWk0yOC41IDE1LjE0NDRMMjQgMTIuODk0NFY5LjE3MDk0TDI4LjUgMTEuMjE2NFYxNS4xNDQ0Wk0yOS41IDE1LjE0NDRMMzYgMTEuODk0NFY4LjE3OTU0TDI5LjUgMTEuMjEyOVYxNS4xNDQ0Wk0zMSA0Ljg5NDQzTDI0LjMzNzMgOC4yMjU3OUwyOC45OTcyIDEwLjM0NEwzNS42NzA2IDcuMjI5NzNMMzEgNC44OTQ0M1oiIGZpbGw9IiMwMDdBQ0MiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00NS4zNTM2IDI4LjY0NjRMNDQuMDYwNyAyNy4zNTM1TDQ3LjM1MzYgMjQuMDYwN0w0OC42NDY1IDI1LjM1MzVMNDUuMzUzNiAyOC42NDY0Wk00NyAyM0w0MyAyN1YyNy43MDcxTDQ1IDI5LjcwNzFINDUuNzA3MUw0Ni44NTM2IDI4LjU2MDZWMzQuMzUzNUw0Ny4zNTM2IDM0Ljg1MzVINTIuMDA5N1YzNS4zNzQxTDUzLjM0MyAzNi43MDc0SDU0LjA1MDFMNTYuNzE2OCAzNC4wNDA3VjMzLjMzMzZMNTUuMzgzNSAzMi4wMDAzSDU0LjY3NjNMNTIuODIzMSAzMy44NTM1SDQ3Ljg1MzZWMjkuODkzNUg1Mi4wMDk3VjMwLjM3NEw1My4zNDMgMzEuNzA3M0g1NC4wNTAxTDU2LjcxNjggMjkuMDQwN1YyOC4zMzM2TDU1LjM4MzUgMjcuMDAwMkg1NC42NzYzTDUyLjg2MyAyOC44MTM2SDQ3Ljg1MzZWMjcuNTYwNkw0OS43MDcxIDI1LjcwNzFWMjVMNDcuNzA3MSAyM0g0N1pNNTMuMDcwMyAzMC4wMjA1TDUzLjY5NjYgMzAuNjQ2N0w1NS42NTYxIDI4LjY4NzFMNTUuMDI5OSAyOC4wNjA5TDUzLjA3MDMgMzAuMDIwNVpNNTMuMDcwMyAzNS4wMjA1TDUzLjY5NjYgMzUuNjQ2N0w1NS42NTYxIDMzLjY4NzJMNTUuMDI5OSAzMy4wNjFMNTMuMDcwMyAzNS4wMjA1WiIgZmlsbD0iI0VFOUQyOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTQ1LjM1MzYgOC42NDY0Mkw0NC4wNjA3IDcuMzUzNTNMNDcuMzUzNiA0LjA2MDY1TDQ4LjY0NjUgNS4zNTM1NEw0NS4zNTM2IDguNjQ2NDJaTTQ3IDNMNDMgNi45OTk5OFY3LjcwNzA4TDQ1IDkuNzA3MDdINDUuNzA3MUw0Ni44NTM2IDguNTYwNjNWMTQuMzUzNUw0Ny4zNTM2IDE0Ljg1MzVINTIuMDA5N1YxNS4zNzQxTDUzLjM0MyAxNi43MDc0SDU0LjA1MDFMNTYuNzE2OCAxNC4wNDA3VjEzLjMzMzZMNTUuMzgzNSAxMi4wMDAzSDU0LjY3NjNMNTIuODIzMSAxMy44NTM1SDQ3Ljg1MzZWOS44OTM1NUg1Mi4wMDk3VjEwLjM3NEw1My4zNDMgMTEuNzA3M0g1NC4wNTAxTDU2LjcxNjggOS4wNDA2OFY4LjMzMzU3TDU1LjM4MzUgNy4wMDAyNEg1NC42NzYzTDUyLjg2MyA4LjgxMzU2SDQ3Ljg1MzZWNy41NjA2NEw0OS43MDcxIDUuNzA3MDlWNC45OTk5OUw0Ny43MDcxIDNINDdaTTUzLjA3MDMgMTAuMDIwNUw1My42OTY2IDEwLjY0NjdMNTUuNjU2MSA4LjY4NzEzTDU1LjAyOTkgOC4wNjA5TDUzLjA3MDMgMTAuMDIwNVpNNTMuMDcwMyAxNS4wMjA1TDUzLjY5NjYgMTUuNjQ2N0w1NS42NTYxIDEzLjY4NzJMNTUuMDI5OSAxMy4wNjFMNTMuMDcwMyAxNS4wMjA1WiIgZmlsbD0iI0Q2N0UwMCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg4IDI0Ljk4MzZWMjQuOTcxOFYyNEg4Ny45MTA4Qzg3LjU5NzQgMjQgODcuMjk0MSAyNC4wNjE2IDg3LjAwMTMgMjQuMTg0N0M4Ni43MDgyIDI0LjMwOCA4Ni40NDk0IDI0LjQ4NDcgODYuMjI1OCAyNC43MTVDODYuMDAzMSAyNC45NDQyIDg1LjgzNzkgMjUuMTk1IDg1LjczMjggMjUuNDY3N0w4NS43MzIzIDI1LjQ2OUM4NS42MzM4IDI1LjczNTIgODUuNTY4MSAyNi4wMTIgODUuNTM1MyAyNi4yOTkyTDg1LjUzNTIgMjYuMzAwNUM4NS41MDY4IDI2LjU4MDUgODUuNDk4NyAyNi44Njg0IDg1LjUxMDggMjcuMTY0M0M4NS41MjI3IDI3LjQ1MzggODUuNTI4NyAyNy43NDMzIDg1LjUyODcgMjguMDMyOEM4NS41Mjg3IDI4LjIzNTYgODUuNDg5NyAyOC40MjU5IDg1LjQxMiAyOC42MDUxTDg1LjQxMTYgMjguNjA2Qzg1LjMzNjkgMjguNzgzIDg1LjIzNDIgMjguOTM4NyA4NS4xMDMyIDI5LjA3MzZDODQuOTc2NCAyOS4yMDQxIDg0LjgyNDcgMjkuMzEwNiA4NC42NDY3IDI5LjM5MjVDODQuNDcwNiAyOS40Njk1IDg0LjI4NSAyOS41MDgyIDg0LjA4OTIgMjkuNTA4Mkg4NFYyOS42VjMwLjRWMzAuNDkxOEg4NC4wODkyQzg0LjI4NDcgMzAuNDkxOCA4NC40NyAzMC41MzI0IDg0LjY0NiAzMC42MTMzTDg0LjY0NzQgMzAuNjE0Qzg0LjgyNDYgMzAuNjkxNiA4NC45NzU4IDMwLjc5NzYgODUuMTAyMiAzMC45MzE2TDg1LjEwNDEgMzAuOTMzNUM4NS4yMzQzIDMxLjA2MzcgODUuMzM2NiAzMS4yMTg3IDg1LjQxMTMgMzEuMzk5NEw4NS40MTIgMzEuNDAxMUM4NS40ODk5IDMxLjU4MDUgODUuNTI4NyAzMS43Njg4IDg1LjUyODcgMzEuOTY3MkM4NS41Mjg3IDMyLjI1NjcgODUuNTIyNyAzMi41NDYyIDg1LjUxMDggMzIuODM1N0M4NS40OTg3IDMzLjEzMTYgODUuNTA2OCAzMy40MjE1IDg1LjUzNTIgMzMuNzA1NUw4NS41MzU0IDMzLjcwNzJDODUuNTY4MiAzMy45OTAzIDg1LjYzMzkgMzQuMjY1IDg1LjczMjMgMzQuNTMxTDg1LjczMjggMzQuNTMyM0M4NS44Mzc5IDM0LjgwNSA4Ni4wMDMxIDM1LjA1NTggODYuMjI1OCAzNS4yODVDODYuNDQ5NCAzNS41MTUzIDg2LjcwODIgMzUuNjkyIDg3LjAwMTMgMzUuODE1M0M4Ny4yOTQxIDM1LjkzODQgODcuNTk3NCAzNiA4Ny45MTA4IDM2SDg4VjM1LjJWMzUuMDE2NEg4Ny45MTA4Qzg3LjcxMDkgMzUuMDE2NCA4Ny41MjM1IDM0Ljk3NzcgODcuMzQ3NiAzNC45MDA4Qzg3LjE3NCAzNC44MTkxIDg3LjAyMTkgMzQuNzEyNiA4Ni44OTA5IDM0LjU4MThDODYuNzYzOSAzNC40NDY5IDg2LjY2MSAzNC4yOTExIDg2LjU4MjIgMzQuMTEzN0M4Ni41MDg0IDMzLjkzNDYgODYuNDcxMyAzMy43NDQgODYuNDcxMyAzMy41NDFDODYuNDcxMyAzMy4zMTI3IDg2LjQ3NTMgMzMuMDg4NSA4Ni40ODMyIDMyLjg2ODZDODYuNDkxMiAzMi42NDExIDg2LjQ5MTMgMzIuNDE5NSA4Ni40ODMyIDMyLjIwMzlDODYuNDc5MSAzMS45ODI1IDg2LjQ2MDggMzEuNzY4OCA4Ni40MjgyIDMxLjU2MzFDODYuMzk1MSAzMS4zNTAyIDg2LjMzOTIgMzEuMTQ3NiA4Ni4yNjA0IDMwLjk1NTRDODYuMTgwOSAzMC43NjE2IDg2LjA3MjYgMzAuNTc3NSA4NS45MzYyIDMwLjQwM0M4NS44MjM1IDMwLjI1ODggODUuNjg1NCAzMC4xMjQ2IDg1LjUyMjggMzBDODUuNjg1NCAyOS44NzU0IDg1LjgyMzUgMjkuNzQxMiA4NS45MzYyIDI5LjU5N0M4Ni4wNzI2IDI5LjQyMjUgODYuMTgwOSAyOS4yMzg0IDg2LjI2MDQgMjkuMDQ0NkM4Ni4zMzkxIDI4Ljg1MjYgODYuMzk1MSAyOC42NTE3IDg2LjQyODMgMjguNDQyOEM4Ni40NjA4IDI4LjIzMzMgODYuNDc5MSAyOC4wMTk3IDg2LjQ4MzIgMjcuODAyMkM4Ni40OTEzIDI3LjU4MjYgODYuNDkxMyAyNy4zNjExIDg2LjQ4MzIgMjcuMTM3NUM4Ni40NzUzIDI2LjkxMzQgODYuNDcxMyAyNi42ODcyIDg2LjQ3MTMgMjYuNDU5Qzg2LjQ3MTMgMjYuMjYwMiA4Ni41MDgzIDI2LjA3MTUgODYuNTgyNCAyNS44OTIxQzg2LjY2MTQgMjUuNzEwMyA4Ni43NjQyIDI1LjU1NDggODYuODkwOSAyNS40MjQ0Qzg3LjAyMTkgMjUuMjg5NCA4Ny4xNzQ2IDI1LjE4MjcgODcuMzQ4IDI1LjEwNTFDODcuNTIzOCAyNS4wMjQzIDg3LjcxMTEgMjQuOTgzNiA4Ny45MTA4IDI0Ljk4MzZIODhaTTkyIDM1LjAxNjRWMzUuMDI4MlYzNkg5Mi4wODkyQzkyLjQwMjYgMzYgOTIuNzA1OSAzNS45Mzg0IDkyLjk5ODcgMzUuODE1M0M5My4yOTE4IDM1LjY5MiA5My41NTA2IDM1LjUxNTMgOTMuNzc0MiAzNS4yODVDOTMuOTk2OSAzNS4wNTU4IDk0LjE2MjEgMzQuODA1IDk0LjI2NzIgMzQuNTMyM0w5NC4yNjc3IDM0LjUzMUM5NC4zNjYyIDM0LjI2NDggOTQuNDMxOSAzMy45ODggOTQuNDY0NyAzMy43MDA4TDk0LjQ2NDggMzMuNjk5NUM5NC40OTMyIDMzLjQxOTUgOTQuNTAxMyAzMy4xMzE2IDk0LjQ4OTIgMzIuODM1N0M5NC40NzczIDMyLjU0NjIgOTQuNDcxMyAzMi4yNTY3IDk0LjQ3MTMgMzEuOTY3MkM5NC40NzEzIDMxLjc2NDQgOTQuNTEwMyAzMS41NzQxIDk0LjU4OCAzMS4zOTQ5TDk0LjU4ODQgMzEuMzk0Qzk0LjY2MzEgMzEuMjE3IDk0Ljc2NTggMzEuMDYxMyA5NC44OTY4IDMwLjkyNjRDOTUuMDIzNiAzMC43OTU5IDk1LjE3NTMgMzAuNjg5NCA5NS4zNTMzIDMwLjYwNzVDOTUuNTI5NCAzMC41MzA1IDk1LjcxNSAzMC40OTE4IDk1LjkxMDggMzAuNDkxOEg5NlYzMC40VjI5LjZWMjkuNTA4Mkg5NS45MTA4Qzk1LjcxNTMgMjkuNTA4MiA5NS41MyAyOS40Njc2IDk1LjM1NCAyOS4zODY3TDk1LjM1MjYgMjkuMzg2Qzk1LjE3NTQgMjkuMzA4NCA5NS4wMjQyIDI5LjIwMjQgOTQuODk3OCAyOS4wNjg0TDk0Ljg5NTkgMjkuMDY2NUM5NC43NjU3IDI4LjkzNjMgOTQuNjYzNCAyOC43ODEzIDk0LjU4ODcgMjguNjAwNkw5NC41ODggMjguNTk4OUM5NC41MTAxIDI4LjQxOTUgOTQuNDcxMyAyOC4yMzEyIDk0LjQ3MTMgMjguMDMyOEM5NC40NzEzIDI3Ljc0MzMgOTQuNDc3MyAyNy40NTM4IDk0LjQ4OTIgMjcuMTY0M0M5NC41MDEzIDI2Ljg2ODQgOTQuNDkzMiAyNi41Nzg1IDk0LjQ2NDggMjYuMjk0NUw5NC40NjQ2IDI2LjI5MjhDOTQuNDMxOCAyNi4wMDk3IDk0LjM2NjEgMjUuNzM1IDk0LjI2NzcgMjUuNDY5TDk0LjI2NzIgMjUuNDY3N0M5NC4xNjIxIDI1LjE5NSA5My45OTY5IDI0Ljk0NDIgOTMuNzc0MiAyNC43MTVDOTMuNTUwNiAyNC40ODQ3IDkzLjI5MTggMjQuMzA4IDkyLjk5ODcgMjQuMTg0N0M5Mi43MDU5IDI0LjA2MTYgOTIuNDAyNiAyNCA5Mi4wODkyIDI0SDkyVjI0LjhWMjQuOTgzNkg5Mi4wODkyQzkyLjI4OTEgMjQuOTgzNiA5Mi40NzY1IDI1LjAyMjMgOTIuNjUyNCAyNS4wOTkyQzkyLjgyNiAyNS4xODA5IDkyLjk3ODEgMjUuMjg3NCA5My4xMDkxIDI1LjQxODJDOTMuMjM2MSAyNS41NTMxIDkzLjMzOSAyNS43MDg5IDkzLjQxNzggMjUuODg2M0M5My40OTE2IDI2LjA2NTQgOTMuNTI4NyAyNi4yNTYgOTMuNTI4NyAyNi40NTlDOTMuNTI4NyAyNi42ODczIDkzLjUyNDcgMjYuOTExNSA5My41MTY4IDI3LjEzMTRDOTMuNTA4OCAyNy4zNTg5IDkzLjUwODcgMjcuNTgwNSA5My41MTY4IDI3Ljc5NjFDOTMuNTIwOSAyOC4wMTc1IDkzLjUzOTIgMjguMjMxMiA5My41NzE4IDI4LjQzNjlDOTMuNjA0OSAyOC42NDk4IDkzLjY2MDggMjguODUyNCA5My43Mzk2IDI5LjA0NDZDOTMuODE5MSAyOS4yMzg0IDkzLjkyNzQgMjkuNDIyNSA5NC4wNjM4IDI5LjU5N0M5NC4xNzY1IDI5Ljc0MTIgOTQuMzE0NiAyOS44NzU0IDk0LjQ3NzIgMzBDOTQuMzE0NiAzMC4xMjQ2IDk0LjE3NjUgMzAuMjU4OCA5NC4wNjM4IDMwLjQwM0M5My45Mjc0IDMwLjU3NzUgOTMuODE5MSAzMC43NjE2IDkzLjczOTYgMzAuOTU1NEM5My42NjA5IDMxLjE0NzQgOTMuNjA0OSAzMS4zNDgzIDkzLjU3MTcgMzEuNTU3MkM5My41MzkyIDMxLjc2NjcgOTMuNTIwOSAzMS45ODAzIDkzLjUxNjggMzIuMTk3OEM5My41MDg3IDMyLjQxNzQgOTMuNTA4NyAzMi42Mzg5IDkzLjUxNjggMzIuODYyNUM5My41MjQ3IDMzLjA4NjYgOTMuNTI4NyAzMy4zMTI4IDkzLjUyODcgMzMuNTQxQzkzLjUyODcgMzMuNzM5OCA5My40OTE3IDMzLjkyODUgOTMuNDE3NiAzNC4xMDc5QzkzLjMzODYgMzQuMjg5NyA5My4yMzU4IDM0LjQ0NTIgOTMuMTA5MSAzNC41NzU2QzkyLjk3ODEgMzQuNzEwNiA5Mi44MjU0IDM0LjgxNzMgOTIuNjUyIDM0Ljg5NDlDOTIuNDc2MiAzNC45NzU3IDkyLjI4ODkgMzUuMDE2NCA5Mi4wODkyIDM1LjAxNjRIOTJaIiBmaWxsPSIjQzVDNUM1Ii8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNODggNC45ODM2MVY0Ljk3MTg0VjRIODcuOTEwOEM4Ny41OTc0IDQgODcuMjk0MSA0LjA2MTYxIDg3LjAwMTMgNC4xODQ3M0M4Ni43MDgyIDQuMzA3OTggODYuNDQ5NCA0LjQ4NDc0IDg2LjIyNTggNC43MTQ5OEM4Ni4wMDMxIDQuOTQ0MjIgODUuODM3OSA1LjE5NDk4IDg1LjczMjggNS40Njc2Nkw4NS43MzIzIDUuNDY4OThDODUuNjMzOCA1LjczNTIgODUuNTY4MSA2LjAxMjAxIDg1LjUzNTMgNi4yOTkxN0w4NS41MzUyIDYuMzAwNTNDODUuNTA2OCA2LjU4MDUgODUuNDk4NyA2Ljg2ODQ0IDg1LjUxMDggNy4xNjQyOEM4NS41MjI3IDcuNDUzNzkgODUuNTI4NyA3Ljc0MzI5IDg1LjUyODcgOC4wMzI3OUM4NS41Mjg3IDguMjM1NTYgODUuNDg5NyA4LjQyNTk0IDg1LjQxMiA4LjYwNTA3TDg1LjQxMTYgOC42MDYwMUM4NS4zMzY5IDguNzgyOTYgODUuMjM0MiA4LjkzODY2IDg1LjEwMzIgOS4wNzM1OUM4NC45NzY0IDkuMjA0MDUgODQuODI0NyA5LjMxMDU1IDg0LjY0NjcgOS4zOTI1Qzg0LjQ3MDYgOS40Njk1NCA4NC4yODUgOS41MDgyIDg0LjA4OTIgOS41MDgySDg0VjkuNlYxMC40VjEwLjQ5MThIODQuMDg5MkM4NC4yODQ3IDEwLjQ5MTggODQuNDcgMTAuNTMyNCA4NC42NDYgMTAuNjEzM0w4NC42NDc0IDEwLjYxNEM4NC44MjQ2IDEwLjY5MTYgODQuOTc1OCAxMC43OTc2IDg1LjEwMjIgMTAuOTMxNkw4NS4xMDQxIDEwLjkzMzVDODUuMjM0MyAxMS4wNjM3IDg1LjMzNjYgMTEuMjE4NyA4NS40MTEzIDExLjM5OTRMODUuNDEyIDExLjQwMTFDODUuNDg5OSAxMS41ODA1IDg1LjUyODcgMTEuNzY4OCA4NS41Mjg3IDExLjk2NzJDODUuNTI4NyAxMi4yNTY3IDg1LjUyMjcgMTIuNTQ2MiA4NS41MTA4IDEyLjgzNTdDODUuNDk4NyAxMy4xMzE2IDg1LjUwNjggMTMuNDIxNSA4NS41MzUyIDEzLjcwNTVMODUuNTM1NCAxMy43MDcyQzg1LjU2ODIgMTMuOTkwMyA4NS42MzM5IDE0LjI2NSA4NS43MzIzIDE0LjUzMUw4NS43MzI4IDE0LjUzMjNDODUuODM3OSAxNC44MDUgODYuMDAzMSAxNS4wNTU4IDg2LjIyNTggMTUuMjg1Qzg2LjQ0OTQgMTUuNTE1MyA4Ni43MDgyIDE1LjY5MiA4Ny4wMDEzIDE1LjgxNTNDODcuMjk0MSAxNS45Mzg0IDg3LjU5NzQgMTYgODcuOTEwOCAxNkg4OFYxNS4yVjE1LjAxNjRIODcuOTEwOEM4Ny43MTA5IDE1LjAxNjQgODcuNTIzNSAxNC45Nzc3IDg3LjM0NzYgMTQuOTAwOEM4Ny4xNzQgMTQuODE5MSA4Ny4wMjE5IDE0LjcxMjYgODYuODkwOSAxNC41ODE4Qzg2Ljc2MzkgMTQuNDQ2OSA4Ni42NjEgMTQuMjkxMSA4Ni41ODIyIDE0LjExMzdDODYuNTA4NCAxMy45MzQ2IDg2LjQ3MTMgMTMuNzQ0IDg2LjQ3MTMgMTMuNTQxQzg2LjQ3MTMgMTMuMzEyNyA4Ni40NzUzIDEzLjA4ODUgODYuNDgzMiAxMi44Njg2Qzg2LjQ5MTIgMTIuNjQxMSA4Ni40OTEzIDEyLjQxOTUgODYuNDgzMiAxMi4yMDM5Qzg2LjQ3OTEgMTEuOTgyNSA4Ni40NjA4IDExLjc2ODggODYuNDI4MiAxMS41NjMxQzg2LjM5NTEgMTEuMzUwMiA4Ni4zMzkyIDExLjE0NzYgODYuMjYwNCAxMC45NTU0Qzg2LjE4MDkgMTAuNzYxNiA4Ni4wNzI2IDEwLjU3NzUgODUuOTM2MiAxMC40MDNDODUuODIzNSAxMC4yNTg4IDg1LjY4NTQgMTAuMTI0NiA4NS41MjI4IDEwQzg1LjY4NTQgOS44NzUzOCA4NS44MjM1IDkuNzQxMTkgODUuOTM2MiA5LjU5NzAyQzg2LjA3MjYgOS40MjI1NCA4Ni4xODA5IDkuMjM4NDMgODYuMjYwNCA5LjA0NDY0Qzg2LjMzOTEgOC44NTI2MyA4Ni4zOTUxIDguNjUxNzUgODYuNDI4MyA4LjQ0Mjg1Qzg2LjQ2MDggOC4yMzMzIDg2LjQ3OTEgOC4wMTk3MyA4Ni40ODMyIDcuODAyMTlDODYuNDkxMyA3LjU4MjYyIDg2LjQ5MTMgNy4zNjEwNSA4Ni40ODMyIDcuMTM3NDlDODYuNDc1MyA2LjkxMzQgODYuNDcxMyA2LjY4NzI1IDg2LjQ3MTMgNi40NTkwMkM4Ni40NzEzIDYuMjYwMTkgODYuNTA4MyA2LjA3MTUyIDg2LjU4MjQgNS44OTIwNUM4Ni42NjE0IDUuNzEwMzQgODYuNzY0MiA1LjU1NDc1IDg2Ljg5MDkgNS40MjQzN0M4Ny4wMjE5IDUuMjg5NDIgODcuMTc0NiA1LjE4Mjc1IDg3LjM0OCA1LjEwNTEzQzg3LjUyMzggNS4wMjQyNyA4Ny43MTExIDQuOTgzNjEgODcuOTEwOCA0Ljk4MzYxSDg4Wk05MiAxNS4wMTY0VjE1LjAyODJWMTZIOTIuMDg5MkM5Mi40MDI2IDE2IDkyLjcwNTkgMTUuOTM4NCA5Mi45OTg3IDE1LjgxNTNDOTMuMjkxOCAxNS42OTIgOTMuNTUwNiAxNS41MTUzIDkzLjc3NDIgMTUuMjg1QzkzLjk5NjkgMTUuMDU1OCA5NC4xNjIxIDE0LjgwNSA5NC4yNjcyIDE0LjUzMjNMOTQuMjY3NyAxNC41MzFDOTQuMzY2MiAxNC4yNjQ4IDk0LjQzMTkgMTMuOTg4IDk0LjQ2NDcgMTMuNzAwOEw5NC40NjQ4IDEzLjY5OTVDOTQuNDkzMiAxMy40MTk1IDk0LjUwMTMgMTMuMTMxNiA5NC40ODkyIDEyLjgzNTdDOTQuNDc3MyAxMi41NDYyIDk0LjQ3MTMgMTIuMjU2NyA5NC40NzEzIDExLjk2NzJDOTQuNDcxMyAxMS43NjQ0IDk0LjUxMDMgMTEuNTc0MSA5NC41ODggMTEuMzk0OUw5NC41ODg0IDExLjM5NEM5NC42NjMxIDExLjIxNyA5NC43NjU4IDExLjA2MTMgOTQuODk2OCAxMC45MjY0Qzk1LjAyMzYgMTAuNzk1OSA5NS4xNzUzIDEwLjY4OTQgOTUuMzUzMyAxMC42MDc1Qzk1LjUyOTQgMTAuNTMwNSA5NS43MTUgMTAuNDkxOCA5NS45MTA4IDEwLjQ5MThIOTZWMTAuNFY5LjZWOS41MDgySDk1LjkxMDhDOTUuNzE1MyA5LjUwODIgOTUuNTMgOS40Njc2MiA5NS4zNTQgOS4zODY2Nkw5NS4zNTI2IDkuMzg2MDRDOTUuMTc1NCA5LjMwODQ0IDk1LjAyNDIgOS4yMDIzOCA5NC44OTc4IDkuMDY4MzlMOTQuODk1OSA5LjA2NjQ4Qzk0Ljc2NTcgOC45MzYzIDk0LjY2MzQgOC43ODEyOSA5NC41ODg3IDguNjAwNThMOTQuNTg4IDguNTk4OTJDOTQuNTEwMSA4LjQxOTUzIDk0LjQ3MTMgOC4yMzExNyA5NC40NzEzIDguMDMyNzlDOTQuNDcxMyA3Ljc0MzI5IDk0LjQ3NzMgNy40NTM3OSA5NC40ODkyIDcuMTY0MjhDOTQuNTAxMyA2Ljg2ODQyIDk0LjQ5MzIgNi41Nzg0OCA5NC40NjQ4IDYuMjk0NTRMOTQuNDY0NiA2LjI5Mjg1Qzk0LjQzMTggNi4wMDk3MSA5NC4zNjYxIDUuNzM1MDIgOTQuMjY3NyA1LjQ2ODk3TDk0LjI2NzIgNS40Njc2NkM5NC4xNjIxIDUuMTk0OTkgOTMuOTk2OSA0Ljk0NDIyIDkzLjc3NDIgNC43MTQ5OEM5My41NTA2IDQuNDg0NzQgOTMuMjkxOCA0LjMwNzk4IDkyLjk5ODcgNC4xODQ3M0M5Mi43MDU5IDQuMDYxNjEgOTIuNDAyNiA0IDkyLjA4OTIgNEg5MlY0LjhWNC45ODM2MUg5Mi4wODkyQzkyLjI4OTEgNC45ODM2MSA5Mi40NzY1IDUuMDIyMyA5Mi42NTI0IDUuMDk5MTdDOTIuODI2IDUuMTgwOTIgOTIuOTc4MSA1LjI4NzM2IDkzLjEwOTEgNS40MTgyM0M5My4yMzYxIDUuNTUzMDUgOTMuMzM5IDUuNzA4ODkgOTMuNDE3OCA1Ljg4NjI4QzkzLjQ5MTYgNi4wNjU0IDkzLjUyODcgNi4yNTU5NiA5My41Mjg3IDYuNDU5MDJDOTMuNTI4NyA2LjY4NzI3IDkzLjUyNDcgNi45MTE0NSA5My41MTY4IDcuMTMxNDJDOTMuNTA4OCA3LjM1ODk0IDkzLjUwODcgNy41ODA0OSA5My41MTY4IDcuNzk2MDVDOTMuNTIwOSA4LjAxNzU0IDkzLjUzOTIgOC4yMzExNyA5My41NzE4IDguNDM2ODhDOTMuNjA0OSA4LjY0OTc2IDkzLjY2MDggOC44NTI0MyA5My43Mzk2IDkuMDQ0NjRDOTMuODE5MSA5LjIzODQzIDkzLjkyNzQgOS40MjI1NCA5NC4wNjM4IDkuNTk3MDJDOTQuMTc2NSA5Ljc0MTE5IDk0LjMxNDYgOS44NzUzOCA5NC40NzcyIDEwQzk0LjMxNDYgMTAuMTI0NiA5NC4xNzY1IDEwLjI1ODggOTQuMDYzOCAxMC40MDNDOTMuOTI3NCAxMC41Nzc1IDkzLjgxOTEgMTAuNzYxNiA5My43Mzk2IDEwLjk1NTRDOTMuNjYwOSAxMS4xNDc0IDkzLjYwNDkgMTEuMzQ4MyA5My41NzE3IDExLjU1NzJDOTMuNTM5MiAxMS43NjY3IDkzLjUyMDkgMTEuOTgwMyA5My41MTY4IDEyLjE5NzhDOTMuNTA4NyAxMi40MTc0IDkzLjUwODcgMTIuNjM4OSA5My41MTY4IDEyLjg2MjVDOTMuNTI0NyAxMy4wODY2IDkzLjUyODcgMTMuMzEyOCA5My41Mjg3IDEzLjU0MUM5My41Mjg3IDEzLjczOTggOTMuNDkxNyAxMy45Mjg1IDkzLjQxNzYgMTQuMTA3OUM5My4zMzg2IDE0LjI4OTcgOTMuMjM1OCAxNC40NDUyIDkzLjEwOTEgMTQuNTc1NkM5Mi45NzgxIDE0LjcxMDYgOTIuODI1NCAxNC44MTczIDkyLjY1MiAxNC44OTQ5QzkyLjQ3NjIgMTQuOTc1NyA5Mi4yODg5IDE1LjAxNjQgOTIuMDg5MiAxNS4wMTY0SDkyWiIgZmlsbD0iIzQyNDI0MiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTczLjUgMjdDNzIuMTE5MyAyNyA3MSAyOC4xMTkzIDcxIDI5LjVDNzEgMzAuODgwNyA3Mi4xMTkzIDMyIDczLjUgMzJDNzQuODgwNyAzMiA3NiAzMC44ODA3IDc2IDI5LjVDNzYgMjguMTE5MyA3NC44ODA3IDI3IDczLjUgMjdaTTcwLjAzNTQgMzBDNzAuMjc4MSAzMS42OTYxIDcxLjczNjggMzMgNzMuNSAzM0M3NS40MzMgMzMgNzcgMzEuNDMzIDc3IDI5LjVDNzcgMjcuNTY3IDc1LjQzMyAyNiA3My41IDI2QzcxLjczNjggMjYgNzAuMjc4MSAyNy4zMDM5IDcwLjAzNTQgMjlINjYuOTM3QzY2LjcxNSAyOC4xMzc0IDY1LjkzMTkgMjcuNSA2NSAyNy41QzYzLjg5NTQgMjcuNSA2MyAyOC4zOTU0IDYzIDI5LjVDNjMgMzAuNjA0NiA2My44OTU0IDMxLjUgNjUgMzEuNUM2NS45MzE5IDMxLjUgNjYuNzE1IDMwLjg2MjYgNjYuOTM3IDMwSDcwLjAzNTRaIiBmaWxsPSIjNzVCRUZGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNzMuNSA3QzcyLjExOTMgNyA3MSA4LjExOTI5IDcxIDkuNUM3MSAxMC44ODA3IDcyLjExOTMgMTIgNzMuNSAxMkM3NC44ODA3IDEyIDc2IDEwLjg4MDcgNzYgOS41Qzc2IDguMTE5MjkgNzQuODgwNyA3IDczLjUgN1pNNzAuMDM1NCAxMEM3MC4yNzgxIDExLjY5NjEgNzEuNzM2OCAxMyA3My41IDEzQzc1LjQzMyAxMyA3NyAxMS40MzMgNzcgOS41Qzc3IDcuNTY3IDc1LjQzMyA2IDczLjUgNkM3MS43MzY4IDYgNzAuMjc4MSA3LjMwMzg1IDcwLjAzNTQgOUg2Ni45MzdDNjYuNzE1IDguMTM3MzkgNjUuOTMxOSA3LjUgNjUgNy41QzYzLjg5NTQgNy41IDYzIDguMzk1NDMgNjMgOS41QzYzIDEwLjYwNDYgNjMuODk1NCAxMS41IDY1IDExLjVDNjUuOTMxOSAxMS41IDY2LjcxNSAxMC44NjI2IDY2LjkzNyAxMEg3MC4wMzU0WiIgZmlsbD0iIzAwN0FDQyIvPgo8cGF0aCBkPSJNMTA0LjgwNyAzNi45NzU0QzEwNC41NzEgMzYuOTcyMSAxMDQuMzM4IDM2LjkyMTEgMTA0LjEyMiAzNi44MjU0QzEwMy45MDcgMzYuNzI5NyAxMDMuNzEyIDM2LjU5MTMgMTAzLjU1MiAzNi40MTg2QzEwMy4yMzkgMzYuMTMzNCAxMDMuMDQ0IDM1Ljc0MDggMTAzLjAwOCAzNS4zMTg5QzEwMi45NjYgMzQuODgyOCAxMDMuMDkzIDM0LjQ0NzMgMTAzLjM2MSAzNC4xMDEzQzEwNC41NjggMzIuODI4OSAxMDYuOTQ3IDMwLjQ0OTQgMTA4LjY3OCAyOC43NTQ4QzEwOC4zMSAyNy43NTg5IDEwOC4zMjcgMjYuNjYxMyAxMDguNzI2IDI1LjY3NzRDMTA5LjA1NSAyNC44NTg4IDEwOS42MzkgMjQuMTY4MSAxMTAuMzkxIDIzLjcwODFDMTEwLjk4MiAyMy4zMTcxIDExMS42NiAyMy4wNzk0IDExMi4zNjYgMjMuMDE2N0MxMTMuMDcxIDIyLjk1NCAxMTMuNzgxIDIzLjA2ODIgMTE0LjQzMSAyMy4zNDg5TDExNS4wNDggMjMuNjE2MkwxMTIuMTgyIDI2LjU2NzRMMTEzLjQzNyAyNy44MjU4TDExNi4zODEgMjQuOTQ4OUwxMTYuNjQ4IDI1LjU2NzlDMTE2Ljg3NCAyNi4wODk4IDExNi45OTMgMjYuNjUxMiAxMTcgMjcuMjE5NkMxMTcuMDA2IDI3Ljc4OCAxMTYuOSAyOC4zNTIxIDExNi42ODcgMjguODc5MUMxMTYuNDc2IDI5LjQwMDMgMTE2LjE2MiAyOS44NzM3IDExNS43NjUgMzAuMjcxMkMxMTUuNTM5IDMwLjQ5MTcgMTE1LjI5IDMwLjY4NjUgMTE1LjAyMiAzMC44NTIyQzExNC40NjcgMzEuMjIyOCAxMTMuODMyIDMxLjQ1NjQgMTEzLjE3IDMxLjUzMzhDMTEyLjUwNyAzMS42MTEyIDExMS44MzUgMzEuNTMwMyAxMTEuMjEgMzEuMjk3NkMxMTAuMTEyIDMyLjQxMTMgMTA3LjM3MSAzNS4xNzA0IDEwNS44OTEgMzYuNTUyMkMxMDUuNTk0IDM2LjgyMTkgMTA1LjIwOCAzNi45NzI2IDEwNC44MDcgMzYuOTc1NFpNMTEyLjc0NSAyMy45MjhDMTEyLjA4NyAyMy45MjY0IDExMS40NDQgMjQuMTIwMiAxMTAuODk2IDI0LjQ4NDhDMTEwLjY4MyAyNC42MTUyIDExMC40ODQgMjQuNzY5IDExMC4zMDUgMjQuOTQzM0MxMDkuODI4IDI1LjQyNDIgMTA5LjUwOSAyNi4wMzk1IDEwOS4zOTIgMjYuNzA2N0MxMDkuMjc0IDI3LjM3MzkgMTA5LjM2NCAyOC4wNjEgMTA5LjY0OCAyOC42NzU5TDEwOS43ODMgMjguOTcyOUwxMDkuNTUgMjkuMjAwM0MxMDcuODEyIDMwLjg5NjcgMTA1LjI4MSAzMy40MjAxIDEwNC4wNjUgMzQuNzA0NUMxMDMuOTU2IDM0Ljg2NTggMTAzLjkxIDM1LjA2MDggMTAzLjkzNCAzNS4yNTM1QzEwMy45NTkgMzUuNDQ2MyAxMDQuMDUyIDM1LjYyMzggMTA0LjE5NyAzNS43NTMyQzEwNC4yOCAzNS44NDYyIDEwNC4zODIgMzUuOTIxMSAxMDQuNDk1IDM1Ljk3MzFDMTA0LjU5NiAzNi4wMTg0IDEwNC43MDQgMzYuMDQzIDEwNC44MTQgMzYuMDQ1NUMxMDQuOTgxIDM2LjA0MTMgMTA1LjE0IDM1Ljk3NyAxMDUuMjY0IDM1Ljg2NDZDMTA2LjgzNyAzNC4zOTY0IDEwOS44NzYgMzEuMzI2NCAxMTAuNzY4IDMwLjQyNDNMMTEwLjk5NyAzMC4xOTMzTDExMS4yOTIgMzAuMzI3OEMxMTEuODA2IDMwLjU2NzMgMTEyLjM3MyAzMC42Njk4IDExMi45MzggMzAuNjI1NUMxMTMuNTAzIDMwLjU4MTEgMTE0LjA0NyAzMC4zOTEzIDExNC41MTcgMzAuMDc0NUMxMTQuNzMxIDI5Ljk0MjYgMTE0LjkzIDI5Ljc4NjkgMTE1LjEwOSAyOS42MTA1QzExNS40MTggMjkuMzAxNSAxMTUuNjYzIDI4LjkzMzcgMTE1LjgyOSAyOC41Mjg3QzExNS45OTQgMjguMTIzNyAxMTYuMDc3IDI3LjY4OTcgMTE2LjA3MiAyNy4yNTIzQzExNi4wNzIgMjcuMDM2NiAxMTYuMDUgMjYuODIxNSAxMTYuMDA4IDI2LjYxMDFMMTEzLjQzMSAyOS4xMjUxTDExMC44NzkgMjYuNTc3NkwxMTMuMzk0IDIzLjk4ODNDMTEzLjE4IDIzLjk0NjcgMTEyLjk2MyAyMy45MjY1IDExMi43NDUgMjMuOTI4WiIgZmlsbD0iI0M1QzVDNSIvPgo8cGF0aCBkPSJNMTA0LjgwNyAxNi45NzU0QzEwNC41NzEgMTYuOTcyMSAxMDQuMzM4IDE2LjkyMTEgMTA0LjEyMiAxNi44MjU0QzEwMy45MDcgMTYuNzI5NyAxMDMuNzEyIDE2LjU5MTMgMTAzLjU1MiAxNi40MTg2QzEwMy4yMzkgMTYuMTMzNCAxMDMuMDQ0IDE1Ljc0MDggMTAzLjAwOCAxNS4zMTg5QzEwMi45NjYgMTQuODgyOCAxMDMuMDkzIDE0LjQ0NzMgMTAzLjM2MSAxNC4xMDEzQzEwNC41NjggMTIuODI4OSAxMDYuOTQ3IDEwLjQ0OTQgMTA4LjY3OCA4Ljc1NDc5QzEwOC4zMSA3Ljc1ODg3IDEwOC4zMjcgNi42NjEyNyAxMDguNzI2IDUuNjc3MzlDMTA5LjA1NSA0Ljg1ODc2IDEwOS42MzkgNC4xNjgwNSAxMTAuMzkxIDMuNzA4MDdDMTEwLjk4MiAzLjMxNzA2IDExMS42NiAzLjA3OTQ0IDExMi4zNjYgMy4wMTY3M0MxMTMuMDcxIDIuOTU0MDIgMTEzLjc4MSAzLjA2ODE5IDExNC40MzEgMy4zNDg5MkwxMTUuMDQ4IDMuNjE2MkwxMTIuMTgyIDYuNTY3MzhMMTEzLjQzNyA3LjgyNTgyTDExNi4zODEgNC45NDg4N0wxMTYuNjQ4IDUuNTY3ODhDMTE2Ljg3NCA2LjA4OTc2IDExNi45OTMgNi42NTExOSAxMTcgNy4yMTk2MUMxMTcuMDA2IDcuNzg4MDIgMTE2LjkgOC4zNTIxMSAxMTYuNjg3IDguODc5MTVDMTE2LjQ3NiA5LjQwMDI5IDExNi4xNjIgOS44NzM2OCAxMTUuNzY1IDEwLjI3MTJDMTE1LjUzOSAxMC40OTE3IDExNS4yOSAxMC42ODY1IDExNS4wMjIgMTAuODUyMkMxMTQuNDY3IDExLjIyMjggMTEzLjgzMiAxMS40NTY0IDExMy4xNyAxMS41MzM4QzExMi41MDcgMTEuNjExMiAxMTEuODM1IDExLjUzMDMgMTExLjIxIDExLjI5NzZDMTEwLjExMiAxMi40MTEzIDEwNy4zNzEgMTUuMTcwNCAxMDUuODkxIDE2LjU1MjJDMTA1LjU5NCAxNi44MjE5IDEwNS4yMDggMTYuOTcyNiAxMDQuODA3IDE2Ljk3NTRaTTExMi43NDUgMy45MjgwMkMxMTIuMDg3IDMuOTI2MzcgMTExLjQ0NCA0LjEyMDE4IDExMC44OTYgNC40ODQ4NUMxMTAuNjgzIDQuNjE1MiAxMTAuNDg0IDQuNzY4OTcgMTEwLjMwNSA0Ljk0MzNDMTA5LjgyOCA1LjQyNDIzIDEwOS41MDkgNi4wMzk1MyAxMDkuMzkyIDYuNzA2NjlDMTA5LjI3NCA3LjM3Mzg1IDEwOS4zNjQgOC4wNjA5OCAxMDkuNjQ4IDguNjc1OTFMMTA5Ljc4MyA4Ljk3Mjg4TDEwOS41NSA5LjIwMDI1QzEwNy44MTIgMTAuODk2NyAxMDUuMjgxIDEzLjQyMDEgMTA0LjA2NSAxNC43MDQ1QzEwMy45NTYgMTQuODY1OCAxMDMuOTEgMTUuMDYwOCAxMDMuOTM0IDE1LjI1MzVDMTAzLjk1OSAxNS40NDYzIDEwNC4wNTIgMTUuNjIzOCAxMDQuMTk3IDE1Ljc1MzJDMTA0LjI4IDE1Ljg0NjIgMTA0LjM4MiAxNS45MjExIDEwNC40OTUgMTUuOTczMUMxMDQuNTk2IDE2LjAxODQgMTA0LjcwNCAxNi4wNDMgMTA0LjgxNCAxNi4wNDU1QzEwNC45ODEgMTYuMDQxMyAxMDUuMTQgMTUuOTc3IDEwNS4yNjQgMTUuODY0NkMxMDYuODM3IDE0LjM5NjQgMTA5Ljg3NiAxMS4zMjY0IDExMC43NjggMTAuNDI0M0wxMTAuOTk3IDEwLjE5MzNMMTExLjI5MiAxMC4zMjc4QzExMS44MDYgMTAuNTY3MyAxMTIuMzczIDEwLjY2OTggMTEyLjkzOCAxMC42MjU1QzExMy41MDMgMTAuNTgxMSAxMTQuMDQ3IDEwLjM5MTMgMTE0LjUxNyAxMC4wNzQ1QzExNC43MzEgOS45NDI2IDExNC45MyA5Ljc4Njk0IDExNS4xMDkgOS42MTA0NUMxMTUuNDE4IDkuMzAxNTMgMTE1LjY2MyA4LjkzMzc0IDExNS44MjkgOC41Mjg3NEMxMTUuOTk0IDguMTIzNzUgMTE2LjA3NyA3LjY4OTc0IDExNi4wNzIgNy4yNTIyOEMxMTYuMDcyIDcuMDM2NjIgMTE2LjA1IDYuODIxNDggMTE2LjAwOCA2LjYxMDA3TDExMy40MzEgOS4xMjUwOEwxMTAuODc5IDYuNTc3NTlMMTEzLjM5NCAzLjk4ODM0QzExMy4xOCAzLjk0Njc0IDExMi45NjMgMy45MjY1MyAxMTIuNzQ1IDMuOTI4MDJaIiBmaWxsPSIjNDI0MjQyIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTQ5IDI1TDE1MCAyNEgxNTZMMTU3IDI1VjMwTDE1NiAzMUgxNTJWMzBIMTU2VjI1SDE1MFYyOEgxNDlWMjVaTTE1MCAyOUwxNTEgMzBWMzFWMzVMMTUwIDM2SDE0NEwxNDMgMzVWMzBMMTQ0IDI5SDE0OUgxNTBaTTE1MCAzMFYzMVYzNUgxNDRWMzBIMTQ5SDE1MFpNMTUxLjQxNCAyOUwxNTEgMjguNTg1OFYyOEgxNTVWMjlIMTUxLjQxNFpNMTUxIDI2SDE1NVYyN0gxNTFWMjZaTTE0OSAzMkgxNDVWMzNIMTQ5VjMyWiIgZmlsbD0iIzc1QkVGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTE0OSA1TDE1MCA0SDE1NkwxNTcgNVYxMEwxNTYgMTFIMTUyVjEwSDE1NlY1SDE1MFY4SDE0OVY1Wk0xNTAgOUwxNTEgMTBWMTFWMTVMMTUwIDE2SDE0NEwxNDMgMTVWMTBMMTQ0IDlIMTQ5SDE1MFpNMTUwIDEwVjExVjE1SDE0NFYxMEgxNDlIMTUwWk0xNTEuNDE0IDlMMTUxIDguNTg1NzlWOEgxNTVWOUgxNTEuNDE0Wk0xNTEgNkgxNTVWN0gxNTFWNlpNMTQ5IDEySDE0NVYxM0gxNDlWMTJaIiBmaWxsPSIjMDA3QUNDIi8+CjxwYXRoIGQ9Ik0xNzcgNkgxNzJWNUgxNzdWNlpNMTc2IDlIMTc0VjEwSDE3NlY5Wk0xNzIgOUgxNjNWMTBIMTcyVjlaTTE3NCAxNUgxNjNWMTZIMTc0VjE1Wk0xNjkgMTJIMTYzVjEzSDE2OVYxMlpNMTc3IDEySDE3MlYxM0gxNzdWMTJaTTE3MCA0VjdIMTYzVjRIMTcwWk0xNjkgNUgxNjRWNkgxNjlWNVoiIGZpbGw9IiNDNUM1QzUiLz4KPHBhdGggZD0iTTE3NyAyNkgxNzJWMjVIMTc3VjI2Wk0xNzYgMjlIMTc0VjMwSDE3NlYyOVpNMTcyIDI5SDE2M1YzMEgxNzJWMjlaTTE3NCAzNUgxNjNWMzZIMTc0VjM1Wk0xNjkgMzJIMTYzVjMzSDE2OVYzMlpNMTc3IDMySDE3MlYzM0gxNzdWMzJaTTE3MCAyNFYyN0gxNjNWMjRIMTcwWk0xNjkgMjVIMTY0VjI2SDE2OVYyNVoiIGZpbGw9IiM0MjQyNDIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yMDkuMjIzIDMyLjkzM0MyMDkuNTQ5IDMzLjEyNTQgMjA5LjkyMiAzMy4yMjMxIDIxMC4zIDMzLjIxNUMyMTAuNjM4IDMzLjIyMTggMjEwLjk3MyAzMy4xNDkyIDIxMS4yNzcgMzMuMDAzQzIxMS41ODIgMzIuODU2NyAyMTEuODQ4IDMyLjY0MDkgMjEyLjA1NCAzMi4zNzNDMjEyLjUwOSAzMS43NjUyIDIxMi43NCAzMS4wMTg3IDIxMi43MDggMzAuMjZDMjEyLjc0MSAyOS41ODYyIDIxMi41MzcgMjguOTIyMSAyMTIuMTMyIDI4LjM4M0MyMTEuOTM2IDI4LjE0MTYgMjExLjY4NiAyNy45NDk2IDIxMS40MDIgMjcuODIyM0MyMTEuMTE4IDI3LjY5NSAyMTAuODA5IDI3LjYzNiAyMTAuNDk4IDI3LjY1QzIxMC4wNzUgMjcuNjQ3IDIwOS42NiAyNy43NjA4IDIwOS4yOTggMjcuOTc5QzIwOS4xODMgMjguMDQ4MSAyMDkuMDc1IDI4LjEyNzggMjA4Ljk3NSAyOC4yMTdWMjUuNDc1SDIwNy45ODRWMzMuMUgyMDguOTc5VjMyLjc1NkMyMDkuMDU1IDMyLjgyMTcgMjA5LjEzNyAzMi44ODA5IDIwOS4yMjMgMzIuOTMzWk0yMDkuODUgMjguNzAwMUMyMTAuMDM2IDI4LjYyMSAyMTAuMjM4IDI4LjU4NjggMjEwLjQ0IDI4LjZDMjEwLjYxMyAyOC41OTQ1IDIxMC43ODQgMjguNjMwNSAyMTAuOTQgMjguNzA1QzIxMS4wOTYgMjguNzc5NSAyMTEuMjMyIDI4Ljg5MDIgMjExLjMzNiAyOS4wMjhDMjExLjU5MyAyOS4zOTA1IDIxMS43MTggMjkuODI5NSAyMTEuNjkzIDMwLjI3M0MyMTEuNzIgMzAuNzk3NSAyMTEuNTggMzEuMzE3IDIxMS4yOTMgMzEuNzU3QzIxMS4xODggMzEuOTE1MyAyMTEuMDQ1IDMyLjA0NDcgMjEwLjg3OCAzMi4xMzM1QzIxMC43MSAzMi4yMjIzIDIxMC41MjMgMzIuMjY3NSAyMTAuMzMzIDMyLjI2NUMyMTAuMTQ5IDMyLjI3MzIgMjA5Ljk2NiAzMi4yNCAyMDkuNzk3IDMyLjE2NzhDMjA5LjYyOCAzMi4wOTU2IDIwOS40NzggMzEuOTg2MyAyMDkuMzU3IDMxLjg0OEMyMDkuMTAyIDMxLjU1OTYgMjA4Ljk2NSAzMS4xODUxIDIwOC45NzUgMzAuOFYzMC4yQzIwOC45NjMgMjkuNzgzMyAyMDkuMTAzIDI5LjM3NjUgMjA5LjM2OCAyOS4wNTVDMjA5LjQ5OSAyOC45MDA2IDIwOS42NjQgMjguNzc5MSAyMDkuODUgMjguNzAwMVpNMjA1LjI4OSAyNy42NzVDMjA0Ljk3IDI3LjY3OTMgMjA0LjY1NCAyNy43MzQgMjA0LjM1MiAyNy44MzdDMjA0LjA2NCAyNy45MjI5IDIwMy43OTMgMjguMDU4MyAyMDMuNTUyIDI4LjIzN0wyMDMuNDUyIDI4LjMxNFYyOS41MTRMMjAzLjg3NSAyOS4xNTVDMjA0LjI0NiAyOC44MDQ4IDIwNC43MzEgMjguNjAxNSAyMDUuMjQxIDI4LjU4M0MyMDUuMzY2IDI4LjU3MTYgMjA1LjQ5MiAyOC41OTE1IDIwNS42MDcgMjguNjQwN0MyMDUuNzIyIDI4LjY4OTkgMjA1LjgyNCAyOC43NjcgMjA1LjkwMiAyOC44NjVDMjA2LjA1MiAyOS4wOTcxIDIwNi4xMzIgMjkuMzY3NSAyMDYuMTMzIDI5LjY0NEwyMDQuOSAyOS44MjVDMjA0LjM5NCAyOS44Nzc4IDIwMy45MTUgMzAuMDc3NyAyMDMuNTIyIDMwLjRDMjAzLjM2NyAzMC41NTE4IDIwMy4yNDMgMzAuNzMyNyAyMDMuMTU4IDMwLjkzMjRDMjAzLjA3MyAzMS4xMzIgMjAzLjAyOCAzMS4zNDY0IDIwMy4wMjYgMzEuNTYzNEMyMDMuMDI0IDMxLjc4MDQgMjAzLjA2NSAzMS45OTU3IDIwMy4xNDYgMzIuMTk2OUMyMDMuMjI4IDMyLjM5ODEgMjAzLjM0OCAzMi41ODEzIDIwMy41IDMyLjczNkMyMDMuNjY5IDMyLjg5MDQgMjAzLjg2NiAzMy4wMSAyMDQuMDgxIDMzLjA4NzlDMjA0LjI5NiAzMy4xNjU5IDIwNC41MjUgMzMuMjAwNSAyMDQuNzUzIDMzLjE5QzIwNS4xNDcgMzMuMTkzMSAyMDUuNTMzIDMzLjA3NzQgMjA1Ljg2IDMyLjg1OEMyMDUuOTYyIDMyLjc4OTcgMjA2LjA1NyAzMi43MTMxIDIwNi4xNDYgMzIuNjI5VjMzLjA3M0gyMDcuMDg3VjI5LjcxNUMyMDcuMTIxIDI5LjE3NDIgMjA2Ljk1NCAyOC42Mzk5IDIwNi42MTggMjguMjE1QzIwNi40NSAyOC4wMzI5IDIwNi4yNDMgMjcuODkgMjA2LjAxNCAyNy43OTY3QzIwNS43ODQgMjcuNzAzNCAyMDUuNTM3IDI3LjY2MTggMjA1LjI4OSAyNy42NzVaTTIwNi4xNDYgMzAuNzE2QzIwNi4xNjYgMzEuMTM0MyAyMDYuMDI2IDMxLjU0NDYgMjA1Ljc1NSAzMS44NjRDMjA1LjYzNyAzMi4wMDA1IDIwNS40OSAzMi4xMDkyIDIwNS4zMjUgMzIuMTgyMUMyMDUuMTYgMzIuMjU1MSAyMDQuOTggMzIuMjkwNiAyMDQuOCAzMi4yODZDMjA0LjY5IDMyLjI5NDUgMjA0LjU4IDMyLjI4MTIgMjA0LjQ3NiAzMi4yNDY5QzIwNC4zNzIgMzIuMjEyNSAyMDQuMjc1IDMyLjE1NzkgMjA0LjE5MiAzMi4wODZDMjA0LjA2MSAzMS45MzQ2IDIwMy45ODkgMzEuNzQwOSAyMDMuOTg5IDMxLjU0MDVDMjAzLjk4OSAzMS4zNDAxIDIwNC4wNjEgMzEuMTQ2NCAyMDQuMTkyIDMwLjk5NUMyMDQuNDczIDMwLjgyMTMgMjA0Ljc5MiAzMC43MTg0IDIwNS4xMjIgMzAuNjk1TDIwNi4xNDIgMzAuNTQ3TDIwNi4xNDYgMzAuNzE2Wk0yMTQuNDU5IDMzLjAzMjVDMjE0Ljc2NiAzMy4xNjM4IDIxNS4wOTggMzMuMjI2MSAyMTUuNDMyIDMzLjIxNUMyMTUuOTI3IDMzLjIyNyAyMTYuNDE1IDMzLjEwMDYgMjE2Ljg0MiAzMi44NUwyMTYuOTY1IDMyLjc3NUwyMTYuOTc4IDMyLjc2OFYzMS42MTVMMjE2LjUzMiAzMS45MzVDMjE2LjIxNiAzMi4xNTkyIDIxNS44MzYgMzIuMjc0NyAyMTUuNDQ4IDMyLjI2NEMyMTUuMjUgMzIuMjcxOSAyMTUuMDUyIDMyLjIzNDIgMjE0Ljg3IDMyLjE1MzhDMjE0LjY4OSAzMi4wNzMzIDIxNC41MjggMzEuOTUyMyAyMTQuNCAzMS44QzIxNC4xMTQgMzEuNDI0NSAyMTMuOTczIDMwLjk1OTEgMjE0IDMwLjQ4OEMyMTMuOTc0IDI5Ljk4NzMgMjE0LjEzNSAyOS40OTQ4IDIxNC40NTMgMjkuMTA3QzIxNC41OTMgMjguOTQxMSAyMTQuNzcgMjguODA5MSAyMTQuOTY4IDI4LjcyMTNDMjE1LjE2NyAyOC42MzM1IDIxNS4zODMgMjguNTkyIDIxNS42IDI4LjZDMjE1Ljk0NCAyOC41OTg0IDIxNi4yODEgMjguNjk1MyAyMTYuNTcxIDI4Ljg3OUwyMTcgMjkuMTQ0VjI3Ljk3TDIxNi44MzEgMjcuODk3QzIxNi40NjMgMjcuNzM0MyAyMTYuMDY0IDI3LjY1MDIgMjE1LjY2MSAyNy42NUMyMTUuMyAyNy42Mzk5IDIxNC45NDEgMjcuNzA3NiAyMTQuNjA4IDI3Ljg0ODZDMjE0LjI3NSAyNy45ODk2IDIxMy45NzYgMjguMjAwNSAyMTMuNzMyIDI4LjQ2N0MyMTMuMjI2IDI5LjAyNjggMjEyLjk1OCAyOS43NjE5IDIxMi45ODUgMzAuNTE2QzIxMi45NTcgMzEuMjIzNSAyMTMuMTk2IDMxLjkxNTcgMjEzLjY1NCAzMi40NTVDMjEzLjg3NyAzMi43MDQgMjE0LjE1MiAzMi45MDEyIDIxNC40NTkgMzMuMDMyNVoiIGZpbGw9IiNDNUM1QzUiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yMDkuMjIzIDEyLjkzM0MyMDkuNTQ5IDEzLjEyNTQgMjA5LjkyMiAxMy4yMjMxIDIxMC4zIDEzLjIxNUMyMTAuNjM4IDEzLjIyMTggMjEwLjk3MyAxMy4xNDkyIDIxMS4yNzcgMTMuMDAzQzIxMS41ODIgMTIuODU2NyAyMTEuODQ4IDEyLjY0MDkgMjEyLjA1NCAxMi4zNzNDMjEyLjUwOSAxMS43NjUyIDIxMi43NCAxMS4wMTg3IDIxMi43MDggMTAuMjZDMjEyLjc0MSA5LjU4NjIyIDIxMi41MzcgOC45MjIxIDIxMi4xMzIgOC4zODI5OEMyMTEuOTM2IDguMTQxNjEgMjExLjY4NiA3Ljk0OTU3IDIxMS40MDIgNy44MjIyOEMyMTEuMTE4IDcuNjk0OTggMjEwLjgwOSA3LjYzNTk3IDIxMC40OTggNy42NDk5N0MyMTAuMDc1IDcuNjQ2OTkgMjA5LjY2IDcuNzYwODUgMjA5LjI5OCA3Ljk3ODk4QzIwOS4xODMgOC4wNDgwNyAyMDkuMDc1IDguMTI3NzUgMjA4Ljk3NSA4LjIxNjk4VjUuNDc0OThIMjA3Ljk4NFYxMy4xSDIwOC45NzlWMTIuNzU2QzIwOS4wNTUgMTIuODIxNyAyMDkuMTM3IDEyLjg4MDkgMjA5LjIyMyAxMi45MzNaTTIwOS44NSA4LjcwMDA2QzIxMC4wMzYgOC42MjEwNSAyMTAuMjM4IDguNTg2NzcgMjEwLjQ0IDguNTk5OThDMjEwLjYxMyA4LjU5NDUyIDIxMC43ODQgOC42MzA1NCAyMTAuOTQgOC43MDUwMUMyMTEuMDk2IDguNzc5NDggMjExLjIzMiA4Ljg5MDIzIDIxMS4zMzYgOS4wMjc5OEMyMTEuNTkzIDkuMzkwNTMgMjExLjcxOCA5LjgyOTUxIDIxMS42OTMgMTAuMjczQzIxMS43MiAxMC43OTc1IDIxMS41OCAxMS4zMTcgMjExLjI5MyAxMS43NTdDMjExLjE4OCAxMS45MTUzIDIxMS4wNDUgMTIuMDQ0NyAyMTAuODc4IDEyLjEzMzVDMjEwLjcxIDEyLjIyMjMgMjEwLjUyMyAxMi4yNjc1IDIxMC4zMzMgMTIuMjY1QzIxMC4xNDkgMTIuMjczMiAyMDkuOTY2IDEyLjI0IDIwOS43OTcgMTIuMTY3OEMyMDkuNjI4IDEyLjA5NTYgMjA5LjQ3OCAxMS45ODYzIDIwOS4zNTcgMTEuODQ4QzIwOS4xMDIgMTEuNTU5NiAyMDguOTY1IDExLjE4NTEgMjA4Ljk3NSAxMC44VjEwLjJDMjA4Ljk2MyA5Ljc4MzMyIDIwOS4xMDMgOS4zNzY1IDIwOS4zNjggOS4wNTQ5OEMyMDkuNDk5IDguOTAwNjQgMjA5LjY2NCA4Ljc3OTA4IDIwOS44NSA4LjcwMDA2Wk0yMDUuMjg5IDcuNjc0OTlDMjA0Ljk3IDcuNjc5MzMgMjA0LjY1NCA3LjczNCAyMDQuMzUyIDcuODM2OTlDMjA0LjA2NCA3LjkyMjkzIDIwMy43OTMgOC4wNTgyOCAyMDMuNTUyIDguMjM2OTlMMjAzLjQ1MiA4LjMxMzk5VjkuNTEzOTlMMjAzLjg3NSA5LjE1NDk5QzIwNC4yNDYgOC44MDQ3OCAyMDQuNzMxIDguNjAxNDYgMjA1LjI0MSA4LjU4Mjk5QzIwNS4zNjYgOC41NzE2NCAyMDUuNDkyIDguNTkxNDcgMjA1LjYwNyA4LjY0MDY4QzIwNS43MjIgOC42ODk5IDIwNS44MjQgOC43NjY5NyAyMDUuOTAyIDguODY0OTlDMjA2LjA1MiA5LjA5NzEgMjA2LjEzMiA5LjM2NzU0IDIwNi4xMzMgOS42NDM5OUwyMDQuOSA5LjgyNDk5QzIwNC4zOTQgOS44Nzc4MSAyMDMuOTE1IDEwLjA3NzcgMjAzLjUyMiAxMC40QzIwMy4zNjcgMTAuNTUxOCAyMDMuMjQzIDEwLjczMjcgMjAzLjE1OCAxMC45MzI0QzIwMy4wNzMgMTEuMTMyIDIwMy4wMjggMTEuMzQ2NCAyMDMuMDI2IDExLjU2MzRDMjAzLjAyNCAxMS43ODA0IDIwMy4wNjUgMTEuOTk1NyAyMDMuMTQ2IDEyLjE5NjlDMjAzLjIyOCAxMi4zOTgxIDIwMy4zNDggMTIuNTgxMyAyMDMuNSAxMi43MzZDMjAzLjY2OSAxMi44OTA0IDIwMy44NjYgMTMuMDEgMjA0LjA4MSAxMy4wODc5QzIwNC4yOTYgMTMuMTY1OSAyMDQuNTI1IDEzLjIwMDUgMjA0Ljc1MyAxMy4xOUMyMDUuMTQ3IDEzLjE5MzEgMjA1LjUzMyAxMy4wNzc0IDIwNS44NiAxMi44NThDMjA1Ljk2MiAxMi43ODk3IDIwNi4wNTcgMTIuNzEzMSAyMDYuMTQ2IDEyLjYyOVYxMy4wNzNIMjA3LjA4N1Y5LjcxNDk5QzIwNy4xMjEgOS4xNzQyMiAyMDYuOTU0IDguNjM5ODggMjA2LjYxOCA4LjIxNDk5QzIwNi40NSA4LjAzMjg1IDIwNi4yNDMgNy44OTAwMyAyMDYuMDE0IDcuNzk2N0MyMDUuNzg0IDcuNzAzMzYgMjA1LjUzNyA3LjY2MTgxIDIwNS4yODkgNy42NzQ5OVpNMjA2LjE0NiAxMC43MTZDMjA2LjE2NiAxMS4xMzQzIDIwNi4wMjYgMTEuNTQ0NiAyMDUuNzU1IDExLjg2NEMyMDUuNjM3IDEyLjAwMDUgMjA1LjQ5IDEyLjEwOTIgMjA1LjMyNSAxMi4xODIxQzIwNS4xNiAxMi4yNTUxIDIwNC45OCAxMi4yOTA2IDIwNC44IDEyLjI4NkMyMDQuNjkgMTIuMjk0NSAyMDQuNTggMTIuMjgxMiAyMDQuNDc2IDEyLjI0NjlDMjA0LjM3MiAxMi4yMTI1IDIwNC4yNzUgMTIuMTU3OSAyMDQuMTkyIDEyLjA4NkMyMDQuMDYxIDExLjkzNDYgMjAzLjk4OSAxMS43NDA5IDIwMy45ODkgMTEuNTQwNUMyMDMuOTg5IDExLjM0MDEgMjA0LjA2MSAxMS4xNDY0IDIwNC4xOTIgMTAuOTk1QzIwNC40NzMgMTAuODIxMyAyMDQuNzkyIDEwLjcxODQgMjA1LjEyMiAxMC42OTVMMjA2LjE0MiAxMC41NDdMMjA2LjE0NiAxMC43MTZaTTIxNC40NTkgMTMuMDMyNUMyMTQuNzY2IDEzLjE2MzggMjE1LjA5OCAxMy4yMjYxIDIxNS40MzIgMTMuMjE1QzIxNS45MjcgMTMuMjI3IDIxNi40MTUgMTMuMTAwNiAyMTYuODQyIDEyLjg1TDIxNi45NjUgMTIuNzc1TDIxNi45NzggMTIuNzY4VjExLjYxNUwyMTYuNTMyIDExLjkzNUMyMTYuMjE2IDEyLjE1OTIgMjE1LjgzNiAxMi4yNzQ3IDIxNS40NDggMTIuMjY0QzIxNS4yNSAxMi4yNzE5IDIxNS4wNTIgMTIuMjM0MiAyMTQuODcgMTIuMTUzOEMyMTQuNjg5IDEyLjA3MzMgMjE0LjUyOCAxMS45NTIzIDIxNC40IDExLjhDMjE0LjExNCAxMS40MjQ1IDIxMy45NzMgMTAuOTU5MSAyMTQgMTAuNDg4QzIxMy45NzQgOS45ODczMiAyMTQuMTM1IDkuNDk0NzUgMjE0LjQ1MyA5LjEwNzA0QzIxNC41OTMgOC45NDEwNSAyMTQuNzcgOC44MDkxNCAyMTQuOTY4IDguNzIxM0MyMTUuMTY3IDguNjMzNDYgMjE1LjM4MyA4LjU5MiAyMTUuNiA4LjYwMDA0QzIxNS45NDQgOC41OTg0NCAyMTYuMjgxIDguNjk1MjUgMjE2LjU3MSA4Ljg3OTA0TDIxNyA5LjE0NDA0VjcuOTcwMDRMMjE2LjgzMSA3Ljg5NzA0QzIxNi40NjMgNy43MzQzMiAyMTYuMDY0IDcuNjUwMiAyMTUuNjYxIDcuNjUwMDRDMjE1LjMgNy42Mzk5MSAyMTQuOTQxIDcuNzA3NjIgMjE0LjYwOCA3Ljg0ODU5QzIxNC4yNzUgNy45ODk1NiAyMTMuOTc2IDguMjAwNDggMjEzLjczMiA4LjQ2NzA0QzIxMy4yMjYgOS4wMjY4MyAyMTIuOTU4IDkuNzYxODYgMjEyLjk4NSAxMC41MTZDMjEyLjk1NyAxMS4yMjM1IDIxMy4xOTYgMTEuOTE1NyAyMTMuNjU0IDEyLjQ1NUMyMTMuODc3IDEyLjcwNCAyMTQuMTUyIDEyLjkwMTIgMjE0LjQ1OSAxMy4wMzI1WiIgZmlsbD0iIzQyNDI0MiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI2NiAzTDI2NSA0VjE2TDI2NiAxN0gyNzVMMjc2IDE2VjdMMjc1LjcwNyA2LjI5Mjg5TDI3Mi43MDcgMy4yOTI4OUwyNzIgM0gyNjZaTTI2NiAxNlY0TDI3MSA0VjhIMjc1VjE2SDI2NlpNMjc1IDdMMjcyIDRWN0wyNzUgN1oiIGZpbGw9IiM0MjQyNDIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yNjYgMjNMMjY1IDI0VjM2TDI2NiAzN0gyNzVMMjc2IDM2VjI3TDI3NS43MDcgMjYuMjkyOUwyNzIuNzA3IDIzLjI5MjlMMjcyIDIzSDI2NlpNMjY2IDM2VjI0TDI3MSAyNFYyOEgyNzVWMzZIMjY2Wk0yNzUgMjdMMjcyIDI0VjI3TDI3NSAyN1oiIGZpbGw9IiNDNUM1QzUiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMzAgMjRMMTI5IDI1VjI4SDEzMFYyNUgxMzZWMzBIMTMyVjMxSDEzNkwxMzcgMzBWMjVMMTM2IDI0SDEzMFpNMTMxIDMwTDEzMCAyOUgxMjlIMTI0TDEyMyAzMFYzNUwxMjQgMzZIMTMwTDEzMSAzNVYzMVYzMFpNMTMwIDMxVjMwSDEyOUgxMjRWMzVIMTMwVjMxWk0xMzEgMjguNTg1OEwxMzEuNDE0IDI5SDEzNVYyOEgxMzFWMjguNTg1OFpNMTM1IDI2SDEzMVYyN0gxMzVWMjZaTTEyOSAzMUgxMjVWMzJIMTI5VjMxWk0xMjUgMzNIMTI5VjM0SDEyNVYzM1oiIGZpbGw9IiNFRTlEMjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMzAgNEwxMjkgNVY4SDEzMFY1SDEzNlYxMEgxMzJWMTFIMTM2TDEzNyAxMFY1TDEzNiA0SDEzMFpNMTMxIDEwTDEzMCA5SDEyOUgxMjRMMTIzIDEwVjE1TDEyNCAxNkgxMzBMMTMxIDE1VjExVjEwWk0xMzAgMTFWMTBIMTI5SDEyNFYxNUgxMzBWMTFaTTEzMSA4LjU4NTc5TDEzMS40MTQgOUgxMzVWOEgxMzFWOC41ODU3OVpNMTM1IDZIMTMxVjdIMTM1VjZaTTEyOSAxMUgxMjVWMTJIMTI5VjExWk0xMjUgMTNIMTI5VjE0SDEyNVYxM1oiIGZpbGw9IiNENjdFMDAiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yNDYgM0wyNDUgNFYxNkwyNDYgMTdIMjU0TDI1NSAxNlY0TDI1NCAzSDI0NlpNMjQ2IDVWNEgyNTRWMTZIMjQ2VjE1SDI0OFYxNEgyNDZWMTJIMjUwVjExSDI0NlY5SDI0OFY4SDI0NlY2SDI1MFY1SDI0NloiIGZpbGw9IiM0MjQyNDIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yNDYgMjNMMjQ1IDI0VjM2TDI0NiAzN0gyNTRMMjU1IDM2VjI0TDI1NCAyM0gyNDZaTTI0NiAyNVYyNEgyNTRWMzZIMjQ2VjM1SDI0OFYzNEgyNDZWMzJIMjUwVjMxSDI0NlYyOUgyNDhWMjhIMjQ2VjI2SDI1MFYyNUgyNDZaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=");background-repeat:no-repeat;background-position:-2px -22px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon,.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor,.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function,.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method{background-position:-2px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.field,.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable{background-position:-22px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class{background-position:-42px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface{background-position:-62px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module{background-position:-82px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property{background-position:-102px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum{background-position:-122px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string{background-position:-202px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule{background-position:-242px -2px}.monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file{background-position:-262px -2px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor,.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function,.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method{background-position:-2px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.field,.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable{background-position:-22px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class{background-position:-43px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface{background-position:-63px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module{background-position:-82px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property{background-position:-102px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum{background-position:-122px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string{background-position:-202px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule{background-position:-242px -22px}.vs-dark .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file{background-position:-262px -22px}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon{background:none;display:inline}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon:before{height:16px;width:16px;display:inline-block}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.constructor:before,.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.function:before,.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.method:before,.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yIDQuODU3NDlMMi40ODU1IDRMNy40ODU1IDFIOC41MTQ1TDEzLjUxNDUgNEwxNCA0Ljg1NzQ5VjEwLjg1NzVMMTMuNTE0NSAxMS43MTVMOC41MTQ1IDE0LjcxNUg3LjQ4NTVMMi40ODU1IDExLjcxNUwyIDEwLjg1NzVWNC44NTc0OVpNNy41IDEzLjU1NzVMMyAxMC44NTc1VjUuNjk5NzVMNy41IDguMTU0M1YxMy41NTc1Wk04LjUgMTMuNTU3NUwxMyAxMC44NTc1VjUuNjk5NzVMOC41IDguMTU0M1YxMy41NTc1Wk04IDEuODU3NDlMMy4yNTkxMyA0LjcwMjAxTDggNy4yODc5NEwxMi43NDA5IDQuNzAyMDFMOCAxLjg1NzQ5WiIgZmlsbD0iI0IxODBENyIvPgo8L3N2Zz4K)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.field:before,.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.variable:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xIDYuMzk0NDNMMS41NTI3OSA1LjVMOC41NTI3OSAySDkuNDQ3MjFMMTQuNDQ3MiA0LjVMMTUgNS4zOTQ0M1Y5Ljg5NDQzTDE0LjQ0NzIgMTAuNzg4OUw3LjQ0NzIxIDE0LjI4ODlINi41NTI3OUwxLjU1Mjc5IDExLjc4ODlMMSAxMC44OTQ0VjYuMzk0NDNaTTYuNSAxMy4xNDQ0TDIgMTAuODk0NFY3LjE3MDk0TDYuNSA5LjIxNjM5VjEzLjE0NDRaTTcuNSAxMy4xNDQ0TDE0IDkuODk0NDNWNi4xNzk1NEw3LjUgOS4yMTI4N1YxMy4xNDQ0Wk05IDIuODk0NDNMMi4zMzcyOCA2LjIyNTc5TDYuOTk3MjUgOC4zNDM5NkwxMy42NzA2IDUuMjI5NzNMOSAyLjg5NDQzWiIgZmlsbD0iIzc1QkVGRiIvPgo8L3N2Zz4K)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.class:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjM1MzU2IDYuNjQ2NDJMMi4wNjA2NiA1LjM1MzUzTDUuMzUzNTYgMi4wNjA2NUw2LjY0NjQ1IDMuMzUzNTRMMy4zNTM1NiA2LjY0NjQyWk01IDFMMSA0Ljk5OTk4VjUuNzA3MDhMMyA3LjcwNzA3SDMuNzA3MTFMNC44NTM1NSA2LjU2MDYzVjEyLjM1MzVMNS4zNTM1NSAxMi44NTM1SDEwLjAwOTdWMTMuMzc0MUwxMS4zNDMgMTQuNzA3NEgxMi4wNTAxTDE0LjcxNjggMTIuMDQwN1YxMS4zMzM2TDEzLjM4MzUgMTAuMDAwM0gxMi42NzYzTDEwLjgyMzEgMTEuODUzNUg1Ljg1MzU1VjcuODkzNTVIMTAuMDA5N1Y4LjM3NDAxTDExLjM0MyA5LjcwNzM0SDEyLjA1MDFMMTQuNzE2OCA3LjA0MDY4VjYuMzMzNTdMMTMuMzgzNSA1LjAwMDI0SDEyLjY3NjNMMTAuODYzIDYuODEzNTZINS44NTM1NVY1LjU2MDY0TDcuNzA3MTEgMy43MDcwOVYyLjk5OTk5TDUuNzA3MTEgMUg1Wk0xMS4wNzAzIDguMDIwNDZMMTEuNjk2NiA4LjY0NjY4TDEzLjY1NjEgNi42ODcxM0wxMy4wMjk5IDYuMDYwOUwxMS4wNzAzIDguMDIwNDZaTTExLjA3MDMgMTMuMDIwNUwxMS42OTY2IDEzLjY0NjdMMTMuNjU2MSAxMS42ODcyTDEzLjAyOTkgMTEuMDYxTDExLjA3MDMgMTMuMDIwNVoiIGZpbGw9IiNFRTlEMjgiLz4KPC9zdmc+Cg==)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.interface:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS41IDVDMTAuMTE5MyA1IDkgNi4xMTkyOSA5IDcuNUM5IDguODgwNzEgMTAuMTE5MyAxMCAxMS41IDEwQzEyLjg4MDcgMTAgMTQgOC44ODA3MSAxNCA3LjVDMTQgNi4xMTkyOSAxMi44ODA3IDUgMTEuNSA1Wk04LjAzNTQ0IDhDOC4yNzgwNiA5LjY5NjE1IDkuNzM2NzYgMTEgMTEuNSAxMUMxMy40MzMgMTEgMTUgOS40MzMgMTUgNy41QzE1IDUuNTY3IDEzLjQzMyA0IDExLjUgNEM5LjczNjc2IDQgOC4yNzgwNiA1LjMwMzg1IDguMDM1NDQgN0g0LjkzNjk5QzQuNzE0OTcgNi4xMzczOSAzLjkzMTkyIDUuNSAzIDUuNUMxLjg5NTQzIDUuNSAxIDYuMzk1NDMgMSA3LjVDMSA4LjYwNDU3IDEuODk1NDMgOS41IDMgOS41QzMuOTMxOTIgOS41IDQuNzE0OTcgOC44NjI2MSA0LjkzNjk5IDhIOC4wMzU0NFoiIGZpbGw9IiM3NUJFRkYiLz4KPC9zdmc+Cg==)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.module:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02IDIuOTgzNjFWMi45NzE4NFYySDUuOTEwODNDNS41OTc0MyAyIDUuMjk0MDcgMi4wNjE2MSA1LjAwMTI4IDIuMTg0NzNDNC43MDgxOCAyLjMwNzk4IDQuNDQ5NDIgMi40ODQ3NCA0LjIyNTc4IDIuNzE0OThDNC4wMDMxMSAyLjk0NDIyIDMuODM3OTIgMy4xOTQ5OCAzLjczMjgyIDMuNDY3NjZMMy43MzIzMyAzLjQ2ODk4QzMuNjMzODIgMy43MzUyIDMuNTY4MTQgNC4wMTIwMSAzLjUzNTMzIDQuMjk5MTdMMy41MzUxOSA0LjMwMDUzQzMuNTA2NzggNC41ODA1IDMuNDk4NyA0Ljg2ODQ0IDMuNTEwODQgNS4xNjQyOEMzLjUyMjcyIDUuNDUzNzkgMy41Mjg2NiA1Ljc0MzI5IDMuNTI4NjYgNi4wMzI3OUMzLjUyODY2IDYuMjM1NTYgMy40ODk3NCA2LjQyNTk0IDMuNDEyIDYuNjA1MDdMMy40MTE2IDYuNjA2MDFDMy4zMzY4NyA2Ljc4Mjk2IDMuMjM0MjMgNi45Mzg2NiAzLjEwMzE3IDcuMDczNTlDMi45NzY0NCA3LjIwNDA1IDIuODI0NjYgNy4zMTA1NSAyLjY0NjcyIDcuMzkyNUMyLjQ3MDYgNy40Njk1NCAyLjI4NDk3IDcuNTA4MiAyLjA4OTE3IDcuNTA4MkgyVjcuNlY4LjRWOC40OTE4SDIuMDg5MTdDMi4yODQ2NSA4LjQ5MTggMi40NzAwMSA4LjUzMjM4IDIuNjQ2MDEgOC42MTMzNEwyLjY0NzQyIDguNjEzOTZDMi44MjQ1NyA4LjY5MTU3IDIuOTc1NzcgOC43OTc2MiAzLjEwMjIxIDguOTMxNjFMMy4xMDQxMiA4LjkzMzUyQzMuMjM0MjggOS4wNjM3IDMuMzM2NTkgOS4yMTg3MSAzLjQxMTI5IDkuMzk5NDJMMy40MTIwMSA5LjQwMTA4QzMuNDg5ODYgOS41ODA0NyAzLjUyODY2IDkuNzY4ODMgMy41Mjg2NiA5Ljk2NzIxQzMuNTI4NjYgMTAuMjU2NyAzLjUyMjcyIDEwLjU0NjIgMy41MTA4NCAxMC44MzU3QzMuNDk4NyAxMS4xMzE2IDMuNTA2NzcgMTEuNDIxNSAzLjUzNTE2IDExLjcwNTVMMy41MzUzNSAxMS43MDcyQzMuNTY4MTkgMTEuOTkwMyAzLjYzMzg3IDEyLjI2NSAzLjczMjMyIDEyLjUzMUwzLjczMjgzIDEyLjUzMjNDMy44Mzc5MyAxMi44MDUgNC4wMDMxMSAxMy4wNTU4IDQuMjI1NzggMTMuMjg1QzQuNDQ5NDIgMTMuNTE1MyA0LjcwODE4IDEzLjY5MiA1LjAwMTI4IDEzLjgxNTNDNS4yOTQwNyAxMy45Mzg0IDUuNTk3NDMgMTQgNS45MTA4MyAxNEg2VjEzLjJWMTMuMDE2NEg1LjkxMDgzQzUuNzEwOTUgMTMuMDE2NCA1LjUyMzQ2IDEyLjk3NzcgNS4zNDc2MyAxMi45MDA4QzUuMTczOTYgMTIuODE5MSA1LjAyMTk0IDEyLjcxMjYgNC44OTA4NiAxMi41ODE4QzQuNzYzODYgMTIuNDQ2OSA0LjY2MTA0IDEyLjI5MTEgNC41ODIyMyAxMi4xMTM3QzQuNTA4MzggMTEuOTM0NiA0LjQ3MTM0IDExLjc0NCA0LjQ3MTM0IDExLjU0MUM0LjQ3MTM0IDExLjMxMjcgNC40NzUzIDExLjA4ODUgNC40ODMyMSAxMC44Njg2QzQuNDkxMjUgMTAuNjQxMSA0LjQ5MTI3IDEwLjQxOTUgNC40ODMyNCAxMC4yMDM5QzQuNDc5MTQgOS45ODI0NiA0LjQ2MDg0IDkuNzY4ODMgNC40MjgyMyA5LjU2MzEyQzQuMzk1MTMgOS4zNTAyNCA0LjMzOTIxIDkuMTQ3NTcgNC4yNjAzOSA4Ljk1NTM2QzQuMTgwOTEgOC43NjE1NyA0LjA3MjU4IDguNTc3NDYgMy45MzYxNiA4LjQwMjk4QzMuODIzNDUgOC4yNTg4MSAzLjY4NTM4IDguMTI0NjIgMy41MjI4MyA4QzMuNjg1MzggNy44NzUzOCAzLjgyMzQ1IDcuNzQxMTkgMy45MzYxNiA3LjU5NzAyQzQuMDcyNTggNy40MjI1NCA0LjE4MDkxIDcuMjM4NDMgNC4yNjAzOSA3LjA0NDY0QzQuMzM5MTMgNi44NTI2MyA0LjM5NTEzIDYuNjUxNzUgNC40MjgyNiA2LjQ0Mjg1QzQuNDYwODIgNi4yMzMzIDQuNDc5MTQgNi4wMTk3MyA0LjQ4MzI0IDUuODAyMTlDNC40OTEyNyA1LjU4MjYyIDQuNDkxMjUgNS4zNjEwNSA0LjQ4MzIxIDUuMTM3NDlDNC40NzUzIDQuOTEzNCA0LjQ3MTM0IDQuNjg3MjUgNC40NzEzNCA0LjQ1OTAyQzQuNDcxMzQgNC4yNjAxOSA0LjUwODMzIDQuMDcxNTIgNC41ODIzOCAzLjg5MjA1QzQuNjYxMzUgMy43MTAzNCA0Ljc2NDIxIDMuNTU0NzUgNC44OTA4NiAzLjQyNDM3QzUuMDIxOTMgMy4yODk0MiA1LjE3NDYxIDMuMTgyNzUgNS4zNDgwMiAzLjEwNTEzQzUuNTIzOCAzLjAyNDI3IDUuNzExMTMgMi45ODM2MSA1LjkxMDgzIDIuOTgzNjFINlpNMTAgMTMuMDE2NFYxMy4wMjgyVjE0SDEwLjA4OTJDMTAuNDAyNiAxNCAxMC43MDU5IDEzLjkzODQgMTAuOTk4NyAxMy44MTUzQzExLjI5MTggMTMuNjkyIDExLjU1MDYgMTMuNTE1MyAxMS43NzQyIDEzLjI4NUMxMS45OTY5IDEzLjA1NTggMTIuMTYyMSAxMi44MDUgMTIuMjY3MiAxMi41MzIzTDEyLjI2NzcgMTIuNTMxQzEyLjM2NjIgMTIuMjY0OCAxMi40MzE5IDExLjk4OCAxMi40NjQ3IDExLjcwMDhMMTIuNDY0OCAxMS42OTk1QzEyLjQ5MzIgMTEuNDE5NSAxMi41MDEzIDExLjEzMTYgMTIuNDg5MiAxMC44MzU3QzEyLjQ3NzMgMTAuNTQ2MiAxMi40NzEzIDEwLjI1NjcgMTIuNDcxMyA5Ljk2NzIxQzEyLjQ3MTMgOS43NjQ0NCAxMi41MTAzIDkuNTc0MDYgMTIuNTg4IDkuMzk0OTNMMTIuNTg4NCA5LjM5Mzk5QzEyLjY2MzEgOS4yMTcwNCAxMi43NjU4IDkuMDYxMzQgMTIuODk2OCA4LjkyNjQyQzEzLjAyMzYgOC43OTU5NSAxMy4xNzUzIDguNjg5NDUgMTMuMzUzMyA4LjYwNzVDMTMuNTI5NCA4LjUzMDQ2IDEzLjcxNSA4LjQ5MTggMTMuOTEwOCA4LjQ5MThIMTRWOC40VjcuNlY3LjUwODJIMTMuOTEwOEMxMy43MTUzIDcuNTA4MiAxMy41MyA3LjQ2NzYyIDEzLjM1NCA3LjM4NjY2TDEzLjM1MjYgNy4zODYwNEMxMy4xNzU0IDcuMzA4NDQgMTMuMDI0MiA3LjIwMjM4IDEyLjg5NzggNy4wNjgzOUwxMi44OTU5IDcuMDY2NDhDMTIuNzY1NyA2LjkzNjMgMTIuNjYzNCA2Ljc4MTI5IDEyLjU4ODcgNi42MDA1OEwxMi41ODggNi41OTg5MkMxMi41MTAxIDYuNDE5NTMgMTIuNDcxMyA2LjIzMTE3IDEyLjQ3MTMgNi4wMzI3OUMxMi40NzEzIDUuNzQzMjkgMTIuNDc3MyA1LjQ1Mzc5IDEyLjQ4OTIgNS4xNjQyOEMxMi41MDEzIDQuODY4NDIgMTIuNDkzMiA0LjU3ODQ4IDEyLjQ2NDggNC4yOTQ1NEwxMi40NjQ2IDQuMjkyODVDMTIuNDMxOCA0LjAwOTcxIDEyLjM2NjEgMy43MzUwMiAxMi4yNjc3IDMuNDY4OTdMMTIuMjY3MiAzLjQ2NzY2QzEyLjE2MjEgMy4xOTQ5OSAxMS45OTY5IDIuOTQ0MjIgMTEuNzc0MiAyLjcxNDk4QzExLjU1MDYgMi40ODQ3NCAxMS4yOTE4IDIuMzA3OTggMTAuOTk4NyAyLjE4NDczQzEwLjcwNTkgMi4wNjE2MSAxMC40MDI2IDIgMTAuMDg5MiAySDEwVjIuOFYyLjk4MzYxSDEwLjA4OTJDMTAuMjg5MSAyLjk4MzYxIDEwLjQ3NjUgMy4wMjIzIDEwLjY1MjQgMy4wOTkxN0MxMC44MjYgMy4xODA5MiAxMC45NzgxIDMuMjg3MzYgMTEuMTA5MSAzLjQxODIzQzExLjIzNjEgMy41NTMwNSAxMS4zMzkgMy43MDg4OSAxMS40MTc4IDMuODg2MjhDMTEuNDkxNiA0LjA2NTQgMTEuNTI4NyA0LjI1NTk2IDExLjUyODcgNC40NTkwMkMxMS41Mjg3IDQuNjg3MjcgMTEuNTI0NyA0LjkxMTQ1IDExLjUxNjggNS4xMzE0MkMxMS41MDg4IDUuMzU4OTQgMTEuNTA4NyA1LjU4MDQ5IDExLjUxNjggNS43OTYwNUMxMS41MjA5IDYuMDE3NTQgMTEuNTM5MiA2LjIzMTE3IDExLjU3MTggNi40MzY4OEMxMS42MDQ5IDYuNjQ5NzYgMTEuNjYwOCA2Ljg1MjQzIDExLjczOTYgNy4wNDQ2NEMxMS44MTkxIDcuMjM4NDMgMTEuOTI3NCA3LjQyMjU0IDEyLjA2MzggNy41OTcwMkMxMi4xNzY1IDcuNzQxMTkgMTIuMzE0NiA3Ljg3NTM4IDEyLjQ3NzIgOEMxMi4zMTQ2IDguMTI0NjIgMTIuMTc2NSA4LjI1ODgxIDEyLjA2MzggOC40MDI5OEMxMS45Mjc0IDguNTc3NDYgMTEuODE5MSA4Ljc2MTU3IDExLjczOTYgOC45NTUzNkMxMS42NjA5IDkuMTQ3MzcgMTEuNjA0OSA5LjM0ODI1IDExLjU3MTcgOS41NTcxNUMxMS41MzkyIDkuNzY2NyAxMS41MjA5IDkuOTgwMjcgMTEuNTE2OCAxMC4xOTc4QzExLjUwODcgMTAuNDE3NCAxMS41MDg3IDEwLjYzODkgMTEuNTE2OCAxMC44NjI1QzExLjUyNDcgMTEuMDg2NiAxMS41Mjg3IDExLjMxMjggMTEuNTI4NyAxMS41NDFDMTEuNTI4NyAxMS43Mzk4IDExLjQ5MTcgMTEuOTI4NSAxMS40MTc2IDEyLjEwNzlDMTEuMzM4NiAxMi4yODk3IDExLjIzNTggMTIuNDQ1MiAxMS4xMDkxIDEyLjU3NTZDMTAuOTc4MSAxMi43MTA2IDEwLjgyNTQgMTIuODE3MyAxMC42NTIgMTIuODk0OUMxMC40NzYyIDEyLjk3NTcgMTAuMjg4OSAxMy4wMTY0IDEwLjA4OTIgMTMuMDE2NEgxMFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.property:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTIuODA3MjMgMTQuOTc1NEMyLjU3MTE5IDE0Ljk3MjEgMi4zMzgyNiAxNC45MjExIDIuMTIyNDcgMTQuODI1NEMxLjkwNjY3IDE0LjcyOTcgMS43MTI0OCAxNC41OTEzIDEuNTUxNTggMTQuNDE4NkMxLjIzODUgMTQuMTMzNCAxLjA0NDMzIDEzLjc0MDggMS4wMDc3NSAxMy4zMTg5QzAuOTY2MjI1IDEyLjg4MjggMS4wOTI2OSAxMi40NDczIDEuMzYxMzMgMTIuMTAxM0MyLjU2Nzc5IDEwLjgyODkgNC45NDczIDguNDQ5NCA2LjY3ODExIDYuNzU0NzlDNi4zMDk4MyA1Ljc1ODg3IDYuMzI3MDQgNC42NjEyNyA2LjcyNjM3IDMuNjc3MzlDNy4wNTQ3NCAyLjg1ODc2IDcuNjM4NjkgMi4xNjgwNSA4LjM5MTI5IDEuNzA4MDdDOC45ODE3IDEuMzE3MDYgOS42NjAzMSAxLjA3OTQ0IDEwLjM2NTcgMS4wMTY3M0MxMS4wNzExIDAuOTU0MDIyIDExLjc4MDkgMS4wNjgxOSAxMi40MzExIDEuMzQ4OTJMMTMuMDQ4MiAxLjYxNjJMMTAuMTgyNCA0LjU2NzM4TDExLjQzNzEgNS44MjU4MkwxNC4zODA5IDIuOTQ4ODdMMTQuNjQ4MiAzLjU2Nzg4QzE0Ljg3MzUgNC4wODk3NiAxNC45OTMgNC42NTExOSAxNC45OTk3IDUuMjE5NjFDMTUuMDA2NCA1Ljc4ODAyIDE0LjkwMDIgNi4zNTIxMSAxNC42ODcyIDYuODc5MTVDMTQuNDc2IDcuNDAwMjkgMTQuMTYyMyA3Ljg3MzY4IDEzLjc2NDcgOC4yNzEyMkMxMy41Mzk0IDguNDkxNjkgMTMuMjkwNCA4LjY4NjUzIDEzLjAyMjIgOC44NTIxOEMxMi40NjczIDkuMjIyNzUgMTEuODMyNCA5LjQ1NjM2IDExLjE2OTcgOS41MzM4QzEwLjUwNjkgOS42MTEyNCA5LjgzNTIxIDkuNTMwMyA5LjIwOTgyIDkuMjk3NjRDOC4xMTE5NCAxMC40MTEzIDUuMzcxNDIgMTMuMTcwNCAzLjg5MTE5IDE0LjU1MjJDMy41OTQyNiAxNC44MjE5IDMuMjA4MzIgMTQuOTcyNiAyLjgwNzIzIDE0Ljk3NTRaTTEwLjc0NDggMS45MjgwMkMxMC4wODcgMS45MjYzNyA5LjQ0MzU5IDIuMTIwMTggOC44OTYxNCAyLjQ4NDg1QzguNjgyNjUgMi42MTUyIDguNDg0MzcgMi43Njg5NyA4LjMwNDk4IDIuOTQzM0M3LjgyNzg5IDMuNDI0MjMgNy41MDkyNiA0LjAzOTUzIDcuMzkxODIgNC43MDY2OUM3LjI3NDM4IDUuMzczODUgNy4zNjM3NCA2LjA2MDk4IDcuNjQ3OTIgNi42NzU5MUw3Ljc4MzQyIDYuOTcyODhMNy41NTA0OCA3LjIwMDI1QzUuODEyMjQgOC44OTY3MiAzLjI4MTQ2IDExLjQyMDEgMi4wNjQ3OSAxMi43MDQ1QzEuOTU2NDYgMTIuODY1OCAxLjkxMDEyIDEzLjA2MDggMS45MzQzNSAxMy4yNTM1QzEuOTU4NTcgMTMuNDQ2MyAyLjA1MTcxIDEzLjYyMzggMi4xOTY1NyAxMy43NTMyQzIuMjgwMDUgMTMuODQ2MiAyLjM4MTc3IDEzLjkyMTEgMi40OTU0MSAxMy45NzMxQzIuNTk1NTcgMTQuMDE4NCAyLjcwMzgzIDE0LjA0MyAyLjgxMzczIDE0LjA0NTVDMi45ODA2NCAxNC4wNDEzIDMuMTQwNDQgMTMuOTc3IDMuMjYzODMgMTMuODY0NkM0LjgzNjg3IDEyLjM5NjQgNy44NzYyMiA5LjMyNjQxIDguNzY4MDcgOC40MjQzNUw4Ljk5NzMgOC4xOTMyNkw5LjI5MjQyIDguMzI3ODNDOS44MDYxNyA4LjU2NzMyIDEwLjM3MzEgOC42Njk4NSAxMC45MzgyIDguNjI1NDVDMTEuNTAzMyA4LjU4MTA2IDEyLjA0NzMgOC4zOTEyNSAxMi41MTc0IDguMDc0NDdDMTIuNzMxMyA3Ljk0MjYgMTIuOTI5NiA3Ljc4Njk0IDEzLjEwODUgNy42MTA0NUMxMy40MTgzIDcuMzAxNTMgMTMuNjYzMSA2LjkzMzc0IDEzLjgyODYgNi41Mjg3NEMxMy45OTQgNi4xMjM3NSAxNC4wNzY3IDUuNjg5NzQgMTQuMDcxOSA1LjI1MjI4QzE0LjA3MTkgNS4wMzY2MiAxNC4wNTA1IDQuODIxNDggMTQuMDA3OCA0LjYxMDA3TDExLjQzMDYgNy4xMjUwOEw4Ljg3OTQ0IDQuNTc3NTlMMTEuMzk0NCAxLjk4ODM0QzExLjE4MDQgMS45NDY3NCAxMC45NjI4IDEuOTI2NTMgMTAuNzQ0OCAxLjkyODAyWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.enum:before,.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.value:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04IDJMNyAzVjZIOFYzSDE0VjhIMTBWOUgxNEwxNSA4VjNMMTQgMkg4Wk05IDhMOCA3SDdIMkwxIDhWMTNMMiAxNEg4TDkgMTNWOVY4Wk04IDlWOEg3SDJWMTNIOFY5Wk05IDYuNTg1NzlMOS40MTQyMSA3SDEzVjZIOVY2LjU4NTc5Wk0xMyA0SDlWNUgxM1Y0Wk03IDlIM1YxMEg3VjlaTTMgMTFIN1YxMkgzVjExWiIgZmlsbD0iI0VFOUQyOCIvPgo8L3N2Zz4K)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.rule:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDFMMyAyVjE0TDQgMTVIMTJMMTMgMTRWMkwxMiAxSDRaTTQgM1YySDEyVjE0SDRWMTNINlYxMkg0VjEwSDhWOUg0VjdINlY2SDRWNEg4VjNINFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.file:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDFMMyAyVjE0TDQgMTVIMTNMMTQgMTRWNUwxMy43MDcxIDQuMjkyODlMMTAuNzA3MSAxLjI5Mjg5TDEwIDFINFpNNCAxNFYyTDkgMlY2SDEzVjE0SDRaTTEzIDVMMTAgMlY1TDEzIDVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=)}.hc-black .monaco-quick-open-widget .quick-open-tree .quick-open-entry .quick-open-entry-icon.string:before{content:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjIyMjg5IDEwLjkzM0M3LjU0ODYzIDExLjEyNTQgNy45MjE2MyAxMS4yMjMxIDguMjk5ODkgMTEuMjE1QzguNjM3NzcgMTEuMjIxOCA4Ljk3MjU0IDExLjE0OTIgOS4yNzcyMSAxMS4wMDNDOS41ODE4OCAxMC44NTY3IDkuODQ3OTIgMTAuNjQwOSAxMC4wNTM5IDEwLjM3M0MxMC41MDkxIDkuNzY1MTkgMTAuNzQwMiA5LjAxODY3IDEwLjcwNzkgOC4yNTk5OEMxMC43NDEyIDcuNTg2MjIgMTAuNTM3NCA2LjkyMjEgMTAuMTMxOSA2LjM4Mjk4QzkuOTM1NzUgNi4xNDE2MSA5LjY4NTc3IDUuOTQ5NTcgOS40MDIgNS44MjIyOEM5LjExODI0IDUuNjk0OTggOC44MDg1OCA1LjYzNTk3IDguNDk3ODkgNS42NDk5N0M4LjA3NTIyIDUuNjQ2OTkgNy42NTk5NCA1Ljc2MDg1IDcuMjk3ODkgNS45Nzg5OEM3LjE4MzA0IDYuMDQ4MDcgNy4wNzQ5IDYuMTI3NzUgNi45NzQ4OSA2LjIxNjk4VjMuNDc0OThINS45ODM4OVYxMS4xSDYuOTc4ODlWMTAuNzU2QzcuMDU1MTYgMTAuODIxNyA3LjEzNjc3IDEwLjg4MDkgNy4yMjI4OSAxMC45MzNaTTcuODQ5ODEgNi43MDAwNkM4LjAzNTk4IDYuNjIxMDUgOC4yMzgwNyA2LjU4Njc3IDguNDM5ODkgNi41OTk5OEM4LjYxMjU3IDYuNTk0NTIgOC43ODQwNCA2LjYzMDU0IDguOTM5OTQgNi43MDUwMUM5LjA5NTgzIDYuNzc5NDggOS4yMzE2MSA2Ljg5MDIzIDkuMzM1ODkgNy4wMjc5OEM5LjU5MjUzIDcuMzkwNTMgOS43MTg0IDcuODI5NTEgOS42OTI4OSA4LjI3Mjk3QzkuNzE5NzIgOC43OTc0OCA5LjU3OTY5IDkuMzE3MDEgOS4yOTI4OSA5Ljc1Njk4QzkuMTg4MjIgOS45MTUyNyA5LjA0NTQ2IDEwLjA0NDcgOC44Nzc3MyAxMC4xMzM1QzguNzA5OTkgMTAuMjIyMyA4LjUyMjY0IDEwLjI2NzUgOC4zMzI4OSAxMC4yNjVDOC4xNDkzNCAxMC4yNzMyIDcuOTY2MyAxMC4yNCA3Ljc5NzM0IDEwLjE2NzhDNy42MjgzOCAxMC4wOTU2IDcuNDc3ODQgOS45ODYyOCA3LjM1Njg5IDkuODQ3OTdDNy4xMDE1MiA5LjU1OTU3IDYuOTY1MDEgOS4xODUwNiA2Ljk3NDg5IDguNzk5OThWOC4xOTk5OEM2Ljk2Mjk5IDcuNzgzMzIgNy4xMDI2MyA3LjM3NjUgNy4zNjc4OSA3LjA1NDk4QzcuNDk4NTggNi45MDA2NCA3LjY2MzY0IDYuNzc5MDggNy44NDk4MSA2LjcwMDA2Wk0zLjI4OTAyIDUuNjc0OTlDMi45NzAxMSA1LjY3OTMzIDIuNjUzODggNS43MzQgMi4zNTIwMiA1LjgzNjk5QzIuMDY0MTcgNS45MjI5MyAxLjc5MzQ3IDYuMDU4MjggMS41NTIwMiA2LjIzNjk5TDEuNDUyMDIgNi4zMTM5OVY3LjUxMzk5TDEuODc1MDIgNy4xNTQ5OUMyLjI0NTc5IDYuODA0NzggMi43MzEzMyA2LjYwMTQ2IDMuMjQxMDIgNi41ODI5OUMzLjM2NTkzIDYuNTcxNjQgMy40OTE3IDYuNTkxNDcgMy42MDcwNiA2LjY0MDY4QzMuNzIyNDMgNi42ODk5IDMuODIzNzcgNi43NjY5NyAzLjkwMjAyIDYuODY0OTlDNC4wNTIyIDcuMDk3MSA0LjEzMjM5IDcuMzY3NTQgNC4xMzMwMiA3LjY0Mzk5TDIuOTAwMDIgNy44MjQ5OUMyLjM5NDM1IDcuODc3ODEgMS45MTUyNSA4LjA3NzcyIDEuNTIyMDIgOC4zOTk5OUMxLjM2Njk3IDguNTUxODEgMS4yNDMzOSA4LjczMjcxIDEuMTU4MzUgOC45MzIzNUMxLjA3MzMxIDkuMTMxOTkgMS4wMjg0OCA5LjM0NjQ0IDEuMDI2NDQgOS41NjM0M0MxLjAyNDQgOS43ODA0MiAxLjA2NTE3IDkuOTk1NjggMS4xNDY0NCAxMC4xOTY5QzEuMjI3NyAxMC4zOTgxIDEuMzQ3ODYgMTAuNTgxMyAxLjUwMDAyIDEwLjczNkMxLjY2ODcgMTAuODkwNCAxLjg2NjIyIDExLjAxIDIuMDgxMjUgMTEuMDg3OUMyLjI5NjI3IDExLjE2NTkgMi41MjQ1NiAxMS4yMDA1IDIuNzUzMDIgMTEuMTlDMy4xNDcgMTEuMTkzMSAzLjUzMjc4IDExLjA3NzQgMy44NjAwMiAxMC44NThDMy45NjE1MyAxMC43ODk3IDQuMDU3MiAxMC43MTMxIDQuMTQ2MDIgMTAuNjI5VjExLjA3M0g1LjA4NzAyVjcuNzE0OTlDNS4xMjEzNyA3LjE3NDIyIDQuOTU0MyA2LjYzOTg4IDQuNjE4MDIgNi4yMTQ5OUM0LjQ0OTc5IDYuMDMyODUgNC4yNDM0OCA1Ljg5MDAzIDQuMDEzNzggNS43OTY3QzMuNzg0MDcgNS43MDMzNiAzLjUzNjYxIDUuNjYxODEgMy4yODkwMiA1LjY3NDk5Wk00LjE0NjAyIDguNzE1OTlDNC4xNjU2NCA5LjEzNDM1IDQuMDI1OTIgOS41NDQ1OSAzLjc1NTAyIDkuODY0QzMuNjM2ODkgMTAuMDAwNSAzLjQ4OTk4IDEwLjEwOTIgMy4zMjQ4NiAxMC4xODIxQzMuMTU5NzMgMTAuMjU1MSAyLjk4MDQ5IDEwLjI5MDYgMi44MDAwMiAxMC4yODZDMi42OTA0OSAxMC4yOTQ1IDIuNTgwMzUgMTAuMjgxMiAyLjQ3NTk5IDEwLjI0NjlDMi4zNzE2MyAxMC4yMTI1IDIuMjc1MTEgMTAuMTU3OSAyLjE5MjAyIDEwLjA4NkMyLjA2MDc5IDkuOTM0NTUgMS45ODg1NiA5Ljc0MDg4IDEuOTg4NTYgOS41NDA0OUMxLjk4ODU2IDkuMzQwMTEgMi4wNjA3OSA5LjE0NjQ0IDIuMTkyMDIgOC45OTQ5OUMyLjQ3MzIyIDguODIxMzEgMi43OTIzMyA4LjcxODM3IDMuMTIyMDIgOC42OTQ5OUw0LjE0MjAyIDguNTQ2OTlMNC4xNDYwMiA4LjcxNTk5Wk0xMi40NTg4IDExLjAzMjVDMTIuNzY2IDExLjE2MzggMTMuMDk4MyAxMS4yMjYxIDEzLjQzMjIgMTEuMjE1QzEzLjkyNyAxMS4yMjcgMTQuNDE1MyAxMS4xMDA2IDE0Ljg0MjIgMTAuODVMMTQuOTY1MiAxMC43NzVMMTQuOTc4MiAxMC43NjhWOS42MTUwNEwxNC41MzIyIDkuOTM1MDRDMTQuMjE2IDEwLjE1OTIgMTMuODM1NiAxMC4yNzQ3IDEzLjQ0ODIgMTAuMjY0QzEzLjI0OTcgMTAuMjcxOSAxMy4wNTIgMTAuMjM0MiAxMi44NzAzIDEwLjE1MzhDMTIuNjg4NiAxMC4wNzMzIDEyLjUyNzggOS45NTIzMiAxMi40MDAyIDkuODAwMDRDMTIuMTE0NCA5LjQyNDUzIDExLjk3MjUgOC45NTkxMSAxMi4wMDAyIDguNDg4MDRDMTEuOTczNyA3Ljk4NzMyIDEyLjEzNTIgNy40OTQ3NSAxMi40NTMyIDcuMTA3MDRDMTIuNTkzNCA2Ljk0MTA1IDEyLjc2OTUgNi44MDkxNCAxMi45NjgyIDYuNzIxM0MxMy4xNjcgNi42MzM0NiAxMy4zODMxIDYuNTkyIDEzLjYwMDIgNi42MDAwNEMxMy45NDM5IDYuNTk4NDQgMTQuMjgwOCA2LjY5NTI1IDE0LjU3MTIgNi44NzkwNEwxNS4wMDAyIDcuMTQ0MDRWNS45NzAwNEwxNC44MzEyIDUuODk3MDRDMTQuNDYyNiA1LjczNDMyIDE0LjA2NDEgNS42NTAyIDEzLjY2MTIgNS42NTAwNEMxMy4yOTk5IDUuNjM5OTEgMTIuOTQwNiA1LjcwNzYyIDEyLjYwNzggNS44NDg1OUMxMi4yNzQ5IDUuOTg5NTYgMTEuOTc2MyA2LjIwMDQ4IDExLjczMjIgNi40NjcwNEMxMS4yMjYxIDcuMDI2ODMgMTAuOTU4MSA3Ljc2MTg2IDEwLjk4NTIgOC41MTYwNEMxMC45NTY3IDkuMjIzNDYgMTEuMTk1NSA5LjkxNTY5IDExLjY1NDIgMTAuNDU1QzExLjg3NjkgMTAuNzA0IDEyLjE1MTYgMTAuOTAxMiAxMi40NTg4IDExLjAzMjVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=)}.monaco-editor .rename-box{z-index:100;color:inherit}.monaco-editor .rename-box .rename-input{padding:4px}.monaco-editor .snippet-placeholder{min-width:2px}.monaco-editor .finish-snippet-placeholder,.monaco-editor .snippet-placeholder{outline-style:solid;outline-width:1px}.monaco-editor .suggest-widget{z-index:40;width:430px}.monaco-editor .suggest-widget>.details,.monaco-editor .suggest-widget>.message,.monaco-editor .suggest-widget>.tree{width:100%;border-style:solid;border-width:1px;box-sizing:border-box}.monaco-editor.hc-black .suggest-widget>.details,.monaco-editor.hc-black .suggest-widget>.message,.monaco-editor.hc-black .suggest-widget>.tree{border-width:2px}.monaco-editor .suggest-widget.docs-side{width:660px}.monaco-editor .suggest-widget.docs-side>.details,.monaco-editor .suggest-widget.docs-side>.tree{width:50%;float:left}.monaco-editor .suggest-widget.docs-side.list-right>.details,.monaco-editor .suggest-widget.docs-side.list-right>.tree{float:right}.monaco-editor .suggest-widget>.message{padding-left:22px}.monaco-editor .suggest-widget>.tree{height:100%}.monaco-editor .suggest-widget .monaco-list{-webkit-user-select:none;-moz-user-select:-moz-none;-ms-user-select:none;-o-user-select:none;user-select:none}.monaco-editor .suggest-widget .monaco-list .monaco-list-row{display:-ms-flexbox;display:flex;-mox-box-sizing:border-box;box-sizing:border-box;padding-right:10px;background-repeat:no-repeat;background-position:2px 2px;white-space:nowrap;cursor:pointer;-ms-touch-action:none;touch-action:none}.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents{-ms-flex:1;flex:1;height:100%;overflow:hidden;padding-left:2px}.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main{display:-ms-flexbox;display:flex;overflow:hidden;text-overflow:ellipsis;white-space:pre}.monaco-editor .suggest-widget:not(.frozen) .monaco-highlighted-label .highlight{font-weight:700}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.header>.close,.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.readMore{opacity:.6;background-position:50%;background-repeat:no-repeat;background-size:70%;cursor:pointer}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.header>.close{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk5OTk4IDguNzA3MDhMMTEuNjQ2NCAxMi4zNTM1TDEyLjM1MzUgMTEuNjQ2NEw4LjcwNzA4IDcuOTk5OThMMTIuMzUzNSA0LjM1MzUzTDExLjY0NjQgMy42NDY0Mkw3Ljk5OTk4IDcuMjkyODdMNC4zNTM1MyAzLjY0NjQyTDMuNjQ2NDIgNC4zNTM1M0w3LjI5Mjg3IDcuOTk5OThMMy42NDY0MiAxMS42NDY0TDQuMzUzNTMgMTIuMzUzNUw3Ljk5OTk4IDguNzA3MDhaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=");position:absolute;top:0;right:0;margin-right:5px}.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.readMore{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zIDcuNUMzIDQuNDYyNDMgNS40NjI0MyAyIDguNSAyQzExLjUzNzYgMiAxNCA0LjQ2MjQzIDE0IDcuNUMxNCAxMC41Mzc2IDExLjUzNzYgMTMgOC41IDEzQzUuNDYyNDMgMTMgMyAxMC41Mzc2IDMgNy41Wk0yIDcuNUMyIDMuOTEwMTUgNC45MTAxNSAxIDguNSAxQzEyLjA4OTkgMSAxNSAzLjkxMDE1IDE1IDcuNUMxNSAxMS4wODk5IDEyLjA4OTkgMTQgOC41IDE0QzQuOTEwMTUgMTQgMiAxMS4wODk5IDIgNy41Wk04IDVWNEg5VjVIOFpNOCAxMFY5TDggN1Y2SDlWN0w5IDlWMTBIOFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.header>.close:hover,.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.readMore:hover{opacity:1}.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.type-label{margin-left:.8em;-ms-flex:1;flex:1;text-align:right;overflow:hidden;text-overflow:ellipsis;opacity:.7;white-space:nowrap}.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.type-label>.monaco-tokenized-source{display:inline}.monaco-editor .suggest-widget.docs-below .monaco-list .monaco-list-row.focused>.contents>.main>.readMore,.monaco-editor .suggest-widget.docs-side .monaco-list .monaco-list-row.focused>.contents>.main>.readMore,.monaco-editor .suggest-widget.docs-side .monaco-list .monaco-list-row.focused>.contents>.main>.type-label,.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.readMore,.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.type-label{display:none}.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused>.contents>.main>.readMore,.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused>.contents>.main>.type-label{display:inline}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.deprecated{opacity:.66;text-decoration:unset}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.deprecated>.monaco-icon-label-description-container{text-decoration:line-through}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label:before{height:100%}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon{display:block;height:16px;width:16px;margin-left:2px;background-repeat:no-repeat;background-size:80%;background-position:50%}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon.hide,.monaco-editor .suggest-widget.no-icons .monaco-list .monaco-list-row .icon,.monaco-editor .suggest-widget.no-icons .monaco-list .monaco-list-row .monaco-icon-label.suggest-icon:before{display:none}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.suggest-icon:before{content:" ";background-repeat:no-repeat;background-position:50%;background-size:75%}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.constructor:before,.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.function:before,.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.method:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yIDQuODU3NDlMMi40ODU1IDRMNy40ODU1IDFIOC41MTQ1TDEzLjUxNDUgNEwxNCA0Ljg1NzQ5VjEwLjg1NzVMMTMuNTE0NSAxMS43MTVMOC41MTQ1IDE0LjcxNUg3LjQ4NTVMMi40ODU1IDExLjcxNUwyIDEwLjg1NzVWNC44NTc0OVpNNy41IDEzLjU1NzVMMyAxMC44NTc1VjUuNjk5NzVMNy41IDguMTU0M1YxMy41NTc1Wk04LjUgMTMuNTU3NUwxMyAxMC44NTc1VjUuNjk5NzVMOC41IDguMTU0M1YxMy41NTc1Wk04IDEuODU3NDlMMy4yNTkxMyA0LjcwMjAxTDggNy4yODc5NEwxMi43NDA5IDQuNzAyMDFMOCAxLjg1NzQ5WiIgZmlsbD0iIzY1MkQ5MCIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.field:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xIDYuMzk0NDNMMS41NTI3OSA1LjVMOC41NTI3OSAySDkuNDQ3MjFMMTQuNDQ3MiA0LjVMMTUgNS4zOTQ0M1Y5Ljg5NDQzTDE0LjQ0NzIgMTAuNzg4OUw3LjQ0NzIxIDE0LjI4ODlINi41NTI3OUwxLjU1Mjc5IDExLjc4ODlMMSAxMC44OTQ0VjYuMzk0NDNaTTYuNSAxMy4xNDQ0TDIgMTAuODk0NFY3LjE3MDk0TDYuNSA5LjIxNjM5VjEzLjE0NDRaTTcuNSAxMy4xNDQ0TDE0IDkuODk0NDNWNi4xNzk1NEw3LjUgOS4yMTI4N1YxMy4xNDQ0Wk05IDIuODk0NDNMMi4zMzcyOCA2LjIyNTc5TDYuOTk3MjUgOC4zNDM5NkwxMy42NzA2IDUuMjI5NzNMOSAyLjg5NDQzWiIgZmlsbD0iIzAwN0FDQyIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.event:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjQxMzU0IDEuNTU5OTZMOC4zMTE1MiAxSDExLjYwNTZMMTIuNDI0IDIuNTc0NjVMMTAuMjM1NiA2SDEyLjAxNzRMMTIuNzM2MyA3LjY5NTEyTDUuNjE5NDMgMTVMNC4wMTY3NSAxMy44MzdMNi4xMTk0MyAxMEg0Ljg5Nzk4TDQgOC41NTk5Nkw3LjQxMzU0IDEuNTU5OTZaTTcuNzgwMzMgOUw0LjkwMDU0IDE0LjMwNDlMMTIuMDE3NCA3SDguMzExNTJMMTEuNjA1NiAySDguMzExNTJMNC44OTc5OCA5SDcuNzgwMzNaIiBmaWxsPSIjRDY3RTAwIi8+Cjwvc3ZnPgo=")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.operator:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yLjg3Mjg5IDEuMTAwMjNDMy4yMDc2OCAxLjIzNTc5IDMuNDc1NDUgMS40OTggMy42MTgwMiAxLjgyOTg4QzMuNjkwMzIgMS45OTk1OSAzLjcyNjc1IDIuMTgyNDIgMy43MjUwMiAyLjM2Njg4QzMuNzI2MTcgMi41NDk5OSAzLjY4OTc1IDIuNzMxNCAzLjYxODAyIDIuODk5ODhDMy41MTI5OSAzLjE0NTY3IDMuMzM3ODIgMy4zNTUwMyAzLjExNDQyIDMuNTAxNzdDMi44OTEwMiAzLjY0ODUxIDIuNjI5MyAzLjcyNjEyIDIuMzYyMDIgMy43MjQ4OEMyLjE3OTI0IDMuNzI1OTIgMS45OTgxOCAzLjY4OTUxIDEuODMwMDIgMy42MTc4OEMxLjU4Mjk4IDMuNTE0MDYgMS4zNzIyNyAzLjMzOTMyIDEuMjI0NTMgMy4xMTU3NUMxLjA3NjggMi44OTIxOSAwLjk5ODY2NiAyLjYyOTg0IDEuMDAwMDIgMi4zNjE4OEMwLjk5OTEzIDIuMTc5MjEgMS4wMzUxOSAxLjk5ODI1IDEuMTA2MDIgMS44Mjk4OEMxLjI0MzM3IDEuNTAzMTQgMS41MDMyOCAxLjI0MzIzIDEuODMwMDIgMS4xMDU4OEMyLjE2MzMyIDAuOTY2NjkyIDIuNTM4MDkgMC45NjQ2NjEgMi44NzI4OSAxLjEwMDIzWk0yLjU3NTAyIDIuODY0ODhDMi43MDU0IDIuODA5MTMgMi44MDkyNyAyLjcwNTI2IDIuODY1MDIgMi41NzQ4OEMyLjg5MjkgMi41MDgzOCAyLjkwNzE4IDIuNDM2OTggMi45MDcwMiAyLjM2NDg4QzIuOTA4MTMgMi4yNjU0IDIuODgyMTUgMi4xNjc1IDIuODMxODUgMi4wODE2N0MyLjc4MTU2IDEuOTk1ODQgMi43MDg4NCAxLjkyNTMxIDIuNjIxNTEgMS44Nzc2N0MyLjUzNDE4IDEuODMwMDIgMi40MzU1MyAxLjgwNzA1IDIuMzM2MTQgMS44MTEyMUMyLjIzNjc0IDEuODE1MzcgMi4xNDAzNSAxLjg0NjUgMi4wNTczMSAxLjkwMTI4QzEuOTc0MjYgMS45NTYwNiAxLjkwNzcgMi4wMzI0MSAxLjg2NDc1IDIuMTIyMTVDMS44MjE4IDIuMjExODggMS44MDQwOSAyLjMxMTYxIDEuODEzNTIgMi40MTA2NUMxLjgyMjk0IDIuNTA5NjggMS44NTkxNSAyLjYwNDI4IDEuOTE4MjUgMi42ODQzQzEuOTc3MzYgMi43NjQzMyAyLjA1NzEzIDIuODI2NzUgMi4xNDkwMiAyLjg2NDg4QzIuMjg1NDkgMi45MjA4OSAyLjQzODU0IDIuOTIwODkgMi41NzUwMiAyLjg2NDg4Wk02LjQyOTk1IDEuMTA5NUwxLjEwOTY3IDYuNDI5NzdMMS43OTU1NyA3LjExNTY3TDcuMTE1ODQgMS43OTU0TDYuNDI5OTUgMS4xMDk1Wk0xMS41IDguOTk5OTlIMTIuNVYxMS41SDE1VjEyLjVIMTIuNVYxNUgxMS41VjEyLjVIOVYxMS41SDExLjVWOC45OTk5OVpNNS43Njc3NyA5LjUyNTA5TDYuNDc0ODcgMTAuMjMyMkw0LjcwNzExIDEyTDYuNDc0ODcgMTMuNzY3N0w1Ljc2Nzc3IDE0LjQ3NDhMNCAxMi43MDcxTDIuMjMyMjMgMTQuNDc0OEwxLjUyNTEzIDEzLjc2NzdMMy4yOTI4OSAxMkwxLjUyNTEzIDEwLjIzMjJMMi4yMzIyMyA5LjUyNTA5TDQgMTEuMjkyOUw1Ljc2Nzc3IDkuNTI1MDlaTTcuMTE4MDIgNS4zMjk4OEM3LjAxNDQyIDUuMDgyNjggNi44Mzk3MyA0Ljg3MTgzIDYuNjE2MTIgNC43MjQwNkM2LjM5MjUgNC41NzYyOSA2LjEzMDA0IDQuNDk4MjYgNS44NjIwMiA0LjQ5OTg4QzUuNjc5MzUgNC40OTg5OSA1LjQ5ODM5IDQuNTM1MDUgNS4zMzAwMiA0LjYwNTg4QzUuMDAzMjggNC43NDMyMyA0Ljc0MzM3IDUuMDAzMTQgNC42MDYwMiA1LjMyOTg4QzQuNTM1ODggNS40OTQ3OCA0LjQ5ODk3IDUuNjcxOTEgNC40OTc0MSA1Ljg1MTFDNC40OTU4NiA2LjAzMDMgNC41Mjk2NyA2LjIwODA0IDQuNTk2OTMgNi4zNzQxNEM0LjY2NDE5IDYuNTQwMjQgNC43NjM1NiA2LjY5MTQzIDQuODg5MzYgNi44MTkwNkM1LjAxNTE2IDYuOTQ2NjkgNS4xNjQ5IDcuMDQ4MjMgNS4zMzAwMiA3LjExNzg4QzUuNDk4NjcgNy4xODg0OCA1LjY3OTY4IDcuMjI0ODQgNS44NjI1MiA3LjIyNDg0QzYuMDQ1MzUgNy4yMjQ4NCA2LjIyNjM2IDcuMTg4NDggNi4zOTUwMiA3LjExNzg4QzYuNjQyMDEgNy4wMTM4OCA2Ljg1MjcgNi44MzkxMyA3LjAwMDU4IDYuNjE1NjNDNy4xNDg0NSA2LjM5MjEzIDcuMjI2ODkgNi4xMjk4NyA3LjIyNjAyIDUuODYxODhDNy4yMjY1NSA1LjY3OTA1IDcuMTg5OCA1LjQ5ODAzIDcuMTE4MDIgNS4zMjk4OFpNNi4zNjUwMiA2LjA3NDg4QzYuMzM3NjYgNi4xMzkzNyA2LjI5ODI5IDYuMTk4MDggNi4yNDkwMiA2LjI0Nzg4QzYuMTk5MDggNi4yOTcyNCA2LjE0MDQyIDYuMzM2OTEgNi4wNzYwMiA2LjM2NDg4QzYuMDA4NTQgNi4zOTI5NyA1LjkzNjExIDYuNDA3MjUgNS44NjMwMiA2LjQwNjg4QzUuNzg5OTEgNi40MDc0NCA1LjcxNzQ0IDYuMzkzMTUgNS42NTAwMiA2LjM2NDg4QzUuNTg1NDEgNi4zMzcyOSA1LjUyNjY4IDYuMjk3NTcgNS40NzcwMiA2LjI0Nzg4QzUuNDI2OTEgNi4xOTg1NiA1LjM4NzEzIDYuMTM5NzUgNS4zNjAwMiA2LjA3NDg4QzUuMzA0MDEgNS45Mzg0IDUuMzA0MDEgNS43ODUzNiA1LjM2MDAyIDUuNjQ4ODhDNS40MTUzNiA1LjUxODQ2IDUuNTE5NDEgNS40MTQ3NyA1LjY1MDAyIDUuMzU5ODhDNS43MTczNyA1LjMzMTI2IDUuNzg5ODQgNS4zMTY2MyA1Ljg2MzAyIDUuMzE2ODhDNS45MzYxOCA1LjMxNjg1IDYuMDA4NiA1LjMzMTQ3IDYuMDc2MDIgNS4zNTk4OEM2LjE0MDM3IDUuMzg3NDkgNi4xOTkwNCA1LjQyNjgyIDYuMjQ5MDIgNS40NzU4OEM2LjI5Nzg2IDUuNTI2MDMgNi4zMzcxNiA1LjU4NDY1IDYuMzY1MDIgNS42NDg4OEM2LjM5MzQgNS43MTYzIDYuNDA4MDIgNS43ODg3MiA2LjQwODAyIDUuODYxODhDNi40MDgwMiA1LjkzNTAzIDYuMzkzNCA2LjAwNzQ1IDYuMzY1MDIgNi4wNzQ4OFpNMTQgM0gxMFY0SDE0VjNaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.variable:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xLjUgNEwxIDQuNVYxMi41TDEuNSAxM0g0VjEySDJWNUg0VjRIMS41Wk0xNC41IDEzTDE1IDEyLjVMMTUgNC41TDE0LjUgNEgxMlY1TDE0IDVMMTQgMTJIMTJWMTNIMTQuNVpNOC43OTY5MyA1TDQuMjk2OTMgN0w0IDcuNDU2OTFWOS45NTY5MUw0LjI0Mjc1IDEwLjM4NTdMNi43NDI3NSAxMS44ODU3TDcuMjAzMDcgMTEuOTEzOEwxMS43MDMxIDkuOTEzODFMMTIgOS40NTY5MVY2Ljk1NjkxTDExLjc1NzIgNi41MjgxNkw5LjI1NzI1IDUuMDI4MTZMOC43OTY5MyA1Wk01IDguMzRWOS42NzM4MUw2LjUgMTAuNTczOFY5LjI0TDUgOC4zNFpNNy41IDkuMjgxODRWMTAuNjg3NUwxMSA5LjEzMTk3VjcuNzI2MjlMNy41IDkuMjgxODRaTTEwLjQxNzggNi44OTA3MUw4Ljk2NTU5IDYuMDE5MzZMNS41ODIxNiA3LjUyMzExTDcuMDM0NDEgOC4zOTQ0NUwxMC40MTc4IDYuODkwNzFaIiBmaWxsPSIjMDA3QUNDIi8+Cjwvc3ZnPgo=")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.class:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjM1MzU2IDYuNjQ2NDJMMi4wNjA2NiA1LjM1MzUzTDUuMzUzNTYgMi4wNjA2NUw2LjY0NjQ1IDMuMzUzNTRMMy4zNTM1NiA2LjY0NjQyWk01IDFMMSA0Ljk5OTk4VjUuNzA3MDhMMyA3LjcwNzA3SDMuNzA3MTFMNC44NTM1NSA2LjU2MDYzVjEyLjM1MzVMNS4zNTM1NSAxMi44NTM1SDEwLjAwOTdWMTMuMzc0MUwxMS4zNDMgMTQuNzA3NEgxMi4wNTAxTDE0LjcxNjggMTIuMDQwN1YxMS4zMzM2TDEzLjM4MzUgMTAuMDAwM0gxMi42NzYzTDEwLjgyMzEgMTEuODUzNUg1Ljg1MzU1VjcuODkzNTVIMTAuMDA5N1Y4LjM3NDAxTDExLjM0MyA5LjcwNzM0SDEyLjA1MDFMMTQuNzE2OCA3LjA0MDY4VjYuMzMzNTdMMTMuMzgzNSA1LjAwMDI0SDEyLjY3NjNMMTAuODYzIDYuODEzNTZINS44NTM1NVY1LjU2MDY0TDcuNzA3MTEgMy43MDcwOVYyLjk5OTk5TDUuNzA3MTEgMUg1Wk0xMS4wNzAzIDguMDIwNDZMMTEuNjk2NiA4LjY0NjY4TDEzLjY1NjEgNi42ODcxM0wxMy4wMjk5IDYuMDYwOUwxMS4wNzAzIDguMDIwNDZaTTExLjA3MDMgMTMuMDIwNUwxMS42OTY2IDEzLjY0NjdMMTMuNjU2MSAxMS42ODcyTDEzLjAyOTkgMTEuMDYxTDExLjA3MDMgMTMuMDIwNVoiIGZpbGw9IiNENjdFMDAiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.interface:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS41IDVDMTAuMTE5MyA1IDkgNi4xMTkyOSA5IDcuNUM5IDguODgwNzEgMTAuMTE5MyAxMCAxMS41IDEwQzEyLjg4MDcgMTAgMTQgOC44ODA3MSAxNCA3LjVDMTQgNi4xMTkyOSAxMi44ODA3IDUgMTEuNSA1Wk04LjAzNTQ0IDhDOC4yNzgwNiA5LjY5NjE1IDkuNzM2NzYgMTEgMTEuNSAxMUMxMy40MzMgMTEgMTUgOS40MzMgMTUgNy41QzE1IDUuNTY3IDEzLjQzMyA0IDExLjUgNEM5LjczNjc2IDQgOC4yNzgwNiA1LjMwMzg1IDguMDM1NDQgN0g0LjkzNjk5QzQuNzE0OTcgNi4xMzczOSAzLjkzMTkyIDUuNSAzIDUuNUMxLjg5NTQzIDUuNSAxIDYuMzk1NDMgMSA3LjVDMSA4LjYwNDU3IDEuODk1NDMgOS41IDMgOS41QzMuOTMxOTIgOS41IDQuNzE0OTcgOC44NjI2MSA0LjkzNjk5IDhIOC4wMzU0NFoiIGZpbGw9IiMwMDdBQ0MiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.struct:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yIDJMMSAzVjZMMiA3SDE0TDE1IDZWM0wxNCAySDJaTTIgM0gzSDEzSDE0VjRWNVY2SDEzSDNIMlY1VjRWM1pNMSAxMEwyIDlINUw2IDEwVjEzTDUgMTRIMkwxIDEzVjEwWk0zIDEwSDJWMTFWMTJWMTNIM0g0SDVWMTJWMTFWMTBINEgzWk0xMCAxMEwxMSA5SDE0TDE1IDEwVjEzTDE0IDE0SDExTDEwIDEzVjEwWk0xMiAxMEgxMVYxMVYxMlYxM0gxMkgxM0gxNFYxMlYxMVYxMEgxM0gxMloiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.type-parameter:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMSA2SDEwVjUuNUMxMCA1LjIyMzg2IDkuNzc2MTYgNSA5LjUwMDAxIDVIOC40NzkwMlYxMC41QzguNDc5MDIgMTAuNzc2MSA4LjcwMjg4IDExIDguOTc5MDIgMTFIOS40NzkwMlYxMkg2LjQ3OTAyVjExSDYuOTc5MDJDNy4yNTUxNiAxMSA3LjQ3OTAyIDEwLjc3NjEgNy40NzkwMiAxMC41VjVINi41MDAwMUM2LjIyMzg3IDUgNi4wMDAwMSA1LjIyMzg2IDYuMDAwMDEgNS41VjZINS4wMDAwMVY0SDExVjZaTTEzLjkxNDIgOC4wNDgxTDEyLjQ1MTkgNi41ODU4MUwxMy4xNTkgNS44Nzg3MUwxNC45NzQ5IDcuNjk0NTRWOC40MDE2NUwxMy4yMDcxIDEwLjE2OTRMMTIuNSA5LjQ2MjMxTDEzLjkxNDIgOC4wNDgxWk0zLjU0ODEgOS40NjIzTDIuMDg1ODEgOC4wMDAwMkwzLjUwMDAyIDYuNTg1ODFMMi43OTI5MSA1Ljg3ODdMMS4wMjUxNSA3LjY0NjQ3VjguMzUzNTdMMi44NDEgMTAuMTY5NEwzLjU0ODEgOS40NjIzWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.module:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02IDIuOTgzNjFWMi45NzE4NFYySDUuOTEwODNDNS41OTc0MyAyIDUuMjk0MDcgMi4wNjE2MSA1LjAwMTI4IDIuMTg0NzNDNC43MDgxOCAyLjMwNzk4IDQuNDQ5NDIgMi40ODQ3NCA0LjIyNTc4IDIuNzE0OThDNC4wMDMxMSAyLjk0NDIyIDMuODM3OTIgMy4xOTQ5OCAzLjczMjgyIDMuNDY3NjZMMy43MzIzMyAzLjQ2ODk4QzMuNjMzODIgMy43MzUyIDMuNTY4MTQgNC4wMTIwMSAzLjUzNTMzIDQuMjk5MTdMMy41MzUxOSA0LjMwMDUzQzMuNTA2NzggNC41ODA1IDMuNDk4NyA0Ljg2ODQ0IDMuNTEwODQgNS4xNjQyOEMzLjUyMjcyIDUuNDUzNzkgMy41Mjg2NiA1Ljc0MzI5IDMuNTI4NjYgNi4wMzI3OUMzLjUyODY2IDYuMjM1NTYgMy40ODk3NCA2LjQyNTk0IDMuNDEyIDYuNjA1MDdMMy40MTE2IDYuNjA2MDFDMy4zMzY4NyA2Ljc4Mjk2IDMuMjM0MjMgNi45Mzg2NiAzLjEwMzE3IDcuMDczNTlDMi45NzY0NCA3LjIwNDA1IDIuODI0NjYgNy4zMTA1NSAyLjY0NjcyIDcuMzkyNUMyLjQ3MDYgNy40Njk1NCAyLjI4NDk3IDcuNTA4MiAyLjA4OTE3IDcuNTA4MkgyVjcuNlY4LjRWOC40OTE4SDIuMDg5MTdDMi4yODQ2NSA4LjQ5MTggMi40NzAwMSA4LjUzMjM4IDIuNjQ2MDEgOC42MTMzNEwyLjY0NzQyIDguNjEzOTZDMi44MjQ1NyA4LjY5MTU3IDIuOTc1NzcgOC43OTc2MiAzLjEwMjIxIDguOTMxNjFMMy4xMDQxMiA4LjkzMzUyQzMuMjM0MjggOS4wNjM3IDMuMzM2NTkgOS4yMTg3MSAzLjQxMTI5IDkuMzk5NDJMMy40MTIwMSA5LjQwMTA4QzMuNDg5ODYgOS41ODA0NyAzLjUyODY2IDkuNzY4ODMgMy41Mjg2NiA5Ljk2NzIxQzMuNTI4NjYgMTAuMjU2NyAzLjUyMjcyIDEwLjU0NjIgMy41MTA4NCAxMC44MzU3QzMuNDk4NyAxMS4xMzE2IDMuNTA2NzcgMTEuNDIxNSAzLjUzNTE2IDExLjcwNTVMMy41MzUzNSAxMS43MDcyQzMuNTY4MTkgMTEuOTkwMyAzLjYzMzg3IDEyLjI2NSAzLjczMjMyIDEyLjUzMUwzLjczMjgzIDEyLjUzMjNDMy44Mzc5MyAxMi44MDUgNC4wMDMxMSAxMy4wNTU4IDQuMjI1NzggMTMuMjg1QzQuNDQ5NDIgMTMuNTE1MyA0LjcwODE4IDEzLjY5MiA1LjAwMTI4IDEzLjgxNTNDNS4yOTQwNyAxMy45Mzg0IDUuNTk3NDMgMTQgNS45MTA4MyAxNEg2VjEzLjJWMTMuMDE2NEg1LjkxMDgzQzUuNzEwOTUgMTMuMDE2NCA1LjUyMzQ2IDEyLjk3NzcgNS4zNDc2MyAxMi45MDA4QzUuMTczOTYgMTIuODE5MSA1LjAyMTk0IDEyLjcxMjYgNC44OTA4NiAxMi41ODE4QzQuNzYzODYgMTIuNDQ2OSA0LjY2MTA0IDEyLjI5MTEgNC41ODIyMyAxMi4xMTM3QzQuNTA4MzggMTEuOTM0NiA0LjQ3MTM0IDExLjc0NCA0LjQ3MTM0IDExLjU0MUM0LjQ3MTM0IDExLjMxMjcgNC40NzUzIDExLjA4ODUgNC40ODMyMSAxMC44Njg2QzQuNDkxMjUgMTAuNjQxMSA0LjQ5MTI3IDEwLjQxOTUgNC40ODMyNCAxMC4yMDM5QzQuNDc5MTQgOS45ODI0NiA0LjQ2MDg0IDkuNzY4ODMgNC40MjgyMyA5LjU2MzEyQzQuMzk1MTMgOS4zNTAyNCA0LjMzOTIxIDkuMTQ3NTcgNC4yNjAzOSA4Ljk1NTM2QzQuMTgwOTEgOC43NjE1NyA0LjA3MjU4IDguNTc3NDYgMy45MzYxNiA4LjQwMjk4QzMuODIzNDUgOC4yNTg4MSAzLjY4NTM4IDguMTI0NjIgMy41MjI4MyA4QzMuNjg1MzggNy44NzUzOCAzLjgyMzQ1IDcuNzQxMTkgMy45MzYxNiA3LjU5NzAyQzQuMDcyNTggNy40MjI1NCA0LjE4MDkxIDcuMjM4NDMgNC4yNjAzOSA3LjA0NDY0QzQuMzM5MTMgNi44NTI2MyA0LjM5NTEzIDYuNjUxNzUgNC40MjgyNiA2LjQ0Mjg1QzQuNDYwODIgNi4yMzMzIDQuNDc5MTQgNi4wMTk3MyA0LjQ4MzI0IDUuODAyMTlDNC40OTEyNyA1LjU4MjYyIDQuNDkxMjUgNS4zNjEwNSA0LjQ4MzIxIDUuMTM3NDlDNC40NzUzIDQuOTEzNCA0LjQ3MTM0IDQuNjg3MjUgNC40NzEzNCA0LjQ1OTAyQzQuNDcxMzQgNC4yNjAxOSA0LjUwODMzIDQuMDcxNTIgNC41ODIzOCAzLjg5MjA1QzQuNjYxMzUgMy43MTAzNCA0Ljc2NDIxIDMuNTU0NzUgNC44OTA4NiAzLjQyNDM3QzUuMDIxOTMgMy4yODk0MiA1LjE3NDYxIDMuMTgyNzUgNS4zNDgwMiAzLjEwNTEzQzUuNTIzOCAzLjAyNDI3IDUuNzExMTMgMi45ODM2MSA1LjkxMDgzIDIuOTgzNjFINlpNMTAgMTMuMDE2NFYxMy4wMjgyVjE0SDEwLjA4OTJDMTAuNDAyNiAxNCAxMC43MDU5IDEzLjkzODQgMTAuOTk4NyAxMy44MTUzQzExLjI5MTggMTMuNjkyIDExLjU1MDYgMTMuNTE1MyAxMS43NzQyIDEzLjI4NUMxMS45OTY5IDEzLjA1NTggMTIuMTYyMSAxMi44MDUgMTIuMjY3MiAxMi41MzIzTDEyLjI2NzcgMTIuNTMxQzEyLjM2NjIgMTIuMjY0OCAxMi40MzE5IDExLjk4OCAxMi40NjQ3IDExLjcwMDhMMTIuNDY0OCAxMS42OTk1QzEyLjQ5MzIgMTEuNDE5NSAxMi41MDEzIDExLjEzMTYgMTIuNDg5MiAxMC44MzU3QzEyLjQ3NzMgMTAuNTQ2MiAxMi40NzEzIDEwLjI1NjcgMTIuNDcxMyA5Ljk2NzIxQzEyLjQ3MTMgOS43NjQ0NCAxMi41MTAzIDkuNTc0MDYgMTIuNTg4IDkuMzk0OTNMMTIuNTg4NCA5LjM5Mzk5QzEyLjY2MzEgOS4yMTcwNCAxMi43NjU4IDkuMDYxMzQgMTIuODk2OCA4LjkyNjQyQzEzLjAyMzYgOC43OTU5NSAxMy4xNzUzIDguNjg5NDUgMTMuMzUzMyA4LjYwNzVDMTMuNTI5NCA4LjUzMDQ2IDEzLjcxNSA4LjQ5MTggMTMuOTEwOCA4LjQ5MThIMTRWOC40VjcuNlY3LjUwODJIMTMuOTEwOEMxMy43MTUzIDcuNTA4MiAxMy41MyA3LjQ2NzYyIDEzLjM1NCA3LjM4NjY2TDEzLjM1MjYgNy4zODYwNEMxMy4xNzU0IDcuMzA4NDQgMTMuMDI0MiA3LjIwMjM4IDEyLjg5NzggNy4wNjgzOUwxMi44OTU5IDcuMDY2NDhDMTIuNzY1NyA2LjkzNjMgMTIuNjYzNCA2Ljc4MTI5IDEyLjU4ODcgNi42MDA1OEwxMi41ODggNi41OTg5MkMxMi41MTAxIDYuNDE5NTMgMTIuNDcxMyA2LjIzMTE3IDEyLjQ3MTMgNi4wMzI3OUMxMi40NzEzIDUuNzQzMjkgMTIuNDc3MyA1LjQ1Mzc5IDEyLjQ4OTIgNS4xNjQyOEMxMi41MDEzIDQuODY4NDIgMTIuNDkzMiA0LjU3ODQ4IDEyLjQ2NDggNC4yOTQ1NEwxMi40NjQ2IDQuMjkyODVDMTIuNDMxOCA0LjAwOTcxIDEyLjM2NjEgMy43MzUwMiAxMi4yNjc3IDMuNDY4OTdMMTIuMjY3MiAzLjQ2NzY2QzEyLjE2MjEgMy4xOTQ5OSAxMS45OTY5IDIuOTQ0MjIgMTEuNzc0MiAyLjcxNDk4QzExLjU1MDYgMi40ODQ3NCAxMS4yOTE4IDIuMzA3OTggMTAuOTk4NyAyLjE4NDczQzEwLjcwNTkgMi4wNjE2MSAxMC40MDI2IDIgMTAuMDg5MiAySDEwVjIuOFYyLjk4MzYxSDEwLjA4OTJDMTAuMjg5MSAyLjk4MzYxIDEwLjQ3NjUgMy4wMjIzIDEwLjY1MjQgMy4wOTkxN0MxMC44MjYgMy4xODA5MiAxMC45NzgxIDMuMjg3MzYgMTEuMTA5MSAzLjQxODIzQzExLjIzNjEgMy41NTMwNSAxMS4zMzkgMy43MDg4OSAxMS40MTc4IDMuODg2MjhDMTEuNDkxNiA0LjA2NTQgMTEuNTI4NyA0LjI1NTk2IDExLjUyODcgNC40NTkwMkMxMS41Mjg3IDQuNjg3MjcgMTEuNTI0NyA0LjkxMTQ1IDExLjUxNjggNS4xMzE0MkMxMS41MDg4IDUuMzU4OTQgMTEuNTA4NyA1LjU4MDQ5IDExLjUxNjggNS43OTYwNUMxMS41MjA5IDYuMDE3NTQgMTEuNTM5MiA2LjIzMTE3IDExLjU3MTggNi40MzY4OEMxMS42MDQ5IDYuNjQ5NzYgMTEuNjYwOCA2Ljg1MjQzIDExLjczOTYgNy4wNDQ2NEMxMS44MTkxIDcuMjM4NDMgMTEuOTI3NCA3LjQyMjU0IDEyLjA2MzggNy41OTcwMkMxMi4xNzY1IDcuNzQxMTkgMTIuMzE0NiA3Ljg3NTM4IDEyLjQ3NzIgOEMxMi4zMTQ2IDguMTI0NjIgMTIuMTc2NSA4LjI1ODgxIDEyLjA2MzggOC40MDI5OEMxMS45Mjc0IDguNTc3NDYgMTEuODE5MSA4Ljc2MTU3IDExLjczOTYgOC45NTUzNkMxMS42NjA5IDkuMTQ3MzcgMTEuNjA0OSA5LjM0ODI1IDExLjU3MTcgOS41NTcxNUMxMS41MzkyIDkuNzY2NyAxMS41MjA5IDkuOTgwMjcgMTEuNTE2OCAxMC4xOTc4QzExLjUwODcgMTAuNDE3NCAxMS41MDg3IDEwLjYzODkgMTEuNTE2OCAxMC44NjI1QzExLjUyNDcgMTEuMDg2NiAxMS41Mjg3IDExLjMxMjggMTEuNTI4NyAxMS41NDFDMTEuNTI4NyAxMS43Mzk4IDExLjQ5MTcgMTEuOTI4NSAxMS40MTc2IDEyLjEwNzlDMTEuMzM4NiAxMi4yODk3IDExLjIzNTggMTIuNDQ1MiAxMS4xMDkxIDEyLjU3NTZDMTAuOTc4MSAxMi43MTA2IDEwLjgyNTQgMTIuODE3MyAxMC42NTIgMTIuODk0OUMxMC40NzYyIDEyLjk3NTcgMTAuMjg4OSAxMy4wMTY0IDEwLjA4OTIgMTMuMDE2NEgxMFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.property:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTIuODA3MjMgMTQuOTc1NEMyLjU3MTE5IDE0Ljk3MjEgMi4zMzgyNiAxNC45MjExIDIuMTIyNDcgMTQuODI1NEMxLjkwNjY3IDE0LjcyOTcgMS43MTI0OCAxNC41OTEzIDEuNTUxNTggMTQuNDE4NkMxLjIzODUgMTQuMTMzNCAxLjA0NDMzIDEzLjc0MDggMS4wMDc3NSAxMy4zMTg5QzAuOTY2MjI1IDEyLjg4MjggMS4wOTI2OSAxMi40NDczIDEuMzYxMzMgMTIuMTAxM0MyLjU2Nzc5IDEwLjgyODkgNC45NDczIDguNDQ5NCA2LjY3ODExIDYuNzU0NzlDNi4zMDk4MyA1Ljc1ODg3IDYuMzI3MDQgNC42NjEyNyA2LjcyNjM3IDMuNjc3MzlDNy4wNTQ3NCAyLjg1ODc2IDcuNjM4NjkgMi4xNjgwNSA4LjM5MTI5IDEuNzA4MDdDOC45ODE3IDEuMzE3MDYgOS42NjAzMSAxLjA3OTQ0IDEwLjM2NTcgMS4wMTY3M0MxMS4wNzExIDAuOTU0MDIyIDExLjc4MDkgMS4wNjgxOSAxMi40MzExIDEuMzQ4OTJMMTMuMDQ4MiAxLjYxNjJMMTAuMTgyNCA0LjU2NzM4TDExLjQzNzEgNS44MjU4MkwxNC4zODA5IDIuOTQ4ODdMMTQuNjQ4MiAzLjU2Nzg4QzE0Ljg3MzUgNC4wODk3NiAxNC45OTMgNC42NTExOSAxNC45OTk3IDUuMjE5NjFDMTUuMDA2NCA1Ljc4ODAyIDE0LjkwMDIgNi4zNTIxMSAxNC42ODcyIDYuODc5MTVDMTQuNDc2IDcuNDAwMjkgMTQuMTYyMyA3Ljg3MzY4IDEzLjc2NDcgOC4yNzEyMkMxMy41Mzk0IDguNDkxNjkgMTMuMjkwNCA4LjY4NjUzIDEzLjAyMjIgOC44NTIxOEMxMi40NjczIDkuMjIyNzUgMTEuODMyNCA5LjQ1NjM2IDExLjE2OTcgOS41MzM4QzEwLjUwNjkgOS42MTEyNCA5LjgzNTIxIDkuNTMwMyA5LjIwOTgyIDkuMjk3NjRDOC4xMTE5NCAxMC40MTEzIDUuMzcxNDIgMTMuMTcwNCAzLjg5MTE5IDE0LjU1MjJDMy41OTQyNiAxNC44MjE5IDMuMjA4MzIgMTQuOTcyNiAyLjgwNzIzIDE0Ljk3NTRaTTEwLjc0NDggMS45MjgwMkMxMC4wODcgMS45MjYzNyA5LjQ0MzU5IDIuMTIwMTggOC44OTYxNCAyLjQ4NDg1QzguNjgyNjUgMi42MTUyIDguNDg0MzcgMi43Njg5NyA4LjMwNDk4IDIuOTQzM0M3LjgyNzg5IDMuNDI0MjMgNy41MDkyNiA0LjAzOTUzIDcuMzkxODIgNC43MDY2OUM3LjI3NDM3IDUuMzczODUgNy4zNjM3NCA2LjA2MDk4IDcuNjQ3OTIgNi42NzU5MUw3Ljc4MzQyIDYuOTcyODhMNy41NTA0OCA3LjIwMDI1QzUuODEyMjQgOC44OTY3MiAzLjI4MTQ2IDExLjQyMDEgMi4wNjQ3OSAxMi43MDQ1QzEuOTU2NDYgMTIuODY1OCAxLjkxMDEyIDEzLjA2MDggMS45MzQzNSAxMy4yNTM1QzEuOTU4NTcgMTMuNDQ2MyAyLjA1MTcxIDEzLjYyMzggMi4xOTY1NyAxMy43NTMyQzIuMjgwMDUgMTMuODQ2MiAyLjM4MTc3IDEzLjkyMTEgMi40OTU0MSAxMy45NzMxQzIuNTk1NTcgMTQuMDE4NCAyLjcwMzgzIDE0LjA0MyAyLjgxMzczIDE0LjA0NTVDMi45ODA2NCAxNC4wNDEzIDMuMTQwNDQgMTMuOTc3IDMuMjYzODMgMTMuODY0NkM0LjgzNjg3IDEyLjM5NjQgNy44NzYyMiA5LjMyNjQxIDguNzY4MDcgOC40MjQzNUw4Ljk5NzMgOC4xOTMyNkw5LjI5MjQyIDguMzI3ODNDOS44MDYxOCA4LjU2NzMyIDEwLjM3MzEgOC42Njk4NSAxMC45MzgyIDguNjI1NDVDMTEuNTAzMyA4LjU4MTA2IDEyLjA0NzMgOC4zOTEyNSAxMi41MTc0IDguMDc0NDdDMTIuNzMxMyA3Ljk0MjYgMTIuOTI5NiA3Ljc4Njk0IDEzLjEwODUgNy42MTA0NUMxMy40MTgzIDcuMzAxNTMgMTMuNjYzMSA2LjkzMzc0IDEzLjgyODYgNi41Mjg3NEMxMy45OTQgNi4xMjM3NSAxNC4wNzY3IDUuNjg5NzQgMTQuMDcxOSA1LjI1MjI4QzE0LjA3MTkgNS4wMzY2MiAxNC4wNTA1IDQuODIxNDggMTQuMDA3OCA0LjYxMDA3TDExLjQzMDYgNy4xMjUwOEw4Ljg3OTQ0IDQuNTc3NTlMMTEuMzk0NCAxLjk4ODM0QzExLjE4MDQgMS45NDY3NCAxMC45NjI4IDEuOTI2NTMgMTAuNzQ0OCAxLjkyODAyWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.unit:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDFMMyAyVjE0TDQgMTVIMTJMMTMgMTRWMkwxMiAxSDRaTTQgM1YySDEyVjE0SDRWMTNINlYxMkg0VjEwSDhWOUg0VjdINlY2SDRWNEg4VjNINFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.constant:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDZIMTJWN0g0VjZaTTEyIDlINFYxMEgxMlY5WiIgZmlsbD0iIzQyNDI0MiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEgNEwyIDNIMTRMMTUgNFYxMkwxNCAxM0gyTDEgMTJWNFpNMiA0VjEySDE0VjRIMloiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.enum:before,.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.value:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04IDJMNyAzVjZIOFYzSDE0VjhIMTBWOUgxNEwxNSA4VjNMMTQgMkg4Wk05IDhMOCA3SDdIMkwxIDhWMTNMMiAxNEg4TDkgMTNWOVY4Wk04IDlWOEg3SDJWMTNIOFY5Wk05IDYuNTg1NzlMOS40MTQyMSA3SDEzVjZIOVY2LjU4NTc5Wk0xMyA0SDlWNUgxM1Y0Wk03IDlIM1YxMEg3VjlaTTMgMTFIN1YxMkgzVjExWiIgZmlsbD0iI0Q2N0UwMCIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.enum-member:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDNMOCAySDE0TDE1IDNWOEwxNCA5SDEwVjhIMTRWM0g4VjZIN1YzWk04IDdMOSA4VjlWMTNMOCAxNEgyTDEgMTNWOEwyIDdIN0g4Wk04IDhWOVYxM0gyVjhIN0g4Wk05LjQxNDIxIDdMOSA2LjU4NTc5VjZIMTNWN0g5LjQxNDIxWk05IDRIMTNWNUg5VjRaTTcgMTBIM1YxMUg3VjEwWiIgZmlsbD0iIzAwN0FDQyIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.keyword:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE1IDRIMTBWM0gxNVY0Wk0xNCA3SDEyVjhIMTRWN1pNMTAgN0gxVjhIMTBWN1pNMTIgMTNIMVYxNEgxMlYxM1pNNyAxMEgxVjExSDdWMTBaTTE1IDEwSDEwVjExSDE1VjEwWk04IDJWNUgxVjJIOFpNNyAzSDJWNEg3VjNaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.text:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjIyMjg5IDEwLjkzM0M3LjU0ODYzIDExLjEyNTQgNy45MjE2MyAxMS4yMjMxIDguMjk5ODkgMTEuMjE1QzguNjM3NzcgMTEuMjIxOCA4Ljk3MjU0IDExLjE0OTIgOS4yNzcyMSAxMS4wMDNDOS41ODE4OCAxMC44NTY3IDkuODQ3OTIgMTAuNjQwOSAxMC4wNTM5IDEwLjM3M0MxMC41MDkxIDkuNzY1MTkgMTAuNzQwMiA5LjAxODY3IDEwLjcwNzkgOC4yNTk5OEMxMC43NDEyIDcuNTg2MjIgMTAuNTM3NCA2LjkyMjEgMTAuMTMxOSA2LjM4Mjk4QzkuOTM1NzUgNi4xNDE2MSA5LjY4NTc3IDUuOTQ5NTcgOS40MDIgNS44MjIyOEM5LjExODI0IDUuNjk0OTggOC44MDg1OCA1LjYzNTk3IDguNDk3ODkgNS42NDk5N0M4LjA3NTIyIDUuNjQ2OTkgNy42NTk5NCA1Ljc2MDg1IDcuMjk3ODkgNS45Nzg5OEM3LjE4MzA0IDYuMDQ4MDcgNy4wNzQ5IDYuMTI3NzUgNi45NzQ4OSA2LjIxNjk4VjMuNDc0OThINS45ODM4OVYxMS4xSDYuOTc4ODlWMTAuNzU2QzcuMDU1MTYgMTAuODIxNyA3LjEzNjc3IDEwLjg4MDkgNy4yMjI4OSAxMC45MzNaTTcuODQ5ODEgNi43MDAwNkM4LjAzNTk4IDYuNjIxMDUgOC4yMzgwNyA2LjU4Njc3IDguNDM5ODkgNi41OTk5OEM4LjYxMjU3IDYuNTk0NTIgOC43ODQwNCA2LjYzMDU0IDguOTM5OTQgNi43MDUwMUM5LjA5NTgzIDYuNzc5NDggOS4yMzE2MSA2Ljg5MDIzIDkuMzM1ODkgNy4wMjc5OEM5LjU5MjUzIDcuMzkwNTMgOS43MTg0IDcuODI5NTEgOS42OTI4OSA4LjI3Mjk3QzkuNzE5NzIgOC43OTc0OCA5LjU3OTY5IDkuMzE3MDEgOS4yOTI4OSA5Ljc1Njk4QzkuMTg4MjIgOS45MTUyNyA5LjA0NTQ2IDEwLjA0NDcgOC44Nzc3MyAxMC4xMzM1QzguNzA5OTkgMTAuMjIyMyA4LjUyMjY0IDEwLjI2NzUgOC4zMzI4OSAxMC4yNjVDOC4xNDkzNCAxMC4yNzMyIDcuOTY2MyAxMC4yNCA3Ljc5NzM0IDEwLjE2NzhDNy42MjgzOCAxMC4wOTU2IDcuNDc3ODQgOS45ODYyOCA3LjM1Njg5IDkuODQ3OTdDNy4xMDE1MiA5LjU1OTU3IDYuOTY1MDEgOS4xODUwNiA2Ljk3NDg5IDguNzk5OThWOC4xOTk5OEM2Ljk2Mjk5IDcuNzgzMzIgNy4xMDI2MyA3LjM3NjUgNy4zNjc4OSA3LjA1NDk4QzcuNDk4NTggNi45MDA2NCA3LjY2MzY0IDYuNzc5MDggNy44NDk4MSA2LjcwMDA2Wk0zLjI4OTAyIDUuNjc0OTlDMi45NzAxMSA1LjY3OTMzIDIuNjUzODggNS43MzQgMi4zNTIwMiA1LjgzNjk5QzIuMDY0MTcgNS45MjI5MyAxLjc5MzQ3IDYuMDU4MjggMS41NTIwMiA2LjIzNjk5TDEuNDUyMDIgNi4zMTM5OVY3LjUxMzk5TDEuODc1MDIgNy4xNTQ5OUMyLjI0NTc5IDYuODA0NzggMi43MzEzMyA2LjYwMTQ2IDMuMjQxMDIgNi41ODI5OUMzLjM2NTkzIDYuNTcxNjQgMy40OTE3IDYuNTkxNDcgMy42MDcwNiA2LjY0MDY4QzMuNzIyNDMgNi42ODk5IDMuODIzNzcgNi43NjY5NyAzLjkwMjAyIDYuODY0OTlDNC4wNTIyIDcuMDk3MSA0LjEzMjM5IDcuMzY3NTQgNC4xMzMwMiA3LjY0Mzk5TDIuOTAwMDIgNy44MjQ5OUMyLjM5NDM1IDcuODc3ODEgMS45MTUyNSA4LjA3NzcyIDEuNTIyMDIgOC4zOTk5OUMxLjM2Njk3IDguNTUxODEgMS4yNDMzOSA4LjczMjcxIDEuMTU4MzUgOC45MzIzNUMxLjA3MzMxIDkuMTMxOTkgMS4wMjg0OCA5LjM0NjQ0IDEuMDI2NDQgOS41NjM0M0MxLjAyNDQgOS43ODA0MiAxLjA2NTE3IDkuOTk1NjggMS4xNDY0NCAxMC4xOTY5QzEuMjI3NyAxMC4zOTgxIDEuMzQ3ODYgMTAuNTgxMyAxLjUwMDAyIDEwLjczNkMxLjY2ODcgMTAuODkwNCAxLjg2NjIyIDExLjAxIDIuMDgxMjUgMTEuMDg3OUMyLjI5NjI3IDExLjE2NTkgMi41MjQ1NiAxMS4yMDA1IDIuNzUzMDIgMTEuMTlDMy4xNDcgMTEuMTkzMSAzLjUzMjc4IDExLjA3NzQgMy44NjAwMiAxMC44NThDMy45NjE1MyAxMC43ODk3IDQuMDU3MiAxMC43MTMxIDQuMTQ2MDIgMTAuNjI5VjExLjA3M0g1LjA4NzAyVjcuNzE0OTlDNS4xMjEzNyA3LjE3NDIyIDQuOTU0MyA2LjYzOTg4IDQuNjE4MDIgNi4yMTQ5OUM0LjQ0OTc5IDYuMDMyODUgNC4yNDM0OCA1Ljg5MDAzIDQuMDEzNzggNS43OTY3QzMuNzg0MDcgNS43MDMzNiAzLjUzNjYxIDUuNjYxODEgMy4yODkwMiA1LjY3NDk5Wk00LjE0NjAyIDguNzE1OTlDNC4xNjU2NCA5LjEzNDM1IDQuMDI1OTIgOS41NDQ1OSAzLjc1NTAyIDkuODY0QzMuNjM2ODkgMTAuMDAwNSAzLjQ4OTk4IDEwLjEwOTIgMy4zMjQ4NiAxMC4xODIxQzMuMTU5NzMgMTAuMjU1MSAyLjk4MDQ5IDEwLjI5MDYgMi44MDAwMiAxMC4yODZDMi42OTA0OSAxMC4yOTQ1IDIuNTgwMzUgMTAuMjgxMiAyLjQ3NTk5IDEwLjI0NjlDMi4zNzE2MyAxMC4yMTI1IDIuMjc1MTEgMTAuMTU3OSAyLjE5MjAyIDEwLjA4NkMyLjA2MDc5IDkuOTM0NTUgMS45ODg1NiA5Ljc0MDg4IDEuOTg4NTYgOS41NDA0OUMxLjk4ODU2IDkuMzQwMTEgMi4wNjA3OSA5LjE0NjQ0IDIuMTkyMDIgOC45OTQ5OUMyLjQ3MzIyIDguODIxMzEgMi43OTIzMyA4LjcxODM3IDMuMTIyMDIgOC42OTQ5OUw0LjE0MjAyIDguNTQ2OTlMNC4xNDYwMiA4LjcxNTk5Wk0xMi40NTg4IDExLjAzMjVDMTIuNzY2IDExLjE2MzggMTMuMDk4MyAxMS4yMjYxIDEzLjQzMjIgMTEuMjE1QzEzLjkyNyAxMS4yMjcgMTQuNDE1MyAxMS4xMDA2IDE0Ljg0MjIgMTAuODVMMTQuOTY1MiAxMC43NzVMMTQuOTc4MiAxMC43NjhWOS42MTUwNEwxNC41MzIyIDkuOTM1MDRDMTQuMjE2IDEwLjE1OTIgMTMuODM1NiAxMC4yNzQ3IDEzLjQ0ODIgMTAuMjY0QzEzLjI0OTcgMTAuMjcxOSAxMy4wNTIgMTAuMjM0MiAxMi44NzAzIDEwLjE1MzhDMTIuNjg4NiAxMC4wNzMzIDEyLjUyNzggOS45NTIzMiAxMi40MDAyIDkuODAwMDRDMTIuMTE0NCA5LjQyNDUzIDExLjk3MjUgOC45NTkxMSAxMi4wMDAyIDguNDg4MDRDMTEuOTczNyA3Ljk4NzMyIDEyLjEzNTIgNy40OTQ3NSAxMi40NTMyIDcuMTA3MDRDMTIuNTkzNCA2Ljk0MTA1IDEyLjc2OTUgNi44MDkxNCAxMi45NjgyIDYuNzIxM0MxMy4xNjcgNi42MzM0NiAxMy4zODMxIDYuNTkyIDEzLjYwMDIgNi42MDAwNEMxMy45NDM5IDYuNTk4NDQgMTQuMjgwOCA2LjY5NTI1IDE0LjU3MTIgNi44NzkwNEwxNS4wMDAyIDcuMTQ0MDRWNS45NzAwNEwxNC44MzEyIDUuODk3MDRDMTQuNDYyNiA1LjczNDMyIDE0LjA2NDEgNS42NTAyIDEzLjY2MTIgNS42NTAwNEMxMy4yOTk5IDUuNjM5OTEgMTIuOTQwNiA1LjcwNzYyIDEyLjYwNzggNS44NDg1OUMxMi4yNzQ5IDUuOTg5NTYgMTEuOTc2MyA2LjIwMDQ4IDExLjczMjIgNi40NjcwNEMxMS4yMjYxIDcuMDI2ODMgMTAuOTU4MSA3Ljc2MTg2IDEwLjk4NTIgOC41MTYwNEMxMC45NTY3IDkuMjIzNDYgMTEuMTk1NSA5LjkxNTY5IDExLjY1NDIgMTAuNDU1QzExLjg3NjkgMTAuNzA0IDEyLjE1MTYgMTAuOTAxMiAxMi40NTg4IDExLjAzMjVaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.color:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02LjYgMTEuNzY3M0M3LjMyODcxIDExLjAzODMgNy4zMjg3MSA5Ljg1NjM4IDYuNiA5LjEyNzQyQzUuODcwODMgOC4zOTg0NSA0LjY4OTEzIDguMzk4NDUgMy45NTk5NiA5LjEyNzQyQzIuOTE4MTIgMTAuMjI0OSAxLjEwNDExIDkuOTM5MDEgMS4wMTI5IDguNDI4NTNDMS4wMDQzNCA4LjI4Njc5IDEgOC4xNDM5IDEgOEMxIDQuMTMzOTkgNC4xMzQwNSAxIDggMUMxMS44NjYgMSAxNSA0LjEzMzk5IDE1IDhDMTUgMTEuODY2IDExLjg2NiAxNSA4IDE1QzcuNzk3NzQgMTUgNy41OTc0OSAxNC45OTE0IDcuMzk5NTkgMTQuOTc0NkM1LjgwNjQ2IDE0LjgzOTMgNS40OTg2IDEyLjkyNjMgNi42IDExLjc2NzNaTTYuOTY2NzUgMTMuNTQzNEM2LjkwMjUxIDEzLjI0NjQgNi45ODgyMSAxMi44MTUgNy4zMTgxOSAxMi40NjMyQzguNDI2MjkgMTEuMzQyOSA4LjQyMjY0IDkuNTM2MjMgNy4zMDcyMyA4LjQyMDQzTDcuMzA3MDEgOC40MjAyMUM2LjE4NzM0IDcuMzAwODUgNC4zNzI2MiA3LjMwMDg1IDMuMjUyOTUgOC40MjAyMUwzLjI0MzcxIDguNDI5NDVMMy4yMzQ3MSA4LjQzODkzQzIuOTM5MDMgOC43NTA0IDIuNTcwOTEgOC44MjU5OSAyLjMzMjUgOC43NzY2OEMyLjIxOTM2IDguNzUzMjggMi4xNTAyMSA4LjcwNjY3IDIuMTA5NzkgOC42NjE2MUMyLjA3MzkzIDguNjIxNjIgMi4wMjE0NiA4LjU0MDE2IDIuMDExMDggOC4zNjgyNkMyLjAwMzczIDguMjQ2NTYgMiA4LjEyMzc4IDIgOEMyIDQuNjg2MjggNC42ODYzMyAyIDggMkMxMS4zMTM3IDIgMTQgNC42ODYyOCAxNCA4QzE0IDExLjMxMzcgMTEuMzEzNyAxNCA4IDE0QzcuODI2MDIgMTQgNy42NTQgMTMuOTkyNiA3LjQ4NDIxIDEzLjk3ODJDNy4yODk5MiAxMy45NjE3IDcuMTg0ODggMTMuODk4NyA3LjEyNDE0IDEzLjg0MjlDNy4wNTgzMSAxMy43ODI0IDYuOTk3NjcgMTMuNjg2NCA2Ljk2Njc1IDEzLjU0MzRaTTUgNkM1LjU1MjI4IDYgNiA1LjU1MjI4IDYgNUM2IDQuNDQ3NzIgNS41NTIyOCA0IDUgNEM0LjQ0NzcyIDQgNCA0LjQ0NzcyIDQgNUM0IDUuNTUyMjggNC40NDc3MiA2IDUgNlpNMTIgMTFDMTIgMTEuNTUyMyAxMS41NTIzIDEyIDExIDEyQzEwLjQ0NzcgMTIgMTAgMTEuNTUyMyAxMCAxMUMxMCAxMC40NDc3IDEwLjQ0NzcgMTAgMTEgMTBDMTEuNTUyMyAxMCAxMiAxMC40NDc3IDEyIDExWk04IDVDOC41NTIyOCA1IDkgNC41NTIyOCA5IDRDOSAzLjQ0NzcyIDguNTUyMjggMyA4IDNDNy40NDc3MiAzIDcgMy40NDc3MiA3IDRDNyA0LjU1MjI4IDcuNDQ3NzIgNSA4IDVaTTEzIDhDMTMgOC41NTIyOCAxMi41NTIzIDkgMTIgOUMxMS40NDc3IDkgMTEgOC41NTIyOCAxMSA4QzExIDcuNDQ3NzIgMTEuNDQ3NyA3IDEyIDdDMTIuNTUyMyA3IDEzIDcuNDQ3NzIgMTMgOFpNMTEgNkMxMS41NTIzIDYgMTIgNS41NTIyOCAxMiA1QzEyIDQuNDQ3NzIgMTEuNTUyMyA0IDExIDRDMTAuNDQ3NyA0IDEwIDQuNDQ3NzIgMTAgNUMxMCA1LjU1MjI4IDEwLjQ0NzcgNiAxMSA2WiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.file:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDFMMyAyVjE0TDQgMTVIMTNMMTQgMTRWNUwxMy43MDcxIDQuMjkyODlMMTAuNzA3MSAxLjI5Mjg5TDEwIDFINFpNNCAxNFYyTDkgMlY2SDEzVjE0SDRaTTEzIDVMMTAgMlY1TDEzIDVaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.reference:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjA2MDY1IDMuODUzNTZMNS45MTQyMSA2TDUuMjA3MSA1LjI5Mjg5TDYuNDk5OTkgNEgzLjVDMy4xMDIxOCA0IDIuNzIwNjQgNC4xNTgwNCAyLjQzOTM0IDQuNDM5MzRDMi4xNTgwNCA0LjcyMDY1IDIgNS4xMDIxOCAyIDUuNUMyIDUuODk3ODMgMi4xNTgwNCA2LjI3OTM2IDIuNDM5MzQgNi41NjA2NkMyLjcyMDY0IDYuODQxOTcgMy4xMDIxOCA3IDMuNSA3SDRWOEgzLjVDMi44MzY5NiA4IDIuMjAxMDcgNy43MzY2MSAxLjczMjIzIDcuMjY3NzdDMS4yNjMzOSA2Ljc5ODkzIDEgNi4xNjMwNSAxIDUuNUMxIDQuODM2OTYgMS4yNjMzOSA0LjIwMTA4IDEuNzMyMjMgMy43MzIyNEMyLjIwMTA3IDMuMjYzNCAyLjgzNjk2IDMgMy41IDNINi40OTk5OUw2LjQ5OTk5IDNINi40OTk5Nkw2IDIuNTAwMDRWMi41MDAwMUw1LjIwNzEgMS43MDcxMUw1LjkxNDIxIDFMOC4wNjA2NSAzLjE0NjQ1TDguMDYwNjUgMy44NTM1NlpNNSA2LjUwMDAzTDUuOTE0MjEgNy40MTQyNEw2IDcuMzI4NDVWMTRIMTRWN0gxMFYzSDkuMDYwNjVWMi43MzIyN0w4LjMyODM4IDJIMTEuMkwxMS41IDIuMUwxNC45IDUuNkwxNSA2VjE0LjVMMTQuNSAxNUg1LjVMNSAxNC41VjkuMDAwMDNWNi41MDAwM1pNMTEgM1Y2SDEzLjkwMzJMMTEgM1oiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.snippet:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yLjUgMUwyIDEuNVYxM0gzVjJIMTRWMTNIMTVWMS41TDE0LjUgMUgyLjVaTTIgMTVWMTRIM1YxNUgyWk01IDE0LjAwMDFINFYxNS4wMDAxSDVWMTQuMDAwMVpNNiAxNC4wMDAxSDdWMTUuMDAwMUg2VjE0LjAwMDFaTTkgMTQuMDAwMUg4VjE1LjAwMDFIOVYxNC4wMDAxWk0xMCAxNC4wMDAxSDExVjE1LjAwMDFIMTBWMTQuMDAwMVpNMTUgMTUuMDAwMVYxNC4wMDAxSDE0VjE1LjAwMDFIMTVaTTEyIDE0LjAwMDFIMTNWMTUuMDAwMUgxMlYxNC4wMDAxWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.customcolor:before{background-image:none}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon.folder:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xLjAxMDg3IDIuNUwxLjUxMDg3IDJINi41MDcxM0w2Ljg2MDY4IDIuMTQ2NDVMNy43MTM0OSAyLjk5OTI1SDE0LjUwMTFMMTUuMDAxMSAzLjQ5OTI1VjguOTk1MTJMMTQuOTkwMyA5LjAwNTk5VjEzLjUwMjFMMTQuNDkwMyAxNC4wMDIxSDEuNUwxIDEzLjUwMjFWNi41MDczNUwxLjAxMDg3IDYuNDk2NDhWMi41Wk0xNC4wMDExIDMuOTk5MjVWNS4wMDMxMUg3LjUwMDVMNy4xNDY5NSA1LjE0OTU2TDYuMjg5MTUgNi4wMDczNUgyLjAxMDg3VjNINi4zMDAwMkw3LjE1MjgzIDMuODUyOEw3LjUwNjM4IDMuOTk5MjVIMTQuMDAxMVpNNi40OTYyNiA3LjAwNzM1SDIuMDEwODdWNy40OTU4OEgxLjk5OTYzVjExLjQ5MjlIMlYxMy4wMDIxSDEzLjk5MDNWMTEuNDkyOUgxMy45OTA2VjcuNDk1ODhIMTMuOTkwM1Y2LjAwMzExSDcuNzA3NjFMNi44NDk4MSA2Ljg2MDlMNi40OTYyNiA3LjAwNzM1WiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K")}.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon.customcolor .colorspan{margin:0 0 0 .3em;border:.1em solid #000;width:.7em;height:.7em;display:inline-block}.monaco-editor .suggest-widget .details{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;cursor:default}.monaco-editor .suggest-widget .details.no-docs{display:none}.monaco-editor .suggest-widget.docs-below .details{border-top-width:0}.monaco-editor .suggest-widget .details>.monaco-scrollable-element{-ms-flex:1;flex:1}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body{position:absolute;box-sizing:border-box;height:100%;width:100%}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.header>.type{-ms-flex:2;flex:2;overflow:hidden;text-overflow:ellipsis;opacity:.7;word-break:break-all;margin:0 24px 0 0;padding:4px 0 12px 5px}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs{margin:0;padding:4px 5px;white-space:pre-wrap}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs.markdown-docs{padding:0;white-space:normal}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs.markdown-docs>div,.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs.markdown-docs>span:not(:empty){padding:4px 5px}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs.markdown-docs>div>p:first-child{margin-top:0}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs.markdown-docs>div>p:last-child{margin-bottom:0}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>.docs .code{white-space:pre-wrap;word-wrap:break-word}.monaco-editor .suggest-widget .details>.monaco-scrollable-element>.body>p:empty{display:none}.monaco-editor .suggest-widget .details code{border-radius:3px;padding:0 .4em}.monaco-editor.hc-black .suggest-widget .details>.monaco-scrollable-element>.body>.header>.close,.monaco-editor.vs-dark .suggest-widget .details>.monaco-scrollable-element>.body>.header>.close{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03Ljk5OTk4IDguNzA3MDhMMTEuNjQ2NCAxMi4zNTM1TDEyLjM1MzUgMTEuNjQ2NEw4LjcwNzA4IDcuOTk5OThMMTIuMzUzNSA0LjM1MzUzTDExLjY0NjQgMy42NDY0Mkw3Ljk5OTk4IDcuMjkyODdMNC4zNTM1MyAzLjY0NjQyTDMuNjQ2NDIgNC4zNTM1M0w3LjI5Mjg3IDcuOTk5OThMMy42NDY0MiAxMS42NDY0TDQuMzUzNTMgMTIuMzUzNUw3Ljk5OTk4IDguNzA3MDhaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.readMore,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.readMore{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zIDcuNUMzIDQuNDYyNDMgNS40NjI0MyAyIDguNSAyQzExLjUzNzYgMiAxNCA0LjQ2MjQzIDE0IDcuNUMxNCAxMC41Mzc2IDExLjUzNzYgMTMgOC41IDEzQzUuNDYyNDMgMTMgMyAxMC41Mzc2IDMgNy41Wk0yIDcuNUMyIDMuOTEwMTUgNC45MTAxNSAxIDguNSAxQzEyLjA4OTkgMSAxNSAzLjkxMDE1IDE1IDcuNUMxNSAxMS4wODk5IDEyLjA4OTkgMTQgOC41IDE0QzQuOTEwMTUgMTQgMiAxMS4wODk5IDIgNy41Wk04IDRWNUg5VjRIOFpNOCA2TDggMTBIOUw5IDZIOFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.constructor:before,.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.function:before,.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.method:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.constructor:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.function:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.method:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yIDQuODU3NDlMMi40ODU1IDRMNy40ODU1IDFIOC41MTQ1TDEzLjUxNDUgNEwxNCA0Ljg1NzQ5VjEwLjg1NzVMMTMuNTE0NSAxMS43MTVMOC41MTQ1IDE0LjcxNUg3LjQ4NTVMMi40ODU1IDExLjcxNUwyIDEwLjg1NzVWNC44NTc0OVpNNy41IDEzLjU1NzVMMyAxMC44NTc1VjUuNjk5NzVMNy41IDguMTU0M1YxMy41NTc1Wk04LjUgMTMuNTU3NUwxMyAxMC44NTc1VjUuNjk5NzVMOC41IDguMTU0M1YxMy41NTc1Wk04IDEuODU3NDlMMy4yNTkxMyA0LjcwMjAxTDggNy4yODc5NEwxMi43NDA5IDQuNzAyMDFMOCAxLjg1NzQ5WiIgZmlsbD0iI0IxODBENyIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.field:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.field:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xIDYuMzk0NDNMMS41NTI3OSA1LjVMOC41NTI3OSAySDkuNDQ3MjFMMTQuNDQ3MiA0LjVMMTUgNS4zOTQ0M1Y5Ljg5NDQzTDE0LjQ0NzIgMTAuNzg4OUw3LjQ0NzIxIDE0LjI4ODlINi41NTI3OUwxLjU1Mjc5IDExLjc4ODlMMSAxMC44OTQ0VjYuMzk0NDNaTTYuNSAxMy4xNDQ0TDIgMTAuODk0NFY3LjE3MDk0TDYuNSA5LjIxNjM5VjEzLjE0NDRaTTcuNSAxMy4xNDQ0TDE0IDkuODk0NDNWNi4xNzk1NEw3LjUgOS4yMTI4N1YxMy4xNDQ0Wk05IDIuODk0NDNMMi4zMzcyOCA2LjIyNTc5TDYuOTk3MjUgOC4zNDM5NkwxMy42NzA2IDUuMjI5NzNMOSAyLjg5NDQzWiIgZmlsbD0iIzc1QkVGRiIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.event:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.event:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjQxMzU0IDEuNTU5OTZMOC4zMTE1MiAxSDExLjYwNTZMMTIuNDI0IDIuNTc0NjVMMTAuMjM1NiA2SDEyLjAxNzRMMTIuNzM2MyA3LjY5NTEyTDUuNjE5NDMgMTVMNC4wMTY3NSAxMy44MzdMNi4xMTk0MyAxMEg0Ljg5Nzk4TDQgOC41NTk5Nkw3LjQxMzU0IDEuNTU5OTZaTTcuNzgwMzMgOUw0LjkwMDU0IDE0LjMwNDlMMTIuMDE3NCA3SDguMzExNTJMMTEuNjA1NiAySDguMzExNTJMNC44OTc5OCA5SDcuNzgwMzNaIiBmaWxsPSIjRDY3RTAwIi8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.operator:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.operator:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yLjg3Mjg5IDEuMTAwMjNDMy4yMDc2OCAxLjIzNTc5IDMuNDc1NDUgMS40OTggMy42MTgwMiAxLjgyOTg4QzMuNjkwMzIgMS45OTk1OSAzLjcyNjc1IDIuMTgyNDIgMy43MjUwMiAyLjM2Njg4QzMuNzI2MTcgMi41NDk5OSAzLjY4OTc1IDIuNzMxNCAzLjYxODAyIDIuODk5ODhDMy41MTI5OSAzLjE0NTY3IDMuMzM3ODIgMy4zNTUwMyAzLjExNDQyIDMuNTAxNzdDMi44OTEwMiAzLjY0ODUxIDIuNjI5MyAzLjcyNjEyIDIuMzYyMDIgMy43MjQ4OEMyLjE3OTI0IDMuNzI1OTIgMS45OTgxOCAzLjY4OTUxIDEuODMwMDIgMy42MTc4OEMxLjU4Mjk4IDMuNTE0MDYgMS4zNzIyNyAzLjMzOTMyIDEuMjI0NTMgMy4xMTU3NUMxLjA3NjggMi44OTIxOSAwLjk5ODY2NiAyLjYyOTg0IDEuMDAwMDIgMi4zNjE4OEMwLjk5OTEzIDIuMTc5MjEgMS4wMzUxOSAxLjk5ODI1IDEuMTA2MDIgMS44Mjk4OEMxLjI0MzM3IDEuNTAzMTQgMS41MDMyOCAxLjI0MzIzIDEuODMwMDIgMS4xMDU4OEMyLjE2MzMyIDAuOTY2NjkyIDIuNTM4MDkgMC45NjQ2NjEgMi44NzI4OSAxLjEwMDIzWk0yLjU3NTAyIDIuODY0ODhDMi43MDU0IDIuODA5MTMgMi44MDkyNyAyLjcwNTI2IDIuODY1MDIgMi41NzQ4OEMyLjg5MjkgMi41MDgzOCAyLjkwNzE4IDIuNDM2OTggMi45MDcwMiAyLjM2NDg4QzIuOTA4MTMgMi4yNjU0IDIuODgyMTUgMi4xNjc1IDIuODMxODUgMi4wODE2N0MyLjc4MTU2IDEuOTk1ODQgMi43MDg4NCAxLjkyNTMxIDIuNjIxNTEgMS44Nzc2N0MyLjUzNDE4IDEuODMwMDIgMi40MzU1MyAxLjgwNzA1IDIuMzM2MTQgMS44MTEyMUMyLjIzNjc0IDEuODE1MzcgMi4xNDAzNSAxLjg0NjUgMi4wNTczMSAxLjkwMTI4QzEuOTc0MjYgMS45NTYwNiAxLjkwNzcgMi4wMzI0MSAxLjg2NDc1IDIuMTIyMTVDMS44MjE4IDIuMjExODggMS44MDQwOSAyLjMxMTYxIDEuODEzNTIgMi40MTA2NUMxLjgyMjk0IDIuNTA5NjggMS44NTkxNSAyLjYwNDI4IDEuOTE4MjUgMi42ODQzQzEuOTc3MzYgMi43NjQzMyAyLjA1NzEzIDIuODI2NzUgMi4xNDkwMiAyLjg2NDg4QzIuMjg1NDkgMi45MjA4OSAyLjQzODU0IDIuOTIwODkgMi41NzUwMiAyLjg2NDg4Wk02LjQyOTk1IDEuMTA5NUwxLjEwOTY3IDYuNDI5NzdMMS43OTU1NyA3LjExNTY3TDcuMTE1ODQgMS43OTU0TDYuNDI5OTUgMS4xMDk1Wk0xMS41IDguOTk5OTlIMTIuNVYxMS41SDE1VjEyLjVIMTIuNVYxNUgxMS41VjEyLjVIOVYxMS41SDExLjVWOC45OTk5OVpNNS43Njc3NyA5LjUyNTA5TDYuNDc0ODcgMTAuMjMyMkw0LjcwNzExIDEyTDYuNDc0ODcgMTMuNzY3N0w1Ljc2Nzc3IDE0LjQ3NDhMNCAxMi43MDcxTDIuMjMyMjMgMTQuNDc0OEwxLjUyNTEzIDEzLjc2NzdMMy4yOTI4OSAxMkwxLjUyNTEzIDEwLjIzMjJMMi4yMzIyMyA5LjUyNTA5TDQgMTEuMjkyOUw1Ljc2Nzc3IDkuNTI1MDlaTTcuMTE4MDIgNS4zMjk4OEM3LjAxNDQyIDUuMDgyNjggNi44Mzk3MyA0Ljg3MTgzIDYuNjE2MTIgNC43MjQwNkM2LjM5MjUgNC41NzYyOSA2LjEzMDA0IDQuNDk4MjYgNS44NjIwMiA0LjQ5OTg4QzUuNjc5MzUgNC40OTg5OSA1LjQ5ODM5IDQuNTM1MDUgNS4zMzAwMiA0LjYwNTg4QzUuMDAzMjggNC43NDMyMyA0Ljc0MzM3IDUuMDAzMTQgNC42MDYwMiA1LjMyOTg4QzQuNTM1ODggNS40OTQ3OCA0LjQ5ODk3IDUuNjcxOTEgNC40OTc0MSA1Ljg1MTFDNC40OTU4NiA2LjAzMDMgNC41Mjk2NyA2LjIwODA0IDQuNTk2OTMgNi4zNzQxNEM0LjY2NDE5IDYuNTQwMjQgNC43NjM1NiA2LjY5MTQzIDQuODg5MzYgNi44MTkwNkM1LjAxNTE2IDYuOTQ2NjkgNS4xNjQ5IDcuMDQ4MjMgNS4zMzAwMiA3LjExNzg4QzUuNDk4NjcgNy4xODg0OCA1LjY3OTY4IDcuMjI0ODQgNS44NjI1MiA3LjIyNDg0QzYuMDQ1MzUgNy4yMjQ4NCA2LjIyNjM2IDcuMTg4NDggNi4zOTUwMiA3LjExNzg4QzYuNjQyMDEgNy4wMTM4OCA2Ljg1MjcgNi44MzkxMyA3LjAwMDU4IDYuNjE1NjNDNy4xNDg0NSA2LjM5MjEzIDcuMjI2ODkgNi4xMjk4NyA3LjIyNjAyIDUuODYxODhDNy4yMjY1NSA1LjY3OTA1IDcuMTg5OCA1LjQ5ODAzIDcuMTE4MDIgNS4zMjk4OFpNNi4zNjUwMiA2LjA3NDg4QzYuMzM3NjYgNi4xMzkzNyA2LjI5ODI5IDYuMTk4MDggNi4yNDkwMiA2LjI0Nzg4QzYuMTk5MDggNi4yOTcyNCA2LjE0MDQyIDYuMzM2OTEgNi4wNzYwMiA2LjM2NDg4QzYuMDA4NTQgNi4zOTI5NyA1LjkzNjExIDYuNDA3MjUgNS44NjMwMiA2LjQwNjg4QzUuNzg5OTEgNi40MDc0NCA1LjcxNzQ0IDYuMzkzMTUgNS42NTAwMiA2LjM2NDg4QzUuNTg1NDEgNi4zMzcyOSA1LjUyNjY4IDYuMjk3NTcgNS40NzcwMiA2LjI0Nzg4QzUuNDI2OTEgNi4xOTg1NiA1LjM4NzEzIDYuMTM5NzUgNS4zNjAwMiA2LjA3NDg4QzUuMzA0MDEgNS45Mzg0IDUuMzA0MDEgNS43ODUzNiA1LjM2MDAyIDUuNjQ4ODhDNS40MTUzNiA1LjUxODQ2IDUuNTE5NDEgNS40MTQ3NyA1LjY1MDAyIDUuMzU5ODhDNS43MTczNyA1LjMzMTI2IDUuNzg5ODQgNS4zMTY2MyA1Ljg2MzAyIDUuMzE2ODhDNS45MzYxOCA1LjMxNjg1IDYuMDA4NiA1LjMzMTQ3IDYuMDc2MDIgNS4zNTk4OEM2LjE0MDM3IDUuMzg3NDkgNi4xOTkwNCA1LjQyNjgyIDYuMjQ5MDIgNS40NzU4OEM2LjI5Nzg2IDUuNTI2MDMgNi4zMzcxNyA1LjU4NDY1IDYuMzY1MDIgNS42NDg4OEM2LjM5MzQgNS43MTYzIDYuNDA4MDIgNS43ODg3MiA2LjQwODAyIDUuODYxODhDNi40MDgwMiA1LjkzNTAzIDYuMzkzNCA2LjAwNzQ1IDYuMzY1MDIgNi4wNzQ4OFpNMTQgM0gxMFY0SDE0VjNaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.variable:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.variable:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xLjUgNEwxIDQuNVYxMi41TDEuNSAxM0g0VjEySDJWNUg0VjRIMS41Wk0xNC41IDEzTDE1IDEyLjVMMTUgNC41TDE0LjUgNEgxMlY1TDE0IDVMMTQgMTJIMTJWMTNIMTQuNVpNOC43OTY5MyA1TDQuMjk2OTMgN0w0IDcuNDU2OTFWOS45NTY5MUw0LjI0Mjc1IDEwLjM4NTdMNi43NDI3NSAxMS44ODU3TDcuMjAzMDcgMTEuOTEzOEwxMS43MDMxIDkuOTEzODFMMTIgOS40NTY5MVY2Ljk1NjkxTDExLjc1NzIgNi41MjgxNkw5LjI1NzI1IDUuMDI4MTZMOC43OTY5MyA1Wk01IDguMzRWOS42NzM4MUw2LjUgMTAuNTczOFY5LjI0TDUgOC4zNFpNNy41IDkuMjgxODRWMTAuNjg3NUwxMSA5LjEzMTk3VjcuNzI2MjlMNy41IDkuMjgxODRaTTEwLjQxNzggNi44OTA3MUw4Ljk2NTU5IDYuMDE5MzZMNS41ODIxNiA3LjUyMzExTDcuMDM0NDEgOC4zOTQ0NUwxMC40MTc4IDYuODkwNzFaIiBmaWxsPSIjNzVCRUZGIi8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.class:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.class:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zLjM1MzU2IDYuNjQ2NDJMMi4wNjA2NiA1LjM1MzUzTDUuMzUzNTYgMi4wNjA2NUw2LjY0NjQ1IDMuMzUzNTRMMy4zNTM1NiA2LjY0NjQyWk01IDFMMSA0Ljk5OTk4VjUuNzA3MDhMMyA3LjcwNzA3SDMuNzA3MTFMNC44NTM1NSA2LjU2MDYzVjEyLjM1MzVMNS4zNTM1NSAxMi44NTM1SDEwLjAwOTdWMTMuMzc0MUwxMS4zNDMgMTQuNzA3NEgxMi4wNTAxTDE0LjcxNjggMTIuMDQwN1YxMS4zMzM2TDEzLjM4MzUgMTAuMDAwM0gxMi42NzYzTDEwLjgyMzEgMTEuODUzNUg1Ljg1MzU1VjcuODkzNTVIMTAuMDA5N1Y4LjM3NDAxTDExLjM0MyA5LjcwNzM0SDEyLjA1MDFMMTQuNzE2OCA3LjA0MDY4VjYuMzMzNTdMMTMuMzgzNSA1LjAwMDI0SDEyLjY3NjNMMTAuODYzIDYuODEzNTZINS44NTM1NVY1LjU2MDY0TDcuNzA3MTEgMy43MDcwOVYyLjk5OTk5TDUuNzA3MTEgMUg1Wk0xMS4wNzAzIDguMDIwNDZMMTEuNjk2NiA4LjY0NjY4TDEzLjY1NjEgNi42ODcxM0wxMy4wMjk5IDYuMDYwOUwxMS4wNzAzIDguMDIwNDZaTTExLjA3MDMgMTMuMDIwNUwxMS42OTY2IDEzLjY0NjdMMTMuNjU2MSAxMS42ODcyTDEzLjAyOTkgMTEuMDYxTDExLjA3MDMgMTMuMDIwNVoiIGZpbGw9IiNFRTlEMjgiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.interface:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.interface:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS41IDVDMTAuMTE5MyA1IDkgNi4xMTkyOSA5IDcuNUM5IDguODgwNzEgMTAuMTE5MyAxMCAxMS41IDEwQzEyLjg4MDcgMTAgMTQgOC44ODA3MSAxNCA3LjVDMTQgNi4xMTkyOSAxMi44ODA3IDUgMTEuNSA1Wk04LjAzNTQ0IDhDOC4yNzgwNiA5LjY5NjE1IDkuNzM2NzYgMTEgMTEuNSAxMUMxMy40MzMgMTEgMTUgOS40MzMgMTUgNy41QzE1IDUuNTY3IDEzLjQzMyA0IDExLjUgNEM5LjczNjc2IDQgOC4yNzgwNiA1LjMwMzg1IDguMDM1NDQgN0g0LjkzNjk5QzQuNzE0OTcgNi4xMzczOSAzLjkzMTkyIDUuNSAzIDUuNUMxLjg5NTQzIDUuNSAxIDYuMzk1NDMgMSA3LjVDMSA4LjYwNDU3IDEuODk1NDMgOS41IDMgOS41QzMuOTMxOTIgOS41IDQuNzE0OTcgOC44NjI2MSA0LjkzNjk5IDhIOC4wMzU0NFoiIGZpbGw9IiM3NUJFRkYiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.struct:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.struct:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yIDJMMSAzVjZMMiA3SDE0TDE1IDZWM0wxNCAySDJaTTIgM0gzSDEzSDE0VjRWNVY2SDEzSDNIMlY1VjRWM1pNMSAxMEwyIDlINUw2IDEwVjEzTDUgMTRIMkwxIDEzVjEwWk0zIDEwSDJWMTFWMTJWMTNIM0g0SDVWMTJWMTFWMTBINEgzWk0xMCAxMEwxMSA5SDE0TDE1IDEwVjEzTDE0IDE0SDExTDEwIDEzVjEwWk0xMiAxMEgxMVYxMVYxMlYxM0gxMkgxM0gxNFYxMlYxMVYxMEgxM0gxMloiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.type-parameter:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.type-parameter:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMSA2SDEwVjUuNUMxMCA1LjIyMzg2IDkuNzc2MTYgNSA5LjUwMDAxIDVIOC40NzkwMlYxMC41QzguNDc5MDIgMTAuNzc2MSA4LjcwMjg4IDExIDguOTc5MDIgMTFIOS40NzkwMlYxMkg2LjQ3OTAyVjExSDYuOTc5MDJDNy4yNTUxNiAxMSA3LjQ3OTAyIDEwLjc3NjEgNy40NzkwMiAxMC41VjVINi41MDAwMUM2LjIyMzg3IDUgNi4wMDAwMSA1LjIyMzg2IDYuMDAwMDEgNS41VjZINS4wMDAwMVY0SDExVjZaTTEzLjkxNDIgOC4wNDgxTDEyLjQ1MTkgNi41ODU4MUwxMy4xNTkgNS44Nzg3MUwxNC45NzQ5IDcuNjk0NTRWOC40MDE2NUwxMy4yMDcxIDEwLjE2OTRMMTIuNSA5LjQ2MjMxTDEzLjkxNDIgOC4wNDgxWk0zLjU0ODEgOS40NjIzTDIuMDg1ODEgOC4wMDAwMkwzLjUwMDAyIDYuNTg1ODFMMi43OTI5MSA1Ljg3ODdMMS4wMjUxNSA3LjY0NjQ3VjguMzUzNTdMMi44NDEgMTAuMTY5NEwzLjU0ODEgOS40NjIzWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.module:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.module:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02IDIuOTgzNjFWMi45NzE4NFYySDUuOTEwODNDNS41OTc0MyAyIDUuMjk0MDcgMi4wNjE2MSA1LjAwMTI4IDIuMTg0NzNDNC43MDgxOCAyLjMwNzk4IDQuNDQ5NDIgMi40ODQ3NCA0LjIyNTc4IDIuNzE0OThDNC4wMDMxMSAyLjk0NDIyIDMuODM3OTIgMy4xOTQ5OCAzLjczMjgyIDMuNDY3NjZMMy43MzIzMyAzLjQ2ODk4QzMuNjMzODIgMy43MzUyIDMuNTY4MTQgNC4wMTIwMSAzLjUzNTMzIDQuMjk5MTdMMy41MzUxOSA0LjMwMDUzQzMuNTA2NzggNC41ODA1IDMuNDk4NyA0Ljg2ODQ0IDMuNTEwODQgNS4xNjQyOEMzLjUyMjcyIDUuNDUzNzkgMy41Mjg2NiA1Ljc0MzI5IDMuNTI4NjYgNi4wMzI3OUMzLjUyODY2IDYuMjM1NTYgMy40ODk3NCA2LjQyNTk0IDMuNDEyIDYuNjA1MDdMMy40MTE2IDYuNjA2MDFDMy4zMzY4NyA2Ljc4Mjk2IDMuMjM0MjMgNi45Mzg2NiAzLjEwMzE3IDcuMDczNTlDMi45NzY0NCA3LjIwNDA1IDIuODI0NjYgNy4zMTA1NSAyLjY0NjcyIDcuMzkyNUMyLjQ3MDYgNy40Njk1NCAyLjI4NDk3IDcuNTA4MiAyLjA4OTE3IDcuNTA4MkgyVjcuNlY4LjRWOC40OTE4SDIuMDg5MTdDMi4yODQ2NSA4LjQ5MTggMi40NzAwMSA4LjUzMjM4IDIuNjQ2MDEgOC42MTMzNEwyLjY0NzQyIDguNjEzOTZDMi44MjQ1NyA4LjY5MTU3IDIuOTc1NzcgOC43OTc2MiAzLjEwMjIxIDguOTMxNjFMMy4xMDQxMiA4LjkzMzUyQzMuMjM0MjggOS4wNjM3IDMuMzM2NTkgOS4yMTg3MSAzLjQxMTI5IDkuMzk5NDJMMy40MTIwMSA5LjQwMTA4QzMuNDg5ODYgOS41ODA0NyAzLjUyODY2IDkuNzY4ODMgMy41Mjg2NiA5Ljk2NzIxQzMuNTI4NjYgMTAuMjU2NyAzLjUyMjcyIDEwLjU0NjIgMy41MTA4NCAxMC44MzU3QzMuNDk4NyAxMS4xMzE2IDMuNTA2NzcgMTEuNDIxNSAzLjUzNTE2IDExLjcwNTVMMy41MzUzNSAxMS43MDcyQzMuNTY4MTkgMTEuOTkwMyAzLjYzMzg3IDEyLjI2NSAzLjczMjMyIDEyLjUzMUwzLjczMjgzIDEyLjUzMjNDMy44Mzc5MyAxMi44MDUgNC4wMDMxMSAxMy4wNTU4IDQuMjI1NzggMTMuMjg1QzQuNDQ5NDIgMTMuNTE1MyA0LjcwODE4IDEzLjY5MiA1LjAwMTI4IDEzLjgxNTNDNS4yOTQwNyAxMy45Mzg0IDUuNTk3NDMgMTQgNS45MTA4MyAxNEg2VjEzLjJWMTMuMDE2NEg1LjkxMDgzQzUuNzEwOTUgMTMuMDE2NCA1LjUyMzQ2IDEyLjk3NzcgNS4zNDc2MyAxMi45MDA4QzUuMTczOTYgMTIuODE5MSA1LjAyMTk0IDEyLjcxMjYgNC44OTA4NiAxMi41ODE4QzQuNzYzODYgMTIuNDQ2OSA0LjY2MTA0IDEyLjI5MTEgNC41ODIyMyAxMi4xMTM3QzQuNTA4MzggMTEuOTM0NiA0LjQ3MTM0IDExLjc0NCA0LjQ3MTM0IDExLjU0MUM0LjQ3MTM0IDExLjMxMjcgNC40NzUzIDExLjA4ODUgNC40ODMyMSAxMC44Njg2QzQuNDkxMjUgMTAuNjQxMSA0LjQ5MTI3IDEwLjQxOTUgNC40ODMyNCAxMC4yMDM5QzQuNDc5MTQgOS45ODI0NiA0LjQ2MDg0IDkuNzY4ODMgNC40MjgyMyA5LjU2MzEyQzQuMzk1MTMgOS4zNTAyNCA0LjMzOTIxIDkuMTQ3NTcgNC4yNjAzOSA4Ljk1NTM2QzQuMTgwOTEgOC43NjE1NyA0LjA3MjU4IDguNTc3NDYgMy45MzYxNiA4LjQwMjk4QzMuODIzNDUgOC4yNTg4MSAzLjY4NTM4IDguMTI0NjIgMy41MjI4MyA4QzMuNjg1MzggNy44NzUzOCAzLjgyMzQ1IDcuNzQxMTkgMy45MzYxNiA3LjU5NzAyQzQuMDcyNTggNy40MjI1NCA0LjE4MDkxIDcuMjM4NDMgNC4yNjAzOSA3LjA0NDY0QzQuMzM5MTMgNi44NTI2MyA0LjM5NTEzIDYuNjUxNzUgNC40MjgyNiA2LjQ0Mjg1QzQuNDYwODIgNi4yMzMzIDQuNDc5MTQgNi4wMTk3MyA0LjQ4MzI0IDUuODAyMTlDNC40OTEyNyA1LjU4MjYyIDQuNDkxMjUgNS4zNjEwNSA0LjQ4MzIxIDUuMTM3NDlDNC40NzUzIDQuOTEzNCA0LjQ3MTM0IDQuNjg3MjUgNC40NzEzNCA0LjQ1OTAyQzQuNDcxMzQgNC4yNjAxOSA0LjUwODMzIDQuMDcxNTIgNC41ODIzOCAzLjg5MjA1QzQuNjYxMzUgMy43MTAzNCA0Ljc2NDIxIDMuNTU0NzUgNC44OTA4NiAzLjQyNDM3QzUuMDIxOTMgMy4yODk0MiA1LjE3NDYxIDMuMTgyNzUgNS4zNDgwMiAzLjEwNTEzQzUuNTIzOCAzLjAyNDI3IDUuNzExMTMgMi45ODM2MSA1LjkxMDgzIDIuOTgzNjFINlpNMTAgMTMuMDE2NFYxMy4wMjgyVjE0SDEwLjA4OTJDMTAuNDAyNiAxNCAxMC43MDU5IDEzLjkzODQgMTAuOTk4NyAxMy44MTUzQzExLjI5MTggMTMuNjkyIDExLjU1MDYgMTMuNTE1MyAxMS43NzQyIDEzLjI4NUMxMS45OTY5IDEzLjA1NTggMTIuMTYyMSAxMi44MDUgMTIuMjY3MiAxMi41MzIzTDEyLjI2NzcgMTIuNTMxQzEyLjM2NjIgMTIuMjY0OCAxMi40MzE5IDExLjk4OCAxMi40NjQ3IDExLjcwMDhMMTIuNDY0OCAxMS42OTk1QzEyLjQ5MzIgMTEuNDE5NSAxMi41MDEzIDExLjEzMTYgMTIuNDg5MiAxMC44MzU3QzEyLjQ3NzMgMTAuNTQ2MiAxMi40NzEzIDEwLjI1NjcgMTIuNDcxMyA5Ljk2NzIxQzEyLjQ3MTMgOS43NjQ0NCAxMi41MTAzIDkuNTc0MDYgMTIuNTg4IDkuMzk0OTNMMTIuNTg4NCA5LjM5Mzk5QzEyLjY2MzEgOS4yMTcwNCAxMi43NjU4IDkuMDYxMzQgMTIuODk2OCA4LjkyNjQyQzEzLjAyMzYgOC43OTU5NSAxMy4xNzUzIDguNjg5NDUgMTMuMzUzMyA4LjYwNzVDMTMuNTI5NCA4LjUzMDQ2IDEzLjcxNSA4LjQ5MTggMTMuOTEwOCA4LjQ5MThIMTRWOC40VjcuNlY3LjUwODJIMTMuOTEwOEMxMy43MTUzIDcuNTA4MiAxMy41MyA3LjQ2NzYyIDEzLjM1NCA3LjM4NjY2TDEzLjM1MjYgNy4zODYwNEMxMy4xNzU0IDcuMzA4NDQgMTMuMDI0MiA3LjIwMjM4IDEyLjg5NzggNy4wNjgzOUwxMi44OTU5IDcuMDY2NDhDMTIuNzY1NyA2LjkzNjMgMTIuNjYzNCA2Ljc4MTI5IDEyLjU4ODcgNi42MDA1OEwxMi41ODggNi41OTg5MkMxMi41MTAxIDYuNDE5NTMgMTIuNDcxMyA2LjIzMTE3IDEyLjQ3MTMgNi4wMzI3OUMxMi40NzEzIDUuNzQzMjkgMTIuNDc3MyA1LjQ1Mzc5IDEyLjQ4OTIgNS4xNjQyOEMxMi41MDEzIDQuODY4NDIgMTIuNDkzMiA0LjU3ODQ4IDEyLjQ2NDggNC4yOTQ1NEwxMi40NjQ2IDQuMjkyODVDMTIuNDMxOCA0LjAwOTcxIDEyLjM2NjEgMy43MzUwMiAxMi4yNjc3IDMuNDY4OTdMMTIuMjY3MiAzLjQ2NzY2QzEyLjE2MjEgMy4xOTQ5OSAxMS45OTY5IDIuOTQ0MjIgMTEuNzc0MiAyLjcxNDk4QzExLjU1MDYgMi40ODQ3NCAxMS4yOTE4IDIuMzA3OTggMTAuOTk4NyAyLjE4NDczQzEwLjcwNTkgMi4wNjE2MSAxMC40MDI2IDIgMTAuMDg5MiAySDEwVjIuOFYyLjk4MzYxSDEwLjA4OTJDMTAuMjg5MSAyLjk4MzYxIDEwLjQ3NjUgMy4wMjIzIDEwLjY1MjQgMy4wOTkxN0MxMC44MjYgMy4xODA5MiAxMC45NzgxIDMuMjg3MzYgMTEuMTA5MSAzLjQxODIzQzExLjIzNjEgMy41NTMwNSAxMS4zMzkgMy43MDg4OSAxMS40MTc4IDMuODg2MjhDMTEuNDkxNiA0LjA2NTQgMTEuNTI4NyA0LjI1NTk2IDExLjUyODcgNC40NTkwMkMxMS41Mjg3IDQuNjg3MjcgMTEuNTI0NyA0LjkxMTQ1IDExLjUxNjggNS4xMzE0MkMxMS41MDg4IDUuMzU4OTQgMTEuNTA4NyA1LjU4MDQ5IDExLjUxNjggNS43OTYwNUMxMS41MjA5IDYuMDE3NTQgMTEuNTM5MiA2LjIzMTE3IDExLjU3MTggNi40MzY4OEMxMS42MDQ5IDYuNjQ5NzYgMTEuNjYwOCA2Ljg1MjQzIDExLjczOTYgNy4wNDQ2NEMxMS44MTkxIDcuMjM4NDMgMTEuOTI3NCA3LjQyMjU0IDEyLjA2MzggNy41OTcwMkMxMi4xNzY1IDcuNzQxMTkgMTIuMzE0NiA3Ljg3NTM4IDEyLjQ3NzIgOEMxMi4zMTQ2IDguMTI0NjIgMTIuMTc2NSA4LjI1ODgxIDEyLjA2MzggOC40MDI5OEMxMS45Mjc0IDguNTc3NDYgMTEuODE5MSA4Ljc2MTU3IDExLjczOTYgOC45NTUzNkMxMS42NjA5IDkuMTQ3MzcgMTEuNjA0OSA5LjM0ODI1IDExLjU3MTcgOS41NTcxNUMxMS41MzkyIDkuNzY2NyAxMS41MjA5IDkuOTgwMjcgMTEuNTE2OCAxMC4xOTc4QzExLjUwODcgMTAuNDE3NCAxMS41MDg3IDEwLjYzODkgMTEuNTE2OCAxMC44NjI1QzExLjUyNDcgMTEuMDg2NiAxMS41Mjg3IDExLjMxMjggMTEuNTI4NyAxMS41NDFDMTEuNTI4NyAxMS43Mzk4IDExLjQ5MTcgMTEuOTI4NSAxMS40MTc2IDEyLjEwNzlDMTEuMzM4NiAxMi4yODk3IDExLjIzNTggMTIuNDQ1MiAxMS4xMDkxIDEyLjU3NTZDMTAuOTc4MSAxMi43MTA2IDEwLjgyNTQgMTIuODE3MyAxMC42NTIgMTIuODk0OUMxMC40NzYyIDEyLjk3NTcgMTAuMjg4OSAxMy4wMTY0IDEwLjA4OTIgMTMuMDE2NEgxMFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.property:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.property:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTIuODA3MjMgMTQuOTc1NEMyLjU3MTE5IDE0Ljk3MjEgMi4zMzgyNiAxNC45MjExIDIuMTIyNDcgMTQuODI1NEMxLjkwNjY3IDE0LjcyOTcgMS43MTI0OCAxNC41OTEzIDEuNTUxNTggMTQuNDE4NkMxLjIzODUgMTQuMTMzNCAxLjA0NDMzIDEzLjc0MDggMS4wMDc3NSAxMy4zMTg5QzAuOTY2MjI1IDEyLjg4MjggMS4wOTI2OSAxMi40NDczIDEuMzYxMzMgMTIuMTAxM0MyLjU2Nzc5IDEwLjgyODkgNC45NDczIDguNDQ5NCA2LjY3ODExIDYuNzU0NzlDNi4zMDk4MyA1Ljc1ODg3IDYuMzI3MDQgNC42NjEyNyA2LjcyNjM3IDMuNjc3MzlDNy4wNTQ3NCAyLjg1ODc2IDcuNjM4NjkgMi4xNjgwNSA4LjM5MTI5IDEuNzA4MDdDOC45ODE3IDEuMzE3MDYgOS42NjAzMSAxLjA3OTQ0IDEwLjM2NTcgMS4wMTY3M0MxMS4wNzExIDAuOTU0MDIyIDExLjc4MDkgMS4wNjgxOSAxMi40MzExIDEuMzQ4OTJMMTMuMDQ4MiAxLjYxNjJMMTAuMTgyNCA0LjU2NzM4TDExLjQzNzEgNS44MjU4MkwxNC4zODA5IDIuOTQ4ODdMMTQuNjQ4MiAzLjU2Nzg4QzE0Ljg3MzUgNC4wODk3NiAxNC45OTMgNC42NTExOSAxNC45OTk3IDUuMjE5NjFDMTUuMDA2NCA1Ljc4ODAyIDE0LjkwMDIgNi4zNTIxMSAxNC42ODcyIDYuODc5MTVDMTQuNDc2IDcuNDAwMjkgMTQuMTYyMyA3Ljg3MzY4IDEzLjc2NDcgOC4yNzEyMkMxMy41Mzk0IDguNDkxNjkgMTMuMjkwNCA4LjY4NjUzIDEzLjAyMjIgOC44NTIxOEMxMi40NjczIDkuMjIyNzUgMTEuODMyNCA5LjQ1NjM2IDExLjE2OTcgOS41MzM4QzEwLjUwNjkgOS42MTEyNCA5LjgzNTIxIDkuNTMwMyA5LjIwOTgyIDkuMjk3NjRDOC4xMTE5NCAxMC40MTEzIDUuMzcxNDIgMTMuMTcwNCAzLjg5MTE5IDE0LjU1MjJDMy41OTQyNiAxNC44MjE5IDMuMjA4MzIgMTQuOTcyNiAyLjgwNzIzIDE0Ljk3NTRaTTEwLjc0NDggMS45MjgwMkMxMC4wODcgMS45MjYzNyA5LjQ0MzU5IDIuMTIwMTggOC44OTYxNCAyLjQ4NDg1QzguNjgyNjUgMi42MTUyIDguNDg0MzcgMi43Njg5NyA4LjMwNDk4IDIuOTQzM0M3LjgyNzg5IDMuNDI0MjMgNy41MDkyNiA0LjAzOTUzIDcuMzkxODIgNC43MDY2OUM3LjI3NDM3IDUuMzczODUgNy4zNjM3NCA2LjA2MDk4IDcuNjQ3OTIgNi42NzU5MUw3Ljc4MzQyIDYuOTcyODhMNy41NTA0OCA3LjIwMDI1QzUuODEyMjQgOC44OTY3MiAzLjI4MTQ2IDExLjQyMDEgMi4wNjQ3OSAxMi43MDQ1QzEuOTU2NDYgMTIuODY1OCAxLjkxMDEyIDEzLjA2MDggMS45MzQzNSAxMy4yNTM1QzEuOTU4NTcgMTMuNDQ2MyAyLjA1MTcxIDEzLjYyMzggMi4xOTY1NyAxMy43NTMyQzIuMjgwMDUgMTMuODQ2MiAyLjM4MTc3IDEzLjkyMTEgMi40OTU0MSAxMy45NzMxQzIuNTk1NTcgMTQuMDE4NCAyLjcwMzgzIDE0LjA0MyAyLjgxMzczIDE0LjA0NTVDMi45ODA2NCAxNC4wNDEzIDMuMTQwNDQgMTMuOTc3IDMuMjYzODMgMTMuODY0NkM0LjgzNjg3IDEyLjM5NjQgNy44NzYyMiA5LjMyNjQxIDguNzY4MDcgOC40MjQzNUw4Ljk5NzMgOC4xOTMyNkw5LjI5MjQyIDguMzI3ODNDOS44MDYxOCA4LjU2NzMyIDEwLjM3MzEgOC42Njk4NSAxMC45MzgyIDguNjI1NDVDMTEuNTAzMyA4LjU4MTA2IDEyLjA0NzMgOC4zOTEyNSAxMi41MTc0IDguMDc0NDdDMTIuNzMxMyA3Ljk0MjYgMTIuOTI5NiA3Ljc4Njk0IDEzLjEwODUgNy42MTA0NUMxMy40MTgzIDcuMzAxNTMgMTMuNjYzMSA2LjkzMzc0IDEzLjgyODYgNi41Mjg3NEMxMy45OTQgNi4xMjM3NSAxNC4wNzY3IDUuNjg5NzQgMTQuMDcxOSA1LjI1MjI4QzE0LjA3MTkgNS4wMzY2MiAxNC4wNTA1IDQuODIxNDggMTQuMDA3OCA0LjYxMDA3TDExLjQzMDYgNy4xMjUwOEw4Ljg3OTQ0IDQuNTc3NTlMMTEuMzk0NCAxLjk4ODM0QzExLjE4MDQgMS45NDY3NCAxMC45NjI4IDEuOTI2NTMgMTAuNzQ0OCAxLjkyODAyWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.unit:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.unit:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDFMMyAyVjE0TDQgMTVIMTJMMTMgMTRWMkwxMiAxSDRaTTQgM1YySDEyVjE0SDRWMTNINlYxMkg0VjEwSDhWOUg0VjdINlY2SDRWNEg4VjNINFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.constant:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.constant:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDZIMTJWN0g0VjZaTTEyIDlINFYxMEgxMlY5WiIgZmlsbD0iI0M1QzVDNSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEgNEwyIDNIMTRMMTUgNFYxMkwxNCAxM0gyTDEgMTJWNFpNMiA0VjEySDE0VjRIMloiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.enum:before,.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.value:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.enum:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.value:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04IDJMNyAzVjZIOFYzSDE0VjhIMTBWOUgxNEwxNSA4VjNMMTQgMkg4Wk05IDhMOCA3SDdIMkwxIDhWMTNMMiAxNEg4TDkgMTNWOVY4Wk04IDlWOEg3SDJWMTNIOFY5Wk05IDYuNTg1NzlMOS40MTQyMSA3SDEzVjZIOVY2LjU4NTc5Wk0xMyA0SDlWNUgxM1Y0Wk03IDlIM1YxMEg3VjlaTTMgMTFIN1YxMkgzVjExWiIgZmlsbD0iI0VFOUQyOCIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.enum-member:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.enum-member:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDNMOCAySDE0TDE1IDNWOEwxNCA5SDEwVjhIMTRWM0g4VjZIN1YzWk04IDdMOSA4VjlWMTNMOCAxNEgyTDEgMTNWOEwyIDdIN0g4Wk04IDhWOVYxM0gyVjhIN0g4Wk05LjQxNDIxIDdMOSA2LjU4NTc5VjZIMTNWN0g5LjQxNDIxWk05IDRIMTNWNUg5VjRaTTcgMTBIM1YxMUg3VjEwWiIgZmlsbD0iIzc1QkVGRiIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.keyword:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.keyword:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE1IDRIMTBWM0gxNVY0Wk0xNCA3SDEyVjhIMTRWN1pNMTAgN0gxVjhIMTBWN1pNMTIgMTNIMVYxNEgxMlYxM1pNNyAxMEgxVjExSDdWMTBaTTE1IDEwSDEwVjExSDE1VjEwWk04IDJWNUgxVjJIOFpNNyAzSDJWNEg3VjNaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.text:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.text:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03LjIyMjg5IDEwLjkzM0M3LjU0ODYzIDExLjEyNTQgNy45MjE2MyAxMS4yMjMxIDguMjk5ODkgMTEuMjE1QzguNjM3NzcgMTEuMjIxOCA4Ljk3MjU0IDExLjE0OTIgOS4yNzcyMSAxMS4wMDNDOS41ODE4OCAxMC44NTY3IDkuODQ3OTIgMTAuNjQwOSAxMC4wNTM5IDEwLjM3M0MxMC41MDkxIDkuNzY1MTkgMTAuNzQwMiA5LjAxODY3IDEwLjcwNzkgOC4yNTk5OEMxMC43NDEyIDcuNTg2MjIgMTAuNTM3NCA2LjkyMjEgMTAuMTMxOSA2LjM4Mjk4QzkuOTM1NzUgNi4xNDE2MSA5LjY4NTc3IDUuOTQ5NTcgOS40MDIgNS44MjIyOEM5LjExODI0IDUuNjk0OTggOC44MDg1OCA1LjYzNTk3IDguNDk3ODkgNS42NDk5N0M4LjA3NTIyIDUuNjQ2OTkgNy42NTk5NCA1Ljc2MDg1IDcuMjk3ODkgNS45Nzg5OEM3LjE4MzA0IDYuMDQ4MDcgNy4wNzQ5IDYuMTI3NzUgNi45NzQ4OSA2LjIxNjk4VjMuNDc0OThINS45ODM4OVYxMS4xSDYuOTc4ODlWMTAuNzU2QzcuMDU1MTYgMTAuODIxNyA3LjEzNjc3IDEwLjg4MDkgNy4yMjI4OSAxMC45MzNaTTcuODQ5ODEgNi43MDAwNkM4LjAzNTk4IDYuNjIxMDUgOC4yMzgwNyA2LjU4Njc3IDguNDM5ODkgNi41OTk5OEM4LjYxMjU3IDYuNTk0NTIgOC43ODQwNCA2LjYzMDU0IDguOTM5OTQgNi43MDUwMUM5LjA5NTgzIDYuNzc5NDggOS4yMzE2MSA2Ljg5MDIzIDkuMzM1ODkgNy4wMjc5OEM5LjU5MjUzIDcuMzkwNTMgOS43MTg0IDcuODI5NTEgOS42OTI4OSA4LjI3Mjk3QzkuNzE5NzIgOC43OTc0OCA5LjU3OTY5IDkuMzE3MDEgOS4yOTI4OSA5Ljc1Njk4QzkuMTg4MjIgOS45MTUyNyA5LjA0NTQ2IDEwLjA0NDcgOC44Nzc3MyAxMC4xMzM1QzguNzA5OTkgMTAuMjIyMyA4LjUyMjY0IDEwLjI2NzUgOC4zMzI4OSAxMC4yNjVDOC4xNDkzNCAxMC4yNzMyIDcuOTY2MyAxMC4yNCA3Ljc5NzM0IDEwLjE2NzhDNy42MjgzOCAxMC4wOTU2IDcuNDc3ODQgOS45ODYyOCA3LjM1Njg5IDkuODQ3OTdDNy4xMDE1MiA5LjU1OTU3IDYuOTY1MDEgOS4xODUwNiA2Ljk3NDg5IDguNzk5OThWOC4xOTk5OEM2Ljk2Mjk5IDcuNzgzMzIgNy4xMDI2MyA3LjM3NjUgNy4zNjc4OSA3LjA1NDk4QzcuNDk4NTggNi45MDA2NCA3LjY2MzY0IDYuNzc5MDggNy44NDk4MSA2LjcwMDA2Wk0zLjI4OTAyIDUuNjc0OTlDMi45NzAxMSA1LjY3OTMzIDIuNjUzODggNS43MzQgMi4zNTIwMiA1LjgzNjk5QzIuMDY0MTcgNS45MjI5MyAxLjc5MzQ3IDYuMDU4MjggMS41NTIwMiA2LjIzNjk5TDEuNDUyMDIgNi4zMTM5OVY3LjUxMzk5TDEuODc1MDIgNy4xNTQ5OUMyLjI0NTc5IDYuODA0NzggMi43MzEzMyA2LjYwMTQ2IDMuMjQxMDIgNi41ODI5OUMzLjM2NTkzIDYuNTcxNjQgMy40OTE3IDYuNTkxNDcgMy42MDcwNiA2LjY0MDY4QzMuNzIyNDMgNi42ODk5IDMuODIzNzcgNi43NjY5NyAzLjkwMjAyIDYuODY0OTlDNC4wNTIyIDcuMDk3MSA0LjEzMjM5IDcuMzY3NTQgNC4xMzMwMiA3LjY0Mzk5TDIuOTAwMDIgNy44MjQ5OUMyLjM5NDM1IDcuODc3ODEgMS45MTUyNSA4LjA3NzcyIDEuNTIyMDIgOC4zOTk5OUMxLjM2Njk3IDguNTUxODEgMS4yNDMzOSA4LjczMjcxIDEuMTU4MzUgOC45MzIzNUMxLjA3MzMxIDkuMTMxOTkgMS4wMjg0OCA5LjM0NjQ0IDEuMDI2NDQgOS41NjM0M0MxLjAyNDQgOS43ODA0MiAxLjA2NTE3IDkuOTk1NjggMS4xNDY0NCAxMC4xOTY5QzEuMjI3NyAxMC4zOTgxIDEuMzQ3ODYgMTAuNTgxMyAxLjUwMDAyIDEwLjczNkMxLjY2ODcgMTAuODkwNCAxLjg2NjIyIDExLjAxIDIuMDgxMjUgMTEuMDg3OUMyLjI5NjI3IDExLjE2NTkgMi41MjQ1NiAxMS4yMDA1IDIuNzUzMDIgMTEuMTlDMy4xNDcgMTEuMTkzMSAzLjUzMjc4IDExLjA3NzQgMy44NjAwMiAxMC44NThDMy45NjE1MyAxMC43ODk3IDQuMDU3MiAxMC43MTMxIDQuMTQ2MDIgMTAuNjI5VjExLjA3M0g1LjA4NzAyVjcuNzE0OTlDNS4xMjEzNyA3LjE3NDIyIDQuOTU0MyA2LjYzOTg4IDQuNjE4MDIgNi4yMTQ5OUM0LjQ0OTc5IDYuMDMyODUgNC4yNDM0OCA1Ljg5MDAzIDQuMDEzNzggNS43OTY3QzMuNzg0MDcgNS43MDMzNiAzLjUzNjYxIDUuNjYxODEgMy4yODkwMiA1LjY3NDk5Wk00LjE0NjAyIDguNzE1OTlDNC4xNjU2NCA5LjEzNDM1IDQuMDI1OTIgOS41NDQ1OSAzLjc1NTAyIDkuODY0QzMuNjM2ODkgMTAuMDAwNSAzLjQ4OTk4IDEwLjEwOTIgMy4zMjQ4NiAxMC4xODIxQzMuMTU5NzMgMTAuMjU1MSAyLjk4MDQ5IDEwLjI5MDYgMi44MDAwMiAxMC4yODZDMi42OTA0OSAxMC4yOTQ1IDIuNTgwMzUgMTAuMjgxMiAyLjQ3NTk5IDEwLjI0NjlDMi4zNzE2MyAxMC4yMTI1IDIuMjc1MTEgMTAuMTU3OSAyLjE5MjAyIDEwLjA4NkMyLjA2MDc5IDkuOTM0NTUgMS45ODg1NiA5Ljc0MDg4IDEuOTg4NTYgOS41NDA0OUMxLjk4ODU2IDkuMzQwMTEgMi4wNjA3OSA5LjE0NjQ0IDIuMTkyMDIgOC45OTQ5OUMyLjQ3MzIyIDguODIxMzEgMi43OTIzMyA4LjcxODM3IDMuMTIyMDIgOC42OTQ5OUw0LjE0MjAyIDguNTQ2OTlMNC4xNDYwMiA4LjcxNTk5Wk0xMi40NTg4IDExLjAzMjVDMTIuNzY2IDExLjE2MzggMTMuMDk4MyAxMS4yMjYxIDEzLjQzMjIgMTEuMjE1QzEzLjkyNyAxMS4yMjcgMTQuNDE1MyAxMS4xMDA2IDE0Ljg0MjIgMTAuODVMMTQuOTY1MiAxMC43NzVMMTQuOTc4MiAxMC43NjhWOS42MTUwNEwxNC41MzIyIDkuOTM1MDRDMTQuMjE2IDEwLjE1OTIgMTMuODM1NiAxMC4yNzQ3IDEzLjQ0ODIgMTAuMjY0QzEzLjI0OTcgMTAuMjcxOSAxMy4wNTIgMTAuMjM0MiAxMi44NzAzIDEwLjE1MzhDMTIuNjg4NiAxMC4wNzMzIDEyLjUyNzggOS45NTIzMiAxMi40MDAyIDkuODAwMDRDMTIuMTE0NCA5LjQyNDUzIDExLjk3MjUgOC45NTkxMSAxMi4wMDAyIDguNDg4MDRDMTEuOTczNyA3Ljk4NzMyIDEyLjEzNTIgNy40OTQ3NSAxMi40NTMyIDcuMTA3MDRDMTIuNTkzNCA2Ljk0MTA1IDEyLjc2OTUgNi44MDkxNCAxMi45NjgyIDYuNzIxM0MxMy4xNjcgNi42MzM0NiAxMy4zODMxIDYuNTkyIDEzLjYwMDIgNi42MDAwNEMxMy45NDM5IDYuNTk4NDQgMTQuMjgwOCA2LjY5NTI1IDE0LjU3MTIgNi44NzkwNEwxNS4wMDAyIDcuMTQ0MDRWNS45NzAwNEwxNC44MzEyIDUuODk3MDRDMTQuNDYyNiA1LjczNDMyIDE0LjA2NDEgNS42NTAyIDEzLjY2MTIgNS42NTAwNEMxMy4yOTk5IDUuNjM5OTEgMTIuOTQwNiA1LjcwNzYyIDEyLjYwNzggNS44NDg1OUMxMi4yNzQ5IDUuOTg5NTYgMTEuOTc2MyA2LjIwMDQ4IDExLjczMjIgNi40NjcwNEMxMS4yMjYxIDcuMDI2ODMgMTAuOTU4MSA3Ljc2MTg2IDEwLjk4NTIgOC41MTYwNEMxMC45NTY3IDkuMjIzNDYgMTEuMTk1NSA5LjkxNTY5IDExLjY1NDIgMTAuNDU1QzExLjg3NjkgMTAuNzA0IDEyLjE1MTYgMTAuOTAxMiAxMi40NTg4IDExLjAzMjVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.color:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.color:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02LjYgMTEuNzY3M0M3LjMyODcxIDExLjAzODMgNy4zMjg3MSA5Ljg1NjM4IDYuNiA5LjEyNzQyQzUuODcwODMgOC4zOTg0NSA0LjY4OTEzIDguMzk4NDUgMy45NTk5NiA5LjEyNzQyQzIuOTE4MTIgMTAuMjI0OSAxLjEwNDExIDkuOTM5MDEgMS4wMTI5IDguNDI4NTNDMS4wMDQzNCA4LjI4Njc5IDEgOC4xNDM5IDEgOEMxIDQuMTMzOTkgNC4xMzQwNSAxIDggMUMxMS44NjYgMSAxNSA0LjEzMzk5IDE1IDhDMTUgMTEuODY2IDExLjg2NiAxNSA4IDE1QzcuNzk3NzQgMTUgNy41OTc0OSAxNC45OTE0IDcuMzk5NTkgMTQuOTc0NkM1LjgwNjQ2IDE0LjgzOTMgNS40OTg2IDEyLjkyNjMgNi42IDExLjc2NzNaTTYuOTY2NzUgMTMuNTQzNEM2LjkwMjUxIDEzLjI0NjQgNi45ODgyMSAxMi44MTUgNy4zMTgxOSAxMi40NjMyQzguNDI2MjkgMTEuMzQyOSA4LjQyMjY0IDkuNTM2MjMgNy4zMDcyMyA4LjQyMDQzTDcuMzA3MDEgOC40MjAyMUM2LjE4NzM0IDcuMzAwODUgNC4zNzI2MiA3LjMwMDg1IDMuMjUyOTUgOC40MjAyMUwzLjI0MzcxIDguNDI5NDVMMy4yMzQ3MSA4LjQzODkzQzIuOTM5MDMgOC43NTA0IDIuNTcwOTEgOC44MjU5OSAyLjMzMjUgOC43NzY2OEMyLjIxOTM2IDguNzUzMjggMi4xNTAyMSA4LjcwNjY3IDIuMTA5NzkgOC42NjE2MUMyLjA3MzkzIDguNjIxNjIgMi4wMjE0NiA4LjU0MDE2IDIuMDExMDggOC4zNjgyNkMyLjAwMzczIDguMjQ2NTYgMiA4LjEyMzc4IDIgOEMyIDQuNjg2MjggNC42ODYzMyAyIDggMkMxMS4zMTM3IDIgMTQgNC42ODYyOCAxNCA4QzE0IDExLjMxMzcgMTEuMzEzNyAxNCA4IDE0QzcuODI2MDIgMTQgNy42NTQgMTMuOTkyNiA3LjQ4NDIxIDEzLjk3ODJDNy4yODk5MiAxMy45NjE3IDcuMTg0ODggMTMuODk4NyA3LjEyNDE0IDEzLjg0MjlDNy4wNTgzMSAxMy43ODI0IDYuOTk3NjcgMTMuNjg2NCA2Ljk2Njc1IDEzLjU0MzRaTTUgNkM1LjU1MjI4IDYgNiA1LjU1MjI4IDYgNUM2IDQuNDQ3NzIgNS41NTIyOCA0IDUgNEM0LjQ0NzcyIDQgNCA0LjQ0NzcyIDQgNUM0IDUuNTUyMjggNC40NDc3MiA2IDUgNlpNMTIgMTFDMTIgMTEuNTUyMyAxMS41NTIzIDEyIDExIDEyQzEwLjQ0NzcgMTIgMTAgMTEuNTUyMyAxMCAxMUMxMCAxMC40NDc3IDEwLjQ0NzcgMTAgMTEgMTBDMTEuNTUyMyAxMCAxMiAxMC40NDc3IDEyIDExWk04IDVDOC41NTIyOCA1IDkgNC41NTIyOCA5IDRDOSAzLjQ0NzcyIDguNTUyMjggMyA4IDNDNy40NDc3MiAzIDcgMy40NDc3MiA3IDRDNyA0LjU1MjI4IDcuNDQ3NzIgNSA4IDVaTTEzIDhDMTMgOC41NTIyOCAxMi41NTIzIDkgMTIgOUMxMS40NDc3IDkgMTEgOC41NTIyOCAxMSA4QzExIDcuNDQ3NzIgMTEuNDQ3NyA3IDEyIDdDMTIuNTUyMyA3IDEzIDcuNDQ3NzIgMTMgOFpNMTEgNkMxMS41NTIzIDYgMTIgNS41NTIyOCAxMiA1QzEyIDQuNDQ3NzIgMTEuNTUyMyA0IDExIDRDMTAuNDQ3NyA0IDEwIDQuNDQ3NzIgMTAgNUMxMCA1LjU1MjI4IDEwLjQ0NzcgNiAxMSA2WiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.file:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.file:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00IDFMMyAyVjE0TDQgMTVIMTNMMTQgMTRWNUwxMy43MDcxIDQuMjkyODlMMTAuNzA3MSAxLjI5Mjg5TDEwIDFINFpNNCAxNFYyTDkgMlY2SDEzVjE0SDRaTTEzIDVMMTAgMlY1TDEzIDVaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.reference:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.reference:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjA2MDY1IDMuODUzNTZMNS45MTQyMSA2TDUuMjA3MSA1LjI5Mjg5TDYuNDk5OTkgNEgzLjVDMy4xMDIxOCA0IDIuNzIwNjQgNC4xNTgwNCAyLjQzOTM0IDQuNDM5MzRDMi4xNTgwNCA0LjcyMDY1IDIgNS4xMDIxOCAyIDUuNUMyIDUuODk3ODMgMi4xNTgwNCA2LjI3OTM2IDIuNDM5MzQgNi41NjA2NkMyLjcyMDY0IDYuODQxOTcgMy4xMDIxOCA3IDMuNSA3SDRWOEgzLjVDMi44MzY5NiA4IDIuMjAxMDcgNy43MzY2MSAxLjczMjIzIDcuMjY3NzdDMS4yNjMzOSA2Ljc5ODkzIDEgNi4xNjMwNSAxIDUuNUMxIDQuODM2OTYgMS4yNjMzOSA0LjIwMTA4IDEuNzMyMjMgMy43MzIyNEMyLjIwMTA3IDMuMjYzNCAyLjgzNjk2IDMgMy41IDNINi40OTk5OUw2LjQ5OTk5IDNINi40OTk5Nkw2IDIuNTAwMDRWMi41MDAwMUw1LjIwNzEgMS43MDcxMUw1LjkxNDIxIDFMOC4wNjA2NSAzLjE0NjQ1TDguMDYwNjUgMy44NTM1NlpNNSA2LjUwMDAzTDUuOTE0MjEgNy40MTQyNEw2IDcuMzI4NDVWMTRIMTRWN0gxMFYzSDkuMDYwNjVWMi43MzIyN0w4LjMyODM4IDJIMTEuMkwxMS41IDIuMUwxNC45IDUuNkwxNSA2VjE0LjVMMTQuNSAxNUg1LjVMNSAxNC41VjkuMDAwMDNWNi41MDAwM1pNMTEgM1Y2SDEzLjkwMzJMMTEgM1oiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.snippet:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.snippet:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0yLjUgMUwyIDEuNVYxM0gzVjJIMTRWMTNIMTVWMS41TDE0LjUgMUgyLjVaTTIgMTVWMTRIM1YxNUgyWk01IDE0LjAwMDFINFYxNS4wMDAxSDVWMTQuMDAwMVpNNiAxNC4wMDAxSDdWMTUuMDAwMUg2VjE0LjAwMDFaTTkgMTQuMDAwMUg4VjE1LjAwMDFIOVYxNC4wMDAxWk0xMCAxNC4wMDAxSDExVjE1LjAwMDFIMTBWMTQuMDAwMVpNMTUgMTUuMDAwMVYxNC4wMDAxSDE0VjE1LjAwMDFIMTVaTTEyIDE0LjAwMDFIMTNWMTUuMDAwMUgxMlYxNC4wMDAxWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.customcolor:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.customcolor:before{background-image:none}.monaco-editor.hc-black .suggest-widget .monaco-list .monaco-list-row .suggest-icon.folder:before,.monaco-editor.vs-dark .suggest-widget .monaco-list .monaco-list-row .suggest-icon.folder:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xLjAxMDg3IDIuNUwxLjUxMDg3IDJINi41MDcxM0w2Ljg2MDY4IDIuMTQ2NDVMNy43MTM0OSAyLjk5OTI1SDE0LjUwMTFMMTUuMDAxMSAzLjQ5OTI1VjguOTk1MTJMMTQuOTkwMyA5LjAwNTk5VjEzLjUwMjFMMTQuNDkwMyAxNC4wMDIxSDEuNUwxIDEzLjUwMjFWNi41MDczNUwxLjAxMDg3IDYuNDk2NDhWMi41Wk0xNC4wMDExIDMuOTk5MjVWNS4wMDMxMUg3LjUwMDVMNy4xNDY5NSA1LjE0OTU2TDYuMjg5MTUgNi4wMDczNUgyLjAxMDg3VjNINi4zMDAwMkw3LjE1MjgzIDMuODUyOEw3LjUwNjM4IDMuOTk5MjVIMTQuMDAxMVpNNi40OTYyNiA3LjAwNzM1SDIuMDEwODdWNy40OTU4OEgxLjk5OTYzVjExLjQ5MjlIMlYxMy4wMDIxSDEzLjk5MDNWMTEuNDkyOUgxMy45OTA2VjcuNDk1ODhIMTMuOTkwM1Y2LjAwMzExSDcuNzA3NjFMNi44NDk4MSA2Ljg2MDlMNi40OTYyNiA3LjAwNzM1WiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K")}.monaco-editor{font-family:-apple-system,BlinkMacSystemFont,Segoe WPC,Segoe UI,HelveticaNeue-Light,Ubuntu,Droid Sans,sans-serif}.monaco-editor.hc-black .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,.monaco-menu .monaco-action-bar.vertical .action-item .action-menu-item:focus .action-label{stroke-width:1.2px}.monaco-editor-hover p{margin:0}.monaco-editor.hc-black{-ms-high-contrast-adjust:none}@media screen and (-ms-high-contrast:active){.monaco-editor.vs-dark .view-overlays .current-line,.monaco-editor.vs .view-overlays .current-line{border-color:windowtext!important;border-left:0;border-right:0}.monaco-editor.vs-dark .cursor,.monaco-editor.vs .cursor{background-color:windowtext!important}.monaco-editor.vs-dark .dnd-target,.monaco-editor.vs .dnd-target{border-color:windowtext!important}.monaco-editor.vs-dark .selected-text,.monaco-editor.vs .selected-text{background-color:highlight!important}.monaco-editor.vs-dark .view-line,.monaco-editor.vs .view-line{-ms-high-contrast-adjust:none}.monaco-editor.vs-dark .view-line span,.monaco-editor.vs .view-line span{color:windowtext!important}.monaco-editor.vs-dark .view-line span.inline-selected-text,.monaco-editor.vs .view-line span.inline-selected-text{color:highlighttext!important}.monaco-editor.vs-dark .view-overlays,.monaco-editor.vs .view-overlays{-ms-high-contrast-adjust:none}.monaco-editor.vs-dark .reference-decoration,.monaco-editor.vs-dark .selectionHighlight,.monaco-editor.vs-dark .wordHighlight,.monaco-editor.vs-dark .wordHighlightStrong,.monaco-editor.vs .reference-decoration,.monaco-editor.vs .selectionHighlight,.monaco-editor.vs .wordHighlight,.monaco-editor.vs .wordHighlightStrong{border:2px dotted highlight!important;background:transparent!important;box-sizing:border-box}.monaco-editor.vs-dark .rangeHighlight,.monaco-editor.vs .rangeHighlight{background:transparent!important;border:1px dotted activeborder!important;box-sizing:border-box}.monaco-editor.vs-dark .bracket-match,.monaco-editor.vs .bracket-match{border-color:windowtext!important;background:transparent!important}.monaco-editor.vs-dark .currentFindMatch,.monaco-editor.vs-dark .findMatch,.monaco-editor.vs .currentFindMatch,.monaco-editor.vs .findMatch{border:2px dotted activeborder!important;background:transparent!important;box-sizing:border-box}.monaco-editor.vs-dark .find-widget,.monaco-editor.vs .find-widget{border:1px solid windowtext}.monaco-editor.vs-dark .monaco-list .monaco-list-row,.monaco-editor.vs .monaco-list .monaco-list-row{-ms-high-contrast-adjust:none;color:windowtext!important}.monaco-editor.vs-dark .monaco-list .monaco-list-row.focused,.monaco-editor.vs .monaco-list .monaco-list-row.focused{color:highlighttext!important;background-color:highlight!important}.monaco-editor.vs-dark .monaco-list .monaco-list-row:hover,.monaco-editor.vs .monaco-list .monaco-list-row:hover{background:transparent!important;border:1px solid highlight;box-sizing:border-box}.monaco-editor.vs-dark .monaco-tree .monaco-tree-row,.monaco-editor.vs .monaco-tree .monaco-tree-row{-ms-high-contrast-adjust:none;color:windowtext!important}.monaco-editor.vs-dark .monaco-tree .monaco-tree-row.focused,.monaco-editor.vs-dark .monaco-tree .monaco-tree-row.selected,.monaco-editor.vs .monaco-tree .monaco-tree-row.focused,.monaco-editor.vs .monaco-tree .monaco-tree-row.selected{color:highlighttext!important;background-color:highlight!important}.monaco-editor.vs-dark .monaco-tree .monaco-tree-row:hover,.monaco-editor.vs .monaco-tree .monaco-tree-row:hover{background:transparent!important;border:1px solid highlight;box-sizing:border-box}.monaco-editor.vs-dark .monaco-scrollable-element>.scrollbar,.monaco-editor.vs .monaco-scrollable-element>.scrollbar{-ms-high-contrast-adjust:none;background:background!important;border:1px solid windowtext;box-sizing:border-box}.monaco-editor.vs-dark .monaco-scrollable-element>.scrollbar>.slider,.monaco-editor.vs .monaco-scrollable-element>.scrollbar>.slider{background:windowtext!important}.monaco-editor.vs-dark .monaco-scrollable-element>.scrollbar>.slider.active,.monaco-editor.vs-dark .monaco-scrollable-element>.scrollbar>.slider:hover,.monaco-editor.vs .monaco-scrollable-element>.scrollbar>.slider.active,.monaco-editor.vs .monaco-scrollable-element>.scrollbar>.slider:hover{background:highlight!important}.monaco-editor.vs-dark .decorationsOverviewRuler,.monaco-editor.vs .decorationsOverviewRuler{opacity:0}.monaco-editor.vs-dark .minimap,.monaco-editor.vs .minimap{display:none}.monaco-editor.vs-dark .squiggly-d-error,.monaco-editor.vs .squiggly-d-error{background:transparent!important;border-bottom:4px double #e47777}.monaco-editor.vs-dark .squiggly-b-info,.monaco-editor.vs-dark .squiggly-c-warning,.monaco-editor.vs .squiggly-b-info,.monaco-editor.vs .squiggly-c-warning{border-bottom:4px double #71b771}.monaco-editor.vs-dark .squiggly-a-hint,.monaco-editor.vs .squiggly-a-hint{border-bottom:4px double #6c6c6c}.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label{-ms-high-contrast-adjust:none;color:highlighttext!important;background-color:highlight!important}.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label,.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label{-ms-high-contrast-adjust:none;background:transparent!important;border:1px solid highlight;box-sizing:border-box}.monaco-diff-editor.vs-dark .diffOverviewRuler,.monaco-diff-editor.vs .diffOverviewRuler{display:none}.monaco-editor.vs-dark .line-delete,.monaco-editor.vs-dark .line-insert,.monaco-editor.vs .line-delete,.monaco-editor.vs .line-insert{background:transparent!important;border:1px solid highlight!important;box-sizing:border-box}.monaco-editor.vs-dark .char-delete,.monaco-editor.vs-dark .char-insert,.monaco-editor.vs .char-delete,.monaco-editor.vs .char-insert{background:transparent!important}}.monaco-diff-editor .diffOverview{z-index:9}.monaco-diff-editor.vs .diffOverview{background:rgba(0,0,0,.03)}.monaco-diff-editor.vs-dark .diffOverview{background:hsla(0,0%,100%,.01)}.monaco-diff-editor .diffViewport{box-shadow:inset 0 0 1px 0 #b9b9b9;background:rgba(0,0,0,.1)}.monaco-diff-editor.hc-black .diffViewport,.monaco-diff-editor.vs-dark .diffViewport{background:hsla(0,0%,100%,.1)}.monaco-scrollable-element.modified-in-monaco-diff-editor.vs-dark .scrollbar,.monaco-scrollable-element.modified-in-monaco-diff-editor.vs .scrollbar{background:transparent}.monaco-scrollable-element.modified-in-monaco-diff-editor.hc-black .scrollbar{background:none}.monaco-scrollable-element.modified-in-monaco-diff-editor .slider{z-index:10}.modified-in-monaco-diff-editor .slider.active{background:hsla(0,0%,67%,.4)}.modified-in-monaco-diff-editor.hc-black .slider.active{background:none}.monaco-diff-editor .delete-sign,.monaco-diff-editor .insert-sign,.monaco-editor .delete-sign,.monaco-editor .insert-sign{background-size:60%;opacity:.7;background-repeat:no-repeat;background-position:75%;background-size:11px 11px}.monaco-diff-editor.hc-black .delete-sign,.monaco-diff-editor.hc-black .insert-sign,.monaco-editor.hc-black .delete-sign,.monaco-editor.hc-black .insert-sign{opacity:1}.monaco-diff-editor .insert-sign,.monaco-editor .insert-sign{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE0IDdWOEg4VjE0SDdWOEgxVjdIN1YxSDhWN0gxNFoiIGZpbGw9IiM0MjQyNDIiLz4KPC9zdmc+Cg==")}.monaco-diff-editor .delete-sign,.monaco-editor .delete-sign{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE1IDhIMVY3SDE1VjhaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=")}.monaco-diff-editor.hc-black .insert-sign,.monaco-diff-editor.vs-dark .insert-sign,.monaco-editor.hc-black .insert-sign,.monaco-editor.vs-dark .insert-sign{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE0IDdWOEg4VjE0SDdWOEgxVjdIN1YxSDhWN0gxNFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==")}.monaco-diff-editor.hc-black .delete-sign,.monaco-diff-editor.vs-dark .delete-sign,.monaco-editor.hc-black .delete-sign,.monaco-editor.vs-dark .delete-sign{background-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTE1IDhIMVY3SDE1VjhaIiBmaWxsPSIjQzVDNUM1Ii8+Cjwvc3ZnPgo=")}.monaco-editor .inline-added-margin-view-zone,.monaco-editor .inline-deleted-margin-view-zone{text-align:right}.monaco-editor .diagonal-fill{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAChJREFUKFNjOH/+fAMDDgCSu3Dhwn9c8gwwBTgNGR4KQP4HhQOhsAIAZCBTkhtqePcAAAAASUVORK5CYII=")}.monaco-editor.vs-dark .diagonal-fill{opacity:.2}.monaco-editor.hc-black .diagonal-fill{background:none}.monaco-editor .view-zones .view-lines .view-line span{display:inline-block}.monaco-editor .margin-view-zones .inline-deleted-margin-view-zone .lightbulb-glyph{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS42NzA4IDguNjU4MDZDMTEuMzMxOSA4Ljk5MTYgMTEuMDcxNiA5LjM2Mjc4IDEwLjg4ODYgOS43NzE3MkMxMC43MTA1IDEwLjE3OTIgMTAuNjIxIDEwLjYyMTkgMTAuNjIxIDExLjEwMDlWMTIuNzAxMkMxMC42MjEgMTIuODgwNyAxMC41ODcyIDEzLjA1MDMgMTAuNTE4OSAxMy4yMDkxQzEwLjQ1MTMgMTMuMzY2MSAxMC4zNTg2IDEzLjUwMzggMTAuMjQwNyAxMy42MjEzQzEwLjEyMjggMTMuNzM4OCA5Ljk4NDY0IDEzLjgzMTEgOS44MjcyMyAxMy44OTg0QzkuNjY4MDYgMTMuOTY2MyA5LjQ5ODA2IDE0IDkuMzE4MjMgMTRINy43MTIwNUM3LjUzMjIzIDE0IDcuMzYyMjMgMTMuOTY2MyA3LjIwMzA2IDEzLjg5ODRDNy4wNDU2NCAxMy44MzExIDYuOTA3NTMgMTMuNzM4OCA2Ljc4OTYxIDEzLjYyMTNDNi42NzE2OCAxMy41MDM4IDYuNTc4OTUgMTMuMzY2MSA2LjUxMTQxIDEzLjIwOTFDNi40NDMxMSAxMy4wNTAzIDYuNDA5MjcgMTIuODgwNyA2LjQwOTI3IDEyLjcwMTJWMTEuMTAwOUM2LjQwOTI3IDEwLjYyMiA2LjMxNzcyIDEwLjE3OTUgNi4xMzU1MyA5Ljc3MjA5QzUuOTU2ODMgOS4zNjMzNiA1LjY5ODMyIDguOTkxNTYgNS4zNTk1MyA4LjY1ODA2QzQuOTI0NjggOC4yMjkwMyA0LjU4ODk2IDcuNzUwMDMgNC4zNTM2MSA3LjIyMTM0QzQuMTE3NTYgNi42OTEwNyA0IDYuMTE2NzIgNCA1LjQ5OTUzQzQgNS4wODY2NCA0LjA1MzQyIDQuNjg4MDIgNC4xNjA0OCA0LjMwMzk3QzQuMjY3MjggMy45MjA4OSA0LjQxOTA3IDMuNTYyODYgNC42MTU5NSAzLjIzMDE4QzQuODEyNTcgMi44OTM3NyA1LjA0Nzc3IDIuNTg5MTEgNS4zMjE0NiAyLjMxNjQxQzUuNTk1MDMgMi4wNDM4MyA1Ljg5ODU4IDEuODA5NTMgNi4yMzE5NSAxLjYxMzY0QzYuNTY5NzkgMS40MTc2NCA2LjkzMTQ2IDEuMjY2MiA3LjMxNTc4IDEuMTU5ODNDNy43MDEwNiAxLjA1MzIgOC4xMDA5NCAxIDguNTE1MTQgMUM4LjkyOTM0IDEgOS4zMjkyMyAxLjA1MzIgOS43MTQ1MSAxLjE1OTgzQzEwLjA5ODggMS4yNjYyIDEwLjQ1OCAxLjQxNzM5IDEwLjc5MTggMS42MTM1MUMxMS4xMjk0IDEuODA5MzggMTEuNDM1MSAyLjA0MzcgMTEuNzA4OCAyLjMxNjQxQzExLjk4MjUgMi41ODkxIDEyLjIxNzcgMi44OTM3NiAxMi40MTQzIDMuMjMwMTZDMTIuNjExMiAzLjU2Mjg1IDEyLjc2MyAzLjkyMDg4IDEyLjg2OTggNC4zMDM5N0MxMi45NzY5IDQuNjg4MDIgMTMuMDMwMyA1LjA4NjY0IDEzLjAzMDMgNS40OTk1M0MxMy4wMzAzIDYuMTE2NzIgMTIuOTEyNyA2LjY5MTA3IDEyLjY3NjcgNy4yMjEzNEMxMi40NDEzIDcuNzUwMDMgMTIuMTA1NiA4LjIyOTAzIDExLjY3MDggOC42NTgwNlpNOS42MjE2MiAxMC41SDcuNDA4NjdWMTIuNzAxMkM3LjQwODY3IDEyLjc4MjMgNy40MzcyIDEyLjg1MTIgNy40OTg4OCAxMi45MTI3QzcuNTYwNTggMTIuOTc0MSA3LjYzMDA3IDEzLjAwMjggNy43MTIwNSAxMy4wMDI4SDkuMzE4MjNDOS40MDAyMiAxMy4wMDI4IDkuNDY5NzEgMTIuOTc0MSA5LjUzMTQgMTIuOTEyN0M5LjU5MzA5IDEyLjg1MTIgOS42MjE2MiAxMi43ODIzIDkuNjIxNjIgMTIuNzAxMlYxMC41WiIgZmlsbD0iIzQyNDI0MiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjY3MDggOC42NTgwNkMxMS4zMzE5IDguOTkxNiAxMS4wNzE2IDkuMzYyNzggMTAuODg4NiA5Ljc3MTcyQzEwLjcxMDUgMTAuMTc5MiAxMC42MjEgMTAuNjIxOSAxMC42MjEgMTEuMTAwOVYxMi43MDEyQzEwLjYyMSAxMi44ODA3IDEwLjU4NzIgMTMuMDUwMyAxMC41MTg5IDEzLjIwOTFDMTAuNDUxMyAxMy4zNjYxIDEwLjM1ODYgMTMuNTAzOCAxMC4yNDA3IDEzLjYyMTNDMTAuMTIyOCAxMy43Mzg4IDkuOTg0NjQgMTMuODMxMSA5LjgyNzIzIDEzLjg5ODRDOS42NjgwNiAxMy45NjYzIDkuNDk4MDYgMTQgOS4zMTgyMyAxNEg3LjcxMjA1QzcuNTMyMjMgMTQgNy4zNjIyMyAxMy45NjYzIDcuMjAzMDYgMTMuODk4NEM3LjA0NTY0IDEzLjgzMTEgNi45MDc1MyAxMy43Mzg4IDYuNzg5NjEgMTMuNjIxM0M2LjY3MTY4IDEzLjUwMzggNi41Nzg5NSAxMy4zNjYxIDYuNTExNDEgMTMuMjA5MUM2LjQ0MzExIDEzLjA1MDMgNi40MDkyNyAxMi44ODA3IDYuNDA5MjcgMTIuNzAxMlYxMS4xMDA5QzYuNDA5MjcgMTAuNjIyIDYuMzE3NzIgMTAuMTc5NSA2LjEzNTUzIDkuNzcyMDlDNS45NTY4MyA5LjM2MzM2IDUuNjk4MzIgOC45OTE1NiA1LjM1OTUzIDguNjU4MDZDNC45MjQ2OCA4LjIyOTAzIDQuNTg4OTYgNy43NTAwMyA0LjM1MzYxIDcuMjIxMzRDNC4xMTc1NiA2LjY5MTA3IDQgNi4xMTY3MiA0IDUuNDk5NTNDNCA1LjA4NjY0IDQuMDUzNDIgNC42ODgwMiA0LjE2MDQ4IDQuMzAzOTdDNC4yNjcyOCAzLjkyMDg5IDQuNDE5MDcgMy41NjI4NiA0LjYxNTk1IDMuMjMwMThDNC44MTI1NyAyLjg5Mzc3IDUuMDQ3NzcgMi41ODkxMSA1LjMyMTQ2IDIuMzE2NDFDNS41OTUwMyAyLjA0MzgzIDUuODk4NTggMS44MDk1MyA2LjIzMTk1IDEuNjEzNjRDNi41Njk3OSAxLjQxNzY0IDYuOTMxNDYgMS4yNjYyIDcuMzE1NzggMS4xNTk4M0M3LjcwMTA2IDEuMDUzMiA4LjEwMDk0IDEgOC41MTUxNCAxQzguOTI5MzQgMSA5LjMyOTIzIDEuMDUzMiA5LjcxNDUxIDEuMTU5ODNDMTAuMDk4OCAxLjI2NjIgMTAuNDU4IDEuNDE3MzkgMTAuNzkxOCAxLjYxMzUxQzExLjEyOTQgMS44MDkzOCAxMS40MzUxIDIuMDQzNyAxMS43MDg4IDIuMzE2NDFDMTEuOTgyNSAyLjU4OTEgMTIuMjE3NyAyLjg5Mzc2IDEyLjQxNDMgMy4yMzAxNkMxMi42MTEyIDMuNTYyODUgMTIuNzYzIDMuOTIwODggMTIuODY5OCA0LjMwMzk3QzEyLjk3NjkgNC42ODgwMiAxMy4wMzAzIDUuMDg2NjQgMTMuMDMwMyA1LjQ5OTUzQzEzLjAzMDMgNi4xMTY3MiAxMi45MTI3IDYuNjkxMDcgMTIuNjc2NyA3LjIyMTM0QzEyLjQ0MTMgNy43NTAwMyAxMi4xMDU2IDguMjI5MDMgMTEuNjcwOCA4LjY1ODA2Wk05LjYyMTYyIDEwLjVINy40MDg2N1YxMi43MDEyQzcuNDA4NjcgMTIuNzgyMyA3LjQzNzIgMTIuODUxMiA3LjQ5ODg4IDEyLjkxMjdDNy41NjA1OCAxMi45NzQxIDcuNjMwMDcgMTMuMDAyOCA3LjcxMjA1IDEzLjAwMjhIOS4zMTgyM0M5LjQwMDIyIDEzLjAwMjggOS40Njk3MSAxMi45NzQxIDkuNTMxNCAxMi45MTI3QzkuNTkzMDkgMTIuODUxMiA5LjYyMTYyIDEyLjc4MjMgOS42MjE2MiAxMi43MDEyVjEwLjVaIiBmaWxsPSIjNDI0MjQyIi8+Cjwvc3ZnPgo=") 50% no-repeat}.monaco-editor.hc-dark .margin-view-zones .inline-deleted-margin-view-zone .lightbulb-glyph,.monaco-editor.vs-dark .margin-view-zones .inline-deleted-margin-view-zone .lightbulb-glyph{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMS42NzA4IDguNjU4MDZDMTEuMzMxOSA4Ljk5MTYgMTEuMDcxNiA5LjM2Mjc4IDEwLjg4ODYgOS43NzE3MkMxMC43MTA1IDEwLjE3OTIgMTAuNjIxIDEwLjYyMTkgMTAuNjIxIDExLjEwMDlWMTIuNzAxMkMxMC42MjEgMTIuODgwNyAxMC41ODcyIDEzLjA1MDMgMTAuNTE4OSAxMy4yMDkxQzEwLjQ1MTMgMTMuMzY2MSAxMC4zNTg2IDEzLjUwMzggMTAuMjQwNyAxMy42MjEzQzEwLjEyMjggMTMuNzM4OCA5Ljk4NDY0IDEzLjgzMTEgOS44MjcyMyAxMy44OTg0QzkuNjY4MDYgMTMuOTY2MyA5LjQ5ODA2IDE0IDkuMzE4MjMgMTRINy43MTIwNUM3LjUzMjIzIDE0IDcuMzYyMjMgMTMuOTY2MyA3LjIwMzA2IDEzLjg5ODRDNy4wNDU2NCAxMy44MzExIDYuOTA3NTMgMTMuNzM4OCA2Ljc4OTYxIDEzLjYyMTNDNi42NzE2OCAxMy41MDM4IDYuNTc4OTUgMTMuMzY2MSA2LjUxMTQxIDEzLjIwOTFDNi40NDMxMSAxMy4wNTAzIDYuNDA5MjcgMTIuODgwNyA2LjQwOTI3IDEyLjcwMTJWMTEuMTAwOUM2LjQwOTI3IDEwLjYyMiA2LjMxNzcyIDEwLjE3OTUgNi4xMzU1MyA5Ljc3MjA5QzUuOTU2ODMgOS4zNjMzNiA1LjY5ODMyIDguOTkxNTYgNS4zNTk1MyA4LjY1ODA2QzQuOTI0NjggOC4yMjkwMyA0LjU4ODk2IDcuNzUwMDMgNC4zNTM2MSA3LjIyMTM0QzQuMTE3NTYgNi42OTEwNyA0IDYuMTE2NzIgNCA1LjQ5OTUzQzQgNS4wODY2NCA0LjA1MzQyIDQuNjg4MDIgNC4xNjA0OCA0LjMwMzk3QzQuMjY3MjggMy45MjA4OSA0LjQxOTA3IDMuNTYyODYgNC42MTU5NSAzLjIzMDE4QzQuODEyNTcgMi44OTM3NyA1LjA0Nzc3IDIuNTg5MTEgNS4zMjE0NiAyLjMxNjQxQzUuNTk1MDMgMi4wNDM4MyA1Ljg5ODU4IDEuODA5NTMgNi4yMzE5NSAxLjYxMzY0QzYuNTY5NzkgMS40MTc2NCA2LjkzMTQ2IDEuMjY2MiA3LjMxNTc4IDEuMTU5ODNDNy43MDEwNiAxLjA1MzIgOC4xMDA5NCAxIDguNTE1MTQgMUM4LjkyOTM0IDEgOS4zMjkyMyAxLjA1MzIgOS43MTQ1MSAxLjE1OTgzQzEwLjA5ODggMS4yNjYyIDEwLjQ1OCAxLjQxNzM5IDEwLjc5MTggMS42MTM1MUMxMS4xMjk0IDEuODA5MzggMTEuNDM1MSAyLjA0MzcgMTEuNzA4OCAyLjMxNjQxQzExLjk4MjUgMi41ODkxIDEyLjIxNzcgMi44OTM3NiAxMi40MTQzIDMuMjMwMTZDMTIuNjExMiAzLjU2Mjg1IDEyLjc2MyAzLjkyMDg4IDEyLjg2OTggNC4zMDM5N0MxMi45NzY5IDQuNjg4MDIgMTMuMDMwMyA1LjA4NjY0IDEzLjAzMDMgNS40OTk1M0MxMy4wMzAzIDYuMTE2NzIgMTIuOTEyNyA2LjY5MTA3IDEyLjY3NjcgNy4yMjEzNEMxMi40NDEzIDcuNzUwMDMgMTIuMTA1NiA4LjIyOTAzIDExLjY3MDggOC42NTgwNlpNOS42MjE2MiAxMC41SDcuNDA4NjdWMTIuNzAxMkM3LjQwODY3IDEyLjc4MjMgNy40MzcyIDEyLjg1MTIgNy40OTg4OCAxMi45MTI3QzcuNTYwNTggMTIuOTc0MSA3LjYzMDA3IDEzLjAwMjggNy43MTIwNSAxMy4wMDI4SDkuMzE4MjNDOS40MDAyMiAxMy4wMDI4IDkuNDY5NzEgMTIuOTc0MSA5LjUzMTQgMTIuOTEyN0M5LjU5MzA5IDEyLjg1MTIgOS42MjE2MiAxMi43ODIzIDkuNjIxNjIgMTIuNzAxMlYxMC41WiIgZmlsbD0iI0MyQzJDMiIvPgo8L3N2Zz4K") 50% no-repeat}.monaco-editor .margin-view-zones .lightbulb-glyph:hover{cursor:pointer}.monaco-diff-editor .diff-review-line-number{text-align:right;display:inline-block}.monaco-diff-editor .diff-review{position:absolute;-webkit-user-select:none;-ms-user-select:none;-moz-user-select:none;-o-user-select:none;user-select:none}.monaco-diff-editor .diff-review-summary{padding-left:10px}.monaco-diff-editor .diff-review-shadow{position:absolute}.monaco-diff-editor .diff-review-row{white-space:pre}.monaco-diff-editor .diff-review-table{display:table;min-width:100%}.monaco-diff-editor .diff-review-row{display:table-row;width:100%}.monaco-diff-editor .diff-review-cell{display:table-cell}.monaco-diff-editor .diff-review-spacer{display:inline-block;width:10px}.monaco-diff-editor .diff-review-actions{display:inline-block;position:absolute;right:10px;top:2px}.monaco-diff-editor .diff-review-actions .action-label{width:16px;height:16px;margin:2px 0}.monaco-diff-editor .action-label.icon.close-diff-review{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjAwMDAxIDguNzA3MTFMMTEuNjQ2NSAxMi4zNTM2TDEyLjM1MzYgMTEuNjQ2NUw4LjcwNzExIDguMDAwMDFMMTIuMzUzNiA0LjM1MzU2TDExLjY0NjUgMy42NDY0NUw4LjAwMDAxIDcuMjkyOUw0LjM1MzU2IDMuNjQ2NDVMMy42NDY0NSA0LjM1MzU2TDcuMjkyOSA4LjAwMDAxTDMuNjQ2NDUgMTEuNjQ2NUw0LjM1MzU2IDEyLjM1MzZMOC4wMDAwMSA4LjcwNzExWiIgZmlsbD0iIzQyNDI0MiIvPgo8L3N2Zz4K") 50% no-repeat}.monaco-diff-editor.hc-black .action-label.icon.close-diff-review,.monaco-diff-editor.vs-dark .action-label.icon.close-diff-review{background:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik04LjAwMDAxIDguNzA3MTFMMTEuNjQ2NSAxMi4zNTM2TDEyLjM1MzYgMTEuNjQ2NUw4LjcwNzExIDguMDAwMDFMMTIuMzUzNiA0LjM1MzU2TDExLjY0NjUgMy42NDY0NUw4LjAwMDAxIDcuMjkyOUw0LjM1MzU2IDMuNjQ2NDVMMy42NDY0NSA0LjM1MzU2TDcuMjkyOSA4LjAwMDAxTDMuNjQ2NDUgMTEuNjQ2NUw0LjM1MzU2IDEyLjM1MzZMOC4wMDAwMSA4LjcwNzExWiIgZmlsbD0iI0M1QzVDNSIvPgo8L3N2Zz4K") 50% no-repeat}.context-view .monaco-menu{min-width:130px}.context-view-block{position:fixed;left:0;top:0;z-index:-1;width:100%;height:100%}.monaco-menu .monaco-action-bar.vertical{margin-left:0;overflow:visible}.monaco-menu .monaco-action-bar.vertical .actions-container{display:block}.monaco-menu .monaco-action-bar.vertical .action-item{padding:0;transform:none;display:-ms-flexbox;display:flex}.monaco-menu .monaco-action-bar.vertical .action-item.active{transform:none}.monaco-menu .monaco-action-bar.vertical .action-menu-item{-ms-flex:1 1 auto;flex:1 1 auto;display:-ms-flexbox;display:flex;height:2em;-ms-flex-align:center;align-items:center;position:relative}.monaco-menu .monaco-action-bar.vertical .action-label{-ms-flex:1 1 auto;flex:1 1 auto;text-decoration:none;padding:0 1em;background:none;font-size:12px;line-height:1}.monaco-menu .monaco-action-bar.vertical .keybinding,.monaco-menu .monaco-action-bar.vertical .submenu-indicator{display:inline-block;-ms-flex:2 1 auto;flex:2 1 auto;padding:0 1em;text-align:right;font-size:12px;line-height:1}.monaco-menu .monaco-action-bar.vertical .submenu-indicator{height:100%;-webkit-mask:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTQiIGhlaWdodD0iMTQiIHZpZXdCb3g9IjAgMCAxNCAxNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQuNTIwNTEgMTIuMzY0M0w5Ljg3NzkzIDdMNC41MjA1MSAxLjYzNTc0Mkw1LjEzNTc0IDEuMDIwNTA3OEwxMS4xMjIxIDdMNS4xMzU3NCAxMi45Nzk1TDQuNTIwNTEgMTIuMzY0M1oiIGZpbGw9ImJsYWNrIi8+Cjwvc3ZnPgo=") no-repeat 90% 50%/13px 13px;mask:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTQiIGhlaWdodD0iMTQiIHZpZXdCb3g9IjAgMCAxNCAxNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQuNTIwNTEgMTIuMzY0M0w5Ljg3NzkzIDdMNC41MjA1MSAxLjYzNTc0Mkw1LjEzNTc0IDEuMDIwNTA3OEwxMS4xMjIxIDdMNS4xMzU3NCAxMi45Nzk1TDQuNTIwNTEgMTIuMzY0M1oiIGZpbGw9ImJsYWNrIi8+Cjwvc3ZnPgo=") no-repeat 90% 50%/13px 13px}.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator{opacity:.4}.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator){display:inline-block;-o-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;margin:0}.monaco-menu .monaco-action-bar.vertical .action-item{position:static;overflow:visible}.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu{position:absolute}.monaco-menu .monaco-action-bar.vertical .action-label.separator{padding:.5em 0 0;margin-bottom:.5em;width:100%}.monaco-menu .monaco-action-bar.vertical .action-label.separator.text{padding:.7em 1em .1em;font-weight:700;opacity:1}.monaco-menu .monaco-action-bar.vertical .action-label:hover{color:inherit}.monaco-menu .monaco-action-bar.vertical .menu-item-check{position:absolute;visibility:hidden;-webkit-mask:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNC40MzE1IDMuMzIzMkw1Ljk2MTUxIDEzLjMyMzJMNS4xNzA4IDEzLjI4NzRMMS44MjA4IDguNTE3NEwyLjYzOTE1IDcuOTQyNjhMNS42MTY5NyAxMi4xODI3TDEzLjY2ODQgMi42NzY4OEwxNC40MzE1IDMuMzIzMloiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") no-repeat 50% 56%/15px 15px;mask:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNC40MzE1IDMuMzIzMkw1Ljk2MTUxIDEzLjMyMzJMNS4xNzA4IDEzLjI4NzRMMS44MjA4IDguNTE3NEwyLjYzOTE1IDcuOTQyNjhMNS42MTY5NyAxMi4xODI3TDEzLjY2ODQgMi42NzY4OEwxNC40MzE1IDMuMzIzMloiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") no-repeat 50% 56%/15px 15px;width:1em;height:100%}.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check{visibility:visible}.context-view.monaco-menu-container{outline:0;border:none;animation:fadeIn 83ms linear}.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,.context-view.monaco-menu-container .monaco-action-bar.vertical :focus,.context-view.monaco-menu-container :focus{outline:0}.monaco-menu .monaco-action-bar.vertical .action-item{border:thin solid transparent}.hc-black .context-view.monaco-menu-container{box-shadow:none}.hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused{background:none}.menubar{display:-ms-flexbox;display:flex;-ms-flex-negative:1;flex-shrink:1;box-sizing:border-box;height:30px;overflow:hidden;-ms-flex-wrap:wrap;flex-wrap:wrap}.fullscreen .menubar{margin:0;padding:0 5px}.menubar>.menubar-menu-button{-ms-flex-align:center;align-items:center;box-sizing:border-box;padding:0 8px;cursor:default;-webkit-app-region:no-drag;zoom:1;white-space:nowrap;outline:0}.menubar .menubar-menu-items-holder{position:absolute;left:0;opacity:1;z-index:2000}.menubar .menubar-menu-items-holder.monaco-menu-container{outline:0;border:none}.menubar .menubar-menu-items-holder.monaco-menu-container :focus{outline:0}.menubar .toolbar-toggle-more{background-position:50%;background-repeat:no-repeat;background-size:14px;width:20px;height:100%;display:inline-block;padding:0;-webkit-mask:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQgOEM0IDguMTk3NzggMy45NDEzNSA4LjM5MTEyIDMuODMxNDcgOC41NTU1N0MzLjcyMTU5IDguNzIwMDIgMy41NjU0MSA4Ljg0ODE5IDMuMzgyNjggOC45MjM4OEMzLjE5OTk2IDguOTk5NTcgMi45OTg4OSA5LjAxOTM3IDIuODA0OTEgOC45ODA3OUMyLjYxMDkzIDguOTQyMiAyLjQzMjc1IDguODQ2OTYgMi4yOTI4OSA4LjcwNzExQzIuMTUzMDQgOC41NjcyNSAyLjA1NzggOC4zODkwNyAyLjAxOTIyIDguMTk1MDlDMS45ODA2MyA4LjAwMTExIDIuMDAwNDMgNy44MDAwNCAyLjA3NjEyIDcuNjE3MzJDMi4xNTE4MSA3LjQzNDU5IDIuMjc5OTggNy4yNzg0MSAyLjQ0NDQzIDcuMTY4NTNDMi42MDg4OCA3LjA1ODY1IDIuODAyMjIgNyAzIDdDMy4yNjUyMiA3IDMuNTE5NTcgNy4xMDUzNiAzLjcwNzExIDcuMjkyODlDMy44OTQ2NCA3LjQ4MDQzIDQgNy43MzQ3OCA0IDhaIiBmaWxsPSIjQzVDNUM1Ii8+CjxwYXRoIGQ9Ik05IDhDOSA4LjE5Nzc4IDguOTQxMzUgOC4zOTExMiA4LjgzMTQ3IDguNTU1NTdDOC43MjE1OSA4LjcyMDAyIDguNTY1NDEgOC44NDgxOSA4LjM4MjY4IDguOTIzODhDOC4xOTk5NiA4Ljk5OTU3IDcuOTk4ODkgOS4wMTkzNyA3LjgwNDkxIDguOTgwNzlDNy42MTA5MyA4Ljk0MjIgNy40MzI3NSA4Ljg0Njk2IDcuMjkyODkgOC43MDcxMUM3LjE1MzA0IDguNTY3MjUgNy4wNTc4IDguMzg5MDcgNy4wMTkyMiA4LjE5NTA5QzYuOTgwNjMgOC4wMDExMSA3LjAwMDQzIDcuODAwMDQgNy4wNzYxMiA3LjYxNzMyQzcuMTUxODEgNy40MzQ1OSA3LjI3OTk4IDcuMjc4NDEgNy40NDQ0MyA3LjE2ODUzQzcuNjA4ODggNy4wNTg2NSA3LjgwMjIyIDcgOCA3QzguMjY1MjIgNyA4LjUxOTU3IDcuMTA1MzYgOC43MDcxMSA3LjI5Mjg5QzguODk0NjQgNy40ODA0MyA5IDcuNzM0NzggOSA4WiIgZmlsbD0iI0M1QzVDNSIvPgo8cGF0aCBkPSJNMTQgOEMxNCA4LjE5Nzc4IDEzLjk0MTQgOC4zOTExMiAxMy44MzE1IDguNTU1NTdDMTMuNzIxNiA4LjcyMDAyIDEzLjU2NTQgOC44NDgxOSAxMy4zODI3IDguOTIzODhDMTMuMiA4Ljk5OTU3IDEyLjk5ODkgOS4wMTkzNyAxMi44MDQ5IDguOTgwNzlDMTIuNjEwOSA4Ljk0MjIgMTIuNDMyNyA4Ljg0Njk2IDEyLjI5MjkgOC43MDcxMUMxMi4xNTMgOC41NjcyNSAxMi4wNTc4IDguMzg5MDcgMTIuMDE5MiA4LjE5NTA5QzExLjk4MDYgOC4wMDExMSAxMi4wMDA0IDcuODAwMDQgMTIuMDc2MSA3LjYxNzMyQzEyLjE1MTggNy40MzQ1OSAxMi4yOCA3LjI3ODQxIDEyLjQ0NDQgNy4xNjg1M0MxMi42MDg5IDcuMDU4NjUgMTIuODAyMiA3IDEzIDdDMTMuMjY1MiA3IDEzLjUxOTYgNy4xMDUzNiAxMy43MDcxIDcuMjkyODlDMTMuODk0NiA3LjQ4MDQzIDE0IDcuNzM0NzggMTQgOFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") no-repeat 50% 55%/14px 14px;mask:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQgOEM0IDguMTk3NzggMy45NDEzNSA4LjM5MTEyIDMuODMxNDcgOC41NTU1N0MzLjcyMTU5IDguNzIwMDIgMy41NjU0MSA4Ljg0ODE5IDMuMzgyNjggOC45MjM4OEMzLjE5OTk2IDguOTk5NTcgMi45OTg4OSA5LjAxOTM3IDIuODA0OTEgOC45ODA3OUMyLjYxMDkzIDguOTQyMiAyLjQzMjc1IDguODQ2OTYgMi4yOTI4OSA4LjcwNzExQzIuMTUzMDQgOC41NjcyNSAyLjA1NzggOC4zODkwNyAyLjAxOTIyIDguMTk1MDlDMS45ODA2MyA4LjAwMTExIDIuMDAwNDMgNy44MDAwNCAyLjA3NjEyIDcuNjE3MzJDMi4xNTE4MSA3LjQzNDU5IDIuMjc5OTggNy4yNzg0MSAyLjQ0NDQzIDcuMTY4NTNDMi42MDg4OCA3LjA1ODY1IDIuODAyMjIgNyAzIDdDMy4yNjUyMiA3IDMuNTE5NTcgNy4xMDUzNiAzLjcwNzExIDcuMjkyODlDMy44OTQ2NCA3LjQ4MDQzIDQgNy43MzQ3OCA0IDhaIiBmaWxsPSIjQzVDNUM1Ii8+CjxwYXRoIGQ9Ik05IDhDOSA4LjE5Nzc4IDguOTQxMzUgOC4zOTExMiA4LjgzMTQ3IDguNTU1NTdDOC43MjE1OSA4LjcyMDAyIDguNTY1NDEgOC44NDgxOSA4LjM4MjY4IDguOTIzODhDOC4xOTk5NiA4Ljk5OTU3IDcuOTk4ODkgOS4wMTkzNyA3LjgwNDkxIDguOTgwNzlDNy42MTA5MyA4Ljk0MjIgNy40MzI3NSA4Ljg0Njk2IDcuMjkyODkgOC43MDcxMUM3LjE1MzA0IDguNTY3MjUgNy4wNTc4IDguMzg5MDcgNy4wMTkyMiA4LjE5NTA5QzYuOTgwNjMgOC4wMDExMSA3LjAwMDQzIDcuODAwMDQgNy4wNzYxMiA3LjYxNzMyQzcuMTUxODEgNy40MzQ1OSA3LjI3OTk4IDcuMjc4NDEgNy40NDQ0MyA3LjE2ODUzQzcuNjA4ODggNy4wNTg2NSA3LjgwMjIyIDcgOCA3QzguMjY1MjIgNyA4LjUxOTU3IDcuMTA1MzYgOC43MDcxMSA3LjI5Mjg5QzguODk0NjQgNy40ODA0MyA5IDcuNzM0NzggOSA4WiIgZmlsbD0iI0M1QzVDNSIvPgo8cGF0aCBkPSJNMTQgOEMxNCA4LjE5Nzc4IDEzLjk0MTQgOC4zOTExMiAxMy44MzE1IDguNTU1NTdDMTMuNzIxNiA4LjcyMDAyIDEzLjU2NTQgOC44NDgxOSAxMy4zODI3IDguOTIzODhDMTMuMiA4Ljk5OTU3IDEyLjk5ODkgOS4wMTkzNyAxMi44MDQ5IDguOTgwNzlDMTIuNjEwOSA4Ljk0MjIgMTIuNDMyNyA4Ljg0Njk2IDEyLjI5MjkgOC43MDcxMUMxMi4xNTMgOC41NjcyNSAxMi4wNTc4IDguMzg5MDcgMTIuMDE5MiA4LjE5NTA5QzExLjk4MDYgOC4wMDExMSAxMi4wMDA0IDcuODAwMDQgMTIuMDc2MSA3LjYxNzMyQzEyLjE1MTggNy40MzQ1OSAxMi4yOCA3LjI3ODQxIDEyLjQ0NDQgNy4xNjg1M0MxMi42MDg5IDcuMDU4NjUgMTIuODAyMiA3IDEzIDdDMTMuMjY1MiA3IDEzLjUxOTYgNy4xMDUzNiAxMy43MDcxIDcuMjkyODlDMTMuODk0NiA3LjQ4MDQzIDE0IDcuNzM0NzggMTQgOFoiIGZpbGw9IiNDNUM1QzUiLz4KPC9zdmc+Cg==") no-repeat 50% 55%/14px 14px}.context-view{position:absolute;z-index:2000}.rule-view .el-card{margin-top:24px;min-height:150px}.rule-view .page-title .el-breadcrumb{text-transform:none}.resources-view .el-table{margin-top:24px}.resources-view .status-wrapper{padding:0;list-style-type:none}.resources-view .status-wrapper .status-item{padding:2px 6px}.resources-view .status-wrapper .status-item>span{margin-right:12px}.resources-view .el-form-item__content{clear:both}.resources-view .expand-column .cell{opacity:0}.topic-metrics .sub-tip{font-size:14px;color:#9e9e9f;text-transform:none;margin-right:10px}.topic-metrics .el-table{margin-top:24px}.topic-metrics .el-table .expand-header{height:32px;line-height:32px;margin-bottom:20px}.topic-metrics .el-table .topic-qos-radio{float:right}.topic-metrics .el-table .message-card{height:112px;border-radius:4px;padding:6px 12px}.topic-metrics .el-table .message-card .message-card--body{font-size:28px;height:80px;line-height:80px;text-align:center}.topic-metrics .el-table .message-card .message-rate{float:right}.plugins-view .el-card.plugin-config,.plugins-view .el-table{margin-top:24px}.plugins-view .el-row{margin-top:20px}.plugins-view .oper{min-width:50px;font-size:14px;margin-bottom:4px}.plugins-view .tutorial{margin-left:5px;color:#a7a7a7}.plugins-view .tutorial:hover{color:#34c388}.plugin-manage .page-title{text-transform:none}.plugin-manage .el-card{margin-top:24px;min-height:150px}.plugin-manage .el-card .config-null{text-align:center;margin:20px auto}.plugin-manage .el-input.input-radius,.plugin-manage .el-textarea.input-radius{width:100%}.auth-clientid-table .el-form-item__error,.auth-username-table .el-form-item__error{display:none}.generate-jwt .monaco-container{height:200px}.generate-jwt .el-date-editor.el-input,.generate-jwt .el-date-editor.el-input__inner,.generate-jwt .el-select{width:100%}.generate-jwt .el-table{margin-top:40px}.generate-jwt .jwt-payload-desc{font-size:14px;padding:6px;border-radius:4px;line-height:1.4;margin:16px 0}.modules-view .el-table{margin-top:24px}.modules-view .oper{min-width:50px;font-size:14px;margin-bottom:4px}.listeners-view .el-table{margin-top:24px}.websocket-view .el-form-item--small.el-form-item{margin-bottom:2px}.websocket-view .check-area .el-form-item__content{line-height:20px!important}.websocket-view .operation-area{margin-top:10px!important}.websocket-view .el-input .el-input--medium{margin-bottom:10px!important}.websocket-view .el-select{width:100%}.websocket-view .refresh-btn{font-size:12px;margin-left:8px;cursor:pointer}.websocket-view .connect-state{display:inline-block;margin-left:20px;font-size:14px;color:#a7a7a7}.websocket-view .connect-state span{margin-left:4px}.websocket-view .el-table{margin-top:5px;border-width:0!important}.websocket-view .el-card{margin-top:24px}.websocket-view .el-checkbox,.websocket-view .el-input{margin:5px 0 20px}.http-api{margin-top:0!important}.http-api .link-disabled{cursor:not-allowed}.http-api .el-card{margin-top:24px}.http-api .el-table{border-width:0!important}.http-api .refresh-btn{cursor:pointer;font-size:16px;padding:0!important}.http-api .response-container{line-height:1.5}.http-api .response-container h3{font-size:14px!important}.http-api .response-container a{margin-left:12px}.applications-view .el-date-editor,.applications-view .el-select{width:100%}.applications-view .el-table{margin-top:24px}.applications-view .el-row{margin-top:20px}.applications-view .search-btn{margin-left:8px}.applications-view .el-breadcrumb{margin-top:10px;margin-bottom:20px}.applications-view .el-date-picker{max-width:600px!important}.applications-view .el-form-item--medium .el-form-item__content{line-height:38px}.app-info .el-input.is-disabled .el-input__inner{cursor:text}.users-view .el-table{margin-top:24px}.users-view .change-password{text-align:left}.settings-view .el-card{margin-top:24px}.settings-view .el-button{width:80px}.settings-view .el-switch.is-checked .el-switch__core{background-color:#42d885;border-color:#42d885}.settings-view .confirm-btn .el-form-item{margin-bottom:4px!important}.help-view{width:80%}.help-view .help-item h3{font-size:16px}.help-view .help-item p{color:#b0b0b0;line-height:1.8}.help-view .help-item a{margin-right:16px}.help-view .help-item .follow-link{display:inline-block;width:64px;height:52px;text-align:center;line-height:52px;background:#232429;color:#9ea3b1;margin-bottom:20px}.help-view .help-item .follow-link .iconfont{font-size:24px}.help-view .el-divider{margin:30px 0;background-color:#2b2c30}@media (max-width:996px){.help-view{width:100%}}.not-found{text-align:center;padding:50px}.not-found p{margin-top:30px;font-size:20px}.not-found a{margin-right:20px}.not-found a:hover{text-decoration:underline}@font-face{font-family:element-icons;src:url(/static/fonts/element-icons.535877f.woff) format("woff"),url(/static/fonts/element-icons.732389d.ttf) format("truetype");font-weight:400;font-style:normal}[class*=" el-icon-"],[class^=el-icon-]{font-family:element-icons!important;speak:none;font-style:normal;font-weight:400;font-variant:normal;text-transform:none;line-height:1;vertical-align:baseline;display:inline-block;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.el-icon-ice-cream-round:before{content:"\E6A0"}.el-icon-ice-cream-square:before{content:"\E6A3"}.el-icon-lollipop:before{content:"\E6A4"}.el-icon-potato-strips:before{content:"\E6A5"}.el-icon-milk-tea:before{content:"\E6A6"}.el-icon-ice-drink:before{content:"\E6A7"}.el-icon-ice-tea:before{content:"\E6A9"}.el-icon-coffee:before{content:"\E6AA"}.el-icon-orange:before{content:"\E6AB"}.el-icon-pear:before{content:"\E6AC"}.el-icon-apple:before{content:"\E6AD"}.el-icon-cherry:before{content:"\E6AE"}.el-icon-watermelon:before{content:"\E6AF"}.el-icon-grape:before{content:"\E6B0"}.el-icon-refrigerator:before{content:"\E6B1"}.el-icon-goblet-square-full:before{content:"\E6B2"}.el-icon-goblet-square:before{content:"\E6B3"}.el-icon-goblet-full:before{content:"\E6B4"}.el-icon-goblet:before{content:"\E6B5"}.el-icon-cold-drink:before{content:"\E6B6"}.el-icon-coffee-cup:before{content:"\E6B8"}.el-icon-water-cup:before{content:"\E6B9"}.el-icon-hot-water:before{content:"\E6BA"}.el-icon-ice-cream:before{content:"\E6BB"}.el-icon-dessert:before{content:"\E6BC"}.el-icon-sugar:before{content:"\E6BD"}.el-icon-tableware:before{content:"\E6BE"}.el-icon-burger:before{content:"\E6BF"}.el-icon-knife-fork:before{content:"\E6C1"}.el-icon-fork-spoon:before{content:"\E6C2"}.el-icon-chicken:before{content:"\E6C3"}.el-icon-food:before{content:"\E6C4"}.el-icon-dish-1:before{content:"\E6C5"}.el-icon-dish:before{content:"\E6C6"}.el-icon-moon-night:before{content:"\E6EE"}.el-icon-moon:before{content:"\E6F0"}.el-icon-cloudy-and-sunny:before{content:"\E6F1"}.el-icon-partly-cloudy:before{content:"\E6F2"}.el-icon-cloudy:before{content:"\E6F3"}.el-icon-sunny:before{content:"\E6F6"}.el-icon-sunset:before{content:"\E6F7"}.el-icon-sunrise-1:before{content:"\E6F8"}.el-icon-sunrise:before{content:"\E6F9"}.el-icon-heavy-rain:before{content:"\E6FA"}.el-icon-lightning:before{content:"\E6FB"}.el-icon-light-rain:before{content:"\E6FC"}.el-icon-wind-power:before{content:"\E6FD"}.el-icon-baseball:before{content:"\E712"}.el-icon-soccer:before{content:"\E713"}.el-icon-football:before{content:"\E715"}.el-icon-basketball:before{content:"\E716"}.el-icon-ship:before{content:"\E73F"}.el-icon-truck:before{content:"\E740"}.el-icon-bicycle:before{content:"\E741"}.el-icon-mobile-phone:before{content:"\E6D3"}.el-icon-service:before{content:"\E6D4"}.el-icon-key:before{content:"\E6E2"}.el-icon-unlock:before{content:"\E6E4"}.el-icon-lock:before{content:"\E6E5"}.el-icon-watch:before{content:"\E6FE"}.el-icon-watch-1:before{content:"\E6FF"}.el-icon-timer:before{content:"\E702"}.el-icon-alarm-clock:before{content:"\E703"}.el-icon-map-location:before{content:"\E704"}.el-icon-delete-location:before{content:"\E705"}.el-icon-add-location:before{content:"\E706"}.el-icon-location-information:before{content:"\E707"}.el-icon-location-outline:before{content:"\E708"}.el-icon-location:before{content:"\E79E"}.el-icon-place:before{content:"\E709"}.el-icon-discover:before{content:"\E70A"}.el-icon-first-aid-kit:before{content:"\E70B"}.el-icon-trophy-1:before{content:"\E70C"}.el-icon-trophy:before{content:"\E70D"}.el-icon-medal:before{content:"\E70E"}.el-icon-medal-1:before{content:"\E70F"}.el-icon-stopwatch:before{content:"\E710"}.el-icon-mic:before{content:"\E711"}.el-icon-copy-document:before{content:"\E718"}.el-icon-full-screen:before{content:"\E719"}.el-icon-switch-button:before{content:"\E71B"}.el-icon-aim:before{content:"\E71C"}.el-icon-crop:before{content:"\E71D"}.el-icon-odometer:before{content:"\E71E"}.el-icon-time:before{content:"\E71F"}.el-icon-bangzhu:before{content:"\E724"}.el-icon-close-notification:before{content:"\E726"}.el-icon-microphone:before{content:"\E727"}.el-icon-turn-off-microphone:before{content:"\E728"}.el-icon-position:before{content:"\E729"}.el-icon-postcard:before{content:"\E72A"}.el-icon-message:before{content:"\E72B"}.el-icon-chat-line-square:before{content:"\E72D"}.el-icon-chat-dot-square:before{content:"\E72E"}.el-icon-chat-dot-round:before{content:"\E72F"}.el-icon-chat-square:before{content:"\E730"}.el-icon-chat-line-round:before{content:"\E731"}.el-icon-chat-round:before{content:"\E732"}.el-icon-set-up:before{content:"\E733"}.el-icon-turn-off:before{content:"\E734"}.el-icon-open:before{content:"\E735"}.el-icon-connection:before{content:"\E736"}.el-icon-link:before{content:"\E737"}.el-icon-cpu:before{content:"\E738"}.el-icon-thumb:before{content:"\E739"}.el-icon-female:before{content:"\E73A"}.el-icon-male:before{content:"\E73B"}.el-icon-guide:before{content:"\E73C"}.el-icon-news:before{content:"\E73E"}.el-icon-price-tag:before{content:"\E744"}.el-icon-discount:before{content:"\E745"}.el-icon-wallet:before{content:"\E747"}.el-icon-coin:before{content:"\E748"}.el-icon-money:before{content:"\E749"}.el-icon-bank-card:before{content:"\E74A"}.el-icon-box:before{content:"\E74B"}.el-icon-present:before{content:"\E74C"}.el-icon-sell:before{content:"\E6D5"}.el-icon-sold-out:before{content:"\E6D6"}.el-icon-shopping-bag-2:before{content:"\E74D"}.el-icon-shopping-bag-1:before{content:"\E74E"}.el-icon-shopping-cart-2:before{content:"\E74F"}.el-icon-shopping-cart-1:before{content:"\E750"}.el-icon-shopping-cart-full:before{content:"\E751"}.el-icon-smoking:before{content:"\E752"}.el-icon-no-smoking:before{content:"\E753"}.el-icon-house:before{content:"\E754"}.el-icon-table-lamp:before{content:"\E755"}.el-icon-school:before{content:"\E756"}.el-icon-office-building:before{content:"\E757"}.el-icon-toilet-paper:before{content:"\E758"}.el-icon-notebook-2:before{content:"\E759"}.el-icon-notebook-1:before{content:"\E75A"}.el-icon-files:before{content:"\E75B"}.el-icon-collection:before{content:"\E75C"}.el-icon-receiving:before{content:"\E75D"}.el-icon-suitcase-1:before{content:"\E760"}.el-icon-suitcase:before{content:"\E761"}.el-icon-film:before{content:"\E763"}.el-icon-collection-tag:before{content:"\E765"}.el-icon-data-analysis:before{content:"\E766"}.el-icon-pie-chart:before{content:"\E767"}.el-icon-data-board:before{content:"\E768"}.el-icon-data-line:before{content:"\E76D"}.el-icon-reading:before{content:"\E769"}.el-icon-magic-stick:before{content:"\E76A"}.el-icon-coordinate:before{content:"\E76B"}.el-icon-mouse:before{content:"\E76C"}.el-icon-brush:before{content:"\E76E"}.el-icon-headset:before{content:"\E76F"}.el-icon-umbrella:before{content:"\E770"}.el-icon-scissors:before{content:"\E771"}.el-icon-mobile:before{content:"\E773"}.el-icon-attract:before{content:"\E774"}.el-icon-monitor:before{content:"\E775"}.el-icon-search:before{content:"\E778"}.el-icon-takeaway-box:before{content:"\E77A"}.el-icon-paperclip:before{content:"\E77D"}.el-icon-printer:before{content:"\E77E"}.el-icon-document-add:before{content:"\E782"}.el-icon-document:before{content:"\E785"}.el-icon-document-checked:before{content:"\E786"}.el-icon-document-copy:before{content:"\E787"}.el-icon-document-delete:before{content:"\E788"}.el-icon-document-remove:before{content:"\E789"}.el-icon-tickets:before{content:"\E78B"}.el-icon-folder-checked:before{content:"\E77F"}.el-icon-folder-delete:before{content:"\E780"}.el-icon-folder-remove:before{content:"\E781"}.el-icon-folder-add:before{content:"\E783"}.el-icon-folder-opened:before{content:"\E784"}.el-icon-folder:before{content:"\E78A"}.el-icon-edit-outline:before{content:"\E764"}.el-icon-edit:before{content:"\E78C"}.el-icon-date:before{content:"\E78E"}.el-icon-c-scale-to-original:before{content:"\E7C6"}.el-icon-view:before{content:"\E6CE"}.el-icon-loading:before{content:"\E6CF"}.el-icon-rank:before{content:"\E6D1"}.el-icon-sort-down:before{content:"\E7C4"}.el-icon-sort-up:before{content:"\E7C5"}.el-icon-sort:before{content:"\E6D2"}.el-icon-finished:before{content:"\E6CD"}.el-icon-refresh-left:before{content:"\E6C7"}.el-icon-refresh-right:before{content:"\E6C8"}.el-icon-refresh:before{content:"\E6D0"}.el-icon-video-play:before{content:"\E7C0"}.el-icon-video-pause:before{content:"\E7C1"}.el-icon-d-arrow-right:before{content:"\E6DC"}.el-icon-d-arrow-left:before{content:"\E6DD"}.el-icon-arrow-up:before{content:"\E6E1"}.el-icon-arrow-down:before{content:"\E6DF"}.el-icon-arrow-right:before{content:"\E6E0"}.el-icon-arrow-left:before{content:"\E6DE"}.el-icon-top-right:before{content:"\E6E7"}.el-icon-top-left:before{content:"\E6E8"}.el-icon-top:before{content:"\E6E6"}.el-icon-bottom:before{content:"\E6EB"}.el-icon-right:before{content:"\E6E9"}.el-icon-back:before{content:"\E6EA"}.el-icon-bottom-right:before{content:"\E6EC"}.el-icon-bottom-left:before{content:"\E6ED"}.el-icon-caret-top:before{content:"\E78F"}.el-icon-caret-bottom:before{content:"\E790"}.el-icon-caret-right:before{content:"\E791"}.el-icon-caret-left:before{content:"\E792"}.el-icon-d-caret:before{content:"\E79A"}.el-icon-share:before{content:"\E793"}.el-icon-menu:before{content:"\E798"}.el-icon-s-grid:before{content:"\E7A6"}.el-icon-s-check:before{content:"\E7A7"}.el-icon-s-data:before{content:"\E7A8"}.el-icon-s-opportunity:before{content:"\E7AA"}.el-icon-s-custom:before{content:"\E7AB"}.el-icon-s-claim:before{content:"\E7AD"}.el-icon-s-finance:before{content:"\E7AE"}.el-icon-s-comment:before{content:"\E7AF"}.el-icon-s-flag:before{content:"\E7B0"}.el-icon-s-marketing:before{content:"\E7B1"}.el-icon-s-shop:before{content:"\E7B4"}.el-icon-s-open:before{content:"\E7B5"}.el-icon-s-management:before{content:"\E7B6"}.el-icon-s-ticket:before{content:"\E7B7"}.el-icon-s-release:before{content:"\E7B8"}.el-icon-s-home:before{content:"\E7B9"}.el-icon-s-promotion:before{content:"\E7BA"}.el-icon-s-operation:before{content:"\E7BB"}.el-icon-s-unfold:before{content:"\E7BC"}.el-icon-s-fold:before{content:"\E7A9"}.el-icon-s-platform:before{content:"\E7BD"}.el-icon-s-order:before{content:"\E7BE"}.el-icon-s-cooperation:before{content:"\E7BF"}.el-icon-bell:before{content:"\E725"}.el-icon-message-solid:before{content:"\E799"}.el-icon-video-camera:before{content:"\E772"}.el-icon-video-camera-solid:before{content:"\E796"}.el-icon-camera:before{content:"\E779"}.el-icon-camera-solid:before{content:"\E79B"}.el-icon-download:before{content:"\E77C"}.el-icon-upload2:before{content:"\E77B"}.el-icon-upload:before{content:"\E7C3"}.el-icon-picture-outline-round:before{content:"\E75F"}.el-icon-picture-outline:before{content:"\E75E"}.el-icon-picture:before{content:"\E79F"}.el-icon-close:before{content:"\E6DB"}.el-icon-check:before{content:"\E6DA"}.el-icon-plus:before{content:"\E6D9"}.el-icon-minus:before{content:"\E6D8"}.el-icon-help:before{content:"\E73D"}.el-icon-s-help:before{content:"\E7B3"}.el-icon-circle-close:before{content:"\E78D"}.el-icon-circle-check:before{content:"\E720"}.el-icon-circle-plus-outline:before{content:"\E723"}.el-icon-remove-outline:before{content:"\E722"}.el-icon-zoom-out:before{content:"\E776"}.el-icon-zoom-in:before{content:"\E777"}.el-icon-error:before{content:"\E79D"}.el-icon-success:before{content:"\E79C"}.el-icon-circle-plus:before{content:"\E7A0"}.el-icon-remove:before{content:"\E7A2"}.el-icon-info:before{content:"\E7A1"}.el-icon-question:before{content:"\E7A4"}.el-icon-warning-outline:before{content:"\E6C9"}.el-icon-warning:before{content:"\E7A3"}.el-icon-goods:before{content:"\E7C2"}.el-icon-s-goods:before{content:"\E7B2"}.el-icon-star-off:before{content:"\E717"}.el-icon-star-on:before{content:"\E797"}.el-icon-more-outline:before{content:"\E6CC"}.el-icon-more:before{content:"\E794"}.el-icon-phone-outline:before{content:"\E6CB"}.el-icon-phone:before{content:"\E795"}.el-icon-user:before{content:"\E6E3"}.el-icon-user-solid:before{content:"\E7A5"}.el-icon-setting:before{content:"\E6CA"}.el-icon-s-tools:before{content:"\E7AC"}.el-icon-delete:before{content:"\E6D7"}.el-icon-delete-solid:before{content:"\E7C9"}.el-icon-eleme:before{content:"\E7C7"}.el-icon-platform-eleme:before{content:"\E7CA"}.el-icon-loading{animation:rotating 2s linear infinite}.el-icon--right{margin-left:5px}.el-icon--left{margin-right:5px}@keyframes rotating{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.el-pagination{white-space:nowrap;padding:2px 5px;color:#303133;font-weight:700}.el-pagination:after,.el-pagination:before{display:table;content:""}.el-pagination:after{clear:both}.el-pagination button,.el-pagination span:not([class*=suffix]){display:inline-block;font-size:13px;min-width:35.5px;height:28px;line-height:28px;vertical-align:top;box-sizing:border-box}.el-pagination .el-input__inner{text-align:center;-moz-appearance:textfield;line-height:normal}.el-pagination .el-input__suffix{right:0;transform:scale(.8)}.el-pagination .el-select .el-input{width:100px;margin:0 5px}.el-pagination .el-select .el-input .el-input__inner{padding-right:25px;border-radius:3px}.el-pagination button{border:none;padding:0 6px;background:transparent}.el-pagination button:focus{outline:none}.el-pagination button:hover{color:#42d885}.el-pagination button:disabled{color:#c0c4cc;background-color:#fff;cursor:not-allowed}.el-pagination .btn-next,.el-pagination .btn-prev{background:50% no-repeat;background-size:16px;background-color:#fff;cursor:pointer;margin:0;color:#303133}.el-pagination .btn-next .el-icon,.el-pagination .btn-prev .el-icon{display:block;font-size:12px;font-weight:700}.el-pagination .btn-prev{padding-right:12px}.el-pagination .btn-next{padding-left:12px}.el-pagination .el-pager li.disabled{color:#c0c4cc;cursor:not-allowed}.el-pagination--small .btn-next,.el-pagination--small .btn-prev,.el-pagination--small .el-pager li,.el-pagination--small .el-pager li.btn-quicknext,.el-pagination--small .el-pager li.btn-quickprev,.el-pagination--small .el-pager li:last-child{border-color:transparent;font-size:12px;line-height:22px;height:22px;min-width:22px}.el-pagination--small .arrow.disabled{visibility:hidden}.el-pagination--small .more:before,.el-pagination--small li.more:before{line-height:24px}.el-pagination--small button,.el-pagination--small span:not([class*=suffix]){height:22px;line-height:22px}.el-pagination--small .el-pagination__editor,.el-pagination--small .el-pagination__editor.el-input .el-input__inner{height:22px}.el-pagination__sizes{margin:0 10px 0 0;font-weight:400;color:#606266}.el-pagination__sizes .el-input .el-input__inner{font-size:13px;padding-left:8px}.el-pagination__sizes .el-input .el-input__inner:hover{border-color:#42d885}.el-pagination__total{margin-right:10px;font-weight:400;color:#606266}.el-pagination__jump{margin-left:24px;font-weight:400;color:#606266}.el-pagination__jump .el-input__inner{padding:0 3px}.el-pagination__rightwrapper{float:right}.el-pagination__editor{line-height:18px;padding:0 2px;height:28px;text-align:center;margin:0 2px;box-sizing:border-box;border-radius:3px}.el-pagination__editor.el-input{width:50px}.el-pagination__editor.el-input .el-input__inner{height:28px}.el-pagination__editor .el-input__inner::-webkit-inner-spin-button,.el-pagination__editor .el-input__inner::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.el-pagination.is-background .btn-next,.el-pagination.is-background .btn-prev,.el-pagination.is-background .el-pager li{margin:0 5px;background-color:#f4f4f5;color:#606266;min-width:30px;border-radius:2px}.el-pagination.is-background .btn-next.disabled,.el-pagination.is-background .btn-prev.disabled,.el-pagination.is-background .el-pager li.disabled{color:#c0c4cc}.el-pagination.is-background .btn-next,.el-pagination.is-background .btn-prev{padding:0}.el-pagination.is-background .btn-next:disabled,.el-pagination.is-background .btn-prev:disabled{color:#c0c4cc}.el-pagination.is-background .el-pager li:not(.disabled):hover{color:#42d885}.el-pagination.is-background .el-pager li:not(.disabled).active{background-color:#42d885;color:#fff}.el-pagination.is-background.el-pagination--small .btn-next,.el-pagination.is-background.el-pagination--small .btn-prev,.el-pagination.is-background.el-pagination--small .el-pager li{margin:0 3px;min-width:22px}.el-pager{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;list-style:none;display:inline-block;vertical-align:top;font-size:0;padding:0;margin:0}.el-pager .more:before{line-height:30px}.el-pager li{padding:0 4px;background:#fff;vertical-align:top;display:inline-block;font-size:13px;min-width:35.5px;height:28px;line-height:28px;cursor:pointer;box-sizing:border-box;text-align:center;margin:0}.el-pager li.btn-quicknext,.el-pager li.btn-quickprev{line-height:28px;color:#303133}.el-pager li.btn-quicknext.disabled,.el-pager li.btn-quickprev.disabled{color:#c0c4cc}.el-pager li.btn-quicknext:hover,.el-pager li.btn-quickprev:hover{cursor:pointer}.el-pager li.active+li{border-left:0}.el-pager li:hover{color:#42d885}.el-pager li.active{color:#42d885;cursor:default}.el-dialog{position:relative;margin:0 auto 50px;background:#fff;border-radius:2px;box-shadow:0 1px 3px rgba(0,0,0,.3);box-sizing:border-box;width:50%}.el-dialog.is-fullscreen{width:100%;margin-top:0;margin-bottom:0;height:100%;overflow:auto}.el-dialog__wrapper{position:fixed;top:0;right:0;bottom:0;left:0;overflow:auto;margin:0}.el-dialog__header{padding:20px;padding-bottom:10px}.el-dialog__headerbtn{position:absolute;top:20px;right:20px;padding:0;background:transparent;border:none;outline:none;cursor:pointer;font-size:16px}.el-dialog__headerbtn .el-dialog__close{color:#909399}.el-dialog__headerbtn:focus .el-dialog__close,.el-dialog__headerbtn:hover .el-dialog__close{color:#42d885}.el-dialog__title{line-height:24px;font-size:18px;color:#303133}.el-dialog__body{padding:30px 20px;color:#606266;font-size:14px;word-break:break-all}.el-dialog__footer{padding:20px;padding-top:10px;text-align:right;box-sizing:border-box}.el-dialog--center{text-align:center}.el-dialog--center .el-dialog__body{text-align:initial;padding:25px 25px 30px}.el-dialog--center .el-dialog__footer{text-align:inherit}.dialog-fade-enter-active{animation:dialog-fade-in .3s}.dialog-fade-leave-active{animation:dialog-fade-out .3s}@keyframes dialog-fade-in{0%{transform:translate3d(0,-20px,0);opacity:0}to{transform:translateZ(0);opacity:1}}@keyframes dialog-fade-out{0%{transform:translateZ(0);opacity:1}to{transform:translate3d(0,-20px,0);opacity:0}}.el-autocomplete{position:relative;display:inline-block}.el-autocomplete-suggestion{margin:5px 0;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);border-radius:4px;border:1px solid #e4e7ed;box-sizing:border-box;background-color:#fff}.el-autocomplete-suggestion__wrap{max-height:280px;padding:10px 0;box-sizing:border-box}.el-autocomplete-suggestion__list{margin:0;padding:0}.el-autocomplete-suggestion li{padding:0 20px;margin:0;line-height:34px;cursor:pointer;color:#606266;font-size:14px;list-style:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.el-autocomplete-suggestion li.highlighted,.el-autocomplete-suggestion li:hover{background-color:#f5f7fa}.el-autocomplete-suggestion li.divider{margin-top:6px;border-top:1px solid #000}.el-autocomplete-suggestion li.divider:last-child{margin-bottom:-6px}.el-autocomplete-suggestion.is-loading li{text-align:center;height:100px;line-height:100px;font-size:20px;color:#999}.el-autocomplete-suggestion.is-loading li:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-autocomplete-suggestion.is-loading li:hover{background-color:#fff}.el-autocomplete-suggestion.is-loading .el-icon-loading{vertical-align:middle}.el-dropdown{display:inline-block;position:relative;color:#606266;font-size:14px}.el-dropdown .el-button-group{display:block}.el-dropdown .el-button-group .el-button{float:none}.el-dropdown .el-dropdown__caret-button{padding-left:5px;padding-right:5px;position:relative;border-left:none}.el-dropdown .el-dropdown__caret-button:before{content:"";position:absolute;display:block;width:1px;top:5px;bottom:5px;left:0;background:hsla(0,0%,100%,.5)}.el-dropdown .el-dropdown__caret-button.el-button--default:before{background:rgba(220,223,230,.5)}.el-dropdown .el-dropdown__caret-button:hover:before{top:0;bottom:0}.el-dropdown .el-dropdown__caret-button .el-dropdown__icon{padding-left:0}.el-dropdown__icon{font-size:12px;margin:0 3px}.el-dropdown .el-dropdown-selfdefine:focus:active,.el-dropdown .el-dropdown-selfdefine:focus:not(.focusing){outline-width:0}.el-dropdown-menu{position:absolute;top:0;left:0;z-index:10;padding:10px 0;margin:5px 0;background-color:#fff;border:1px solid #ebeef5;border-radius:4px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1)}.el-dropdown-menu__item{list-style:none;line-height:36px;padding:0 20px;margin:0;font-size:14px;color:#606266;cursor:pointer;outline:none}.el-dropdown-menu__item:focus,.el-dropdown-menu__item:not(.is-disabled):hover{background-color:#ecfbf3;color:#68e09d}.el-dropdown-menu__item i{margin-right:5px}.el-dropdown-menu__item--divided{position:relative;margin-top:6px;border-top:1px solid #ebeef5}.el-dropdown-menu__item--divided:before{content:"";height:6px;display:block;margin:0 -20px;background-color:#fff}.el-dropdown-menu__item.is-disabled{cursor:default;color:#bbb;pointer-events:none}.el-dropdown-menu--medium{padding:6px 0}.el-dropdown-menu--medium .el-dropdown-menu__item{line-height:30px;padding:0 17px;font-size:14px}.el-dropdown-menu--medium .el-dropdown-menu__item.el-dropdown-menu__item--divided{margin-top:6px}.el-dropdown-menu--medium .el-dropdown-menu__item.el-dropdown-menu__item--divided:before{height:6px;margin:0 -17px}.el-dropdown-menu--small{padding:6px 0}.el-dropdown-menu--small .el-dropdown-menu__item{line-height:27px;padding:0 15px;font-size:13px}.el-dropdown-menu--small .el-dropdown-menu__item.el-dropdown-menu__item--divided{margin-top:4px}.el-dropdown-menu--small .el-dropdown-menu__item.el-dropdown-menu__item--divided:before{height:4px;margin:0 -15px}.el-dropdown-menu--mini{padding:3px 0}.el-dropdown-menu--mini .el-dropdown-menu__item{line-height:24px;padding:0 10px;font-size:12px}.el-dropdown-menu--mini .el-dropdown-menu__item.el-dropdown-menu__item--divided{margin-top:3px}.el-dropdown-menu--mini .el-dropdown-menu__item.el-dropdown-menu__item--divided:before{height:3px;margin:0 -10px}.el-menu{border-right:1px solid #e6e6e6;list-style:none;position:relative;margin:0;padding-left:0;background-color:#fff}.el-menu:after,.el-menu:before{display:table;content:""}.el-menu:after{clear:both}.el-menu.el-menu--horizontal{border-bottom:1px solid #e6e6e6}.el-menu--horizontal{border-right:none}.el-menu--horizontal>.el-menu-item{float:left;height:60px;line-height:60px;margin:0;border-bottom:2px solid transparent;color:#909399}.el-menu--horizontal>.el-menu-item a,.el-menu--horizontal>.el-menu-item a:hover{color:inherit}.el-menu--horizontal>.el-menu-item:not(.is-disabled):focus,.el-menu--horizontal>.el-menu-item:not(.is-disabled):hover{background-color:#fff}.el-menu--horizontal>.el-submenu{float:left}.el-menu--horizontal>.el-submenu:focus,.el-menu--horizontal>.el-submenu:hover{outline:none}.el-menu--horizontal>.el-submenu:focus .el-submenu__title,.el-menu--horizontal>.el-submenu:hover .el-submenu__title{color:#303133}.el-menu--horizontal>.el-submenu.is-active .el-submenu__title{border-bottom:2px solid #42d885;color:#303133}.el-menu--horizontal>.el-submenu .el-submenu__title{height:60px;line-height:60px;border-bottom:2px solid transparent;color:#909399}.el-menu--horizontal>.el-submenu .el-submenu__title:hover{background-color:#fff}.el-menu--horizontal>.el-submenu .el-submenu__icon-arrow{position:static;vertical-align:middle;margin-left:8px;margin-top:-3px}.el-menu--horizontal .el-menu .el-menu-item,.el-menu--horizontal .el-menu .el-submenu__title{background-color:#fff;float:none;height:36px;line-height:36px;padding:0 10px;color:#909399}.el-menu--horizontal .el-menu .el-menu-item.is-active,.el-menu--horizontal .el-menu .el-submenu.is-active>.el-submenu__title{color:#303133}.el-menu--horizontal .el-menu-item:not(.is-disabled):focus,.el-menu--horizontal .el-menu-item:not(.is-disabled):hover{outline:none;color:#303133}.el-menu--horizontal>.el-menu-item.is-active{border-bottom:2px solid #42d885;color:#303133}.el-menu--collapse{width:64px}.el-menu--collapse>.el-menu-item [class^=el-icon-],.el-menu--collapse>.el-submenu>.el-submenu__title [class^=el-icon-]{margin:0;vertical-align:middle;width:24px;text-align:center}.el-menu--collapse>.el-menu-item .el-submenu__icon-arrow,.el-menu--collapse>.el-submenu>.el-submenu__title .el-submenu__icon-arrow{display:none}.el-menu--collapse>.el-menu-item span,.el-menu--collapse>.el-submenu>.el-submenu__title span{height:0;width:0;overflow:hidden;visibility:hidden;display:inline-block}.el-menu--collapse>.el-menu-item.is-active i{color:inherit}.el-menu--collapse .el-menu .el-submenu{min-width:200px}.el-menu--collapse .el-submenu{position:relative}.el-menu--collapse .el-submenu .el-menu{position:absolute;margin-left:5px;top:0;left:100%;z-index:10;border:1px solid #e4e7ed;border-radius:2px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1)}.el-menu--collapse .el-submenu.is-opened>.el-submenu__title .el-submenu__icon-arrow{transform:none}.el-menu--popup{z-index:100;min-width:200px;border:none;padding:5px 0;border-radius:2px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1)}.el-menu--popup-bottom-start{margin-top:5px}.el-menu--popup-right-start{margin-left:5px;margin-right:5px}.el-menu-item{height:56px;line-height:56px;font-size:14px;color:#303133;padding:0 20px;list-style:none;cursor:pointer;position:relative;transition:border-color .3s,background-color .3s,color .3s;box-sizing:border-box;white-space:nowrap}.el-menu-item *{vertical-align:middle}.el-menu-item i{color:#909399}.el-menu-item:focus,.el-menu-item:hover{outline:none;background-color:#ecfbf3}.el-menu-item.is-disabled{opacity:.25;cursor:not-allowed;background:none!important}.el-menu-item [class^=el-icon-]{margin-right:5px;width:24px;text-align:center;font-size:18px;vertical-align:middle}.el-menu-item.is-active{color:#42d885}.el-menu-item.is-active i{color:inherit}.el-submenu{list-style:none;margin:0;padding-left:0}.el-submenu__title{height:56px;line-height:56px;font-size:14px;color:#303133;padding:0 20px;list-style:none;cursor:pointer;position:relative;transition:border-color .3s,background-color .3s,color .3s;box-sizing:border-box;white-space:nowrap}.el-submenu__title *{vertical-align:middle}.el-submenu__title i{color:#909399}.el-submenu__title:focus,.el-submenu__title:hover{outline:none;background-color:#ecfbf3}.el-submenu__title.is-disabled{opacity:.25;cursor:not-allowed;background:none!important}.el-submenu__title:hover{background-color:#ecfbf3}.el-submenu .el-menu{border:none}.el-submenu .el-menu-item{height:50px;line-height:50px;padding:0 45px;min-width:200px}.el-submenu__icon-arrow{position:absolute;top:50%;right:20px;margin-top:-7px;transition:transform .3s;font-size:12px}.el-submenu.is-active .el-submenu__title{border-bottom-color:#42d885}.el-submenu.is-opened>.el-submenu__title .el-submenu__icon-arrow{transform:rotate(180deg)}.el-submenu.is-disabled .el-menu-item,.el-submenu.is-disabled .el-submenu__title{opacity:.25;cursor:not-allowed;background:none!important}.el-submenu [class^=el-icon-]{vertical-align:middle;margin-right:5px;width:24px;text-align:center;font-size:18px}.el-menu-item-group>ul{padding:0}.el-menu-item-group__title{padding:7px 0 7px 20px;line-height:normal;font-size:12px;color:#909399}.horizontal-collapse-transition .el-submenu__title .el-submenu__icon-arrow{transition:.2s;opacity:0}.el-radio-group{display:inline-block;line-height:1;vertical-align:middle;font-size:0}.el-radio-button,.el-radio-button__inner{position:relative;display:inline-block;outline:none}.el-radio-button__inner{line-height:1;white-space:nowrap;vertical-align:middle;background:#fff;border:1px solid #dcdfe6;font-weight:500;border-left:0;color:#606266;-webkit-appearance:none;text-align:center;box-sizing:border-box;margin:0;cursor:pointer;transition:all .3s cubic-bezier(.645,.045,.355,1);padding:12px 20px;font-size:14px;border-radius:0}.el-radio-button__inner.is-round{padding:12px 20px}.el-radio-button__inner:hover{color:#42d885}.el-radio-button__inner [class*=el-icon-]{line-height:.9}.el-radio-button__inner [class*=el-icon-]+span{margin-left:5px}.el-radio-button:first-child .el-radio-button__inner{border-left:1px solid #dcdfe6;border-radius:4px 0 0 4px;box-shadow:none!important}.el-radio-button__orig-radio{opacity:0;outline:none;position:absolute;z-index:-1}.el-radio-button__orig-radio:checked+.el-radio-button__inner{color:#fff;background-color:#42d885;border-color:#42d885;box-shadow:-1px 0 0 0 #42d885}.el-radio-button__orig-radio:disabled+.el-radio-button__inner{color:#c0c4cc;cursor:not-allowed;background-image:none;background-color:#fff;border-color:#ebeef5;box-shadow:none}.el-radio-button__orig-radio:disabled:checked+.el-radio-button__inner{background-color:#f2f6fc}.el-radio-button:last-child .el-radio-button__inner{border-radius:0 4px 4px 0}.el-radio-button:first-child:last-child .el-radio-button__inner{border-radius:4px}.el-radio-button--medium .el-radio-button__inner{padding:10px 20px;font-size:14px;border-radius:0}.el-radio-button--medium .el-radio-button__inner.is-round{padding:10px 20px}.el-radio-button--small .el-radio-button__inner{padding:9px 15px;font-size:12px;border-radius:0}.el-radio-button--small .el-radio-button__inner.is-round{padding:9px 15px}.el-radio-button--mini .el-radio-button__inner{padding:7px 15px;font-size:12px;border-radius:0}.el-radio-button--mini .el-radio-button__inner.is-round{padding:7px 15px}.el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled){box-shadow:0 0 2px 2px #42d885}.el-switch{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;position:relative;font-size:14px;line-height:20px;height:20px;vertical-align:middle}.el-switch.is-disabled .el-switch__core,.el-switch.is-disabled .el-switch__label{cursor:not-allowed}.el-switch__label{transition:.2s;height:20px;display:inline-block;font-size:14px;font-weight:500;cursor:pointer;vertical-align:middle;color:#303133}.el-switch__label.is-active{color:#42d885}.el-switch__label--left{margin-right:10px}.el-switch__label--right{margin-left:10px}.el-switch__label *{line-height:1;font-size:14px;display:inline-block}.el-switch__input{position:absolute;width:0;height:0;opacity:0;margin:0}.el-switch__core{margin:0;display:inline-block;position:relative;width:40px;height:20px;border:1px solid #dcdfe6;outline:none;border-radius:10px;box-sizing:border-box;background:#dcdfe6;cursor:pointer;transition:border-color .3s,background-color .3s;vertical-align:middle}.el-switch__core:after{content:"";position:absolute;top:1px;left:1px;border-radius:100%;transition:all .3s;width:16px;height:16px;background-color:#fff}.el-switch.is-checked .el-switch__core{border-color:#42d885;background-color:#42d885}.el-switch.is-checked .el-switch__core:after{left:100%;margin-left:-17px}.el-switch.is-disabled{opacity:.6}.el-switch--wide .el-switch__label.el-switch__label--left span{left:10px}.el-switch--wide .el-switch__label.el-switch__label--right span{right:10px}.el-switch .label-fade-enter,.el-switch .label-fade-leave-active{opacity:0}.el-select-dropdown{position:absolute;z-index:1001;border:1px solid #e4e7ed;border-radius:4px;background-color:#fff;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);box-sizing:border-box;margin:5px 0}.el-select-dropdown.is-multiple .el-select-dropdown__item.selected{color:#42d885;background-color:#fff}.el-select-dropdown.is-multiple .el-select-dropdown__item.selected.hover{background-color:#f5f7fa}.el-select-dropdown.is-multiple .el-select-dropdown__item.selected:after{position:absolute;right:20px;font-family:element-icons;content:"\E6DA";font-size:12px;font-weight:700;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.el-select-dropdown .el-scrollbar.is-empty .el-select-dropdown__list{padding:0}.el-select-dropdown__empty{padding:10px 0;margin:0;text-align:center;color:#999;font-size:14px}.el-select-dropdown__wrap{max-height:274px}.el-select-dropdown__list{list-style:none;padding:6px 0;margin:0;box-sizing:border-box}.el-select-dropdown__item{font-size:14px;padding:0 20px;position:relative;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#606266;height:34px;line-height:34px;box-sizing:border-box;cursor:pointer}.el-select-dropdown__item.is-disabled{color:#c0c4cc;cursor:not-allowed}.el-select-dropdown__item.is-disabled:hover{background-color:#fff}.el-select-dropdown__item.hover,.el-select-dropdown__item:hover{background-color:#f5f7fa}.el-select-dropdown__item.selected{color:#42d885;font-weight:700}.el-select-group{margin:0;padding:0}.el-select-group__wrap{position:relative;list-style:none;margin:0;padding:0}.el-select-group__wrap:not(:last-of-type){padding-bottom:24px}.el-select-group__wrap:not(:last-of-type):after{content:"";position:absolute;display:block;left:20px;right:20px;bottom:12px;height:1px;background:#e4e7ed}.el-select-group__title{padding-left:20px;font-size:12px;color:#909399;line-height:30px}.el-select-group .el-select-dropdown__item{padding-left:20px}.el-select{display:inline-block;position:relative}.el-select .el-select__tags>span{display:contents}.el-select:hover .el-input__inner{border-color:#c0c4cc}.el-select .el-input__inner{cursor:pointer;padding-right:35px}.el-select .el-input__inner:focus{border-color:#42d885}.el-select .el-input .el-select__caret{color:#c0c4cc;font-size:14px;transition:transform .3s;transform:rotate(180deg);cursor:pointer}.el-select .el-input .el-select__caret.is-reverse{transform:rotate(0deg)}.el-select .el-input .el-select__caret.is-show-close{font-size:14px;text-align:center;transform:rotate(180deg);border-radius:100%;color:#c0c4cc;transition:color .2s cubic-bezier(.645,.045,.355,1)}.el-select .el-input .el-select__caret.is-show-close:hover{color:#909399}.el-select .el-input.is-disabled .el-input__inner{cursor:not-allowed}.el-select .el-input.is-disabled .el-input__inner:hover{border-color:#e4e7ed}.el-select .el-input.is-focus .el-input__inner{border-color:#42d885}.el-select>.el-input{display:block}.el-select__input{border:none;outline:none;padding:0;margin-left:15px;color:#666;font-size:14px;-webkit-appearance:none;-moz-appearance:none;appearance:none;height:28px;background-color:transparent}.el-select__input.is-mini{height:14px}.el-select__close{cursor:pointer;position:absolute;top:8px;z-index:1000;right:25px;color:#c0c4cc;line-height:18px;font-size:14px}.el-select__close:hover{color:#909399}.el-select__tags{position:absolute;line-height:normal;white-space:normal;z-index:1;top:50%;transform:translateY(-50%);display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-wrap:wrap;flex-wrap:wrap}.el-select .el-tag__close{margin-top:-2px}.el-select .el-tag{box-sizing:border-box;border-color:transparent;margin:2px 0 2px 6px;background-color:#f0f2f5}.el-select .el-tag__close.el-icon-close{background-color:#c0c4cc;right:-7px;top:0;color:#fff}.el-select .el-tag__close.el-icon-close:hover{background-color:#909399}.el-select .el-tag__close.el-icon-close:before{display:block;transform:translateY(.5px)}.el-table{position:relative;overflow:hidden;box-sizing:border-box;-ms-flex:1;flex:1;width:100%;max-width:100%;background-color:#fff;font-size:14px;color:#606266}.el-table__empty-block{min-height:60px;text-align:center;width:100%;height:100%;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.el-table__empty-text{line-height:60px;width:50%;color:#909399}.el-table__expand-column .cell{padding:0;text-align:center}.el-table__expand-icon{position:relative;cursor:pointer;color:#666;font-size:12px;transition:transform .2s ease-in-out;height:20px}.el-table__expand-icon--expanded{transform:rotate(90deg)}.el-table__expand-icon>.el-icon{position:absolute;left:50%;top:50%;margin-left:-5px;margin-top:-5px}.el-table__expanded-cell{background-color:#fff}.el-table__expanded-cell[class*=cell]{padding:20px 50px}.el-table__expanded-cell:hover{background-color:transparent!important}.el-table__placeholder{display:inline-block;width:20px}.el-table__append-wrapper{overflow:hidden}.el-table--fit{border-right:0;border-bottom:0}.el-table--fit td.gutter,.el-table--fit th.gutter{border-right-width:1px}.el-table--scrollable-x .el-table__body-wrapper{overflow-x:auto}.el-table--scrollable-y .el-table__body-wrapper{overflow-y:auto}.el-table thead{color:#909399;font-weight:500}.el-table thead.is-group th{background:#f5f7fa}.el-table td,.el-table th{padding:12px 0;min-width:0;box-sizing:border-box;text-overflow:ellipsis;vertical-align:middle;position:relative;text-align:left}.el-table td.is-center,.el-table th.is-center{text-align:center}.el-table td.is-right,.el-table th.is-right{text-align:right}.el-table td.gutter,.el-table th.gutter{width:15px;border-right-width:0;border-bottom-width:0;padding:0}.el-table td.is-hidden>*,.el-table th.is-hidden>*{visibility:hidden}.el-table--medium td,.el-table--medium th{padding:10px 0}.el-table--small{font-size:12px}.el-table--small td,.el-table--small th{padding:8px 0}.el-table--mini{font-size:12px}.el-table--mini td,.el-table--mini th{padding:6px 0}.el-table tr{background-color:#fff}.el-table tr input[type=checkbox]{margin:0}.el-table td,.el-table th.is-leaf{border-bottom:1px solid #ebeef5}.el-table th.is-sortable{cursor:pointer}.el-table th{white-space:nowrap;overflow:hidden;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#fff}.el-table th div{padding-left:10px;padding-right:10px;line-height:40px;overflow:hidden;white-space:nowrap}.el-table th>.cell,.el-table th div{display:inline-block;box-sizing:border-box;text-overflow:ellipsis}.el-table th>.cell{position:relative;word-wrap:normal;vertical-align:middle;width:100%}.el-table th>.cell.highlight{color:#42d885}.el-table th.required>div:before{display:inline-block;content:"";width:8px;height:8px;border-radius:50%;background:#ff4d51;margin-right:5px;vertical-align:middle}.el-table td div{box-sizing:border-box}.el-table td.gutter{width:0}.el-table .cell{box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:normal;word-break:break-all;line-height:23px;padding-left:10px;padding-right:10px}.el-table .cell.el-tooltip{white-space:nowrap;min-width:50px}.el-table--border,.el-table--group{border:1px solid #ebeef5}.el-table--border:after,.el-table--group:after,.el-table:before{content:"";position:absolute;background-color:#ebeef5;z-index:1}.el-table--border:after,.el-table--group:after{top:0;right:0;width:1px;height:100%}.el-table:before{left:0;bottom:0;width:100%;height:1px}.el-table--border{border-right:none;border-bottom:none}.el-table--border.el-loading-parent--relative{border-color:transparent}.el-table--border td,.el-table--border th{border-right:1px solid #ebeef5}.el-table--border td:first-child .cell,.el-table--border th:first-child .cell{padding-left:10px}.el-table--border th.gutter:last-of-type{border-bottom:1px solid #ebeef5;border-bottom-width:1px}.el-table--border th{border-bottom:1px solid #ebeef5}.el-table--hidden{visibility:hidden}.el-table__fixed,.el-table__fixed-right{position:absolute;top:0;left:0;overflow-x:hidden;overflow-y:hidden;box-shadow:0 0 10px rgba(0,0,0,.12)}.el-table__fixed-right:before,.el-table__fixed:before{content:"";position:absolute;left:0;bottom:0;width:100%;height:1px;background-color:#ebeef5;z-index:4}.el-table__fixed-right-patch{position:absolute;top:-1px;right:0;background-color:#fff;border-bottom:1px solid #ebeef5}.el-table__fixed-right{top:0;left:auto;right:0}.el-table__fixed-right .el-table__fixed-body-wrapper,.el-table__fixed-right .el-table__fixed-footer-wrapper,.el-table__fixed-right .el-table__fixed-header-wrapper{left:auto;right:0}.el-table__fixed-header-wrapper{position:absolute;left:0;top:0;z-index:3}.el-table__fixed-footer-wrapper{position:absolute;left:0;bottom:0;z-index:3}.el-table__fixed-footer-wrapper tbody td{border-top:1px solid #ebeef5;background-color:#f5f7fa;color:#606266}.el-table__fixed-body-wrapper{position:absolute;left:0;top:37px;overflow:hidden;z-index:3}.el-table__body-wrapper,.el-table__footer-wrapper,.el-table__header-wrapper{width:100%}.el-table__footer-wrapper{margin-top:-1px}.el-table__footer-wrapper td{border-top:1px solid #ebeef5}.el-table__body,.el-table__footer,.el-table__header{table-layout:fixed;border-collapse:separate}.el-table__footer-wrapper,.el-table__header-wrapper{overflow:hidden}.el-table__footer-wrapper tbody td,.el-table__header-wrapper tbody td{background-color:#f5f7fa;color:#606266}.el-table__body-wrapper{overflow:hidden;position:relative}.el-table__body-wrapper.is-scrolling-left~.el-table__fixed,.el-table__body-wrapper.is-scrolling-none~.el-table__fixed,.el-table__body-wrapper.is-scrolling-none~.el-table__fixed-right,.el-table__body-wrapper.is-scrolling-right~.el-table__fixed-right{box-shadow:none}.el-table__body-wrapper .el-table--border.is-scrolling-right~.el-table__fixed-right{border-left:1px solid #ebeef5}.el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed{border-right:1px solid #ebeef5}.el-table .caret-wrapper{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:center;align-items:center;height:34px;width:24px;vertical-align:middle;cursor:pointer;overflow:initial;position:relative}.el-table .sort-caret{width:0;height:0;border:5px solid transparent;position:absolute;left:7px}.el-table .sort-caret.ascending{border-bottom-color:#c0c4cc;top:5px}.el-table .sort-caret.descending{border-top-color:#c0c4cc;bottom:7px}.el-table .ascending .sort-caret.ascending{border-bottom-color:#42d885}.el-table .descending .sort-caret.descending{border-top-color:#42d885}.el-table .hidden-columns{visibility:hidden;position:absolute;z-index:-1}.el-table--striped .el-table__body tr.el-table__row--striped td{background:#fafafa}.el-table--striped .el-table__body tr.el-table__row--striped.current-row td{background-color:#ecfbf3}.el-table__body tr.hover-row.current-row>td,.el-table__body tr.hover-row.el-table__row--striped.current-row>td,.el-table__body tr.hover-row.el-table__row--striped>td,.el-table__body tr.hover-row>td{background-color:#f5f7fa}.el-table__body tr.current-row>td{background-color:#ecfbf3}.el-table__column-resize-proxy{position:absolute;left:200px;top:0;bottom:0;width:0;border-left:1px solid #ebeef5;z-index:10}.el-table__column-filter-trigger{display:inline-block;line-height:34px;cursor:pointer}.el-table__column-filter-trigger i{color:#909399;font-size:12px;transform:scale(.75)}.el-table--enable-row-transition .el-table__body td{transition:background-color .25s ease}.el-table--enable-row-hover .el-table__body tr:hover>td{background-color:#f5f7fa}.el-table--fluid-height .el-table__fixed,.el-table--fluid-height .el-table__fixed-right{bottom:0;overflow:hidden}.el-table [class*=el-table__row--level] .el-table__expand-icon{display:inline-block;width:20px;line-height:20px;height:20px;text-align:center;margin-right:3px}.el-table-column--selection .cell{padding-left:14px;padding-right:14px}.el-table-filter{border:1px solid #ebeef5;border-radius:2px;background-color:#fff;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);box-sizing:border-box;margin:2px 0}.el-table-filter__list{padding:5px 0;margin:0;list-style:none;min-width:100px}.el-table-filter__list-item{line-height:36px;padding:0 10px;cursor:pointer;font-size:14px}.el-table-filter__list-item:hover{background-color:#ecfbf3;color:#68e09d}.el-table-filter__list-item.is-active{background-color:#42d885;color:#fff}.el-table-filter__content{min-width:100px}.el-table-filter__bottom{border-top:1px solid #ebeef5;padding:8px}.el-table-filter__bottom button{background:transparent;border:none;color:#606266;cursor:pointer;font-size:13px;padding:0 3px}.el-table-filter__bottom button:hover{color:#42d885}.el-table-filter__bottom button:focus{outline:none}.el-table-filter__bottom button.is-disabled{color:#c0c4cc;cursor:not-allowed}.el-table-filter__wrap{max-height:280px}.el-table-filter__checkbox-group{padding:10px}.el-table-filter__checkbox-group label.el-checkbox{display:block;margin-right:5px;margin-bottom:8px;margin-left:5px}.el-table-filter__checkbox-group .el-checkbox:last-child{margin-bottom:0}.el-date-table{font-size:12px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.el-date-table.is-week-mode .el-date-table__row:hover div{background-color:#f2f6fc}.el-date-table.is-week-mode .el-date-table__row:hover td.available:hover{color:#606266}.el-date-table.is-week-mode .el-date-table__row:hover td:first-child div{margin-left:5px;border-top-left-radius:15px;border-bottom-left-radius:15px}.el-date-table.is-week-mode .el-date-table__row:hover td:last-child div{margin-right:5px;border-top-right-radius:15px;border-bottom-right-radius:15px}.el-date-table.is-week-mode .el-date-table__row.current div{background-color:#f2f6fc}.el-date-table td{width:32px;height:30px;padding:4px 0;box-sizing:border-box;text-align:center;cursor:pointer;position:relative}.el-date-table td div{height:30px;padding:3px 0;box-sizing:border-box}.el-date-table td span{width:24px;height:24px;display:block;margin:0 auto;line-height:24px;position:absolute;left:50%;transform:translateX(-50%);border-radius:50%}.el-date-table td.next-month,.el-date-table td.prev-month{color:#c0c4cc}.el-date-table td.today{position:relative}.el-date-table td.today span{color:#42d885;font-weight:700}.el-date-table td.today.end-date span,.el-date-table td.today.start-date span{color:#fff}.el-date-table td.available:hover{color:#42d885}.el-date-table td.in-range div,.el-date-table td.in-range div:hover{background-color:#f2f6fc}.el-date-table td.current:not(.disabled) span{color:#fff;background-color:#42d885}.el-date-table td.end-date div,.el-date-table td.start-date div{color:#fff}.el-date-table td.end-date span,.el-date-table td.start-date span{background-color:#42d885}.el-date-table td.start-date div{margin-left:5px;border-top-left-radius:15px;border-bottom-left-radius:15px}.el-date-table td.end-date div{margin-right:5px;border-top-right-radius:15px;border-bottom-right-radius:15px}.el-date-table td.disabled div{background-color:#f5f7fa;opacity:1;cursor:not-allowed;color:#c0c4cc}.el-date-table td.selected div{margin-left:5px;margin-right:5px;background-color:#f2f6fc;border-radius:15px}.el-date-table td.selected div:hover{background-color:#f2f6fc}.el-date-table td.selected span{background-color:#42d885;color:#fff;border-radius:15px}.el-date-table td.week{font-size:80%;color:#606266}.el-date-table th{padding:5px;color:#606266;font-weight:400;border-bottom:1px solid #ebeef5}.el-month-table{font-size:12px;margin:-1px;border-collapse:collapse}.el-month-table td{text-align:center;padding:8px 0;cursor:pointer}.el-month-table td div{height:48px;padding:6px 0;box-sizing:border-box}.el-month-table td.today .cell{color:#42d885;font-weight:700}.el-month-table td.today.end-date .cell,.el-month-table td.today.start-date .cell{color:#fff}.el-month-table td.disabled .cell{background-color:#f5f7fa;cursor:not-allowed;color:#c0c4cc}.el-month-table td.disabled .cell:hover{color:#c0c4cc}.el-month-table td .cell{width:60px;height:36px;display:block;line-height:36px;color:#606266;margin:0 auto;border-radius:18px}.el-month-table td .cell:hover{color:#42d885}.el-month-table td.in-range div,.el-month-table td.in-range div:hover{background-color:#f2f6fc}.el-month-table td.end-date div,.el-month-table td.start-date div{color:#fff}.el-month-table td.end-date .cell,.el-month-table td.start-date .cell{color:#fff;background-color:#42d885}.el-month-table td.start-date div{border-top-left-radius:24px;border-bottom-left-radius:24px}.el-month-table td.end-date div{border-top-right-radius:24px;border-bottom-right-radius:24px}.el-month-table td.current:not(.disabled) .cell{color:#42d885}.el-year-table{font-size:12px;margin:-1px;border-collapse:collapse}.el-year-table .el-icon{color:#303133}.el-year-table td{text-align:center;padding:20px 3px;cursor:pointer}.el-year-table td.today .cell{color:#42d885;font-weight:700}.el-year-table td.disabled .cell{background-color:#f5f7fa;cursor:not-allowed;color:#c0c4cc}.el-year-table td.disabled .cell:hover{color:#c0c4cc}.el-year-table td .cell{width:48px;height:32px;display:block;line-height:32px;color:#606266;margin:0 auto}.el-year-table td .cell:hover,.el-year-table td.current:not(.disabled) .cell{color:#42d885}.el-date-range-picker{width:646px}.el-date-range-picker.has-sidebar{width:756px}.el-date-range-picker table{table-layout:fixed;width:100%}.el-date-range-picker .el-picker-panel__body{min-width:513px}.el-date-range-picker .el-picker-panel__content{margin:0}.el-date-range-picker__header{position:relative;text-align:center;height:28px}.el-date-range-picker__header [class*=arrow-left]{float:left}.el-date-range-picker__header [class*=arrow-right]{float:right}.el-date-range-picker__header div{font-size:16px;font-weight:500;margin-right:50px}.el-date-range-picker__content{float:left;width:50%;box-sizing:border-box;margin:0;padding:16px}.el-date-range-picker__content.is-left{border-right:1px solid #e4e4e4}.el-date-range-picker__content .el-date-range-picker__header div{margin-left:50px;margin-right:50px}.el-date-range-picker__editors-wrap{box-sizing:border-box;display:table-cell}.el-date-range-picker__editors-wrap.is-right{text-align:right}.el-date-range-picker__time-header{position:relative;border-bottom:1px solid #e4e4e4;font-size:12px;padding:8px 5px 5px;display:table;width:100%;box-sizing:border-box}.el-date-range-picker__time-header>.el-icon-arrow-right{font-size:20px;vertical-align:middle;display:table-cell;color:#303133}.el-date-range-picker__time-picker-wrap{position:relative;display:table-cell;padding:0 5px}.el-date-range-picker__time-picker-wrap .el-picker-panel{position:absolute;top:13px;right:0;z-index:1;background:#fff}.el-date-picker{width:322px}.el-date-picker.has-sidebar.has-time{width:434px}.el-date-picker.has-sidebar{width:438px}.el-date-picker.has-time .el-picker-panel__body-wrapper{position:relative}.el-date-picker .el-picker-panel__content{width:292px}.el-date-picker table{table-layout:fixed;width:100%}.el-date-picker__editor-wrap{position:relative;display:table-cell;padding:0 5px}.el-date-picker__time-header{position:relative;border-bottom:1px solid #e4e4e4;font-size:12px;padding:8px 5px 5px;display:table;width:100%;box-sizing:border-box}.el-date-picker__header{margin:12px;text-align:center}.el-date-picker__header--bordered{margin-bottom:0;padding-bottom:12px;border-bottom:1px solid #ebeef5}.el-date-picker__header--bordered+.el-picker-panel__content{margin-top:0}.el-date-picker__header-label{font-size:16px;font-weight:500;padding:0 5px;line-height:22px;text-align:center;cursor:pointer;color:#606266}.el-date-picker__header-label.active,.el-date-picker__header-label:hover{color:#42d885}.el-date-picker__prev-btn{float:left}.el-date-picker__next-btn{float:right}.el-date-picker__time-wrap{padding:10px;text-align:center}.el-date-picker__time-label{float:left;cursor:pointer;line-height:30px;margin-left:10px}.time-select{margin:5px 0;min-width:0}.time-select .el-picker-panel__content{max-height:200px;margin:0}.time-select-item{padding:8px 10px;font-size:14px;line-height:20px}.time-select-item.selected:not(.disabled){color:#42d885;font-weight:700}.time-select-item.disabled{color:#e4e7ed;cursor:not-allowed}.time-select-item:hover{background-color:#f5f7fa;font-weight:700;cursor:pointer}.el-date-editor{position:relative;display:inline-block;text-align:left}.el-date-editor.el-input,.el-date-editor.el-input__inner{width:220px}.el-date-editor--monthrange.el-input,.el-date-editor--monthrange.el-input__inner{width:300px}.el-date-editor--daterange.el-input,.el-date-editor--daterange.el-input__inner,.el-date-editor--timerange.el-input,.el-date-editor--timerange.el-input__inner{width:350px}.el-date-editor--datetimerange.el-input,.el-date-editor--datetimerange.el-input__inner{width:400px}.el-date-editor--dates .el-input__inner{text-overflow:ellipsis;white-space:nowrap}.el-date-editor .el-icon-circle-close{cursor:pointer}.el-date-editor .el-range__icon{font-size:14px;margin-left:-5px;color:#c0c4cc;float:left;line-height:32px}.el-date-editor .el-range-input{-webkit-appearance:none;-moz-appearance:none;appearance:none;border:none;outline:none;display:inline-block;height:100%;margin:0;padding:0;width:39%;text-align:center;font-size:14px;color:#606266}.el-date-editor .el-range-input::-webkit-input-placeholder{color:#c0c4cc}.el-date-editor .el-range-input::-ms-input-placeholder{color:#c0c4cc}.el-date-editor .el-range-input::placeholder{color:#c0c4cc}.el-date-editor .el-range-separator{display:inline-block;height:100%;padding:0 5px;margin:0;text-align:center;line-height:32px;font-size:14px;width:5%;color:#303133}.el-date-editor .el-range__close-icon{font-size:14px;color:#c0c4cc;width:25px;display:inline-block;float:right;line-height:32px}.el-range-editor.el-input__inner{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;padding:3px 10px}.el-range-editor .el-range-input{line-height:1}.el-range-editor.is-active,.el-range-editor.is-active:hover{border-color:#42d885}.el-range-editor--medium.el-input__inner{height:36px}.el-range-editor--medium .el-range-separator{line-height:28px;font-size:14px}.el-range-editor--medium .el-range-input{font-size:14px}.el-range-editor--medium .el-range__close-icon,.el-range-editor--medium .el-range__icon{line-height:28px}.el-range-editor--small.el-input__inner{height:32px}.el-range-editor--small .el-range-separator{line-height:24px;font-size:13px}.el-range-editor--small .el-range-input{font-size:13px}.el-range-editor--small .el-range__close-icon,.el-range-editor--small .el-range__icon{line-height:24px}.el-range-editor--mini.el-input__inner{height:28px}.el-range-editor--mini .el-range-separator{line-height:20px;font-size:12px}.el-range-editor--mini .el-range-input{font-size:12px}.el-range-editor--mini .el-range__close-icon,.el-range-editor--mini .el-range__icon{line-height:20px}.el-range-editor.is-disabled{background-color:#f5f7fa;border-color:#e4e7ed;color:#c0c4cc;cursor:not-allowed}.el-range-editor.is-disabled:focus,.el-range-editor.is-disabled:hover{border-color:#e4e7ed}.el-range-editor.is-disabled input{background-color:#f5f7fa;color:#c0c4cc;cursor:not-allowed}.el-range-editor.is-disabled input::-webkit-input-placeholder{color:#c0c4cc}.el-range-editor.is-disabled input::-ms-input-placeholder{color:#c0c4cc}.el-range-editor.is-disabled input::placeholder{color:#c0c4cc}.el-range-editor.is-disabled .el-range-separator{color:#c0c4cc}.el-picker-panel{color:#606266;border:1px solid #e4e7ed;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);background:#fff;border-radius:4px;line-height:30px;margin:5px 0}.el-picker-panel__body-wrapper:after,.el-picker-panel__body:after{content:"";display:table;clear:both}.el-picker-panel__content{position:relative;margin:15px}.el-picker-panel__footer{border-top:1px solid #e4e4e4;padding:4px;text-align:right;background-color:#fff;position:relative;font-size:0}.el-picker-panel__shortcut{display:block;width:100%;border:0;background-color:transparent;line-height:28px;font-size:14px;color:#606266;padding-left:12px;text-align:left;outline:none;cursor:pointer}.el-picker-panel__shortcut:hover{color:#42d885}.el-picker-panel__shortcut.active{background-color:#e6f1fe;color:#42d885}.el-picker-panel__btn{border:1px solid #dcdcdc;color:#333;line-height:24px;border-radius:2px;padding:0 20px;cursor:pointer;background-color:transparent;outline:none;font-size:12px}.el-picker-panel__btn[disabled]{color:#ccc;cursor:not-allowed}.el-picker-panel__icon-btn{font-size:12px;color:#303133;border:0;background:transparent;cursor:pointer;outline:none;margin-top:8px}.el-picker-panel__icon-btn:hover{color:#42d885}.el-picker-panel__icon-btn.is-disabled{color:#bbb}.el-picker-panel__icon-btn.is-disabled:hover{cursor:not-allowed}.el-picker-panel__link-btn{vertical-align:middle}.el-picker-panel [slot=sidebar],.el-picker-panel__sidebar{position:absolute;top:0;bottom:0;width:110px;border-right:1px solid #e4e4e4;box-sizing:border-box;padding-top:6px;background-color:#fff;overflow:auto}.el-picker-panel [slot=sidebar]+.el-picker-panel__body,.el-picker-panel__sidebar+.el-picker-panel__body{margin-left:110px}.el-time-spinner.has-seconds .el-time-spinner__wrapper{width:33.3%}.el-time-spinner__wrapper{max-height:190px;overflow:auto;display:inline-block;width:50%;vertical-align:top;position:relative}.el-time-spinner__wrapper .el-scrollbar__wrap:not(.el-scrollbar__wrap--hidden-default){padding-bottom:15px}.el-time-spinner__wrapper.is-arrow{box-sizing:border-box;text-align:center;overflow:hidden}.el-time-spinner__wrapper.is-arrow .el-time-spinner__list{transform:translateY(-32px)}.el-time-spinner__wrapper.is-arrow .el-time-spinner__item:hover:not(.disabled):not(.active){background:#fff;cursor:default}.el-time-spinner__arrow{font-size:12px;color:#909399;position:absolute;left:0;width:100%;z-index:1;text-align:center;height:30px;line-height:30px;cursor:pointer}.el-time-spinner__arrow:hover{color:#42d885}.el-time-spinner__arrow.el-icon-arrow-up{top:10px}.el-time-spinner__arrow.el-icon-arrow-down{bottom:10px}.el-time-spinner__input.el-input{width:70%}.el-time-spinner__input.el-input .el-input__inner,.el-time-spinner__list{padding:0;text-align:center}.el-time-spinner__list{margin:0;list-style:none}.el-time-spinner__list:after,.el-time-spinner__list:before{content:"";display:block;width:100%;height:80px}.el-time-spinner__item{height:32px;line-height:32px;font-size:12px;color:#606266}.el-time-spinner__item:hover:not(.disabled):not(.active){background:#f5f7fa;cursor:pointer}.el-time-spinner__item.active:not(.disabled){color:#303133;font-weight:700}.el-time-spinner__item.disabled{color:#c0c4cc;cursor:not-allowed}.el-time-panel{margin:5px 0;border:1px solid #e4e7ed;background-color:#fff;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);border-radius:2px;position:absolute;width:180px;left:0;z-index:1000;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;box-sizing:content-box}.el-time-panel__content{font-size:0;position:relative;overflow:hidden}.el-time-panel__content:after,.el-time-panel__content:before{content:"";top:50%;position:absolute;margin-top:-15px;height:32px;z-index:-1;left:0;right:0;box-sizing:border-box;padding-top:6px;text-align:left;border-top:1px solid #e4e7ed;border-bottom:1px solid #e4e7ed}.el-time-panel__content:after{left:50%;margin-left:12%;margin-right:12%}.el-time-panel__content:before{padding-left:50%;margin-right:12%;margin-left:12%}.el-time-panel__content.has-seconds:after{left:66.66667%}.el-time-panel__content.has-seconds:before{padding-left:33.33333%}.el-time-panel__footer{border-top:1px solid #e4e4e4;padding:4px;height:36px;line-height:25px;text-align:right;box-sizing:border-box}.el-time-panel__btn{border:none;line-height:28px;padding:0 5px;margin:0 5px;cursor:pointer;background-color:transparent;outline:none;font-size:12px;color:#303133}.el-time-panel__btn.confirm{font-weight:800;color:#42d885}.el-time-range-picker{width:354px;overflow:visible}.el-time-range-picker__content{position:relative;text-align:center;padding:10px}.el-time-range-picker__cell{box-sizing:border-box;margin:0;padding:4px 7px 7px;width:50%;display:inline-block}.el-time-range-picker__header{margin-bottom:5px;text-align:center;font-size:14px}.el-time-range-picker__body{border-radius:2px;border:1px solid #e4e7ed}.el-popover{position:absolute;background:#fff;min-width:150px;border-radius:4px;border:1px solid #ebeef5;padding:12px;z-index:2000;color:#606266;line-height:1.4;text-align:justify;font-size:14px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);word-break:break-all}.el-popover--plain{padding:18px 20px}.el-popover__title{color:#303133;font-size:16px;line-height:1;margin-bottom:12px}.el-popover:focus,.el-popover:focus:active,.el-popover__reference:focus:hover,.el-popover__reference:focus:not(.focusing){outline-width:0}.v-modal-enter{animation:v-modal-in .2s ease}.v-modal-leave{animation:v-modal-out .2s ease forwards}@keyframes v-modal-in{0%{opacity:0}}@keyframes v-modal-out{to{opacity:0}}.v-modal{position:fixed;left:0;top:0;width:100%;height:100%;opacity:.5;background:#000}.el-popup-parent--hidden{overflow:hidden}.el-message-box{display:inline-block;width:420px;padding-bottom:10px;vertical-align:middle;background-color:#fff;border-radius:4px;border:1px solid #ebeef5;font-size:18px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);text-align:left;overflow:hidden;-webkit-backface-visibility:hidden;backface-visibility:hidden}.el-message-box__wrapper{position:fixed;top:0;bottom:0;left:0;right:0;text-align:center}.el-message-box__wrapper:after{content:"";display:inline-block;height:100%;width:0;vertical-align:middle}.el-message-box__header{position:relative;padding:15px;padding-bottom:10px}.el-message-box__title{padding-left:0;margin-bottom:0;font-size:18px;line-height:1;color:#303133}.el-message-box__headerbtn{position:absolute;top:15px;right:15px;padding:0;border:none;outline:none;background:transparent;font-size:16px;cursor:pointer}.el-message-box__headerbtn .el-message-box__close{color:#909399}.el-message-box__headerbtn:focus .el-message-box__close,.el-message-box__headerbtn:hover .el-message-box__close{color:#42d885}.el-message-box__content{position:relative;padding:10px 15px;color:#606266;font-size:14px}.el-message-box__input{padding-top:15px}.el-message-box__input input.invalid,.el-message-box__input input.invalid:focus{border-color:#ff6d6d}.el-message-box__status{position:absolute;top:50%;transform:translateY(-50%);font-size:24px!important}.el-message-box__status:before{padding-left:1px}.el-message-box__status+.el-message-box__message{padding-left:36px;padding-right:12px}.el-message-box__status.el-icon-success{color:#42d885}.el-message-box__status.el-icon-info{color:#909399}.el-message-box__status.el-icon-warning{color:#f9c855}.el-message-box__status.el-icon-error{color:#ff6d6d}.el-message-box__message{margin:0}.el-message-box__message p{margin:0;line-height:24px}.el-message-box__errormsg{color:#ff6d6d;font-size:12px;min-height:18px;margin-top:2px}.el-message-box__btns{padding:5px 15px 0;text-align:right}.el-message-box__btns button:nth-child(2){margin-left:10px}.el-message-box__btns-reverse{-ms-flex-direction:row-reverse;flex-direction:row-reverse}.el-message-box--center{padding-bottom:30px}.el-message-box--center .el-message-box__header{padding-top:30px}.el-message-box--center .el-message-box__title{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.el-message-box--center .el-message-box__status{position:relative;top:auto;padding-right:5px;text-align:center;transform:translateY(-1px)}.el-message-box--center .el-message-box__message{margin-left:0}.el-message-box--center .el-message-box__btns,.el-message-box--center .el-message-box__content{text-align:center}.el-message-box--center .el-message-box__content{padding-left:27px;padding-right:27px}.msgbox-fade-enter-active{animation:msgbox-fade-in .3s}.msgbox-fade-leave-active{animation:msgbox-fade-out .3s}@keyframes msgbox-fade-in{0%{transform:translate3d(0,-20px,0);opacity:0}to{transform:translateZ(0);opacity:1}}@keyframes msgbox-fade-out{0%{transform:translateZ(0);opacity:1}to{transform:translate3d(0,-20px,0);opacity:0}}.el-breadcrumb{font-size:14px;line-height:1}.el-breadcrumb:after,.el-breadcrumb:before{display:table;content:""}.el-breadcrumb:after{clear:both}.el-breadcrumb__separator{margin:0 9px;font-weight:700;color:#c0c4cc}.el-breadcrumb__separator[class*=icon]{margin:0 6px;font-weight:400}.el-breadcrumb__item{float:left}.el-breadcrumb__inner{color:#606266}.el-breadcrumb__inner.is-link,.el-breadcrumb__inner a{font-weight:700;text-decoration:none;transition:color .2s cubic-bezier(.645,.045,.355,1);color:#303133}.el-breadcrumb__inner.is-link:hover,.el-breadcrumb__inner a:hover{color:#42d885;cursor:pointer}.el-breadcrumb__item:last-child .el-breadcrumb__inner,.el-breadcrumb__item:last-child .el-breadcrumb__inner:hover,.el-breadcrumb__item:last-child .el-breadcrumb__inner a,.el-breadcrumb__item:last-child .el-breadcrumb__inner a:hover{font-weight:400;color:#606266;cursor:text}.el-breadcrumb__item:last-child .el-breadcrumb__separator{display:none}.el-form--label-left .el-form-item__label{text-align:left}.el-form--label-top .el-form-item__label{float:none;display:inline-block;text-align:left;padding:0 0 10px}.el-form--inline .el-form-item{display:inline-block;margin-right:10px;vertical-align:top}.el-form--inline .el-form-item__label{float:none;display:inline-block}.el-form--inline .el-form-item__content{display:inline-block;vertical-align:top}.el-form--inline.el-form--label-top .el-form-item__content{display:block}.el-form-item{margin-bottom:22px}.el-form-item:after,.el-form-item:before{display:table;content:""}.el-form-item:after{clear:both}.el-form-item .el-form-item{margin-bottom:0}.el-form-item .el-input__validateIcon{display:none}.el-form-item--medium .el-form-item__content,.el-form-item--medium .el-form-item__label{line-height:36px}.el-form-item--small .el-form-item__content,.el-form-item--small .el-form-item__label{line-height:32px}.el-form-item--small.el-form-item{margin-bottom:18px}.el-form-item--small .el-form-item__error{padding-top:2px}.el-form-item--mini .el-form-item__content,.el-form-item--mini .el-form-item__label{line-height:28px}.el-form-item--mini.el-form-item{margin-bottom:18px}.el-form-item--mini .el-form-item__error{padding-top:1px}.el-form-item__label-wrap{float:left}.el-form-item__label-wrap .el-form-item__label{display:inline-block;float:none}.el-form-item__label{text-align:right;vertical-align:middle;float:left;font-size:14px;color:#606266;line-height:40px;padding:0 12px 0 0;box-sizing:border-box}.el-form-item__content{line-height:40px;position:relative;font-size:14px}.el-form-item__content:after,.el-form-item__content:before{display:table;content:""}.el-form-item__content:after{clear:both}.el-form-item__content .el-input-group{vertical-align:top}.el-form-item__error{color:#ff6d6d;font-size:12px;line-height:1;padding-top:4px;position:absolute;top:100%;left:0}.el-form-item__error--inline{position:relative;top:auto;left:auto;display:inline-block;margin-left:10px}.el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label:before,.el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before{content:"*";color:#ff6d6d;margin-right:4px}.el-form-item.is-error .el-input__inner,.el-form-item.is-error .el-input__inner:focus,.el-form-item.is-error .el-textarea__inner,.el-form-item.is-error .el-textarea__inner:focus{border-color:#ff6d6d}.el-form-item.is-error .el-input-group__append .el-input__inner,.el-form-item.is-error .el-input-group__prepend .el-input__inner{border-color:transparent}.el-form-item.is-error .el-input__validateIcon{color:#ff6d6d}.el-form-item--feedback .el-input__validateIcon{display:inline-block}.el-tabs__header{padding:0;position:relative;margin:0 0 15px}.el-tabs__active-bar{position:absolute;bottom:0;left:0;height:2px;background-color:#42d885;z-index:1;transition:transform .3s cubic-bezier(.645,.045,.355,1);list-style:none}.el-tabs__new-tab{float:right;border:1px solid #d3dce6;height:18px;width:18px;line-height:18px;margin:12px 0 9px 10px;border-radius:3px;text-align:center;font-size:12px;color:#d3dce6;cursor:pointer;transition:all .15s}.el-tabs__new-tab .el-icon-plus{transform:scale(.8)}.el-tabs__new-tab:hover{color:#42d885}.el-tabs__nav-wrap{overflow:hidden;margin-bottom:-1px;position:relative}.el-tabs__nav-wrap:after{content:"";position:absolute;left:0;bottom:0;width:100%;height:2px;background-color:#e4e7ed;z-index:1}.el-tabs__nav-wrap.is-scrollable{padding:0 20px;box-sizing:border-box}.el-tabs__nav-scroll{overflow:hidden}.el-tabs__nav-next,.el-tabs__nav-prev{position:absolute;cursor:pointer;line-height:44px;font-size:12px;color:#909399}.el-tabs__nav-next{right:0}.el-tabs__nav-prev{left:0}.el-tabs__nav{white-space:nowrap;position:relative;transition:transform .3s;float:left;z-index:2}.el-tabs__nav.is-stretch{min-width:100%;display:-ms-flexbox;display:flex}.el-tabs__nav.is-stretch>*{-ms-flex:1;flex:1;text-align:center}.el-tabs__item{padding:0 20px;height:40px;box-sizing:border-box;line-height:40px;display:inline-block;list-style:none;font-size:14px;font-weight:500;color:#303133;position:relative}.el-tabs__item:focus,.el-tabs__item:focus:active{outline:none}.el-tabs__item:focus.is-active.is-focus:not(:active){box-shadow:inset 0 0 2px 2px #42d885;border-radius:3px}.el-tabs__item .el-icon-close{border-radius:50%;text-align:center;transition:all .3s cubic-bezier(.645,.045,.355,1);margin-left:5px}.el-tabs__item .el-icon-close:before{transform:scale(.9);display:inline-block}.el-tabs__item .el-icon-close:hover{background-color:#c0c4cc;color:#fff}.el-tabs__item.is-active{color:#42d885}.el-tabs__item:hover{color:#42d885;cursor:pointer}.el-tabs__item.is-disabled{color:#c0c4cc;cursor:default}.el-tabs__content{overflow:hidden;position:relative}.el-tabs--card>.el-tabs__header{border-bottom:1px solid #e4e7ed}.el-tabs--card>.el-tabs__header .el-tabs__nav-wrap:after{content:none}.el-tabs--card>.el-tabs__header .el-tabs__nav{border:1px solid #e4e7ed;border-bottom:none;border-radius:4px 4px 0 0;box-sizing:border-box}.el-tabs--card>.el-tabs__header .el-tabs__active-bar{display:none}.el-tabs--card>.el-tabs__header .el-tabs__item .el-icon-close{position:relative;font-size:12px;width:0;height:14px;vertical-align:middle;line-height:15px;overflow:hidden;top:-1px;right:-2px;transform-origin:100% 50%}.el-tabs--card>.el-tabs__header .el-tabs__item{border-bottom:1px solid transparent;border-left:1px solid #e4e7ed;transition:color .3s cubic-bezier(.645,.045,.355,1),padding .3s cubic-bezier(.645,.045,.355,1)}.el-tabs--card>.el-tabs__header .el-tabs__item:first-child{border-left:none}.el-tabs--card>.el-tabs__header .el-tabs__item.is-closable:hover{padding-left:13px;padding-right:13px}.el-tabs--card>.el-tabs__header .el-tabs__item.is-closable:hover .el-icon-close{width:14px}.el-tabs--card>.el-tabs__header .el-tabs__item.is-active{border-bottom-color:#fff}.el-tabs--card>.el-tabs__header .el-tabs__item.is-active.is-closable{padding-left:20px;padding-right:20px}.el-tabs--card>.el-tabs__header .el-tabs__item.is-active.is-closable .el-icon-close{width:14px}.el-tabs--border-card{background:#fff;border:1px solid #dcdfe6;box-shadow:0 2px 4px 0 rgba(0,0,0,.12),0 0 6px 0 rgba(0,0,0,.04)}.el-tabs--border-card>.el-tabs__content{padding:15px}.el-tabs--border-card>.el-tabs__header{background-color:#f5f7fa;border-bottom:1px solid #e4e7ed;margin:0}.el-tabs--border-card>.el-tabs__header .el-tabs__nav-wrap:after{content:none}.el-tabs--border-card>.el-tabs__header .el-tabs__item{transition:all .3s cubic-bezier(.645,.045,.355,1);border:1px solid transparent;margin-top:-1px;color:#909399}.el-tabs--border-card>.el-tabs__header .el-tabs__item+.el-tabs__item,.el-tabs--border-card>.el-tabs__header .el-tabs__item:first-child{margin-left:-1px}.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active{color:#42d885;background-color:#fff;border-right-color:#dcdfe6;border-left-color:#dcdfe6}.el-tabs--border-card>.el-tabs__header .el-tabs__item:not(.is-disabled):hover{color:#42d885}.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-disabled{color:#c0c4cc}.el-tabs--border-card>.el-tabs__header .is-scrollable .el-tabs__item:first-child{margin-left:0}.el-tabs--bottom .el-tabs__item.is-bottom:nth-child(2),.el-tabs--bottom .el-tabs__item.is-top:nth-child(2),.el-tabs--top .el-tabs__item.is-bottom:nth-child(2),.el-tabs--top .el-tabs__item.is-top:nth-child(2){padding-left:0}.el-tabs--bottom .el-tabs__item.is-bottom:last-child,.el-tabs--bottom .el-tabs__item.is-top:last-child,.el-tabs--top .el-tabs__item.is-bottom:last-child,.el-tabs--top .el-tabs__item.is-top:last-child{padding-right:0}.el-tabs--bottom.el-tabs--border-card>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--bottom.el-tabs--card>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--bottom .el-tabs--left>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--bottom .el-tabs--right>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--top.el-tabs--border-card>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--top.el-tabs--card>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--top .el-tabs--left>.el-tabs__header .el-tabs__item:nth-child(2),.el-tabs--top .el-tabs--right>.el-tabs__header .el-tabs__item:nth-child(2){padding-left:20px}.el-tabs--bottom.el-tabs--border-card>.el-tabs__header .el-tabs__item:last-child,.el-tabs--bottom.el-tabs--card>.el-tabs__header .el-tabs__item:last-child,.el-tabs--bottom .el-tabs--left>.el-tabs__header .el-tabs__item:last-child,.el-tabs--bottom .el-tabs--right>.el-tabs__header .el-tabs__item:last-child,.el-tabs--top.el-tabs--border-card>.el-tabs__header .el-tabs__item:last-child,.el-tabs--top.el-tabs--card>.el-tabs__header .el-tabs__item:last-child,.el-tabs--top .el-tabs--left>.el-tabs__header .el-tabs__item:last-child,.el-tabs--top .el-tabs--right>.el-tabs__header .el-tabs__item:last-child{padding-right:20px}.el-tabs--bottom .el-tabs__header.is-bottom{margin-bottom:0;margin-top:10px}.el-tabs--bottom.el-tabs--border-card .el-tabs__header.is-bottom{border-bottom:0;border-top:1px solid #dcdfe6}.el-tabs--bottom.el-tabs--border-card .el-tabs__nav-wrap.is-bottom{margin-top:-1px;margin-bottom:0}.el-tabs--bottom.el-tabs--border-card .el-tabs__item.is-bottom:not(.is-active){border:1px solid transparent}.el-tabs--bottom.el-tabs--border-card .el-tabs__item.is-bottom{margin:0 -1px -1px}.el-tabs--left,.el-tabs--right{overflow:hidden}.el-tabs--left .el-tabs__header.is-left,.el-tabs--left .el-tabs__header.is-right,.el-tabs--left .el-tabs__nav-scroll,.el-tabs--left .el-tabs__nav-wrap.is-left,.el-tabs--left .el-tabs__nav-wrap.is-right,.el-tabs--right .el-tabs__header.is-left,.el-tabs--right .el-tabs__header.is-right,.el-tabs--right .el-tabs__nav-scroll,.el-tabs--right .el-tabs__nav-wrap.is-left,.el-tabs--right .el-tabs__nav-wrap.is-right{height:100%}.el-tabs--left .el-tabs__active-bar.is-left,.el-tabs--left .el-tabs__active-bar.is-right,.el-tabs--right .el-tabs__active-bar.is-left,.el-tabs--right .el-tabs__active-bar.is-right{top:0;bottom:auto;width:2px;height:auto}.el-tabs--left .el-tabs__nav-wrap.is-left,.el-tabs--left .el-tabs__nav-wrap.is-right,.el-tabs--right .el-tabs__nav-wrap.is-left,.el-tabs--right .el-tabs__nav-wrap.is-right{margin-bottom:0}.el-tabs--left .el-tabs__nav-wrap.is-left>.el-tabs__nav-next,.el-tabs--left .el-tabs__nav-wrap.is-left>.el-tabs__nav-prev,.el-tabs--left .el-tabs__nav-wrap.is-right>.el-tabs__nav-next,.el-tabs--left .el-tabs__nav-wrap.is-right>.el-tabs__nav-prev,.el-tabs--right .el-tabs__nav-wrap.is-left>.el-tabs__nav-next,.el-tabs--right .el-tabs__nav-wrap.is-left>.el-tabs__nav-prev,.el-tabs--right .el-tabs__nav-wrap.is-right>.el-tabs__nav-next,.el-tabs--right .el-tabs__nav-wrap.is-right>.el-tabs__nav-prev{height:30px;line-height:30px;width:100%;text-align:center;cursor:pointer}.el-tabs--left .el-tabs__nav-wrap.is-left>.el-tabs__nav-next i,.el-tabs--left .el-tabs__nav-wrap.is-left>.el-tabs__nav-prev i,.el-tabs--left .el-tabs__nav-wrap.is-right>.el-tabs__nav-next i,.el-tabs--left .el-tabs__nav-wrap.is-right>.el-tabs__nav-prev i,.el-tabs--right .el-tabs__nav-wrap.is-left>.el-tabs__nav-next i,.el-tabs--right .el-tabs__nav-wrap.is-left>.el-tabs__nav-prev i,.el-tabs--right .el-tabs__nav-wrap.is-right>.el-tabs__nav-next i,.el-tabs--right .el-tabs__nav-wrap.is-right>.el-tabs__nav-prev i{transform:rotate(90deg)}.el-tabs--left .el-tabs__nav-wrap.is-left>.el-tabs__nav-prev,.el-tabs--left .el-tabs__nav-wrap.is-right>.el-tabs__nav-prev,.el-tabs--right .el-tabs__nav-wrap.is-left>.el-tabs__nav-prev,.el-tabs--right .el-tabs__nav-wrap.is-right>.el-tabs__nav-prev{left:auto;top:0}.el-tabs--left .el-tabs__nav-wrap.is-left>.el-tabs__nav-next,.el-tabs--left .el-tabs__nav-wrap.is-right>.el-tabs__nav-next,.el-tabs--right .el-tabs__nav-wrap.is-left>.el-tabs__nav-next,.el-tabs--right .el-tabs__nav-wrap.is-right>.el-tabs__nav-next{right:auto;bottom:0}.el-tabs--left .el-tabs__nav-wrap.is-left.is-scrollable,.el-tabs--left .el-tabs__nav-wrap.is-right.is-scrollable,.el-tabs--right .el-tabs__nav-wrap.is-left.is-scrollable,.el-tabs--right .el-tabs__nav-wrap.is-right.is-scrollable{padding:30px 0}.el-tabs--left .el-tabs__nav-wrap.is-left:after,.el-tabs--left .el-tabs__nav-wrap.is-right:after,.el-tabs--right .el-tabs__nav-wrap.is-left:after,.el-tabs--right .el-tabs__nav-wrap.is-right:after{height:100%;width:2px;bottom:auto;top:0}.el-tabs--left .el-tabs__nav.is-left,.el-tabs--left .el-tabs__nav.is-right,.el-tabs--right .el-tabs__nav.is-left,.el-tabs--right .el-tabs__nav.is-right{float:none}.el-tabs--left .el-tabs__item.is-left,.el-tabs--left .el-tabs__item.is-right,.el-tabs--right .el-tabs__item.is-left,.el-tabs--right .el-tabs__item.is-right{display:block}.el-tabs--left .el-tabs__header.is-left{float:left;margin-bottom:0;margin-right:10px}.el-tabs--left .el-tabs__nav-wrap.is-left{margin-right:-1px}.el-tabs--left .el-tabs__active-bar.is-left,.el-tabs--left .el-tabs__nav-wrap.is-left:after{left:auto;right:0}.el-tabs--left .el-tabs__item.is-left{text-align:right}.el-tabs--left.el-tabs--card .el-tabs__active-bar.is-left{display:none}.el-tabs--left.el-tabs--card .el-tabs__item.is-left{border-left:none;border-right:1px solid #e4e7ed;border-bottom:none;border-top:1px solid #e4e7ed;text-align:left}.el-tabs--left.el-tabs--card .el-tabs__item.is-left:first-child{border-right:1px solid #e4e7ed;border-top:none}.el-tabs--left.el-tabs--card .el-tabs__item.is-left.is-active{border:1px solid #e4e7ed;border-right-color:#fff;border-left:none;border-bottom:none}.el-tabs--left.el-tabs--card .el-tabs__item.is-left.is-active:first-child{border-top:none}.el-tabs--left.el-tabs--card .el-tabs__item.is-left.is-active:last-child{border-bottom:none}.el-tabs--left.el-tabs--card .el-tabs__nav{border-radius:4px 0 0 4px;border-bottom:1px solid #e4e7ed;border-right:none}.el-tabs--left.el-tabs--card .el-tabs__new-tab{float:none}.el-tabs--left.el-tabs--border-card .el-tabs__header.is-left{border-right:1px solid #dfe4ed}.el-tabs--left.el-tabs--border-card .el-tabs__item.is-left{border:1px solid transparent;margin:-1px 0 -1px -1px}.el-tabs--left.el-tabs--border-card .el-tabs__item.is-left.is-active{border-color:transparent;border-top-color:#d1dbe5;border-bottom-color:#d1dbe5}.el-tabs--right .el-tabs__header.is-right{float:right;margin-bottom:0;margin-left:10px}.el-tabs--right .el-tabs__nav-wrap.is-right{margin-left:-1px}.el-tabs--right .el-tabs__nav-wrap.is-right:after{left:0;right:auto}.el-tabs--right .el-tabs__active-bar.is-right{left:0}.el-tabs--right.el-tabs--card .el-tabs__active-bar.is-right{display:none}.el-tabs--right.el-tabs--card .el-tabs__item.is-right{border-bottom:none;border-top:1px solid #e4e7ed}.el-tabs--right.el-tabs--card .el-tabs__item.is-right:first-child{border-left:1px solid #e4e7ed;border-top:none}.el-tabs--right.el-tabs--card .el-tabs__item.is-right.is-active{border:1px solid #e4e7ed;border-left-color:#fff;border-right:none;border-bottom:none}.el-tabs--right.el-tabs--card .el-tabs__item.is-right.is-active:first-child{border-top:none}.el-tabs--right.el-tabs--card .el-tabs__item.is-right.is-active:last-child{border-bottom:none}.el-tabs--right.el-tabs--card .el-tabs__nav{border-radius:0 4px 4px 0;border-bottom:1px solid #e4e7ed;border-left:none}.el-tabs--right.el-tabs--border-card .el-tabs__header.is-right{border-left:1px solid #dfe4ed}.el-tabs--right.el-tabs--border-card .el-tabs__item.is-right{border:1px solid transparent;margin:-1px -1px -1px 0}.el-tabs--right.el-tabs--border-card .el-tabs__item.is-right.is-active{border-color:transparent;border-top-color:#d1dbe5;border-bottom-color:#d1dbe5}.slideInLeft-transition,.slideInRight-transition{display:inline-block}.slideInRight-enter{animation:slideInRight-enter .3s}.slideInRight-leave{position:absolute;left:0;right:0;animation:slideInRight-leave .3s}.slideInLeft-enter{animation:slideInLeft-enter .3s}.slideInLeft-leave{position:absolute;left:0;right:0;animation:slideInLeft-leave .3s}@keyframes slideInRight-enter{0%{opacity:0;transform-origin:0 0;transform:translateX(100%)}to{opacity:1;transform-origin:0 0;transform:translateX(0)}}@keyframes slideInRight-leave{0%{transform-origin:0 0;transform:translateX(0);opacity:1}to{transform-origin:0 0;transform:translateX(100%);opacity:0}}@keyframes slideInLeft-enter{0%{opacity:0;transform-origin:0 0;transform:translateX(-100%)}to{opacity:1;transform-origin:0 0;transform:translateX(0)}}@keyframes slideInLeft-leave{0%{transform-origin:0 0;transform:translateX(0);opacity:1}to{transform-origin:0 0;transform:translateX(-100%);opacity:0}}.el-tree{position:relative;cursor:default;background:#fff;color:#606266}.el-tree__empty-block{position:relative;min-height:60px;text-align:center;width:100%;height:100%}.el-tree__empty-text{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);color:#909399}.el-tree__drop-indicator{position:absolute;left:0;right:0;height:1px;background-color:#42d885}.el-tree-node{white-space:nowrap;outline:none}.el-tree-node:focus>.el-tree-node__content{background-color:#f5f7fa}.el-tree-node.is-drop-inner>.el-tree-node__content .el-tree-node__label{background-color:#42d885;color:#fff}.el-tree-node__content{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;height:26px;cursor:pointer}.el-tree-node__content>.el-tree-node__expand-icon{padding:6px}.el-tree-node__content>.el-checkbox{margin-right:8px}.el-tree-node__content:hover{background-color:#f5f7fa}.el-tree.is-dragging .el-tree-node__content{cursor:move}.el-tree.is-dragging .el-tree-node__content *{pointer-events:none}.el-tree.is-dragging.is-drop-not-allow .el-tree-node__content{cursor:not-allowed}.el-tree-node__expand-icon{cursor:pointer;color:#c0c4cc;font-size:12px;transform:rotate(0deg);transition:transform .3s ease-in-out}.el-tree-node__expand-icon.expanded{transform:rotate(90deg)}.el-tree-node__expand-icon.is-leaf{color:transparent;cursor:default}.el-tree-node__label{font-size:14px}.el-tree-node__loading-icon{margin-right:8px;font-size:14px;color:#c0c4cc}.el-tree-node>.el-tree-node__children{overflow:hidden;background-color:transparent}.el-tree-node.is-expanded>.el-tree-node__children{display:block}.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{background-color:#f0fcf5}.el-alert{width:100%;padding:8px 16px;margin:0;box-sizing:border-box;border-radius:4px;position:relative;background-color:#fff;overflow:hidden;opacity:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;transition:opacity .2s}.el-alert.is-light .el-alert__closebtn{color:#c0c4cc}.el-alert.is-dark .el-alert__closebtn,.el-alert.is-dark .el-alert__description{color:#fff}.el-alert.is-center{-ms-flex-pack:center;justify-content:center}.el-alert--success.is-light{background-color:#ecfbf3;color:#42d885}.el-alert--success.is-light .el-alert__description{color:#42d885}.el-alert--success.is-dark{background-color:#42d885;color:#fff}.el-alert--info.is-light{background-color:#f4f4f5;color:#909399}.el-alert--info.is-dark{background-color:#909399;color:#fff}.el-alert--info .el-alert__description{color:#909399}.el-alert--warning.is-light{background-color:#fefaee;color:#f9c855}.el-alert--warning.is-light .el-alert__description{color:#f9c855}.el-alert--warning.is-dark{background-color:#f9c855;color:#fff}.el-alert--error.is-light{background-color:#fff0f0;color:#ff6d6d}.el-alert--error.is-light .el-alert__description{color:#ff6d6d}.el-alert--error.is-dark{background-color:#ff6d6d;color:#fff}.el-alert__content{display:table-cell;padding:0 8px}.el-alert__icon{font-size:16px;width:16px}.el-alert__icon.is-big{font-size:28px;width:28px}.el-alert__title{font-size:13px;line-height:18px}.el-alert__title.is-bold{font-weight:700}.el-alert .el-alert__description{font-size:12px;margin:5px 0 0}.el-alert__closebtn{font-size:12px;opacity:1;position:absolute;top:12px;right:15px;cursor:pointer}.el-alert__closebtn.is-customed{font-style:normal;font-size:13px;top:9px}.el-alert-fade-enter,.el-alert-fade-leave-active{opacity:0}.el-notification{display:-ms-flexbox;display:flex;width:330px;padding:14px 26px 14px 13px;border-radius:8px;box-sizing:border-box;border:1px solid #ebeef5;position:fixed;background-color:#fff;box-shadow:0 2px 12px 0 rgba(0,0,0,.1);transition:opacity .3s,transform .3s,left .3s,right .3s,top .4s,bottom .3s;overflow:hidden}.el-notification.right{right:16px}.el-notification.left{left:16px}.el-notification__group{margin-left:13px;margin-right:8px}.el-notification__title{font-weight:700;font-size:16px;color:#303133;margin:0}.el-notification__content{font-size:14px;line-height:21px;margin:6px 0 0;color:#606266;text-align:justify}.el-notification__content p{margin:0}.el-notification__icon{height:24px;width:24px;font-size:24px}.el-notification__closeBtn{position:absolute;top:18px;right:15px;cursor:pointer;color:#909399;font-size:16px}.el-notification__closeBtn:hover{color:#606266}.el-notification .el-icon-success{color:#42d885}.el-notification .el-icon-error{color:#ff6d6d}.el-notification .el-icon-info{color:#909399}.el-notification .el-icon-warning{color:#f9c855}.el-notification-fade-enter.right{right:0;transform:translateX(100%)}.el-notification-fade-enter.left{left:0;transform:translateX(-100%)}.el-notification-fade-leave-active{opacity:0}.el-input-number{position:relative;display:inline-block;width:180px;line-height:38px}.el-input-number .el-input{display:block}.el-input-number .el-input__inner{-webkit-appearance:none;padding-left:50px;padding-right:50px;text-align:center}.el-input-number__decrease,.el-input-number__increase{position:absolute;z-index:1;top:1px;width:40px;height:auto;text-align:center;background:#f5f7fa;color:#606266;cursor:pointer;font-size:13px}.el-input-number__decrease:hover,.el-input-number__increase:hover{color:#42d885}.el-input-number__decrease:hover:not(.is-disabled)~.el-input .el-input__inner:not(.is-disabled),.el-input-number__increase:hover:not(.is-disabled)~.el-input .el-input__inner:not(.is-disabled){border-color:#42d885}.el-input-number__decrease.is-disabled,.el-input-number__increase.is-disabled{color:#c0c4cc;cursor:not-allowed}.el-input-number__increase{right:1px;border-radius:0 4px 4px 0;border-left:1px solid #dcdfe6}.el-input-number__decrease{left:1px;border-radius:4px 0 0 4px;border-right:1px solid #dcdfe6}.el-input-number.is-disabled .el-input-number__decrease,.el-input-number.is-disabled .el-input-number__increase{border-color:#e4e7ed;color:#e4e7ed}.el-input-number.is-disabled .el-input-number__decrease:hover,.el-input-number.is-disabled .el-input-number__increase:hover{color:#e4e7ed;cursor:not-allowed}.el-input-number--medium{width:200px;line-height:34px}.el-input-number--medium .el-input-number__decrease,.el-input-number--medium .el-input-number__increase{width:36px;font-size:14px}.el-input-number--medium .el-input__inner{padding-left:43px;padding-right:43px}.el-input-number--small{width:130px;line-height:30px}.el-input-number--small .el-input-number__decrease,.el-input-number--small .el-input-number__increase{width:32px;font-size:13px}.el-input-number--small .el-input-number__decrease [class*=el-icon],.el-input-number--small .el-input-number__increase [class*=el-icon]{transform:scale(.9)}.el-input-number--small .el-input__inner{padding-left:39px;padding-right:39px}.el-input-number--mini{width:130px;line-height:26px}.el-input-number--mini .el-input-number__decrease,.el-input-number--mini .el-input-number__increase{width:28px;font-size:12px}.el-input-number--mini .el-input-number__decrease [class*=el-icon],.el-input-number--mini .el-input-number__increase [class*=el-icon]{transform:scale(.8)}.el-input-number--mini .el-input__inner{padding-left:35px;padding-right:35px}.el-input-number.is-without-controls .el-input__inner{padding-left:15px;padding-right:15px}.el-input-number.is-controls-right .el-input__inner{padding-left:15px;padding-right:50px}.el-input-number.is-controls-right .el-input-number__decrease,.el-input-number.is-controls-right .el-input-number__increase{height:auto;line-height:19px}.el-input-number.is-controls-right .el-input-number__decrease [class*=el-icon],.el-input-number.is-controls-right .el-input-number__increase [class*=el-icon]{transform:scale(.8)}.el-input-number.is-controls-right .el-input-number__increase{border-radius:0 4px 0 0;border-bottom:1px solid #dcdfe6}.el-input-number.is-controls-right .el-input-number__decrease{right:1px;bottom:1px;top:auto;left:auto;border-right:none;border-left:1px solid #dcdfe6;border-radius:0 0 4px 0}.el-input-number.is-controls-right[class*=medium] [class*=decrease],.el-input-number.is-controls-right[class*=medium] [class*=increase]{line-height:17px}.el-input-number.is-controls-right[class*=small] [class*=decrease],.el-input-number.is-controls-right[class*=small] [class*=increase]{line-height:15px}.el-input-number.is-controls-right[class*=mini] [class*=decrease],.el-input-number.is-controls-right[class*=mini] [class*=increase]{line-height:13px}.el-tooltip:focus:hover,.el-tooltip:focus:not(.focusing){outline-width:0}.el-tooltip__popper{position:absolute;border-radius:4px;padding:10px;z-index:2000;font-size:12px;line-height:1.2;min-width:10px;word-wrap:break-word}.el-tooltip__popper .popper__arrow,.el-tooltip__popper .popper__arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.el-tooltip__popper .popper__arrow{border-width:6px}.el-tooltip__popper .popper__arrow:after{content:" ";border-width:5px}.el-tooltip__popper[x-placement^=top]{margin-bottom:12px}.el-tooltip__popper[x-placement^=top] .popper__arrow{bottom:-6px;border-top-color:#303133;border-bottom-width:0}.el-tooltip__popper[x-placement^=top] .popper__arrow:after{bottom:1px;margin-left:-5px;border-top-color:#303133;border-bottom-width:0}.el-tooltip__popper[x-placement^=bottom]{margin-top:12px}.el-tooltip__popper[x-placement^=bottom] .popper__arrow{top:-6px;border-top-width:0;border-bottom-color:#303133}.el-tooltip__popper[x-placement^=bottom] .popper__arrow:after{top:1px;margin-left:-5px;border-top-width:0;border-bottom-color:#303133}.el-tooltip__popper[x-placement^=right]{margin-left:12px}.el-tooltip__popper[x-placement^=right] .popper__arrow{left:-6px;border-right-color:#303133;border-left-width:0}.el-tooltip__popper[x-placement^=right] .popper__arrow:after{bottom:-5px;left:1px;border-right-color:#303133;border-left-width:0}.el-tooltip__popper[x-placement^=left]{margin-right:12px}.el-tooltip__popper[x-placement^=left] .popper__arrow{right:-6px;border-right-width:0;border-left-color:#303133}.el-tooltip__popper[x-placement^=left] .popper__arrow:after{right:1px;bottom:-5px;margin-left:-5px;border-right-width:0;border-left-color:#303133}.el-tooltip__popper.is-dark{background:#303133;color:#fff}.el-tooltip__popper.is-light{background:#fff;border:1px solid #303133}.el-tooltip__popper.is-light[x-placement^=top] .popper__arrow{border-top-color:#303133}.el-tooltip__popper.is-light[x-placement^=top] .popper__arrow:after{border-top-color:#fff}.el-tooltip__popper.is-light[x-placement^=bottom] .popper__arrow{border-bottom-color:#303133}.el-tooltip__popper.is-light[x-placement^=bottom] .popper__arrow:after{border-bottom-color:#fff}.el-tooltip__popper.is-light[x-placement^=left] .popper__arrow{border-left-color:#303133}.el-tooltip__popper.is-light[x-placement^=left] .popper__arrow:after{border-left-color:#fff}.el-tooltip__popper.is-light[x-placement^=right] .popper__arrow{border-right-color:#303133}.el-tooltip__popper.is-light[x-placement^=right] .popper__arrow:after{border-right-color:#fff}.el-slider:after,.el-slider:before{display:table;content:""}.el-slider:after{clear:both}.el-slider__runway{width:100%;height:6px;margin:16px 0;background-color:#e4e7ed;border-radius:3px;position:relative;cursor:pointer;vertical-align:middle}.el-slider__runway.show-input{margin-right:160px;width:auto}.el-slider__runway.disabled{cursor:default}.el-slider__runway.disabled .el-slider__bar{background-color:#c0c4cc}.el-slider__runway.disabled .el-slider__button{border-color:#c0c4cc}.el-slider__runway.disabled .el-slider__button-wrapper.dragging,.el-slider__runway.disabled .el-slider__button-wrapper.hover,.el-slider__runway.disabled .el-slider__button-wrapper:hover{cursor:not-allowed}.el-slider__runway.disabled .el-slider__button.dragging,.el-slider__runway.disabled .el-slider__button.hover,.el-slider__runway.disabled .el-slider__button:hover{transform:scale(1)}.el-slider__runway.disabled .el-slider__button.dragging,.el-slider__runway.disabled .el-slider__button.hover,.el-slider__runway.disabled .el-slider__button:hover{cursor:not-allowed}.el-slider__input{float:right;margin-top:3px;width:130px}.el-slider__input.el-input-number--mini{margin-top:5px}.el-slider__input.el-input-number--medium{margin-top:0}.el-slider__input.el-input-number--large{margin-top:-2px}.el-slider__bar{height:6px;background-color:#42d885;border-top-left-radius:3px;border-bottom-left-radius:3px;position:absolute}.el-slider__button-wrapper{height:36px;width:36px;position:absolute;z-index:1001;top:-15px;transform:translateX(-50%);background-color:transparent;text-align:center;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;line-height:normal}.el-slider__button-wrapper:after{content:"";height:100%}.el-slider__button-wrapper .el-tooltip,.el-slider__button-wrapper:after{display:inline-block;vertical-align:middle}.el-slider__button-wrapper.hover,.el-slider__button-wrapper:hover{cursor:grab}.el-slider__button-wrapper.dragging{cursor:grabbing}.el-slider__button{width:16px;height:16px;border:2px solid #42d885;background-color:#fff;border-radius:50%;transition:.2s;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.el-slider__button.dragging,.el-slider__button.hover,.el-slider__button:hover{transform:scale(1.2)}.el-slider__button.hover,.el-slider__button:hover{cursor:grab}.el-slider__button.dragging{cursor:grabbing}.el-slider__stop{position:absolute;height:6px;width:6px;border-radius:100%;background-color:#fff;transform:translateX(-50%)}.el-slider__marks{top:0;left:12px;width:18px;height:100%}.el-slider__marks-text{position:absolute;transform:translateX(-50%);font-size:14px;color:#909399;margin-top:15px}.el-slider.is-vertical{position:relative}.el-slider.is-vertical .el-slider__runway{width:6px;height:100%;margin:0 16px}.el-slider.is-vertical .el-slider__bar{width:6px;height:auto;border-radius:0 0 3px 3px}.el-slider.is-vertical .el-slider__button-wrapper{top:auto;left:-15px;transform:translateY(50%)}.el-slider.is-vertical .el-slider__stop{transform:translateY(50%)}.el-slider.is-vertical.el-slider--with-input{padding-bottom:58px}.el-slider.is-vertical.el-slider--with-input .el-slider__input{overflow:visible;float:none;position:absolute;bottom:22px;width:36px;margin-top:15px}.el-slider.is-vertical.el-slider--with-input .el-slider__input .el-input__inner{text-align:center;padding-left:5px;padding-right:5px}.el-slider.is-vertical.el-slider--with-input .el-slider__input .el-input-number__decrease,.el-slider.is-vertical.el-slider--with-input .el-slider__input .el-input-number__increase{top:32px;margin-top:-1px;border:1px solid #dcdfe6;line-height:20px;box-sizing:border-box;transition:border-color .2s cubic-bezier(.645,.045,.355,1)}.el-slider.is-vertical.el-slider--with-input .el-slider__input .el-input-number__decrease{width:18px;right:18px;border-bottom-left-radius:4px}.el-slider.is-vertical.el-slider--with-input .el-slider__input .el-input-number__increase{width:19px;border-bottom-right-radius:4px}.el-slider.is-vertical.el-slider--with-input .el-slider__input .el-input-number__increase~.el-input .el-input__inner{border-bottom-left-radius:0;border-bottom-right-radius:0}.el-slider.is-vertical.el-slider--with-input .el-slider__input:hover .el-input-number__decrease,.el-slider.is-vertical.el-slider--with-input .el-slider__input:hover .el-input-number__increase{border-color:#c0c4cc}.el-slider.is-vertical.el-slider--with-input .el-slider__input:active .el-input-number__decrease,.el-slider.is-vertical.el-slider--with-input .el-slider__input:active .el-input-number__increase{border-color:#42d885}.el-slider.is-vertical .el-slider__marks-text{margin-top:0;left:15px;transform:translateY(50%)}.el-loading-parent--relative{position:relative!important}.el-loading-parent--hidden{overflow:hidden!important}.el-loading-mask{position:absolute;z-index:2000;background-color:hsla(0,0%,100%,.9);margin:0;top:0;right:0;bottom:0;left:0;transition:opacity .3s}.el-loading-mask.is-fullscreen{position:fixed}.el-loading-mask.is-fullscreen .el-loading-spinner{margin-top:-25px}.el-loading-mask.is-fullscreen .el-loading-spinner .circular{height:50px;width:50px}.el-loading-spinner{top:50%;margin-top:-21px;width:100%;text-align:center;position:absolute}.el-loading-spinner .el-loading-text{color:#42d885;margin:3px 0;font-size:14px}.el-loading-spinner .circular{height:42px;width:42px;animation:loading-rotate 2s linear infinite}.el-loading-spinner .path{animation:loading-dash 1.5s ease-in-out infinite;stroke-dasharray:90,150;stroke-dashoffset:0;stroke-width:2;stroke:#42d885;stroke-linecap:round}.el-loading-spinner i{color:#42d885}.el-loading-fade-enter,.el-loading-fade-leave-active{opacity:0}@keyframes loading-rotate{to{transform:rotate(1turn)}}@keyframes loading-dash{0%{stroke-dasharray:1,200;stroke-dashoffset:0}50%{stroke-dasharray:90,150;stroke-dashoffset:-40px}to{stroke-dasharray:90,150;stroke-dashoffset:-120px}}.el-row{position:relative;box-sizing:border-box}.el-row:after,.el-row:before{display:table;content:""}.el-row:after{clear:both}.el-row--flex{display:-ms-flexbox;display:flex}.el-row--flex:after,.el-row--flex:before{display:none}.el-row--flex.is-justify-center{-ms-flex-pack:center;justify-content:center}.el-row--flex.is-justify-end{-ms-flex-pack:end;justify-content:flex-end}.el-row--flex.is-justify-space-between{-ms-flex-pack:justify;justify-content:space-between}.el-row--flex.is-justify-space-around{-ms-flex-pack:distribute;justify-content:space-around}.el-row--flex.is-align-middle{-ms-flex-align:center;align-items:center}.el-row--flex.is-align-bottom{-ms-flex-align:end;align-items:flex-end}[class*=el-col-]{float:left;box-sizing:border-box}.el-col-0{display:none;width:0}.el-col-offset-0{margin-left:0}.el-col-pull-0{position:relative;right:0}.el-col-push-0{position:relative;left:0}.el-col-1{width:4.16667%}.el-col-offset-1{margin-left:4.16667%}.el-col-pull-1{position:relative;right:4.16667%}.el-col-push-1{position:relative;left:4.16667%}.el-col-2{width:8.33333%}.el-col-offset-2{margin-left:8.33333%}.el-col-pull-2{position:relative;right:8.33333%}.el-col-push-2{position:relative;left:8.33333%}.el-col-3{width:12.5%}.el-col-offset-3{margin-left:12.5%}.el-col-pull-3{position:relative;right:12.5%}.el-col-push-3{position:relative;left:12.5%}.el-col-4{width:16.66667%}.el-col-offset-4{margin-left:16.66667%}.el-col-pull-4{position:relative;right:16.66667%}.el-col-push-4{position:relative;left:16.66667%}.el-col-5{width:20.83333%}.el-col-offset-5{margin-left:20.83333%}.el-col-pull-5{position:relative;right:20.83333%}.el-col-push-5{position:relative;left:20.83333%}.el-col-6{width:25%}.el-col-offset-6{margin-left:25%}.el-col-pull-6{position:relative;right:25%}.el-col-push-6{position:relative;left:25%}.el-col-7{width:29.16667%}.el-col-offset-7{margin-left:29.16667%}.el-col-pull-7{position:relative;right:29.16667%}.el-col-push-7{position:relative;left:29.16667%}.el-col-8{width:33.33333%}.el-col-offset-8{margin-left:33.33333%}.el-col-pull-8{position:relative;right:33.33333%}.el-col-push-8{position:relative;left:33.33333%}.el-col-9{width:37.5%}.el-col-offset-9{margin-left:37.5%}.el-col-pull-9{position:relative;right:37.5%}.el-col-push-9{position:relative;left:37.5%}.el-col-10{width:41.66667%}.el-col-offset-10{margin-left:41.66667%}.el-col-pull-10{position:relative;right:41.66667%}.el-col-push-10{position:relative;left:41.66667%}.el-col-11{width:45.83333%}.el-col-offset-11{margin-left:45.83333%}.el-col-pull-11{position:relative;right:45.83333%}.el-col-push-11{position:relative;left:45.83333%}.el-col-12{width:50%}.el-col-offset-12{margin-left:50%}.el-col-pull-12{position:relative;right:50%}.el-col-push-12{position:relative;left:50%}.el-col-13{width:54.16667%}.el-col-offset-13{margin-left:54.16667%}.el-col-pull-13{position:relative;right:54.16667%}.el-col-push-13{position:relative;left:54.16667%}.el-col-14{width:58.33333%}.el-col-offset-14{margin-left:58.33333%}.el-col-pull-14{position:relative;right:58.33333%}.el-col-push-14{position:relative;left:58.33333%}.el-col-15{width:62.5%}.el-col-offset-15{margin-left:62.5%}.el-col-pull-15{position:relative;right:62.5%}.el-col-push-15{position:relative;left:62.5%}.el-col-16{width:66.66667%}.el-col-offset-16{margin-left:66.66667%}.el-col-pull-16{position:relative;right:66.66667%}.el-col-push-16{position:relative;left:66.66667%}.el-col-17{width:70.83333%}.el-col-offset-17{margin-left:70.83333%}.el-col-pull-17{position:relative;right:70.83333%}.el-col-push-17{position:relative;left:70.83333%}.el-col-18{width:75%}.el-col-offset-18{margin-left:75%}.el-col-pull-18{position:relative;right:75%}.el-col-push-18{position:relative;left:75%}.el-col-19{width:79.16667%}.el-col-offset-19{margin-left:79.16667%}.el-col-pull-19{position:relative;right:79.16667%}.el-col-push-19{position:relative;left:79.16667%}.el-col-20{width:83.33333%}.el-col-offset-20{margin-left:83.33333%}.el-col-pull-20{position:relative;right:83.33333%}.el-col-push-20{position:relative;left:83.33333%}.el-col-21{width:87.5%}.el-col-offset-21{margin-left:87.5%}.el-col-pull-21{position:relative;right:87.5%}.el-col-push-21{position:relative;left:87.5%}.el-col-22{width:91.66667%}.el-col-offset-22{margin-left:91.66667%}.el-col-pull-22{position:relative;right:91.66667%}.el-col-push-22{position:relative;left:91.66667%}.el-col-23{width:95.83333%}.el-col-offset-23{margin-left:95.83333%}.el-col-pull-23{position:relative;right:95.83333%}.el-col-push-23{position:relative;left:95.83333%}.el-col-24{width:100%}.el-col-offset-24{margin-left:100%}.el-col-pull-24{position:relative;right:100%}.el-col-push-24{position:relative;left:100%}@media only screen and (max-width:767px){.el-col-xs-0{display:none;width:0}.el-col-xs-offset-0{margin-left:0}.el-col-xs-pull-0{position:relative;right:0}.el-col-xs-push-0{position:relative;left:0}.el-col-xs-1{width:4.16667%}.el-col-xs-offset-1{margin-left:4.16667%}.el-col-xs-pull-1{position:relative;right:4.16667%}.el-col-xs-push-1{position:relative;left:4.16667%}.el-col-xs-2{width:8.33333%}.el-col-xs-offset-2{margin-left:8.33333%}.el-col-xs-pull-2{position:relative;right:8.33333%}.el-col-xs-push-2{position:relative;left:8.33333%}.el-col-xs-3{width:12.5%}.el-col-xs-offset-3{margin-left:12.5%}.el-col-xs-pull-3{position:relative;right:12.5%}.el-col-xs-push-3{position:relative;left:12.5%}.el-col-xs-4{width:16.66667%}.el-col-xs-offset-4{margin-left:16.66667%}.el-col-xs-pull-4{position:relative;right:16.66667%}.el-col-xs-push-4{position:relative;left:16.66667%}.el-col-xs-5{width:20.83333%}.el-col-xs-offset-5{margin-left:20.83333%}.el-col-xs-pull-5{position:relative;right:20.83333%}.el-col-xs-push-5{position:relative;left:20.83333%}.el-col-xs-6{width:25%}.el-col-xs-offset-6{margin-left:25%}.el-col-xs-pull-6{position:relative;right:25%}.el-col-xs-push-6{position:relative;left:25%}.el-col-xs-7{width:29.16667%}.el-col-xs-offset-7{margin-left:29.16667%}.el-col-xs-pull-7{position:relative;right:29.16667%}.el-col-xs-push-7{position:relative;left:29.16667%}.el-col-xs-8{width:33.33333%}.el-col-xs-offset-8{margin-left:33.33333%}.el-col-xs-pull-8{position:relative;right:33.33333%}.el-col-xs-push-8{position:relative;left:33.33333%}.el-col-xs-9{width:37.5%}.el-col-xs-offset-9{margin-left:37.5%}.el-col-xs-pull-9{position:relative;right:37.5%}.el-col-xs-push-9{position:relative;left:37.5%}.el-col-xs-10{width:41.66667%}.el-col-xs-offset-10{margin-left:41.66667%}.el-col-xs-pull-10{position:relative;right:41.66667%}.el-col-xs-push-10{position:relative;left:41.66667%}.el-col-xs-11{width:45.83333%}.el-col-xs-offset-11{margin-left:45.83333%}.el-col-xs-pull-11{position:relative;right:45.83333%}.el-col-xs-push-11{position:relative;left:45.83333%}.el-col-xs-12{width:50%}.el-col-xs-offset-12{margin-left:50%}.el-col-xs-pull-12{position:relative;right:50%}.el-col-xs-push-12{position:relative;left:50%}.el-col-xs-13{width:54.16667%}.el-col-xs-offset-13{margin-left:54.16667%}.el-col-xs-pull-13{position:relative;right:54.16667%}.el-col-xs-push-13{position:relative;left:54.16667%}.el-col-xs-14{width:58.33333%}.el-col-xs-offset-14{margin-left:58.33333%}.el-col-xs-pull-14{position:relative;right:58.33333%}.el-col-xs-push-14{position:relative;left:58.33333%}.el-col-xs-15{width:62.5%}.el-col-xs-offset-15{margin-left:62.5%}.el-col-xs-pull-15{position:relative;right:62.5%}.el-col-xs-push-15{position:relative;left:62.5%}.el-col-xs-16{width:66.66667%}.el-col-xs-offset-16{margin-left:66.66667%}.el-col-xs-pull-16{position:relative;right:66.66667%}.el-col-xs-push-16{position:relative;left:66.66667%}.el-col-xs-17{width:70.83333%}.el-col-xs-offset-17{margin-left:70.83333%}.el-col-xs-pull-17{position:relative;right:70.83333%}.el-col-xs-push-17{position:relative;left:70.83333%}.el-col-xs-18{width:75%}.el-col-xs-offset-18{margin-left:75%}.el-col-xs-pull-18{position:relative;right:75%}.el-col-xs-push-18{position:relative;left:75%}.el-col-xs-19{width:79.16667%}.el-col-xs-offset-19{margin-left:79.16667%}.el-col-xs-pull-19{position:relative;right:79.16667%}.el-col-xs-push-19{position:relative;left:79.16667%}.el-col-xs-20{width:83.33333%}.el-col-xs-offset-20{margin-left:83.33333%}.el-col-xs-pull-20{position:relative;right:83.33333%}.el-col-xs-push-20{position:relative;left:83.33333%}.el-col-xs-21{width:87.5%}.el-col-xs-offset-21{margin-left:87.5%}.el-col-xs-pull-21{position:relative;right:87.5%}.el-col-xs-push-21{position:relative;left:87.5%}.el-col-xs-22{width:91.66667%}.el-col-xs-offset-22{margin-left:91.66667%}.el-col-xs-pull-22{position:relative;right:91.66667%}.el-col-xs-push-22{position:relative;left:91.66667%}.el-col-xs-23{width:95.83333%}.el-col-xs-offset-23{margin-left:95.83333%}.el-col-xs-pull-23{position:relative;right:95.83333%}.el-col-xs-push-23{position:relative;left:95.83333%}.el-col-xs-24{width:100%}.el-col-xs-offset-24{margin-left:100%}.el-col-xs-pull-24{position:relative;right:100%}.el-col-xs-push-24{position:relative;left:100%}}@media only screen and (min-width:768px){.el-col-sm-0{display:none;width:0}.el-col-sm-offset-0{margin-left:0}.el-col-sm-pull-0{position:relative;right:0}.el-col-sm-push-0{position:relative;left:0}.el-col-sm-1{width:4.16667%}.el-col-sm-offset-1{margin-left:4.16667%}.el-col-sm-pull-1{position:relative;right:4.16667%}.el-col-sm-push-1{position:relative;left:4.16667%}.el-col-sm-2{width:8.33333%}.el-col-sm-offset-2{margin-left:8.33333%}.el-col-sm-pull-2{position:relative;right:8.33333%}.el-col-sm-push-2{position:relative;left:8.33333%}.el-col-sm-3{width:12.5%}.el-col-sm-offset-3{margin-left:12.5%}.el-col-sm-pull-3{position:relative;right:12.5%}.el-col-sm-push-3{position:relative;left:12.5%}.el-col-sm-4{width:16.66667%}.el-col-sm-offset-4{margin-left:16.66667%}.el-col-sm-pull-4{position:relative;right:16.66667%}.el-col-sm-push-4{position:relative;left:16.66667%}.el-col-sm-5{width:20.83333%}.el-col-sm-offset-5{margin-left:20.83333%}.el-col-sm-pull-5{position:relative;right:20.83333%}.el-col-sm-push-5{position:relative;left:20.83333%}.el-col-sm-6{width:25%}.el-col-sm-offset-6{margin-left:25%}.el-col-sm-pull-6{position:relative;right:25%}.el-col-sm-push-6{position:relative;left:25%}.el-col-sm-7{width:29.16667%}.el-col-sm-offset-7{margin-left:29.16667%}.el-col-sm-pull-7{position:relative;right:29.16667%}.el-col-sm-push-7{position:relative;left:29.16667%}.el-col-sm-8{width:33.33333%}.el-col-sm-offset-8{margin-left:33.33333%}.el-col-sm-pull-8{position:relative;right:33.33333%}.el-col-sm-push-8{position:relative;left:33.33333%}.el-col-sm-9{width:37.5%}.el-col-sm-offset-9{margin-left:37.5%}.el-col-sm-pull-9{position:relative;right:37.5%}.el-col-sm-push-9{position:relative;left:37.5%}.el-col-sm-10{width:41.66667%}.el-col-sm-offset-10{margin-left:41.66667%}.el-col-sm-pull-10{position:relative;right:41.66667%}.el-col-sm-push-10{position:relative;left:41.66667%}.el-col-sm-11{width:45.83333%}.el-col-sm-offset-11{margin-left:45.83333%}.el-col-sm-pull-11{position:relative;right:45.83333%}.el-col-sm-push-11{position:relative;left:45.83333%}.el-col-sm-12{width:50%}.el-col-sm-offset-12{margin-left:50%}.el-col-sm-pull-12{position:relative;right:50%}.el-col-sm-push-12{position:relative;left:50%}.el-col-sm-13{width:54.16667%}.el-col-sm-offset-13{margin-left:54.16667%}.el-col-sm-pull-13{position:relative;right:54.16667%}.el-col-sm-push-13{position:relative;left:54.16667%}.el-col-sm-14{width:58.33333%}.el-col-sm-offset-14{margin-left:58.33333%}.el-col-sm-pull-14{position:relative;right:58.33333%}.el-col-sm-push-14{position:relative;left:58.33333%}.el-col-sm-15{width:62.5%}.el-col-sm-offset-15{margin-left:62.5%}.el-col-sm-pull-15{position:relative;right:62.5%}.el-col-sm-push-15{position:relative;left:62.5%}.el-col-sm-16{width:66.66667%}.el-col-sm-offset-16{margin-left:66.66667%}.el-col-sm-pull-16{position:relative;right:66.66667%}.el-col-sm-push-16{position:relative;left:66.66667%}.el-col-sm-17{width:70.83333%}.el-col-sm-offset-17{margin-left:70.83333%}.el-col-sm-pull-17{position:relative;right:70.83333%}.el-col-sm-push-17{position:relative;left:70.83333%}.el-col-sm-18{width:75%}.el-col-sm-offset-18{margin-left:75%}.el-col-sm-pull-18{position:relative;right:75%}.el-col-sm-push-18{position:relative;left:75%}.el-col-sm-19{width:79.16667%}.el-col-sm-offset-19{margin-left:79.16667%}.el-col-sm-pull-19{position:relative;right:79.16667%}.el-col-sm-push-19{position:relative;left:79.16667%}.el-col-sm-20{width:83.33333%}.el-col-sm-offset-20{margin-left:83.33333%}.el-col-sm-pull-20{position:relative;right:83.33333%}.el-col-sm-push-20{position:relative;left:83.33333%}.el-col-sm-21{width:87.5%}.el-col-sm-offset-21{margin-left:87.5%}.el-col-sm-pull-21{position:relative;right:87.5%}.el-col-sm-push-21{position:relative;left:87.5%}.el-col-sm-22{width:91.66667%}.el-col-sm-offset-22{margin-left:91.66667%}.el-col-sm-pull-22{position:relative;right:91.66667%}.el-col-sm-push-22{position:relative;left:91.66667%}.el-col-sm-23{width:95.83333%}.el-col-sm-offset-23{margin-left:95.83333%}.el-col-sm-pull-23{position:relative;right:95.83333%}.el-col-sm-push-23{position:relative;left:95.83333%}.el-col-sm-24{width:100%}.el-col-sm-offset-24{margin-left:100%}.el-col-sm-pull-24{position:relative;right:100%}.el-col-sm-push-24{position:relative;left:100%}}@media only screen and (min-width:992px){.el-col-md-0{display:none;width:0}.el-col-md-offset-0{margin-left:0}.el-col-md-pull-0{position:relative;right:0}.el-col-md-push-0{position:relative;left:0}.el-col-md-1{width:4.16667%}.el-col-md-offset-1{margin-left:4.16667%}.el-col-md-pull-1{position:relative;right:4.16667%}.el-col-md-push-1{position:relative;left:4.16667%}.el-col-md-2{width:8.33333%}.el-col-md-offset-2{margin-left:8.33333%}.el-col-md-pull-2{position:relative;right:8.33333%}.el-col-md-push-2{position:relative;left:8.33333%}.el-col-md-3{width:12.5%}.el-col-md-offset-3{margin-left:12.5%}.el-col-md-pull-3{position:relative;right:12.5%}.el-col-md-push-3{position:relative;left:12.5%}.el-col-md-4{width:16.66667%}.el-col-md-offset-4{margin-left:16.66667%}.el-col-md-pull-4{position:relative;right:16.66667%}.el-col-md-push-4{position:relative;left:16.66667%}.el-col-md-5{width:20.83333%}.el-col-md-offset-5{margin-left:20.83333%}.el-col-md-pull-5{position:relative;right:20.83333%}.el-col-md-push-5{position:relative;left:20.83333%}.el-col-md-6{width:25%}.el-col-md-offset-6{margin-left:25%}.el-col-md-pull-6{position:relative;right:25%}.el-col-md-push-6{position:relative;left:25%}.el-col-md-7{width:29.16667%}.el-col-md-offset-7{margin-left:29.16667%}.el-col-md-pull-7{position:relative;right:29.16667%}.el-col-md-push-7{position:relative;left:29.16667%}.el-col-md-8{width:33.33333%}.el-col-md-offset-8{margin-left:33.33333%}.el-col-md-pull-8{position:relative;right:33.33333%}.el-col-md-push-8{position:relative;left:33.33333%}.el-col-md-9{width:37.5%}.el-col-md-offset-9{margin-left:37.5%}.el-col-md-pull-9{position:relative;right:37.5%}.el-col-md-push-9{position:relative;left:37.5%}.el-col-md-10{width:41.66667%}.el-col-md-offset-10{margin-left:41.66667%}.el-col-md-pull-10{position:relative;right:41.66667%}.el-col-md-push-10{position:relative;left:41.66667%}.el-col-md-11{width:45.83333%}.el-col-md-offset-11{margin-left:45.83333%}.el-col-md-pull-11{position:relative;right:45.83333%}.el-col-md-push-11{position:relative;left:45.83333%}.el-col-md-12{width:50%}.el-col-md-offset-12{margin-left:50%}.el-col-md-pull-12{position:relative;right:50%}.el-col-md-push-12{position:relative;left:50%}.el-col-md-13{width:54.16667%}.el-col-md-offset-13{margin-left:54.16667%}.el-col-md-pull-13{position:relative;right:54.16667%}.el-col-md-push-13{position:relative;left:54.16667%}.el-col-md-14{width:58.33333%}.el-col-md-offset-14{margin-left:58.33333%}.el-col-md-pull-14{position:relative;right:58.33333%}.el-col-md-push-14{position:relative;left:58.33333%}.el-col-md-15{width:62.5%}.el-col-md-offset-15{margin-left:62.5%}.el-col-md-pull-15{position:relative;right:62.5%}.el-col-md-push-15{position:relative;left:62.5%}.el-col-md-16{width:66.66667%}.el-col-md-offset-16{margin-left:66.66667%}.el-col-md-pull-16{position:relative;right:66.66667%}.el-col-md-push-16{position:relative;left:66.66667%}.el-col-md-17{width:70.83333%}.el-col-md-offset-17{margin-left:70.83333%}.el-col-md-pull-17{position:relative;right:70.83333%}.el-col-md-push-17{position:relative;left:70.83333%}.el-col-md-18{width:75%}.el-col-md-offset-18{margin-left:75%}.el-col-md-pull-18{position:relative;right:75%}.el-col-md-push-18{position:relative;left:75%}.el-col-md-19{width:79.16667%}.el-col-md-offset-19{margin-left:79.16667%}.el-col-md-pull-19{position:relative;right:79.16667%}.el-col-md-push-19{position:relative;left:79.16667%}.el-col-md-20{width:83.33333%}.el-col-md-offset-20{margin-left:83.33333%}.el-col-md-pull-20{position:relative;right:83.33333%}.el-col-md-push-20{position:relative;left:83.33333%}.el-col-md-21{width:87.5%}.el-col-md-offset-21{margin-left:87.5%}.el-col-md-pull-21{position:relative;right:87.5%}.el-col-md-push-21{position:relative;left:87.5%}.el-col-md-22{width:91.66667%}.el-col-md-offset-22{margin-left:91.66667%}.el-col-md-pull-22{position:relative;right:91.66667%}.el-col-md-push-22{position:relative;left:91.66667%}.el-col-md-23{width:95.83333%}.el-col-md-offset-23{margin-left:95.83333%}.el-col-md-pull-23{position:relative;right:95.83333%}.el-col-md-push-23{position:relative;left:95.83333%}.el-col-md-24{width:100%}.el-col-md-offset-24{margin-left:100%}.el-col-md-pull-24{position:relative;right:100%}.el-col-md-push-24{position:relative;left:100%}}@media only screen and (min-width:1200px){.el-col-lg-0{display:none;width:0}.el-col-lg-offset-0{margin-left:0}.el-col-lg-pull-0{position:relative;right:0}.el-col-lg-push-0{position:relative;left:0}.el-col-lg-1{width:4.16667%}.el-col-lg-offset-1{margin-left:4.16667%}.el-col-lg-pull-1{position:relative;right:4.16667%}.el-col-lg-push-1{position:relative;left:4.16667%}.el-col-lg-2{width:8.33333%}.el-col-lg-offset-2{margin-left:8.33333%}.el-col-lg-pull-2{position:relative;right:8.33333%}.el-col-lg-push-2{position:relative;left:8.33333%}.el-col-lg-3{width:12.5%}.el-col-lg-offset-3{margin-left:12.5%}.el-col-lg-pull-3{position:relative;right:12.5%}.el-col-lg-push-3{position:relative;left:12.5%}.el-col-lg-4{width:16.66667%}.el-col-lg-offset-4{margin-left:16.66667%}.el-col-lg-pull-4{position:relative;right:16.66667%}.el-col-lg-push-4{position:relative;left:16.66667%}.el-col-lg-5{width:20.83333%}.el-col-lg-offset-5{margin-left:20.83333%}.el-col-lg-pull-5{position:relative;right:20.83333%}.el-col-lg-push-5{position:relative;left:20.83333%}.el-col-lg-6{width:25%}.el-col-lg-offset-6{margin-left:25%}.el-col-lg-pull-6{position:relative;right:25%}.el-col-lg-push-6{position:relative;left:25%}.el-col-lg-7{width:29.16667%}.el-col-lg-offset-7{margin-left:29.16667%}.el-col-lg-pull-7{position:relative;right:29.16667%}.el-col-lg-push-7{position:relative;left:29.16667%}.el-col-lg-8{width:33.33333%}.el-col-lg-offset-8{margin-left:33.33333%}.el-col-lg-pull-8{position:relative;right:33.33333%}.el-col-lg-push-8{position:relative;left:33.33333%}.el-col-lg-9{width:37.5%}.el-col-lg-offset-9{margin-left:37.5%}.el-col-lg-pull-9{position:relative;right:37.5%}.el-col-lg-push-9{position:relative;left:37.5%}.el-col-lg-10{width:41.66667%}.el-col-lg-offset-10{margin-left:41.66667%}.el-col-lg-pull-10{position:relative;right:41.66667%}.el-col-lg-push-10{position:relative;left:41.66667%}.el-col-lg-11{width:45.83333%}.el-col-lg-offset-11{margin-left:45.83333%}.el-col-lg-pull-11{position:relative;right:45.83333%}.el-col-lg-push-11{position:relative;left:45.83333%}.el-col-lg-12{width:50%}.el-col-lg-offset-12{margin-left:50%}.el-col-lg-pull-12{position:relative;right:50%}.el-col-lg-push-12{position:relative;left:50%}.el-col-lg-13{width:54.16667%}.el-col-lg-offset-13{margin-left:54.16667%}.el-col-lg-pull-13{position:relative;right:54.16667%}.el-col-lg-push-13{position:relative;left:54.16667%}.el-col-lg-14{width:58.33333%}.el-col-lg-offset-14{margin-left:58.33333%}.el-col-lg-pull-14{position:relative;right:58.33333%}.el-col-lg-push-14{position:relative;left:58.33333%}.el-col-lg-15{width:62.5%}.el-col-lg-offset-15{margin-left:62.5%}.el-col-lg-pull-15{position:relative;right:62.5%}.el-col-lg-push-15{position:relative;left:62.5%}.el-col-lg-16{width:66.66667%}.el-col-lg-offset-16{margin-left:66.66667%}.el-col-lg-pull-16{position:relative;right:66.66667%}.el-col-lg-push-16{position:relative;left:66.66667%}.el-col-lg-17{width:70.83333%}.el-col-lg-offset-17{margin-left:70.83333%}.el-col-lg-pull-17{position:relative;right:70.83333%}.el-col-lg-push-17{position:relative;left:70.83333%}.el-col-lg-18{width:75%}.el-col-lg-offset-18{margin-left:75%}.el-col-lg-pull-18{position:relative;right:75%}.el-col-lg-push-18{position:relative;left:75%}.el-col-lg-19{width:79.16667%}.el-col-lg-offset-19{margin-left:79.16667%}.el-col-lg-pull-19{position:relative;right:79.16667%}.el-col-lg-push-19{position:relative;left:79.16667%}.el-col-lg-20{width:83.33333%}.el-col-lg-offset-20{margin-left:83.33333%}.el-col-lg-pull-20{position:relative;right:83.33333%}.el-col-lg-push-20{position:relative;left:83.33333%}.el-col-lg-21{width:87.5%}.el-col-lg-offset-21{margin-left:87.5%}.el-col-lg-pull-21{position:relative;right:87.5%}.el-col-lg-push-21{position:relative;left:87.5%}.el-col-lg-22{width:91.66667%}.el-col-lg-offset-22{margin-left:91.66667%}.el-col-lg-pull-22{position:relative;right:91.66667%}.el-col-lg-push-22{position:relative;left:91.66667%}.el-col-lg-23{width:95.83333%}.el-col-lg-offset-23{margin-left:95.83333%}.el-col-lg-pull-23{position:relative;right:95.83333%}.el-col-lg-push-23{position:relative;left:95.83333%}.el-col-lg-24{width:100%}.el-col-lg-offset-24{margin-left:100%}.el-col-lg-pull-24{position:relative;right:100%}.el-col-lg-push-24{position:relative;left:100%}}@media only screen and (min-width:1920px){.el-col-xl-0{display:none;width:0}.el-col-xl-offset-0{margin-left:0}.el-col-xl-pull-0{position:relative;right:0}.el-col-xl-push-0{position:relative;left:0}.el-col-xl-1{width:4.16667%}.el-col-xl-offset-1{margin-left:4.16667%}.el-col-xl-pull-1{position:relative;right:4.16667%}.el-col-xl-push-1{position:relative;left:4.16667%}.el-col-xl-2{width:8.33333%}.el-col-xl-offset-2{margin-left:8.33333%}.el-col-xl-pull-2{position:relative;right:8.33333%}.el-col-xl-push-2{position:relative;left:8.33333%}.el-col-xl-3{width:12.5%}.el-col-xl-offset-3{margin-left:12.5%}.el-col-xl-pull-3{position:relative;right:12.5%}.el-col-xl-push-3{position:relative;left:12.5%}.el-col-xl-4{width:16.66667%}.el-col-xl-offset-4{margin-left:16.66667%}.el-col-xl-pull-4{position:relative;right:16.66667%}.el-col-xl-push-4{position:relative;left:16.66667%}.el-col-xl-5{width:20.83333%}.el-col-xl-offset-5{margin-left:20.83333%}.el-col-xl-pull-5{position:relative;right:20.83333%}.el-col-xl-push-5{position:relative;left:20.83333%}.el-col-xl-6{width:25%}.el-col-xl-offset-6{margin-left:25%}.el-col-xl-pull-6{position:relative;right:25%}.el-col-xl-push-6{position:relative;left:25%}.el-col-xl-7{width:29.16667%}.el-col-xl-offset-7{margin-left:29.16667%}.el-col-xl-pull-7{position:relative;right:29.16667%}.el-col-xl-push-7{position:relative;left:29.16667%}.el-col-xl-8{width:33.33333%}.el-col-xl-offset-8{margin-left:33.33333%}.el-col-xl-pull-8{position:relative;right:33.33333%}.el-col-xl-push-8{position:relative;left:33.33333%}.el-col-xl-9{width:37.5%}.el-col-xl-offset-9{margin-left:37.5%}.el-col-xl-pull-9{position:relative;right:37.5%}.el-col-xl-push-9{position:relative;left:37.5%}.el-col-xl-10{width:41.66667%}.el-col-xl-offset-10{margin-left:41.66667%}.el-col-xl-pull-10{position:relative;right:41.66667%}.el-col-xl-push-10{position:relative;left:41.66667%}.el-col-xl-11{width:45.83333%}.el-col-xl-offset-11{margin-left:45.83333%}.el-col-xl-pull-11{position:relative;right:45.83333%}.el-col-xl-push-11{position:relative;left:45.83333%}.el-col-xl-12{width:50%}.el-col-xl-offset-12{margin-left:50%}.el-col-xl-pull-12{position:relative;right:50%}.el-col-xl-push-12{position:relative;left:50%}.el-col-xl-13{width:54.16667%}.el-col-xl-offset-13{margin-left:54.16667%}.el-col-xl-pull-13{position:relative;right:54.16667%}.el-col-xl-push-13{position:relative;left:54.16667%}.el-col-xl-14{width:58.33333%}.el-col-xl-offset-14{margin-left:58.33333%}.el-col-xl-pull-14{position:relative;right:58.33333%}.el-col-xl-push-14{position:relative;left:58.33333%}.el-col-xl-15{width:62.5%}.el-col-xl-offset-15{margin-left:62.5%}.el-col-xl-pull-15{position:relative;right:62.5%}.el-col-xl-push-15{position:relative;left:62.5%}.el-col-xl-16{width:66.66667%}.el-col-xl-offset-16{margin-left:66.66667%}.el-col-xl-pull-16{position:relative;right:66.66667%}.el-col-xl-push-16{position:relative;left:66.66667%}.el-col-xl-17{width:70.83333%}.el-col-xl-offset-17{margin-left:70.83333%}.el-col-xl-pull-17{position:relative;right:70.83333%}.el-col-xl-push-17{position:relative;left:70.83333%}.el-col-xl-18{width:75%}.el-col-xl-offset-18{margin-left:75%}.el-col-xl-pull-18{position:relative;right:75%}.el-col-xl-push-18{position:relative;left:75%}.el-col-xl-19{width:79.16667%}.el-col-xl-offset-19{margin-left:79.16667%}.el-col-xl-pull-19{position:relative;right:79.16667%}.el-col-xl-push-19{position:relative;left:79.16667%}.el-col-xl-20{width:83.33333%}.el-col-xl-offset-20{margin-left:83.33333%}.el-col-xl-pull-20{position:relative;right:83.33333%}.el-col-xl-push-20{position:relative;left:83.33333%}.el-col-xl-21{width:87.5%}.el-col-xl-offset-21{margin-left:87.5%}.el-col-xl-pull-21{position:relative;right:87.5%}.el-col-xl-push-21{position:relative;left:87.5%}.el-col-xl-22{width:91.66667%}.el-col-xl-offset-22{margin-left:91.66667%}.el-col-xl-pull-22{position:relative;right:91.66667%}.el-col-xl-push-22{position:relative;left:91.66667%}.el-col-xl-23{width:95.83333%}.el-col-xl-offset-23{margin-left:95.83333%}.el-col-xl-pull-23{position:relative;right:95.83333%}.el-col-xl-push-23{position:relative;left:95.83333%}.el-col-xl-24{width:100%}.el-col-xl-offset-24{margin-left:100%}.el-col-xl-pull-24{position:relative;right:100%}.el-col-xl-push-24{position:relative;left:100%}}.el-upload{display:inline-block;text-align:center;cursor:pointer;outline:none}.el-upload__input{display:none}.el-upload__tip{font-size:12px;color:#606266;margin-top:7px}.el-upload iframe{position:absolute;z-index:-1;top:0;left:0;opacity:0;filter:alpha(opacity=0)}.el-upload--picture-card{background-color:#fbfdff;border:1px dashed #c0ccda;border-radius:6px;box-sizing:border-box;width:148px;height:148px;cursor:pointer;line-height:146px;vertical-align:top}.el-upload--picture-card i{font-size:28px;color:#8c939d}.el-upload--picture-card:hover,.el-upload:focus{border-color:#42d885;color:#42d885}.el-upload:focus .el-upload-dragger{border-color:#42d885}.el-upload-dragger{background-color:#fff;border:1px dashed #d9d9d9;border-radius:6px;box-sizing:border-box;width:360px;height:180px;text-align:center;cursor:pointer;position:relative;overflow:hidden}.el-upload-dragger .el-icon-upload{font-size:67px;color:#c0c4cc;margin:40px 0 16px;line-height:50px}.el-upload-dragger+.el-upload__tip{text-align:center}.el-upload-dragger~.el-upload__files{border-top:1px solid #dcdfe6;margin-top:7px;padding-top:5px}.el-upload-dragger .el-upload__text{color:#606266;font-size:14px;text-align:center}.el-upload-dragger .el-upload__text em{color:#42d885;font-style:normal}.el-upload-dragger:hover{border-color:#42d885}.el-upload-dragger.is-dragover{background-color:rgba(32,159,255,.06);border:2px dashed #42d885}.el-upload-list{margin:0;padding:0;list-style:none}.el-upload-list__item{transition:all .5s cubic-bezier(.55,0,.1,1);font-size:14px;color:#606266;line-height:1.8;margin-top:5px;position:relative;box-sizing:border-box;border-radius:4px;width:100%}.el-upload-list__item .el-progress{position:absolute;top:20px;width:100%}.el-upload-list__item .el-progress__text{position:absolute;right:0;top:-13px}.el-upload-list__item .el-progress-bar{margin-right:0;padding-right:0}.el-upload-list__item:first-child{margin-top:10px}.el-upload-list__item .el-icon-upload-success{color:#42d885}.el-upload-list__item .el-icon-close{display:none;position:absolute;top:5px;right:5px;cursor:pointer;opacity:.75;color:#606266}.el-upload-list__item .el-icon-close:hover{opacity:1}.el-upload-list__item .el-icon-close-tip{display:none;position:absolute;top:5px;right:5px;font-size:12px;cursor:pointer;opacity:1;color:#42d885}.el-upload-list__item:hover{background-color:#f5f7fa}.el-upload-list__item:hover .el-icon-close{display:inline-block}.el-upload-list__item:hover .el-progress__text{display:none}.el-upload-list__item.is-success .el-upload-list__item-status-label{display:block}.el-upload-list__item.is-success .el-upload-list__item-name:focus,.el-upload-list__item.is-success .el-upload-list__item-name:hover{color:#42d885;cursor:pointer}.el-upload-list__item.is-success:focus:not(:hover) .el-icon-close-tip{display:inline-block}.el-upload-list__item.is-success:active,.el-upload-list__item.is-success:not(.focusing):focus{outline-width:0}.el-upload-list__item.is-success:active .el-icon-close-tip,.el-upload-list__item.is-success:focus .el-upload-list__item-status-label,.el-upload-list__item.is-success:hover .el-upload-list__item-status-label,.el-upload-list__item.is-success:not(.focusing):focus .el-icon-close-tip{display:none}.el-upload-list.is-disabled .el-upload-list__item:hover .el-upload-list__item-status-label{display:block}.el-upload-list__item-name{color:#606266;display:block;margin-right:40px;overflow:hidden;padding-left:4px;text-overflow:ellipsis;transition:color .3s;white-space:nowrap}.el-upload-list__item-name [class^=el-icon]{height:100%;margin-right:7px;color:#909399;line-height:inherit}.el-upload-list__item-status-label{position:absolute;right:5px;top:0;line-height:inherit;display:none}.el-upload-list__item-delete{position:absolute;right:10px;top:0;font-size:12px;color:#606266;display:none}.el-upload-list__item-delete:hover{color:#42d885}.el-upload-list--picture-card{margin:0;display:inline;vertical-align:top}.el-upload-list--picture-card .el-upload-list__item{overflow:hidden;background-color:#fff;border:1px solid #c0ccda;border-radius:6px;box-sizing:border-box;width:148px;height:148px;margin:0 8px 8px 0;display:inline-block}.el-upload-list--picture-card .el-upload-list__item .el-icon-check,.el-upload-list--picture-card .el-upload-list__item .el-icon-circle-check{color:#fff}.el-upload-list--picture-card .el-upload-list__item .el-icon-close,.el-upload-list--picture-card .el-upload-list__item:hover .el-upload-list__item-status-label{display:none}.el-upload-list--picture-card .el-upload-list__item:hover .el-progress__text{display:block}.el-upload-list--picture-card .el-upload-list__item-name{display:none}.el-upload-list--picture-card .el-upload-list__item-thumbnail{width:100%;height:100%}.el-upload-list--picture-card .el-upload-list__item-status-label{position:absolute;right:-15px;top:-6px;width:40px;height:24px;background:#13ce66;text-align:center;transform:rotate(45deg);box-shadow:0 0 1pc 1px rgba(0,0,0,.2)}.el-upload-list--picture-card .el-upload-list__item-status-label i{font-size:12px;margin-top:11px;transform:rotate(-45deg)}.el-upload-list--picture-card .el-upload-list__item-actions{position:absolute;width:100%;height:100%;left:0;top:0;cursor:default;text-align:center;color:#fff;opacity:0;font-size:20px;background-color:rgba(0,0,0,.5);transition:opacity .3s}.el-upload-list--picture-card .el-upload-list__item-actions:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-upload-list--picture-card .el-upload-list__item-actions span{display:none;cursor:pointer}.el-upload-list--picture-card .el-upload-list__item-actions span+span{margin-left:15px}.el-upload-list--picture-card .el-upload-list__item-actions .el-upload-list__item-delete{position:static;font-size:inherit;color:inherit}.el-upload-list--picture-card .el-upload-list__item-actions:hover{opacity:1}.el-upload-list--picture-card .el-upload-list__item-actions:hover span{display:inline-block}.el-upload-list--picture-card .el-progress{top:50%;left:50%;transform:translate(-50%,-50%);bottom:auto;width:126px}.el-upload-list--picture-card .el-progress .el-progress__text{top:50%}.el-upload-list--picture .el-upload-list__item{overflow:hidden;z-index:0;background-color:#fff;border:1px solid #c0ccda;border-radius:6px;box-sizing:border-box;margin-top:10px;padding:10px 10px 10px 90px;height:92px}.el-upload-list--picture .el-upload-list__item .el-icon-check,.el-upload-list--picture .el-upload-list__item .el-icon-circle-check{color:#fff}.el-upload-list--picture .el-upload-list__item:hover .el-upload-list__item-status-label{background:transparent;box-shadow:none;top:-2px;right:-12px}.el-upload-list--picture .el-upload-list__item:hover .el-progress__text{display:block}.el-upload-list--picture .el-upload-list__item.is-success .el-upload-list__item-name{line-height:70px;margin-top:0}.el-upload-list--picture .el-upload-list__item.is-success .el-upload-list__item-name i{display:none}.el-upload-list--picture .el-upload-list__item-thumbnail{vertical-align:middle;display:inline-block;width:70px;height:70px;float:left;position:relative;z-index:1;margin-left:-80px;background-color:#fff}.el-upload-list--picture .el-upload-list__item-name{display:block;margin-top:20px}.el-upload-list--picture .el-upload-list__item-name i{font-size:70px;line-height:1;position:absolute;left:9px;top:10px}.el-upload-list--picture .el-upload-list__item-status-label{position:absolute;right:-17px;top:-7px;width:46px;height:26px;background:#13ce66;text-align:center;transform:rotate(45deg);box-shadow:0 1px 1px #ccc}.el-upload-list--picture .el-upload-list__item-status-label i{font-size:12px;margin-top:12px;transform:rotate(-45deg)}.el-upload-list--picture .el-progress{position:relative;top:-7px}.el-upload-cover{position:absolute;left:0;top:0;width:100%;height:100%;overflow:hidden;z-index:10;cursor:default}.el-upload-cover:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-upload-cover img{display:block;width:100%;height:100%}.el-upload-cover__label{position:absolute;right:-15px;top:-6px;width:40px;height:24px;background:#13ce66;text-align:center;transform:rotate(45deg);box-shadow:0 0 1pc 1px rgba(0,0,0,.2)}.el-upload-cover__label i{font-size:12px;margin-top:11px;transform:rotate(-45deg);color:#fff}.el-upload-cover__progress{display:inline-block;vertical-align:middle;position:static;width:243px}.el-upload-cover__progress+.el-upload__inner{opacity:0}.el-upload-cover__content{position:absolute;top:0;left:0;width:100%;height:100%}.el-upload-cover__interact{position:absolute;bottom:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,.72);text-align:center}.el-upload-cover__interact .btn{display:inline-block;color:#fff;font-size:14px;cursor:pointer;vertical-align:middle;transition:transform .3s cubic-bezier(.23,1,.32,1),opacity .3s cubic-bezier(.23,1,.32,1);margin-top:60px}.el-upload-cover__interact .btn i{margin-top:0}.el-upload-cover__interact .btn span{opacity:0;transition:opacity .15s linear}.el-upload-cover__interact .btn:not(:first-child){margin-left:35px}.el-upload-cover__interact .btn:hover{transform:translateY(-13px)}.el-upload-cover__interact .btn:hover span{opacity:1}.el-upload-cover__interact .btn i{color:#fff;display:block;font-size:24px;line-height:inherit;margin:0 auto 5px}.el-upload-cover__title{position:absolute;bottom:0;left:0;background-color:#fff;height:36px;width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:400;text-align:left;padding:0 10px;margin:0;line-height:36px;font-size:14px;color:#303133}.el-upload-cover+.el-upload__inner{opacity:0;position:relative;z-index:1}.el-progress{position:relative;line-height:1}.el-progress__text{font-size:14px;color:#606266;display:inline-block;vertical-align:middle;margin-left:10px;line-height:1}.el-progress__text i{vertical-align:middle;display:block}.el-progress--circle,.el-progress--dashboard{display:inline-block}.el-progress--circle .el-progress__text,.el-progress--dashboard .el-progress__text{position:absolute;top:50%;left:0;width:100%;text-align:center;margin:0;transform:translateY(-50%)}.el-progress--circle .el-progress__text i,.el-progress--dashboard .el-progress__text i{vertical-align:middle;display:inline-block}.el-progress--without-text .el-progress__text{display:none}.el-progress--without-text .el-progress-bar{padding-right:0;margin-right:0;display:block}.el-progress--text-inside .el-progress-bar{padding-right:0;margin-right:0}.el-progress.is-success .el-progress-bar__inner{background-color:#42d885}.el-progress.is-success .el-progress__text{color:#42d885}.el-progress.is-warning .el-progress-bar__inner{background-color:#f9c855}.el-progress.is-warning .el-progress__text{color:#f9c855}.el-progress.is-exception .el-progress-bar__inner{background-color:#ff6d6d}.el-progress.is-exception .el-progress__text{color:#ff6d6d}.el-progress-bar{padding-right:50px;display:inline-block;vertical-align:middle;width:100%;margin-right:-55px;box-sizing:border-box}.el-progress-bar__outer{height:6px;border-radius:100px;background-color:#ebeef5;overflow:hidden;position:relative;vertical-align:middle}.el-progress-bar__inner{position:absolute;left:0;top:0;height:100%;background-color:#42d885;text-align:right;border-radius:100px;line-height:1;white-space:nowrap;transition:width .6s ease}.el-progress-bar__inner:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-progress-bar__innerText{display:inline-block;vertical-align:middle;color:#fff;font-size:12px;margin:0 5px}@keyframes progress{0%{background-position:0 0}to{background-position:32px 0}}.el-time-spinner{width:100%;white-space:nowrap}.el-spinner{display:inline-block;vertical-align:middle}.el-spinner-inner{animation:rotate 2s linear infinite;width:50px;height:50px}.el-spinner-inner .path{stroke:#ececec;stroke-linecap:round;animation:dash 1.5s ease-in-out infinite}@keyframes rotate{to{transform:rotate(1turn)}}@keyframes dash{0%{stroke-dasharray:1,150;stroke-dashoffset:0}50%{stroke-dasharray:90,150;stroke-dashoffset:-35}to{stroke-dasharray:90,150;stroke-dashoffset:-124}}.el-message{min-width:380px;box-sizing:border-box;border-radius:4px;border:1px solid #ebeef5;position:fixed;left:50%;top:20px;transform:translateX(-50%);background-color:#edf2fc;transition:opacity .3s,transform .4s,top .4s;overflow:hidden;padding:15px 15px 15px 20px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.el-message.is-center{-ms-flex-pack:center;justify-content:center}.el-message.is-closable .el-message__content{padding-right:16px}.el-message p{margin:0}.el-message--info .el-message__content{color:#909399}.el-message--success{background-color:#ecfbf3;border-color:#d9f7e7}.el-message--success .el-message__content{color:#42d885}.el-message--warning{background-color:#fefaee;border-color:#fef4dd}.el-message--warning .el-message__content{color:#f9c855}.el-message--error{background-color:#fff0f0;border-color:#ffe2e2}.el-message--error .el-message__content{color:#ff6d6d}.el-message__icon{margin-right:10px}.el-message__content{padding:0;font-size:14px;line-height:1}.el-message__content:focus{outline-width:0}.el-message__closeBtn{position:absolute;top:50%;right:15px;transform:translateY(-50%);cursor:pointer;color:#c0c4cc;font-size:16px}.el-message__closeBtn:focus{outline-width:0}.el-message__closeBtn:hover{color:#909399}.el-message .el-icon-success{color:#42d885}.el-message .el-icon-error{color:#ff6d6d}.el-message .el-icon-info{color:#909399}.el-message .el-icon-warning{color:#f9c855}.el-message-fade-enter,.el-message-fade-leave-active{opacity:0;transform:translate(-50%,-100%)}.el-badge{position:relative;vertical-align:middle;display:inline-block}.el-badge__content{background-color:#ff6d6d;border-radius:10px;color:#fff;display:inline-block;font-size:12px;height:18px;line-height:18px;padding:0 6px;text-align:center;white-space:nowrap;border:1px solid #fff}.el-badge__content.is-fixed{position:absolute;top:0;right:10px;transform:translateY(-50%) translateX(100%)}.el-badge__content.is-fixed.is-dot{right:5px}.el-badge__content.is-dot{height:8px;width:8px;padding:0;right:0;border-radius:50%}.el-badge__content--primary,.el-badge__content--success{background-color:#42d885}.el-badge__content--warning{background-color:#f9c855}.el-badge__content--info{background-color:#909399}.el-badge__content--danger{background-color:#ff6d6d}.el-card{border-radius:4px;border:1px solid #ebeef5;background-color:#fff;overflow:hidden;color:#303133;transition:.3s}.el-card.is-always-shadow,.el-card.is-hover-shadow:focus,.el-card.is-hover-shadow:hover{box-shadow:0 2px 12px 0 rgba(0,0,0,.1)}.el-card__header{padding:18px 20px;border-bottom:1px solid #ebeef5;box-sizing:border-box}.el-card__body{padding:20px}.el-rate{height:20px;line-height:1}.el-rate:active,.el-rate:focus{outline-width:0}.el-rate__item{font-size:0;vertical-align:middle}.el-rate__icon,.el-rate__item{display:inline-block;position:relative}.el-rate__icon{font-size:18px;margin-right:6px;color:#c0c4cc;transition:.3s}.el-rate__icon.hover{transform:scale(1.15)}.el-rate__decimal,.el-rate__icon .path2{position:absolute;left:0;top:0}.el-rate__decimal{display:inline-block;overflow:hidden}.el-rate__text{font-size:14px;vertical-align:middle}.el-steps{display:-ms-flexbox;display:flex}.el-steps--simple{padding:13px 8%;border-radius:4px;background:#f5f7fa}.el-steps--horizontal{white-space:nowrap}.el-steps--vertical{height:100%;-ms-flex-flow:column;flex-flow:column}.el-step{position:relative;-ms-flex-negative:1;flex-shrink:1}.el-step:last-of-type .el-step__line{display:none}.el-step:last-of-type.is-flex{-ms-flex-preferred-size:auto!important;flex-basis:auto!important;-ms-flex-negative:0;flex-shrink:0;-ms-flex-positive:0;flex-grow:0}.el-step:last-of-type .el-step__description,.el-step:last-of-type .el-step__main{padding-right:0}.el-step__head{position:relative;width:100%}.el-step__head.is-process{color:#303133;border-color:#303133}.el-step__head.is-wait{color:#c0c4cc;border-color:#c0c4cc}.el-step__head.is-success{color:#42d885;border-color:#42d885}.el-step__head.is-error{color:#ff6d6d;border-color:#ff6d6d}.el-step__head.is-finish{color:#42d885;border-color:#42d885}.el-step__icon{position:relative;z-index:1;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;width:24px;height:24px;font-size:14px;box-sizing:border-box;background:#fff;transition:.15s ease-out}.el-step__icon.is-text{border-radius:50%;border:2px solid;border-color:inherit}.el-step__icon.is-icon{width:40px}.el-step__icon-inner{display:inline-block;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:center;font-weight:700;line-height:1;color:inherit}.el-step__icon-inner[class*=el-icon]:not(.is-status){font-size:25px;font-weight:400}.el-step__icon-inner.is-status{transform:translateY(1px)}.el-step__line{position:absolute;border-color:inherit;background-color:#c0c4cc}.el-step__line-inner{display:block;border-width:1px;border-style:solid;border-color:inherit;transition:.15s ease-out;box-sizing:border-box;width:0;height:0}.el-step__main{white-space:normal;text-align:left}.el-step__title{font-size:16px;line-height:38px}.el-step__title.is-process{font-weight:700;color:#303133}.el-step__title.is-wait{color:#c0c4cc}.el-step__title.is-success{color:#42d885}.el-step__title.is-error{color:#ff6d6d}.el-step__title.is-finish{color:#42d885}.el-step__description{padding-right:10%;margin-top:-5px;font-size:12px;line-height:20px;font-weight:400}.el-step__description.is-process{color:#303133}.el-step__description.is-wait{color:#c0c4cc}.el-step__description.is-success{color:#42d885}.el-step__description.is-error{color:#ff6d6d}.el-step__description.is-finish{color:#42d885}.el-step.is-horizontal{display:inline-block}.el-step.is-horizontal .el-step__line{height:2px;top:11px;left:0;right:0}.el-step.is-vertical{display:-ms-flexbox;display:flex}.el-step.is-vertical .el-step__head{-ms-flex-positive:0;flex-grow:0;width:24px}.el-step.is-vertical .el-step__main{padding-left:10px;-ms-flex-positive:1;flex-grow:1}.el-step.is-vertical .el-step__title{line-height:24px;padding-bottom:8px}.el-step.is-vertical .el-step__line{width:2px;top:0;bottom:0;left:11px}.el-step.is-vertical .el-step__icon.is-icon{width:24px}.el-step.is-center .el-step__head,.el-step.is-center .el-step__main{text-align:center}.el-step.is-center .el-step__description{padding-left:20%;padding-right:20%}.el-step.is-center .el-step__line{left:50%;right:-50%}.el-step.is-simple{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.el-step.is-simple .el-step__head{width:auto;font-size:0;padding-right:10px}.el-step.is-simple .el-step__icon{background:transparent;width:16px;height:16px;font-size:12px}.el-step.is-simple .el-step__icon-inner[class*=el-icon]:not(.is-status){font-size:18px}.el-step.is-simple .el-step__icon-inner.is-status{transform:scale(.8) translateY(1px)}.el-step.is-simple .el-step__main{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:stretch;align-items:stretch;-ms-flex-positive:1;flex-grow:1}.el-step.is-simple .el-step__title{font-size:16px;line-height:20px}.el-step.is-simple:not(:last-of-type) .el-step__title{max-width:50%;word-break:break-all}.el-step.is-simple .el-step__arrow{-ms-flex-positive:1;flex-grow:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.el-step.is-simple .el-step__arrow:after,.el-step.is-simple .el-step__arrow:before{content:"";display:inline-block;position:absolute;height:15px;width:1px;background:#c0c4cc}.el-step.is-simple .el-step__arrow:before{transform:rotate(-45deg) translateY(-4px);transform-origin:0 0}.el-step.is-simple .el-step__arrow:after{transform:rotate(45deg) translateY(4px);transform-origin:100% 100%}.el-step.is-simple:last-of-type .el-step__arrow{display:none}.el-carousel{position:relative}.el-carousel--horizontal{overflow-x:hidden}.el-carousel--vertical{overflow-y:hidden}.el-carousel__container{position:relative;height:300px}.el-carousel__arrow{border:none;outline:none;padding:0;margin:0;height:36px;width:36px;cursor:pointer;transition:.3s;border-radius:50%;background-color:rgba(31,45,61,.11);color:#fff;position:absolute;top:50%;z-index:10;transform:translateY(-50%);text-align:center;font-size:12px}.el-carousel__arrow--left{left:16px}.el-carousel__arrow--right{right:16px}.el-carousel__arrow:hover{background-color:rgba(31,45,61,.23)}.el-carousel__arrow i{cursor:pointer}.el-carousel__indicators{position:absolute;list-style:none;margin:0;padding:0;z-index:2}.el-carousel__indicators--horizontal{bottom:0;left:50%;transform:translateX(-50%)}.el-carousel__indicators--vertical{right:0;top:50%;transform:translateY(-50%)}.el-carousel__indicators--outside{bottom:26px;text-align:center;position:static;transform:none}.el-carousel__indicators--outside .el-carousel__indicator:hover button{opacity:.64}.el-carousel__indicators--outside button{background-color:#c0c4cc;opacity:.24}.el-carousel__indicators--labels{left:0;right:0;transform:none;text-align:center}.el-carousel__indicators--labels .el-carousel__button{height:auto;width:auto;padding:2px 18px;font-size:12px}.el-carousel__indicators--labels .el-carousel__indicator{padding:6px 4px}.el-carousel__indicator{background-color:transparent;cursor:pointer}.el-carousel__indicator:hover button{opacity:.72}.el-carousel__indicator--horizontal{display:inline-block;padding:12px 4px}.el-carousel__indicator--vertical{padding:4px 12px}.el-carousel__indicator--vertical .el-carousel__button{width:2px;height:15px}.el-carousel__indicator.is-active button{opacity:1}.el-carousel__button{display:block;opacity:.48;width:30px;height:2px;background-color:#fff;border:none;outline:none;padding:0;margin:0;cursor:pointer;transition:.3s}.carousel-arrow-left-enter,.carousel-arrow-left-leave-active{transform:translateY(-50%) translateX(-10px);opacity:0}.carousel-arrow-right-enter,.carousel-arrow-right-leave-active{transform:translateY(-50%) translateX(10px);opacity:0}.el-carousel__item{position:absolute;top:0;left:0;width:100%;height:100%;display:inline-block;overflow:hidden;z-index:0}.el-carousel__item.is-active{z-index:2}.el-carousel__item--card,.el-carousel__item.is-animating{transition:transform .4s ease-in-out}.el-carousel__item--card{width:50%}.el-carousel__item--card.is-in-stage{cursor:pointer;z-index:1}.el-carousel__item--card.is-in-stage.is-hover .el-carousel__mask,.el-carousel__item--card.is-in-stage:hover .el-carousel__mask{opacity:.12}.el-carousel__item--card.is-active{z-index:2}.el-carousel__mask{position:absolute;width:100%;height:100%;top:0;left:0;background-color:#fff;opacity:.24;transition:.2s}.fade-in-linear-enter-active,.fade-in-linear-leave-active{transition:opacity .2s linear}.fade-in-linear-enter,.fade-in-linear-leave,.fade-in-linear-leave-active{opacity:0}.el-fade-in-linear-enter-active,.el-fade-in-linear-leave-active{transition:opacity .2s linear}.el-fade-in-linear-enter,.el-fade-in-linear-leave,.el-fade-in-linear-leave-active{opacity:0}.el-fade-in-enter-active,.el-fade-in-leave-active{transition:all .3s cubic-bezier(.55,0,.1,1)}.el-fade-in-enter,.el-fade-in-leave-active{opacity:0}.el-zoom-in-center-enter-active,.el-zoom-in-center-leave-active{transition:all .3s cubic-bezier(.55,0,.1,1)}.el-zoom-in-center-enter,.el-zoom-in-center-leave-active{opacity:0;transform:scaleX(0)}.el-zoom-in-top-enter-active,.el-zoom-in-top-leave-active{opacity:1;transform:scaleY(1);transition:transform .3s cubic-bezier(.23,1,.32,1),opacity .3s cubic-bezier(.23,1,.32,1);transform-origin:center top}.el-zoom-in-top-enter,.el-zoom-in-top-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-bottom-enter-active,.el-zoom-in-bottom-leave-active{opacity:1;transform:scaleY(1);transition:transform .3s cubic-bezier(.23,1,.32,1),opacity .3s cubic-bezier(.23,1,.32,1);transform-origin:center bottom}.el-zoom-in-bottom-enter,.el-zoom-in-bottom-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-left-enter-active,.el-zoom-in-left-leave-active{opacity:1;transform:scale(1);transition:transform .3s cubic-bezier(.23,1,.32,1),opacity .3s cubic-bezier(.23,1,.32,1);transform-origin:top left}.el-zoom-in-left-enter,.el-zoom-in-left-leave-active{opacity:0;transform:scale(.45)}.collapse-transition{transition:height .3s ease-in-out,padding-top .3s ease-in-out,padding-bottom .3s ease-in-out}.horizontal-collapse-transition{transition:width .3s ease-in-out,padding-left .3s ease-in-out,padding-right .3s ease-in-out}.el-list-enter-active,.el-list-leave-active{transition:all 1s}.el-list-enter,.el-list-leave-active{opacity:0;transform:translateY(-30px)}.el-opacity-transition{transition:opacity .3s cubic-bezier(.55,0,.1,1)}.el-collapse{border-top:1px solid #ebeef5;border-bottom:1px solid #ebeef5}.el-collapse-item.is-disabled .el-collapse-item__header{color:#bbb;cursor:not-allowed}.el-collapse-item__header{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;height:48px;line-height:48px;background-color:#fff;color:#303133;cursor:pointer;border-bottom:1px solid #ebeef5;font-size:13px;font-weight:500;transition:border-bottom-color .3s;outline:none}.el-collapse-item__arrow{margin:0 8px 0 auto;transition:transform .3s;font-weight:300}.el-collapse-item__arrow.is-active{transform:rotate(90deg)}.el-collapse-item__header.focusing:focus:not(:hover){color:#42d885}.el-collapse-item__header.is-active{border-bottom-color:transparent}.el-collapse-item__wrap{will-change:height;background-color:#fff;overflow:hidden;box-sizing:border-box;border-bottom:1px solid #ebeef5}.el-collapse-item__content{padding-bottom:25px;font-size:13px;color:#303133;line-height:1.769230769230769}.el-collapse-item:last-child{margin-bottom:-1px}.el-popper .popper__arrow,.el-popper .popper__arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.el-popper .popper__arrow{border-width:6px;filter:drop-shadow(0 2px 12px rgba(0,0,0,.03))}.el-popper .popper__arrow:after{content:" ";border-width:6px}.el-popper[x-placement^=top]{margin-bottom:12px}.el-popper[x-placement^=top] .popper__arrow{bottom:-6px;left:50%;margin-right:3px;border-top-color:#ebeef5;border-bottom-width:0}.el-popper[x-placement^=top] .popper__arrow:after{bottom:1px;margin-left:-6px;border-top-color:#fff;border-bottom-width:0}.el-popper[x-placement^=bottom]{margin-top:12px}.el-popper[x-placement^=bottom] .popper__arrow{top:-6px;left:50%;margin-right:3px;border-top-width:0;border-bottom-color:#ebeef5}.el-popper[x-placement^=bottom] .popper__arrow:after{top:1px;margin-left:-6px;border-top-width:0;border-bottom-color:#fff}.el-popper[x-placement^=right]{margin-left:12px}.el-popper[x-placement^=right] .popper__arrow{top:50%;left:-6px;margin-bottom:3px;border-right-color:#ebeef5;border-left-width:0}.el-popper[x-placement^=right] .popper__arrow:after{bottom:-6px;left:1px;border-right-color:#fff;border-left-width:0}.el-popper[x-placement^=left]{margin-right:12px}.el-popper[x-placement^=left] .popper__arrow{top:50%;right:-6px;margin-bottom:3px;border-right-width:0;border-left-color:#ebeef5}.el-popper[x-placement^=left] .popper__arrow:after{right:1px;bottom:-6px;margin-left:-6px;border-right-width:0;border-left-color:#fff}.el-tag{background-color:#ecfbf3;border:1px solid #d9f7e7;display:inline-block;height:32px;padding:0 10px;line-height:30px;font-size:12px;color:#42d885;border-radius:4px;box-sizing:border-box;white-space:nowrap}.el-tag.is-hit{border-color:#42d885}.el-tag .el-tag__close{color:#42d885}.el-tag .el-tag__close:hover{color:#fff;background-color:#42d885}.el-tag.el-tag--info{background-color:#f4f4f5;border-color:#e9e9eb;color:#909399}.el-tag.el-tag--info.is-hit{border-color:#909399}.el-tag.el-tag--info .el-tag__close{color:#909399}.el-tag.el-tag--info .el-tag__close:hover{color:#fff;background-color:#909399}.el-tag.el-tag--success{background-color:#ecfbf3;border-color:#d9f7e7;color:#42d885}.el-tag.el-tag--success.is-hit{border-color:#42d885}.el-tag.el-tag--success .el-tag__close{color:#42d885}.el-tag.el-tag--success .el-tag__close:hover{color:#fff;background-color:#42d885}.el-tag.el-tag--warning{background-color:#fefaee;border-color:#fef4dd;color:#f9c855}.el-tag.el-tag--warning.is-hit{border-color:#f9c855}.el-tag.el-tag--warning .el-tag__close{color:#f9c855}.el-tag.el-tag--warning .el-tag__close:hover{color:#fff;background-color:#f9c855}.el-tag.el-tag--danger{background-color:#fff0f0;border-color:#ffe2e2;color:#ff6d6d}.el-tag.el-tag--danger.is-hit{border-color:#ff6d6d}.el-tag.el-tag--danger .el-tag__close{color:#ff6d6d}.el-tag.el-tag--danger .el-tag__close:hover{color:#fff;background-color:#ff6d6d}.el-tag .el-icon-close{border-radius:50%;text-align:center;position:relative;cursor:pointer;font-size:12px;height:16px;width:16px;line-height:16px;vertical-align:middle;top:-1px;right:-5px}.el-tag .el-icon-close:before{display:block}.el-tag--dark{background-color:#42d885;color:#fff}.el-tag--dark,.el-tag--dark.is-hit{border-color:#42d885}.el-tag--dark .el-tag__close{color:#fff}.el-tag--dark .el-tag__close:hover{color:#fff;background-color:#68e09d}.el-tag--dark.el-tag--info{background-color:#909399;border-color:#909399;color:#fff}.el-tag--dark.el-tag--info.is-hit{border-color:#909399}.el-tag--dark.el-tag--info .el-tag__close{color:#fff}.el-tag--dark.el-tag--info .el-tag__close:hover{color:#fff;background-color:#a6a9ad}.el-tag--dark.el-tag--success{background-color:#42d885;border-color:#42d885;color:#fff}.el-tag--dark.el-tag--success.is-hit{border-color:#42d885}.el-tag--dark.el-tag--success .el-tag__close{color:#fff}.el-tag--dark.el-tag--success .el-tag__close:hover{color:#fff;background-color:#68e09d}.el-tag--dark.el-tag--warning{background-color:#f9c855;border-color:#f9c855;color:#fff}.el-tag--dark.el-tag--warning.is-hit{border-color:#f9c855}.el-tag--dark.el-tag--warning .el-tag__close{color:#fff}.el-tag--dark.el-tag--warning .el-tag__close:hover{color:#fff;background-color:#fad377}.el-tag--dark.el-tag--danger{background-color:#ff6d6d;border-color:#ff6d6d;color:#fff}.el-tag--dark.el-tag--danger.is-hit{border-color:#ff6d6d}.el-tag--dark.el-tag--danger .el-tag__close{color:#fff}.el-tag--dark.el-tag--danger .el-tag__close:hover{color:#fff;background-color:#ff8a8a}.el-tag--plain{background-color:#fff;border-color:#b3efce;color:#42d885}.el-tag--plain.is-hit{border-color:#42d885}.el-tag--plain .el-tag__close{color:#42d885}.el-tag--plain .el-tag__close:hover{color:#fff;background-color:#42d885}.el-tag--plain.el-tag--info{background-color:#fff;border-color:#d3d4d6;color:#909399}.el-tag--plain.el-tag--info.is-hit{border-color:#909399}.el-tag--plain.el-tag--info .el-tag__close{color:#909399}.el-tag--plain.el-tag--info .el-tag__close:hover{color:#fff;background-color:#909399}.el-tag--plain.el-tag--success{background-color:#fff;border-color:#b3efce;color:#42d885}.el-tag--plain.el-tag--success.is-hit{border-color:#42d885}.el-tag--plain.el-tag--success .el-tag__close{color:#42d885}.el-tag--plain.el-tag--success .el-tag__close:hover{color:#fff;background-color:#42d885}.el-tag--plain.el-tag--warning{background-color:#fff;border-color:#fde9bb;color:#f9c855}.el-tag--plain.el-tag--warning.is-hit{border-color:#f9c855}.el-tag--plain.el-tag--warning .el-tag__close{color:#f9c855}.el-tag--plain.el-tag--warning .el-tag__close:hover{color:#fff;background-color:#f9c855}.el-tag--plain.el-tag--danger{background-color:#fff;border-color:#ffc5c5;color:#ff6d6d}.el-tag--plain.el-tag--danger.is-hit{border-color:#ff6d6d}.el-tag--plain.el-tag--danger .el-tag__close{color:#ff6d6d}.el-tag--plain.el-tag--danger .el-tag__close:hover{color:#fff;background-color:#ff6d6d}.el-tag--medium{height:28px;line-height:26px}.el-tag--medium .el-icon-close{transform:scale(.8)}.el-tag--small{height:24px;padding:0 8px;line-height:22px}.el-tag--small .el-icon-close{transform:scale(.8)}.el-tag--mini{height:20px;padding:0 5px;line-height:19px}.el-tag--mini .el-icon-close{margin-left:-3px;transform:scale(.7)}.el-cascader{display:inline-block;position:relative;font-size:14px;line-height:40px}.el-cascader:not(.is-disabled):hover .el-input__inner{cursor:pointer;border-color:#c0c4cc}.el-cascader .el-input{cursor:pointer}.el-cascader .el-input .el-input__inner{text-overflow:ellipsis}.el-cascader .el-input .el-input__inner:focus{border-color:#42d885}.el-cascader .el-input .el-icon-arrow-down{transition:transform .3s;font-size:14px}.el-cascader .el-input .el-icon-arrow-down.is-reverse{transform:rotate(180deg)}.el-cascader .el-input .el-icon-circle-close:hover{color:#909399}.el-cascader .el-input.is-focus .el-input__inner{border-color:#42d885}.el-cascader--medium{font-size:14px;line-height:36px}.el-cascader--small{font-size:13px;line-height:32px}.el-cascader--mini{font-size:12px;line-height:28px}.el-cascader.is-disabled .el-cascader__label{z-index:2;color:#c0c4cc}.el-cascader__dropdown{margin:5px 0;font-size:14px;background:#fff;border:1px solid #e4e7ed;border-radius:4px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1)}.el-cascader__tags{position:absolute;left:0;right:30px;top:50%;transform:translateY(-50%);display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;line-height:normal;text-align:left;box-sizing:border-box}.el-cascader__tags .el-tag{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;max-width:100%;margin:2px 0 2px 6px;text-overflow:ellipsis;background:#f0f2f5}.el-cascader__tags .el-tag:not(.is-hit){border-color:transparent}.el-cascader__tags .el-tag>span{-ms-flex:1;flex:1;overflow:hidden;text-overflow:ellipsis}.el-cascader__tags .el-tag .el-icon-close{-ms-flex:none;flex:none;background-color:#c0c4cc;color:#fff}.el-cascader__tags .el-tag .el-icon-close:hover{background-color:#909399}.el-cascader__suggestion-panel{border-radius:4px}.el-cascader__suggestion-list{max-height:204px;margin:0;padding:6px 0;font-size:14px;color:#606266;text-align:center}.el-cascader__suggestion-item{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center;height:34px;padding:0 15px;text-align:left;outline:none;cursor:pointer}.el-cascader__suggestion-item:focus,.el-cascader__suggestion-item:hover{background:#f5f7fa}.el-cascader__suggestion-item.is-checked{color:#42d885;font-weight:700}.el-cascader__suggestion-item>span{margin-right:10px}.el-cascader__empty-text{margin:10px 0;color:#c0c4cc}.el-cascader__search-input{-ms-flex:1;flex:1;height:24px;min-width:60px;margin:2px 0 2px 15px;padding:0;color:#606266;border:none;outline:none;box-sizing:border-box}.el-cascader__search-input::-webkit-input-placeholder{color:#c0c4cc}.el-cascader__search-input::-ms-input-placeholder{color:#c0c4cc}.el-cascader__search-input::placeholder{color:#c0c4cc}.el-color-predefine{display:-ms-flexbox;display:flex;font-size:12px;margin-top:8px;width:280px}.el-color-predefine__colors{display:-ms-flexbox;display:flex;-ms-flex:1;flex:1;-ms-flex-wrap:wrap;flex-wrap:wrap}.el-color-predefine__color-selector{margin:0 0 8px 8px;width:20px;height:20px;border-radius:4px;cursor:pointer}.el-color-predefine__color-selector:nth-child(10n+1){margin-left:0}.el-color-predefine__color-selector.selected{box-shadow:0 0 3px 2px #42d885}.el-color-predefine__color-selector>div{display:-ms-flexbox;display:flex;height:100%;border-radius:3px}.el-color-predefine__color-selector.is-alpha{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.el-color-hue-slider{position:relative;box-sizing:border-box;width:280px;height:12px;background-color:red;padding:0 2px}.el-color-hue-slider__bar{position:relative;background:linear-gradient(90deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red);height:100%}.el-color-hue-slider__thumb{position:absolute;cursor:pointer;box-sizing:border-box;left:0;top:0;width:4px;height:100%;border-radius:1px;background:#fff;border:1px solid #f0f0f0;box-shadow:0 0 2px rgba(0,0,0,.6);z-index:1}.el-color-hue-slider.is-vertical{width:12px;height:180px;padding:2px 0}.el-color-hue-slider.is-vertical .el-color-hue-slider__bar{background:linear-gradient(180deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red)}.el-color-hue-slider.is-vertical .el-color-hue-slider__thumb{left:0;top:0;width:100%;height:4px}.el-color-svpanel{position:relative;width:280px;height:180px}.el-color-svpanel__black,.el-color-svpanel__white{position:absolute;top:0;left:0;right:0;bottom:0}.el-color-svpanel__white{background:linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.el-color-svpanel__black{background:linear-gradient(0deg,#000,transparent)}.el-color-svpanel__cursor{position:absolute}.el-color-svpanel__cursor>div{cursor:head;width:4px;height:4px;box-shadow:0 0 0 1.5px #fff,inset 0 0 1px 1px rgba(0,0,0,.3),0 0 1px 2px rgba(0,0,0,.4);border-radius:50%;transform:translate(-2px,-2px)}.el-color-alpha-slider{position:relative;box-sizing:border-box;width:280px;height:12px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.el-color-alpha-slider__bar{position:relative;background:linear-gradient(90deg,hsla(0,0%,100%,0) 0,#fff);height:100%}.el-color-alpha-slider__thumb{position:absolute;cursor:pointer;box-sizing:border-box;left:0;top:0;width:4px;height:100%;border-radius:1px;background:#fff;border:1px solid #f0f0f0;box-shadow:0 0 2px rgba(0,0,0,.6);z-index:1}.el-color-alpha-slider.is-vertical{width:20px;height:180px}.el-color-alpha-slider.is-vertical .el-color-alpha-slider__bar{background:linear-gradient(180deg,hsla(0,0%,100%,0) 0,#fff)}.el-color-alpha-slider.is-vertical .el-color-alpha-slider__thumb{left:0;top:0;width:100%;height:4px}.el-color-dropdown{width:300px}.el-color-dropdown__main-wrapper{margin-bottom:6px}.el-color-dropdown__main-wrapper:after{content:"";display:table;clear:both}.el-color-dropdown__btns{margin-top:6px;text-align:right}.el-color-dropdown__value{float:left;line-height:26px;font-size:12px;color:#000;width:160px}.el-color-dropdown__btn{border:1px solid #dcdcdc;color:#333;line-height:24px;border-radius:2px;padding:0 20px;cursor:pointer;background-color:transparent;outline:none;font-size:12px}.el-color-dropdown__btn[disabled]{color:#ccc;cursor:not-allowed}.el-color-dropdown__btn:hover{color:#42d885;border-color:#42d885}.el-color-dropdown__link-btn{cursor:pointer;color:#42d885;text-decoration:none;padding:15px;font-size:12px}.el-color-dropdown__link-btn:hover{color:tint(#42d885,20%)}.el-color-picker{display:inline-block;position:relative;line-height:normal;height:40px}.el-color-picker.is-disabled .el-color-picker__trigger{cursor:not-allowed}.el-color-picker--medium{height:36px}.el-color-picker--medium .el-color-picker__trigger{height:36px;width:36px}.el-color-picker--medium .el-color-picker__mask{height:34px;width:34px}.el-color-picker--small{height:32px}.el-color-picker--small .el-color-picker__trigger{height:32px;width:32px}.el-color-picker--small .el-color-picker__mask{height:30px;width:30px}.el-color-picker--small .el-color-picker__empty,.el-color-picker--small .el-color-picker__icon{transform:translate3d(-50%,-50%,0) scale(.8)}.el-color-picker--mini{height:28px}.el-color-picker--mini .el-color-picker__trigger{height:28px;width:28px}.el-color-picker--mini .el-color-picker__mask{height:26px;width:26px}.el-color-picker--mini .el-color-picker__empty,.el-color-picker--mini .el-color-picker__icon{transform:translate3d(-50%,-50%,0) scale(.8)}.el-color-picker__mask{height:38px;width:38px;border-radius:4px;position:absolute;top:1px;left:1px;z-index:1;cursor:not-allowed;background-color:hsla(0,0%,100%,.7)}.el-color-picker__trigger{display:inline-block;box-sizing:border-box;height:40px;width:40px;padding:4px;border:1px solid #e6e6e6;border-radius:4px;font-size:0;position:relative;cursor:pointer}.el-color-picker__color{position:relative;display:block;box-sizing:border-box;border:1px solid #999;border-radius:2px;width:100%;height:100%;text-align:center}.el-color-picker__color.is-alpha{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)}.el-color-picker__color-inner{position:absolute;left:0;top:0;right:0;bottom:0}.el-color-picker__empty{color:#999}.el-color-picker__empty,.el-color-picker__icon{font-size:12px;position:absolute;top:50%;left:50%;transform:translate3d(-50%,-50%,0)}.el-color-picker__icon{display:inline-block;width:100%;color:#fff;text-align:center}.el-color-picker__panel{position:absolute;z-index:10;padding:6px;box-sizing:content-box;background-color:#fff;border:1px solid #ebeef5;border-radius:4px;box-shadow:0 2px 12px 0 rgba(0,0,0,.1)}.el-textarea{position:relative;display:inline-block;width:100%;vertical-align:bottom;font-size:14px}.el-textarea__inner{display:block;resize:vertical;padding:5px 15px;line-height:1.5;box-sizing:border-box;width:100%;font-size:inherit;color:#606266;background-color:#fff;background-image:none;border:1px solid #dcdfe6;border-radius:4px;transition:border-color .2s cubic-bezier(.645,.045,.355,1)}.el-textarea__inner::-webkit-input-placeholder{color:#c0c4cc}.el-textarea__inner::-ms-input-placeholder{color:#c0c4cc}.el-textarea__inner::placeholder{color:#c0c4cc}.el-textarea__inner:hover{border-color:#c0c4cc}.el-textarea__inner:focus{outline:none;border-color:#42d885}.el-textarea .el-input__count{color:#909399;background:#fff;position:absolute;font-size:12px;bottom:5px;right:10px}.el-textarea.is-disabled .el-textarea__inner{background-color:#f5f7fa;border-color:#e4e7ed;color:#c0c4cc;cursor:not-allowed}.el-textarea.is-disabled .el-textarea__inner::-webkit-input-placeholder{color:#c0c4cc}.el-textarea.is-disabled .el-textarea__inner::-ms-input-placeholder{color:#c0c4cc}.el-textarea.is-disabled .el-textarea__inner::placeholder{color:#c0c4cc}.el-textarea.is-exceed .el-textarea__inner{border-color:#ff6d6d}.el-textarea.is-exceed .el-input__count{color:#ff6d6d}.el-input{position:relative;font-size:14px;display:inline-block;width:100%}.el-input::-webkit-scrollbar{z-index:11;width:6px}.el-input::-webkit-scrollbar:horizontal{height:6px}.el-input::-webkit-scrollbar-thumb{border-radius:5px;width:6px;background:#b4bccc}.el-input::-webkit-scrollbar-corner,.el-input::-webkit-scrollbar-track{background:#fff}.el-input::-webkit-scrollbar-track-piece{background:#fff;width:6px}.el-input .el-input__clear{color:#c0c4cc;font-size:14px;cursor:pointer;transition:color .2s cubic-bezier(.645,.045,.355,1)}.el-input .el-input__clear:hover{color:#909399}.el-input .el-input__count{height:100%;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;color:#909399;font-size:12px}.el-input .el-input__count .el-input__count-inner{background:#fff;line-height:normal;display:inline-block;padding:0 5px}.el-input__inner{-webkit-appearance:none;background-color:#fff;background-image:none;border-radius:4px;border:1px solid #dcdfe6;box-sizing:border-box;color:#606266;display:inline-block;font-size:inherit;height:40px;line-height:40px;outline:none;padding:0 15px;transition:border-color .2s cubic-bezier(.645,.045,.355,1);width:100%}.el-input__inner::-webkit-input-placeholder{color:#c0c4cc}.el-input__inner::-ms-input-placeholder{color:#c0c4cc}.el-input__inner::placeholder{color:#c0c4cc}.el-input__inner:hover{border-color:#c0c4cc}.el-input__inner:focus{outline:none;border-color:#42d885}.el-input__suffix{position:absolute;height:100%;right:5px;top:0;text-align:center;color:#c0c4cc;transition:all .3s;pointer-events:none}.el-input__suffix-inner{pointer-events:all}.el-input__prefix{position:absolute;left:5px;top:0;color:#c0c4cc}.el-input__icon,.el-input__prefix{height:100%;text-align:center;transition:all .3s}.el-input__icon{width:25px;line-height:40px}.el-input__icon:after{content:"";height:100%;width:0;display:inline-block;vertical-align:middle}.el-input__validateIcon{pointer-events:none}.el-input.is-active .el-input__inner{outline:none;border-color:#42d885}.el-input.is-disabled .el-input__inner{background-color:#f5f7fa;border-color:#e4e7ed;color:#c0c4cc;cursor:not-allowed}.el-input.is-disabled .el-input__inner::-webkit-input-placeholder{color:#c0c4cc}.el-input.is-disabled .el-input__inner::-ms-input-placeholder{color:#c0c4cc}.el-input.is-disabled .el-input__inner::placeholder{color:#c0c4cc}.el-input.is-disabled .el-input__icon{cursor:not-allowed}.el-input.is-exceed .el-input__inner{border-color:#ff6d6d}.el-input.is-exceed .el-input__suffix .el-input__count{color:#ff6d6d}.el-input--suffix .el-input__inner{padding-right:30px}.el-input--prefix .el-input__inner{padding-left:30px}.el-input--medium{font-size:14px}.el-input--medium .el-input__inner{height:36px;line-height:36px}.el-input--medium .el-input__icon{line-height:36px}.el-input--small{font-size:13px}.el-input--small .el-input__inner{height:32px;line-height:32px}.el-input--small .el-input__icon{line-height:32px}.el-input--mini{font-size:12px}.el-input--mini .el-input__inner{height:28px;line-height:28px}.el-input--mini .el-input__icon{line-height:28px}.el-input-group{line-height:normal;display:inline-table;width:100%;border-collapse:separate;border-spacing:0}.el-input-group>.el-input__inner{vertical-align:middle;display:table-cell}.el-input-group__append,.el-input-group__prepend{background-color:#f5f7fa;color:#909399;vertical-align:middle;display:table-cell;position:relative;border:1px solid #dcdfe6;border-radius:4px;padding:0 20px;width:1px;white-space:nowrap}.el-input-group__append:focus,.el-input-group__prepend:focus{outline:none}.el-input-group__append .el-button,.el-input-group__append .el-select,.el-input-group__prepend .el-button,.el-input-group__prepend .el-select{display:inline-block;margin:-10px -20px}.el-input-group__append button.el-button,.el-input-group__append div.el-select .el-input__inner,.el-input-group__append div.el-select:hover .el-input__inner,.el-input-group__prepend button.el-button,.el-input-group__prepend div.el-select .el-input__inner,.el-input-group__prepend div.el-select:hover .el-input__inner{border-color:transparent;background-color:transparent;color:inherit;border-top:0;border-bottom:0}.el-input-group__append .el-button,.el-input-group__append .el-input,.el-input-group__prepend .el-button,.el-input-group__prepend .el-input{font-size:inherit}.el-input-group__prepend{border-right:0;border-top-right-radius:0;border-bottom-right-radius:0}.el-input-group__append{border-left:0}.el-input-group--prepend .el-input__inner,.el-input-group__append{border-top-left-radius:0;border-bottom-left-radius:0}.el-input-group--prepend .el-select .el-input.is-focus .el-input__inner{border-color:transparent}.el-input-group--append .el-input__inner{border-top-right-radius:0;border-bottom-right-radius:0}.el-input-group--append .el-select .el-input.is-focus .el-input__inner{border-color:transparent}.el-input__inner::-ms-clear{display:none;width:0;height:0}.el-button{display:inline-block;line-height:1;white-space:nowrap;cursor:pointer;background:#fff;border:1px solid #dcdfe6;border-color:#dcdfe6;color:#606266;-webkit-appearance:none;text-align:center;box-sizing:border-box;outline:none;margin:0;transition:.1s;font-weight:500;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;padding:12px 20px;font-size:14px;border-radius:4px}.el-button+.el-button{margin-left:10px}.el-button.is-round{padding:12px 20px}.el-button:focus,.el-button:hover{color:#42d885;border-color:#c6f3da;background-color:#ecfbf3}.el-button:active{color:#3bc278;border-color:#3bc278;outline:none}.el-button::-moz-focus-inner{border:0}.el-button [class*=el-icon-]+span{margin-left:5px}.el-button.is-plain:focus,.el-button.is-plain:hover{background:#fff;border-color:#42d885;color:#42d885}.el-button.is-plain:active{background:#fff;outline:none}.el-button.is-active,.el-button.is-plain:active{border-color:#3bc278;color:#3bc278}.el-button.is-disabled,.el-button.is-disabled:focus,.el-button.is-disabled:hover{color:#c0c4cc;cursor:not-allowed;background-image:none;background-color:#fff;border-color:#ebeef5}.el-button.is-disabled.el-button--text{background-color:transparent}.el-button.is-disabled.is-plain,.el-button.is-disabled.is-plain:focus,.el-button.is-disabled.is-plain:hover{background-color:#fff;border-color:#ebeef5;color:#c0c4cc}.el-button.is-loading{position:relative;pointer-events:none}.el-button.is-loading:before{pointer-events:none;content:"";position:absolute;left:-1px;top:-1px;right:-1px;bottom:-1px;border-radius:inherit;background-color:hsla(0,0%,100%,.35)}.el-button.is-round{border-radius:20px;padding:12px 23px}.el-button.is-circle{border-radius:50%;padding:12px}.el-button--primary{color:#fff;background-color:#42d885;border-color:#42d885}.el-button--primary:focus,.el-button--primary:hover{background:#68e09d;border-color:#68e09d;color:#fff}.el-button--primary:active{outline:none}.el-button--primary.is-active,.el-button--primary:active{background:#3bc278;border-color:#3bc278;color:#fff}.el-button--primary.is-disabled,.el-button--primary.is-disabled:active,.el-button--primary.is-disabled:focus,.el-button--primary.is-disabled:hover{color:#fff;background-color:#a1ecc2;border-color:#a1ecc2}.el-button--primary.is-plain{color:#42d885;background:#ecfbf3;border-color:#b3efce}.el-button--primary.is-plain:focus,.el-button--primary.is-plain:hover{background:#42d885;border-color:#42d885;color:#fff}.el-button--primary.is-plain:active{background:#3bc278;border-color:#3bc278;color:#fff;outline:none}.el-button--primary.is-plain.is-disabled,.el-button--primary.is-plain.is-disabled:active,.el-button--primary.is-plain.is-disabled:focus,.el-button--primary.is-plain.is-disabled:hover{color:#8ee8b6;background-color:#ecfbf3;border-color:#d9f7e7}.el-button--success{color:#fff;background-color:#42d885;border-color:#42d885}.el-button--success:focus,.el-button--success:hover{background:#68e09d;border-color:#68e09d;color:#fff}.el-button--success:active{outline:none}.el-button--success.is-active,.el-button--success:active{background:#3bc278;border-color:#3bc278;color:#fff}.el-button--success.is-disabled,.el-button--success.is-disabled:active,.el-button--success.is-disabled:focus,.el-button--success.is-disabled:hover{color:#fff;background-color:#a1ecc2;border-color:#a1ecc2}.el-button--success.is-plain{color:#42d885;background:#ecfbf3;border-color:#b3efce}.el-button--success.is-plain:focus,.el-button--success.is-plain:hover{background:#42d885;border-color:#42d885;color:#fff}.el-button--success.is-plain:active{background:#3bc278;border-color:#3bc278;color:#fff;outline:none}.el-button--success.is-plain.is-disabled,.el-button--success.is-plain.is-disabled:active,.el-button--success.is-plain.is-disabled:focus,.el-button--success.is-plain.is-disabled:hover{color:#8ee8b6;background-color:#ecfbf3;border-color:#d9f7e7}.el-button--warning{color:#fff;background-color:#f9c855;border-color:#f9c855}.el-button--warning:focus,.el-button--warning:hover{background:#fad377;border-color:#fad377;color:#fff}.el-button--warning:active{outline:none}.el-button--warning.is-active,.el-button--warning:active{background:#e0b44d;border-color:#e0b44d;color:#fff}.el-button--warning.is-disabled,.el-button--warning.is-disabled:active,.el-button--warning.is-disabled:focus,.el-button--warning.is-disabled:hover{color:#fff;background-color:#fce4aa;border-color:#fce4aa}.el-button--warning.is-plain{color:#f9c855;background:#fefaee;border-color:#fde9bb}.el-button--warning.is-plain:focus,.el-button--warning.is-plain:hover{background:#f9c855;border-color:#f9c855;color:#fff}.el-button--warning.is-plain:active{background:#e0b44d;border-color:#e0b44d;color:#fff;outline:none}.el-button--warning.is-plain.is-disabled,.el-button--warning.is-plain.is-disabled:active,.el-button--warning.is-plain.is-disabled:focus,.el-button--warning.is-plain.is-disabled:hover{color:#fbde99;background-color:#fefaee;border-color:#fef4dd}.el-button--danger{color:#fff;background-color:#ff6d6d;border-color:#ff6d6d}.el-button--danger:focus,.el-button--danger:hover{background:#ff8a8a;border-color:#ff8a8a;color:#fff}.el-button--danger:active{outline:none}.el-button--danger.is-active,.el-button--danger:active{background:#e66262;border-color:#e66262;color:#fff}.el-button--danger.is-disabled,.el-button--danger.is-disabled:active,.el-button--danger.is-disabled:focus,.el-button--danger.is-disabled:hover{color:#fff;background-color:#ffb6b6;border-color:#ffb6b6}.el-button--danger.is-plain{color:#ff6d6d;background:#fff0f0;border-color:#ffc5c5}.el-button--danger.is-plain:focus,.el-button--danger.is-plain:hover{background:#ff6d6d;border-color:#ff6d6d;color:#fff}.el-button--danger.is-plain:active{background:#e66262;border-color:#e66262;color:#fff;outline:none}.el-button--danger.is-plain.is-disabled,.el-button--danger.is-plain.is-disabled:active,.el-button--danger.is-plain.is-disabled:focus,.el-button--danger.is-plain.is-disabled:hover{color:#ffa7a7;background-color:#fff0f0;border-color:#ffe2e2}.el-button--info{color:#fff;background-color:#909399;border-color:#909399}.el-button--info:focus,.el-button--info:hover{background:#a6a9ad;border-color:#a6a9ad;color:#fff}.el-button--info:active{outline:none}.el-button--info.is-active,.el-button--info:active{background:#82848a;border-color:#82848a;color:#fff}.el-button--info.is-disabled,.el-button--info.is-disabled:active,.el-button--info.is-disabled:focus,.el-button--info.is-disabled:hover{color:#fff;background-color:#c8c9cc;border-color:#c8c9cc}.el-button--info.is-plain{color:#909399;background:#f4f4f5;border-color:#d3d4d6}.el-button--info.is-plain:focus,.el-button--info.is-plain:hover{background:#909399;border-color:#909399;color:#fff}.el-button--info.is-plain:active{background:#82848a;border-color:#82848a;color:#fff;outline:none}.el-button--info.is-plain.is-disabled,.el-button--info.is-plain.is-disabled:active,.el-button--info.is-plain.is-disabled:focus,.el-button--info.is-plain.is-disabled:hover{color:#bcbec2;background-color:#f4f4f5;border-color:#e9e9eb}.el-button--medium{padding:10px 20px;font-size:14px;border-radius:4px}.el-button--medium.is-round{padding:10px 20px}.el-button--medium.is-circle{padding:10px}.el-button--small{padding:9px 15px;font-size:12px;border-radius:3px}.el-button--small.is-round{padding:9px 15px}.el-button--small.is-circle{padding:9px}.el-button--mini{padding:7px 15px;font-size:12px;border-radius:3px}.el-button--mini.is-round{padding:7px 15px}.el-button--mini.is-circle{padding:7px}.el-button--text{border-color:transparent;color:#42d885;background:transparent;padding-left:0;padding-right:0}.el-button--text:focus,.el-button--text:hover{color:#68e09d;border-color:transparent;background-color:transparent}.el-button--text:active{color:#3bc278;background-color:transparent}.el-button--text.is-disabled,.el-button--text.is-disabled:focus,.el-button--text.is-disabled:hover,.el-button--text:active{border-color:transparent}.el-button-group{display:inline-block;vertical-align:middle}.el-button-group:after,.el-button-group:before{display:table;content:""}.el-button-group:after{clear:both}.el-button-group>.el-button{float:left;position:relative}.el-button-group>.el-button+.el-button{margin-left:0}.el-button-group>.el-button.is-disabled{z-index:1}.el-button-group>.el-button:first-child{border-top-right-radius:0;border-bottom-right-radius:0}.el-button-group>.el-button:last-child{border-top-left-radius:0;border-bottom-left-radius:0}.el-button-group>.el-button:first-child:last-child{border-top-right-radius:4px;border-bottom-right-radius:4px;border-top-left-radius:4px;border-bottom-left-radius:4px}.el-button-group>.el-button:first-child:last-child.is-round{border-radius:20px}.el-button-group>.el-button:first-child:last-child.is-circle{border-radius:50%}.el-button-group>.el-button:not(:first-child):not(:last-child){border-radius:0}.el-button-group>.el-button:not(:last-child){margin-right:-1px}.el-button-group>.el-button.is-active,.el-button-group>.el-button:active,.el-button-group>.el-button:focus,.el-button-group>.el-button:hover{z-index:1}.el-button-group>.el-dropdown>.el-button{border-top-left-radius:0;border-bottom-left-radius:0;border-left-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--primary:first-child{border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--primary:last-child{border-left-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--primary:not(:first-child):not(:last-child){border-left-color:hsla(0,0%,100%,.5);border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--success:first-child{border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--success:last-child{border-left-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--success:not(:first-child):not(:last-child){border-left-color:hsla(0,0%,100%,.5);border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--warning:first-child{border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--warning:last-child{border-left-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--warning:not(:first-child):not(:last-child){border-left-color:hsla(0,0%,100%,.5);border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--danger:first-child{border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--danger:last-child{border-left-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--danger:not(:first-child):not(:last-child){border-left-color:hsla(0,0%,100%,.5);border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--info:first-child{border-right-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--info:last-child{border-left-color:hsla(0,0%,100%,.5)}.el-button-group .el-button--info:not(:first-child):not(:last-child){border-left-color:hsla(0,0%,100%,.5);border-right-color:hsla(0,0%,100%,.5)}.el-transfer{font-size:14px}.el-transfer__buttons{display:inline-block;vertical-align:middle;padding:0 30px}.el-transfer__button{display:block;margin:0 auto;padding:10px;border-radius:50%;color:#fff;background-color:#42d885;font-size:0}.el-transfer__button.is-with-texts{border-radius:4px}.el-transfer__button.is-disabled,.el-transfer__button.is-disabled:hover{border:1px solid #dcdfe6;background-color:#f5f7fa;color:#c0c4cc}.el-transfer__button:first-child{margin-bottom:10px}.el-transfer__button:nth-child(2){margin:0}.el-transfer__button i,.el-transfer__button span{font-size:14px}.el-transfer__button [class*=el-icon-]+span{margin-left:0}.el-transfer-panel{border:1px solid #ebeef5;border-radius:4px;overflow:hidden;background:#fff;display:inline-block;vertical-align:middle;width:200px;max-height:100%;box-sizing:border-box;position:relative}.el-transfer-panel__body{height:246px}.el-transfer-panel__body.is-with-footer{padding-bottom:40px}.el-transfer-panel__list{margin:0;padding:6px 0;list-style:none;height:246px;overflow:auto;box-sizing:border-box}.el-transfer-panel__list.is-filterable{height:194px;padding-top:0}.el-transfer-panel__item{height:30px;line-height:30px;padding-left:15px;display:block}.el-transfer-panel__item+.el-transfer-panel__item{margin-left:0}.el-transfer-panel__item.el-checkbox{color:#606266}.el-transfer-panel__item:hover{color:#42d885}.el-transfer-panel__item.el-checkbox .el-checkbox__label{width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block;box-sizing:border-box;padding-left:24px;line-height:30px}.el-transfer-panel__item .el-checkbox__input{position:absolute;top:8px}.el-transfer-panel__filter{text-align:center;margin:15px;box-sizing:border-box;display:block;width:auto}.el-transfer-panel__filter .el-input__inner{height:32px;width:100%;font-size:12px;display:inline-block;box-sizing:border-box;border-radius:16px;padding-right:10px;padding-left:30px}.el-transfer-panel__filter .el-input__icon{margin-left:5px}.el-transfer-panel__filter .el-icon-circle-close{cursor:pointer}.el-transfer-panel .el-transfer-panel__header{height:40px;line-height:40px;background:#f5f7fa;margin:0;padding-left:15px;border-bottom:1px solid #ebeef5;box-sizing:border-box;color:#000}.el-transfer-panel .el-transfer-panel__header .el-checkbox{display:block;line-height:40px}.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label{font-size:16px;color:#303133;font-weight:400}.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label span{position:absolute;right:15px;color:#909399;font-size:12px;font-weight:400}.el-transfer-panel .el-transfer-panel__footer{height:40px;background:#fff;margin:0;padding:0;border-top:1px solid #ebeef5;position:absolute;bottom:0;left:0;width:100%;z-index:1}.el-transfer-panel .el-transfer-panel__footer:after{display:inline-block;content:"";height:100%;vertical-align:middle}.el-transfer-panel .el-transfer-panel__footer .el-checkbox{padding-left:20px;color:#606266}.el-transfer-panel .el-transfer-panel__empty{margin:0;height:30px;line-height:30px;padding:6px 15px 0;color:#909399;text-align:center}.el-transfer-panel .el-checkbox__label{padding-left:8px}.el-transfer-panel .el-checkbox__inner{height:14px;width:14px;border-radius:3px}.el-transfer-panel .el-checkbox__inner:after{height:6px;width:3px;left:4px}.el-container{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex:1;flex:1;-ms-flex-preferred-size:auto;flex-basis:auto;box-sizing:border-box;min-width:0}.el-container.is-vertical{-ms-flex-direction:column;flex-direction:column}.el-header{padding:0 20px}.el-aside,.el-header{box-sizing:border-box;-ms-flex-negative:0;flex-shrink:0}.el-aside,.el-main{overflow:auto}.el-main{display:block;-ms-flex:1;flex:1;-ms-flex-preferred-size:auto;flex-basis:auto;padding:20px}.el-footer,.el-main{box-sizing:border-box}.el-footer{padding:0 20px;-ms-flex-negative:0;flex-shrink:0}.el-timeline{margin:0;font-size:14px;list-style:none}.el-timeline .el-timeline-item:last-child .el-timeline-item__tail{display:none}.el-timeline-item{position:relative;padding-bottom:20px}.el-timeline-item__wrapper{position:relative;padding-left:28px;top:-3px}.el-timeline-item__tail{position:absolute;left:4px;height:100%;border-left:2px solid #e4e7ed}.el-timeline-item__icon{color:#fff;font-size:13px}.el-timeline-item__node{position:absolute;background-color:#e4e7ed;border-radius:50%;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.el-timeline-item__node--normal{left:-1px;width:12px;height:12px}.el-timeline-item__node--large{left:-2px;width:14px;height:14px}.el-timeline-item__node--primary,.el-timeline-item__node--success{background-color:#42d885}.el-timeline-item__node--warning{background-color:#f9c855}.el-timeline-item__node--danger{background-color:#ff6d6d}.el-timeline-item__node--info{background-color:#909399}.el-timeline-item__dot{position:absolute;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.el-timeline-item__content{color:#303133}.el-timeline-item__timestamp{color:#909399;line-height:1;font-size:13px}.el-timeline-item__timestamp.is-top{margin-bottom:8px;padding-top:4px}.el-timeline-item__timestamp.is-bottom{margin-top:8px}.el-link{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;vertical-align:middle;position:relative;text-decoration:none;outline:none;cursor:pointer;padding:0;font-size:14px;font-weight:500}.el-link.is-underline:hover:after{content:"";position:absolute;left:0;right:0;height:0;bottom:0;border-bottom:1px solid #42d885}.el-link.is-disabled{cursor:not-allowed}.el-link [class*=el-icon-]+span{margin-left:5px}.el-link.el-link--default{color:#606266}.el-link.el-link--default:hover{color:#42d885}.el-link.el-link--default:after{border-color:#42d885}.el-link.el-link--default.is-disabled{color:#c0c4cc}.el-link.el-link--primary{color:#42d885}.el-link.el-link--primary:hover{color:#68e09d}.el-link.el-link--primary:after{border-color:#42d885}.el-link.el-link--primary.is-disabled{color:#a1ecc2}.el-link.el-link--primary.is-underline:hover:after{border-color:#42d885}.el-link.el-link--danger{color:#ff6d6d}.el-link.el-link--danger:hover{color:#ff8a8a}.el-link.el-link--danger:after{border-color:#ff6d6d}.el-link.el-link--danger.is-disabled{color:#ffb6b6}.el-link.el-link--danger.is-underline:hover:after{border-color:#ff6d6d}.el-link.el-link--success{color:#42d885}.el-link.el-link--success:hover{color:#68e09d}.el-link.el-link--success:after{border-color:#42d885}.el-link.el-link--success.is-disabled{color:#a1ecc2}.el-link.el-link--success.is-underline:hover:after{border-color:#42d885}.el-link.el-link--warning{color:#f9c855}.el-link.el-link--warning:hover{color:#fad377}.el-link.el-link--warning:after{border-color:#f9c855}.el-link.el-link--warning.is-disabled{color:#fce4aa}.el-link.el-link--warning.is-underline:hover:after{border-color:#f9c855}.el-link.el-link--info{color:#909399}.el-link.el-link--info:hover{color:#a6a9ad}.el-link.el-link--info:after{border-color:#909399}.el-link.el-link--info.is-disabled{color:#c8c9cc}.el-link.el-link--info.is-underline:hover:after{border-color:#909399}.el-divider{background-color:#dcdfe6;position:relative}.el-divider--horizontal{display:block;height:1px;width:100%;margin:24px 0}.el-divider--vertical{display:inline-block;width:1px;height:1em;margin:0 8px;vertical-align:middle;position:relative}.el-divider__text{position:absolute;background-color:#fff;padding:0 20px;font-weight:500;color:#303133;font-size:14px}.el-divider__text.is-left{left:20px;transform:translateY(-50%)}.el-divider__text.is-center{left:50%;transform:translateX(-50%) translateY(-50%)}.el-divider__text.is-right{right:20px;transform:translateY(-50%)}.el-image__error,.el-image__inner,.el-image__placeholder{width:100%;height:100%}.el-image{position:relative;display:inline-block;overflow:hidden}.el-image__inner{vertical-align:top}.el-image__inner--center{position:relative;top:50%;left:50%;transform:translate(-50%,-50%);display:block}.el-image__error,.el-image__placeholder{background:#f5f7fa}.el-image__error{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;font-size:14px;color:#c0c4cc;vertical-align:middle}.el-image__preview{cursor:pointer}.el-image-viewer__wrapper{position:fixed;top:0;right:0;bottom:0;left:0}.el-image-viewer__btn{position:absolute;z-index:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;border-radius:50%;opacity:.8;cursor:pointer;box-sizing:border-box;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.el-image-viewer__close{top:40px;right:40px;width:40px;height:40px;font-size:40px}.el-image-viewer__canvas{width:100%;height:100%;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.el-image-viewer__actions{left:50%;bottom:30px;transform:translateX(-50%);width:282px;height:44px;padding:0 23px;background-color:#606266;border-color:#fff;border-radius:22px}.el-image-viewer__actions__inner{width:100%;height:100%;text-align:justify;cursor:default;font-size:23px;color:#fff;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:distribute;justify-content:space-around}.el-image-viewer__prev{left:40px}.el-image-viewer__next,.el-image-viewer__prev{top:50%;transform:translateY(-50%);width:44px;height:44px;font-size:24px;color:#fff;background-color:#606266;border-color:#fff}.el-image-viewer__next{right:40px;text-indent:2px}.el-image-viewer__mask{position:absolute;width:100%;height:100%;top:0;left:0;opacity:.5;background:#000}.viewer-fade-enter-active{animation:viewer-fade-in .3s}.viewer-fade-leave-active{animation:viewer-fade-out .3s}@keyframes viewer-fade-in{0%{transform:translate3d(0,-20px,0);opacity:0}to{transform:translateZ(0);opacity:1}}@keyframes viewer-fade-out{0%{transform:translateZ(0);opacity:1}to{transform:translate3d(0,-20px,0);opacity:0}}.el-calendar{background-color:#fff}.el-calendar__header{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;padding:12px 20px;border-bottom:1px solid #ebeef5}.el-calendar__title{color:#000;-ms-flex-item-align:center;align-self:center}.el-calendar__body{padding:12px 20px 35px}.el-calendar-table{table-layout:fixed;width:100%}.el-calendar-table thead th{padding:12px 0;color:#606266;font-weight:400}.el-calendar-table:not(.is-range) td.next,.el-calendar-table:not(.is-range) td.prev{color:#c0c4cc}.el-calendar-table td{border-bottom:1px solid #ebeef5;border-right:1px solid #ebeef5;vertical-align:top;transition:background-color .2s ease}.el-calendar-table td.is-selected{background-color:#f2f8fe}.el-calendar-table td.is-today{color:#42d885}.el-calendar-table tr:first-child td{border-top:1px solid #ebeef5}.el-calendar-table tr td:first-child{border-left:1px solid #ebeef5}.el-calendar-table tr.el-calendar-table__row--hide-border td{border-top:none}.el-calendar-table .el-calendar-day{box-sizing:border-box;padding:8px;height:85px}.el-calendar-table .el-calendar-day:hover{cursor:pointer;background-color:#f2f8fe}.el-backtop{position:fixed;background-color:#fff;width:40px;height:40px;border-radius:50%;color:#42d885;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;font-size:20px;box-shadow:0 0 6px rgba(0,0,0,.12);cursor:pointer;z-index:5}.el-backtop:hover{background-color:#f2f6fc}.el-page-header{display:-ms-flexbox;display:flex;line-height:24px}.el-page-header__left{display:-ms-flexbox;display:flex;cursor:pointer;margin-right:40px;position:relative}.el-page-header__left:after{content:"";position:absolute;width:1px;height:16px;right:-20px;top:50%;transform:translateY(-50%);background-color:#dcdfe6}.el-page-header__left .el-icon-back{font-size:18px;margin-right:6px;-ms-flex-item-align:center;align-self:center}.el-page-header__title{font-size:14px;font-weight:500}.el-page-header__content{font-size:18px;color:#303133}.el-checkbox{color:#606266;font-weight:500;font-size:14px;position:relative;cursor:pointer;display:inline-block;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;margin-right:30px}.el-checkbox.is-bordered{padding:9px 20px 9px 10px;border-radius:4px;border:1px solid #dcdfe6;box-sizing:border-box;line-height:normal;height:40px}.el-checkbox.is-bordered.is-checked{border-color:#42d885}.el-checkbox.is-bordered.is-disabled{border-color:#ebeef5;cursor:not-allowed}.el-checkbox.is-bordered+.el-checkbox.is-bordered{margin-left:10px}.el-checkbox.is-bordered.el-checkbox--medium{padding:7px 20px 7px 10px;border-radius:4px;height:36px}.el-checkbox.is-bordered.el-checkbox--medium .el-checkbox__label{line-height:17px;font-size:14px}.el-checkbox.is-bordered.el-checkbox--medium .el-checkbox__inner{height:14px;width:14px}.el-checkbox.is-bordered.el-checkbox--small{padding:5px 15px 5px 10px;border-radius:3px;height:32px}.el-checkbox.is-bordered.el-checkbox--small .el-checkbox__label{line-height:15px;font-size:12px}.el-checkbox.is-bordered.el-checkbox--small .el-checkbox__inner{height:12px;width:12px}.el-checkbox.is-bordered.el-checkbox--small .el-checkbox__inner:after{height:6px;width:2px}.el-checkbox.is-bordered.el-checkbox--mini{padding:3px 15px 3px 10px;border-radius:3px;height:28px}.el-checkbox.is-bordered.el-checkbox--mini .el-checkbox__label{line-height:12px;font-size:12px}.el-checkbox.is-bordered.el-checkbox--mini .el-checkbox__inner{height:12px;width:12px}.el-checkbox.is-bordered.el-checkbox--mini .el-checkbox__inner:after{height:6px;width:2px}.el-checkbox__input{white-space:nowrap;cursor:pointer;outline:none;display:inline-block;line-height:1;position:relative;vertical-align:middle}.el-checkbox__input.is-disabled .el-checkbox__inner{background-color:#edf2fc;border-color:#dcdfe6;cursor:not-allowed}.el-checkbox__input.is-disabled .el-checkbox__inner:after{cursor:not-allowed;border-color:#c0c4cc}.el-checkbox__input.is-disabled .el-checkbox__inner+.el-checkbox__label{cursor:not-allowed}.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner{background-color:#f2f6fc;border-color:#dcdfe6}.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner:after{border-color:#c0c4cc}.el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner{background-color:#f2f6fc;border-color:#dcdfe6}.el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner:before{background-color:#c0c4cc;border-color:#c0c4cc}.el-checkbox__input.is-disabled+span.el-checkbox__label{color:#c0c4cc;cursor:not-allowed}.el-checkbox__input.is-checked .el-checkbox__inner{background-color:#42d885;border-color:#42d885}.el-checkbox__input.is-checked .el-checkbox__inner:after{transform:rotate(45deg) scaleY(1)}.el-checkbox__input.is-checked+.el-checkbox__label{color:#42d885}.el-checkbox__input.is-focus .el-checkbox__inner{border-color:#42d885}.el-checkbox__input.is-indeterminate .el-checkbox__inner{background-color:#42d885;border-color:#42d885}.el-checkbox__input.is-indeterminate .el-checkbox__inner:before{content:"";position:absolute;display:block;background-color:#fff;height:2px;transform:scale(.5);left:0;right:0;top:5px}.el-checkbox__input.is-indeterminate .el-checkbox__inner:after{display:none}.el-checkbox__inner{display:inline-block;position:relative;border:1px solid #dcdfe6;border-radius:2px;box-sizing:border-box;width:14px;height:14px;background-color:#fff;z-index:1;transition:border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46)}.el-checkbox__inner:hover{border-color:#42d885}.el-checkbox__inner:after{box-sizing:content-box;content:"";border:1px solid #fff;border-left:0;border-top:0;height:7px;left:4px;position:absolute;top:1px;transform:rotate(45deg) scaleY(0);width:3px;transition:transform .15s ease-in .05s;transform-origin:center}.el-checkbox__original{opacity:0;outline:none;position:absolute;margin:0;width:0;height:0;z-index:-1}.el-checkbox__label{display:inline-block;padding-left:10px;line-height:19px;font-size:14px}.el-checkbox:last-of-type{margin-right:0}.el-checkbox-button,.el-checkbox-button__inner{position:relative;display:inline-block}.el-checkbox-button__inner{line-height:1;font-weight:500;white-space:nowrap;vertical-align:middle;cursor:pointer;background:#fff;border:1px solid #dcdfe6;border-left:0;color:#606266;-webkit-appearance:none;text-align:center;box-sizing:border-box;outline:none;margin:0;transition:all .3s cubic-bezier(.645,.045,.355,1);-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;padding:12px 20px;font-size:14px;border-radius:0}.el-checkbox-button__inner.is-round{padding:12px 20px}.el-checkbox-button__inner:hover{color:#42d885}.el-checkbox-button__inner [class*=el-icon-]{line-height:.9}.el-checkbox-button__inner [class*=el-icon-]+span{margin-left:5px}.el-checkbox-button__original{opacity:0;outline:none;position:absolute;margin:0;z-index:-1}.el-checkbox-button.is-checked .el-checkbox-button__inner{color:#fff;background-color:#42d885;border-color:#42d885;box-shadow:-1px 0 0 0 #8ee8b6}.el-checkbox-button.is-checked:first-child .el-checkbox-button__inner{border-left-color:#42d885}.el-checkbox-button.is-disabled .el-checkbox-button__inner{color:#c0c4cc;cursor:not-allowed;background-image:none;background-color:#fff;border-color:#ebeef5;box-shadow:none}.el-checkbox-button.is-disabled:first-child .el-checkbox-button__inner{border-left-color:#ebeef5}.el-checkbox-button:first-child .el-checkbox-button__inner{border-left:1px solid #dcdfe6;border-radius:4px 0 0 4px;box-shadow:none!important}.el-checkbox-button.is-focus .el-checkbox-button__inner{border-color:#42d885}.el-checkbox-button:last-child .el-checkbox-button__inner{border-radius:0 4px 4px 0}.el-checkbox-button--medium .el-checkbox-button__inner{padding:10px 20px;font-size:14px;border-radius:0}.el-checkbox-button--medium .el-checkbox-button__inner.is-round{padding:10px 20px}.el-checkbox-button--small .el-checkbox-button__inner{padding:9px 15px;font-size:12px;border-radius:0}.el-checkbox-button--small .el-checkbox-button__inner.is-round{padding:9px 15px}.el-checkbox-button--mini .el-checkbox-button__inner{padding:7px 15px;font-size:12px;border-radius:0}.el-checkbox-button--mini .el-checkbox-button__inner.is-round{padding:7px 15px}.el-checkbox-group{font-size:0}.el-radio{color:#606266;font-weight:500;line-height:1;position:relative;cursor:pointer;display:inline-block;white-space:nowrap;outline:none;font-size:14px;margin-right:30px;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none}.el-radio.is-bordered{padding:12px 20px 0 10px;border-radius:4px;border:1px solid #dcdfe6;box-sizing:border-box;height:40px}.el-radio.is-bordered.is-checked{border-color:#42d885}.el-radio.is-bordered.is-disabled{cursor:not-allowed;border-color:#ebeef5}.el-radio.is-bordered+.el-radio.is-bordered{margin-left:10px}.el-radio--medium.is-bordered{padding:10px 20px 0 10px;border-radius:4px;height:36px}.el-radio--medium.is-bordered .el-radio__label{font-size:14px}.el-radio--medium.is-bordered .el-radio__inner{height:14px;width:14px}.el-radio--small.is-bordered{padding:8px 15px 0 10px;border-radius:3px;height:32px}.el-radio--small.is-bordered .el-radio__label{font-size:12px}.el-radio--small.is-bordered .el-radio__inner{height:12px;width:12px}.el-radio--mini.is-bordered{padding:6px 15px 0 10px;border-radius:3px;height:28px}.el-radio--mini.is-bordered .el-radio__label{font-size:12px}.el-radio--mini.is-bordered .el-radio__inner{height:12px;width:12px}.el-radio:last-child{margin-right:0}.el-radio__input{white-space:nowrap;cursor:pointer;outline:none;display:inline-block;line-height:1;position:relative;vertical-align:middle}.el-radio__input.is-disabled .el-radio__inner{background-color:#f5f7fa;border-color:#e4e7ed;cursor:not-allowed}.el-radio__input.is-disabled .el-radio__inner:after{cursor:not-allowed;background-color:#f5f7fa}.el-radio__input.is-disabled .el-radio__inner+.el-radio__label{cursor:not-allowed}.el-radio__input.is-disabled.is-checked .el-radio__inner{background-color:#f5f7fa;border-color:#e4e7ed}.el-radio__input.is-disabled.is-checked .el-radio__inner:after{background-color:#c0c4cc}.el-radio__input.is-disabled+span.el-radio__label{color:#c0c4cc;cursor:not-allowed}.el-radio__input.is-checked .el-radio__inner{border-color:#42d885;background:#42d885}.el-radio__input.is-checked .el-radio__inner:after{transform:translate(-50%,-50%) scale(1)}.el-radio__input.is-checked+.el-radio__label{color:#42d885}.el-radio__input.is-focus .el-radio__inner{border-color:#42d885}.el-radio__inner{border:1px solid #dcdfe6;border-radius:100%;width:14px;height:14px;background-color:#fff;position:relative;cursor:pointer;display:inline-block;box-sizing:border-box}.el-radio__inner:hover{border-color:#42d885}.el-radio__inner:after{width:4px;height:4px;border-radius:100%;background-color:#fff;content:"";position:absolute;left:50%;top:50%;transform:translate(-50%,-50%) scale(0);transition:transform .15s ease-in}.el-radio__original{opacity:0;outline:none;position:absolute;z-index:-1;top:0;left:0;right:0;bottom:0;margin:0}.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner{box-shadow:0 0 2px 2px #42d885}.el-radio__label{font-size:14px;padding-left:10px}.el-scrollbar{overflow:hidden;position:relative}.el-scrollbar:active>.el-scrollbar__bar,.el-scrollbar:focus>.el-scrollbar__bar,.el-scrollbar:hover>.el-scrollbar__bar{opacity:1;transition:opacity .34s ease-out}.el-scrollbar__wrap{overflow:scroll;height:100%}.el-scrollbar__wrap--hidden-default::-webkit-scrollbar{width:0;height:0}.el-scrollbar__thumb{position:relative;display:block;width:0;height:0;cursor:pointer;border-radius:inherit;background-color:hsla(220,4%,58%,.3);transition:background-color .3s}.el-scrollbar__thumb:hover{background-color:hsla(220,4%,58%,.5)}.el-scrollbar__bar{position:absolute;right:2px;bottom:2px;z-index:1;border-radius:4px;opacity:0;transition:opacity .12s ease-out}.el-scrollbar__bar.is-vertical{width:6px;top:2px}.el-scrollbar__bar.is-vertical>div{width:100%}.el-scrollbar__bar.is-horizontal{height:6px;left:2px}.el-scrollbar__bar.is-horizontal>div{height:100%}.el-cascader-panel{display:-ms-flexbox;display:flex;border-radius:4px;font-size:14px}.el-cascader-panel.is-bordered{border:1px solid #e4e7ed;border-radius:4px}.el-cascader-menu{min-width:180px;box-sizing:border-box;color:#606266;border-right:1px solid #e4e7ed}.el-cascader-menu:last-child{border-right:none}.el-cascader-menu:last-child .el-cascader-node{padding-right:20px}.el-cascader-menu__wrap{height:204px}.el-cascader-menu__list{position:relative;min-height:100%;margin:0;padding:6px 0;list-style:none;box-sizing:border-box}.el-cascader-menu__hover-zone{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none}.el-cascader-menu__empty-text{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;color:#c0c4cc}.el-cascader-node{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:0 30px 0 20px;height:34px;line-height:34px;outline:none}.el-cascader-node.is-selectable.in-active-path{color:#606266}.el-cascader-node.in-active-path,.el-cascader-node.is-active,.el-cascader-node.is-selectable.in-checked-path{color:#42d885;font-weight:700}.el-cascader-node:not(.is-disabled){cursor:pointer}.el-cascader-node:not(.is-disabled):focus,.el-cascader-node:not(.is-disabled):hover{background:#f5f7fa}.el-cascader-node.is-disabled{color:#c0c4cc;cursor:not-allowed}.el-cascader-node__prefix{position:absolute;left:10px}.el-cascader-node__postfix{position:absolute;right:10px}.el-cascader-node__label{-ms-flex:1;flex:1;padding:0 10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.el-cascader-node>.el-checkbox,.el-cascader-node>.el-radio{margin-right:0}.el-cascader-node>.el-radio .el-radio__label{padding-left:0}.el-avatar{display:inline-block;box-sizing:border-box;text-align:center;overflow:hidden;color:#fff;background:#c0c4cc;width:40px;height:40px;line-height:40px;font-size:14px}.el-avatar>img{display:block;height:100%;vertical-align:middle}.el-avatar--circle{border-radius:50%}.el-avatar--square{border-radius:4px}.el-avatar--icon{font-size:18px}.el-avatar--large{width:40px;height:40px;line-height:40px}.el-avatar--medium{width:36px;height:36px;line-height:36px}.el-avatar--small{width:28px;height:28px;line-height:28px}@keyframes el-drawer-fade-in{0%{opacity:0}to{opacity:1}}@keyframes rtl-drawer-in{0%{transform:translate(100%)}to{transform:translate(0)}}@keyframes rtl-drawer-out{0%{transform:translate(0)}to{transform:translate(100%)}}@keyframes ltr-drawer-in{0%{transform:translate(-100%)}to{transform:translate(0)}}@keyframes ltr-drawer-out{0%{transform:translate(0)}to{transform:translate(-100%)}}@keyframes ttb-drawer-in{0%{transform:translateY(-100%)}to{transform:translate(0)}}@keyframes ttb-drawer-out{0%{transform:translate(0)}to{transform:translateY(-100%)}}@keyframes btt-drawer-in{0%{transform:translateY(100%)}to{transform:translate(0)}}@keyframes btt-drawer-out{0%{transform:translate(0)}to{transform:translateY(100%)}}.el-drawer{position:absolute;box-sizing:border-box;background-color:#fff;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;box-shadow:0 8px 10px -5px rgba(0,0,0,.2),0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12);overflow:hidden}.el-drawer.rtl{animation:rtl-drawer-out 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer__open .el-drawer.rtl{animation:rtl-drawer-in 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer.ltr{animation:ltr-drawer-out 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer__open .el-drawer.ltr{animation:ltr-drawer-in 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer.ttb{animation:ttb-drawer-out 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer__open .el-drawer.ttb{animation:ttb-drawer-in 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer.btt{animation:btt-drawer-out 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer__open .el-drawer.btt{animation:btt-drawer-in 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer__header{-ms-flex-align:center;align-items:center;color:#72767b;display:-ms-flexbox;display:flex;margin-bottom:32px;padding:20px;padding-bottom:0}.el-drawer__header>:first-child{-ms-flex:1;flex:1}.el-drawer__title{margin:0;-ms-flex:1;flex:1;line-height:inherit;font-size:1rem}.el-drawer__close-btn{border:none;cursor:pointer;font-size:20px;color:inherit;background-color:transparent}.el-drawer__body{-ms-flex:1;flex:1}.el-drawer__body>*{box-sizing:border-box}.el-drawer.ltr,.el-drawer.rtl{height:100%;top:0;bottom:0}.el-drawer.btt,.el-drawer.ttb{width:100%;left:0;right:0}.el-drawer.ltr{left:0}.el-drawer.rtl{right:0}.el-drawer.ttb{top:0}.el-drawer.btt{bottom:0}.el-drawer__container{position:relative;left:0;right:0;top:0;bottom:0;height:100%;width:100%}.el-drawer-fade-enter-active{animation:el-drawer-fade-in 225ms cubic-bezier(0,0,.2,1) 0ms}.el-drawer-fade-leave-active{animation:el-drawer-fade-in 225ms cubic-bezier(0,0,.2,1) 0ms reverse}.dark-themes #app,.dark-themes body,.dark-themeshtml{background-color:#161616;color:#a7a7a7}.dark-themes .h1,.dark-themes .h2,.dark-themes .h3,.dark-themes .h4,.dark-themes .h5,.dark-themes .h6,.dark-themes h1,.dark-themes h2,.dark-themes h3,.dark-themes h4,.dark-themes h5,.dark-themes h6,.dark-themes p{color:#a7a7a7;font-weight:400}.dark-themes .el-table:not(.el-table--public){color:#a7a7a7!important;border:1px solid #292929;background-color:transparent!important}.dark-themes .el-table:not(.el-table--public) .el-table__empty-block,.dark-themes .el-table:not(.el-table--public) th,.dark-themes .el-table:not(.el-table--public) tr{background-color:#1f1d1d!important}.dark-themes .el-table:not(.el-table--public) .el-table__header-wrapper,.dark-themes .el-table:not(.el-table--public) td,.dark-themes .el-table:not(.el-table--public) th.is-leaf{border-bottom:1px solid #161616}.dark-themes .el-table:not(.el-table--public) .el-table__header-wrapper .cell{color:#ddd!important}.dark-themes .el-table:not(.el-table--public) .el-table__expanded-cell{background-color:#242327}.dark-themes .el-table:not(.el-table--public) .el-table__body-wrapper .el-table__body tr.current-row>td{background-color:transparent}.dark-themes .el-table:not(.el-table--public) .el-table__body-wrapper .el-table__body tr:hover td{background-color:#393a3e!important;color:#ddd!important}.dark-themes .el-table:not(.el-table--public) .el-table__body-wrapper .el-table__body tr:last-child td{border-bottom:none}.dark-themes .el-table__body tr.hover-row.current-row>td,.dark-themes .el-table__body tr.hover-row.el-table__row--striped.current-row>td,.dark-themes .el-table__body tr.hover-row.el-table__row--striped>td,.dark-themes .el-table__body tr.hover-row>td,.dark-themes .el-table__body tr:hover>td{background-color:#393a3e!important}.dark-themes .el-table__fixed,.dark-themes .el-table__fixed-right{box-shadow:0 0 10px rgba(0,0,0,.48)}.dark-themes .el-checkbox .el-checkbox__input.is-checked+.el-checkbox__label{color:#606266}.dark-themes .el-select:not(.el-select--public) .el-input__inner{background-color:transparent!important;color:#a7a7a7}.dark-themes .el-select:not(.el-select--public) .el-input__inner:focus,.dark-themes .el-select:not(.el-select--public) .el-input__inner:hover{border-color:#737373}.dark-themes .el-select:not(.el-select--public).select-radius .el-input__inner{border-color:#37363d!important}.dark-themes .el-select:not(.el-select--public):hover .el-input__inner{border-color:#737373!important}.dark-themes .el-dialog:not(.el-dialog--private) .el-dialog__body{padding:10px 20px}.dark-themes .el-select-dropdown:not(.el-select--public){border-color:#373737;background-color:#373737;border-left:none;border-right:none}.dark-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item{color:#a7a7a7!important}.dark-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item.hover,.dark-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item.selected,.dark-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item:hover{background-color:#282828}.dark-themes .el-select-dropdown:not(.el-select--public) .popper__arrow,.dark-themes .el-select-dropdown:not(.el-select--public) .popper__arrow:after{border-bottom-color:#373737}.dark-themes .el-date-picker .el-popper[x-placement^=bottom] .popper__arrow,.dark-themes .el-date-picker .el-popper[x-placement^=bottom] .popper__arrow:after{border-bottom-color:#fff!important}.dark-themes .el-form:not(.el-form--public) .el-form-item .el-checkbox__label,.dark-themes .el-form:not(.el-form--public) .el-form-item .el-form-item__label,.dark-themes .page-title .el-form-item .el-checkbox__label,.dark-themes .page-title .el-form-item .el-form-item__label{color:#a7a7a7!important}.dark-themes .el-form:not(.el-form--public) .el-input .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-input .el-textarea__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea .el-textarea__inner,.dark-themes .page-title .el-input .el-input__inner,.dark-themes .page-title .el-input .el-textarea__inner,.dark-themes .page-title .el-textarea .el-input__inner,.dark-themes .page-title .el-textarea .el-textarea__inner{background-color:transparent!important;color:#a7a7a7!important;border-color:#37363d!important}.dark-themes .el-form:not(.el-form--public) .el-input.is-disabled .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-input.is-disabled .el-textarea__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea.is-disabled .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea.is-disabled .el-textarea__inner,.dark-themes .page-title .el-input.is-disabled .el-input__inner,.dark-themes .page-title .el-input.is-disabled .el-textarea__inner,.dark-themes .page-title .el-textarea.is-disabled .el-input__inner,.dark-themes .page-title .el-textarea.is-disabled .el-textarea__inner{background-color:#242325!important;border-color:#242325!important}.dark-themes .el-form:not(.el-form--public) .el-input.is-disabled:hover .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-input.is-disabled:hover .el-textarea__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea.is-disabled:hover .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea.is-disabled:hover .el-textarea__inner,.dark-themes .page-title .el-input.is-disabled:hover .el-input__inner,.dark-themes .page-title .el-input.is-disabled:hover .el-textarea__inner,.dark-themes .page-title .el-textarea.is-disabled:hover .el-input__inner,.dark-themes .page-title .el-textarea.is-disabled:hover .el-textarea__inner{border-color:#242325!important}.dark-themes .el-form:not(.el-form--public) .el-input.input-radius .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea.input-radius .el-input__inner,.dark-themes .page-title .el-input.input-radius .el-input__inner,.dark-themes .page-title .el-textarea.input-radius .el-input__inner{border-color:#37363d!important;border-radius:40px}.dark-themes .el-form:not(.el-form--public) .el-input:hover .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-input:hover .el-textarea__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea:hover .el-input__inner,.dark-themes .el-form:not(.el-form--public) .el-textarea:hover .el-textarea__inner,.dark-themes .page-title .el-input:hover .el-input__inner,.dark-themes .page-title .el-input:hover .el-textarea__inner,.dark-themes .page-title .el-textarea:hover .el-input__inner,.dark-themes .page-title .el-textarea:hover .el-textarea__inner{border-color:#737373!important}.dark-themes .el-form:not(.el-form--public) input::-webkit-input-placeholder,.dark-themes .el-form:not(.el-form--public) textarea::-webkit-input-placeholder,.dark-themes .page-title input::-webkit-input-placeholder,.dark-themes .page-title textarea::-webkit-input-placeholder{color:hsla(0,0%,65%,.5)!important}.dark-themes .el-form:not(.el-form--public) input:-moz-placeholder,.dark-themes .el-form:not(.el-form--public) input::-moz-placeholder,.dark-themes .el-form:not(.el-form--public) textarea:-moz-placeholder,.dark-themes .el-form:not(.el-form--public) textarea::-moz-placeholder,.dark-themes .page-title input:-moz-placeholder,.dark-themes .page-title input::-moz-placeholder,.dark-themes .page-title textarea:-moz-placeholder,.dark-themes .page-title textarea::-moz-placeholder{color:hsla(0,0%,65%,.5)!important}.dark-themes .el-form:not(.el-form--public) input:-ms-input-placeholder,.dark-themes .el-form:not(.el-form--public) textarea:-ms-input-placeholder,.dark-themes .page-title input:-ms-input-placeholder,.dark-themes .page-title textarea:-ms-input-placeholder{color:hsla(0,0%,65%,.5)!important}.dark-themes .el-form.el-form--public .el-input.is-disabled .el-input__inner,.dark-themes .el-form.el-form--public .el-input.is-disabled .el-textarea__inner,.dark-themes .el-form.el-form--public .el-input.is-disabled:hover .el-input__inner,.dark-themes .el-form.el-form--public .el-input.is-disabled:hover .el-textarea__inner{border-color:#f5f7fa!important}.dark-themes .el-loading-mask{background-color:#232429!important}.dark-themes .el-button.is-plain{color:#a7a7a7!important;background-color:transparent!important;border-color:#44444c!important}.dark-themes .el-button.is-plain.el-button--success:hover{border-color:#42d885!important;background-color:#42d885!important;color:#fff!important}.dark-themes .el-button.is-plain.el-button--warning:hover{border-color:#f9c855!important;background-color:#f9c855!important;color:#fff!important}.dark-themes .el-button.is-plain.el-button--danger:hover{border-color:#ff6d6d!important;background-color:#ff6d6d!important;color:#fff!important}.dark-themes .el-card.el-card--self{color:#a7a7a7!important;background-color:#1f1d1d!important}.dark-themes .el-card.el-card--self .el-card__header{color:#fff!important}.dark-themes .cache-btn{color:#a7a7a7!important}.dark-themes .cache-btn:hover{color:#42d885!important}.dark-themes .refresh-btn{color:#fff!important}.dark-themes .page-title,.dark-themes .refresh-btn:hover{color:#fff}.dark-themes .page-title .el-breadcrumb .el-breadcrumb__inner{color:#e8e8e8!important}.dark-themes .page-title .el-breadcrumb .el-breadcrumb__inner:hover{color:#fff!important}.dark-themes .page-title .el-breadcrumb .el-breadcrumb__item.breadcrumb-name .el-breadcrumb__inner,.dark-themes .page-title .el-breadcrumb .el-breadcrumb__item.breadcrumb-name:hover .el-breadcrumb__inner{color:#929299!important}.dark-themes .overview-view .card-box .card-title{color:#fff}.dark-themes .overview-view .card-item{background-color:#1f1d1d;border:1px solid #292929}.dark-themes .overview-view .card-item .icon{color:#227d51;border-color:#227d51;background-color:#232d2e}.dark-themes .overview-view .card-item .desc h3{color:#fff}.dark-themes .overview-view .card-item .desc p{color:#929299}.dark-themes .status:before{background-color:#a7a7a7!important}.dark-themes .status.running{color:#227d51!important}.dark-themes .status.stopped.danger:before{background-color:#f56c6c!important}.dark-themes .status.running:before{background-color:#227d51!important}.dark-themes .el-pagination .el-select .el-input .el-input__inner{border-color:#37363d}.dark-themes .el-pagination.is-background{color:#a7a7a7!important}.dark-themes .el-pagination.is-background button{background-color:transparent!important}.dark-themes .el-pagination.is-background button:hover{color:#42d885}.dark-themes .el-pagination.is-background .el-pager .number{color:#a7a7a7!important;background-color:transparent!important}.dark-themes .el-pagination.is-background .el-pager .number:hover{color:#42d885!important}.dark-themes .el-pagination.is-background .el-pager .number.active{background-color:#42d885!important;color:#fff!important}.dark-themes .rule-create .form-block--wrapper{border-bottom:1px solid #37363d}.dark-themes .rule-create .sql-tips{border:4px dashed #37363d;color:#c0c4cc}.dark-themes .rule-create .sql-tips .title{color:#fff}.dark-themes .rule-create .sql-tips p{color:#c0c4cc}.dark-themes .rule-create .code{background-color:rgba(55,54,61,.5)}.dark-themes .rule-create .code-sql__editor{border:1px solid #37363d;background-color:#2b292d}.dark-themes .rule-create .code-sql__editor .CodeMirror-gutters{background-color:#2b292d!important;border-right-color:#37363d!important}.dark-themes .rule-create .code-sql__editor .CodeMirror-scroll{background-color:#1e1c1c}.dark-themes .rule-create .code-sql__editor .CodeMirror-line{color:#606266}.dark-themes .rule-create .code-sql__editor .cm-keyword,.dark-themes .rule-create .code-sql__editor .cm-operator{color:#f92371}.dark-themes .rule-create .payload-type{background-color:#37363d80;border:1px solid #37363d;border-top:none}.dark-themes .rule-actions .action-card{background:#37363d80}.dark-themes .rule-actions .action-card .action-footer{border-top:1px solid #37363d}.dark-themes .rule-actions .action-card .filed-item .title{color:#ddd}.dark-themes .monaco-container{height:100%;border:1px solid #37363d}.dark-themes .jwt-payload-desc{background:rgba(55,54,61,.5)}.dark-themes .clients-view .card-subtitle{color:#f8f8f8}.dark-themes .custom-pagination a{border:1px solid #292929}.dark-themes .topic-qos-radio .el-radio-button__inner{background:#1b1c20;color:#9e9e9f;border:1px solid #35363b}.dark-themes .topic-qos-radio .el-radio-button__orig-radio:checked+.el-radio-button__inner{background-color:#42d885;color:#fff;box-shadow:none}.dark-themes .topic-metrics .message-card.in{background:linear-gradient(90deg,#1d1e27,#272644)}.dark-themes .topic-metrics .message-card.out{background:linear-gradient(90deg,#1c2023,#1e322d)}.dark-themes .topic-metrics .message-card.drop{background:linear-gradient(90deg,#1a1f27,#212d44)}.light-themes #app,.light-themes body,.light-themeshtml{background-color:#f6f7fb;color:#71737d}.light-themes .h1,.light-themes .h2,.light-themes .h3,.light-themes .h4,.light-themes .h5,.light-themes .h6,.light-themes h1,.light-themes h2,.light-themes h3,.light-themes h4,.light-themes h5,.light-themes h6,.light-themes p{color:#71737d;font-weight:400}.light-themes .el-table:not(.el-table--public){color:#71737d;border:1px solid #f1f1f1;background-color:transparent!important}.light-themes .el-table:not(.el-table--public) .el-table__empty-block,.light-themes .el-table:not(.el-table--public) th,.light-themes .el-table:not(.el-table--public) tr{background-color:#fff!important}.light-themes .el-table:not(.el-table--public) .el-table__header-wrapper,.light-themes .el-table:not(.el-table--public) td,.light-themes .el-table:not(.el-table--public) th.is-leaf{border-bottom:1px solid #f1f1f1}.light-themes .el-table:not(.el-table--public) .el-table__header-wrapper .cell{color:#606266!important}.light-themes .el-table:not(.el-table--public) .el-table__body-wrapper .el-table__body tr.current-row>td{background-color:transparent}.light-themes .el-table:not(.el-table--public) .el-table__body-wrapper .el-table__body tr:hover td{background-color:#f5f5f5!important;color:#71737d!important}.light-themes .el-table:not(.el-table--public) .el-table__body-wrapper .el-table__body tr:last-child td{border-bottom:none}.light-themes .el-table__body tr.hover-row.current-row>td,.light-themes .el-table__body tr.hover-row.el-table__row--striped.current-row>td,.light-themes .el-table__body tr.hover-row.el-table__row--striped>td,.light-themes .el-table__body tr.hover-row>td,.light-themes .el-table__body tr:hover>td{background-color:#f5f5f5!important}.light-themes .el-checkbox .el-checkbox__input.is-checked+.el-checkbox__label{color:#606266}.light-themes .el-select:not(.el-select--public) .el-input__inner{background-color:transparent!important;color:#71737d}.light-themes .el-select:not(.el-select--public) .el-input__inner:focus,.light-themes .el-select:not(.el-select--public) .el-input__inner:hover{border-color:#c0c4cc}.light-themes .el-dialog:not(.el-dialog--private) .el-dialog__body{padding:10px 20px}.light-themes .el-select-dropdown:not(.el-select--public){background-color:#fff}.light-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item{color:#71737d!important}.light-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item.hover,.light-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item.selected,.light-themes .el-select-dropdown:not(.el-select--public) .el-select-dropdown__item:hover{background-color:#f5f5f5}.light-themes .el-form:not(.el-form--public) .el-form-item .el-checkbox__label,.light-themes .el-form:not(.el-form--public) .el-form-item .el-form-item__label,.light-themes .page-title .el-form-item .el-checkbox__label,.light-themes .page-title .el-form-item .el-form-item__label{color:#71737d!important}.light-themes .el-form:not(.el-form--public) .el-input .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-input .el-textarea__inner,.light-themes .el-form:not(.el-form--public) .el-textarea .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-textarea .el-textarea__inner,.light-themes .page-title .el-input .el-input__inner,.light-themes .page-title .el-input .el-textarea__inner,.light-themes .page-title .el-textarea .el-input__inner,.light-themes .page-title .el-textarea .el-textarea__inner{background-color:transparent!important}.light-themes .el-form:not(.el-form--public) .el-input.is-disabled .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-input.is-disabled .el-textarea__inner,.light-themes .el-form:not(.el-form--public) .el-textarea.is-disabled .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-textarea.is-disabled .el-textarea__inner,.light-themes .page-title .el-input.is-disabled .el-input__inner,.light-themes .page-title .el-input.is-disabled .el-textarea__inner,.light-themes .page-title .el-textarea.is-disabled .el-input__inner,.light-themes .page-title .el-textarea.is-disabled .el-textarea__inner{background-color:#f5f5f5!important;border-color:#f5f5f5!important}.light-themes .el-form:not(.el-form--public) .el-input.is-disabled:hover .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-input.is-disabled:hover .el-textarea__inner,.light-themes .el-form:not(.el-form--public) .el-textarea.is-disabled:hover .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-textarea.is-disabled:hover .el-textarea__inner,.light-themes .page-title .el-input.is-disabled:hover .el-input__inner,.light-themes .page-title .el-input.is-disabled:hover .el-textarea__inner,.light-themes .page-title .el-textarea.is-disabled:hover .el-input__inner,.light-themes .page-title .el-textarea.is-disabled:hover .el-textarea__inner{border-color:#f5f5f5!important}.light-themes .el-form:not(.el-form--public) .el-input.input-radius .el-input__inner,.light-themes .el-form:not(.el-form--public) .el-textarea.input-radius .el-input__inner,.light-themes .page-title .el-input.input-radius .el-input__inner,.light-themes .page-title .el-textarea.input-radius .el-input__inner{border-radius:40px}.light-themes .el-form:not(.el-form--public) .el-input.input-radius .el-input__inner:focus,.light-themes .el-form:not(.el-form--public) .el-input.input-radius .el-input__inner:hover,.light-themes .el-form:not(.el-form--public) .el-textarea.input-radius .el-input__inner:focus,.light-themes .el-form:not(.el-form--public) .el-textarea.input-radius .el-input__inner:hover,.light-themes .page-title .el-input.input-radius .el-input__inner:focus,.light-themes .page-title .el-input.input-radius .el-input__inner:hover,.light-themes .page-title .el-textarea.input-radius .el-input__inner:focus,.light-themes .page-title .el-textarea.input-radius .el-input__inner:hover{border-color:#c0c4cc}.light-themes .el-form.el-form--public .el-input.is-disabled .el-input__inner,.light-themes .el-form.el-form--public .el-input.is-disabled .el-textarea__inner,.light-themes .el-form.el-form--public .el-input.is-disabled:hover .el-input__inner,.light-themes .el-form.el-form--public .el-input.is-disabled:hover .el-textarea__inner{border-color:#f5f7fa!important}.light-themes .el-loading-mask{background-color:#f5f5f5!important}.light-themes .el-button.is-plain{color:#71737d!important;background-color:transparent!important;border-color:#d6d9e2!important}.light-themes .el-button.is-plain.el-button--success:hover{border-color:#42d885!important;background-color:#42d885!important;color:#fff!important}.light-themes .el-button.is-plain.el-button--warning:hover{border-color:#f9c855!important;background-color:#f9c855!important;color:#fff!important}.light-themes .el-button.is-plain.el-button--danger:hover{border-color:#ff6d6d!important;background-color:#ff6d6d!important;color:#fff!important}.light-themes .el-card.el-card--self{color:#71737d!important;background-color:#fff!important}.light-themes .cache-btn,.light-themes .el-card.el-card--self .el-card__header{color:#71737d!important}.light-themes .cache-btn:hover{color:#42d885!important}.light-themes .refresh-btn{color:#71737d!important}.light-themes .refresh-btn:hover{color:#444!important}.light-themes .page-title{color:#444}.light-themes .page-title .el-breadcrumb .el-breadcrumb__inner{color:#6e6e75!important}.light-themes .page-title .el-breadcrumb .el-breadcrumb__inner:hover{color:#444!important}.light-themes .page-title .el-breadcrumb .el-breadcrumb__item.breadcrumb-name .el-breadcrumb__inner,.light-themes .page-title .el-breadcrumb .el-breadcrumb__item.breadcrumb-name:hover .el-breadcrumb__inner{color:#929299!important}.light-themes .overview-view .card-box .card-title{color:#606266}.light-themes .overview-view .card-item{background-color:#fff!important;border:1px solid #f1f1f1}.light-themes .overview-view .card-item .icon{color:#34c388;border-color:#34c388;background-color:#eaf9f3}.light-themes .overview-view .card-item .desc h3{color:#444}.light-themes .overview-view .card-item .desc p{color:#71737d}.light-themes .status:before{background-color:#a7a7a7!important}.light-themes .status.running{color:#34c388!important}.light-themes .status.stopped.danger:before{background-color:#f56c6c!important}.light-themes .status.running:before{background-color:#34c388!important}.light-themes .el-pagination .el-select .el-input .el-input__inner{border-color:#c0c4cc}.light-themes .el-pagination.is-background{color:#71737d!important}.light-themes .el-pagination.is-background button{background-color:transparent!important}.light-themes .el-pagination.is-background button:hover{color:#42d885}.light-themes .el-pagination.is-background .el-pager .number{color:#71737d!important;background-color:transparent!important}.light-themes .el-pagination.is-background .el-pager .number:hover{color:#42d885!important}.light-themes .el-pagination.is-background .el-pager .number.active{background-color:#42d885!important;color:#fff!important}.light-themes .rule-create .form-block--wrapper{border-bottom:1px solid #dcdfe6}.light-themes .rule-create .sql-tips{border:4px dashed #d8d8d8;color:#71737d}.light-themes .rule-create .sql-tips .title{color:#666}.light-themes .rule-create .sql-tips p{color:#71737d}.light-themes .rule-create .code{background-color:hsla(0,0%,87%,.8)}.light-themes .rule-create .code-sql__editor{border:1px solid #dcdfe6;background-color:hsla(0,0%,87%,.8)}.light-themes .rule-create .code-sql__editor .CodeMirror-gutters{background-color:hsla(0,0%,87%,.8)!important;border-right-color:hsla(0,0%,87%,.8)!important}.light-themes .rule-create .code-sql__editor .CodeMirror-scroll{background-color:#fff}.light-themes .rule-create .code-sql__editor .CodeMirror-line{color:#71737d}.light-themes .rule-create .code-sql__editor .cm-keyword,.light-themes .rule-create .code-sql__editor .cm-operator{color:#a11}.light-themes .rule-create .payload-type{background-color:#dfdfdfcc;border:1px solid #dcdfe6;border-top:none}.light-themes .rule-actions .action-card{background:#dfdfdfcc}.light-themes .rule-actions .action-card .action-footer{border-top:1px solid #dcdfe6}.light-themes .rule-actions .action-card .filed-item .title{color:#6e6e75}.light-themes .left-bar{box-shadow:none}.light-themes .help-view{width:80%}.light-themes .help-view .help-item h3{color:#444}.light-themes .help-view .help-item p{color:#606266}.light-themes .help-view .help-item .follow-link{background:#ececec;color:#606266}.light-themes .help-view .el-divider{background-color:#dcdfe6}.light-themes .el-tabs.normal-tabs>.el-tabs__header .el-tabs__item{background:#fff;border-bottom:1px solid #fff}.light-themes .el-tabs.normal-tabs>.el-tabs__header .el-tabs__item.is-active{background:#fff;border:1px solid #fff;border-left:2px solid;color:#34c388}.light-themes .clients-basic .clients-basic-form .form-subtitle{color:#343434;font-size:14px;margin:24px 0}.light-themes .clients-basic .clients-basic-form .el-form-item__content{color:#343434}.light-themes .custom-pagination a{border:1px solid #e6e6e6}.light-themes .monaco-container{height:100%;border:1px solid #dcdfe6}.light-themes .jwt-payload-desc{background:hsla(0,0%,87%,.8)}.light-themes .clients-view .card-subtitle{color:#6e6e75}.light-themes .topic-metrics .message-card{color:#fff}.light-themes .topic-metrics .message-card.in{background:linear-gradient(90deg,#3e3ab4,#4c5ae0)}.light-themes .topic-metrics .message-card.out{background:linear-gradient(90deg,#0c7cd1,#19bcc2)}.light-themes .topic-metrics .message-card.drop{background:linear-gradient(90deg,#00ac70,#34c388)}.el-form--label-top .el-form-item__label{padding:0}.el-table:not(.el-table--public){border-radius:4px}.el-table:not(.el-table--public).el-table--small{font-size:14px}.el-table:not(.el-table--public):before{height:0}.el-table:not(.el-table--public).el-table--border:after,.el-table:not(.el-table--public).el-table--group:after{width:0}.el-table:not(.el-table--public) td,.el-table:not(.el-table--public) th{border-right:none}.el-table:not(.el-table--public) th{border-bottom:none}.el-table__fixed-right:before,.el-table__fixed:before{display:none}.el-checkbox .el-checkbox__inner{width:18px;height:18px;border-radius:4px}.el-checkbox .el-checkbox__inner:after{border-left:0;border-top:0;height:8px;left:5px;position:absolute;top:2px;width:4px}.el-select.el-select--small .el-input__inner{height:40px!important}.el-select.select-radius{width:240px}.el-select.select-radius .el-input__inner{border-radius:40px}.el-select-dropdown{min-height:40px}.el-input.input-radius,.el-textarea.input-radius{width:240px}.el-input.input-radius .el-input__inner,.el-textarea.input-radius .el-input__inner{border-radius:40px}.el-input .el-input__suffix,.el-textarea .el-input__suffix{width:30px;font-size:16px;cursor:pointer}.el-input .el-input__suffix .el-input__suffix-inner,.el-textarea .el-input__suffix .el-input__suffix-inner{font-weight:bolder}.el-button.el-button--mini{padding:4px}.el-button.is-plain{font-weight:400!important}.el-card{border:none!important;font-size:16px;font-weight:600}.el-card .el-card__header{border-bottom:1px solid #f1f1f1}.el-card.el-card--self{font-weight:400}.el-card.el-card--self .el-card__header{border-bottom:none!important}.cache-btn{cursor:pointer;font-weight:500}.el-switch__input:focus~.el-switch__core{outline:none!important}.el-dialog .el-dialog__header{border-bottom:1px solid #f1f1f1!important}.el-loading-mask{opacity:.8}.el-tabs.normal-tabs{margin-top:24px}.el-tabs.normal-tabs>.el-tabs__header{border-bottom:0;margin-bottom:0}.el-tabs.normal-tabs>.el-tabs__header .el-tabs__nav{border:none}.el-tabs.normal-tabs>.el-tabs__header .el-tabs__item{min-width:120px;text-align:center;background:#1d1e24;border-radius:4px 4px 0 0;margin-right:8px;border:1px solid transparent;border-bottom:1px solid #1f1d1d;line-height:38px;color:#adafb4;transition:all .5s;font-size:16px}.el-tabs.normal-tabs>.el-tabs__header .el-tabs__item.is-active{background:#1f1d1d;border:1px solid #1f1d1d;border-left:2px solid;color:#34c388}.el-dropdown{cursor:pointer}.el-pagination{float:none!important}#app,body,html{height:100%;margin:0}@font-face{font-family:Roboto;font-style:normal;font-weight:300;src:local("Roboto Light"),local("Roboto-Light"),url(/static/fonts/Roboto-Light.woff) format("woff"),url(/static/fonts/Roboto-Light.ttf) format("truetype")}body{font-family:Roboto,Helvetica Neue,Helvetica,Work sans,Arial,sans-serif;-webkit-font-smoothing:subpixel-antialiased;font-size:14px;font-weight:400}body #nprogress .bar{background:#42d885}body #nprogress .peg{box-shadow:0 0 10px #42d885,0 0 5px #42d885}*{box-sizing:border-box}a{color:#42d885;text-decoration:none!important}.clear-fix{clear:both}::-ms-clear,::-ms-reveal{display:none}.page-title{font-size:24px;text-transform:capitalize;padding:30px 0 10px!important}.page-title .el-select{float:right}.page-title .el-select input{height:40px!important}.page-title .el-breadcrumb{margin-top:2px;font-size:24px}.page-title .el-breadcrumb .uppercase{text-transform:Capitalize}.operation-area{margin-top:20px}.operation-area .el-button.el-button--text{padding-right:20px}.cache-btn,.confirm-btn{min-width:80px}input{line-height:normal!important}.empty-content{width:100%;height:200px;line-height:200px;margin-top:-20px;text-align:center}.desc--text{font-size:14px;font-weight:400;line-height:1.4}.el-pagination{margin:20px 0;float:right}.el-card.thin__body .el-card__body{padding:0 20px;font-size:16px}.el-card .card-header--like{padding:18px 0;color:#6e6e75}.status:before{content:"";display:inline-block;height:8px;width:8px;margin-right:3px;border-radius:4px}.btn{cursor:pointer;color:#34c388}.a-line:hover{text-decoration:underline}.blank{max-width:500px;width:100%;margin:100px auto;text-align:center;height:200px}.blank .icon{width:80px;height:80px;margin:4px auto;border:2px solid #42d885;border-radius:50%;font-size:36px;color:#42d885;line-height:80px}.guide-doc{text-align:left}.emq-link{cursor:pointer;color:#42d885}.dialog-preview .option-item{margin:0 auto;padding:6px;min-height:32px;line-height:32px;clear:both}.dialog-preview .option-item .option-title{width:48%;float:left;color:#888}.dialog-preview .option-item .option-value{width:48%;float:left;color:#000}.dialog-preview .option-item .option-all{clear:both;width:100%}.dialog-preview .option-item .option-all .option-item{padding:6px 0}.status-circle{width:8px;height:8px;display:inline-block;border-radius:50%;margin-right:5px}.connected{color:#34c388}.connected.status-circle{background:#34c388}.disconnected{color:#ff6d6d}.disconnected.status-circle{background:#ff6d6d}.center-align{text-align:center}.data-table .cell .el-input__inner{border-color:transparent}.data-table .cell .el-input__inner:focus{border-color:#dcdfe6}.data-table .data-input{position:relative}.data-table .data-input .el-input-group__append{background-color:#fff;border:none;font-size:12px;color:#ff6d6d}.data-table .oper-icon{width:40px;height:26px;line-height:28px;visibility:hidden;cursor:pointer;text-align:center}.data-table td{padding:2px 0!important}.data-table .cell{padding:0 4px}.data-table .el-table__row.hover-row .el-icon-close{visibility:visible}.data-table .el-input__inner{border-radius:0}.data-table .el-input.is-error .el-input__inner{border-width:2px;border-color:#ff6d6d}.data-table .data-value,.data-table.disable .el-input{display:none}.data-table.disable .data-value{display:inline-block}.data-table .value-column .cell{display:-ms-flexbox;display:flex}.data-table .value-column .cell .data-input{-ms-flex:1;flex:1}.data-table th.is-leaf{font-weight:400} \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/font-awesome.min.css b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/font-awesome.min.css deleted file mode 100644 index 540440ce89..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/font-awesome.min.css +++ /dev/null @@ -1,4 +0,0 @@ -/*! - * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome - * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) - */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.7.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook-f:before,.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-feed:before,.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before,.fa-gratipay:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper-pp:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}.fa-buysellads:before{content:"\f20d"}.fa-connectdevelop:before{content:"\f20e"}.fa-dashcube:before{content:"\f210"}.fa-forumbee:before{content:"\f211"}.fa-leanpub:before{content:"\f212"}.fa-sellsy:before{content:"\f213"}.fa-shirtsinbulk:before{content:"\f214"}.fa-simplybuilt:before{content:"\f215"}.fa-skyatlas:before{content:"\f216"}.fa-cart-plus:before{content:"\f217"}.fa-cart-arrow-down:before{content:"\f218"}.fa-diamond:before{content:"\f219"}.fa-ship:before{content:"\f21a"}.fa-user-secret:before{content:"\f21b"}.fa-motorcycle:before{content:"\f21c"}.fa-street-view:before{content:"\f21d"}.fa-heartbeat:before{content:"\f21e"}.fa-venus:before{content:"\f221"}.fa-mars:before{content:"\f222"}.fa-mercury:before{content:"\f223"}.fa-intersex:before,.fa-transgender:before{content:"\f224"}.fa-transgender-alt:before{content:"\f225"}.fa-venus-double:before{content:"\f226"}.fa-mars-double:before{content:"\f227"}.fa-venus-mars:before{content:"\f228"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-v:before{content:"\f22a"}.fa-mars-stroke-h:before{content:"\f22b"}.fa-neuter:before{content:"\f22c"}.fa-genderless:before{content:"\f22d"}.fa-facebook-official:before{content:"\f230"}.fa-pinterest-p:before{content:"\f231"}.fa-whatsapp:before{content:"\f232"}.fa-server:before{content:"\f233"}.fa-user-plus:before{content:"\f234"}.fa-user-times:before{content:"\f235"}.fa-hotel:before,.fa-bed:before{content:"\f236"}.fa-viacoin:before{content:"\f237"}.fa-train:before{content:"\f238"}.fa-subway:before{content:"\f239"}.fa-medium:before{content:"\f23a"}.fa-yc:before,.fa-y-combinator:before{content:"\f23b"}.fa-optin-monster:before{content:"\f23c"}.fa-opencart:before{content:"\f23d"}.fa-expeditedssl:before{content:"\f23e"}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:"\f240"}.fa-battery-3:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-battery-2:before,.fa-battery-half:before{content:"\f242"}.fa-battery-1:before,.fa-battery-quarter:before{content:"\f243"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-mouse-pointer:before{content:"\f245"}.fa-i-cursor:before{content:"\f246"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-sticky-note:before{content:"\f249"}.fa-sticky-note-o:before{content:"\f24a"}.fa-cc-jcb:before{content:"\f24b"}.fa-cc-diners-club:before{content:"\f24c"}.fa-clone:before{content:"\f24d"}.fa-balance-scale:before{content:"\f24e"}.fa-hourglass-o:before{content:"\f250"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:"\f252"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-hourglass:before{content:"\f254"}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:"\f255"}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:"\f256"}.fa-hand-scissors-o:before{content:"\f257"}.fa-hand-lizard-o:before{content:"\f258"}.fa-hand-spock-o:before{content:"\f259"}.fa-hand-pointer-o:before{content:"\f25a"}.fa-hand-peace-o:before{content:"\f25b"}.fa-trademark:before{content:"\f25c"}.fa-registered:before{content:"\f25d"}.fa-creative-commons:before{content:"\f25e"}.fa-gg:before{content:"\f260"}.fa-gg-circle:before{content:"\f261"}.fa-tripadvisor:before{content:"\f262"}.fa-odnoklassniki:before{content:"\f263"}.fa-odnoklassniki-square:before{content:"\f264"}.fa-get-pocket:before{content:"\f265"}.fa-wikipedia-w:before{content:"\f266"}.fa-safari:before{content:"\f267"}.fa-chrome:before{content:"\f268"}.fa-firefox:before{content:"\f269"}.fa-opera:before{content:"\f26a"}.fa-internet-explorer:before{content:"\f26b"}.fa-tv:before,.fa-television:before{content:"\f26c"}.fa-contao:before{content:"\f26d"}.fa-500px:before{content:"\f26e"}.fa-amazon:before{content:"\f270"}.fa-calendar-plus-o:before{content:"\f271"}.fa-calendar-minus-o:before{content:"\f272"}.fa-calendar-times-o:before{content:"\f273"}.fa-calendar-check-o:before{content:"\f274"}.fa-industry:before{content:"\f275"}.fa-map-pin:before{content:"\f276"}.fa-map-signs:before{content:"\f277"}.fa-map-o:before{content:"\f278"}.fa-map:before{content:"\f279"}.fa-commenting:before{content:"\f27a"}.fa-commenting-o:before{content:"\f27b"}.fa-houzz:before{content:"\f27c"}.fa-vimeo:before{content:"\f27d"}.fa-black-tie:before{content:"\f27e"}.fa-fonticons:before{content:"\f280"}.fa-reddit-alien:before{content:"\f281"}.fa-edge:before{content:"\f282"}.fa-credit-card-alt:before{content:"\f283"}.fa-codiepie:before{content:"\f284"}.fa-modx:before{content:"\f285"}.fa-fort-awesome:before{content:"\f286"}.fa-usb:before{content:"\f287"}.fa-product-hunt:before{content:"\f288"}.fa-mixcloud:before{content:"\f289"}.fa-scribd:before{content:"\f28a"}.fa-pause-circle:before{content:"\f28b"}.fa-pause-circle-o:before{content:"\f28c"}.fa-stop-circle:before{content:"\f28d"}.fa-stop-circle-o:before{content:"\f28e"}.fa-shopping-bag:before{content:"\f290"}.fa-shopping-basket:before{content:"\f291"}.fa-hashtag:before{content:"\f292"}.fa-bluetooth:before{content:"\f293"}.fa-bluetooth-b:before{content:"\f294"}.fa-percent:before{content:"\f295"}.fa-gitlab:before{content:"\f296"}.fa-wpbeginner:before{content:"\f297"}.fa-wpforms:before{content:"\f298"}.fa-envira:before{content:"\f299"}.fa-universal-access:before{content:"\f29a"}.fa-wheelchair-alt:before{content:"\f29b"}.fa-question-circle-o:before{content:"\f29c"}.fa-blind:before{content:"\f29d"}.fa-audio-description:before{content:"\f29e"}.fa-volume-control-phone:before{content:"\f2a0"}.fa-braille:before{content:"\f2a1"}.fa-assistive-listening-systems:before{content:"\f2a2"}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:"\f2a4"}.fa-glide:before{content:"\f2a5"}.fa-glide-g:before{content:"\f2a6"}.fa-signing:before,.fa-sign-language:before{content:"\f2a7"}.fa-low-vision:before{content:"\f2a8"}.fa-viadeo:before{content:"\f2a9"}.fa-viadeo-square:before{content:"\f2aa"}.fa-snapchat:before{content:"\f2ab"}.fa-snapchat-ghost:before{content:"\f2ac"}.fa-snapchat-square:before{content:"\f2ad"}.fa-pied-piper:before{content:"\f2ae"}.fa-first-order:before{content:"\f2b0"}.fa-yoast:before{content:"\f2b1"}.fa-themeisle:before{content:"\f2b2"}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:"\f2b3"}.fa-fa:before,.fa-font-awesome:before{content:"\f2b4"}.fa-handshake-o:before{content:"\f2b5"}.fa-envelope-open:before{content:"\f2b6"}.fa-envelope-open-o:before{content:"\f2b7"}.fa-linode:before{content:"\f2b8"}.fa-address-book:before{content:"\f2b9"}.fa-address-book-o:before{content:"\f2ba"}.fa-vcard:before,.fa-address-card:before{content:"\f2bb"}.fa-vcard-o:before,.fa-address-card-o:before{content:"\f2bc"}.fa-user-circle:before{content:"\f2bd"}.fa-user-circle-o:before{content:"\f2be"}.fa-user-o:before{content:"\f2c0"}.fa-id-badge:before{content:"\f2c1"}.fa-drivers-license:before,.fa-id-card:before{content:"\f2c2"}.fa-drivers-license-o:before,.fa-id-card-o:before{content:"\f2c3"}.fa-quora:before{content:"\f2c4"}.fa-free-code-camp:before{content:"\f2c5"}.fa-telegram:before{content:"\f2c6"}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:"\f2c7"}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-thermometer-2:before,.fa-thermometer-half:before{content:"\f2c9"}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:"\f2ca"}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:"\f2cb"}.fa-shower:before{content:"\f2cc"}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:"\f2cd"}.fa-podcast:before{content:"\f2ce"}.fa-window-maximize:before{content:"\f2d0"}.fa-window-minimize:before{content:"\f2d1"}.fa-window-restore:before{content:"\f2d2"}.fa-times-rectangle:before,.fa-window-close:before{content:"\f2d3"}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:"\f2d4"}.fa-bandcamp:before{content:"\f2d5"}.fa-grav:before{content:"\f2d6"}.fa-etsy:before{content:"\f2d7"}.fa-imdb:before{content:"\f2d8"}.fa-ravelry:before{content:"\f2d9"}.fa-eercast:before{content:"\f2da"}.fa-microchip:before{content:"\f2db"}.fa-snowflake-o:before{content:"\f2dc"}.fa-superpowers:before{content:"\f2dd"}.fa-wpexplorer:before{content:"\f2de"}.fa-meetup:before{content:"\f2e0"}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto} diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.css b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.css deleted file mode 100644 index 3b6afc896f..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.css +++ /dev/null @@ -1,1237 +0,0 @@ -@font-face {font-family: "iconfont"; - src: url('iconfont.eot?t=1567498326614'); /* IE9 */ - src: url('iconfont.eot?t=1567498326614#iefix') format('embedded-opentype'), /* IE6-IE8 */ - url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAIAcAAsAAAABIDAAAH/IAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgClaAqD4lyC+0UBNgIkA4lIC4RmAAQgBYRtB6B1G2jpN8TbR6K4HcA7n5UfNypqUuBlZmWd5Kyg7P//Py+pjKFpgLSATHHK7j4jwcNNrbaF6ejGN2/NMUbDC/sIaZg4YmqaHd43nD0Q7+0K5u6Qz6hUCU6r6J3juhOjwEWFjxOHmFTSgZklynmL7sp+cmX4FP+HB2ISVerX/sv87JVnJL+U/xRbImP64hXbum/byvtSqdtjIQp8nJxJP/ZAhSxwnAehIycP/O/vv33uuQ/fIycySX0SmZhArP5nSpkIJRlneN5tvQ+oiPBZTlABx8ycgw+uhWOXkGNWrpWClgPLXJWoKWhD256zMpNsLCtrX0vu6uquuytbEzAIDit7Il8it5i0T1wAQIXLzV5PvhpQCiX5yc2XrF+tJBc34IvJvbuIfxFhgRW6LN06dhdRIAPb7R0J+kcP6vVP45ss+pKf4gFR7VPnNx6vFD1lZT/JkDjosD8eAJbHRcNFfb6lmu+xTgxJ0aH6RedAV7+PqWhuQBLafaQESOJiGAjylrOUhFhppjDlbTcTRAjbQFlh5w7o7Xj/OELlYdvO3mYVUg/ds537SSIhJZAAvOtomwez/ILoO/jES1hITT2VRcCxOfq8kghlGr+JJ7GMHAzxmzCoxmIxW+IH1VAvrOyAeKKO4P/qrP6X7OS9L8mKF6jbotu96q4p586yAkOevJkMwbIaq7Xa4QWCY2oD872b/WeAbs+ZSQI9p8AVt3avya6PUFjBWq46P+Q3/I4AQVbAa+t+TZLwTKZyq5IveV1VBFgx8FX1+p+Sb1L7Q3wN6XSDzzhkVIGWe9pPuflNrpNdfzMT2fWQIOtyuHnAq4FS9bkk1+RaAyoGRGry6bqczOr308T+6FZ4IMns7t4rgQQUJrrodG0rVGd29woY6vybqtViBMnxArUhVfLbpw3RoWhkX0xF43dNNT8MgD9//oAzA4AcDEAhkLIAkFoAQ8oIpD0AufaAov1AivaC3iRvlDZSm+KAIG2ClLwgKXlFhzvKUb4c8utTaK9srr13RdVcUfaHDDmVA1jWMqwVYSQRShK0KXoOmf+NjZQiRYKUDvkZc/8f2Bp3WxnlQkU9AuIRsXrvz6EyNEMQ2v9tGdmQcft/mcvn7Y7JtehtBwpIkBky/k82tD8yZ9+AtvtaD+MTAQEnYypCAoEkAlr/ODUBldpZBRr1C4sFZbm4o4Aw7y97HShPmvzm4KAsKC5OmIewt4Jytm2LYc/43g9vmhOGTCGKTsbM9c8Aw56D1hJ67QOaHEdK/D8dRzMiugPyJu1cdsfN0Jt0H7Ry9TetPE6MAZgwWj0HtWn1rf41pB4Px4aG7dZUmE0R2e+E66puCk//fbTSzlPHtGV1q5oy8VxtUl1/49btbDFz94pmWK5v/vd1tQ4teuXGCD0YkJ+fl1hu+84zXunsNZhwES7DXXgKn0s/67PJZpf/Z3GjTzD9rUyuUKrUGq2hUXEYm2SHD1o3fLP8FZQ2lu1wutweLwQjKIfL4wuEIgmGEyRFMzIQHq/PHwiGwpFoLJ5IcrzQ29c/MDg0PDIKgBCMoBhOkBTNsBwviJKiarphWrbjer4AyrgAqVZtrPMhplwqbvtxNsRO58v1dgdACEZQDCdIimZYjhdESVZUTTdMy3Zczw/CKE7SLC/Kqm7arh/GaV7WbT8ez9f78/39IRhBMZwgKZphOV4QJVlRNd0wbcf1/CCM4iTN8qKs6qbt+mGc5mXd9uO87uf9QKcmBZlcoVSpNVraOnTq0q1HLwQjPL5AKBJLpBhOkBRdB4rruQCK7u8GekyuV/pUcMKIqknpULXgY1BdKR2rG6VTdad0rh6ULtWT0rV6UbpVb0r36kPpUdmUnhWh9KocGFa5lN7VN0+fP2ijhrQ8e8dRmjQ4QjsNDZRmjW5QNBXCelkH7SUNOkg6dJQM6CSZ0FmyoItkQ1fJgW6SC90lD3pIPvSU9dArG6B3NkKfFEDfFEK/FEH/FMOAlMDAlMKglMHglMOQVMDQVMLwVMHIVMOo1MDobIIxEcHYtMC4iGF8WmFCtsLEbINJaYPJ2Q5T0g5T0wHT0gnT0wUz0g0zswNmZSfMzi6Ykx6YGwnMl16YP32wQPphweyGhTIAC2cQFokUFo0MFssQLJ5hWCJ7YMnshaWyD5bOflgmM7BsjsNyOQHL5zqskCVYMTdhpTyAlfM7rJKHsGqWYbUoYPX8CWvkGayZ57BW/oK18wLWyUtYN29g/azABnkLG+YdbJT3sHG+wyb5AZvmJ2yWX7B5lLCFALYUgq1EwdaqwjaqwbZiYTvVYXtxsIMasKN42EkC7CwMu0iEXSXBblJhdzVhD7VgT7VhL3Vgb3VhH/VgX2mwn3TYX304QAM4UEM4SAYcLBMOkQWHagSHaQyHawJHaApHagZHaQ5HawHHaAnHagXHuRqO1xZO0A5O1AFO0hFO1glO0RlO1QVO0xVO1w3O0B3O1APO0hPO1gvO0RvO1QfOkw3ni8AFcuBCuXCRvnCxfnCJ/nCpAXCZgXC5QXCFwXClIXCVoXC1YXCN4XCtEXCdkXC9PLjBKLjRaLjJGLjZWLjFOLjVeLjNBLjdRLjDJLjTZLjLFLjbNXCPa+FeU+E++XC/AnjAdfCgafCQ6fCwGfCImfCoWfCY2fC4OfCEufCkefAUMB+eBq6HZ4Ab4FngRngOWADPAwvhBWARvAgshpeAJfAysBReAZbBq8ByeA1YAa8DK+ENYBW8CayGt4A18DZwE7wDrIV3gXXwHlAI7wNF8AGwHj4ENsBHwM3wCXALfApshM+ATfA5sBm+ALbAl0AxfAVsha+BW+Eb4Db4FtgG3wG3w/fAdqjADmgAdkIjsAuagN3QDNwBAe4EgbugBdgDrUAJ/ADshR/tg5/sh5/dDb84AL86CL8phd+VwR8OwZ8Ow1/ugb/dC/+4D/51P/znCPzvKMzzAAUeJNQE2BYZbIcI2yOHHVCAHVGEnVCCnVGGXVABu6ISdkMV7I5q2AM1sCdqYS/Uwd5oEOyDhsG+aBTsh8bBDdA8uCFaBDfCuSuGEiiFGMQhAUlIQRoy0ND4f+BkcG96UPoGdWbzuuRbxu9uPOG9NXVIv0imO2hOKTf8IEUvwd/fsMKNK0oR2TROFrvRNFt0wAXNAdMeH2pM82FhcMt0IulTsVTCaPDBHHRDwiBILgynBEiwYNoRpF7pnCCh60eoeFgeyAnfsQDaCww1E8IlGlIWkrLgZfI9MFgDgJXRFbjLbXQkwDIZZcDgSLzDMkIB1LQEkzGhR4U0A1wBPcFjs3ggYV0xB0dXBC09YOn9AZTFq9/FMdMrFSzDLM9vQj3y0eBmisKA/Z7s0Qg9wYhJ1IHymA6SfMhyb8S9dtDn05aNqNasp4k8+pI1DP0Fm+ms6PPLlPw928vvjSPr8ThlfEOGTNZleYv8vmXYhpLtVSe3+8MmBC4LPR6oL7kZP/SGTFgDN8sH5h3/GwNzsZ0NI5bFJd+4oo/V9mQk9yobcqYkuWH0cK/AadfDgUxRdEpcXGKoG1dj0i4w6Vwx0bYo+/UmjMPOKchwEMapXdNQFCSBtLlJYSA1X9U7uX9ARNc+NbVt5MAPT+efKGdA/AGSbPaclLYwUFVdxwekfoiTXgGJ5btPk8NzXALIZDNkRTt2LQxgCgvmBODIsP44c8VCwT4B3eWkKKNWMZNX6UHZlMykJRuI1VJ8IekkgawxtPtQ7xtr+nQxcnLy+5btCYyy9BexB23LaxG2iwe+6faBIDZxr73X8YzT3vtrVQY23Gei3rP08kw2T1jG6HWpF4t2ax6G25R7zEqpGTG1y1oC1bhkKIGhiZQUOEnP4mnUNCZnVk3JsdiStie7jDnctdm8y6GxbjZ5HptM5ot5y0IUOK9/FH1SvBgVtxpCiGeU361qtNd4ORdPjXkkYkDoDihCoWQa7kkjawn96XB48lqcROC2NHWqAEGBau9uSG+d+4y/DUUAW/AkVPm2v8X6rNeWL+S2iMoXiRMPJHX95j5rXwO9y96EpzzpaJv8452EAP6UCStieQlHSq3BGRROiCgpY8nzrzRIZTRUjC8m37I1UlhXeDSzMxDa6lYPH4IZY0B/Ovho7eIxBcvErz7SWqZ1QpUJ0ISEzsXw0mc9T5I1V/ao9kKHvE7eMXHhcokSucM0OMODNy1AsC1ZYgZG9V2M23tznTcDVUccQ22jHi9pCvzImtlw1SYpQ1rkSTU1lX3v3a2Gi8+ztlAt4HfUSBYM+cfV2JZkLyShgFItacFqUFpgCeBsIZGwztl3VRy5FsSRqyZaCK5RUnJjjx07+/xYljWhDjnXZhh9juigst+g0HqBzDavkrUo8kVcYI8wDgpd5OAyu6bR4owgocDrL0ME9KAhaSiDTH3dQZPNthjSZnK607S/dL92vsnB20NvCmmRfwSdyAtsP72XzaA/aQOXa3HDdHOzEj42Hy8227xfU/7BxadcSATKSHl/6v+0yLbjkOlZsPgs6KHrI/YhrpgLlAwvEvjX4cktxcfT7ui4puxuMnUlHE2KbVidGon1aLmwh05fhLVBuOlQnpz4xNcMd2sneglEr04MNAlUs/Fgs50qASwrKHCPRBUMZPUK2MFZqLDvVjt3++qQE44kFYnZrqal24VtcTGW6ehGrlcu7KMq5SpimstZaQ86Sk5JGWFL6zbHV+qy7MoB08QuvAvLVxSrCaW9JIDJPFARVcsK8KIgVzjgTpT1RkmzwCTX8qgcZSpOKa3lAFOZ6ZfC7SghmMcuRapZxojIn1WmEpkXMA8C3iA1WEdlmNKXlEpfZCrC2Hqhs41EhAh5ngcKMpSWyJro3aF/CBegQWst4VWeumZ/hmmovA0Q5FKWIiyKgtaKwfFSCp9oRrysVKY3aDySWFDIBgTADtSrKgEO7oBu3zKRGoz15rkY8wKCUpZcVRbQ53hnjgMRUBCGWJYP9UUAdlG7sNf55bWqzJsHtgE6aHrfqBakwSZ4mGBpWp/WjjEx04iHVOEBCUi2SVDRYkWbQHFRKnNqblZIVIxbNeXAq0p5IphJ1AxD4oI5TaEruVDhzXAx1IZKfCd/OEFV7a9rogx4xCHWCdDIH7ChH3R3HKXl6v2w2PuqF/Zr/Q7LmstATT5Owy0xDD5RcyvFUOsSUsdaB8DFVdzLrZqIkc4u9S9G7zjBEr266vxIDgVN+9/kRjW2RPpcWLFSeozQMhOUEm8nUGfYvRb61LZMtDpC+FDLbOEJJ8RJ72xeGuKWVtEU4Ojj9hx2VZDWngVia6NQlpESluR5UhnPhQ2Z491bkGp4UyBzkL/ptcIAe/M4Utow/GClMCK+ArQiUMfAsaXk4n1caW0XpKoXNAjNtVb0ymrNx5Eq76r2/xLkmXrbcblo/0FgkzqXfQ095NDWb24De00Y/1O/dZcP6yjsojAE4X6e8jADD04Qy3eSRSFba3rtRrsjjIAHPcPdEA1+hJVBMWih3uYaiO12JrolDsYM9UmwNtDB0GCHejoQCtJ6d3stOGrwRjtIB6B7b3TyoOfwzrb1+F4u+kpeBBB/4iSB3nQ2KPU7ZZgpMtcpK3Q5bfQIVL2DQeUBpaisXO1VHR90SWDdIFz1rHtGx8fQ4xSaCiiXQ06IjrhBN7ang5o+J1kdxX32+PsdXY66vjiB6N+KYg88H0O9NSpOfWka5lG54WyMuDQXXUtfXqzR8kRB14SPdE5EmEuAkwpyrBkAzLLTOvRGO2NELoeH/H22IJcyZuofRB8TWpRGXEL6nraStXJQlOAqwcoFWEWvcKxQDWMsYVpvH/4DtsG9dNv6h6AUIppjxU0HNQgKWCO77tMe1Xn3kMjdS06UTTPCAVw2jyBksAvfs0c9sK9KYnVlRi3volkTbnfUlpljFt5gnLzQYoqT6/52ksw4+mbdrqOt4Pr2VPDyEuzyZ0SvytRdF4SVJ2yRFBYVmxCwYC5Sn22pzGuwHdGUJnCZnLgpzaRPSrem3Z/7RMUv2DrdACLcR0CiYCSQVnCa2mCxu4u+ZUei09FlTjyZdgGB05VIpOJKiccsOVQZ/uDbnU3bIma4OSrCbZ3bzWBvL3iMyW2Ki1xQbboudg2+pIKHEUVxU2TiKWGgBHBDkyVpMNCa1Pw7AhDD6x4r9FmevHQMwF1co1R2wSrRjpJT+odn1A9wX0vS2w5yNEObB3rq3pGa3HIkqZi9igwCxYWhNvgdSG4dxwJdCD+0ADlOINOsoHQyL7gyeLhyF1kfA72ycOsNYRRnMKk2dBtSerwIPxL51+1qZYOd+X7NbUcm/vP1+reONHwa7G+10n9e03/92/z/xz08ifET7TCc8P9Ae+iI3dojs49xcBQOa7T/5qKOkQ+83Ctv3z08JkoG4a2X7LGQca/PPzrM3CUQ8OC9ChDRfXSLzGlQeB0j9JGBEKevbx86pcEMKLBtpeOySA/wQxH77G2Ai/ffBTAFuxpwcXp1aG9fvkAGM7UY5gJnVLO/ExzWr/Jdsem3VhAxPis9gUctbVWxPlNQ1RmQX2g1dT7/NKMW5p9xlM+YKXJeHFIvpkYAY2JuguC+FVd6VYHBen5GBhO92ehn8n0q5QKJMlOQza1ctknKNF1W1hb5S/IcF6nNW0swOMHDglWKkAgXM5YlV/Gbm2WkzK0VnK8ndzip+o625HmR9doL89XU0b2blgMnO2pB5b0mt9Azgw7cUMyDmm/WAPNMq84yPWNTwzxXbzDSSfk6lfFGm8yJ6GGLUvn1luD0FLNigsli2TbcMZjK1jZgg0gqKRPtJmJfdfKKGqM904qxHOwr3kRuyoSS+7FHKu79dFY6BwJwfvZpQBCdgphzKlRfTpolGQABSxfRHSpFLOqQRzpJzZRHRXXXUS/E7OMgBQqJkAiye0ich5gUTvgtIt+BlJ/mNqpGsrVr7tOs/GoUe4a0jWeeUf2NnfnAyQr3FPamZIMNyKxohny3pnMXR6OjptJtjM3A/zakyv7+cE8E4C8H3ubfbu/+9UzGBfQK/hqtFFV+suWS8qencLFtayakfaRPcFBGQSwuHO0QXWVVT7xGiadCiI+1iUUo+InGj99u/kyV2GxQfaxe0VbxYDEy8cga1nXSqd6QOlkzF6e0yMXIxNQyz0eC3PpctwAF0V9/HN92ceA2+hy5anHtVVgjV+/edDWeYbcfO3U7QfbOK8N3krX02pUN1zKQX7Nn8zVsFt9x/PQdFDNkDu1jBC+tIhqubySYHt2JYX54P6ZseTUFtrWFMnLiUft4e23+3URcGFpklXOD1mcEZJODxoEGQYPOAKqPD07tQzG7E+gLwF/N0TAFI2kbfHlanfS+T0qZZnE+09E9FCDmkZ4gg0Ccf9/2UB0Z1uMMcVoMpOmY05I7tGccUF9MLrDTQz0JgJw5psslGBoQwnGCVJLhNAIy0hTBQb92lR5UAYqmTn7w2J0wJGvSQuZQBQFasAqiahf7WVdDGNpYgjHEbBRFNBAKekJp/DEQYAphSQp1k1RHM5GlRG0LukjBUlpMMhcJTuEMlogL4WPwimYaUE3fKHyQ25qKthjTg+3tVZMjFiyPDJgfUWAcfDRY7Y4UX96gM8kR4jwCU5ySCVuxpCxzsImS59g4KCdXz0qAWtVnKJKNBn1Pjd02tsf5/FEea7bZhVsJE4lJNpmya5OsxxjkoyIXXsejQZNtVImckimYIDJJQ6kBlD3g04KYSzB6s6V2UBxrOXsJB6RKKWliif4mgqWlscbDTRnhEPnAGA1+aNhfvY4wjzcd/HrI+Xqc+JNpemFWYWdd1CFkrzyMR8AdiX7EbX/c5mugJZrohDCVD2qQ4HVHU8x/MZVREmUBA0ssUEpcZQXKFtvklAGJSheleW7JiQBahGxOpdeLAHyld5VkmDUk/Rs1pvJUdgwe1QmS+tVsfBcypYx4EZRgTGbCW73fax6GWoIgGmxEUxzXJtCzfYFiSrbBrGSaFgAdATpL15dJG7TaEU7ITbZdP2iXY+9b2Qt1KGq2+cYjyN7Lt/U7IraxshxeJDZkqfZBpeVnOinAc4JWIQkr3SdCxExJhEqF0e5bk6MIb1Gew+2bOsKQrijoBFidlEsmK5I3dN2hbkN6hBnGtD3vtUhUsfkQZPACf++msZvMXAn7HnpiocgLArTfcL8ey8fO9bOpZJ7t5Yk+lcyqZkJJEHAv0oAE8eFNhaFkvoxpt5IgavS7DgvG7KiUteoECwS4SKpRgGZos9K2AhGMO3XIOaY6DkapV10ENMZJDU56ai4qz37gkfLxw/eoaOhqLmpv2KO8wBUMrBwYOCkt9rVfSGx+96AZ6zgbC9X3KHYCvNVm1bygRqoo6p8AKmVqUlfhEsw+K/M/gH3h3wB94nO55o05lY4HXyTn1lhjzHNXptBoIZGa7wJaVH6bIDvtx8ivlEYLj2PoFMHLhx3+lulyiFMrK7+7azG7sXv+2+fXP5U/s4edEYdkbA0eEwMIJGf+QSwZuCgeZSVYwdbUclCxWSFS50w6QXRDuSieWeLJFPKdjATqy02o3o+dN0COQxRFYizBiU4bNukMGYjI1EDS7HvU0eERNoEZBXomaESI4Q7XgQWL1UAkp60Ib8VbuAKbCIgL+PlUuTvYQpvjwgMza1YRKBhGN6W4TyujopsQEooMIZmEXGYOsUN6GNuzmqvgRtnPaApVNjnE/lctNXQt79teUhEx/5D+kdCgcVi+lT3LL4Zr3hXSUZv87gAxsmefPikjDDb9Dabt+lwN64x5SI08QljiSKv0wAaM1BFqZxTAlmVcCx3G9JaZEIqlh/m68lhVGEaKPjCmt94LoVszbTRxFsu/aCK18lILJs6fw1Q8PASlqPC889PzFan4BX0EB63sErygqTPMMESZgTyVnnCU/ppVUOpMlmXYwqZ5llw3h7M4Q0wkpjlBroOqmLR7QbjymDTQLojNT+hwW5arBfA01EDgDch7sSgzWE1ld9Xlscpx+ZnTN3j5pU6mtfdkxzENGb92m9BztMPkxiAgc5jp8MqyeeI2NFn2dhFd3bkmrYMAr23RP3V1fuG73nfv3WvvuXf2rnueu/uu/L2/qE7ciQZBIeEoTpSdYl/bEHd0ljqgKWQCxSgq6GNLArKb/gxZCpFAMgWUEcQEV1y2EdA00Aan12evBVF0NTNnRaq34QRqImsY1P4UtYyzSUa3hntXavA2N1piRbT83jsLeR4jYZWgC1I7bREEwp4BsgWrZb8mQe05yRrbpTDznQbZhaDhWih4xRECg/155LWmiatlpqx2xDB4qr5ZuVtMzn2kayqTrKFoqtOU11Qayw3L8sBZkAESgXCB8Y/XmfakJJzDQeYW63dKV5JpGZcmYwWFC50fPnpBR2WUkyvFtqLzxh4JAosotwrV4BEzPYOBFYjqugYAsqfM/RpuBzrG+A+wwZ3/i2lA5eO6FwVTl8WMwT5I6fyHevqm+Bc8q5HTSYDOk9HaqrUG5Xi2qkXoBiGODDFZUs52RV+Riplzo4lT0jAH5BthTPk8VG/hjKaZEPAOdkhvgkuErqKiDwRiRethFqbnBySDszTlhTJYpmgZood8Cj43coVBhOj6ba5b0HvqP28mM4eTw8VkzS7dPX1Mrvbe+8GMcIJ0i+/v+Trupv8fGdlrZvJ4G7UYPUemjxMZKABlvUSyp4nVvnI9igK8WZ/GJfqnGq6UmV/rSD1ylmnGvtn9L25GGdrCcK96ADkaPOMNLvuX2bCQq+uDqlGNQGBCPv0e3k+7vLlOOvJm0vsPn3Qwx8mtcx6yh7/BD2uwlsI2lT1uxr3mjnDa1iXgCA8LoubBvchQDQUmHHqR6WzQwKfhNjIwxTJCyfXAQs2IlhXN2UH1OhrGpP/c1F4OI7meS4iJFmF9XBM/3GVkwtBgoPNNwFl8bIsXdE8J0N50lnbIQR9FcRZW4lmjTUt6kdvf5NgDDo4PvCGIE5No0LO0bgbw8AME8Zjfvfk3Z4/H3Rex1XXCCmDdQ5xg4RvVIBNw1r4Y+BILPozJ7DS0fffgioUqO7DcqOydGVf2FFS2aSUHtGXJ4w83tdJevhNsvd4mwZVWrfrMqXgp1J3S3raFfCI9RbwONlU5VxH7m1/UVXFxFFyFFSVUgWrFFlWHl3n0R068VfZ1blWRVwxsUzbyV/RWebi62h1tA3YSem2pzLVsmnBApiHIS831yfpq8g3yXNGrOnve4Lxuz22tgfZwgC2Rg23LlX5nj18NWQoqv2oK6LhNHgLvIvPm/tSUnm6ogc5x3wl4SVfiFkv4qFYi4ZAvalat8T8Br/9Bm0J4MMbGwcP4j8bq6AD3E10VL7Xq3/ziuv3a0VKYRly7/eOIVuz1/tXoGAcvxRwHlVEjHHFg2Xt9Vv4Ofz1U30bAKfiTIOuwGB1957XjUAlcfTs7FfgTluwMT34vcoRNe8PnY08JUD1aa34WLo30JC24PHATb7TECZ6hN803OAgx3cX6wcZjfISEXumN5utbSXild3pPjfPNRyf2lLCQQlw05W+OXM5EhhmlPJiB9ptjpsyVQSjbUQMfaHALzanPgdQ5x/CAgq2NcEMQ5EsW3iUoW9Ks3cPrgJTbPS58YO8yJ1V2md2yS5bkFl8NKMmhaaSJUfYOiDdR6RtwIIpzwBEYzeg3ZkSwhyL1TDAdIi1PJTSOugL+TbgwEzcRjBEOMevfdyexZFZxIdZRGQVY9n7ybmD+7Mf4WOyR9+BZFkxMeZM2AE28o9j5cMQQeNvfH2ZAAYZ+YfBxHA0ISvH8WoNwJ/FkJ4LtwDiTBNbokRVFV4Bz4xs7BrSY1v00TU5ZJ6AFYpwveqUrDP14bXoDKatBTqXe4lSX1rsqmpeyvgdtT696BuIu8NjObloFtvh3KVMZg7eC+LVMGZBFEOawhRAqmbALtofgqoX0UA6bpg7Q1x05foBId2vRHjQeg7XZDy++f/XT90eouqAu/QGWibvkb5njEjoRM4Rh+5AIIrtZ+inbTriBnU4z2LpUutsrd26HiUXRqql40azWQW28t6vRDiyjvb3xbO8dFRmHvEEjAeIk3BQjtgd+rqlaRq2dPikFbVMq8FqELK1A58F5SUsvgIgXQme5gKtBPdv15PuBxPxATxVG9vxCITOXZHGUY3coGAfeVWIv2gv/pVmLvCidklAr2LdWqaULq/DJsvtOkWX9J2BeAteCkV/wnMgZRxPsJPuoij77lil9UJci9rJjDTfZZ4Bkn2K9ewg0CGcoAH2zZ2dFapHKN6gHuU7td2X6me1SIto63tKjjr8ktYEl4th4oaf2rB/1pzdN/KpmJa/dUhvsSDe9UsP6sc+Yl918vvl6iPKyySOQZg1DKpENRYDkqZDD9mYJdVlzdLesQkZ1nRnNOdMpPEpIqHlcVlXOaEEVNnf/raPK660SXFZaij2CXepHODiBQNbGJnRoV0jRPhrVkJCUZ7W86k9AAviWh9mfkwMiZipM5faM7UXfxG22hw3jT3R0+egq0At6sMewIgs0gXoV0VFNbLLTQZk6P7XNdK23WC9b/DpbyGvsK2XaTD9WipFt4UoBZkTdlSShTTBkUn6e9IjJ1A8VNnSu+lT0Nuiy+qqKtw6hjyWS2ahn4fSBp+QvU5mdNjdnPLBEJBz0/Gj+TczkgOyTAgMngXkswAvizp8WSqU7CA5wk2LvyrmqiVi/ZiulHo4u56S+gF6gjcttZXn3NFXwYN/Di9fM8Z9hKhka2IhIDu/sPxxnop3ceoq2coTRqac27fHqkIJZPVhPo1vnOTRLo7rA4C+eC/TQrAC87cvapbPHEaRCziwQ635Lj4YhGZ8UTHNRu+RphYkv48NIMKNFP91zm1sQKwlE4//Pwaa7978UHGXP0zLnbxAyEILfElhTYAE7DturHoSp5DwLFduiA5jmKtwc0tJWq1/A8Vhy0eR6Ti+VS9wNogFoijRh2gVbsdDXfhUv056GYVN6YLCvPpEpjHky+Cwqr2Fv3C6l4sWQBihViHJXdK+3oyWjFlRxbf1i6FhqJZ0OZ92245lno0eWOlkUYlHLN8RezEGeuTwpP7WhRXevhXr7q6rFGPm9sqc8vW5oqa7i6MVUvVUbBunwWmX13oS+zWPTw0pRCF3cQyK4fQfu9+FKjlnPadduRcQgkaUU8GDL9HytLPnrbjbKrxKR7OvYSiJHJqvZpRwv9xMaB9EWdJC1qEAwIbCB9itOE4K84aMc8LnrNXN68hHzhWSp2gzaCYlO5hPMSWq5RjhXRw7GG+z8Qv7+KjDxUnF+QK6MGnULZQsN4b+Eoi3SIDlwU9zwJrqWD3upA7fGfvvy5snIRw9ZDNME03lUSgjBTSocJYln8pyo7b+smE2HiicR6C7QXJzQdMhpyJIygZlMUA5WGx5k8aIpAq7Sntd4u+4jSEtTkybTX46gwt7KkdGScMtBbA7sK86t4ajl5QYpvxW5Ww8v7h6n/E2HFv6+Nb9Ws++/u3iwP5+8uef+cXyFoVcrt62GdowqQpuWI1eo1c0D8BR0A+bItIJEf6fl/P9q8kcXBK9eYyJ7fJO6STgj/lhF/Nqm35PpXGhMlsgT4fvvqR+NArUSxCiW6BmMegH/CPbYztIaMx62x7Ixp6dvBeWG+vVgpWmvlSx4zUpS9P6qrUo0rWv8F9/Fo6urXpuNQo3DzMCu8zbykBqotUYpzoprVYLOm/rwELe6BFE8Dhg4K2gIQ58W5SUBNeKSyKEs0CTIapTTJntVpRZszxtw+/NJHceHl9l+jJk6hTQyCERLD86z8PBij+N/oy8hoz32WjWucGntxuBKIsvUVQ4wLAINFBcokQqolE8ccUJ6WzPKo0jquhUCrSWI8OZNgncd2C8tIvogPXpa6K4Z6xYF9jPJmE4PRCwFkEi5gVdnzG2sxKAoVSIPWwUeG+e91F+73xrug0q7ZDEPYOYklsgQv887TYnFNnQlNK8Cve/7Q8fBeQH3xOSgv3lRYbNq0o8JIQxvHSP4C4YXts5/yrYMtXgf+3JBNiDh5tqZN6979aHHr3vjxscffaLwxq1/fDc+uJ4Y2FleQrKI3YrY0WnZuFTqR9DOmTKPubhp9DD76FKNCvy0Z07hyaaFkzUnoZFotf9TZlCNs2917Z+j5iLfcEtSyXQKo72Is0YhD9qrzwgNiatM0sahJmJufR1D9i4udeLkWOO+MSU3Iz9GVHBwFbM+6kVbLHGAIV97nkFtOzwcGxva24cGf9Sr04lhbcujyqjWO3FfPblEBm/6Mx67P5rjsPx9VWJcorspDG2ojaYgespXaUcN0dWcodJ0N2jWuqSEkhlCYubBkiQn5WcuLB/R//1rRja8lfa6E7Myg4yId1QjfWGs8afPgnCjn9pajy8vEb02HDiyFJgReUpluKhD4YhaejwupkLtCpdwr/FEZT9+nYrohhELsAlGIl1PqbSI2jVox62eHlQBKYG2LRul1q9hEzOnV0z9L2KEO65lasd5EOtAzMuiAwOnlOgpMuX+DP8dI64SlxMYl3k7G+C11Gj4hM1NfpCZd6qRwPDExIN2Hw1+da/y9/Jghh7lE1rT8nUxv1dtbUqcqvKkaFLXVsM8GYMeNUXwHIvMWfJI8cB4ec6NnIp8QraowKqFlF4X1m33CJI5rbUtlWu4GnqDx/DbgMn7u7cvt3d57+4Jof9xtGf/8ZuXB44G3ha3vm87Zqs8iLeIk2hHYJBNRzwnVhZwlaMxFJETdNy5nhMvKIFKJuayt1tCM/pmbBGlzTVpGiFWZ2IRW0dSf46MCPuZ4IM6AojJFwYrRaNkbNbgcgwBNdOK+QVTqYSoVLIK63kq5m6EsohRk4GcQn0SJNn3ACCwkTAj/SlB6OEo0DBnhBAhulWRNATJdzFSHnTu3Ht2p88pJR3XUq6tXyANb+B6Z1COQUq02ErEXL88Af8fFs7Juv7nT30NS3nI+wT7mSpbETFUerh4kk1cZK5vgaXFcsFvTwX+8+DAA8PNcQ70LXVlOHD0bFGaH/2SfKZs6BvS5R4b7BNopNCNW9jl0CDLeuUn7/fomqoRaWZY+z0CF21D6mBKXi6x1m0pn3/q6My0D7zCPZYD5ZK3eju0C+TcQq7TGvpQD80vSSJG4uqrIns4PIOM9Ly2aLxh841nEHQVNowjODBqKevWoxxS/dYMSH1U8aqUHq4aogCkz8SHircKiWonS4h59hwERYx9mB90IL2MzAa7jihHJWxJwsu7wZGocmEhX1xr90ma+kf8+8OLyvlftcFPpks2PLQoF8c2fWzgFNkHen7S5zQPbce563O/HoRBsrU+r6KK5DHeZpTButxAjK7Yedwp7QRkCBHBnjhmsKfi2Z7HE9lxtafZk72XJkQBhBS14C+w9j7XL1mnZB4BKxs8pk/Veuh8O4KIvGamRSdCD3JBHRpkQMKcZRLRIc3NYcM2y0njJ3owVgPvFWxqAaXQ8+TFpxUWSxmzyb4MLGtSzVo17+JEGu0wvefgPZlF4pUOeBFONGR6BXn6AbxEilytbvokUK7Q5wGr0wzxaaDh02F9KbokKmcqiyY4kjnUzA0xRJgDj+xVZjCuS3cq7wrBZMbGXutZZjSnzvgA2ayGtHP6Kz8ovugFS15fQUl2gC14O5XvYBRIWt8z1lvh/XSeNZN8p0VX8awsBjaOwMBRkwMYyugE5eitAS0AAbQkg+TMOih/sKgProz0iS32EGDhQQWETtwOvwZN6NUc7NWQ9naTSg9q0K/Y5wkR9d26GDIjQUcYh4KAI/bL2501+I2uHcL58eMBkZqiSwvrxXXnIim/3mZ/vuIGUw47w2QGCVac58bcn9dal4nIK/sWXAtcg2tyQ2GzVEKDkbAQB7z6kWUsGEIGkpflllk21dWYHUrCxhISuiWmuSw1sZedA6Vdae98VI7uFB+gOZpyydd4f1Wjmuj6eFI3lwkAS7qPa7blfhQi4KyW+NREY4Ez1Au681vuuAFygWf2HpOjO8Lj0b01+MWKnOYx+4rC3TBgwpQaqo/UBwESY/ESzT/afgaowHu1iteIAvv+aK4whthy0xFNIekYVRG6bjD2UKSkQcKqWiWjZUEwEuiHqr3scDifoBYsdhFdHHZ2B2j4huTykx/9ce71f/UXh46wxArzBMy4cHncJA2sAAQGC1KcpjpRDrQOMkgu6RhM1lmR+qeYSen7RiS1jFWnBZvoo/I9OnkQM9DHUKcDDFQRtQ5TknLSJ3ezQV/Dkio8k+AAJwbfcnB/T2/EXLrJF30vyH1hvJmNCR7Wq5xhVWPPFfGDsi14rhlYmVKb81uKlikJzfSC6TUcS9ujl43He6XcxnGQ/KR1Fq7h34hs1KDvFqyso4XNTLd/NtHNeMt74X9RjBL/ZIGHym9g83CMdDIRlsAmGuId1DTS/TsREmw6yrT1AQuIiSDJRqSpM1QtonApP88oy2HCKRX4mH+HAH/fRuo96MErnk/g6yF1Zb1FiV5T4caf2XqNBh1LgfiihWYXb0IUA0q/RTpcnOroVfoRKkxAMcHIfR2HdhauJVKolcHG5EnMKKS9I78+mzytqW6SlhAMVDZ4DeNUE/wIpd4tMxIkFroF1jy0slnwtjAOi44QtG2I4bGp0dQqscS+haX1zaTmmmAHJ27RzkJ9HPIe7qxQ7N76/44zvrslUv0S0KrtHsl1kyX7EPPVFf+ph7cMIWVuxrA/WZiLwLHVxZoXtOAkj83mb/cV/Xx9YSaPi9muI82jp3QQI5mOO6cSAvfxXpojWRLB54lTVDCO2e3CH6B6o7lnPCjXl6F8WwhY9+f0PR69PIZTjQRkiDVBDOjLCgJZR5aS/k0ETM1Oy9kHWqQLvQgcamXIWiSaikEDPvCR4qjdoYJMRM0gThRIKmVvPSGaKk3R50gRU9Xg6YnrtvmjKStxbt+fPi7TSSR9XJdw40EB27giU/HkzbbjsVlx5EnrXNnwn4Srp/9i5pq27CMvD7sWS6AVCjY+9qi0E0RFlnScj1965Eo86S6GU7z50RqTuRudi0iox4azvG8pMAfkrBhW4YH4FJy0BiZOGKY/5xm6EKU6lfmlhRAKdKfGFtfX/oxvnZbwYr5P/Qun6eblsedm155eD4G4f2R1zZw50wV/jnY9d2pdF9052DV78uRUzPKyqqGttGK+n5cVTNCr+qNDBxSdbiP3axj2rNrofQ+clzZdJ8TsSh+l/dmqhUlLmuq+0l1y+ONVaRBFesxUOEqsxdwDCDNbQMM189kgoUcm+fb3F9E1rMPd2cFwHki111VJaT4Vq1p5UJJx1al9b5srit4c/vHG6hJv/Rhdp/uZx6Xnx3DspVlCmzrV2wxQqwTu3dAuH3Qa7EMjtiGQ1OMfaDEim34RsB1Nvsiy5ntmk/iFtiMgwBsQcYSGEZxijZvg1KtxSczOY91JeBGTzZw3fshUvyuur4/SBSB0AyCFR8zk7QJDLO8UYUoM0dBe0CQSIPXuk9WQCWaPnPoluInbPbS2IkW7aeYIXeYMxjo2kikbcsWB56oFre3KERFZp0mm1DU8k5ThFUik7eBqMGgqtMpe6OfeLq0yOqQB1Sta1prjuIFCyD+EKSoVAJNG5bX8p0QrOaFtbGXuqxCAISxnpXTWqpbLfUeLSeD1ZPOvE8muaiww0TsB7f2LWC6bLgbsekM0hEVIlu+eGSX1eJqD2XKR6NU/Q94zCf3/EhZ1Tz9oAyWOGIqdD8GgCThva5vwZd2PX/ZngAn+px7eCpjyb2yH1wRuNfrD4zD56wdud/FT8fL1SQn/c7r+W6kk0F/pTvkLPNsh1wuj85OgadvYsEv991uPoBEBNFjHCrXALlSZUoX+oQD+nI/gsRAeQfFAsmUItjNwYVMLB9nDCTzEAvfGHeesoB/qpUrc1D/YL5gigOYmdvRCZBPFWxjdStjmePjJvp3YrzYPNGyTKssteLog7qbKoe1ckAu/oyJjeYpJ4WyLHpI8ZeSjJGymVJxHvVfoIRkHyIDs45ZKx441fQVbKJN3L0vkdK/WIZLPFxj5bB4v5Glhgc0XCBB17K2hutMimDuJDSusVvUhtp8t/JgbX8KDJ7UP8BJXriRnWN8xEl3F8z/IUQzlAfdDtob78B7xRlR7f1vlUzTwg9Nt55UVM5xrV2s5hsN0ZK7zFMEQR/NeAg9bzoSvvheT5s+1Vqx0QIOjfMkQ9Gd817rtcG31FQeD2bp1cZkA0bfLGfUxKmf58SafTvpTl1g5a4dnO86wnJoTvMnLKl/Ih2baT+JbIIGkOtRtcrIwSKTkEoYKREVUQEXIfhhfeTF+GQd5lPmvWP447vAeaoetFY48S9/CsQINg5wha704FDSYfm6erKyA5i4yMXUhHCefay0xYRPQSM/NP+2+kydRVo9iygiXwrS4RtevmLFe3hNqOZcxMUFfJk1odLqo19L444lYi4HEEFSLt7K5TCSTy2qHF5J0FhaE5T7OgY3PoLt/NNMd7SjLUzgkmRzcql1MhBBWqDSl3wE9XhCI15it3PewydEBrWt3Jcvrr4A0IBhogIG77geume69ZHH8jj7AASIk/W/icfC62cgN69n7iRG4x/XHrA9dNd932fLAEbTosMXoJZP9V6wOHoUgQkF8Qt+0ZvdtBVyKBuiZdb17VzNtx95WNifVP3NiINFphmx4zFn8yefFyR/Hxazs88h55zeZre79vmvDeretfXwiyzKZb6K8E+aySsAc5vsPjHxznQdQO8nyTogCHmgRIorDItg4kUwuslwE4q1fz4P0RWSOOETOEMrkzG1tgUqMtSheeTd+/qDM0cXRVXPeYxmPUSKyofhYUrMJXRWtdURagUE8a15QkMohio1/1ZmVBO/fhbdTYviNt3QbWUaT/FTNnM8foqVRNylIdZqsOkMK7GYpLlZXoOpMR9Nb1/kbDAPGN1OYrE+GTfucuMm1qM8EpuhTYBNLWYoTJ88RQgk2LSBAH3Li4lWCgnhB+/BnafAx8hLBiLBEjmv989Ou9YfQu6t1lG1wFgeRtrKEirKMwDAv9hdMhmWawl/Gfn0r1DPYuL8NmVOkHs5eurUQuKIk7JPrHdfIccNW2nZa/wb25BqHNUXZ0G/Zv9XsNvTPV/eXL0P/B9r+zp10nczmo6Og/HxIvqgOkMUQvdPgSQuAJgDNz4DJMFAATF0DJK6RZ4JEQADbBvTJncIk3BlTsbycQmDpswgpx7jZV8HuwZ7eOwvY/bHBPZpNBpbfp5NI6XY/fjd9X3P//SeblJ5OQt8YcF/+/fKWiP5AfOcTPXzgiTLNshP5gdF70hmI70/QTHBb07b9JzGfP2NOJvsN/3xs2bCY6dEa3mLqvi2VD915tAl1aTRZ7HJbnGMPxGNO7rXMEkyG89tSo3lMpioveqGkFsMylKopilUld4hFM4+U8synt9yho2QwGQx9G0yabrqYvV+aPFV2PyebOJ1zr3zqa1v5CXmq6ULO/p/tTpS3f0DOqEjGKbujWPHOhK8c0hgp6MtyJeCxxLBsvnOoTeOMCCbDGkNgM6IzbRp3Dlk1N46krzVGOb41LpnorsSp3den4IpjNo6if1+tEnfPP9NQup8Znd/2NIWnDGAFBhqTg5JCcFmEkCKKwwJsnEiOnMC4+67har4wUTNR2a0NfIu8qPV8W/MsVlvtb2h1apFr1eHGZtiPWtnjfFzsEpngJ7gIigeITqRPJCeiB9BNIRdvwlV2eHRU4j6h+zRh9+fovLSco4tGlxLIbcMRG1K8YDLwgAQCpJLBVG7g+Xqv+MDsyIDCMzyePsorjO7nnvEmQot+s2+69jlQnzpMbqjY4JSD/20FbwZ+z2GH+YTsWGe4o2a1hKBSXC7MAhmgpFq1kHFpVc5mNbupUGNO3NbfgRlecQZyPhMR/Hwhpp0d78vfkrR+wR6/edfOalAHJH24FtRQvmR81Rqv8DVF5PpoNdU0Sfh1nRKwOgZFtjPTuenKGsCPJpGmNSXHxomYANdwqUY5nCN07mK7sTWN/s9uVIFDy9LkAVT89DSBTCfjQd3R2UJAoNDJhAR//qSGuiUdRuq9E4evupcs+sxI9MRA3NlzdMOz7j/ObseEPpoqKe8oVgNBkYa5umWTJV9DVY4ApVBe7pHxy10bFUUPDstt2e8l9Gfx699j8fZ2qeOFhWAY/eABenh9cw7/JaRovsPiHGUiWOrVAt3d5lJqXmA+OGiLmfvRCFjeHQYAEy24ioFhjHZehWGvUYA/WzOGfvUKDd9YB8iiDtBhMkxIy2AyocAOfdBi1gYstyrwcNAqbeskWEPx4ZoaIVIgkuOISW9xVHyRKa1EQf7rDtm0mLECKPzwA2kR/Fma4aMVtBPnJedP0BRW8CXKvTFp4OPwGgsY+gZcjVnbok1IrScITVsMPDm5mmtzGquTPRmr++5v/rijySNaEHzgtCp/dUDZtIC6i+ATE2Nyn38uZ7RpKr/6IAaucarG8yHoT1kde/f+epKO8o2N8UwuNY0dPJmBKfncJPujxszgY7T28XCKxvXbJG4WyZe6lipiTevba20d+Ckm+pGmSX7EyimKQRGupaOyowU3jURxBY0CBjsZKJ41y6aLpQDhmaM8KtiBKyTUvKAcyiklU9uQV962DgY/Fl3Z1+fmByP371SJiIvrAokJGF5Tud1c0B+3B3UD1ZKs8OMt4/hUaQdJ/HYBhMhTC8F59GgPnCMlBybDI0RfRTpMplPgdE2fxWeaIzALuEDIt3gdnHuqZ7qLMtmsERKR6ZJmyUqXdE93vrpu3LcWxXD1c/JX8nPqFuM/hSl9Etc1tpoMwTQrpdlWbczS3UG7pZyMUld1I5AJGstdKEIx9RW1mHBpyrAEE5G6IFuqM2b5FEorLBaoLEbD+HD+QdzH+A2uqADVK3/7dlTacl2tm0iQb1KSr3xQ5ZGiWm0O5HrEMSUETkM17aG3CjYuOg5r7bDrh9M/fx+ICWOiLy/g7fDHqrUL+82oXXP+C4czUns7xA/+dIzk6hxL3iDQ1LCQX0lb21PY8/tC31ULZNU+bSfaEpnwKwXwaErNFkbNM0i6j/5FIBucYiuGgC6aKU+gAEGs4dEe7RYx+Fs/adLZCPk05yDg+bZEVZXuBAL12YUyb2rL3HQrwcfU5dNKeDy1xXskG7tj4XIX7NoGwfSeqxxtPh9nyp/D/GBDC/EoDH76y5vjaPLxpYufxqxfXy4LhuOLVUKxobn8UEjO5yReKoVQKBUMBgVRUH4sFonJ5CEY5q/xM9HpJ898BE7Qv4olMv2U8qgnDJq25oSfVl39mOoOm81b0P4hIbVhYejAsnSfHp1rm9Zq3gszVa/l1apn9AgEsluAIHawKWUIcga7lntpxnriggIJzWjr1Pu2Ond1VU6siPryk2B23ToxTfyrhd6yzv2sdkEdVRSTU2XLUe/svFJ65XDp4VWyZk7zwYPoEzGaXA9mpFfvbOTV14cjD7VMRDI9fKkx/XYHDlRy8g/n510Nv6q8N/c9Y6z9ixwqCDD0pom4Y90fi2bz8iV6EtVM0Jh3OaYRltJ77O6Vq6cK9h5ctbnZxrqhxaa2nqOl7VelISPv4Wv7tqwyYnQwHDnbcbUa1End/AyXAI6W5WbOF3DqznSGo7a2b5zpQHq6tl+LzdifYXokujSdOFr+0f+4uHC1rDejKyDm4Q9h7K9gjOYOVBQmeIdmFMpoATwA0whdgcHknd7HMFK4qd7fUx3aECQgnYl0f74QQQhZRcZWOGapgDS16gg6q6d0qmIme9/6VlgjwTZAVYiheqge0tOWMTnZBp+pGGGA6rOHVAPeXTNVOdM8teW4Eb06Ik0NZKlUOGLJAdYhhFt3PMJvriVlBwJ1f8/6TaJ6RwIlZBvy2NporBese3sD+4C8TjAvFTAFbD5jDZoJ3JGZixdNPVFtp05tR/m/cgNMlj/Bb3a2sHBmBmSS4ozQG4/6b3Gca0N5Rl+66ORkAAyU1V8cX5gF7FxkvfjL1dmtGJL0oooZG0ZHZ2bGxuLggJGRe4xiVK8EKnaLKfnrRQUCTJojeb16RjRJ5NQjJXqXCkCpyFMNlouTL5vIRcuuRXBPcmbmeuS1lUfh4NWpiRPnjZwdxGIqRJ08c3DYd71+jV1HDxZTbpRFGpUuPmQhGzYtiElKcuScPrA2latx5YB+L+jTP/iDQlm7ZmQCL1GKaaE9TMpKDV4CBLWKATRzrq351lYAQfrV2iamjgmJLOSpI4A2NRXF7te5v1bV9uaL9yAIeLU77ZB7mAdo52kHmHvIL2/vEaWJEngVuDQYopmN1ELwt4bqzXy36oJ+8aITHQvMTInKtMfZ/Mr9566cVymZwbRfkJzbX5l/drV2tRt/c3Vh3+CS41ztz6P3T06JU87+vr1KyYgmksBxxKBOZNN1I522sekGEUK2F3s9qr0dJd/6DpDFmIIXP2WsuxZ5vL+gLVN3g1igGmG20jQE5s2Q3pqTiSBah9R9MBFqmfzwka/+wx1lxHvrqinSPkOwXMAaKUG/sYXLUfBsAplA5gZBZA5CAuMpZAKLXoAKy8wIhcKg+D6ACgO+0TkcvGU7SzaLqx6TBwvsO31H+BXz9itO9s1Uxwlao3LBqEPJ/v8B4eBI4ovS6Redm3ruPMMm5AdGHfjAlrDRek09CVDyg6iLqGmlNMIMhqkAKKWpUF0dJF9qB8hiSN71a0Vdi5SCMzSwHBaoGSjmAlk0nzfgEpOiQrkHID/ptxUCj3R5E5LgGP7XOqiotO0iA1dcVfXvpm5B7Sb1Esaltlpdq0YPE25S22VSDGHlt1SNCvuDxZIMglB1u/PZKyk+eOfkEVhMbuXRSHfMi2s3iXactWKy+bDv2vhVFD/Rx3RS4+CuOlAL+rpJm9OwRa3nw/y4ySLghkYAeSKAgRYg236MDeRAKd7qhfPMWmXLrYHAQC6Y37cAQ0cSKdk35bF1kMsph9Cha5P+yXh2Mslp6tq4S9DVUAfa49BYfDJ7+wVhMb92N5lSMg8Tsvpj49wrK72j/U9mUg5nEU74u8dVVkZ7x/ZTt9wq7QYChffocYuJxxvR3qf6tN7T5t/ZyewKpB2yjgK+HMhFiKKRHFIgAJEbb5vcEY8H88ssxUzzbKbjFln82vpZ+ttHQWk3vbBR9knk0bt3cxM0sXzrOhR5uOtK5MmjT0UCBpvowIhVNblFSzazejo0dXt7tzTjFUw3qQbqtIE4URVW3Q3W7mx/5U7SwYaaDDrCYnLmO4cieHisDgqBfOOSOFCTbOfKbr/dKzuPLY8d9nVu1G5U4fND+16jmd/TI7jcdyb6tYgZwDPF3lfxOYpYOaiWwmT4u+C714wuewFg+F1bu254C7yQtMY5s82WI0Ke6ZkoGBwRRxUX8MMJ+MtyRI5rl8llyJh87MPylGzqg/Sq7OqVyEJ5YcfU2NTHsatjwAsNRIEISmsbKSJAGBeWyIReea9f7AQrtJ4TBPLyb2J6b3XtqS6LxfTMjEwxS/SjANwgGYrETFqDQsFkmFisBSa3CXegL1xA70BtGz8jhlNhsnb3xWfGaQdC9Qo20EMFzjU8VtKW+iTDs3lV+6PDIRQXduYVQIBfGqUMt4ew9I1EJLmn8eY/+o/FEqvH61KeTDnEWyh8YXIi1ee/xAj5BTGNpS4GSiWreQphtq2P5pzODBZZVCLo4QcPhtFd5dYci/Lianf2cNUj262hHeLQQ5jMA7w+pd9XouYr7siOF0EjaKa4U6IuwWKetlj9tg0azVZSURRHsi/THsVUZaJ2kFnGFBSVrURHCGPGjeCaYfgMAtBn1HKkPgAeKAWSx+chJiAAkmX3kJBaT5g3mczYMBnmvgHFEThCCPMnauOuzkIUefC7/tOKJDQxSGNF2WMUiX4D9bcxlwKdn1B08cY4iHy0hKJ/7vrIF6i1wC1qT/uAiAkXd1UAFr8D7FLifqc5lF860qPTfEjy/GNvhxG29Su+pVNypH+ivxkI5NWw9whbZFsDwrwILXevS2ji8qbwwCfnjeadl2Jg7XlqxH9RYdVbxYQDr0eGZmctHZI0clyshaGELgbzUlEVangYJV9V51FhmvZDVGdY0ainAzxo/XqIJ5q2vlenWNXTFG1rh0UAEJuugSUy4ablaTcJZHu6Or+Agtzdb11vG4EM4cyUMoLA+UElxAERyL/2XtwlOTu0MPGIVrx470KLzi657B0j3tRFhnsGk2ulK6+JxNcrap/toJ0spNEFNcbhmzYchsnw1jegvixAyRCtSN/LC0++gbnX2FowBAGEZCiUzg+aDO4+Gc8q+mrPRJayBeDXSDQzWE06e+bJpBFsXvlZaibFftjcaPLJvYONeqQ1CcKmvxXSOT3t85B0lmGmuJj74sXgpwNjdki6zERtTL9alY2oqB6k2HeQ6yjP2iE51/HgPl6X2r1LdlxxKChVdH6az+VjiN3FAAKJ8MMpDJ/m70UyacA77O9e2r50D0VMvCP3kE5soe9QpJupq1colRvALUHIhCWjJQJZxBnyee7jNcAByIRLr5E+maA01f9UNrRTI6AoSyhn2QQIYp+eYiYT1TO5wmRurcEC83zxwsbHY10XiiDJ3ocwCrVQ2D2/PU8uHAaBQsmrn/98nDnHpUHr322CJLb876ZVa3beWcVmLN6X75sknRis5PHZBsndfKVmDbt3SlNwS+Be9KBXT+LwYSXhxdr9e/FdPy0jn7moPPbPj83iYNX3mt9E1RZIvXgcjWnZfD/ojJc/e14/dhDwV7lm9oWqflBROXCyV48xkpdhBIFGBFG09VQFIiOhCYY9ocJAQN3CMweuZzV+LYIy93L3qwDxcSLJGKk2qr4tltnYiVbE5yp45VTitojisNkc1KLb4SuN4vU94QEWCd3tvbxKW3FgYJxzovF2THQMertRXGFASaJa5v/dmI6M+iZoE5pB+FJj+JBqjksxuSTXeS3yqw/VbhT3JnRIS7L8K4uEK8KacGzjwqM69IfO82jBwaYvBlYFGMWh2iv30I8e59MF7ykeEILsg0VMZk3k0ahoaXWJOSjkwPD/kyDqBARKvz4ZZgpu0l5Ajoy8B5Nk1YGJQJcl+eCZRrjtnDfk02zYjNg/X6SZWbCBjSgQIUNkIb5wbgLUZQnkGzKfZpyjbFzAf0/hTpHwYXlV+I5neBf38uHCgY6vSYHS8nEBqYyJiI0+1z+C+nMaA6TG1eD5/EaS94Xo4z7H06/5kAKaNSpSCZSzMpvKABzHwsZOl+9eyMhvhcnwmKYfY4+dFjJ2aQjwcgHpm83nJm/Si3/uzbnjXsfPvjnbMiWuE5+rba1rBfZJt84nrV04EU3z8IPjvkat8RckUyuj+aWmZmcWXm4+fGGUp3uMHH08aqsbj6ZXHJ1UaOzkK9Gj1o925bUlaAZxD/cLRIbondsvzjuLaPu9BpcZa6paaBKspmi0Iad1a6n72rPncsPO/Gv/3CqlwoQg7rTXE0uVixwwLn3zpqWA+VpAY/LnEDHW12ixy3Jx0w3bnfqqudNXIrLHtnpEtdT3nBl+lK7/74HtwM6RmBn4ghG+rmZvtSV/s7hmH6/AtgYWBNkWwxVRv6L3icgtyWRhjjK6IxzHccCFF9032NolsKzZ86jagre5Nb+qYWLsBv2ff3hoRDWjVrtVisj7f0W5ROiOh3qGu07oeIb8ivbRLyCVuqcB14VqSUfL6PnHxx+tinn0frFJr3fuURUNXDHPHWUG5Y16RzgAG9/VsOk1ovyFbtmppmhiRFNU5ITdCg+5gfBWIqQdkR1JDglm+0sBjo8zdh3kdbKuHZiv1K3U6/aay/g1zz5J4FWoohGkMv+s3PXeJWT35n/pGY8me0YKxSGCuS5Xrs81AX4m5KjuCvVh7GgXWk8y2dMjmnbghUIS0UJ+eBGzKDwdMUTxB93wQdKtA0K0sHIVO0HhP6xS7y45DxnQHsRIu3PAUAI5YM8jIuTYm6srPTB19fEdoQc0apXKxb/10WFftwNukKLFWwS1DF6sY7UJfOwWtC2+Zc+1oJonJ5vlQ3WAvMboNRVIw1vm2/k5fj0tlyMiUad9OYM9IlFcdJxIBPjL17qEHHVNJBchAEFMILoA9QqFiGWx50VlwWxqTmylB5HbOgGe8gXXibej4hMvvaOCIX8jYaH7/FenTT/tR8X/vWcN10eQOVbAe8x+fn7QaFBO7USmiEl0kTEa0+m08xN+X9KwjCYbTqrxRE1LqdcXKOQ6ECrDTUm3IrGylPXLUGhRciuSjoxJZ9OJURa4dla3xt55/iGPg/2yg8423W0Olsv2c8OtJh4mBm1Dmrj7gU66azplpnbuzpa3tjBpTEEQ4thUEtYs3EBBCvL5LNO4i4kVv4Z2qaJncnHgBSkUQUHs1IWcYsAD4T6/DrdCT3Y4CzOG9m22zp2pKQG70TeX0APkYy270Rlgf6p9TGoqcL9FhyAj2lOvXQpFpoCTPqW1v5QXyucL5B3y9nbeGEc4NMZT8DqM8o4ICAIuaOBe3zD3Ro7JQegJqMKAZRzHW6s/O/o+L4eeegq2d/5As26zHrPH6VbA+WbU0cle+xcN1qtiLW+U51jv3js6IxABH87UP1sGXMZOtvaIBLKjAwfX292uvHfx+ybwfxSR/ygcHXtpDnq9BvqmphI9B5qk8NFK8/LaBsh2ObjAhcWmpgYGclrF0Ul0UODpleVQ9GptyWG0eHkd7t1WBuwa3ILgCp/Z10yzCbH8IgPsXlOco5LTeaBrwfiw0ePTfRG1HXbMNyQ5FY/ebIi3k4/h5Si6LdyBU0nZhJdjLO3k1XgLToe6Fz/ZpfnCkIe2tjlGy6HX7VEHzlbOOWBdhLz83WZythVaPmiumnTHyrz8lbP3X1dGEV4PHZh2659he7w/8zHROD9Oyy/NGR0clJD4YL82VJVcohNspfcqxjpVfUE11KJ1I+uw0QUSZWJnzWp99tB7gubRz8tjqAvAEX34/keEuyR6TVnDXufE/Esl1yeJ0lpg6vL3eQNfvQ0+7nGd2lbeWO+wtWrP7RsCQXJob9CpHt2eDen5wxxUZlNTpnyozsPHuXXe3B0CpaVBIbZBdbkZ5Nt1bKGQtLSQI7xe/e9p4F6Ia21N8OoCMd2bH0F0kHBV0LZtLXQjPQfyJJeDDeP/SaOCQY3kGTeuR1px4XSSwoVU7LGO5jGLOGEWdQFijhN8pqmGN9qxtKgXdJFOghGhFWZ1iYv6PLRWgj1DZx127nyFbhfQWTrM6kYAoIOaVzTaxgCF85+Il8RI7j7AIFDonn7c4eALYTL4CHaJQ6b6a9DXwxdFxhGU9gb7p78JFxBk29rKlmTIknUTl9F0iSFVyBTLkYWgsGP9eMwlxRJQKvvwTXKOo0rrU4vD022FG+MOHnTEOcrJGGcvPBI3mTOdPZ29n/ld9H2e+6crZiomqxPWhvqZGqmzvmdycig6kaYyG6AUwmR4nRcAO/RnY/n+Bw864ByUiSvAbsM6vsKw/Ue8W8IdNfbcfm37TcpNcgTTzQlOd4xz00+IS2P+EoC19ivQHPAA5yHIiUeCvFJTBb65d8vjdOtH2cmV0zGDBDKB6dc/xzNB3qlTem1HZdIJFXi3vl1mwLZxbSzxqEv2qP/+9UBHLaqGhMUgrSYBf2qqEk5F74Fs+BRvLVXi6ZIXGuh/gaGlJdPYgeitHmfFtLqjgbJZiVsiOxkQ09XhQhZTwaTHgdC/pvA9HvswKKWj8tjLa9ULMYTALFBQSlQllk4RXdXx2x4HBKA4iBq8eZqYgMXtdiamX5uHVSz2Teq7EUsnNTx5/pYp3njt29DNnz8SQXHJWum7HIM38UwhG+rTN2P+VPPnB5BAtvHEFAV4QCBS9i/fZ8g4PKGuSnlFtCE1qWv8HktyNchQYWt+riDiV1dPGOuCUY8ODE35JBXV6hF1/K/vFFUTF3eNsrrC4wwpUZ3UuEBKwJEmxBrBxzaLIfmwDDCoQiyxcZOvJsbgiNkpB2fk9FzIBf8YK6gezP1e0aRBWh6eoYn7OZwq5TvRltSD03gVQ3Y3zMBwtXR7iHj73ZOmuuD4mg4YLoUkFbWt+9Xh13SKqplriEZ52PlR6uZ1tZoshmE3Bq1GbrpMrvQ3f3n/i0W93btBXSy5CQdbTg5qFxqqoERYkt/zjCHMTPqBHZjhsbCrnOyoTxR+yd1NSHeNEwO9jcanyFhjqxSygT5tC/qZKnFSc7wIPLtGdU52Gk0rVjoOu123qiY7m6+rr6pKjHDbg1UlPSRYwaXquEu+REdaNNqTMpVN0LBOqGfql6AUy9KgfwiHVVSrdmHxj1+RVFlUN5wK6xg5o/8qdJK91QgpWBcO2cda3isMofcYBmGh6IKNMSgkCOLHQwiKHZH7iFMUEqJjUHKBf5Y75PPMrCMy3Iq+J3MFqCz4mnpWJNpP3ez9le94ngSyBmvHPJURRuhQ+ddesCxsLA67kbVyAA4NYrOUgdw0QD74fVg0NV0IYhsiLO2QUhohZ8CN4iM4hyh6RP2aUeezLMoBwUXxAbdWYhBBwrVXOYhNF67gcuMOO7Q/nBf/UD/m0WB9k3bTQP2r2FXh/bureiqtWzEYqcfojQyE0mqwvpwbg9Nqyks4ssuRR4CSKEP8aQNuINVvypIALZKWulL8UoblpEWIYDllX7VrKX1wMiwo4R5B0JQjyGnCrYAztKSbu3P1zlxdIbHVeI2BCxqR5IjItRf0SsBz6H++9GFpAJzfAVEmVoTNFJ0GKhVjzEKw7BR8ymb72Gl1GkNqAajhNFl0/SV6hA/rEDcANt+5KXzmCwDaUUvf7UOgKGd/Mdr3j2pY+83dWooi/2b3bv6bQ59h33eHY+/sVNNDrxLdFgEhCFAiOoiO+xBQshGcmGcprRiVVQI99U/qegJYIdpnFe49mS6gk98bpyNGV7+gv55fEE+jTQgxuCL0faM0Nz0dWrybYkHv83XOhMIJZDqLQOawAWmkyBA3iHxUezaeQqcQjDj46BzgC4VnZtLv1FG1Y8v/XJPgnU/+2Ce3MEFkWI6ISmBgFL7txMlmFLPxjW+rRgUGqiAa9sgmn3Xs3RVttMKwAS3HoQRie7pN+JrViDpiYvF4TW5QHB4jT1andjIhmZngGvMqkkskpzxk6Ef6S5O91egQUoBv2a57IqKbUSH7rsdtluaa3h1fapFJ5YCqVMa2p4Bwprwl9yJkuKXVpbVWjpVRK8stLzHsGcYRJN9LicbCkBHcf+tWP8yYdvfDl4+F+yfkGjpS2/kZIhw9ShApFxBEsxIRlDhwBoWV1tSLtH9tlHe4Bby+xq/tSO8J9a1W6rSt6ieGH3P9uI+Hra0MoMWoFTlEg+RyFFrmX4V4yaEHCdYsojXpYCOYZ5fRoJAtF4C4R2JXtHvsqKt6nz3SmXqGkNDJv6JZV5Iq2Rc8xUY9Wzp1vCFEmGjRwUMiVD0qrocSMREmlNncNYkCucFwEDQsBO3uHTICQDSwzYY8P1LkE3HKhZeR4FW44GPaYkF/oca/ibbzwm5o0Dlnsk46gC06Wl75q0ltg+xF6fcyaln2uyfAc/yb2eu0ZJNbsePjVEeKSOTgaLRnxdm8OyEUoTjJ1DT5IePtazh/Wih+EeFfqwe0DlrO5gDljVC1DYWdVLqIi5xlhF693kWx4SxZ7KVZSe0E6J3nz++UD1151AnsxhWyOoIWAIIeOTx5GQWMebm47kO24ZQTly6nporn9d7SMsvbuLwspl3+MezSE8CR8J9ChO7hU2tPpZUoCUPACS0QjWAXYKSFj0ggYszXFgQgBRHkJCdCQnZTx+svXyorxK7K9u3J7SYS1ZmDHnDnNYf9B1W3TRcyPdfBLvA6z8VfzhVU/drjOBEhUOBTm36tc3L3THf903kephAQeGiQeSL+r/gTSKGc/B4P0op2ptJTKyhaWpSK1J3/PT9Iw30E88vEv54wr96aRew4e5pfTnC0T82T6r13XOTsJd+v84f3ZD6DiYj8e5oyOyj78kATZ7CP8K9PisBILTmgmcQzMQIstKAffeM6ut+dmfvTxElj3ezKdRzfiQpfe93R/U+d+l8XBQeraQUHCgSjW0vtXAaozmRksJxYz58bOxqnmy8jfUY1buTokDFVjJxRjOJIzbBYOsWZgiJ7R3sgji4uPuG8yKfEsPCijeBs2NxgrmG+JgYQg+NLXdEGAz67DTIMdvsMGKAEB9ZocU2IAXDNWyGLshpZaqFQRgYkX2gHyKt2CN5EfWnQfUGx1bp89tqksbZ5zY8Osw7wq9d48tp92laL8kJ3vHx1v5CxLGAbKx/JXdiF1bFQYSEUSz54Xaq7sHsL6tgxlG8LeMQAX4nYA6MEifMRuBIREACQamQ95XYmQ/29Q8PnpNL4mVvCeuCg9vANpQZwhqi/rlzR5613Edg1GPlyYbmSXV5XczPsN1ciqzftKOdAP0C6wjkaqRUYphUUeZS7MghKd8QMcpVSZelKXhB/S3WkVlCYVqC7bV5QwZYaqnF5bWlPrd6RGpT32CA93yDjiurHddJDfI8O/uem0h/nJaSWVBsbl7NjQXf9wnWxxuijmR926IjDhyr61wqa+OaNW4oqLEuv99B0Lp5Mlzz6W6wnuaXXVt6266Rpe9seYfWWjUHV1FqqVOlwNEo7lKcddsBObcuA/cr2X4z8Ykae0vPSANNabhJQ8gVDneGssxDoSbnd5jL7xxWrBoH90RdGfqnmed6Bn9GL6i2pQcmrHm19K4mMXIx7UfhcRvI2L2jjlryrfgEBU6GL4KH6zYZZIanEJDHKA2DpiHNsGLWMYEEJZWUJ8kE9ACUYeaznXRs3Svr+8vb/rc/jnblpRIDp3nsJjKsjSScvCcbYoRIlBCOAU7UPUAA+AzCZIr8O0JlHBIiUP//StZpvLtsvtYg+8O6ZVAe4cBV/6K5PZUYcrBpmyrNnTp1IPH+3aBA8mWOfAse8t7F3A2n9gLp0fUnCNfr9L31EP4VVYid9Q7Pz76p1efWt596CSH4sIUS9npDaC8aRX7cjjPA0Att0pfk9A3/OKHtU2R0QKe6w1xUH8Ew8XSp35Jnb1Z8e6pXod0ALkNYak8F3K9kHYSJsBqJAlhkdrwCWb/k7GzqZICCQgTtl5/4deXXz+Y5qz03UGtl743Pb7uYHRR84l31k4lDq/ePJU2dP+WnFzKiMsRs5h8cpFCctn9ml9C8mzz4/zpsKdT1wOGXr95Ts9U15/brJuVbpw/yCP0WFamuAB0Dx4CsZFPi5pjhFABq0TYwxKq6M9ET7Grkuvd+Ex/n8/+U+M1xVMOKrPBVlikDsUn1EGNDQ6DxjasMhpgiUPJWr4t1bvLRduZfY5WRovWfyLGgTE+0GYO7fRj5DvRZUKEQkmY9J8CbXrTmY5hTB7HRLPA7AaYmcMgKKRIZYxumJMMAtqlOUyQKFwgES/GS9ThZcnWqJ26V9euLIIo/i+8fTaCLAxbVMzQa8rjOBidV40s9bNihAJj60AB6QXCSLizQijS9BmQzCNUiNPonsnDhUAxlTdpLNRJgCyv5lIWKGGKnXWuohwIN34IpJ7NfDQWeqLM08vWpvimax6QoFmaTyQ6bpA5mGeLvQIYmkeTysyDDyQYfLpjpuOxpGOfN5BJL6u4K/mbxEoS+sQB6fTapmhsVxuIj8V+fvdGZr66cPd7RTw19rJbFs24Qek3Nrr7N3/enH5W3H7c/aCcyYyNR21WdEveD2B3fpZKEnyOcsxr1Qm+d/zsRkfq4Ai+k4MC8ssvPpIgmdryVwuts8I7YL50/pIm/9vXU0ZGJj/9H2Sd72iUq6mM0E211AMmRQBMyKPCgwl5sLKjZjQr47Y1mkEClJc+f6T1axxG9d5x5EWiGIVWTbo0CfDxJGyaO2cyEEibR6MOfybuMQcam7vjVyS4XPVhrhd7/CO5e5O7PNJ1dykEAoUCCYHwkJBJBRNmokX8TjF+X4dl3paHSjUqCGwp789mkWQ77yexIlKddK2kjt7Rrn5kht38+N7zp/vguv/fxabaS5cxrb7ztRfOoUcAKyJT/X3ey4as01R4HmyiU0kvqFUpAgcAq7KQ/OdOoOCq6o39N3bA2j3/mQLiL2Y2zYG/g2WM+cHahjzDLraYjM3/5dfk7rjEDb8q05pTyrcIr03xn6G/F7jd9K6GSwfVxz1nyWfYg6RIojXRyUiTvb/Oz5c30zYhYjk2jWSMpkxJEaS4g9L4tYoi+R7PCtLGuuSNkVI1+fGPsnrB4wGDVUshvrhwok+X6tNnHIDqLw/9HjVzrtah1UD0KFXH8DwLKTiQYJQfnaOe2hmnV1LrRKtMcqnTfdFSKafuh2fW4IVfTnKvZGoHN3LR7oAfzaQg9v98JtAypclYFxm+Nk/zvkXf/2lbgQXd2xmRF1bEZUfFScSCddDukSPAr/Pz9K4yHOt8yNtmRW3h1/rM+NrGhnlfaq0IOA873dqMtj+ykOHcm4DVxQJ81u/0iaXbFl3OUTZ9heMUPlCiZBP0ufcCqtEyUpSlwu4TTOT05gWuzwvoFTG+9Euit98rphwqlNhJMq6GQ0UergDLwa1rc9LfSeAHJwO5d/abB/A0FA+PVThIjmDwj9R/17B2S5HVENMQoI9qtAYUjnI6nuF7vejvVw7ysnm1f164gBi3f/XEPLc3biIT4t6sZ6kspiKm+YEVgrj6muufPA98Uk0agH68wlp1YX1K4unBXTKTSxkUmS1CYB2f14rsHikX9AyOTFkImE9exXyZYnyO5X9bYbcmwnK0YrzkeZmiZYCbSybdbsuKuvswEd+ijHsi2lqSYnxYgTZHDTQX9y4VywDxAOdW4LX9t/ZCBy5Wfmr5e/Pd7WeOJK+JXDIPSI+iXEFD5jfiFDuPyl0HNKs/vrH2d/Plk1N4hZULTY0ye3nmyjXoNlhsWr51bc8jUFfj6kS9x6D/f8s09Zdie5Tt+XOJ20YxHqj/B3MRp9WH4g13q81LR54IV89LtqlTa2YayE7j+vghpAZ4UWfiz0yEKjdtgVXbZ5v7d07341u7FZF+xHbCAkovatj5O90Xkti5O91nmTAWD0MfAYN6aOweq5BKxu0T704wvoneaNrrVr//3zrti8Fucos0dm0Y4wGd5CYMEoCNNkMXs3PuOuLiMoxKrLBFV1fE8riq1n9qCrCIZx3qXG2TjV+ngLVSFmCpLO4quidz6+gK0IiEM/9aMylCuTWuC/f6c6YKKROqDpohFc43zW1wFT9tNWP4MLOqOVrwU7uietZZAU2ow9/AHkL3V/1tLuKWupd3+v5e3bo6cf0q/9RQZNWdd37vTQbN88tQow0gUS1NUZVKtxsUPR2n/flToZF+D8aFoyR5w7TIaTBqyeiZ5KUGCUVoHDas5p8yR3KyETtXFfdx2qFrW/u6JbG1qgW6/OfN0Nk+GcvQH+av2eMixo2BLutUucm8KIQvWbRqdUtjav+bNidblzOdj6Uy2WDeK8QwMNnJ+FVoslobYBgWvNM8D7B/pBXk8KAV+udqJwA65wa27Eeng8q3lVTb0Fl7Y67rbAab1gv58FqeZODrdsjvLre9bTiRU6xy2XxBc/xoCfX+GNqeaZyqkLDjEOApEVHBxiLuzPmsmevOFXCPxkIeAU3IxMudXpn9H+RkbFokjf/h69zLwMvOWhqEyNtI+aWo02uwQ7lsoImh/TMjVQXnw/qKsXhu1voqq9ZB2Kjn8GFWISaoebAA8oUzQeF9WrRwR6k+OfermERqVJ4qLGRQ3mRkSmINIU2VSx2GB5taLINGWVaZ3fvXXOyUd2RZFERNUVfwDDlVVTUZM7jWBFdIZpIcABhRg/TFpzoUWNZ4krMzSCG40lTfv947apbtOk6g7fpT1vI03jreJWLiYumlC00LN1BCp0WlvvUUyzE+O3C4aAHEiVNf804cUxDnD8hOU+c5GpN981r9Ez0X+kX9LZ8hU/BKfDU399PCRp1um5dKTcIe0bEE5CQRweb8QgjvAAb7Xl4A7DOQULnzdYrI4sSvJE+y8n+QWEuWZ8DwvRtt0/oEPL1zOyrC3yDF3vgQBZ8tZ1ki++Wgs7SHjVvr6AU7XOtdqiDUfonfpHass49nnGzPeKAXaP107zCUO0VjepjKun0onBBZzSs2xZOEw3Gud53Ds9X5Pp8vvZ01zTTS4bPE9t2E3vph8Bb5aJN8PeNiX4PSZocgIvBBQaC9T6HUIq5QI+LMfDxg/D1IA76janiXDpvDIQehUfovrGTUK4wBvm7j8EjEuciutvofnN014uh9W9iwG2VGAXKBVBtnIZ3C5ss0BcM2j6NITlPechFZuAFOBl0HjmOYrGKJtVO7b1au2QpiM0Fu2IRCvI3GZW04nQlBsTqGeQIIfTNpBrRliNi4Co24Oluh9iFjUzC1Ajv7+oFGQJFwFlidFli8t+mvMfVcB65AINHfNX7hREvt43dAztwsgqotqbNJgMq5c9QagY/FK6e0gkKQqCup/nMArFI7q7py/h0V2jAwAmw8VvTkc1g+MOAjKLScLdako+ab8yax/SdAtHYrLIguMOzXW90EK4rW0L9UL6/zLOb8btSNWbrDHTDyNEQ8w41E59HhRB0I8g81DL7NQdOJtzwEeWFZwNLiNMm5r6ha1LU0aOnM0JNKOFm2TD2ED+g0ENvAOHsZ4S5tCXYXezWKW5xkYXcQqZncztKZ9aF0H3synLT7TwXcKhuDjf0CTT4ksmm9i7/1JT0dDnYRzTgz0RwavGykXqDvOqmc3nLCpCp7jMh97pmpjTX7QWXbtP9dVsJBn+hmUO5H/MJx/f8OFwN3AnH9HO9Jaz6CwCz7jySCnpAKnsOqs8IGNXdczEyxxxdEdj6I+3FOMJ41vevlSMrek4R4cztNwQzU9FQrTKWRW0sPijZnLugWTWhqlsTRXzJrdC+MDSRleXk7nLrBCHF6lzfqtzhNN0IicIkI62ZpZoq6kIw0Z51MKHvbwNlUF7r4b0/QLML0dfSFnK7bKAtVnIxCf1YBTDaOeWSBXtkpYsuZFUc36Mfm1qxr2tbN/8W+9l1K31MRF7PmlKjgtmyPSPN/l1HhgAMgQI+HwAzyqa5yMyxN4qDf5hWT+Z7GmpOivcObVLkjtR+lNqbhea6pXiOw7tsvd6IVupYTp+wKTIvSv3kF0hoyXr/304Xr6HaPCohgEmGhHQPgGIDqlNCABfSQqZnCQCtffhL7kZ81UyzozKugw3cOkN9NXIQ8voZIKIQD6u1pp0DGzJL6+pTLHfOdWcfGal5NQ0pQTl1Cu9Ht4IXegzrrbvJ+mnauI1ciXtzKi/PNym4oPfqfO6ia2B16T6fLyz7I2rL/Q1Gsgm9lrUMdn2AQ80E8kDAcY6jyvliJwvFeWYgI7X5wNEQLp819+GPVbuxkSBuBjAY/SyxfDWesrISVRjHnWzVp2TA0YOP6e36uKcbOc8VOvEXItGq3p4+FDnSKs7k1xjtjk/cs+zyUOV7d5dhi5HBxKTCwIFAb4v9fmImkUnqkRVbHZ/xgRuo/np2BY62zubuoqM++a2/PN8s6TSNoA2Tmik4SyE8wMaZ9PsFXT6sQ2PpeQyTJKsHqQnS39Fv4liFaDfOQhVJhER3JQqcbPXUT7/1dmqnp7FdZNVKdyICJOpHknl2Vd8/lGv5j3Du3xBuZKmdj0PISLNs1lclXL69b9TTVXSNLRg+e/r08csoYcgQxOVkp4Sd9sFnrQLO8+G7qE+1V+PPOJRjzpLLyD01KlTBWn5LkM3qbOcyxI9I3WJf7ZPtr9E3UhP8poRkeiaa1m/TSzLMqMQrbMWuy0WiQ41rY415s27xiq9OodBK79Gczj+B2YDRqH1R9le+zW42OCeHvw5mfI9mBHyriGcfLd6ttcmCiFvS9yYZ5IWIQG0SIIc8lG1FjWmxgQoWHDjsRTQjnS4R43ZTTd7So22QXlRcstT2G7R645CTV5f3P4O/ct/dycZ/8eZX056k6UmVW9f0Ow4/qowO1hFGPBvIxo63rUkIjr5S56tiJ5NLwn+DtW3XpmIcssC+6Gxx8ADtSLn9bIEeHIOsjD8pFMEb5gX4bTQlde1hNsidkjHezqRMEwg0sMmNj3JUOm9USq3uweTh00dArv6z32Hr+43mz2Nzwlt2AU5yf0aKh4KROW+BKe0nYidGHh1dbQ9zfPYgDOS5cqMcNfaAaar2QBYbvjdH7LB5adjW57HS/2pVHws3iepkiur5AjX3/pWMZnI/dKZWpgM9/gLcB2BQZBaOdffIZAJe86Rxj9ka+IZs+fvN/SYlHt2mkBe+rJEJpyEyX+RIdSx0fF3M6hz0xfCp7x98ORG84k+QIuOvp9Ji/Y+J8C739X9UXFZl42rHHzVfmWdVRRjknfn5dSW5wXV8tCy+DKyi8pbn/DOwNW+N4qP1wa1gTE0/qBcfhCvcUguP9RhDTKNZrOuehnoCL4SkSMCLQyE7LwFKDgvXIKN3hpIVDpsk38TZByTF8qBc5e5OoXjZBATH3vP2tfRUz04uqmcXq7fiI/TbzOtzQje4nLodsMbuBGNDt8aDpF/DQVtsUFgsD2MmFoMwj2xWrwx4EaPiaCRnSj5wO3PgzFp7/SyIjKibNKjwtzHKd5BHqGU8SCf/HgDb/LJLRdfxSoZcwh1fbxPkHvvxiQDmNNi9N5FZMUe9+jkxK52EdnEG6wCbhBBvfRQzlRL2Fo/gtOP775jfrMH/NTUAX+5rIXke4f3HwMcwM0QT34qLTe0iDvtLKotqIbiBo5u9SFRaGy+WyHl3bEBXtH+RdtNzN3G+zyJ4fBtm9ocG8BYFglES1qPsD38w/qErOBJoYIZOB94GQfC/XE/ve26G93voK8K0viul1NcTYzYCDvZVeSKCyqCKVauVpRgHHlZtOwSpsXL85Uxa6mGDZ8SyL79fyCGDXzc2ho29UJP2vfI95ymrabJ+qrbuQN2ZA4KIaEYL89tAvyyklIQrbdh7f//giyfi9vPcsDrFYHyD+5ZO6c/udCNNze4wNtvHXC92QpKgk6Wgwu2+Ipz4QqzcKyQ+dexEFAn1Mh71DZ5HjYrl64hd6sNvS2IRm1lsVP7MvP3piGPZHsmT9recVRs5hKAeJfqZaXCjSySH1lbHaxGM0VykcBA4R4UCIAytkcy0lvY20eJ+yuBGSrTnodT0aQd2oqpJAV/zScvKbNEJlNfzCds7Mi+g5YFaTpaJWtSrbK4I63p/ME2WjJfRibLebNO/om5+wxzDETKrn8F7pOt/SGBc8/k+D5xxGju5squWytHoCNKClU/+ET09v4CLzST2b784UVeHD7dOv1agl/mjBen+T1QFJgM3xq9RY8OuLIf/R0AsGVLzweHaCkChrtNCXBTMx7vd//e4p074VTglSY+9kdS0rEn03fhq/DdC8fuBQePe3HhLnyJcO/uraHIgnMD0dmzW/wKz3cEmEpCDtCnH6p4f9RO4en5073CxREwz+9xP7mD/GrxM3+aToo2La7omTb2Bzu4FT+w44+KluupKgmqmtFq66MNDfKjorBchtAPJDpTNROd/CDy0a1Jvcn6WwRzo7DvVjIwXB8draapmqBCrXd8C4ie4QaSgxkbgj5ox7Q7iFZAi/2IFciLB/HQYA+zJuQv2qowxLoO9b21W6t0qmq39Yr6IRfIKz9VIcY6dIrrHBaq23bKZXgurxywdxPCL563hje93L5jowZE4Trp8xJjZ3T9yJ60iKgmHI5EJDPAeZz5Xf2eQezQN04ti0WIbrXJlXVAje49cJZ9Oxuo5byr9+yavPMLff5xC9bP8qjMgPob9yEZMIYvRD4fyCow/1hDbr9yBGbJyDBqsqWuZRP5Poe5OvNH5D61BUjwzczFl/sthjAcLn67F5M7/E40ITiEZUfefP1ll2Hm73pOMXBWjlDtjLMu7gQ2BDTBZk6QC4DH+L6bRFfUM28R9UQbP0qn/+sJAzPxDSCAwel2dDKodPc6Yr/TtS6Lq1d4nwcYsuIMGC9B/JpWGbKHde3a6JYh56ZBvK9HaYIn5rwvmHaEXzpsAMtDlTdfL742aOYi3GYD/cKblePZZ8OQjmeYSvVtP3OwaOQxUwDWlS4tm5JaR8+8+yTVW9OCSpH/kLvWCqF54fz3COCQL2D8MFxabfHexbqUVpeYUEcrWZXe3R1duGqTdlI0o8q4NKUqRZcze7c2GUQwfowTblj3GZNp7Q0UHicJZF1DOx+G/DazhSJEJF9+QIBSChRAudyNOs97VA4iEAm00fIbZsFrwdKyelRbfhZEPvhdMnzMjtt7pP425hKZMHBj7BsaIJDJYG28WP85CPuL5JwVUccjZ8W7ORo/K0VBmeTkJxyUr2fKXZZ6oomqrR9W1ZeTgGL5+BduMRXM30jV/XbhCl6xlDYU1GqqDXB4dX3g+FXDh5fUVi6J4rBD2DgRtAB5LyV61E6JUjoZasv1PVR1TK++w5wS132dcaQhtxomw9eR6wccVcW+gKw7mIoej6nAQ8/k0tf3InCT/0Stvtqx/1zI9rG9IMx4kR2VE6Fpi3v+tUOnoe3+vTkihRkzzSdvdMj/VfifGbHKgh48Nzfses3MhO/kbpVZML7o1jDX57Vrn0d3rlidRROzfX0PzAccBsKHl3Ye2/b0QEuBZ2eibL4zoFF641l2FPrhHo3A+Xe6eMD7lcbya67IrcMDrVmMms3DPVHoGJZLeQRQHnt5qOxDvnai7n9jGcRerDFI1DT/cF5720pjoN5vEPPfWKKuzu4/YmMmEGzy6azokP8v7tyD5XqcZlA/gJCXsgF155Mxs+ADYD5GUaFvb74fhPwv+l3PNP7bmfZkvRgfyfbMsoHhrd31h4nGvM5YNmBbBiifFR2frBjJnhbO37073p7p7JGKyaLKr0G6v7qZulVYJgiIa/9sCLigchJv3okmIlhdIHWWRxMjIJVIs17TFMTXM8KqHsr3DoaUp8bNrzUISotoIAn4KGSiRb9jmEzM7+QDzL1GAWHPpbMYNBqDnWfRaC9qsvYisojpwywiTtCqOjkaM/oQe5B0EIujuPVYHaLlGLdDwoJBRQ5vrqVljrfkfH6T4M3ljCzgJI7YMjUMBNV7HyymFjWsTRCyaQG/cbTfX5K2t48sBNLO0AO1kIKEtQX1JZqPJbGaFJ8UvSxDt+13Q7eiJL4ZKmijaDVej9NpLOAvxRvmdUKCVz7NBXTSlRMcpzVoe+ISiS7gNr0CqdkdsQySGvGJqCFgkHZHEIVoMr+xTm4inzlmqvYW4tfV8QVZmHdd/ls1M1u+6X3GrR9wtHna5gz/Q5Wtf1z9JdtpEI8KtmZkVuccpELuKuInFrOzG9b7nP/7ZUOzQz9gHt8zvDiMdi0CoRLM6ADuYX6TBl7Fs+I3rOH+q+dxz/+K/+tl3MuX8UDFEUk+WVbtB9wCpUael+kbcGwkMiCGqfwUv4DIwxx8A/IygS1fXRrmoaj/E3wrUhmTCUV/Wo4yBEUqmIbQ4c+fnbazp+hodGJjEZNqQNpYfGQfyK0hEjMziUR8AYVyEYUSA+x5kSlK5fy/HeAB3etAOsC2n60baRstuGvQZZ6CPPtCyszIBl/jdA29LB391xq5O/fk7d2bn2Bv8X6lOSQH/rlMz6rvTDPj+tmtnQbOpORw1x0gGiRxZbV1g5wECKUOJUID3E2buAMgQVUFJHCldbUy7uQQ91eL+E/NU1AaNfrxqX8ENmWxMa9OPabyoHWzKI5N6efpjAmoUf8935qCVaXLnIHd4dBWSkRv7vEZ1/DFYyGFU8cDII+OR2HmtPu7+6HkkrM1/EK/NGyHexopyZsZNQ971OFeMDkTCLl3XA13pd+XDkBrqJFbK2Q+d1Yu+Db7mBod0vnAJc+A/ykixSXT/9Nqnuf6IC7FWbTjgVmeQarLszpn+n3ST829l/5rnIFCMLEwoShrKAtMgpPhpKSgZkLyZDKh+YwCyhRA6TOH+f79EfTk+9xrFGg8s+hDX7+Ohq+vA+RVH5gdg3Zf7S3cc6L+fU1V81ZjhHon/KFJfzrGfHHGyNvTz9fJj5xlPNtfDvibQ+0K0VH79u/7r2zxQtOE4vgEelZoWGh0tKNWEq379tdi4MHE+q34vel/5GyT7pXYlZ7oR7GParUv/yK32NpY45iY2hjgjkgsmizuOTU9b+primpilvQU7F5r6Xelqi1npP9LIi30SiBQN2bXPa5TMbZxe+xGzP876u/qJwewuTcicWfj1vKt4temPPWm0b6+wGiP8bWAAJ2/T2zLv8bEnFx989baW38rZw248t6+/aT0G5XZatLOaH93ac2lrIV1tSP+h9Ydunfibi1SgvTeJdSbRrtqE7QvASaanXFrYLPKMVLz90WiAzS+A7pz7mL7v68L/ru8nXu5ZI43XoK1bx7j/ntssw6lkjTWg758Gd1DPk7eg3ZONzj11Swi7VvGJhPuHJpJ7fA7eMpvbEq6kpTUSDDhsaNEP3+2R7N3ndCY5PCUpsbVptmcjv//7+Cwsb7Ezo1uG2mpXLvrP35cZ3I37qdt5DJfHnA7biqtwA38M1ACwEUrDSZtKPhmNnDMMhvYj3Axbr7o0rb1dQYlAs9HGjX/mNr3ttl9XkPf0ZnXXHsHmJb+H+9HOqLCTb+Ex0KSk0OS7jrEGkjKfBPkdsmSMXZXl5ERXH3QcanRQQqobZggT1RunmCWyejTVzwF2KIoWh9lHHOTHqsgxxTB7tIryZLEh8SQuZbXkDlDLjljHvuSXxqQMlfNcOGNbpzMp+2UHRN9ZYUH4gGFs/zZy7yfPGQP50p1yHj1MTfxogq/6WzHkFt06RWKrQQU4YXuqVL6zg4Qj/v0WFVDN4hw87jl7rWDC4RURQgyza3fz7ziuqq8NKOM76YU9d7PsQXSrLO69pjSAtktP/acU0J0TqdDsuiMPTQJxgry36+U0oULxYambz2nVmKIW7aF1tYkeTyLV4VwsloB2SFi8jzslOyTPUs6tEgkN2/nYB1StlqnbvfH/57H4yfvws4JO3P0jLc8oEbnDYnCvjFmCRMC8Zry6FNkWIQsJVVgxSPDBD2EcRNx0VmyGUMhSgQyhYls0VkxLbtlKlrPM64u3WG1hSbnNSqEm3LuvGGZLKbxK2yngiUKWg5I+zy3RvZts4CwV6I9LqNWxvr3uhy3nI2YylhwmrJ7GJ17DMfWjr1gnhs2kekBccsyr8l5Y44OuYTv/rBe/iG+AHSBeY/dTSQXa9sEprTVMJGIuXI52Bt7FvJAeaCNcr6iKjALozIP7dtHHfmP25zgyhA2oKiRnKRpv0cZhzD98tMAaTsZBHKOUC4vG8VeFRfGyakdxvxyTFtlnJd4eHKIZIcIlg/BvmRCSx56xl+qz3sBIV7K60ma7Bk2Di2zXR5VQOOxG7wTsEluzB7teVx7Rm6Eqw6pwoUJvgK1AddoZVs9PGNJd5zlYBOND5ibDtrIdj+Paxby0MWyQVprFdV4dTKImf+wYvOwQRMZD62jFJExfIWoqmR6hXmPPfYv9Sii6Psqoif8Aclfr/NUZFKrx8p1Zue4akEWhImREGnpqt5TjCc7Ro05+wTtpSngMe7/FOXRbQ1isgHi2XvN3LNYbMOxXfeV9IhSP4wt9YeskBWys9gC3gXpcZAJLWcCqfNCcSn78ubxcflsHnMT4hE8VJX5ZIirbMviCoz6c9+WGg8IfjY4+l8LtETsfmEIrfxL6Q87MXgv3GhDxOPrS3piD2MgzdwAmT15jQWZsgwtG8L6jxHdPb+ap09yT69vo5GDWwcT+CdUWi8J6UaiLIMb/6eHlFyU4PrduxNeIqFvvrG8T7aW/ftFAIQbmP/fsRLOjUL+UYL0TxryX//0S4f/WRdgX8XoNQmEvsYbAshQ+VrHf5pqbyNPXZ/UlBt9kjKD57szJW13R2XtuXxH990FVfrvLioburtSN4Enr9JYsSjkFeiqcbI7aODY7kyto7ujBq5x+Y4nuwua+X93UYPguyuNDdQvQpWOYXrSPRSgCIKwRjSPQcaA3fHgL1Cbo+Xg8Xf9Qal6H5mH6frACwQoItrUXS2IksgSPXmenB44F0kq0QDHYUVMt+MoozYx8OhvuocCFEEQ1j6vqHkM8raxu/me/wK1OVoSqm6v+Ael6redzMPEwb3QwFUVSnHd1YJUl+R9bImePFMd3GsmkhTdygDHYc2RSrcjnUzy0qF65sde2vnGe7nlv6bp/5rqTW5r7/i/Ux3W9f/ygnMg/AFPJDle6O3rHxgcGh4ZBUAIRlAMJ8i/62INDMvxgijJyr9+4H92umFatuN6fhBGcZJmeVFWddN2/TBO87Ju+3Fe9/N+PwjBCIrhBEnRDMvxgijJiqrphmnZjuv5QRjFSZrlRVnVTdv1wzjNy7rtx+P5en++vz8EIyiGEyRFMyzHC6IkK6r2V5B+1TQt23E9PwijOEmzvCirumm7fhineVm3/Tiv+3k/oCgh9KI+1n7LSk03TMt2XM+HYATlcHl8gVAklkgxnCApmpHJFUqVWqM1NDI2MTULJqXcOrWQyGm5UR1ONt5+/ORW3ZVf3VPtPsYt8aGwhmOEdPTY8ZK4HuKckVwRMUh6VMxwktFzwzPfRcw1JFyya8UJL9pB3ILc0HrjXktqGL1dbLL3PqupN10M3rAYx3aVPGDlyPKAuNLAHeBoGkMoIS1TMFGx7aUjzUukRw9Sb1W+nEXFTRw5SlyVJZnrmJI7slaoqhbSk+FshbzWehtIGpKqgZVVUj1tLO5Y7yTv15I4TyoMxypF+1r9YYvJxNjWB7VDYeDDqnpOteJ6iwYbJBfaWDw7oR4kQa2oysUX0BiJ16tSGnqkTk+WyXpI65mUXWdsUDucWy+YWAYVN0PSdfRCTRFQukgP4n+uxa4kpUcKmjNIhxJvn2f0vHqMbEhbk1MFFQrBt1WUjAlpTtHVGxE/qg0c1dUki38aa7V+A0bizqGQmckx59Nn6ErhEl2ANF+IuGCnEnoK7L1b+MK1t71YlSn+gO7b2g8c4oqvEehY3H7z1LU8Z4IdZpqQR+I+9V7UnG7CkCxqz0Vdbxg4IzkuJUtbZacGa2Hfk+NOkRXv4yO6mPCKMDq246RaE3iGZPhWiZWLnogNNMnO/nrqrNeZ6l1TlgJwp2ElizMV55erxwx6o0XAM5EMhGxT9DBZbSvmSowzJCeWpBBw1Leez7HxCYknLTG5SGdwavkqQEdYouuVqvqldvikP35erjrlySxoLLUGeBIPuZGyDSMpQd7dhCfGSq62dJlqST9QJEhOz2oTxj2Oa+nBrcfxagOSAHGtvyoicVnvvE3jd0KeokVQW00X7PqS1I4qAEQ5fdorGrauJq6rBy/SbaBlDAG2K5FzYDBCesz5FNcaeVJkR+JLv2RJA3vqbKbVe1cCPhKrJ4mgxysU691h3KR70EqViU0pl3KyDg9YvjqDNCr3Uh2VqyQLEQ94qSzJfX/Id32uaZ3e3X4bvbXeklNJD35adqQU+P6AbR6vP2zuz/9uXo6fN++3XzYfl1/yI1g9HI8esYq4zrT7SJ1THFgJBwaBL2q9kbwIPrZ57pR2KBXsYwwhl5HVBv+MlTC2E1Qp+K2A6YFwoRqtFtCDO3qxudj+KTgqCQs0pFVdG03zDM4gLS6xNrRYoDSD5PDWg1KxGu1XteXQKpaZTj4jqLjVI2pr3pCkU+rytqUncReSwVAqdMTlYZx/bKwkcY3GEVIkBFRpCvbpQe7TzinRJBhoS1lM5E66eu5gB3Fpv5fk5J9vueXUCl72hpEHI5S1JK03Rsywhc+g7LWKJ926kYW2/3z6mYiXZpNpPkkD0qjez0pSiUFDR2tPikuZMwmTOByBrRHL9BXUONJlQU5Gq4svbcEIfdfJqk7WGRIDScuPUXphpA7rMRpJtBZlWOYwRThqdOTsWFxWXW7Y9RjFAwH5y1K/o7eGYnmjbaLeODnGQZEkgyjigUQXWBuODsP8FeaQzZH48qP3JC52LmoPbJhuoxI2H8f/6VAPxFBrlWFvzSe96K5pjh0cohcZRug6LV8ELbb+Pz6u2yg5haDUiWcWN3oUOMQhZZpk6yOt2q+/mpZl5AH1COMFjMkNatHJMhXLD4RnLMvgyGQN9sofKA5nkBjvJLqVrh5bFIFjDEjFgxk2P60GJYZ2HaOlvj/pxg8EUjmUCAw7NBTqW8VrRnYYMS03RZGMXEnSL+q0psTig65ojNLTTErzC1xwuMyWKkSeIDuc7U64ggujazUMjxGELBd787axJFmjmDtKLwI6wo2SYtB1Xg9qbUcFqcEmJCWLHLSYUXgMB1QLYwYhQsjdP4ND0e9pIRk5udTK0IMSy3PA/CSP88DRYnQuIU4R318njRFIyoc05IxYoRqkuBXiq/BGEqPqbIpGPzpbVFmDuqDMeJ4CX/SMkaNm8FXNLlc2C1MYAdvUctVtcYjpvBbCtotcHkgwSHaCLCnkg61FgtrNlY64NvbcAyVQfszGRM4vHQbCrlatpSKAlpONnKXom2x31np8tdivNWkYV/SyRpJCYU71TmxrN5bwyek/2ytvFOG7vzfggpYCVK4Yg2sWOqznEaNkYvGkBTeIcO0dh/31aeZvx+eJ6XX1kKLUxTw441ZO0rJqDBD2Uj5DhjXnXG09BSTzpNfeJ+ZZBC+yk/mOAZvEhBd9+j6MFAO91fEzsxSNO1J0D0QDqTSwa8TK37b0/dQpq/8x8E3oxvEzk2mESvZ9uCAgHG2vr/Rb/XwDAAAA') format('woff2'), - url('iconfont.woff?t=1567498326614') format('woff'), - url('iconfont.ttf?t=1567498326614') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ - url('iconfont.svg?t=1567498326614#iconfont') format('svg'); /* iOS 4.1- */ -} - -.iconfont { - font-family: "iconfont" !important; - font-size: 16px; - font-style: normal; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -.icon-logout:before { - content: "\e838"; -} - -.icon-facebook:before { - content: "\e645"; -} - -.icon-icons-google_groups:before { - content: "\ee07"; -} - -.icon-youtube:before { - content: "\e733"; -} - -.icon-tiaoshi:before { - content: "\eb61"; -} - -.icon-changjingguanli:before { - content: "\eb62"; -} - -.icon-bianji:before { - content: "\eb63"; -} - -.icon-guanlianshebei:before { - content: "\eb64"; -} - -.icon-guanfangbanben:before { - content: "\eb65"; -} - -.icon-gongnengdingyi:before { - content: "\eb66"; -} - -.icon-jichuguanli:before { - content: "\eb67"; -} - -.icon-jishufuwu:before { - content: "\eb68"; -} - -.icon-hezuohuobanmiyueguanli:before { - content: "\eb69"; -} - -.icon-ceshishenqing:before { - content: "\eb6a"; -} - -.icon-jiedianguanli:before { - content: "\eb6b"; -} - -.icon-jinggao:before { - content: "\eb6c"; -} - -.icon-peiwangyindao:before { - content: "\eb6d"; -} - -.icon-renjijiaohu:before { - content: "\eb6e"; -} - -.icon-shiyongwendang:before { - content: "\eb6f"; -} - -.icon-quanxianshenpi:before { - content: "\eb70"; -} - -.icon-yishouquan:before { - content: "\eb71"; -} - -.icon-tianshenpi:before { - content: "\eb72"; -} - -.icon-shujukanban:before { - content: "\eb73"; -} - -.icon-yingyongguanli:before { - content: "\eb74"; -} - -.icon-yibiaopan:before { - content: "\eb75"; -} - -.icon-zhanghaoquanxianguanli:before { - content: "\eb76"; -} - -.icon-yuanquyunwei:before { - content: "\eb77"; -} - -.icon-slack:before { - content: "\e641"; -} - -.icon-jizhanguanli:before { - content: "\eb78"; -} - -.icon-gongju:before { - content: "\e600"; -} - -.icon-guanbi:before { - content: "\eb79"; -} - -.icon-zidingyi:before { - content: "\eb7a"; -} - -.icon-xiajiantou:before { - content: "\eb7b"; -} - -.icon-shangjiantou:before { - content: "\eb7c"; -} - -.icon-icon_loading:before { - content: "\eb80"; -} - -.icon-icon_renwujincheng:before { - content: "\eb88"; -} - -.icon-icon_rukou:before { - content: "\eb89"; -} - -.icon-icon_yiwenkongxin:before { - content: "\eb8a"; -} - -.icon-icon_fabu:before { - content: "\eb8b"; -} - -.icon-icon_tianjia:before { - content: "\eb8c"; -} - -.icon-icon_yulan:before { - content: "\eb8d"; -} - -.icon-icon_zhanghao:before { - content: "\eb8e"; -} - -.icon-icon_wangye:before { - content: "\eb8f"; -} - -.icon-icon_shezhi:before { - content: "\eb90"; -} - -.icon-icon_baocun:before { - content: "\eb91"; -} - -.icon-icon_yingyongguanli:before { - content: "\eb92"; -} - -.icon-icon_shiyongwendang:before { - content: "\eb93"; -} - -.icon-icon_bangzhuwendang:before { - content: "\eb94"; -} - -.icon-biaodanzujian-shurukuang:before { - content: "\eb95"; -} - -.icon-biaodanzujian-biaoge:before { - content: "\eb96"; -} - -.icon-biaodanzujian-xialakuang:before { - content: "\eb97"; -} - -.icon-tubiao-bingtu:before { - content: "\eb98"; -} - -.icon-biaodanzujian-anniu:before { - content: "\eb99"; -} - -.icon-gongyezujian-yibiaopan:before { - content: "\eb9a"; -} - -.icon-tubiao-qiapian:before { - content: "\eb9b"; -} - -.icon-gongyezujian-zhishideng:before { - content: "\eb9c"; -} - -.icon-tubiao-zhexiantu:before { - content: "\eb9d"; -} - -.icon-xingzhuang-juxing:before { - content: "\eb9e"; -} - -.icon-xingzhuang-jianxing:before { - content: "\eb9f"; -} - -.icon-gongyezujian-kaiguan:before { - content: "\eba0"; -} - -.icon-tubiao-zhuzhuangtu:before { - content: "\eba1"; -} - -.icon-xingzhuang-tupian:before { - content: "\eba2"; -} - -.icon-xingzhuang-wenzi:before { - content: "\eba3"; -} - -.icon-xingzhuang-tuoyuanxing:before { - content: "\eba4"; -} - -.icon-xingzhuang-sanjiaoxing:before { - content: "\eba5"; -} - -.icon-xingzhuang-xingxing:before { - content: "\eba6"; -} - -.icon-guize:before { - content: "\ebb7"; -} - -.icon-shebeiguanli:before { - content: "\ebb8"; -} - -.icon-gongnengdingyi1:before { - content: "\ebb9"; -} - -.icon-jishufuwu1:before { - content: "\ebce"; -} - -.icon-yunyingzhongxin:before { - content: "\ebd0"; -} - -.icon-yunyingguanli:before { - content: "\ebd1"; -} - -.icon-zuzhixiaxia:before { - content: "\ebd8"; -} - -.icon-zuzhizhankai:before { - content: "\ebd9"; -} - -.icon-zuzhiqunzu:before { - content: "\ebda"; -} - -.icon-dakai:before { - content: "\ebdf"; -} - -.icon-yingwen:before { - content: "\ebe0"; -} - -.icon-zhongwen:before { - content: "\ebe2"; -} - -.icon-miwen:before { - content: "\ebe3"; -} - -.icon-xianhao:before { - content: "\ebe4"; -} - -.icon-kongxinduigou:before { - content: "\ebe5"; -} - -.icon-huixingzhen:before { - content: "\ebe6"; -} - -.icon-duigou:before { - content: "\ebe7"; -} - -.icon-stack-overflow:before { - content: "\e970"; -} - -.icon-xiayibu:before { - content: "\ebef"; -} - -.icon-shangyibu:before { - content: "\ebf0"; -} - -.icon-kongjianxuanzhong:before { - content: "\ebf1"; -} - -.icon-kongjianweixuan:before { - content: "\ebf2"; -} - -.icon-kongjianyixuan:before { - content: "\ebf3"; -} - -.icon--diangan:before { - content: "\ebfb"; -} - -.icon-rongxuejirongjiechi:before { - content: "\ebfc"; -} - -.icon-lubiantingchechang:before { - content: "\ebfd"; -} - -.icon--lumingpai:before { - content: "\ebfe"; -} - -.icon-jietouzuoyi:before { - content: "\ebff"; -} - -.icon--zhongdaweixian:before { - content: "\ec00"; -} - -.icon--jiaotongbiaozhipai:before { - content: "\ec01"; -} - -.icon-gongcezhishipai:before { - content: "\ec02"; -} - -.icon-fangkuai:before { - content: "\ec06"; -} - -.icon-fangkuai-:before { - content: "\ec07"; -} - -.icon-shuaxin:before { - content: "\ec08"; -} - -.icon-baocun:before { - content: "\ec09"; -} - -.icon-fabu:before { - content: "\ec0a"; -} - -.icon-xiayibu1:before { - content: "\ec0b"; -} - -.icon-shangyibu1:before { - content: "\ec0c"; -} - -.icon-xiangxiazhanhang:before { - content: "\ec0d"; -} - -.icon-xiangshangzhanhang:before { - content: "\ec0e"; -} - -.icon-tupianjiazaishibai:before { - content: "\ec0f"; -} - -.icon-fuwudiqiu:before { - content: "\ec10"; -} - -.icon-suoxiao:before { - content: "\ec13"; -} - -.icon-fangda:before { - content: "\ec14"; -} - -.icon-huanyuanhuabu:before { - content: "\ec15"; -} - -.icon-quanping:before { - content: "\ec16"; -} - -.icon-biaodanzujian-biaoge1:before { - content: "\ec17"; -} - -.icon-APIshuchu:before { - content: "\ec18"; -} - -.icon-APIjieru:before { - content: "\ec19"; -} - -.icon-wenjianjia:before { - content: "\ec1a"; -} - -.icon-DOC:before { - content: "\ec1b"; -} - -.icon-BMP:before { - content: "\ec1c"; -} - -.icon-GIF:before { - content: "\ec1d"; -} - -.icon-JPG:before { - content: "\ec1e"; -} - -.icon-PNG:before { - content: "\ec1f"; -} - -.icon-weizhigeshi:before { - content: "\ec20"; -} - -.icon-gengduo:before { - content: "\ec21"; -} - -.icon-yunduanxiazai:before { - content: "\ec22"; -} - -.icon-yunduanshangchuan:before { - content: "\ec23"; -} - -.icon-dian:before { - content: "\ec24"; -} - -.icon-mian:before { - content: "\ec25"; -} - -.icon-xian:before { - content: "\ec26"; -} - -.icon-shebeizhuangtai:before { - content: "\ec27"; -} - -.icon-fenzuguanli:before { - content: "\ec28"; -} - -.icon-kuaisubianpai:before { - content: "\ec29"; -} - -.icon-APPkaifa:before { - content: "\ec2a"; -} - -.icon-wentijieda:before { - content: "\ec2e"; -} - -.icon-kefu:before { - content: "\ec2f"; -} - -.icon-ruanjiankaifabao:before { - content: "\ec30"; -} - -.icon-sousuobianxiao:before { - content: "\ec32"; -} - -.icon-sousuofangda:before { - content: "\ec33"; -} - -.icon-dingwei:before { - content: "\ec34"; -} - -.icon-wumoxing:before { - content: "\ec35"; -} - -.icon-gaojing:before { - content: "\ec36"; -} - -.icon-renwujincheng:before { - content: "\ec37"; -} - -.icon-xiaoxitongzhi:before { - content: "\ec38"; -} - -.icon-youhui:before { - content: "\ec39"; -} - -.icon-gaojing1:before { - content: "\ec3a"; -} - -.icon-zhihangfankui:before { - content: "\ec3b"; -} - -.icon-gongdanqueren:before { - content: "\ec3c"; -} - -.icon-guangbo:before { - content: "\ec3d"; -} - -.icon-gongdan:before { - content: "\ec3e"; -} - -.icon-xiaoxi:before { - content: "\ec3f"; -} - -.icon-ditu-qi:before { - content: "\ec40"; -} - -.icon-ditu-dibiao:before { - content: "\ec41"; -} - -.icon-ditu-cha:before { - content: "\ec42"; -} - -.icon-ditu-qipao:before { - content: "\ec43"; -} - -.icon-ditu-tuding:before { - content: "\ec44"; -} - -.icon-ditu-huan:before { - content: "\ec45"; -} - -.icon-ditu-xing:before { - content: "\ec46"; -} - -.icon-ditu-yuan:before { - content: "\ec47"; -} - -.icon-chehuisekuai:before { - content: "\ec48"; -} - -.icon-shanchusekuai:before { - content: "\ec49"; -} - -.icon-fabusekuai:before { - content: "\ec4a"; -} - -.icon-xinhao:before { - content: "\ec4b"; -} - -.icon-lanya:before { - content: "\ec4c"; -} - -.icon-Wi-Fi:before { - content: "\ec4d"; -} - -.icon-chaxun:before { - content: "\ec4e"; -} - -.icon-dianbiao:before { - content: "\ec4f"; -} - -.icon-anquan:before { - content: "\ec50"; -} - -.icon-daibanshixiang:before { - content: "\ec51"; -} - -.icon-bingxiang:before { - content: "\ec52"; -} - -.icon-fanshe:before { - content: "\ec53"; -} - -.icon-fengche:before { - content: "\ec54"; -} - -.icon-guandao:before { - content: "\ec55"; -} - -.icon-guize1:before { - content: "\ec56"; -} - -.icon-guizeyinqing:before { - content: "\ec57"; -} - -.icon-huowudui:before { - content: "\ec58"; -} - -.icon-jianceqi:before { - content: "\ec59"; -} - -.icon-jinggai:before { - content: "\ec5a"; -} - -.icon-liujisuan:before { - content: "\ec5b"; -} - -.icon-hanshu:before { - content: "\ec5c"; -} - -.icon-lianjieliu:before { - content: "\ec5d"; -} - -.icon-ludeng:before { - content: "\ec5e"; -} - -.icon-shexiangji:before { - content: "\ec5f"; -} - -.icon-rentijiance:before { - content: "\ec60"; -} - -.icon-moshubang:before { - content: "\ec61"; -} - -.icon-shujuwajue:before { - content: "\ec62"; -} - -.icon-wangguan:before { - content: "\ec63"; -} - -.icon-shenjing:before { - content: "\ec64"; -} - -.icon-chucun:before { - content: "\ec65"; -} - -.icon-wuguan:before { - content: "\ec66"; -} - -.icon-yunduanshuaxin:before { - content: "\ec67"; -} - -.icon-yunhang:before { - content: "\ec68"; -} - -.icon-luyouqi:before { - content: "\ec69"; -} - -.icon-bug:before { - content: "\ec6a"; -} - -.icon-get:before { - content: "\ec6b"; -} - -.icon-PIR:before { - content: "\ec6c"; -} - -.icon-zhexiantu:before { - content: "\ec6d"; -} - -.icon-shuibiao:before { - content: "\ec6e"; -} - -.icon-js:before { - content: "\ec6f"; -} - -.icon-zihangche:before { - content: "\ec70"; -} - -.icon-liebiao:before { - content: "\ec71"; -} - -.icon-qichedingwei:before { - content: "\ec72"; -} - -.icon-dici:before { - content: "\ec73"; -} - -.icon-mysql:before { - content: "\ec74"; -} - -.icon-qiche:before { - content: "\ec75"; -} - -.icon-shenjing1:before { - content: "\ec76"; -} - -.icon-chengshi:before { - content: "\ec77"; -} - -.icon-tixingshixin:before { - content: "\ec78"; -} - -.icon-menci:before { - content: "\ec79"; -} - -.icon-chazuo:before { - content: "\ec7a"; -} - -.icon-ranqijianceqi:before { - content: "\ec7b"; -} - -.icon-kaiguan:before { - content: "\ec7c"; -} - -.icon-chatou:before { - content: "\ec7d"; -} - -.icon-xiyiji:before { - content: "\ec7e"; -} - -.icon-yijiankaiguan:before { - content: "\ec7f"; -} - -.icon-yanwubaojingqi:before { - content: "\ec80"; -} - -.icon-wuxiandianbo:before { - content: "\ec81"; -} - -.icon-fuzhi:before { - content: "\ec82"; -} - -.icon-tuite:before { - content: "\e615"; -} - -.icon-shanchu:before { - content: "\ec83"; -} - -.icon-bianjisekuai:before { - content: "\ec84"; -} - -.icon-ishipinshixiao:before { - content: "\ec85"; -} - -.icon-iframetianjia:before { - content: "\ec86"; -} - -.icon-tupiantianjia:before { - content: "\ec87"; -} - -.icon-liebiaomoshi_kuai:before { - content: "\ec88"; -} - -.icon-qiapianmoshi_kuai:before { - content: "\ec89"; -} - -.icon-fenlan:before { - content: "\ec8a"; -} - -.icon-fengexian:before { - content: "\ec8b"; -} - -.icon-dianzan:before { - content: "\ec8c"; -} - -.icon-charulianjie:before { - content: "\ec8d"; -} - -.icon-charutupian:before { - content: "\ec8e"; -} - -.icon-quxiaolianjie:before { - content: "\ec8f"; -} - -.icon-wuxupailie:before { - content: "\ec90"; -} - -.icon-juzhongduiqi:before { - content: "\ec91"; -} - -.icon-yinyong:before { - content: "\ec92"; -} - -.icon-youxupailie:before { - content: "\ec93"; -} - -.icon-youduiqi:before { - content: "\ec94"; -} - -.icon-zitidaima:before { - content: "\ec95"; -} - -.icon-xiaolian:before { - content: "\ec96"; -} - -.icon-zitijiacu:before { - content: "\ec97"; -} - -.icon-zitishanchuxian:before { - content: "\ec98"; -} - -.icon-zitishangbiao:before { - content: "\ec99"; -} - -.icon-zitibiaoti:before { - content: "\ec9a"; -} - -.icon-zitixiahuaxian:before { - content: "\ec9b"; -} - -.icon-zitixieti:before { - content: "\ec9c"; -} - -.icon-zitiyanse:before { - content: "\ec9d"; -} - -.icon-zuoduiqi:before { - content: "\ec9e"; -} - -.icon-zitiyulan:before { - content: "\ec9f"; -} - -.icon-zitixiabiao:before { - content: "\eca0"; -} - -.icon-zuoyouduiqi:before { - content: "\eca1"; -} - -.icon-tianxie:before { - content: "\eca2"; -} - -.icon-huowudui1:before { - content: "\eca3"; -} - -.icon-yingjian:before { - content: "\eca4"; -} - -.icon-shebeikaifa:before { - content: "\eca5"; -} - -.icon-dianzan_kuai:before { - content: "\eca6"; -} - -.icon-zhihuan:before { - content: "\eca7"; -} - -.icon-tuoguan:before { - content: "\eca8"; -} - -.icon-duigoux:before { - content: "\eca9"; -} - -.icon-guanbi1:before { - content: "\ecaa"; -} - -.icon-aixin_shixin:before { - content: "\ecab"; -} - -.icon-ranqixieloubaojingqi:before { - content: "\ecac"; -} - -.icon-dianbiao_shiti:before { - content: "\ecad"; -} - -.icon-aixin:before { - content: "\ecae"; -} - -.icon-shuibiao_shiti:before { - content: "\ecaf"; -} - -.icon-zhinengxiaofangshuan:before { - content: "\ecb0"; -} - -.icon-ranqibiao_shiti:before { - content: "\ecb1"; -} - -.icon-shexiangtou_shiti:before { - content: "\ecb2"; -} - -.icon-shexiangtou_guanbi:before { - content: "\ecb3"; -} - -.icon-shexiangtou:before { - content: "\ecb4"; -} - -.icon-shengyin_shiti:before { - content: "\ecb5"; -} - -.icon-shengyinkai:before { - content: "\ecb6"; -} - -.icon-shoucang_shixin:before { - content: "\ecb7"; -} - -.icon-shoucang:before { - content: "\ecb8"; -} - -.icon-shengyinwu:before { - content: "\ecb9"; -} - -.icon-shengyinjingyin:before { - content: "\ecba"; -} - -.icon-zhunbeiliangchan:before { - content: "\ecbb"; -} - -.icon-shebeikaifa1:before { - content: "\ecbc"; -} - -.icon-document-circle:before { - content: "\e6b8"; -} - -.icon-git:before { - content: "\e64a"; -} - -.icon-Notificationlisttongzhiliebiao:before { - content: "\e782"; -} - -.icon-kongxinwenhao:before { - content: "\ed19"; -} - -.icon-cuowukongxin:before { - content: "\ed1a"; -} - -.icon-fangkuai1:before { - content: "\ed1b"; -} - -.icon-fangkuai2:before { - content: "\ed1c"; -} - -.icon-kongjianxuanzhong1:before { - content: "\ed1d"; -} - -.icon-kongxinduigou1:before { - content: "\ed1e"; -} - -.icon-xinxikongxin:before { - content: "\ed1f"; -} - -.icon-kongjian:before { - content: "\ed20"; -} - -.icon-gaojingkongxin:before { - content: "\ed21"; -} - -.icon-duigou_kuai:before { - content: "\ed22"; -} - -.icon-cuocha_kuai:before { - content: "\ed23"; -} - -.icon-jia_sekuai:before { - content: "\ed24"; -} - -.icon-jian_sekuai:before { - content: "\ed25"; -} - -.icon-fenxiangfangshi:before { - content: "\ed2e"; -} - -.icon-i18n:before { - content: "\e614"; -} - -.icon-gongju1:before { - content: "\e637"; -} - -.icon-bangzhu:before { - content: "\e638"; -} - -.icon-xitong:before { - content: "\e639"; -} - -.icon-guanli:before { - content: "\e63a"; -} - -.icon-jiankong:before { - content: "\e63b"; -} - -.icon-guize2:before { - content: "\e63c"; -} - -.icon-arrow:before { - content: "\e63d"; -} - -.icon-systemname:before { - content: "\e63e"; -} - -.icon-version:before { - content: "\e63f"; -} - -.icon-Systemtime:before { - content: "\e640"; -} - -.icon-uptime:before { - content: "\e642"; -} - -.icon-in:before { - content: "\e643"; -} - diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.eot b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.eot deleted file mode 100644 index 0ddb250fc1..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.eot and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.js deleted file mode 100644 index 801ac40095..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.js +++ /dev/null @@ -1 +0,0 @@ -!function(v){var a,l='',h=(a=document.getElementsByTagName("script"))[a.length-1].getAttribute("data-injectcss");if(h&&!v.__iconfont__svg__cssinject__){v.__iconfont__svg__cssinject__=!0;try{document.write("")}catch(a){console&&console.log(a)}}!function(a){if(document.addEventListener)if(~["complete","loaded","interactive"].indexOf(document.readyState))setTimeout(a,0);else{var h=function(){document.removeEventListener("DOMContentLoaded",h,!1),a()};document.addEventListener("DOMContentLoaded",h,!1)}else document.attachEvent&&(c=a,i=v.document,o=!1,(z=function(){try{i.documentElement.doScroll("left")}catch(a){return void setTimeout(z,50)}l()})(),i.onreadystatechange=function(){"complete"==i.readyState&&(i.onreadystatechange=null,l())});function l(){o||(o=!0,c())}var c,i,o,z}(function(){var a,h;(a=document.createElement("div")).innerHTML=l,l=null,(h=a.getElementsByTagName("svg")[0])&&(h.setAttribute("aria-hidden","true"),h.style.position="absolute",h.style.width=0,h.style.height=0,h.style.overflow="hidden",function(a,h){h.firstChild?function(a,h){h.parentNode.insertBefore(a,h)}(a,h.firstChild):h.appendChild(a)}(h,document.body))})}(window); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.svg b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.svg deleted file mode 100644 index bb47f2b065..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.svg +++ /dev/null @@ -1,941 +0,0 @@ - - - - - -Created by iconfont - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.ttf b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.ttf deleted file mode 100644 index e0772f2bce..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.ttf and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.woff b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.woff deleted file mode 100644 index b0bae09a57..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.woff and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.woff2 b/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.woff2 deleted file mode 100644 index 538f1da1c3..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/css/iconfont.woff2 and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/editor.worker.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/editor.worker.js deleted file mode 100644 index b596dd49a1..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/editor.worker.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/",n(n.s="/p8O")}({"/p8O":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=new(function(){function e(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(function(){if(e.stack)throw new Error(e.message+"\n\n"+e.stack);throw e},0)}}return e.prototype.emit=function(e){this.listeners.forEach(function(t){t(e)})},e.prototype.onUnexpectedError=function(e){this.unexpectedErrorHandler(e),this.emit(e)},e.prototype.onUnexpectedExternalError=function(e){this.unexpectedErrorHandler(e)},e}());function i(e){u(e)||r.onUnexpectedError(e)}function o(e){return e instanceof Error?{$isError:!0,name:e.name,message:e.message,stack:e.stacktrace||e.stack}:e}var s="Canceled";function u(e){return e instanceof Error&&e.name===s&&e.message===s}var a=!1,l="__is_disposable_tracked__";function h(e){if(a&&e&&e!==m.None)try{e[l]=!0}catch(e){}}function c(e){if(!a)return e;var t=new Error("Potentially leaked disposable").stack;return setTimeout(function(){e[l]||console.log(t)},3e3),e}function f(){for(var e=[],t=0;tr?e[a]=o[u++]:u>i?e[a]=o[s++]:t(o[u],o[s])<0?e[a]=o[u++]:e[a]=o[s++]}(t,n,r,s,i,o)}(e,t,0,e.length-1,[]),e}var E=function(){function e(e,t,n,r){this.originalStart=e,this.originalLength=t,this.modifiedStart=n,this.modifiedLength=r}return e.prototype.getOriginalEnd=function(){return this.originalStart+this.originalLength},e.prototype.getModifiedEnd=function(){return this.modifiedStart+this.modifiedLength},e}();function S(e){return{getLength:function(){return e.length},getElementAtIndex:function(t){return e.charCodeAt(t)}}}function w(e,t,n){return new T(S(e),S(t)).ComputeDiff(n)}var A,P=function(){function e(){}return e.Assert=function(e,t){if(!e)throw new Error(t)},e}(),M=function(){function e(){}return e.Copy=function(e,t,n,r,i){for(var o=0;o0||this.m_modifiedCount>0)&&this.m_changes.push(new E(this.m_originalStart,this.m_originalCount,this.m_modifiedStart,this.m_modifiedCount)),this.m_originalCount=0,this.m_modifiedCount=0,this.m_originalStart=Number.MAX_VALUE,this.m_modifiedStart=Number.MAX_VALUE},e.prototype.AddOriginalElement=function(e,t){this.m_originalStart=Math.min(this.m_originalStart,e),this.m_modifiedStart=Math.min(this.m_modifiedStart,t),this.m_originalCount++},e.prototype.AddModifiedElement=function(e,t){this.m_originalStart=Math.min(this.m_originalStart,e),this.m_modifiedStart=Math.min(this.m_modifiedStart,t),this.m_modifiedCount++},e.prototype.getChanges=function(){return(this.m_originalCount>0||this.m_modifiedCount>0)&&this.MarkNextChange(),this.m_changes},e.prototype.getReverseChanges=function(){return(this.m_originalCount>0||this.m_modifiedCount>0)&&this.MarkNextChange(),this.m_changes.reverse(),this.m_changes},e}(),T=function(){function e(e,t,n){void 0===n&&(n=null),this.OriginalSequence=e,this.ModifiedSequence=t,this.ContinueProcessingPredicate=n,this.m_forwardHistory=[],this.m_reverseHistory=[]}return e.prototype.ElementsAreEqual=function(e,t){return this.OriginalSequence.getElementAtIndex(e)===this.ModifiedSequence.getElementAtIndex(t)},e.prototype.OriginalElementsAreEqual=function(e,t){return this.OriginalSequence.getElementAtIndex(e)===this.OriginalSequence.getElementAtIndex(t)},e.prototype.ModifiedElementsAreEqual=function(e,t){return this.ModifiedSequence.getElementAtIndex(e)===this.ModifiedSequence.getElementAtIndex(t)},e.prototype.ComputeDiff=function(e){return this._ComputeDiff(0,this.OriginalSequence.getLength()-1,0,this.ModifiedSequence.getLength()-1,e)},e.prototype._ComputeDiff=function(e,t,n,r,i){var o=this.ComputeDiffRecursive(e,t,n,r,[!1]);return i?this.PrettifyChanges(o):o},e.prototype.ComputeDiffRecursive=function(e,t,n,r,i){for(i[0]=!1;e<=t&&n<=r&&this.ElementsAreEqual(e,n);)e++,n++;for(;t>=e&&r>=n&&this.ElementsAreEqual(t,r);)t--,r--;if(e>t||n>r){var o=void 0;return n<=r?(P.Assert(e===t+1,"originalStart should only be one more than originalEnd"),o=[new E(e,0,n,r-n+1)]):e<=t?(P.Assert(n===r+1,"modifiedStart should only be one more than modifiedEnd"),o=[new E(e,t-e+1,n,0)]):(P.Assert(e===t+1,"originalStart should only be one more than originalEnd"),P.Assert(n===r+1,"modifiedStart should only be one more than modifiedEnd"),o=[]),o}var s=[0],u=[0],a=this.ComputeRecursionPoint(e,t,n,r,s,u,i),l=s[0],h=u[0];if(null!==a)return a;if(!i[0]){var c=this.ComputeDiffRecursive(e,l,n,h,i),f=[];return f=i[0]?[new E(l+1,t-(l+1)+1,h+1,r-(h+1)+1)]:this.ComputeDiffRecursive(l+1,t,h+1,r,i),this.ConcatenateChanges(c,f)}return[new E(e,t-e+1,n,r-n+1)]},e.prototype.WALKTRACE=function(e,t,n,r,i,o,s,u,a,l,h,c,f,d,m,p,g,_){var v,y,C=null,b=new O,L=t,N=n,S=f[0]-p[0]-r,w=Number.MIN_VALUE,A=this.m_forwardHistory.length-1;do{(y=S+e)===L||y=0&&(e=(a=this.m_forwardHistory[A])[0],L=1,N=a.length-1)}while(--A>=-1);if(v=b.getReverseChanges(),_[0]){var P=f[0]+1,M=p[0]+1;if(null!==v&&v.length>0){var T=v[v.length-1];P=Math.max(P,T.getOriginalEnd()),M=Math.max(M,T.getModifiedEnd())}C=[new E(P,c-P+1,M,m-M+1)]}else{b=new O,L=o,N=s,S=f[0]-p[0]-u,w=Number.MAX_VALUE,A=g?this.m_reverseHistory.length-1:this.m_reverseHistory.length-2;do{(y=S+i)===L||y=l[y+1]?(d=(h=l[y+1]-1)-S-u,h>w&&b.MarkNextChange(),w=h+1,b.AddOriginalElement(h+1,d+1),S=y+1-i):(d=(h=l[y-1])-S-u,h>w&&b.MarkNextChange(),w=h,b.AddModifiedElement(h+1,d+1),S=y-1-i),A>=0&&(i=(l=this.m_reverseHistory[A])[0],L=1,N=l.length-1)}while(--A>=-1);C=b.getChanges()}return this.ConcatenateChanges(v,C)},e.prototype.ComputeRecursionPoint=function(e,t,n,r,i,o,s){var u,a=0,l=0,h=0,c=0,f=0,d=0;e--,n--,i[0]=0,o[0]=0,this.m_forwardHistory=[],this.m_reverseHistory=[];var m,p,g=t-e+(r-n),_=g+1,v=new Array(_),y=new Array(_),C=r-n,b=t-e,L=e-n,N=t-r,S=(b-C)%2==0;for(v[C]=e,y[b]=t,s[0]=!1,u=1;u<=g/2+1;u++){var w=0,A=0;for(h=this.ClipDiagonalBound(C-u,u,C,_),c=this.ClipDiagonalBound(C+u,u,C,_),m=h;m<=c;m+=2){for(l=(a=m===h||mw+A&&(w=a,A=l),!S&&Math.abs(m-b)<=u-1&&a>=y[m])return i[0]=a,o[0]=l,p<=y[m]&&u<=1448?this.WALKTRACE(C,h,c,L,b,f,d,N,v,y,a,t,i,l,r,o,S,s):null}var P=(w-e+(A-n)-u)/2;if(null!==this.ContinueProcessingPredicate&&!this.ContinueProcessingPredicate(w,this.OriginalSequence,P))return s[0]=!0,i[0]=w,o[0]=A,P>0&&u<=1448?this.WALKTRACE(C,h,c,L,b,f,d,N,v,y,a,t,i,l,r,o,S,s):[new E(++e,t-e+1,++n,r-n+1)];for(f=this.ClipDiagonalBound(b-u,u,b,_),d=this.ClipDiagonalBound(b+u,u,b,_),m=f;m<=d;m+=2){for(l=(a=m===f||m=y[m+1]?y[m+1]-1:y[m-1])-(m-b)-N,p=a;a>e&&l>n&&this.ElementsAreEqual(a,l);)a--,l--;if(y[m]=a,S&&Math.abs(m-C)<=u&&a<=v[m])return i[0]=a,o[0]=l,p>=v[m]&&u<=1448?this.WALKTRACE(C,h,c,L,b,f,d,N,v,y,a,t,i,l,r,o,S,s):null}if(u<=1447){var O=new Array(c-h+2);O[0]=C-h+1,M.Copy(v,h,O,1,c-h+1),this.m_forwardHistory.push(O),(O=new Array(d-f+2))[0]=b-f+1,M.Copy(y,f,O,1,d-f+1),this.m_reverseHistory.push(O)}}return this.WALKTRACE(C,h,c,L,b,f,d,N,v,y,a,t,i,l,r,o,S,s)},e.prototype.PrettifyChanges=function(e){for(var t=0;t0,s=n.modifiedLength>0;n.originalStart+n.originalLength=0;t--){n=e[t],r=0,i=0;if(t>0){var a=e[t-1];a.originalLength>0&&(r=a.originalStart+a.originalLength),a.modifiedLength>0&&(i=a.modifiedStart+a.modifiedLength)}o=n.originalLength>0,s=n.modifiedLength>0;for(var l=0,h=this._boundaryScore(n.originalStart,n.originalLength,n.modifiedStart,n.modifiedLength),c=1;;c++){var f=n.originalStart-c,d=n.modifiedStart-c;if(fh&&(h=m,l=c)}n.originalStart-=l,n.modifiedStart-=l}return e},e.prototype._OriginalIsBoundary=function(e){if(e<=0||e>=this.OriginalSequence.getLength()-1)return!0;var t=this.OriginalSequence.getElementAtIndex(e);return"string"==typeof t&&/^\s*$/.test(t)},e.prototype._OriginalRegionIsBoundary=function(e,t){if(this._OriginalIsBoundary(e)||this._OriginalIsBoundary(e-1))return!0;if(t>0){var n=e+t;if(this._OriginalIsBoundary(n-1)||this._OriginalIsBoundary(n))return!0}return!1},e.prototype._ModifiedIsBoundary=function(e){if(e<=0||e>=this.ModifiedSequence.getLength()-1)return!0;var t=this.ModifiedSequence.getElementAtIndex(e);return"string"==typeof t&&/^\s*$/.test(t)},e.prototype._ModifiedRegionIsBoundary=function(e,t){if(this._ModifiedIsBoundary(e)||this._ModifiedIsBoundary(e-1))return!0;if(t>0){var n=e+t;if(this._ModifiedIsBoundary(n-1)||this._ModifiedIsBoundary(n))return!0}return!1},e.prototype._boundaryScore=function(e,t,n,r){return(this._OriginalRegionIsBoundary(e,t)?1:0)+(this._ModifiedRegionIsBoundary(n,r)?1:0)},e.prototype.ConcatenateChanges=function(e,t){var n=[];if(0===e.length||0===t.length)return t.length>0?t:e;if(this.ChangesOverlap(e[e.length-1],t[0],n)){var r=new Array(e.length+t.length-1);return M.Copy(e,0,r,0,e.length-1),r[e.length-1]=n[0],M.Copy(t,1,r,e.length,t.length-1),r}r=new Array(e.length+t.length);return M.Copy(e,0,r,0,e.length),M.Copy(t,0,r,e.length,t.length),r},e.prototype.ChangesOverlap=function(e,t,n){if(P.Assert(e.originalStart<=t.originalStart,"Left change is not less than or equal to right change"),P.Assert(e.modifiedStart<=t.modifiedStart,"Left change is not less than or equal to right change"),e.originalStart+e.originalLength>=t.originalStart||e.modifiedStart+e.modifiedLength>=t.modifiedStart){var r=e.originalStart,i=e.originalLength,o=e.modifiedStart,s=e.modifiedLength;return e.originalStart+e.originalLength>=t.originalStart&&(i=t.originalStart+t.originalLength-e.originalStart),e.modifiedStart+e.modifiedLength>=t.modifiedStart&&(s=t.modifiedStart+t.modifiedLength-e.modifiedStart),n[0]=new E(r,i,o,s),!0}return n[0]=null,!1},e.prototype.ClipDiagonalBound=function(e,t,n,r){if(e>=0&&e=n?I:{done:!1,value:e[t++]}}}},e.from=function(t){return t?Array.isArray(t)?e.fromArray(t):t:e.empty()},e.map=function(e,t){return{next:function(){var n=e.next();return n.done?I:{done:!1,value:t(n.value)}}}},e.filter=function(e,t){return{next:function(){for(;;){var n=e.next();if(n.done)return I;if(t(n.value))return{done:!1,value:n.value}}}}},e.forEach=function(e,t){for(var n=e.next();!n.done;n=e.next())t(n.value)},e.collect=function(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY);var n=[];if(0===t)return n;for(var r=0,i=e.next();!(i.done||(n.push(i.value),++r>=t));i=e.next());return n},e.concat=function(){for(var e=[],t=0;t=e.length)return I;var t=e[n].next();return t.done?(n++,this.next()):t}}}}(A||(A={}));(function(e){function t(t,n,r,i){return void 0===n&&(n=0),void 0===r&&(r=t.length),void 0===i&&(i=n-1),e.call(this,t,n,r,i)||this}x(t,e),t.prototype.current=function(){return e.prototype.current.call(this)},t.prototype.previous=function(){return this.index=Math.max(this.index-1,this.start-1),this.current()},t.prototype.first=function(){return this.index=this.start,this.current()},t.prototype.last=function(){return this.index=this.end-1,this.current()},t.prototype.parent=function(){return null}})(function(){function e(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=e.length),void 0===r&&(r=t-1),this.items=e,this.start=t,this.end=n,this.index=r}return e.prototype.first=function(){return this.index=this.start,this.current()},e.prototype.next=function(){return this.index=Math.min(this.index+1,this.end),this.current()},e.prototype.current=function(){return this.index===this.start-1||this.index===this.end?null:this.items[this.index]},e}()),function(){function e(e,t){this.iterator=e,this.fn=t}e.prototype.next=function(){return this.fn(this.iterator.next())}}();var R,U=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),k=/^\w[\w\d+.-]*$/,D=/^\//,F=/^\/\//,K=!0;var q="",V="/",B=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,Y=function(){function e(e,t,n,r,i,o){void 0===o&&(o=!1),"object"==typeof e?(this.scheme=e.scheme||q,this.authority=e.authority||q,this.path=e.path||q,this.query=e.query||q,this.fragment=e.fragment||q):(this.scheme=function(e,t){return t||K?e||q:(e||(console.trace("BAD uri lacks scheme, falling back to file-scheme."),e="file"),e)}(e,o),this.authority=t||q,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==V&&(t=V+t):t=V}return t}(this.scheme,n||q),this.query=r||q,this.fragment=i||q,function(e,t){if(!e.scheme){if(t||K)throw new Error('[UriError]: Scheme is missing: {scheme: "", authority: "'+e.authority+'", path: "'+e.path+'", query: "'+e.query+'", fragment: "'+e.fragment+'"}');console.warn('[UriError]: Scheme is missing: {scheme: "", authority: "'+e.authority+'", path: "'+e.path+'", query: "'+e.query+'", fragment: "'+e.fragment+'"}')}if(e.scheme&&!k.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!D.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(F.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}(this,o))}return e.isUri=function(t){return t instanceof e||!!t&&("string"==typeof t.authority&&"string"==typeof t.fragment&&"string"==typeof t.path&&"string"==typeof t.query&&"string"==typeof t.scheme&&"function"==typeof t.fsPath&&"function"==typeof t.with&&"function"==typeof t.toString)},Object.defineProperty(e.prototype,"fsPath",{get:function(){return z(this)},enumerable:!0,configurable:!0}),e.prototype.with=function(e){if(!e)return this;var t=e.scheme,n=e.authority,r=e.path,i=e.query,o=e.fragment;return void 0===t?t=this.scheme:null===t&&(t=q),void 0===n?n=this.authority:null===n&&(n=q),void 0===r?r=this.path:null===r&&(r=q),void 0===i?i=this.query:null===i&&(i=q),void 0===o?o=this.fragment:null===o&&(o=q),t===this.scheme&&n===this.authority&&r===this.path&&i===this.query&&o===this.fragment?this:new W(t,n,r,i,o)},e.parse=function(e,t){void 0===t&&(t=!1);var n=B.exec(e);return n?new W(n[2]||q,decodeURIComponent(n[4]||q),decodeURIComponent(n[5]||q),decodeURIComponent(n[7]||q),decodeURIComponent(n[9]||q),t):new W(q,q,q,q,q)},e.file=function(e){var t=q;if(p.c&&(e=e.replace(/\\/g,V)),e[0]===V&&e[1]===V){var n=e.indexOf(V,2);-1===n?(t=e.substring(2),e=V):(t=e.substring(2,n),e=e.substring(n)||V)}return new W("file",t,e,q,q)},e.from=function(e){return new W(e.scheme,e.authority,e.path,e.query,e.fragment)},e.prototype.toString=function(e){return void 0===e&&(e=!1),X(this,e)},e.prototype.toJSON=function(){return this},e.revive=function(t){if(t){if(t instanceof e)return t;var n=new W(t);return n._formatted=t.external,n._fsPath=t._sep===j?t.fsPath:null,n}return t},e}(),j=p.c?1:void 0,W=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._formatted=null,t._fsPath=null,t}return U(t,e),Object.defineProperty(t.prototype,"fsPath",{get:function(){return this._fsPath||(this._fsPath=z(this)),this._fsPath},enumerable:!0,configurable:!0}),t.prototype.toString=function(e){return void 0===e&&(e=!1),e?X(this,!0):(this._formatted||(this._formatted=X(this,!1)),this._formatted)},t.prototype.toJSON=function(){var e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=j),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e},t}(Y),H=((R={})[58]="%3A",R[47]="%2F",R[63]="%3F",R[35]="%23",R[91]="%5B",R[93]="%5D",R[64]="%40",R[33]="%21",R[36]="%24",R[38]="%26",R[39]="%27",R[40]="%28",R[41]="%29",R[42]="%2A",R[43]="%2B",R[44]="%2C",R[59]="%3B",R[61]="%3D",R[32]="%20",R);function G(e,t){for(var n=void 0,r=-1,i=0;i=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||45===o||46===o||95===o||126===o||t&&47===o)-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),void 0!==n&&(n+=e.charAt(i));else{void 0===n&&(n=e.substr(0,i));var s=H[o];void 0!==s?(-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),n+=s):-1===r&&(r=i)}}return-1!==r&&(n+=encodeURIComponent(e.substring(r))),void 0!==n?n:e}function Q(e){for(var t=void 0,n=0;n1&&"file"===e.scheme?"//"+e.authority+e.path:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?e.path[1].toLowerCase()+e.path.substr(2):e.path,p.c&&(t=t.replace(/\//g,"\\")),t}function X(e,t){var n=t?Q:G,r="",i=e.scheme,o=e.authority,s=e.path,u=e.query,a=e.fragment;if(i&&(r+=i,r+=":"),(o||"file"===i)&&(r+=V,r+=V),o){var l=o.indexOf("@");if(-1!==l){var h=o.substr(0,l);o=o.substr(l+1),-1===(l=h.indexOf(":"))?r+=n(h,!1):(r+=n(h.substr(0,l),!1),r+=":",r+=n(h.substr(l+1),!1)),r+="@"}-1===(l=(o=o.toLowerCase()).indexOf(":"))?r+=n(o,!1):(r+=n(o.substr(0,l),!1),r+=o.substr(l))}if(s){if(s.length>=3&&47===s.charCodeAt(0)&&58===s.charCodeAt(2))(c=s.charCodeAt(1))>=65&&c<=90&&(s="/"+String.fromCharCode(c+32)+":"+s.substr(3));else if(s.length>=2&&58===s.charCodeAt(1)){var c;(c=s.charCodeAt(0))>=65&&c<=90&&(s=String.fromCharCode(c+32)+":"+s.substr(2))}r+=n(s,!0)}return u&&(r+="?",r+=n(u,!1)),a&&(r+="#",r+=t?a:G(a,!1)),r}var Z=function(){function e(e,t){this.lineNumber=e,this.column=t}return e.prototype.with=function(t,n){return void 0===t&&(t=this.lineNumber),void 0===n&&(n=this.column),t===this.lineNumber&&n===this.column?this:new e(t,n)},e.prototype.delta=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=0),this.with(this.lineNumber+e,this.column+t)},e.prototype.equals=function(t){return e.equals(this,t)},e.equals=function(e,t){return!e&&!t||!!e&&!!t&&e.lineNumber===t.lineNumber&&e.column===t.column},e.prototype.isBefore=function(t){return e.isBefore(this,t)},e.isBefore=function(e,t){return e.lineNumbern||e===n&&t>r?(this.startLineNumber=n,this.startColumn=r,this.endLineNumber=e,this.endColumn=t):(this.startLineNumber=e,this.startColumn=t,this.endLineNumber=n,this.endColumn=r)}return e.prototype.isEmpty=function(){return e.isEmpty(this)},e.isEmpty=function(e){return e.startLineNumber===e.endLineNumber&&e.startColumn===e.endColumn},e.prototype.containsPosition=function(t){return e.containsPosition(this,t)},e.containsPosition=function(e,t){return!(t.lineNumbere.endLineNumber)&&(!(t.lineNumber===e.startLineNumber&&t.columne.endColumn))},e.prototype.containsRange=function(t){return e.containsRange(this,t)},e.containsRange=function(e,t){return!(t.startLineNumbere.endLineNumber||t.endLineNumber>e.endLineNumber)&&(!(t.startLineNumber===e.startLineNumber&&t.startColumne.endColumn)))},e.prototype.strictContainsRange=function(t){return e.strictContainsRange(this,t)},e.strictContainsRange=function(e,t){return!(t.startLineNumbere.endLineNumber||t.endLineNumber>e.endLineNumber)&&(!(t.startLineNumber===e.startLineNumber&&t.startColumn<=e.startColumn)&&!(t.endLineNumber===e.endLineNumber&&t.endColumn>=e.endColumn)))},e.prototype.plusRange=function(t){return e.plusRange(this,t)},e.plusRange=function(t,n){var r,i,o,s;return n.startLineNumbert.endLineNumber?(o=n.endLineNumber,s=n.endColumn):n.endLineNumber===t.endLineNumber?(o=n.endLineNumber,s=Math.max(n.endColumn,t.endColumn)):(o=t.endLineNumber,s=t.endColumn),new e(r,i,o,s)},e.prototype.intersectRanges=function(t){return e.intersectRanges(this,t)},e.intersectRanges=function(t,n){var r=t.startLineNumber,i=t.startColumn,o=t.endLineNumber,s=t.endColumn,u=n.startLineNumber,a=n.startColumn,l=n.endLineNumber,h=n.endColumn;return rl?(o=l,s=h):o===l&&(s=Math.min(s,h)),r>o?null:r===o&&i>s?null:new e(r,i,o,s)},e.prototype.equalsRange=function(t){return e.equalsRange(this,t)},e.equalsRange=function(e,t){return!!e&&!!t&&e.startLineNumber===t.startLineNumber&&e.startColumn===t.startColumn&&e.endLineNumber===t.endLineNumber&&e.endColumn===t.endColumn},e.prototype.getEndPosition=function(){return new Z(this.endLineNumber,this.endColumn)},e.prototype.getStartPosition=function(){return new Z(this.startLineNumber,this.startColumn)},e.prototype.toString=function(){return"["+this.startLineNumber+","+this.startColumn+" -> "+this.endLineNumber+","+this.endColumn+"]"},e.prototype.setEndPosition=function(t,n){return new e(this.startLineNumber,this.startColumn,t,n)},e.prototype.setStartPosition=function(t,n){return new e(t,n,this.endLineNumber,this.endColumn)},e.prototype.collapseToStart=function(){return e.collapseToStart(this)},e.collapseToStart=function(t){return new e(t.startLineNumber,t.startColumn,t.startLineNumber,t.startColumn)},e.fromPositions=function(t,n){return void 0===n&&(n=t),new e(t.lineNumber,t.column,n.lineNumber,n.column)},e.lift=function(t){return t?new e(t.startLineNumber,t.startColumn,t.endLineNumber,t.endColumn):null},e.isIRange=function(e){return e&&"number"==typeof e.startLineNumber&&"number"==typeof e.startColumn&&"number"==typeof e.endLineNumber&&"number"==typeof e.endColumn},e.areIntersectingOrTouching=function(e,t){return!(e.endLineNumbere.startLineNumber},e}();String.fromCharCode(65279);var $=5e3,ee=3;function te(e,t,n,r){return new T(e,t,n).ComputeDiff(r)}var ne=function(){function e(t){for(var n=[],r=[],i=0,o=t.length;i=0;n--){var r=e.charCodeAt(n);if(32!==r&&9!==r)return n}return-1}(e);return-1===n?t:n+2},e.prototype.getCharSequence=function(e,t,n){for(var r=[],i=[],o=[],s=0,u=t;u<=n;u++)for(var a=this._lines[u],l=e?this._startColumns[u]:1,h=e?this._endColumns[u]:a.length+1,c=l;c1&&m>1;){if(c.charCodeAt(d-2)!==f.charCodeAt(m-2))break;d--,m--}(d>1||m>1)&&this._pushTrimWhitespaceCharChange(i,o+1,1,d,s+1,1,m);for(var p=ne._getLastNonBlankColumn(c,1),g=ne._getLastNonBlankColumn(f,1),_=c.length+1,v=f.length+1;p<_&&g255?255:0|e}function le(e){return e<0?0:e>4294967295?4294967295:0|e}var he=function(){return function(e,t){this.index=e,this.remainder=t}}(),ce=function(){function e(e){this.values=e,this.prefixSum=new Uint32Array(e.length),this.prefixSumValidIndex=new Int32Array(1),this.prefixSumValidIndex[0]=-1}return e.prototype.getCount=function(){return this.values.length},e.prototype.insertValues=function(e,t){e=le(e);var n=this.values,r=this.prefixSum,i=t.length;return 0!==i&&(this.values=new Uint32Array(n.length+i),this.values.set(n.subarray(0,e),0),this.values.set(n.subarray(e),e+i),this.values.set(t,e),e-1=0&&this.prefixSum.set(r.subarray(0,this.prefixSumValidIndex[0]+1)),!0)},e.prototype.changeValue=function(e,t){return e=le(e),t=le(t),this.values[e]!==t&&(this.values[e]=t,e-1=n.length)return!1;var i=n.length-e;return t>=i&&(t=i),0!==t&&(this.values=new Uint32Array(n.length-t),this.values.set(n.subarray(0,e),0),this.values.set(n.subarray(e+t),e),this.prefixSum=new Uint32Array(this.values.length),e-1=0&&this.prefixSum.set(r.subarray(0,this.prefixSumValidIndex[0]+1)),!0)},e.prototype.getTotalValue=function(){return 0===this.values.length?0:this._getAccumulatedValue(this.values.length-1)},e.prototype.getAccumulatedValue=function(e){return e<0?0:(e=le(e),this._getAccumulatedValue(e))},e.prototype._getAccumulatedValue=function(e){if(e<=this.prefixSumValidIndex[0])return this.prefixSum[e];var t=this.prefixSumValidIndex[0]+1;0===t&&(this.prefixSum[0]=this.values[0],t++),e>=this.values.length&&(e=this.values.length-1);for(var n=t;n<=e;n++)this.prefixSum[n]=this.prefixSum[n-1]+this.values[n];return this.prefixSumValidIndex[0]=Math.max(this.prefixSumValidIndex[0],e),this.prefixSum[e]},e.prototype.getIndexOf=function(e){e=Math.floor(e),this.getTotalValue();for(var t=0,n=this.values.length-1,r=0,i=0,o=0;t<=n;)if(r=t+(n-t)/2|0,e<(o=(i=this.prefixSum[r])-this.values[r]))n=r-1;else{if(!(e>=i))break;t=r+1}return new he(r,e-o)},e}(),fe=(function(){function e(e){this._cacheAccumulatedValueStart=0,this._cache=null,this._actual=new ce(e),this._bustCache()}e.prototype._bustCache=function(){this._cacheAccumulatedValueStart=0,this._cache=null},e.prototype.insertValues=function(e,t){this._actual.insertValues(e,t)&&this._bustCache()},e.prototype.changeValue=function(e,t){this._actual.changeValue(e,t)&&this._bustCache()},e.prototype.removeValues=function(e,t){this._actual.removeValues(e,t)&&this._bustCache()},e.prototype.getTotalValue=function(){return this._actual.getTotalValue()},e.prototype.getAccumulatedValue=function(e){return this._actual.getAccumulatedValue(e)},e.prototype.getIndexOf=function(e){if(e=Math.floor(e),null!==this._cache){var t=e-this._cacheAccumulatedValueStart;if(t>=0&&t/?";var me=function(e){void 0===e&&(e="");for(var t="(-?\\d*\\.\\d\\w*)|([^",n=0,r=de;n=0||(t+="\\"+i)}return t+="\\s]+)",new RegExp(t,"g")}();var pe=function(){function e(t){var n=ae(t);this._defaultValue=n,this._asciiMap=e._createAsciiMap(n),this._map=new Map}return e._createAsciiMap=function(e){for(var t=new Uint8Array(256),n=0;n<256;n++)t[n]=e;return t},e.prototype.set=function(e,t){var n=ae(t);e>=0&&e<256?this._asciiMap[e]=n:this._map.set(e,n)},e.prototype.get=function(e){return e>=0&&e<256?this._asciiMap[e]:this._map.get(e)||this._defaultValue},e}(),ge=(function(){function e(){this._actual=new pe(0)}e.prototype.add=function(e){this._actual.set(e,1)},e.prototype.has=function(e){return 1===this._actual.get(e)}}(),function(){function e(e){for(var t=0,n=0,r=0,i=e.length;rt&&(t=u),s>n&&(n=s),a>n&&(n=a)}var l=new ue(++n,++t,0);for(r=0,i=e.length;r=this._maxCharCode?0:this._states.get(e,t)},e}()),_e=null;var ve=null;var ye=function(){function e(){}return e._createLink=function(e,t,n,r,i){var o=i-1;do{var s=t.charCodeAt(o);if(2!==e.get(s))break;o--}while(o>r);if(r>0){var u=t.charCodeAt(r-1),a=t.charCodeAt(o);(40===u&&41===a||91===u&&93===a||123===u&&125===a)&&o--}return{range:{startLineNumber:n,startColumn:r+1,endLineNumber:n,endColumn:o+2},url:t.substring(r,o+1)}},e.computeLinks=function(t,n){void 0===n&&(null===_e&&(_e=new ge([[1,104,2],[1,72,2],[1,102,6],[1,70,6],[2,116,3],[2,84,3],[3,116,4],[3,84,4],[4,112,5],[4,80,5],[5,115,9],[5,83,9],[5,58,10],[6,105,7],[6,73,7],[7,108,8],[7,76,8],[8,101,9],[8,69,9],[9,58,10],[10,47,11],[11,47,12]])),n=_e);for(var r=function(){if(null===ve){ve=new pe(0);for(var e=0;e<" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…".length;e++)ve.set(" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…".charCodeAt(e),1);for(e=0;e<".,;".length;e++)ve.set(".,;".charCodeAt(e),2)}return ve}(),i=[],o=1,s=t.getLineCount();o<=s;o++){for(var u=t.getLineContent(o),a=u.length,l=0,h=0,c=0,f=1,d=!1,m=!1,p=!1;l=0?((r+=n?1:-1)<0?r=e.length-1:r%=e.length,e[r]):null},e.INSTANCE=new e,e}();n("tZcU");var be,Le=function(){function e(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}return e.Undefined=new e(void 0),e}(),Ne=function(){function e(){this._first=Le.Undefined,this._last=Le.Undefined,this._size=0}return Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),e.prototype.isEmpty=function(){return this._first===Le.Undefined},e.prototype.clear=function(){this._first=Le.Undefined,this._last=Le.Undefined,this._size=0},e.prototype.unshift=function(e){return this._insert(e,!1)},e.prototype.push=function(e){return this._insert(e,!0)},e.prototype._insert=function(e,t){var n=this,r=new Le(e);if(this._first===Le.Undefined)this._first=r,this._last=r;else if(t){var i=this._last;this._last=r,r.prev=i,i.next=r}else{var o=this._first;this._first=r,r.next=o,o.prev=r}this._size+=1;var s=!1;return function(){s||(s=!0,n._remove(r))}},e.prototype.shift=function(){if(this._first!==Le.Undefined){var e=this._first.element;return this._remove(this._first),e}},e.prototype.pop=function(){if(this._last!==Le.Undefined){var e=this._last.element;return this._remove(this._last),e}},e.prototype._remove=function(e){if(e.prev!==Le.Undefined&&e.next!==Le.Undefined){var t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Le.Undefined&&e.next===Le.Undefined?(this._first=Le.Undefined,this._last=Le.Undefined):e.next===Le.Undefined?(this._last=this._last.prev,this._last.next=Le.Undefined):e.prev===Le.Undefined&&(this._first=this._first.next,this._first.prev=Le.Undefined);this._size-=1},e.prototype.iterator=function(){var e,t=this._first;return{next:function(){return t===Le.Undefined?I:(e?e.value=t.element:e={done:!1,value:t.element},t=t.next,e)}}},e.prototype.toArray=function(){for(var e=[],t=this._first;t!==Le.Undefined;t=t.next)e.push(t.element);return e},e}(),Ee=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(e){function t(e){return function(t,n,r){void 0===n&&(n=null);var i,o=!1;return i=e(function(e){if(!o)return i?i.dispose():o=!0,t.call(n,e)},null,r),o&&i.dispose(),i}}function n(e,t){return s(function(n,r,i){return void 0===r&&(r=null),e(function(e){return n.call(r,t(e))},null,i)})}function r(e,t){return s(function(n,r,i){return void 0===r&&(r=null),e(function(e){t(e),n.call(r,e)},null,i)})}function i(e,t){return s(function(n,r,i){return void 0===r&&(r=null),e(function(e){return t(e)&&n.call(r,e)},null,i)})}function o(e,t,r){var i=r;return n(e,function(e){return i=t(i,e)})}function s(e){var t,n=new Pe({onFirstListenerAdd:function(){t=e(n.fire,n)},onLastListenerRemove:function(){t.dispose()}});return n.event}function u(e){var t,n=!0;return i(e,function(e){var r=n||e!==t;return n=!1,t=e,r})}e.None=function(){return m.None},e.once=t,e.map=n,e.forEach=r,e.filter=i,e.signal=function(e){return e},e.any=function(){for(var e=[],t=0;t1)&&l.fire(e),a=0},n)})},onLastListenerRemove:function(){o.dispose()}});return l.event},e.stopwatch=function(e){var r=(new Date).getTime();return n(t(e),function(e){return(new Date).getTime()-r})},e.latch=u,e.buffer=function(e,t,n){void 0===t&&(t=!1),void 0===n&&(n=[]);var r=n.slice(),i=e(function(e){r?r.push(e):s.fire(e)}),o=function(){r&&r.forEach(function(e){return s.fire(e)}),r=null},s=new Pe({onFirstListenerAdd:function(){i||(i=e(function(e){return s.fire(e)}))},onFirstListenerDidAdd:function(){r&&(t?setTimeout(o):o())},onLastListenerRemove:function(){i&&i.dispose(),i=null}});return s.event};var a=function(){function e(e){this.event=e}return e.prototype.map=function(t){return new e(n(this.event,t))},e.prototype.forEach=function(t){return new e(r(this.event,t))},e.prototype.filter=function(t){return new e(i(this.event,t))},e.prototype.reduce=function(t,n){return new e(o(this.event,t,n))},e.prototype.latch=function(){return new e(u(this.event))},e.prototype.on=function(e,t,n){return this.event(e,t,n)},e.prototype.once=function(e,n,r){return t(this.event)(e,n,r)},e}();e.chain=function(e){return new a(e)},e.fromNodeEventEmitter=function(e,t,n){void 0===n&&(n=function(e){return e});var r=function(){for(var e=[],t=0;t0?new Ae(this._options&&this._options.leakWarningThreshold):void 0}return Object.defineProperty(e.prototype,"event",{get:function(){var t=this;return this._event||(this._event=function(n,r,i){t._listeners||(t._listeners=new Ne);var o=t._listeners.isEmpty();o&&t._options&&t._options.onFirstListenerAdd&&t._options.onFirstListenerAdd(t);var s,u,a=t._listeners.push(r?[n,r]:n);return o&&t._options&&t._options.onFirstListenerDidAdd&&t._options.onFirstListenerDidAdd(t),t._options&&t._options.onListenerDidAdd&&t._options.onListenerDidAdd(t,n,r),t._leakageMon&&(s=t._leakageMon.check(t._listeners.size)),u={dispose:function(){(s&&s(),u.dispose=e._noop,t._disposed)||(a(),t._options&&t._options.onLastListenerRemove&&(t._listeners&&!t._listeners.isEmpty()||t._options.onLastListenerRemove(t)))}},i instanceof d?i.add(u):Array.isArray(i)&&i.push(u),u}),this._event},enumerable:!0,configurable:!0}),e.prototype.fire=function(e){if(this._listeners){this._deliveryQueue||(this._deliveryQueue=new Ne);for(var t=this._listeners.iterator(),n=t.next();!n.done;n=t.next())this._deliveryQueue.push([n.value,e]);for(;this._deliveryQueue.size>0;){var r=this._deliveryQueue.shift(),o=r[0],s=r[1];try{"function"==typeof o?o.call(void 0,s):o[0].call(o[1],s)}catch(n){i(n)}}}},e.prototype.dispose=function(){this._listeners&&this._listeners.clear(),this._deliveryQueue&&this._deliveryQueue.clear(),this._leakageMon&&this._leakageMon.dispose(),this._disposed=!0},e._noop=function(){},e}(),Me=(function(e){function t(t){var n=e.call(this,t)||this;return n._isPaused=0,n._eventQueue=new Ne,n._mergeFn=t&&t.merge,n}Ee(t,e),t.prototype.pause=function(){this._isPaused++},t.prototype.resume=function(){if(0!==this._isPaused&&0==--this._isPaused)if(this._mergeFn){var t=this._eventQueue.toArray();this._eventQueue.clear(),e.prototype.fire.call(this,this._mergeFn(t))}else for(;!this._isPaused&&0!==this._eventQueue.size;)e.prototype.fire.call(this,this._eventQueue.shift())},t.prototype.fire=function(t){this._listeners&&(0!==this._isPaused?this._eventQueue.push(t):e.prototype.fire.call(this,t))}}(Pe),function(){function e(){var e=this;this.hasListeners=!1,this.events=[],this.emitter=new Pe({onFirstListenerAdd:function(){return e.onFirstListenerAdd()},onLastListenerRemove:function(){return e.onLastListenerRemove()}})}Object.defineProperty(e.prototype,"event",{get:function(){return this.emitter.event},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this,n={event:e,listener:null};this.events.push(n),this.hasListeners&&this.hook(n);var r,i;return r=function(e){var t,n=this,r=!1;return function(){return r?t:(r=!0,t=e.apply(n,arguments))}}(function(){t.hasListeners&&t.unhook(n);var e=t.events.indexOf(n);t.events.splice(e,1)}),i=c({dispose:function(){h(i),r()}})},e.prototype.onFirstListenerAdd=function(){var e=this;this.hasListeners=!0,this.events.forEach(function(t){return e.hook(t)})},e.prototype.onLastListenerRemove=function(){var e=this;this.hasListeners=!1,this.events.forEach(function(t){return e.unhook(t)})},e.prototype.hook=function(e){var t=this;e.listener=e.event(function(e){return t.emitter.fire(e)})},e.prototype.unhook=function(e){e.listener&&e.listener.dispose(),e.listener=null},e.prototype.dispose=function(){this.emitter.dispose()}}(),function(){function e(){this.buffers=[]}e.prototype.wrapEvent=function(e){var t=this;return function(n,r,i){return e(function(e){var i=t.buffers[t.buffers.length-1];i?i.push(function(){return n.call(r,e)}):n.call(r,e)},void 0,i)}},e.prototype.bufferEvents=function(e){var t=[];this.buffers.push(t);var n=e();return this.buffers.pop(),t.forEach(function(e){return e()}),n}}(),function(){function e(){var e=this;this.listening=!1,this.inputEvent=be.None,this.inputEventListener=m.None,this.emitter=new Pe({onFirstListenerDidAdd:function(){e.listening=!0,e.inputEventListener=e.inputEvent(e.emitter.fire,e.emitter)},onLastListenerRemove:function(){e.listening=!1,e.inputEventListener.dispose()}}),this.event=this.emitter.event}Object.defineProperty(e.prototype,"input",{set:function(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.inputEventListener.dispose(),this.emitter.dispose()}}(),Object.freeze(function(e,t){var n=setTimeout(e.bind(t),0);return{dispose:function(){clearTimeout(n)}}}));!function(e){e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof Te||!(!t||"object"!=typeof t)&&"boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:be.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Me})}(Se||(Se={}));var Oe,Te=function(){function e(){this._isCancelled=!1,this._emitter=null}return e.prototype.cancel=function(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))},Object.defineProperty(e.prototype,"isCancellationRequested",{get:function(){return this._isCancelled},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onCancellationRequested",{get:function(){return this._isCancelled?Me:(this._emitter||(this._emitter=new Pe),this._emitter.event)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._emitter&&(this._emitter.dispose(),this._emitter=null)},e}(),xe=function(){function e(e){this._token=void 0,this._parentListener=void 0,this._parentListener=e&&e.onCancellationRequested(this.cancel,this)}return Object.defineProperty(e.prototype,"token",{get:function(){return this._token||(this._token=new Te),this._token},enumerable:!0,configurable:!0}),e.prototype.cancel=function(){this._token?this._token instanceof Te&&this._token.cancel():this._token=Se.Cancelled},e.prototype.dispose=function(){this._parentListener&&this._parentListener.dispose(),this._token?this._token instanceof Te&&this._token.dispose():this._token=Se.None},e}(),Ie=function(){function e(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}return e.prototype.define=function(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e},e.prototype.keyCodeToStr=function(e){return this._keyCodeToStr[e]},e.prototype.strToKeyCode=function(e){return this._strToKeyCode[e.toLowerCase()]||0},e}(),Re=new Ie,Ue=new Ie,ke=new Ie;!function(){function e(e,t,n,r){void 0===n&&(n=t),void 0===r&&(r=n),Re.define(e,t),Ue.define(e,n),ke.define(e,r)}e(0,"unknown"),e(1,"Backspace"),e(2,"Tab"),e(3,"Enter"),e(4,"Shift"),e(5,"Ctrl"),e(6,"Alt"),e(7,"PauseBreak"),e(8,"CapsLock"),e(9,"Escape"),e(10,"Space"),e(11,"PageUp"),e(12,"PageDown"),e(13,"End"),e(14,"Home"),e(15,"LeftArrow","Left"),e(16,"UpArrow","Up"),e(17,"RightArrow","Right"),e(18,"DownArrow","Down"),e(19,"Insert"),e(20,"Delete"),e(21,"0"),e(22,"1"),e(23,"2"),e(24,"3"),e(25,"4"),e(26,"5"),e(27,"6"),e(28,"7"),e(29,"8"),e(30,"9"),e(31,"A"),e(32,"B"),e(33,"C"),e(34,"D"),e(35,"E"),e(36,"F"),e(37,"G"),e(38,"H"),e(39,"I"),e(40,"J"),e(41,"K"),e(42,"L"),e(43,"M"),e(44,"N"),e(45,"O"),e(46,"P"),e(47,"Q"),e(48,"R"),e(49,"S"),e(50,"T"),e(51,"U"),e(52,"V"),e(53,"W"),e(54,"X"),e(55,"Y"),e(56,"Z"),e(57,"Meta"),e(58,"ContextMenu"),e(59,"F1"),e(60,"F2"),e(61,"F3"),e(62,"F4"),e(63,"F5"),e(64,"F6"),e(65,"F7"),e(66,"F8"),e(67,"F9"),e(68,"F10"),e(69,"F11"),e(70,"F12"),e(71,"F13"),e(72,"F14"),e(73,"F15"),e(74,"F16"),e(75,"F17"),e(76,"F18"),e(77,"F19"),e(78,"NumLock"),e(79,"ScrollLock"),e(80,";",";","OEM_1"),e(81,"=","=","OEM_PLUS"),e(82,",",",","OEM_COMMA"),e(83,"-","-","OEM_MINUS"),e(84,".",".","OEM_PERIOD"),e(85,"/","/","OEM_2"),e(86,"`","`","OEM_3"),e(110,"ABNT_C1"),e(111,"ABNT_C2"),e(87,"[","[","OEM_4"),e(88,"\\","\\","OEM_5"),e(89,"]","]","OEM_6"),e(90,"'","'","OEM_7"),e(91,"OEM_8"),e(92,"OEM_102"),e(93,"NumPad0"),e(94,"NumPad1"),e(95,"NumPad2"),e(96,"NumPad3"),e(97,"NumPad4"),e(98,"NumPad5"),e(99,"NumPad6"),e(100,"NumPad7"),e(101,"NumPad8"),e(102,"NumPad9"),e(103,"NumPad_Multiply"),e(104,"NumPad_Add"),e(105,"NumPad_Separator"),e(106,"NumPad_Subtract"),e(107,"NumPad_Decimal"),e(108,"NumPad_Divide")}(),function(e){e.toString=function(e){return Re.keyCodeToStr(e)},e.fromString=function(e){return Re.strToKeyCode(e)},e.toUserSettingsUS=function(e){return Ue.keyCodeToStr(e)},e.toUserSettingsGeneral=function(e){return ke.keyCodeToStr(e)},e.fromUserSettings=function(e){return Ue.strToKeyCode(e)||ke.strToKeyCode(e)}}(Oe||(Oe={}));!function(){function e(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}e.prototype.equals=function(e){return this.ctrlKey===e.ctrlKey&&this.shiftKey===e.shiftKey&&this.altKey===e.altKey&&this.metaKey===e.metaKey&&this.keyCode===e.keyCode},e.prototype.isModifierKey=function(){return 0===this.keyCode||5===this.keyCode||57===this.keyCode||6===this.keyCode||4===this.keyCode},e.prototype.toChord=function(){return new dt([this])},e.prototype.isDuplicateModifierCase=function(){return this.ctrlKey&&5===this.keyCode||this.shiftKey&&4===this.keyCode||this.altKey&&6===this.keyCode||this.metaKey&&57===this.keyCode}}();var De,Fe,Ke,qe,Ve,Be,Ye,je,We,He,Ge,Qe,ze,Xe,Ze,Je,$e,et,tt,nt,rt,it,ot,st,ut,at,lt,ht,ct,ft,dt=function(){function e(e){if(0===e.length)throw(t="parts")?new Error("Illegal argument: "+t):new Error("Illegal argument");var t;this.parts=e}return e.prototype.equals=function(e){if(null===e)return!1;if(this.parts.length!==e.parts.length)return!1;for(var t=0;t "+this.positionLineNumber+","+this.positionColumn+"]"},t.prototype.equalsSelection=function(e){return t.selectionsEqual(this,e)},t.selectionsEqual=function(e,t){return e.selectionStartLineNumber===t.selectionStartLineNumber&&e.selectionStartColumn===t.selectionStartColumn&&e.positionLineNumber===t.positionLineNumber&&e.positionColumn===t.positionColumn},t.prototype.getDirection=function(){return this.selectionStartLineNumber===this.startLineNumber&&this.selectionStartColumn===this.startColumn?0:1},t.prototype.setEndPosition=function(e,n){return 0===this.getDirection()?new t(this.startLineNumber,this.startColumn,e,n):new t(e,n,this.startLineNumber,this.startColumn)},t.prototype.getPosition=function(){return new Z(this.positionLineNumber,this.positionColumn)},t.prototype.setStartPosition=function(e,n){return 0===this.getDirection()?new t(e,n,this.endLineNumber,this.endColumn):new t(this.endLineNumber,this.endColumn,e,n)},t.fromPositions=function(e,n){return void 0===n&&(n=e),new t(e.lineNumber,e.column,n.lineNumber,n.column)},t.liftSelection=function(e){return new t(e.selectionStartLineNumber,e.selectionStartColumn,e.positionLineNumber,e.positionColumn)},t.selectionsArrEqual=function(e,t){if(e&&!t||!e&&t)return!1;if(!e&&!t)return!0;if(e.length!==t.length)return!1;for(var n=0,r=e.length;n>>0)>>>0}(e,t)},e.CtrlCmd=2048,e.Shift=1024,e.Alt=512,e.WinCtrl=256,e}();var vt=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),yt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return vt(t,e),Object.defineProperty(t.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"version",{get:function(){return this._versionId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"eol",{get:function(){return this._eol},enumerable:!0,configurable:!0}),t.prototype.getValue=function(){return this.getText()},t.prototype.getLinesContent=function(){return this._lines.slice(0)},t.prototype.getLineCount=function(){return this._lines.length},t.prototype.getLineContent=function(e){return this._lines[e-1]},t.prototype.getWordAtPosition=function(e,t){var n=function(e,t,n,r){t.lastIndex=0;var i=t.exec(n);if(!i)return null;var o=i[0].indexOf(" ")>=0?function(e,t,n,r){var i,o=e-1-r;for(t.lastIndex=0;i=t.exec(n);){var s=i.index||0;if(s>o)return null;if(t.lastIndex>=o)return{word:i[0],startColumn:r+1+s,endColumn:r+1+t.lastIndex}}return null}(e,t,n,r):function(e,t,n,r){var i,o=e-1-r,s=n.lastIndexOf(" ",o-1)+1;for(t.lastIndex=s;i=t.exec(n);){var u=i.index||0;if(u<=o&&t.lastIndex>=o)return{word:i[0],startColumn:r+1+u,endColumn:r+1+t.lastIndex}}return null}(e,t,n,r);return t.lastIndex=0,o}(e.column,function(e){var t=me;if(e&&e instanceof RegExp)if(e.global)t=e;else{var n="g";e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.unicode&&(n+="u"),t=new RegExp(e.source,n)}return t.lastIndex=0,t}(t),this._lines[e.lineNumber-1],0);return n?new J(e.lineNumber,n.startColumn,e.lineNumber,n.endColumn):null},t.prototype.getWordUntilPosition=function(e,t){var n=this.getWordAtPosition(e,t);return n?{word:this._lines[e.lineNumber-1].substring(n.startColumn-1,e.column-1),startColumn:n.startColumn,endColumn:e.column}:{word:"",startColumn:e.column,endColumn:e.column}},t.prototype.createWordIterator=function(e){var t,n,r=this,i=0,o=0,s=[],u=function(){if(o=r._lines.length?I:(n=r._lines[i],s=r._wordenize(n,e),o=0,i+=1,u())};return{next:u}},t.prototype.getLineWords=function(e,t){for(var n=this._lines[e-1],r=[],i=0,o=this._wordenize(n,t);ithis._lines.length)t=this._lines.length,n=this._lines[t-1].length+1,r=!0;else{var i=this._lines[t-1].length+1;n<1?(n=1,r=!0):n>i&&(n=i,r=!0)}return r?{lineNumber:t,column:n}:e},t}(fe),Ct=function(){function e(e,t){this._host=e,this._models=Object.create(null),this._foreignModuleFactory=t,this._foreignModule=null}return e.prototype.dispose=function(){this._models=Object.create(null)},e.prototype._getModel=function(e){return this._models[e]},e.prototype._getModels=function(){var e=this,t=[];return Object.keys(this._models).forEach(function(n){return t.push(e._models[n])}),t},e.prototype.acceptNewModel=function(e){this._models[e.url]=new yt(Y.parse(e.url),e.lines,e.EOL,e.versionId)},e.prototype.acceptModelChanged=function(e,t){this._models[e]&&this._models[e].onEvents(t)},e.prototype.acceptRemovedModel=function(e){this._models[e]&&delete this._models[e]},e.prototype.computeDiff=function(e,t,n){var r=this._getModel(e),i=this._getModel(t);if(!r||!i)return Promise.resolve(null);var o=r.getLinesContent(),s=i.getLinesContent(),u=new se(o,s,{shouldComputeCharChanges:!0,shouldPostProcessCharChanges:!0,shouldIgnoreTrimWhitespace:n,shouldMakePrettyDiff:!0}).computeDiff(),a=!(u.length>0)&&this._modelsAreIdentical(r,i);return Promise.resolve({identical:a,changes:u})},e.prototype._modelsAreIdentical=function(e,t){var n=e.getLineCount();if(n!==t.getLineCount())return!1;for(var r=1;r<=n;r++){if(e.getLineContent(r)!==t.getLineContent(r))return!1}return!0},e.prototype.computeMoreMinimalEdits=function(t,n){var r=this._getModel(t);if(!r)return Promise.resolve(n);for(var i=[],o=void 0,s=0,u=n=N(n,function(e,t){return e.range&&t.range?J.compareRangesUsingStarts(e.range,t.range):(e.range?0:1)-(t.range?0:1)});se._diffLimit)i.push({range:l,text:h});else for(var d=w(f,h,!1),m=r.offsetAt(J.lift(l).getStartPosition()),p=0,g=d;p1)for(var n=1;n=0,o=a.indexOf("Macintosh")>=0,s=a.indexOf("Linux")>=0,u=!0,navigator.language;var d=i,m=u,p="object"==typeof self?self:"object"==typeof r?r:{}}).call(t,n("W2nU"),n("DuR2"))},tZcU:function(e,t,n){(function(e){(function(){"use strict";function t(e){var t=this.constructor;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){return t.reject(n)})})}var n=setTimeout;function r(){}function i(e){if(!(this instanceof i))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],l(e,this)}function o(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,i._immediateFn(function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var r;try{r=n(e._value)}catch(e){return void u(t.promise,e)}s(t.promise,r)}else(1===e._state?s:u)(t.promise,e._value)})):e._deferreds.push(t)}function s(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof i)return e._state=3,e._value=t,void a(e);if("function"==typeof n)return void l((r=n,o=t,function(){r.apply(o,arguments)}),e)}e._state=1,e._value=t,a(e)}catch(t){u(e,t)}var r,o}function u(e,t){e._state=2,e._value=t,a(e)}function a(e){2===e._state&&0===e._deferreds.length&&i._immediateFn(function(){e._handled||i._unhandledRejectionFn(e._value)});for(var t=0,n=e._deferreds.length;t - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.ttf b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.ttf deleted file mode 100644 index 7b25f3ce94..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.ttf and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.woff b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.woff deleted file mode 100644 index 941dfa4bae..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.woff and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.woff2 b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.woff2 deleted file mode 100644 index 120796bb71..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/Roboto.woff2 and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/element-icons.535877f.woff b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/element-icons.535877f.woff deleted file mode 100644 index 02b9a2539e..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/element-icons.535877f.woff and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/element-icons.732389d.ttf b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/element-icons.732389d.ttf deleted file mode 100644 index 91b74de367..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/element-icons.732389d.ttf and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.eot b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.eot deleted file mode 100644 index e9f60ca953..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.eot and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.svg b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.svg deleted file mode 100644 index 855c845e53..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.svg +++ /dev/null @@ -1,2671 +0,0 @@ - - - - -Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 - By ,,, -Copyright Dave Gandy 2016. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.ttf b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.ttf deleted file mode 100644 index 35acda2fa1..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.ttf and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.woff b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.woff deleted file mode 100644 index 400014a4b0..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.woff and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.woff2 b/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.woff2 deleted file mode 100644 index 4d13fc6040..0000000000 Binary files a/_build/emqx/lib/emqx_dashboard/priv/www/static/fonts/fontawesome-webfont.woff2 and /dev/null differ diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/0.4e3725210092a2d8386a.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/0.4e3725210092a2d8386a.js deleted file mode 100644 index 43fc40d3f1..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/0.4e3725210092a2d8386a.js +++ /dev/null @@ -1,8 +0,0 @@ -webpackJsonp([0],{"1H6C":function(e,t,r){var n=function(){return this}()||Function("return this")(),i=n.regeneratorRuntime&&Object.getOwnPropertyNames(n).indexOf("regeneratorRuntime")>=0,a=i&&n.regeneratorRuntime;if(n.regeneratorRuntime=void 0,e.exports=r("HhN8"),i)n.regeneratorRuntime=a;else try{delete n.regeneratorRuntime}catch(e){n.regeneratorRuntime=void 0}},"3IRH":function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},"3IWq":function(e,t){},FcGO:function(e,t,r){"use strict";var n=r("Xxa5"),i=r.n(n),a=r("exGp"),s=r.n(a),o={name:"emq-select",components:{},props:{value:{},field:{type:Object,required:!0},fieldName:{type:Object,default:function(){return{label:"label",value:"value"}}},disabledItem:{type:Array,default:function(){return[]}},refresh:{type:Boolean}},data:function(){return{options:[],parserField:{}}},computed:{rawValue:{get:function(){return"boolean"==typeof this.value?this.value.toString():this.value},set:function(e){var t=this.fieldName.value;this.options.find(function(r){return r[t]===e})&&this.parserField[t]&&(e="true"===e),this.$emit("update:value",e)}}},watch:{refresh:function(e){e&&this.loadData()},field:{handler:function(){this.loadData()},deep:!0}},created:function(){this.loadData()},methods:{loadData:function(){var e=this;return s()(i.a.mark(function t(){var r,n,a;return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.getOptions();case 2:r=t.sent,e.parserField={},n=e.fieldName.value,a=e.fieldName.label,e.options=r.map(function(t){var r=t[n],i=t[a];return"boolean"==typeof r&&(e.parserField[n]="boolean",t[n]=r.toString(),"boolean"==typeof i&&(t[a]=i.toString())),t}),e.$emit("update:refresh",!1);case 8:case"end":return t.stop()}},t,e)}))()},isDisabled:function(e){return this.disabledItem.includes(e[this.fieldName.value])},getOptions:function(){var e=this;return s()(i.a.mark(function t(){var r,n,a,s,o;return i.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(r=e.field,n=r.api,r.url,a=r.options,s=r.list,o=[],!a){t.next=6;break}o=a,t.next=14;break;case 6:if(!s){t.next=10;break}o=s.map(function(e){return{label:e,value:e}}),t.next=14;break;case 10:if(!n){t.next=14;break}return t.next=13,n();case 13:o=t.sent;case 14:return t.abrupt("return",o);case 15:case"end":return t.stop()}},t,e)}))()}}},c={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("el-select",e._g(e._b({staticClass:"emq-select",attrs:{value:e.rawValue}},"el-select",e.$attrs,!1),e.$listeners),[e._t("default",e._l(e.options,function(t,n){return r("el-option",{key:n,attrs:{value:t[e.fieldName.value],label:t[e.fieldName.label],disabled:e.isDisabled(t)}},[e._t("option",null,{item:t})],2)}))],2)},staticRenderFns:[]},l=r("VU/8")(o,c,!1,null,null,null);t.a=l.exports},HhN8:function(e,t){!function(t){"use strict";var r,n=Object.prototype,i=n.hasOwnProperty,a="function"==typeof Symbol?Symbol:{},s=a.iterator||"@@iterator",o=a.asyncIterator||"@@asyncIterator",c=a.toStringTag||"@@toStringTag",l="object"==typeof e,u=t.regeneratorRuntime;if(u)l&&(e.exports=u);else{(u=t.regeneratorRuntime=l?e.exports:{}).wrap=_;var p="suspendedStart",h="suspendedYield",d="executing",f="completed",y={},v={};v[s]=function(){return this};var m=Object.getPrototypeOf,b=m&&m(m(A([])));b&&b!==n&&i.call(b,s)&&(v=b);var g=O.prototype=E.prototype=Object.create(v);x.prototype=g.constructor=O,O.constructor=x,O[c]=x.displayName="GeneratorFunction",u.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===x||"GeneratorFunction"===(t.displayName||t.name))},u.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,O):(e.__proto__=O,c in e||(e[c]="GeneratorFunction")),e.prototype=Object.create(g),e},u.awrap=function(e){return{__await:e}},w(S.prototype),S.prototype[o]=function(){return this},u.AsyncIterator=S,u.async=function(e,t,r,n){var i=new S(_(e,t,r,n));return u.isGeneratorFunction(t)?i:i.next().then(function(e){return e.done?e.value:i.next()})},w(g),g[c]="Generator",g[s]=function(){return this},g.toString=function(){return"[object Generator]"},u.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function r(){for(;t.length;){var n=t.pop();if(n in e)return r.value=n,r.done=!1,r}return r.done=!0,r}},u.values=A,I.prototype={constructor:I,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(R),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=r)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(n,i){return o.type="throw",o.arg=e,t.next=n,i&&(t.method="next",t.arg=r),!!i}for(var a=this.tryEntries.length-1;a>=0;--a){var s=this.tryEntries[a],o=s.completion;if("root"===s.tryLoc)return n("end");if(s.tryLoc<=this.prev){var c=i.call(s,"catchLoc"),l=i.call(s,"finallyLoc");if(c&&l){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),R(r),y}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;R(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:A(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=r),y}}}function _(e,t,r,n){var i=t&&t.prototype instanceof E?t:E,a=Object.create(i.prototype),s=new I(n||[]);return a._invoke=function(e,t,r){var n=p;return function(i,a){if(n===d)throw new Error("Generator is already running");if(n===f){if("throw"===i)throw a;return L()}for(r.method=i,r.arg=a;;){var s=r.delegate;if(s){var o=$(s,r);if(o){if(o===y)continue;return o}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===p)throw n=f,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=d;var c=k(e,t,r);if("normal"===c.type){if(n=r.done?f:h,c.arg===y)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n=f,r.method="throw",r.arg=c.arg)}}}(e,r,s),a}function k(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}function E(){}function x(){}function O(){}function w(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function S(e){var t;this._invoke=function(r,n){function a(){return new Promise(function(t,a){!function t(r,n,a,s){var o=k(e[r],e,n);if("throw"!==o.type){var c=o.arg,l=c.value;return l&&"object"==typeof l&&i.call(l,"__await")?Promise.resolve(l.__await).then(function(e){t("next",e,a,s)},function(e){t("throw",e,a,s)}):Promise.resolve(l).then(function(e){c.value=e,a(c)},s)}s(o.arg)}(r,n,t,a)})}return t=t?t.then(a,a):a()}}function $(e,t){var n=e.iterator[t.method];if(n===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=r,$(e,t),"throw"===t.method))return y;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return y}var i=k(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=r),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function R(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0)}function A(e){if(e){var t=e[s];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,a=function t(){for(;++n0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=[],n="",i=c()({},t,{});return s()(e).forEach(function(e){var a=f()(e,2),s=a[0],o=a[1];if("$resource"!==s){var c=o.format,l=o.enum,u=o.input,p=o.order,d=o.title,y=o.type,v=o.description,m=o.default;"object"===(void 0===d?"undefined":h()(d))&&(d=d[O]),"object"===(void 0===v?"undefined":h()(v))&&(v=v[O]);var b=m||"";S.includes(c)&&(b={url:"http://"}[c]);var g={placeholder:b=b.toString()};(l||"boolean"===y)&&(y="emq-select",g.field=l?{options:l.map(function(e){return{value:e,label:e}})}:{options:[{label:!0,value:!0},{label:!1,value:!1}]}),"object"!==y||m||(m={}),"textarea"===u&&(g.type="textarea",g.rows=5),r.push({key:s,type:y,label:d||s,prop:s,defaultValue:m,$attrs:g,description:(v||"").replace(/\n/g,"
      "),order:p}),t?i[t][s]=$(e):i[s]=$(e)}else n="string"}),{model:r=r.sort(function(e,t){return e.order-t.order}),rules:i,resource:n}},t.a=function(e){if("en"===O)return x[e];return E[e]},t.c=function(e,t,r){return new i.a(function(n,i){try{var a=e.filter(function(e){if(e[t]){var n=e[t].toLowerCase().replace(/\s+/g,""),i=r.toLocaleLowerCase().replace(/\s+/g,"");return n.match(i)}return null});return n(a)}catch(e){return i(e)}})},t.f=function(e){var t=e.replace(/\"/g,""),r=null;return["message.publish","message.deliver","message.acked","message.dropped","client.connected","client.disconnected","client.subscribe","client.unsubscribe"].forEach(function(e){var n=e.split("."),i=f()(n,2),a=i[0],s=i[1],o=new RegExp(a+"\\."+s,"gim");t.match(o)&&(r=t.match(o))}),r},t.e=function(e,t){var r={"message.publish":"","message.deliver":"$events/message_delivered","message.acked":"$events/message_acked","message.dropped":"$events/message_dropped","client.connected":"$events/client_connected","client.disconnected":"$events/client_disconnected","client.subscribe":"$events/session_subscribed","client.unsubscribe":"$events/session_unsubscribed"}[t],n=e.replace(/\"/g,""),i=g.a.parse(n);""===r&&(i.value.where=null,r="#");return i.value.from.value[0].value.value.value='"'+r+'"',g.a.stringify(i)};var O=window.localStorage.language||window.EMQX_DASHBOARD_CONFIG.lang||"en",w={is_required:{en:"is required",zh:"必填"}},S=["string","number","boolean","method","regexp","integer","float","array","object","enum","date","url","hex","email"];function $(e){var t=f()(e,2),r=t[0],n=t[1],i=n.type,a=n.format,s=n.required,o=n.enum,c=n.title;"object"===(void 0===c?"undefined":h()(c))&&(c=c[O]);var l={};return s&&(l.required=!0,l.message=(c||r)+" "+w.is_required[O]),l.type=i,S.includes(a)&&"url"!==a&&(l.type=a),l.enum="enum"===i?o:void 0,u()(l).length>0?l:void 0}function T(e,t){var r=new m.a(t.target,{text:function(){return e}});r.on("success",function(){y.default.prototype.$message({message:y.default.prototype.$t("oper.copySuccess"),type:"success",duration:1500}),r.destroy()}),r.on("error",function(){y.default.prototype.$message({message:y.default.prototype.$t("oper.copyFailed"),type:"error"}),r.destroy()}),r.onClick(t)}},SHGx:function(e,t,r){"use strict";var n=r("pFYg"),i=r.n(n),a=r("Dd8w"),s=r.n(a),o=r("FcGO"),c=r("JaHG"),l=window.localStorage.language||window.EMQX_DASHBOARD_CONFIG.lang||"en",u={name:"resource-dialog",components:{EmqSelect:o.a},inheritAttrs:!1,props:{visible:{type:Boolean,required:!0},resourceType:{type:String},enableItem:{type:Array,default:function(){return[]}}},data:function(){return{paramsList:[],resourceRules:{},resourceTypes:[],record:{name:"",type:"",config:{},description:""}}},computed:{dialogVisible:{get:function(){return this.visible},set:function(e){this.$emit("update:visible",e)}},rules:function(){return s()({name:{required:!0},description:{required:!0},type:{required:!0}},this.resourceRules)}},methods:{clearTabIndex:function(){document.querySelectorAll(".el-icon-question").forEach(function(e){e.setAttribute("tabindex","-1")})},close:function(){this.$refs.record&&this.$refs.record.resetFields()},handleCreate:function(){var e=this,t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.$refs.record.validate(function(r){if(r){var n=t?"/resources":"/resources?test=true";e.$httpPost(n,e.record).then(function(r){t?(e.$message.success(e.$t("rule.create_success")),e.dialogVisible=!1,e.$emit("confirm",r.data)):e.$message.success(e.$t("rule.conf_test_success"))}).catch(function(){})}})},handleTypeChange:function(e){this.paramsList=[],this.resourceRules={};var t=this.resourceTypes.find(function(t){return t.name===e});if(t){var r=Object(c.d)(t.params,"config"),n=r.model,i=r.rules;this.resourceRules=i,this.paramsList=n,this.initRecord(),setTimeout(this.clearTabIndex,500)}},initRecord:function(){var e=this;0===this.paramsList.length?this.$set(this.record,"config",void 0):this.record.config||this.$set(this.record,"config",{}),this.$set(this.record,"config",{}),this.paramsList.forEach(function(t){e.$set(e.record.config,t.key,t.defaultValue)}),setTimeout(function(){e.$refs.record.clearValidate()},30)},loadResourceTypes:function(){var e=this;this.$httpGet("/resource_types").then(function(t){e.record={name:"",type:"",config:{},description:""},e.resourceType&&(e.record.type=e.resourceType),e.resourceTypes=t.data.map(function(e){return e.titleLabel="object"===i()(e.title)?e.title[l]:e.title,e}),e.handleTypeChange(e.record.type),setTimeout(function(){e.$refs.record.clearValidate()},30)})}}},p={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("el-dialog",e._b({staticClass:"resource-dialog",attrs:{width:"700px",visible:e.dialogVisible,title:e.$t("rule.resource_mgmt")},on:{"update:visible":function(t){e.dialogVisible=t},close:e.close,open:e.loadResourceTypes}},"el-dialog",e.$attrs,!1),[r("el-form",{ref:"record",staticClass:"el-form--public",attrs:{model:e.record,rules:e.rules}},[r("el-row",{attrs:{gutter:20}},[r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"type",label:e.$t("rule.resource_type")}},[r("el-select",{staticClass:"el-select--public",staticStyle:{width:"100%"},attrs:{"popper-class":"el-select--public",disabled:!!e.resourceType},on:{change:e.handleTypeChange},model:{value:e.record.type,callback:function(t){e.$set(e.record,"type",t)},expression:"record.type"}},e._l(e.resourceTypes,function(t,n){return r("div",{key:n},[0===e.enableItem.length||e.enableItem.includes(t.name)?r("el-option",{attrs:{label:t.titleLabel,value:t.name}}):e._e()],1)}),0)],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",[r("template",{slot:"label"},[e._v(" ")]),e._v(" "),r("el-button",{attrs:{type:"primary"},on:{click:function(t){return e.handleCreate(!1)}}},[e._v("\n "+e._s(e.$t("rule.conf_test"))+"\n ")])],2)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"description",label:e.$t("rule.resource_name")}},[r("el-input",{model:{value:e.record.description,callback:function(t){e.$set(e.record,"description",t)},expression:"record.description"}})],1)],1),e._v(" "),e.record.type?r("div",e._l(e.paramsList,function(t,n){return r("el-col",{key:n,attrs:{span:"object"===t.type||"textarea"===t.$attrs.type?24:12}},[r("el-form-item",{attrs:{prop:"config."+t.prop}},[r("template",{slot:"label"},[e._v("\n "+e._s(t.label)+"\n\n "),t.description?r("el-popover",{attrs:{placement:"right",width:"200",trigger:"hover"}},[r("div",{domProps:{innerHTML:e._s(t.description)}}),e._v(" "),r("span",{staticClass:"el-icon-question",attrs:{slot:"reference",tabindex:"-1"},slot:"reference"})]):e._e()],1),e._v(" "),"object"===t.type?r("data-table",{model:{value:e.record.config[t.key],callback:function(r){e.$set(e.record.config,t.key,r)},expression:"record.config[item.key]"}}):"emq-select"===t.type?r("emq-select",e._b({staticClass:"el-select--public",attrs:{"popper-class":"el-select--public"},model:{value:e.record.config[t.key],callback:function(r){e.$set(e.record.config,t.key,r)},expression:"record.config[item.key]"}},"emq-select",t.$attrs,!1)):"number"===t.type?r("el-input",e._b({attrs:{type:"number"},model:{value:e.record.config[t.key],callback:function(r){e.$set(e.record.config,t.key,e._n(r))},expression:"record.config[item.key]"}},"el-input",t.$attrs,!1)):r("el-input",e._b({model:{value:e.record.config[t.key],callback:function(r){e.$set(e.record.config,t.key,r)},expression:"record.config[item.key]"}},"el-input",t.$attrs,!1))],2)],1)}),1):e._e()],1)],1),e._v(" "),r("div",{attrs:{slot:"footer"},slot:"footer"},[r("el-button",{staticClass:"cache-btn",attrs:{type:"text"},on:{click:function(t){e.dialogVisible=!1}}},[e._v("\n "+e._s(e.$t("rule.cancel"))+"\n ")]),e._v(" "),r("el-button",{staticClass:"confirm-btn",attrs:{type:"success"},on:{click:e.handleCreate}},[e._v("\n "+e._s(e.$t("rule.create"))+"\n ")])],1)],1)},staticRenderFns:[]};var h=r("VU/8")(u,p,!1,function(e){r("jTzk")},null,null);t.a=h.exports},TQvf:function(e,t,r){ -/*! - * clipboard.js v2.0.6 - * https://clipboardjs.com/ - * - * Licensed MIT © Zeno Rocha - */ -var n;n=function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=6)}([function(e,t){e.exports=function(e){var t;if("SELECT"===e.nodeName)e.focus(),t=e.value;else if("INPUT"===e.nodeName||"TEXTAREA"===e.nodeName){var r=e.hasAttribute("readonly");r||e.setAttribute("readonly",""),e.select(),e.setSelectionRange(0,e.value.length),r||e.removeAttribute("readonly"),t=e.value}else{e.hasAttribute("contenteditable")&&e.focus();var n=window.getSelection(),i=document.createRange();i.selectNodeContents(e),n.removeAllRanges(),n.addRange(i),t=n.toString()}return t}},function(e,t){function r(){}r.prototype={on:function(e,t,r){var n=this.e||(this.e={});return(n[e]||(n[e]=[])).push({fn:t,ctx:r}),this},once:function(e,t,r){var n=this;function i(){n.off(e,i),t.apply(r,arguments)}return i._=t,this.on(e,i,r)},emit:function(e){for(var t=[].slice.call(arguments,1),r=((this.e||(this.e={}))[e]||[]).slice(),n=0,i=r.length;n0&&void 0!==arguments[0]?arguments[0]:{};this.action=e.action,this.container=e.container,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""}},{key:"initSelection",value:function(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function(){var e=this,t="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return e.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[t?"right":"left"]="-9999px";var r=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=r+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.container.appendChild(this.fakeElem),this.selectedText=i()(this.fakeElem),this.copyText()}},{key:"removeFake",value:function(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function(){this.selectedText=i()(this.target),this.copyText()}},{key:"copyText",value:function(){var e=void 0;try{e=document.execCommand(this.action)}catch(t){e=!1}this.handleResult(e)}},{key:"handleResult",value:function(e){this.emitter.emit(e?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function(){this.trigger&&this.trigger.focus(),document.activeElement.blur(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function(){this.removeFake()}},{key:"action",set:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(e){if(void 0!==e){if(!e||"object"!==(void 0===e?"undefined":a(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&e.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(e.hasAttribute("readonly")||e.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=e}},get:function(){return this._target}}]),e}(),c=r(1),l=r.n(c),u=r(2),p=r.n(u),h="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},d=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText,this.container="object"===h(e.container)?e.container:document.body}},{key:"listenClick",value:function(e){var t=this;this.listener=p()(e,"click",function(e){return t.onClick(e)})}},{key:"onClick",value:function(e){var t=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new o({action:this.action(t),target:this.target(t),text:this.text(t),container:this.container,trigger:t,emitter:this})}},{key:"defaultAction",value:function(e){return y("action",e)}},{key:"defaultTarget",value:function(e){var t=y("target",e);if(t)return document.querySelector(t)}},{key:"defaultText",value:function(e){return y("text",e)}},{key:"destroy",value:function(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],t="string"==typeof e?[e]:e,r=!!document.queryCommandSupported;return t.forEach(function(e){r=r&&!!document.queryCommandSupported(e)}),r}}]),t}();function y(e,t){var r="data-clipboard-"+e;if(t.hasAttribute(r))return t.getAttribute(r)}t.default=f}]).default},e.exports=n()},Xxa5:function(e,t,r){e.exports=r("1H6C")},cMrt:function(e,t){e.exports={en:{emqx_auth_clientid:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-clientid.html",emqx_auth_username:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-username.html",emqx_auth_http:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-http.html",emqx_auth_jwt:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-jwt.html",emqx_auth_ldap:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-ldap.html",emqx_auth_mnesia:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-mnesia.html",emqx_auth_mongo:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-mongodb.html",emqx_auth_mysql:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-mysql.html",emqx_auth_pgsql:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-postgresql.html",emqx_auth_redis:"https://docs.emqx.io/broker/v4.1/en/advanced/auth-redis.html",emqx_dashboard:"https://docs.emqx.io/broker/v4.1/en/getting-started/dashboard.html",emqx_extension_hook:"https://docs.emqx.io/broker/v4.1/en/advanced/multiple-language-support.html",emqx_rule_engine:"https://docs.emqx.io/broker/v4.1/en/rule/rule-engine.html"},zh:{emqx_auth_clientid:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-clientid.html",emqx_auth_username:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-username.html",emqx_auth_http:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-http.html",emqx_auth_jwt:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-jwt.html",emqx_auth_ldap:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-ldap.html",emqx_auth_mnesia:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-mnesia.html",emqx_auth_mongo:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-mongodb.html",emqx_auth_mysql:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-mysql.html",emqx_auth_pgsql:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-postgresql.html",emqx_auth_redis:"https://docs.emqx.io/broker/v4.1/cn/advanced/auth-redis.html",emqx_dashboard:"https://docs.emqx.io/broker/v4.1/cn/getting-started/dashboard.html",emqx_extension_hook:"https://docs.emqx.io/broker/v4.1/cn/advanced/multiple-language-support.html",emqx_rule_engine:"https://docs.emqx.io/broker/v4.1/cn/rule/rule-engine.html"}}},dmxg:function(e,t,r){var n,i=function(){var e=function(e,t,r,n){for(r=r||{},n=e.length;n--;r[e[n]]=t);return r},t=[1,8],r=[1,4],n=[2,4],i=[1,11],a=[1,10],s=[2,16],o=[1,14],c=[1,15],l=[1,16],u=[6,8],p=[2,144],h=[1,19],d=[1,20],f=[16,33,35,36,37,38,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],y=[16,18,32,33,35,36,37,38,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],v=[2,158],m=[1,29],b=[6,8,14,17,146,150,152,154],g=[1,42],_=[1,60],k=[1,51],E=[1,58],x=[1,59],O=[1,61],w=[1,62],S=[1,63],$=[1,64],T=[1,65],R=[1,57],I=[1,52],A=[1,53],L=[1,54],C=[1,55],N=[1,56],q=[1,43],F=[1,44],K=[1,45],P=[1,34],j=[16,35,36,37,38,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],B=[6,8,14,17,150,152,154],U=[2,141],D=[1,74],H=[1,75],M=[6,8,14,17,43,133,138,144,146,150,152,154],G=[1,80],V=[1,77],Q=[1,78],W=[1,79],X=[1,81],J=[6,8,14,17,36,43,49,50,71,72,74,77,89,107,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],z=[6,8,14,17,34,36,43,49,50,71,72,74,77,89,107,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],Y=[1,102],Z=[1,100],ee=[1,101],te=[1,96],re=[1,97],ne=[1,98],ie=[1,99],ae=[1,103],se=[1,104],oe=[1,105],ce=[1,106],le=[1,107],ue=[1,108],pe=[2,101],he=[6,8,14,17,34,36,43,45,49,50,71,72,74,77,79,81,89,91,92,93,94,95,96,97,98,99,101,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],de=[6,8,14,17,34,36,43,45,49,50,71,72,74,77,79,81,89,91,92,93,94,95,96,97,98,99,101,103,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],fe=[1,109],ye=[1,116],ve=[2,62],me=[1,117],be=[16,35,37,38,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],ge=[16,29,35,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,119],_e=[1,163],ke=[17,43],Ee=[2,57],xe=[1,172],Oe=[1,170],we=[1,171],Se=[6,8,138,146],$e=[16,35,38,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],Te=[6,8,14,17,138,144,146,150,152,154],Re=[6,8,14,17,36,43,49,50,71,72,74,77,89,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],Ie=[6,8,14,17,34,36,43,49,50,71,72,74,77,89,91,92,93,94,99,101,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],Ae=[6,8,14,17,34,36,43,49,50,71,72,74,77,79,81,89,91,92,93,94,99,101,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],Le=[16,35,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],Ce=[16,35,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],Ne=[16,35,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],qe=[71,74,77],Fe=[16,35,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],Ke=[1,232],Pe=[1,233],je=[6,8,14,17],Be=[6,8,14,17,43,157],Ue=[1,249],De=[1,245],He=[2,195],Me=[1,252],Ge=[1,253],Ve=[6,8,14,17,43,129,135,138,144,146,150,152,154,182],Qe=[1,255],We=[1,258],Xe=[1,259],Je=[1,260],ze=[1,261],Ye=[2,172],Ze=[1,257],et=[6,8,14,17,36,43,89,129,135,138,144,146,150,152,154,164,165,167,168,173,177,179,180,182],tt=[6,8,14,17,135,138,144,146,150,152,154],rt=[1,273],nt=[2,177],it=[170,173],at=[6,8,14,17,36,43,89,129,135,138,144,146,150,152,154,164,165,167,168,173,177,179,180,182,192,193,194],st=[2,197],ot=[1,278],ct=[1,290],lt=[1,298],ut=[1,299],pt=[1,300],ht=[6,8,14,17,138,146,150,152,154],dt=[1,310],ft=[1,316],yt=[1,317],vt=[2,202],mt=[1,328],bt=[16,152],gt=[6,8,14,17,152,154],_t=[1,344],kt={trace:function(){},yy:{},symbols_:{error:2,main:3,selectClause:4,semicolonOpt:5,EOF:6,unionClause:7,";":8,unionClauseNotParenthesized:9,unionClauseParenthesized:10,order_by_opt:11,limit_opt:12,selectClauseParenthesized:13,UNION:14,distinctOpt:15,"(":16,")":17,SELECT:18,highPriorityOpt:19,maxStateMentTimeOpt:20,straightJoinOpt:21,sqlSmallResultOpt:22,sqlBigResultOpt:23,sqlBufferResultOpt:24,sqlCacheOpt:25,sqlCalcFoundRowsOpt:26,selectExprList:27,selectDataSetOpt:28,ALL:29,DISTINCT:30,DISTINCTROW:31,HIGH_PRIORITY:32,MAX_STATEMENT_TIME:33,"=":34,NUMERIC:35,STRAIGHT_JOIN:36,SQL_SMALL_RESULT:37,SQL_BIG_RESULT:38,SQL_BUFFER_RESULT:39,SQL_CACHE:40,SQL_NO_CACHE:41,SQL_CALC_FOUND_ROWS:42,",":43,selectExpr:44,"*":45,SELECT_EXPR_STAR:46,expr:47,selectExprAliasOpt:48,AS:49,IDENTIFIER:50,string:51,QUOTED_IDENTIFIER:52,STRING:53,number:54,EXPONENT_NUMERIC:55,HEX_NUMERIC:56,boolean:57,TRUE:58,FALSE:59,null:60,NULL:61,literal:62,function_call:63,function_call_param_list:64,function_call_param:65,identifier:66,DOT:67,identifier_list:68,case_expr_opt:69,when_then_list:70,WHEN:71,THEN:72,case_when_else:73,ELSE:74,case_when:75,CASE:76,END:77,simple_expr_prefix:78,"+":79,simple_expr:80,"-":81,"~":82,"!":83,BINARY:84,expr_list:85,ROW:86,EXISTS:87,"{":88,"}":89,bit_expr:90,"|":91,"&":92,"<<":93,">>":94,"/":95,DIV:96,MOD:97,"%":98,"^":99,not_opt:100,NOT:101,escape_opt:102,ESCAPE:103,predicate:104,IN:105,BETWEEN:106,AND:107,SOUNDS:108,LIKE:109,REGEXP:110,comparison_operator:111,">=":112,">":113,"<=":114,"<":115,"<>":116,"!=":117,sub_query_data_set_opt:118,ANY:119,boolean_primary:120,IS:121,boolean_extra:122,UNKNOWN:123,"&&":124,"||":125,OR:126,XOR:127,where_opt:128,WHERE:129,group_by_opt:130,group_by:131,roll_up_opt:132,WITH:133,ROLLUP:134,GROUP_BY:135,group_by_order_by_item_list:136,order_by:137,ORDER_BY:138,group_by_order_by_item:139,sort_opt:140,ASC:141,DESC:142,having_opt:143,HAVING:144,limit:145,LIMIT:146,OFFSET:147,procedure_opt:148,procedure:149,PROCEDURE:150,for_update_lock_in_share_mode_opt:151,FOR:152,UPDATE:153,LOCK:154,SHARE:155,MODE:156,FROM:157,table_references:158,partitionOpt:159,escaped_table_reference:160,table_reference:161,OJ:162,join_inner_cross:163,INNER:164,CROSS:165,left_right:166,LEFT:167,RIGHT:168,out_opt:169,OUTER:170,left_right_out_opt:171,join_table:172,JOIN:173,table_factor:174,join_condition:175,on_join_condition:176,NATURAL:177,join_condition_opt:178,ON:179,USING:180,partition_names:181,PARTITION:182,aliasOpt:183,index_or_key:184,INDEX:185,KEY:186,for_opt:187,identifier_list_opt:188,index_hint_list_opt:189,index_hint_list:190,index_hint:191,USE:192,IGNORE:193,FORCE:194,$accept:0,$end:1},terminals_:{2:"error",6:"EOF",8:";",14:"UNION",16:"(",17:")",18:"SELECT",29:"ALL",30:"DISTINCT",31:"DISTINCTROW",32:"HIGH_PRIORITY",33:"MAX_STATEMENT_TIME",34:"=",35:"NUMERIC",36:"STRAIGHT_JOIN",37:"SQL_SMALL_RESULT",38:"SQL_BIG_RESULT",39:"SQL_BUFFER_RESULT",40:"SQL_CACHE",41:"SQL_NO_CACHE",42:"SQL_CALC_FOUND_ROWS",43:",",45:"*",46:"SELECT_EXPR_STAR",49:"AS",50:"IDENTIFIER",52:"QUOTED_IDENTIFIER",53:"STRING",55:"EXPONENT_NUMERIC",56:"HEX_NUMERIC",58:"TRUE",59:"FALSE",61:"NULL",67:"DOT",71:"WHEN",72:"THEN",74:"ELSE",76:"CASE",77:"END",79:"+",81:"-",82:"~",83:"!",84:"BINARY",86:"ROW",87:"EXISTS",88:"{",89:"}",91:"|",92:"&",93:"<<",94:">>",95:"/",96:"DIV",97:"MOD",98:"%",99:"^",101:"NOT",103:"ESCAPE",105:"IN",106:"BETWEEN",107:"AND",108:"SOUNDS",109:"LIKE",110:"REGEXP",112:">=",113:">",114:"<=",115:"<",116:"<>",117:"!=",119:"ANY",121:"IS",123:"UNKNOWN",124:"&&",125:"||",126:"OR",127:"XOR",129:"WHERE",133:"WITH",134:"ROLLUP",135:"GROUP_BY",138:"ORDER_BY",141:"ASC",142:"DESC",144:"HAVING",146:"LIMIT",147:"OFFSET",150:"PROCEDURE",152:"FOR",153:"UPDATE",154:"LOCK",155:"SHARE",156:"MODE",157:"FROM",162:"OJ",164:"INNER",165:"CROSS",167:"LEFT",168:"RIGHT",170:"OUTER",173:"JOIN",177:"NATURAL",179:"ON",180:"USING",182:"PARTITION",185:"INDEX",186:"KEY",192:"USE",193:"IGNORE",194:"FORCE"},productions_:[0,[3,3],[3,3],[5,1],[5,0],[7,1],[7,3],[10,4],[10,4],[13,3],[9,4],[9,4],[4,12],[15,1],[15,1],[15,1],[15,0],[19,1],[19,0],[20,3],[20,0],[21,1],[21,0],[22,1],[22,0],[23,1],[23,0],[24,1],[24,0],[25,0],[25,1],[25,1],[26,1],[26,0],[27,3],[27,1],[44,1],[44,1],[44,2],[48,0],[48,2],[48,1],[51,1],[51,1],[54,1],[54,1],[54,1],[57,1],[57,1],[60,1],[62,1],[62,1],[62,1],[62,1],[63,4],[64,3],[64,1],[65,0],[65,1],[65,1],[65,2],[65,1],[66,1],[66,3],[68,1],[68,3],[69,0],[69,1],[70,4],[70,5],[73,0],[73,2],[75,5],[78,2],[78,2],[78,2],[78,2],[78,2],[80,1],[80,1],[80,1],[80,1],[80,3],[80,4],[80,3],[80,4],[80,4],[80,1],[90,1],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[90,3],[100,0],[100,1],[102,0],[102,2],[104,1],[104,6],[104,6],[104,6],[104,4],[104,5],[104,4],[111,1],[111,1],[111,1],[111,1],[111,1],[111,1],[111,1],[118,1],[118,1],[120,1],[120,4],[120,3],[120,6],[122,1],[122,1],[47,1],[47,4],[47,2],[47,3],[47,3],[47,3],[47,3],[47,3],[85,1],[85,3],[128,0],[128,2],[130,0],[130,1],[132,0],[132,2],[131,3],[11,0],[11,1],[137,3],[136,1],[136,3],[139,2],[140,0],[140,1],[140,1],[143,0],[143,2],[145,2],[145,4],[145,4],[12,0],[12,1],[148,0],[148,1],[149,2],[151,0],[151,2],[151,4],[28,0],[28,10],[158,1],[158,3],[160,1],[160,4],[163,0],[163,1],[163,1],[166,1],[166,1],[169,0],[169,1],[171,0],[171,2],[172,4],[172,5],[172,4],[172,6],[172,5],[178,0],[178,1],[176,2],[175,1],[175,4],[161,1],[161,1],[181,1],[181,3],[159,0],[159,4],[183,0],[183,2],[183,1],[184,1],[184,1],[187,0],[187,2],[187,2],[187,2],[188,0],[188,1],[189,0],[189,1],[190,1],[190,3],[191,6],[191,6],[191,6],[174,4],[174,4],[174,3]],performAction:function(e,t,r,n,i,a,s){var o=a.length-1;switch(i){case 1:case 2:return{nodeType:"Main",value:a[o-2],hasSemicolon:a[o-1]};case 3:case 142:this.$=!0;break;case 4:this.$=!1;break;case 5:case 13:case 14:case 15:case 17:case 19:case 21:case 23:case 25:case 27:case 30:case 31:case 32:case 50:case 51:case 52:case 53:case 58:case 59:case 61:case 67:case 71:case 78:case 79:case 80:case 81:case 87:case 88:case 102:case 104:case 105:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 125:case 127:case 138:case 140:case 145:case 151:case 152:case 154:case 159:case 161:case 162:case 173:case 174:case 175:case 176:case 178:case 187:case 189:case 191:case 192:case 200:case 201:case 207:case 209:this.$=a[o];break;case 6:this.$=a[o-2],this.$.orderBy=a[o-1],this.$.limit=a[o];break;case 7:case 8:this.$={type:"Union",left:a[o-3],distinctOpt:a[o-1],right:a[o]};break;case 9:this.$={type:"SelectParenthesized",value:a[o-1]};break;case 10:case 11:this.$={type:"Union",left:a[o-3],distinctOpt:a[o-1],right:a[o]};break;case 12:this.$={type:"Select",distinctOpt:a[o-10],highPriorityOpt:a[o-9],maxStateMentTimeOpt:a[o-8],straightJoinOpt:a[o-7],sqlSmallResultOpt:a[o-6],sqlBigResultOpt:a[o-5],sqlBufferResultOpt:a[o-4],sqlCacheOpt:a[o-3],sqlCalcFoundRowsOpt:a[o-2],selectItems:a[o-1],from:a[o].from,partition:a[o].partition,where:a[o].where,groupBy:a[o].groupBy,having:a[o].having,orderBy:a[o].orderBy,limit:a[o].limit,procedure:a[o].procedure,updateLockMode:a[o].updateLockMode};break;case 16:case 18:case 20:case 22:case 24:case 26:case 28:case 29:case 33:case 57:case 66:case 70:case 101:case 103:case 137:case 139:case 141:case 144:case 150:case 153:case 158:case 160:case 163:case 172:case 177:case 186:case 195:case 202:case 206:case 208:this.$=null;break;case 34:a[o-2].value.push(a[o]);break;case 35:this.$={type:"SelectExpr",value:[a[o]]};break;case 36:case 37:case 62:this.$={type:"Identifier",value:a[o]};break;case 38:this.$=a[o-1],this.$.alias=a[o].alias,this.$.hasAs=a[o].hasAs;break;case 39:case 197:this.$={alias:null,hasAs:null};break;case 40:this.$={alias:a[o],hasAs:!0};break;case 41:this.$={alias:a[o],hasAs:!1};break;case 42:case 43:this.$={type:"String",value:a[o]};break;case 44:case 45:case 46:this.$={type:"Number",value:a[o]};break;case 47:this.$={type:"Boolean",value:"TRUE"};break;case 48:this.$={type:"Boolean",value:"FALSE"};break;case 49:this.$={type:"Null",value:"null"};break;case 54:this.$={type:"FunctionCall",name:a[o-3],params:a[o-1]};break;case 55:a[o-2].push(a[o]),this.$=a[o-2];break;case 56:this.$=[a[o]];break;case 60:this.$={type:"FunctionCallParam",distinctOpt:a[o-1],value:a[o]};break;case 63:this.$=a[o-2],a[o-2].value+="."+a[o];break;case 64:this.$={type:"IdentifierList",value:[a[o]]};break;case 65:case 169:this.$=a[o-2],a[o-2].value.push(a[o]);break;case 68:this.$={type:"WhenThenList",value:[{when:a[o-2],then:a[o]}]};break;case 69:this.$=a[o-4],this.$.value.push({when:a[o-2],then:a[o]});break;case 72:this.$={type:"CaseWhen",caseExprOpt:a[o-3],whenThenList:a[o-2],else:a[o-1]};break;case 73:case 74:case 75:case 76:case 77:this.$={type:"Prefix",prefix:a[o-1],value:a[o]};break;case 82:this.$={type:"SimpleExprParentheses",value:a[o-1]};break;case 83:this.$={type:"SimpleExprParentheses",value:a[o-2],hasRow:!0};break;case 84:this.$={type:"SubQuery",value:a[o-1]};break;case 85:this.$={type:"SubQuery",value:a[o-1],hasExists:!0};break;case 86:this.$={type:"IdentifierExpr",identifier:a[o-2],value:a[o-1]};break;case 89:this.$={type:"BitExpression",operator:"|",left:a[o-2],right:a[o]};break;case 90:this.$={type:"BitExpression",operator:"&",left:a[o-2],right:a[o]};break;case 91:this.$={type:"BitExpression",operator:"<<",left:a[o-2],right:a[o]};break;case 92:this.$={type:"BitExpression",operator:">>",left:a[o-2],right:a[o]};break;case 93:this.$={type:"BitExpression",operator:"+",left:a[o-2],right:a[o]};break;case 94:this.$={type:"BitExpression",operator:"-",left:a[o-2],right:a[o]};break;case 95:this.$={type:"BitExpression",operator:"*",left:a[o-2],right:a[o]};break;case 96:this.$={type:"BitExpression",operator:"/",left:a[o-2],right:a[o]};break;case 97:this.$={type:"BitExpression",operator:"DIV",left:a[o-2],right:a[o]};break;case 98:this.$={type:"BitExpression",operator:"MOD",left:a[o-2],right:a[o]};break;case 99:this.$={type:"BitExpression",operator:"%",left:a[o-2],right:a[o]};break;case 100:this.$={type:"BitExpression",operator:"^",left:a[o-2],right:a[o]};break;case 106:this.$={type:"InSubQueryPredicate",hasNot:a[o-4],left:a[o-5],right:a[o-1]};break;case 107:this.$={type:"InExpressionListPredicate",hasNot:a[o-4],left:a[o-5],right:a[o-1]};break;case 108:this.$={type:"BetweenPredicate",hasNot:a[o-4],left:a[o-5],right:{left:a[o-2],right:a[o]}};break;case 109:this.$={type:"SoundsLikePredicate",hasNot:!1,left:a[o-3],right:a[o]};break;case 110:this.$={type:"LikePredicate",hasNot:a[o-3],left:a[o-4],right:a[o-1],escape:a[o]};break;case 111:this.$={type:"RegexpPredicate",hasNot:a[o-2],left:a[o-3],right:a[o]};break;case 122:this.$={type:"IsNullBooleanPrimary",hasNot:a[o-1],value:a[o-3]};break;case 123:this.$={type:"ComparisonBooleanPrimary",left:a[o-2],operator:a[o-1],right:a[o]};break;case 124:this.$={type:"ComparisonSubQueryBooleanPrimary",operator:a[o-4],subQueryOpt:a[o-3],left:a[o-5],right:a[o-1]};break;case 126:this.$={type:"BooleanExtra",value:a[o]};break;case 128:this.$={type:"IsExpression",hasNot:a[o-1],left:a[o-3],right:a[o]};break;case 129:this.$={type:"NotExpression",value:a[o]};break;case 130:case 133:this.$={type:"AndExpression",operator:a[o-1],left:a[o-2],right:a[o]};break;case 131:case 132:this.$={type:"OrExpression",operator:a[o-1],left:a[o-2],right:a[o]};break;case 134:this.$={type:"XORExpression",left:a[o-2],right:a[o]};break;case 135:this.$={type:"ExpressionList",value:[a[o]]};break;case 136:case 211:this.$=a[o-2],this.$.value.push(a[o]);break;case 143:this.$={type:"GroupBy",value:a[o-1],rollUp:a[o]};break;case 146:this.$={type:"OrderBy",value:a[o-1],rollUp:a[o]};break;case 147:case 193:this.$=[a[o]];break;case 148:this.$=a[o-2],a[o-2].push(a[o]);break;case 149:this.$={type:"GroupByOrderByItem",value:a[o-1],sortOpt:a[o]};break;case 155:this.$={type:"Limit",value:[a[o]]};break;case 156:this.$={type:"Limit",value:[a[o-2],a[o]]};break;case 157:this.$={type:"Limit",value:[a[o],a[o-2]],offsetMode:!0};break;case 164:this.$=a[o-1]+" "+a[o];break;case 165:this.$=a[o-3]+" "+a[o-2]+" "+a[o-1]+" "+a[o];break;case 166:this.$={};break;case 167:this.$={from:a[o-8],partition:a[o-7],where:a[o-6],groupBy:a[o-5],having:a[o-4],orderBy:a[o-3],limit:a[o-2],procedure:a[o-1],updateLockMode:a[o]};break;case 168:this.$={type:"TableReferences",value:[a[o]]};break;case 170:this.$={type:"TableReference",value:a[o]};break;case 171:this.$={type:"TableReference",hasOj:!0,value:a[o-1]};break;case 179:this.$={leftRight:null,outOpt:null};break;case 180:this.$={leftRight:a[o-1],outOpt:a[o]};break;case 181:this.$={type:"InnerCrossJoinTable",innerCrossOpt:a[o-2],left:a[o-3],right:a[o],condition:null};break;case 182:this.$={type:"InnerCrossJoinTable",innerCrossOpt:a[o-3],left:a[o-4],right:a[o-1],condition:a[o]};break;case 183:this.$={type:"StraightJoinTable",left:a[o-3],right:a[o-1],condition:a[o]};break;case 184:this.$={type:"LeftRightJoinTable",leftRight:a[o-4],outOpt:a[o-3],left:a[o-5],right:a[o-1],condition:a[o]};break;case 185:this.$={type:"NaturalJoinTable",leftRight:a[o-2].leftRight,outOpt:a[o-2].outOpt,left:a[o-4],right:a[o]};break;case 188:this.$={type:"OnJoinCondition",value:a[o]};break;case 190:this.$={type:"UsingJoinCondition",value:a[o-1]};break;case 194:this.$=a[o-2],a[o-2].push(a[o]);break;case 196:this.$={type:"Partitions",value:a[o-1]};break;case 198:this.$={hasAs:!0,alias:a[o]};break;case 199:this.$={hasAs:!1,alias:a[o]};break;case 203:case 204:case 205:this.$={type:"ForOptIndexHint",value:a[o]};break;case 210:this.$={type:"IndexHintList",value:[a[o]]};break;case 212:this.$={type:"UseIndexHint",value:a[o-1],forOpt:a[o-3],indexOrKey:a[o-4]};break;case 213:this.$={type:"IgnoreIndexHint",value:a[o-1],forOpt:a[o-3],indexOrKey:a[o-4]};break;case 214:this.$={type:"ForceIndexHint",value:a[o-1],forOpt:a[o-3],indexOrKey:a[o-4]};break;case 215:this.$={type:"TableFactor",value:a[o-3],partition:a[o-2],alias:a[o-1].alias,hasAs:a[o-1].hasAs,indexHintOpt:a[o]};break;case 216:this.$={type:"SubQuery",value:a[o-2],alias:a[o].alias,hasAs:a[o].hasAs};break;case 217:this.$=a[o-1],this.$.hasParentheses=!0}},table:[{3:1,4:2,7:3,9:5,10:6,13:7,16:t,18:r},{1:[3]},{5:9,6:n,8:i,14:a},{5:12,6:n,8:i},e([16,32,33,35,36,37,38,39,40,41,42,45,46,50,52,53,55,56,58,59,61,76,79,81,82,83,84,86,87,88,101],s,{15:13,29:o,30:c,31:l}),e(u,[2,5]),e([6,8,146],p,{11:17,137:18,138:h}),{14:d},{4:21,18:r},{6:[1,22]},{15:23,18:s,29:o,30:c,31:l},{6:[2,3]},{6:[1,24]},e(f,[2,18],{19:25,32:[1,26]}),e(y,[2,13]),e(y,[2,14]),e(y,[2,15]),e(u,v,{12:27,145:28,146:m}),e(b,[2,145]),{16:g,35:_,47:32,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33,136:30,139:31},{15:66,16:s,29:o,30:c,31:l},{17:[1,67]},{1:[2,1]},{4:68,9:69,18:r},{1:[2,2]},e(j,[2,20],{20:70,33:[1,71]}),e(f,[2,17]),e(u,[2,6]),e(B,[2,159]),{35:[1,72]},e(b,U,{132:73,43:D,133:H}),e(M,[2,147]),e(M,[2,150],{140:76,107:G,124:V,125:Q,126:W,127:X,141:[1,82],142:[1,83]}),e(J,[2,127],{111:85,34:[1,86],112:[1,87],113:[1,88],114:[1,89],115:[1,90],116:[1,91],117:[1,92],121:[1,84]}),{16:g,35:_,47:93,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(z,[2,121]),e(z,[2,105],{100:94,45:Y,79:Z,81:ee,91:te,92:re,93:ne,94:ie,95:ae,96:se,97:oe,98:ce,99:le,101:ue,105:pe,106:pe,109:pe,110:pe,108:[1,95]}),e(he,[2,88]),e(de,[2,78]),e(de,[2,79],{67:fe}),e(de,[2,80]),e(de,[2,81]),{4:111,16:g,18:r,35:_,47:112,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,85:110,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:[1,113]},{16:[1,114]},{50:ye,66:115},e(de,[2,87]),e(de,[2,50]),e(de,[2,51]),e(de,[2,52]),e(de,[2,53]),e([6,8,14,17,34,36,43,45,49,50,67,71,72,74,77,79,81,89,91,92,93,94,95,96,97,98,99,101,103,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],ve,{16:me}),{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:118,81:A,82:L,83:C,84:N,86:q,87:F,88:K},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:119,81:A,82:L,83:C,84:N,86:q,87:F,88:K},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:120,81:A,82:L,83:C,84:N,86:q,87:F,88:K},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:121,81:A,82:L,83:C,84:N,86:q,87:F,88:K},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:122,81:A,82:L,83:C,84:N,86:q,87:F,88:K},{16:g,35:_,47:124,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,69:123,71:[2,66],75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(de,[2,42]),e(de,[2,43]),e(de,[2,44]),e(de,[2,45]),e(de,[2,46]),e(de,[2,47]),e(de,[2,48]),e(de,[2,49]),{10:126,13:125,16:t},e([6,8,14,138,146],[2,9]),e(u,[2,10],{14:a}),e(u,[2,11]),e(be,[2,22],{21:127,36:[1,128]}),{34:[1,129]},e(B,[2,155],{43:[1,130],147:[1,131]}),e(b,[2,146]),{16:g,35:_,47:32,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33,139:132},{134:[1,133]},e(M,[2,149]),{16:g,35:_,47:134,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:g,35:_,47:135,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:g,35:_,47:136,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:g,35:_,47:137,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:g,35:_,47:138,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(M,[2,151]),e(M,[2,152]),e([58,59,61,123],pe,{100:139,101:ue}),{16:g,29:[1,142],35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,104:140,118:141,119:[1,143]},e(ge,[2,112]),e(ge,[2,113]),e(ge,[2,114]),e(ge,[2,115]),e(ge,[2,116]),e(ge,[2,117]),e(ge,[2,118]),e(J,[2,129]),{105:[1,144],106:[1,145],109:[1,146],110:[1,147]},{109:[1,148]},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:149},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:150},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:151},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:152},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:153},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:154},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:155},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:156},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:157},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:158},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:159},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:160},e([58,59,61,105,106,109,110,123],[2,102]),{50:[1,161]},{17:[1,162],43:_e},{17:[1,164]},e(ke,[2,135],{107:G,124:V,125:Q,126:W,127:X}),{16:g,35:_,47:112,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,85:165,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{4:166,18:r},{16:g,35:_,47:167,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,67:fe,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e([6,8,14,16,17,35,36,43,49,50,52,53,55,56,58,59,61,67,76,79,81,82,83,84,86,87,88,89,101,129,135,138,144,146,150,152,154,164,165,167,168,173,177,179,180,182,192,193,194],ve),e(ke,Ee,{120:33,104:35,90:36,80:37,62:38,66:39,63:40,78:41,75:46,51:47,54:48,57:49,60:50,64:168,65:169,47:173,16:g,30:xe,35:_,45:Oe,46:we,50:k,52:E,53:x,55:O,56:w,58:S,59:$,61:T,76:R,79:I,81:A,82:L,83:C,84:N,86:q,87:F,88:K,101:P}),e(de,[2,73]),e(de,[2,74]),e(de,[2,75]),e(de,[2,76]),e(de,[2,77]),{70:174,71:[1,175]},{71:[2,67],107:G,124:V,125:Q,126:W,127:X},e(Se,[2,7],{14:d}),e(Se,[2,8]),e($e,[2,24],{22:176,37:[1,177]}),e(be,[2,21]),{35:[1,178]},{35:[1,179]},{35:[1,180]},e(M,[2,148]),e(Te,[2,142]),e(J,[2,130]),e(Re,[2,131],{107:G,124:V}),e(Re,[2,132],{107:G,124:V}),e(J,[2,133]),e(Re,[2,134],{107:G,124:V}),{57:183,58:S,59:$,61:[1,182],122:181,123:[1,184]},e(z,[2,123]),{16:[1,185]},{16:[2,119]},{16:[2,120]},{16:[1,186]},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:187},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:188,81:A,82:L,83:C,84:N,86:q,87:F,88:K},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:189},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:190},e([6,8,14,17,34,36,43,49,50,71,72,74,77,89,91,101,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],[2,89],{45:Y,79:Z,81:ee,92:re,93:ne,94:ie,95:ae,96:se,97:oe,98:ce,99:le}),e([6,8,14,17,34,36,43,49,50,71,72,74,77,89,91,92,99,101,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],[2,90],{45:Y,79:Z,81:ee,93:ne,94:ie,95:ae,96:se,97:oe,98:ce}),e(Ie,[2,91],{45:Y,79:Z,81:ee,95:ae,96:se,97:oe,98:ce}),e(Ie,[2,92],{45:Y,79:Z,81:ee,95:ae,96:se,97:oe,98:ce}),e(Ae,[2,93],{45:Y,95:ae,96:se,97:oe,98:ce}),e(Ae,[2,94],{45:Y,95:ae,96:se,97:oe,98:ce}),e(he,[2,95]),e(he,[2,96]),e(he,[2,97]),e(he,[2,98]),e(he,[2,99]),e([6,8,14,17,34,36,43,49,50,71,72,74,77,89,91,99,101,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182],[2,100],{45:Y,79:Z,81:ee,92:re,93:ne,94:ie,95:ae,96:se,97:oe,98:ce}),e([6,8,14,16,17,34,35,36,43,45,49,50,52,53,55,56,58,59,61,67,71,72,74,76,77,79,81,82,83,84,86,87,88,89,91,92,93,94,95,96,97,98,99,101,103,105,106,107,108,109,110,112,113,114,115,116,117,121,124,125,126,127,129,133,135,138,141,142,144,146,150,152,154,157,164,165,167,168,173,177,179,180,182,192,193,194],[2,63]),e(de,[2,82]),{16:g,35:_,47:191,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(de,[2,84]),{17:[1,192],43:_e},{17:[1,193]},{89:[1,194],107:G,124:V,125:Q,126:W,127:X},{17:[1,195],43:[1,196]},e(ke,[2,56]),e(ke,[2,58]),e(ke,[2,59]),{16:g,35:_,47:197,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(ke,[2,61],{107:G,124:V,125:Q,126:W,127:X}),{71:[1,199],73:198,74:[1,200],77:[2,70]},{16:g,35:_,47:201,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(Le,[2,26],{23:202,38:[1,203]}),e($e,[2,23]),e(j,[2,19]),e(B,[2,156]),e(B,[2,157]),e(J,[2,128]),e(z,[2,122]),e(J,[2,125]),e(J,[2,126]),{4:204,18:r},{4:205,16:g,18:r,35:_,47:112,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,85:206,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{45:Y,79:Z,81:ee,91:te,92:re,93:ne,94:ie,95:ae,96:se,97:oe,98:ce,99:le,107:[1,207]},e(z,[2,103],{102:208,103:[1,209]}),e(z,[2,111],{45:Y,79:Z,81:ee,91:te,92:re,93:ne,94:ie,95:ae,96:se,97:oe,98:ce,99:le}),e(z,[2,109],{45:Y,79:Z,81:ee,91:te,92:re,93:ne,94:ie,95:ae,96:se,97:oe,98:ce,99:le}),e(ke,[2,136],{107:G,124:V,125:Q,126:W,127:X}),e(de,[2,83]),e(de,[2,85]),e(de,[2,86]),e(de,[2,54]),e(ke,Ee,{120:33,104:35,90:36,80:37,62:38,66:39,63:40,78:41,75:46,51:47,54:48,57:49,60:50,47:173,65:210,16:g,30:xe,35:_,45:Oe,46:we,50:k,52:E,53:x,55:O,56:w,58:S,59:$,61:T,76:R,79:I,81:A,82:L,83:C,84:N,86:q,87:F,88:K,101:P}),e(ke,[2,60],{107:G,124:V,125:Q,126:W,127:X}),{77:[1,211]},{16:g,35:_,47:212,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:g,35:_,47:213,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{72:[1,214],107:G,124:V,125:Q,126:W,127:X},e(Ce,[2,28],{24:215,39:[1,216]}),e(Le,[2,25]),{17:[1,217]},{17:[1,218]},{17:[1,219],43:_e},{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,104:220},e(z,[2,110]),{16:g,35:_,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:221,81:A,82:L,83:C,84:N,86:q,87:F,88:K},e(ke,[2,55]),e(de,[2,72]),{72:[1,222],107:G,124:V,125:Q,126:W,127:X},{77:[2,71],107:G,124:V,125:Q,126:W,127:X},{16:g,35:_,47:223,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(Ne,[2,29],{25:224,40:[1,225],41:[1,226]}),e(Ce,[2,27]),e(z,[2,124]),e(z,[2,106]),e(z,[2,107]),e(z,[2,108]),e(z,[2,104]),{16:g,35:_,47:227,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(qe,[2,68],{107:G,124:V,125:Q,126:W,127:X}),e(Fe,[2,33],{26:228,42:[1,229]}),e(Ne,[2,30]),e(Ne,[2,31]),e(qe,[2,69],{107:G,124:V,125:Q,126:W,127:X}),{16:g,27:230,35:_,44:231,45:Ke,46:Pe,47:234,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(Fe,[2,32]),e(je,[2,166],{28:235,43:[1,236],157:[1,237]}),e(Be,[2,35]),e(Be,[2,36]),e(Be,[2,37]),e(Be,[2,39],{48:238,49:[1,239],50:[1,240],107:G,124:V,125:Q,126:W,127:X}),e(je,[2,12]),{16:g,35:_,44:241,45:Ke,46:Pe,47:234,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:Ue,50:ye,66:248,88:De,158:242,160:243,161:244,172:247,174:246},e(Be,[2,38]),{50:[1,250]},e(Be,[2,41]),e(Be,[2,34]),e([6,8,14,17,129,135,138,144,146,150,152,154],He,{159:251,43:Me,182:Ge}),e(Ve,[2,168]),e(Ve,[2,170],{163:254,166:256,36:Qe,164:We,165:Xe,167:Je,168:ze,173:Ye,177:Ze}),{162:[1,262]},e(et,[2,191]),e(et,[2,192]),e([6,8,14,17,36,43,49,50,89,129,135,138,144,146,150,152,154,164,165,167,168,173,177,179,180,192,193,194],He,{159:263,67:fe,182:Ge}),{4:264,16:Ue,18:r,50:ye,66:248,88:De,158:265,160:243,161:244,172:247,174:246},e(Be,[2,40]),e(tt,[2,137],{128:266,129:[1,267]}),{16:Ue,50:ye,66:248,88:De,160:268,161:244,172:247,174:246},{16:[1,269]},{173:[1,270]},{16:Ue,50:ye,66:248,174:271},{169:272,170:rt,173:nt},{166:275,167:Je,168:ze,171:274,173:[2,179]},{173:[2,173]},{173:[2,174]},e(it,[2,175]),e(it,[2,176]),{16:Ue,50:ye,66:248,161:276,172:247,174:246},e(at,st,{183:277,66:279,49:ot,50:ye}),{17:[1,280]},{17:[1,281],43:Me},e(Te,[2,139],{130:282,131:283,135:[1,284]}),{16:g,35:_,47:285,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(Ve,[2,169]),{50:ye,66:287,181:286},{16:Ue,50:ye,66:248,174:288},{176:289,179:ct},{173:[1,291]},{173:[2,178]},{173:[1,292]},{169:293,170:rt,173:nt},{36:Qe,89:[1,294],163:254,164:We,165:Xe,166:256,167:Je,168:ze,173:Ye,177:Ze},e(et,[2,208],{189:295,190:296,191:297,192:lt,193:ut,194:pt}),{50:ye,66:301},e(at,[2,199],{67:fe}),e(et,st,{66:279,183:302,49:ot,50:ye}),e(et,[2,217]),e(ht,[2,153],{143:303,144:[1,304]}),e(Te,[2,140]),{16:g,35:_,47:32,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33,136:305,139:31},e(tt,[2,138],{107:G,124:V,125:Q,126:W,127:X}),{17:[1,306],43:[1,307]},e(ke,[2,193],{67:fe}),e([6,8,14,17,36,43,89,129,135,138,144,146,150,152,154,164,165,167,168,173,177,182],[2,181],{175:308,176:309,179:ct,180:dt}),e(et,[2,183]),{16:g,35:_,47:311,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},{16:Ue,50:ye,66:248,161:312,172:247,174:246},{16:Ue,50:ye,66:248,174:313},{173:[2,180]},e(Ve,[2,171]),e(et,[2,215]),e(et,[2,209]),e(et,[2,210]),{184:315,185:ft,186:yt},{184:318,185:ft,186:yt},{184:319,185:ft,186:yt},e(at,[2,198],{67:fe}),e(et,[2,216]),e(b,p,{137:18,11:320,138:h}),{16:g,35:_,47:321,50:k,51:47,52:E,53:x,54:48,55:O,56:w,57:49,58:S,59:$,60:50,61:T,62:38,63:40,66:39,75:46,76:R,78:41,79:I,80:37,81:A,82:L,83:C,84:N,86:q,87:F,88:K,90:36,101:P,104:35,120:33},e(Te,U,{132:322,43:D,133:H}),e([6,8,14,17,36,43,49,50,89,129,135,138,144,146,150,152,154,164,165,167,168,173,177,179,180,182,192,193,194],[2,196]),{50:ye,66:323},e(et,[2,182]),e(et,[2,189]),{16:[1,324]},e(et,[2,188],{107:G,124:V,125:Q,126:W,127:X}),{36:Qe,163:254,164:We,165:Xe,166:256,167:Je,168:ze,173:Ye,175:325,176:309,177:Ze,179:ct,180:dt},e(et,[2,185]),{191:326,192:lt,193:ut,194:pt},{16:vt,152:mt,187:327},e(bt,[2,200]),e(bt,[2,201]),{16:vt,152:mt,187:329},{16:vt,152:mt,187:330},e(B,v,{145:28,12:331,146:m}),e(ht,[2,154],{107:G,124:V,125:Q,126:W,127:X}),e(Te,[2,143]),e(ke,[2,194],{67:fe}),{50:ye,66:333,68:332},e(et,[2,184]),e(et,[2,211]),{16:[1,334]},{135:[1,337],138:[1,336],173:[1,335]},{16:[1,338]},{16:[1,339]},e(gt,[2,160],{148:340,149:341,150:[1,342]}),{17:[1,343],43:_t},e(ke,[2,64],{67:fe}),{17:[2,206],50:ye,66:333,68:346,188:345},{16:[2,203]},{16:[2,204]},{16:[2,205]},{50:ye,66:333,68:347},{50:ye,66:333,68:348},e(je,[2,163],{151:349,152:[1,350],154:[1,351]}),e(gt,[2,161]),{50:[1,353],63:352},e(et,[2,190]),{50:ye,66:354},{17:[1,355]},{17:[2,207],43:_t},{17:[1,356],43:_t},{17:[1,357],43:_t},e(je,[2,167]),{153:[1,358]},{105:[1,359]},e(gt,[2,162]),{16:me},e(ke,[2,65],{67:fe}),e(et,[2,212]),e(et,[2,213]),e(et,[2,214]),e(je,[2,164]),{155:[1,360]},{156:[1,361]},e(je,[2,165])],defaultActions:{11:[2,3],22:[2,1],24:[2,2],142:[2,119],143:[2,120],258:[2,173],259:[2,174],273:[2,178],293:[2,180],335:[2,203],336:[2,204],337:[2,205]},parseError:function(e,t){if(!t.recoverable){var r=new Error(e);throw r.hash=t,r}this.trace(e)},parse:function(e){var t=this,r=[0],n=[null],i=[],a=this.table,s="",o=0,c=0,l=0,u=i.slice.call(arguments,1),p=Object.create(this.lexer),h={yy:{}};for(var d in this.yy)Object.prototype.hasOwnProperty.call(this.yy,d)&&(h.yy[d]=this.yy[d]);p.setInput(e,h.yy),h.yy.lexer=p,h.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var f=p.yylloc;i.push(f);var y=p.options&&p.options.ranges;"function"==typeof h.yy.parseError?this.parseError=h.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var v,m,b,g,_,k,E,x,O,w=function(){var e;return"number"!=typeof(e=p.lex()||1)&&(e=t.symbols_[e]||e),e},S={};;){if(b=r[r.length-1],this.defaultActions[b]?g=this.defaultActions[b]:(null!==v&&void 0!==v||(v=w()),g=a[b]&&a[b][v]),void 0===g||!g.length||!g[0]){var $="";for(k in O=[],a[b])this.terminals_[k]&&k>2&&O.push("'"+this.terminals_[k]+"'");$=p.showPosition?"Parse error on line "+(o+1)+":\n"+p.showPosition()+"\nExpecting "+O.join(", ")+", got '"+(this.terminals_[v]||v)+"'":"Parse error on line "+(o+1)+": Unexpected "+(1==v?"end of input":"'"+(this.terminals_[v]||v)+"'"),this.parseError($,{text:p.match,token:this.terminals_[v]||v,line:p.yylineno,loc:f,expected:O})}if(g[0]instanceof Array&&g.length>1)throw new Error("Parse Error: multiple actions possible at state: "+b+", token: "+v);switch(g[0]){case 1:r.push(v),n.push(p.yytext),i.push(p.yylloc),r.push(g[1]),v=null,m?(v=m,m=null):(c=p.yyleng,s=p.yytext,o=p.yylineno,f=p.yylloc,l>0&&l--);break;case 2:if(E=this.productions_[g[1]][1],S.$=n[n.length-E],S._$={first_line:i[i.length-(E||1)].first_line,last_line:i[i.length-1].last_line,first_column:i[i.length-(E||1)].first_column,last_column:i[i.length-1].last_column},y&&(S._$.range=[i[i.length-(E||1)].range[0],i[i.length-1].range[1]]),void 0!==(_=this.performAction.apply(S,[s,c,o,h.yy,g[1],n,i].concat(u))))return _;E&&(r=r.slice(0,-1*E*2),n=n.slice(0,-1*E),i=i.slice(0,-1*E)),r.push(this.productions_[g[1]][0]),n.push(S.$),i.push(S._$),x=a[r[r.length-2]][r[r.length-1]],r.push(x);break;case 3:return!0}}return!0}},Et={EOF:1,parseError:function(e,t){if(!this.yy.parser)throw new Error(e);this.yy.parser.parseError(e,t)},setInput:function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},unput:function(e){var t=e.length,r=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var n=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),r.length-1&&(this.yylineno-=r.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:r?(r.length===n.length?this.yylloc.first_column:0)+n[n.length-r.length].length-r[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(e){this.unput(this.match.slice(e))},pastInput:function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?"...":"")+e.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var e=this.pastInput(),t=new Array(e.length+1).join("-");return e+this.upcomingInput()+"\n"+t+"^"},test_match:function(e,t){var r,n,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(n=e[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=n.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:n?n[n.length-1].length-n[n.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],r=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),r)return r;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var e,t,r,n;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;at[0].length)){if(t=r,n=a,this.options.backtrack_lexer){if(!1!==(e=this.test_match(r,i[a])))return e;if(this._backtrack){t=!1;continue}return!1}if(!this.options.flex)break}return t?!1!==(e=this.test_match(t,i[n]))&&e:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var e=this.next();return e||this.lex()},begin:function(e){this.conditionStack.push(e)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(e){return(e=this.conditionStack.length-1-Math.abs(e||0))>=0?this.conditionStack[e]:"INITIAL"},pushState:function(e){this.begin(e)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(e,t,r,n){switch(r){case 0:case 1:case 2:case 3:break;case 4:case 5:case 6:return 50;case 7:return 18;case 8:return 29;case 9:return 119;case 10:return 30;case 11:return 31;case 12:return 32;case 13:return 33;case 14:return 36;case 15:return 37;case 16:return 38;case 17:return 39;case 18:return 40;case 19:return 41;case 20:return 42;case 21:return 46;case 22:return 49;case 23:return 58;case 24:return 59;case 25:return 61;case 26:return"COLLATE";case 27:return 84;case 28:return 86;case 29:return 87;case 30:return 76;case 31:return 71;case 32:return 72;case 33:return 74;case 34:return 77;case 35:return 96;case 36:return 97;case 37:return 101;case 38:return 106;case 39:return 105;case 40:return 108;case 41:return 109;case 42:return 103;case 43:return 110;case 44:return 121;case 45:return 123;case 46:return 107;case 47:return 126;case 48:return 127;case 49:return 157;case 50:return 182;case 51:return 192;case 52:return 185;case 53:return 186;case 54:return 152;case 55:return 173;case 56:return 138;case 57:return 135;case 58:return 193;case 59:return 194;case 60:return 164;case 61:return 165;case 62:return 179;case 63:return 180;case 64:return 167;case 65:return 168;case 66:return 170;case 67:return 177;case 68:return 129;case 69:return 141;case 70:return 142;case 71:return 133;case 72:return 134;case 73:return 144;case 74:return 147;case 75:return 150;case 76:return 153;case 77:return 154;case 78:return 155;case 79:return 156;case 80:return 162;case 81:return 146;case 82:return 14;case 83:return 43;case 84:return 34;case 85:return 16;case 86:return 17;case 87:return 82;case 88:return 117;case 89:return 83;case 90:return 91;case 91:return 92;case 92:return 79;case 93:return 81;case 94:return 45;case 95:return 95;case 96:return 98;case 97:return 99;case 98:return 94;case 99:return 112;case 100:return 113;case 101:return 93;case 102:return"<=>";case 103:return 114;case 104:return 116;case 105:return 115;case 106:return 88;case 107:return 89;case 108:return 8;case 109:case 110:return 53;case 111:return 56;case 112:return 35;case 113:return 55;case 114:return 50;case 115:return 67;case 116:return 52;case 117:return 6;case 118:return"INVALID"}},rules:[/^(?:[\/][*](.|\n)*?[*][\/])/i,/^(?:[-][-]\s.*\n)/i,/^(?:[#]\s.*\n)/i,/^(?:\s+)/i,/^(?:[`][a-zA-Z_\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]*[`])/i,/^(?:[\w]+[\u4e00-\u9fa5]+[0-9a-zA-Z_\u4e00-\u9fa5]*)/i,/^(?:[\u4e00-\u9fa5][0-9a-zA-Z_\u4e00-\u9fa5]*)/i,/^(?:SELECT\b)/i,/^(?:ALL\b)/i,/^(?:ANY\b)/i,/^(?:DISTINCT\b)/i,/^(?:DISTINCTROW\b)/i,/^(?:HIGH_PRIORITY\b)/i,/^(?:MAX_STATEMENT_TIME\b)/i,/^(?:STRAIGHT_JOIN\b)/i,/^(?:SQL_SMALL_RESULT\b)/i,/^(?:SQL_BIG_RESULT\b)/i,/^(?:SQL_BUFFER_RESULT\b)/i,/^(?:SQL_CACHE\b)/i,/^(?:SQL_NO_CACHE\b)/i,/^(?:SQL_CALC_FOUND_ROWS\b)/i,/^(?:([a-zA-Z_\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]*\.){1,2}\*)/i,/^(?:AS\b)/i,/^(?:TRUE\b)/i,/^(?:FALSE\b)/i,/^(?:NULL\b)/i,/^(?:COLLATE\b)/i,/^(?:BINARY\b)/i,/^(?:ROW\b)/i,/^(?:EXISTS\b)/i,/^(?:CASE\b)/i,/^(?:WHEN\b)/i,/^(?:THEN\b)/i,/^(?:ELSE\b)/i,/^(?:END\b)/i,/^(?:DIV\b)/i,/^(?:MOD\b)/i,/^(?:NOT\b)/i,/^(?:BETWEEN\b)/i,/^(?:IN\b)/i,/^(?:SOUNDS\b)/i,/^(?:LIKE\b)/i,/^(?:ESCAPE\b)/i,/^(?:REGEXP\b)/i,/^(?:IS\b)/i,/^(?:UNKNOWN\b)/i,/^(?:AND\b)/i,/^(?:OR\b)/i,/^(?:XOR\b)/i,/^(?:FROM\b)/i,/^(?:PARTITION\b)/i,/^(?:USE\b)/i,/^(?:INDEX\b)/i,/^(?:KEY\b)/i,/^(?:FOR\b)/i,/^(?:JOIN\b)/i,/^(?:ORDER\s+BY\b)/i,/^(?:GROUP\s+BY\b)/i,/^(?:IGNORE\b)/i,/^(?:FORCE\b)/i,/^(?:INNER\b)/i,/^(?:CROSS\b)/i,/^(?:ON\b)/i,/^(?:USING\b)/i,/^(?:LEFT\b)/i,/^(?:RIGHT\b)/i,/^(?:OUTER\b)/i,/^(?:NATURAL\b)/i,/^(?:WHERE\b)/i,/^(?:ASC\b)/i,/^(?:DESC\b)/i,/^(?:WITH\b)/i,/^(?:ROLLUP\b)/i,/^(?:HAVING\b)/i,/^(?:OFFSET\b)/i,/^(?:PROCEDURE\b)/i,/^(?:UPDATE\b)/i,/^(?:LOCK\b)/i,/^(?:SHARE\b)/i,/^(?:MODE\b)/i,/^(?:OJ\b)/i,/^(?:LIMIT\b)/i,/^(?:UNION\b)/i,/^(?:,)/i,/^(?:=)/i,/^(?:\()/i,/^(?:\))/i,/^(?:~)/i,/^(?:!=)/i,/^(?:!)/i,/^(?:\|)/i,/^(?:&)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:\*)/i,/^(?:\/)/i,/^(?:%)/i,/^(?:\^)/i,/^(?:>>)/i,/^(?:>=)/i,/^(?:>)/i,/^(?:<<)/i,/^(?:<=>)/i,/^(?:<=)/i,/^(?:<>)/i,/^(?:<)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:;)/i,/^(?:['](\\.|[^'])*['])/i,/^(?:["](\\.|[^"])*["])/i,/^(?:[0][x][0-9a-fA-F]+)/i,/^(?:[-]?[0-9]+(\.[0-9]+)?)/i,/^(?:[-]?[0-9]+(\.[0-9]+)?[eE][-][0-9]+(\.[0-9]+)?)/i,/^(?:[a-zA-Z_\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]*)/i,/^(?:\.)/i,/^(?:['"][a-zA-Z_\u4e00-\u9fa5][a-zA-Z0-9_\u4e00-\u9fa5]*["'])/i,/^(?:$)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118],inclusive:!0}}};function xt(){this.yy={}}return kt.lexer=Et,xt.prototype=kt,kt.Parser=xt,new xt}();function a(){this.buffer=""}i||(i={}),i.stringify=function(e){var t=new a;return t.travelMain(e),t.buffer},a.prototype.travel=function(e){if(e){if("string"==typeof e)return this.append(e);this["travel"+e.type].call(this,e)}};var s=!1;a.prototype.appendKeyword=function(e,t,r){s&&(t=!0,s=!1),this.buffer+=t?e.toUpperCase():" "+e.toUpperCase(),r&&(s=!0)},a.prototype.append=function(e,t,r){s&&(t=!0,s=!1),this.buffer+=t?e:" "+e,r&&(s=!0)},a.prototype.travelMain=function(e){this.travel(e.value),e.hasSemicolon&&this.append(";",!0)},a.prototype.travelSelect=function(e){this.appendKeyword("select"),e.distinctOpt&&this.appendKeyword(e.distinctOpt),e.highPriorityOpt&&this.appendKeyword(e.highPriorityOpt),e.maxStateMentTimeOpt&&this.append("MAX_STATEMENT_TIME = "+e.maxStateMentTimeOpt),e.straightJoinOpt&&this.appendKeyword(e.straightJoinOpt),e.sqlSmallResultOpt&&this.appendKeyword(e.sqlSmallResultOpt),e.sqlBigResultOpt&&this.appendKeyword(e.sqlBigResultOpt),e.sqlBufferResultOpt&&this.appendKeyword(e.sqlBufferResultOpt),e.sqlCacheOpt&&this.appendKeyword(e.sqlCacheOpt),e.sqlCalcFoundRowsOpt&&this.appendKeyword(e.sqlCalcFoundRowsOpt),e.selectItems&&this.travelSelectExpr(e.selectItems),e.from&&(this.appendKeyword("from"),this.travel(e.from)),e.partition&&this.travel(e.partition),e.where&&(this.appendKeyword("where"),this.travel(e.where)),e.groupBy&&this.travel(e.groupBy),e.having&&(this.appendKeyword("having"),this.travel(e.having)),e.orderBy&&this.travel(e.orderBy),e.limit&&this.travel(e.limit),e.procedure&&(this.appendKeyword("procedure"),this.travel(e.procedure)),e.updateLockMode&&this.appendKeyword(e.updateLockMode)},a.prototype.travelSelectExpr=function(e){for(var t=e.value,r=0;r0&&void 0!==arguments[0]?arguments[0]:void 0;if(this.action&&this.action.params&&this.action.params.$resource){this.$set(this.record.params,"$resource",t),this.$set(this.record,"resource",t);var r=this.action.types,n=void 0===r?[]:r;return this.$httpGet("/resources").then(function(r){var i=r.data;e.resourcesOptions=i.filter(function(e){return n.includes(e.type)}),e.$set(e.record,"resource",t)})}},loadActions:function(){var e=this;return this.$httpGet("/actions",this.params).then(function(t){e.actionsList=t.data.map(function(e){return e.label=(e.title||{})[E],e.descriptionLabel=(e.description||{})[E],e})})},renderForm:function(e){var t=this;return f()(u.a.mark(function r(){var n,i,a,s;return u.a.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(t.formData){r.next=2;break}return r.abrupt("return");case 2:return n=t.formData||e,i=n.name,a=n.params,s=void 0===a?{}:a,r.next=5,t.handleActionChange(i);case 5:t.fillData(s);case 6:case"end":return r.stop()}},r,t)}))()},fillData:function(e){var t=this;c()(e).forEach(function(e){var r=s()(e,2),n=r[0],i=r[1];t.$set(t.record,n,i)})}},created:function(){var e=this;return f()(u.a.mark(function t(){return u.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e.loadActions();case 2:return t.next=4,e.renderForm();case 4:case"end":return t.stop()}},t,e)}))()}},O={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("el-dialog",e._b({staticClass:"action-dialog",attrs:{width:"500px","append-to-body":"",visible:e.dialogVisible,title:e.$t("rule.actions")},on:{"update:visible":function(t){e.dialogVisible=t},open:e.open,close:e.close}},"el-dialog",e.$attrs,!1),[r("el-form",{ref:"record",staticClass:"el-form--public",attrs:{model:e.record,rules:e.rules}},[r("el-row",{attrs:{gutter:20}},[r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"action"}},[r("template",{slot:"label"},[e._v("\n "+e._s(e.$t("rule.action"))+"\n "),r("el-popover",{attrs:{placement:"top-start",width:"200",trigger:"hover"}},[r("div",{domProps:{innerHTML:e._s(e.action.descriptionLabel||e.$t("rule.action_type"))}}),e._v(" "),r("i",{staticClass:"el-icon-question",attrs:{slot:"reference",tabindex:"-1"},slot:"reference"})])],1),e._v(" "),r("el-select",{staticClass:"el-select--public",staticStyle:{width:"100%"},attrs:{"popper-class":"el-select--public"},on:{change:e.handleActionChange},model:{value:e.record.action,callback:function(t){e.$set(e.record,"action",t)},expression:"record.action"}},e._l(e.actionsList,function(e,t){return r("el-option",{key:t,attrs:{label:e.label,value:e.name}})}),1)],2)],1),e._v(" "),e.action.params&&e.action.params.$resource?r("el-col",{attrs:{span:12}},[r("el-form-item",{staticClass:"resource-item",attrs:{prop:"params.$resource"}},[r("template",{slot:"label"},[e._v("\n "+e._s(e.$t("rule.resource"))+"\n "),r("span",{staticClass:"btn",staticStyle:{float:"right","font-size":"12px"},on:{click:e.createResource}},[e._v("\n "+e._s(e.$t("rule.new_resource"))+"\n ")])]),e._v(" "),r("el-select",{staticClass:"el-select--public",staticStyle:{width:"100%"},attrs:{"popper-class":"el-select--public"},model:{value:e.record.params.$resource,callback:function(t){e.$set(e.record.params,"$resource",t)},expression:"record.params.$resource"}},e._l(e.resourcesOptions,function(e,t){return r("el-option",{key:t,attrs:{label:e.description,value:e.id}})}),1)],2)],1):e._e(),e._v(" "),e._l(e.paramsList,function(t,n){return r("el-col",{key:n,attrs:{span:"object"===t.type||"textarea"===t.$attrs.type?24:12}},[r("el-form-item",{attrs:{prop:"params."+t.prop}},[r("template",{slot:"label"},[e._v("\n "+e._s(t.label)+"\n\n "),t.description?r("el-popover",{attrs:{placement:"right",width:"200",trigger:"hover"}},[r("div",{domProps:{innerHTML:e._s(t.description)}}),e._v(" "),r("i",{staticClass:"el-icon-question",attrs:{slot:"reference",tabindex:"-1"},slot:"reference"})]):e._e()],1),e._v(" "),"object"===t.type?r("data-table",{model:{value:e.record.params[t.key],callback:function(r){e.$set(e.record.params,t.key,r)},expression:"record.params[item.key]"}}):"emq-select"===t.type?r("emq-select",e._b({staticClass:"el-select--public",attrs:{"popper-class":"el-select--public"},model:{value:e.record.params[t.key],callback:function(r){e.$set(e.record.params,t.key,r)},expression:"record.params[item.key]"}},"emq-select",t.$attrs,!1)):"number"===t.type?r("el-input",e._b({attrs:{type:"number"},model:{value:e.record.params[t.key],callback:function(r){e.$set(e.record.params,t.key,e._n(r))},expression:"record.params[item.key]"}},"el-input",t.$attrs,!1)):r("el-input",e._b({model:{value:e.record.params[t.key],callback:function(r){e.$set(e.record.params,t.key,r)},expression:"record.params[item.key]"}},"el-input",t.$attrs,!1))],2)],1)})],2)],1),e._v(" "),r("div",{attrs:{slot:"footer"},slot:"footer"},[r("el-button",{staticClass:"cache-btn",attrs:{type:"text"},on:{click:function(t){e.dialogVisible=!1}}},[e._v("\n "+e._s(e.$t("rule.cancel"))+"\n ")]),e._v(" "),r("el-button",{staticClass:"confirm-btn",attrs:{type:"success"},on:{click:e.handleAdd}},[e._v("\n "+e._s(e.$t("rule.confirm"))+"\n ")])],1),e._v(" "),r("resource-dialog",{attrs:{visible:e.resourceDialogVisible,"resource-type":e.resourceType,"enable-item":e.enableItem,"append-to-body":""},on:{"update:visible":function(t){e.resourceDialogVisible=t},confirm:e.handleResourceCreate}})],1)},staticRenderFns:[]};var w={name:"rule-actions",components:{ActionDialog:r("VU/8")(x,O,!1,function(e){r("oq82")},null,null).exports},props:{record:{type:Object,required:!0},inDialog:{type:Boolean,default:!1},operations:{type:Array,default:function(){return["create","edit","delete"]}},params:{type:Object,default:function(){return{}}}},watch:{dialogVisible:function(e){e||(this.editForm=null,this.editIndex=null,this.currentAction={},this.isFallBacks=!1)}},computed:{has:function(){var e=[];return this.operations.forEach(function(t){e[t]=!0}),e}},data:function(){return{dialogVisible:!1,editForm:null,editIndex:null,isFallBacks:!1,currentAction:{}}},filters:{jsonFormat:function(e){return i()(e,null,2)}},methods:{getSum:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(0===e.length||!t)return 0;var r=0;return e.forEach(function(e){var n=e[t]||0;r+=n}),r},handleActionAdd:function(e,t){if(this.isFallBacks)return null!==this.editIndex&&(this.currentAction.fallbacks=[]),void this.currentAction.fallbacks.push(e);null!==t?this.record.actions.splice(t,1,e):this.record.actions.push(e)},handleActionRemove:function(e){var t=e;this.record.actions=this.record.actions.filter(function(e,r){return r!==t})},handleActionEdit:function(e,t){this.editIndex=t,this.editForm=e,this.dialogVisible=!0},handleAddFallbacks:function(e){this.currentAction=e,this.isFallBacks=!0,this.dialogVisible=!0},handleFallbackRemove:function(e){e.fallbacks=[]},handleFallbackEdit:function(e,t,r){this.currentAction=t,this.isFallBacks=!0,this.editIndex=r,this.editForm=e,this.dialogVisible=!0}}},S={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("div",{staticClass:"rule-actions"},[e._l(e.record.actions,function(t,n){return r("div",{key:n,staticClass:"action-card"},[r("el-row",{staticClass:"action-body",attrs:{type:"flex"}},[r("el-col",{attrs:{span:12}},[r("div",{staticClass:"filed-item"},[r("label",{staticClass:"title"},[e._v(e._s(e.$t("rule.type"))+": ")]),e._v(" "),r("span",{staticClass:"desc"},[e._v(e._s(t.name))])]),e._v(" "),e._l(Object.entries(t.params),function(t,n){return r("div",{key:n,staticClass:"filed-item"},[r("label",{staticClass:"title"},[e._v(" "+e._s("$resource"===t[0]?e.$t("rule.rely_resource"):t[0])+": ")]),e._v(" "),r("span",{staticClass:"desc"},[e._v(e._s(t[1]))])])})],2),e._v(" "),e.has.delete||e.has.edit?r("el-col",{staticClass:"action-oper",attrs:{span:12}},[e.has.edit?r("el-button",{attrs:{type:"text"},on:{click:function(r){return e.handleActionEdit(t,n)}}},[e._v("\n "+e._s(e.$t("rule.edit"))+"\n ")]):e._e(),e._v(" "),e.has.delete?r("el-button",{staticClass:"delete-btn",attrs:{type:"text"},on:{click:function(t){return e.handleActionRemove(n)}}},[e._v("\n "+e._s(e.$t("rule.delete"))+"\n ")]):e._e(),e._v(" "),t.fallbacks.length?e._e():r("div",{staticClass:"fallbacks"},[r("el-popover",{attrs:{placement:"top-start",trigger:"hover",content:e.$t("rule.fallbackActionCreate")}},[r("el-button",{attrs:{slot:"reference",type:"text",icon:"el-icon-plus"},on:{click:function(r){return e.handleAddFallbacks(t)}},slot:"reference"},[e._v("\n "+e._s(e.$t("rule.fallbackAction"))+"\n ")])],1)],1)],1):e._e(),e._v(" "),e.has.delete||e.has.edit?e._e():r("el-col",{attrs:{span:12}},[r("div",{staticClass:"status-wrapper filed-item"},[e._l(t.metrics||[],function(t,n){return r("div",{key:n,staticClass:"status-item"},[r("div",{staticClass:"title"},[e._v(e._s(e.$t("rule.metrics"))+": ")]),e._v(" "),r("span",{staticClass:"key"},[e._v("\n "+e._s(t.node)+"\n ")]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.success"))+":\n "),r("span",[e._v(e._s(t.success))])]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.failed"))+":\n "),r("span",[e._v(e._s(t.failed))])])])}),e._v(" "),r("div",{staticClass:"status-item"},[r("span",{staticClass:"key"},[e._v("\n "+e._s(e.$t("rule.all"))+"\n ")]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.success"))+":\n "),r("span",[e._v(e._s(e.getSum(t.metrics,"success")))])]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.failed"))+":\n "),r("span",[e._v(e._s(e.getSum(t.metrics,"failed")))])])])],2)])],1),e._v(" "),t.fallbacks&&t.fallbacks.length?e._l(t.fallbacks,function(n,i){return r("el-row",{key:i,staticClass:"action-footer",attrs:{type:"flex"}},[r("el-col",{attrs:{span:12}},[r("div",{staticClass:"filed-item"},[r("label",{staticClass:"title"},[e._v(e._s(e.$t("rule.type"))+": ")]),e._v(" "),r("span",{staticClass:"desc"},[e._v(e._s(n.name))])]),e._v(" "),e._l(Object.entries(n.params),function(t,n){return r("div",{key:n,staticClass:"filed-item"},[r("label",{staticClass:"title"},[e._v(" "+e._s("$resource"===t[0]?e.$t("rule.rely_resource"):t[0])+": ")]),e._v(" "),r("span",{staticClass:"desc"},[e._v(e._s(t[1]))])])})],2),e._v(" "),e.has.delete||e.has.edit?r("el-col",{staticClass:"action-oper",attrs:{span:12}},[e.has.edit?r("el-button",{attrs:{type:"text"},on:{click:function(r){return e.handleFallbackEdit(n,t,i)}}},[e._v("\n "+e._s(e.$t("rule.edit"))+"\n ")]):e._e(),e._v(" "),e.has.delete?r("el-button",{staticClass:"delete-btn",attrs:{type:"text"},on:{click:function(r){return e.handleFallbackRemove(t,i)}}},[e._v("\n "+e._s(e.$t("rule.delete"))+"\n ")]):e._e(),e._v(" "),r("div",{staticClass:"fallbacks"},[r("el-popover",{attrs:{placement:"top-start",trigger:"hover",content:e.$t("rule.fallbackActionTip")}},[r("span",{attrs:{slot:"reference"},slot:"reference"},[e._v("\n "+e._s(e.$t("rule.fallbackAction"))+"\n ")])])],1)],1):e._e(),e._v(" "),e.has.delete||e.has.edit?e._e():r("el-col",{attrs:{span:12}},[r("div",{staticClass:"status-wrapper filed-item"},[e._l(n.metrics||[],function(t,n){return r("div",{key:n,staticClass:"status-item"},[r("div",{staticClass:"title"},[e._v(e._s(e.$t("rule.metrics"))+": ")]),e._v(" "),r("span",{staticClass:"key"},[e._v("\n "+e._s(t.node)+"\n ")]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.success"))+":\n "),r("span",[e._v(e._s(t.success))])]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.failed"))+":\n "),r("span",[e._v(e._s(t.failed))])])])}),e._v(" "),r("div",{staticClass:"status-item"},[r("span",{staticClass:"key"},[e._v("\n "+e._s(e.$t("rule.all"))+"\n ")]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.success"))+":\n "),r("span",[e._v(e._s(e.getSum(n.metrics,"success")))])]),e._v(" "),r("span",{attrs:{type:"info"}},[e._v("\n "+e._s(e.$t("rule.failed"))+":\n "),r("span",[e._v(e._s(e.getSum(n.metrics,"failed")))])])])],2)])],1)}):e._e()],2)}),e._v(" "),e.has.create?r("el-button",{staticStyle:{"min-width":"80px"},attrs:{type:"success",plain:"",icon:"el-icon-plus",size:"small"},on:{click:function(t){e.dialogVisible=!0}}},[e._v("\n "+e._s(e.$t("rule.add"))+"\n ")]):e._e(),e._v(" "),r("action-dialog",{attrs:{visible:e.dialogVisible,currentActions:e.record.actions,recordIndex:e.editIndex,editRecord:e.editForm,params:e.params},on:{"update:visible":function(t){e.dialogVisible=t},confirm:e.handleActionAdd}})],2)},staticRenderFns:[]};var $=r("VU/8")(w,S,!1,function(e){r("3IWq")},null,null);t.a=$.exports},exGp:function(e,t,r){"use strict";t.__esModule=!0;var n,i=r("//Fk"),a=(n=i)&&n.__esModule?n:{default:n};t.default=function(e){return function(){var t=e.apply(this,arguments);return new a.default(function(e,r){return function n(i,s){try{var o=t[i](s),c=o.value}catch(e){return void r(e)}if(!o.done)return a.default.resolve(c).then(function(e){n("next",e)},function(e){n("throw",e)});e(c)}("next")})}}},jTzk:function(e,t){},oq82:function(e,t){}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/1.0871c1680d75fc72c9a1.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/1.0871c1680d75fc72c9a1.js deleted file mode 100644 index a148e23682..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/1.0871c1680d75fc72c9a1.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([1],{"3WKI":function(e,t){},zXyA:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=a("Dd8w"),i=a.n(s),l=a("zL8q"),n=a("NYxO"),o={name:"data-view",components:{"el-pagination":l.Pagination,"el-input":l.Input,"el-select":l.Select,"el-option":l.Option,"el-table":l.Table,"el-table-column":l.TableColumn,"el-date-picker":l.DatePicker},data:function(){return{searchView:!1,cluster:!1,popoverVisible:!1,count:0,hasnext:!1,params:{_page:1,_limit:10},nodeName:"",nodes:[],activeTab:"clients",searchKey:"",searchValue:"",searchPlaceholder:this.$t("clients.clientId"),clients:[],fuzzyParams:{comparator:"_gte",match:"_match_topic"},topics:[],subscriptions:[],showMoreQuery:!1,protoNames:["MQTT","MQTT-SN","CoAP","LwM2M"]}},watch:{$route:"init",activeTab:function(){this.fuzzyParams={comparator:"_gte",match:"_match_topic"}}},computed:{iconStatus:function(){return this.searchView?"el-icon-close":"el-icon-search"}},methods:i()({},Object(n.b)(["CURRENT_NODE"]),{stashNode:function(){this.cluster="cluster"===this.nodeName,this.cluster||this.CURRENT_NODE(this.nodeName)},init:function(){switch(this.activeTab=this.$route.path.split("/")[1],this.params._page=1,this.activeTab){case"topics":this.searchPlaceholder="Topic";break;default:this.searchPlaceholder=this.$t("clients.clientId")}this.loadData()},loadData:function(){var e=this;this.searchValue="",this.$httpGet("/nodes").then(function(t){var a=e.$store.state.nodeName||t.data[0].node;e.nodeName=e.cluster?"cluster":a,e.nodes=t.data,e.loadChild()}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})},loadChild:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(this.stashNode(),this.searchView=!1,this.searchValue="",!0===t&&(this.params._page=1),this.nodeName||"topics"===this.activeTab){var s="/nodes/"+this.nodeName+"/"+this.activeTab;("topics"===this.activeTab||this.cluster)&&(s="topics"===this.activeTab?"routes":this.activeTab);var l={};l=a?i()({},a,this.params):i()({},this.params),this.$httpGet(s,l).then(function(t){e[e.activeTab]=t.data.items,e.count=t.data.meta.count||0,e.hasnext=t.data.meta.hasnext}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})}},searchChild:function(){var e=this;if(this.searchView)this.loadChild();else if(this.searchValue){var t="/nodes/"+this.nodeName+"/"+this.activeTab+"/"+encodeURIComponent(this.searchValue);if("topics"===this.activeTab||this.cluster)t="/"+("topics"===this.activeTab?"routes":this.activeTab)+"/"+encodeURIComponent(this.searchValue);this.$httpGet(t).then(function(t){e.count=0,e.params={_page:1,_limit:10},e.searchView=!0,e[e.activeTab]=t.data}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})}else this.loadData()},handleSizeChange:function(e){this.params._limit=e,this.loadChild(!0)},handlePrevClick:function(){if(1!==this.params._page){this.params._page-=1;var e=this.genQueryParams(this.fuzzyParams);this.loadChild(!1,e)}},handleNextClick:function(){if(this.hasnext){this.params._page+=1;var e=this.genQueryParams(this.fuzzyParams);this.loadChild(!1,e)}},handleDisconnect:function(e,t,a){var s=this;this.$httpDelete("/clients/"+encodeURIComponent(e.clientid)).then(function(){s.loadData(),a.$refs["popover-"+t].doClose()}).catch(function(e){s.$message.error(e||s.$t("error.networkError"))})},genQueryParams:function(e){var t={};if("clients"===this.activeTab){var a=e._like_clientid,s=e._like_username,i=e.ip_address,l=e.conn_state,n=e.proto_name,o=e.comparator,r=e._connected_at;if(t={_like_clientid:a||void 0,_like_username:s||void 0,ip_address:i||void 0,conn_state:l||void 0,proto_name:n||void 0},r)t[o+"_connected_at"]=Math.floor(r/1e3)}else if("subscriptions"===this.activeTab){var c=e._like_clientid,p=e.topic,u=e.qos,d=e.share,m=e.match;t={clientid:c||void 0,qos:""===u?void 0:u,share:d||void 0},p&&(t[m]=p)}return t},clientQuerySearch:function(){var e=this.genQueryParams(this.fuzzyParams);this.loadChild(!0,e)},resetClientQuerySearch:function(){this.fuzzyParams={comparator:">=",match:"_match_topic"},this.init()}}),created:function(){this.init()}},r={render:function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("div",{staticClass:"data-view"},[a("div",{staticClass:"page-title"},[e._v("\n "+e._s(e.$t("leftbar."+e.activeTab))+"\n "),a("div",{staticStyle:{float:"right"},nativeOn:{keyup:function(t){return!t.type.indexOf("key")&&e._k(t.keyCode,"enter",13,t.key,"Enter")?null:e.searchChild(t)}}},["topics"!==e.activeTab?a("el-select",{staticClass:"select-radius",attrs:{placeholder:e.$t("select.placeholder"),disabled:e.$store.state.loading},on:{change:function(t){return e.loadChild(!0)}},model:{value:e.nodeName,callback:function(t){e.nodeName=t},expression:"nodeName"}},e._l(e.nodes,function(e){return a("el-option",{key:e.node,attrs:{label:e.node,value:e.node}})}),1):e._e()],1)]),e._v(" "),"topics"!==e.activeTab?a("el-card",{staticClass:"el-card--self search-card"},[a("el-form",{ref:"fuzzyParams",attrs:{model:e.fuzzyParams,"label-position":"left","label-width":"110px"}},[a("el-row",{attrs:{gutter:20}},[a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("clients.clientId")}},[a("el-input",{attrs:{type:"text",size:"small"},model:{value:e.fuzzyParams._like_clientid,callback:function(t){e.$set(e.fuzzyParams,"_like_clientid",t)},expression:"fuzzyParams._like_clientid"}})],1)],1),e._v(" "),"clients"===e.activeTab?a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("clients.username")}},[a("el-input",{attrs:{type:"text",size:"small"},model:{value:e.fuzzyParams._like_username,callback:function(t){e.$set(e.fuzzyParams,"_like_username",t)},expression:"fuzzyParams._like_username"}})],1)],1):"subscriptions"===e.activeTab?a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("topics.topic")}},[a("el-row",{staticClass:"form-item-row"},[a("el-col",{attrs:{span:9}},[a("el-select",{staticClass:"match",model:{value:e.fuzzyParams.match,callback:function(t){e.$set(e.fuzzyParams,"match",t)},expression:"fuzzyParams.match"}},[a("el-option",{attrs:{label:"filter",value:"_match_topic"}}),e._v(" "),a("el-option",{attrs:{label:"topic",value:"topic"}})],1)],1),e._v(" "),a("el-col",{attrs:{span:15}},[a("el-input",{attrs:{type:"text",size:"small"},model:{value:e.fuzzyParams.topic,callback:function(t){e.$set(e.fuzzyParams,"topic",t)},expression:"fuzzyParams.topic"}})],1)],1)],1)],1):e._e(),e._v(" "),e.showMoreQuery?["clients"===e.activeTab?[a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("clients.ipAddr")}},[a("el-input",{attrs:{type:"text",size:"small"},model:{value:e.fuzzyParams.ip_address,callback:function(t){e.$set(e.fuzzyParams,"ip_address",t)},expression:"fuzzyParams.ip_address"}})],1)],1),e._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("clients.connected")}},[a("el-select",{model:{value:e.fuzzyParams.conn_state,callback:function(t){e.$set(e.fuzzyParams,"conn_state",t)},expression:"fuzzyParams.conn_state"}},[a("el-option",{attrs:{value:"connected"}}),e._v(" "),a("el-option",{attrs:{value:"disconnected"}})],1)],1)],1),e._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("clients.createdAt")}},[a("el-row",{staticClass:"form-item-row"},[a("el-col",{attrs:{span:8}},[a("el-select",{staticClass:"comparator",model:{value:e.fuzzyParams.comparator,callback:function(t){e.$set(e.fuzzyParams,"comparator",t)},expression:"fuzzyParams.comparator"}},[a("el-option",{attrs:{label:">=",value:"_gte"}}),e._v(" "),a("el-option",{attrs:{label:"<=",value:"_lte"}})],1)],1),e._v(" "),a("el-col",{attrs:{span:16}},[a("el-date-picker",{staticClass:"datatime",attrs:{type:"datetime","value-format":"timestamp"},model:{value:e.fuzzyParams._connected_at,callback:function(t){e.$set(e.fuzzyParams,"_connected_at",t)},expression:"fuzzyParams._connected_at"}})],1)],1)],1)],1),e._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("clients.protoName")}},[a("el-select",{model:{value:e.fuzzyParams.proto_name,callback:function(t){e.$set(e.fuzzyParams,"proto_name",t)},expression:"fuzzyParams.proto_name"}},e._l(e.protoNames,function(e){return a("el-option",{key:e,attrs:{value:e}})}),1)],1)],1)]:"subscriptions"===e.activeTab?[a("el-col",{attrs:{span:8}},[a("el-form-item",{attrs:{label:"QoS"}},[a("el-select",{attrs:{clearable:""},model:{value:e.fuzzyParams.qos,callback:function(t){e.$set(e.fuzzyParams,"qos",t)},expression:"fuzzyParams.qos"}},[a("el-option",{attrs:{value:0}}),e._v(" "),a("el-option",{attrs:{value:1}}),e._v(" "),a("el-option",{attrs:{value:2}})],1)],1)],1),e._v(" "),a("el-col",{staticClass:"col-share",attrs:{span:8}},[a("el-form-item",{attrs:{label:e.$t("subscriptions.share")}},[a("el-input",{attrs:{type:"text",size:"small",placeholder:"group_name"},model:{value:e.fuzzyParams.share,callback:function(t){e.$set(e.fuzzyParams,"share",t)},expression:"fuzzyParams.share"}})],1)],1)]:e._e()]:e._e(),e._v(" "),a("span",{staticClass:"col-oper"},[a("el-button",{attrs:{size:"small",type:"primary",plain:""},on:{click:e.clientQuerySearch}},[e._v("\n "+e._s(e.$t("oper.search"))+"\n ")]),e._v(" "),a("el-button",{attrs:{size:"small",plain:""},on:{click:e.resetClientQuerySearch}},[e._v("\n "+e._s(e.$t("oper.reset"))+"\n ")]),e._v(" "),a("a",{staticClass:"show-more",attrs:{href:"javascript:;"},on:{click:function(t){e.showMoreQuery=!e.showMoreQuery}}},[e._v("\n "+e._s(e.showMoreQuery?e.$t("oper.collapse"):e.$t("oper.expand"))+"\n "),a("i",{class:e.showMoreQuery?"el-icon-arrow-up":"el-icon-arrow-down"})])],1)],2)],1)],1):e._e(),e._v(" "),a("el-table",{directives:[{name:"show",rawName:"v-show",value:"clients"===e.activeTab,expression:"activeTab==='clients'"},{name:"loading",rawName:"v-loading",value:e.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:e.clients}},[a("el-table-column",{attrs:{prop:"clientid",label:e.$t("clients.clientId"),width:"160px","show-overflow-tooltip":""},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[a("a",{attrs:{href:"javascript:;"},on:{click:function(t){e.$router.push({path:"/clients/"+encodeURIComponent(s.clientid)})}}},[e._v("\n "+e._s(s.clientid)+"\n ")])]}}])}),e._v(" "),a("el-table-column",{attrs:{prop:"username","min-width":"100px",label:e.$t("clients.username"),"show-overflow-tooltip":""}}),e._v(" "),a("el-table-column",{attrs:{prop:"ip_address",label:e.$t("clients.ipAddr"),"min-width":"140px","show-overflow-tooltip":""},scopedSlots:e._u([{key:"default",fn:function(t){var a=t.row;return[e._v("\n "+e._s(a.ip_address)+":"+e._s(a.port)+"\n ")]}}])}),e._v(" "),a("el-table-column",{attrs:{prop:"keepalive","min-width":"100px",label:e.$t("clients.keepalive")}}),e._v(" "),a("el-table-column",{attrs:{prop:"expiry_interval","min-width":"150px",label:e.$t("clients.expiryInterval")}}),e._v(" "),a("el-table-column",{attrs:{prop:"subscriptions_cnt","min-width":"160px",label:e.$t("clients.subscriptionsCount")}}),e._v(" "),a("el-table-column",{attrs:{prop:"connected","min-width":"140px",label:e.$t("clients.connected")},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[a("span",{class:[s.connected?"connected":"disconnected","status-circle"]}),e._v("\n "+e._s(s.connected?e.$t("websocket.connected"):e.$t("websocket.disconnected"))+"\n ")]}}])}),e._v(" "),a("el-table-column",{attrs:{prop:"created_at",label:e.$t("clients.createdAt"),"min-width":"160px"}}),e._v(" "),a("el-table-column",{attrs:{fixed:"right",width:"120px",label:e.$t("oper.oper")},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row,i=t.$index,l=t._self;return[a("el-popover",{ref:"popover-"+i,attrs:{placement:"right",trigger:"click"}},[a("p",[e._v(e._s(s.connected?e.$t("oper.confirmKickOut"):e.$t("oper.confirmCleanSession")))]),e._v(" "),a("div",{staticStyle:{"text-align":"right"}},[a("el-button",{staticClass:"cache-btn",attrs:{size:"mini",type:"text"},on:{click:function(e){l.$refs["popover-"+i].doClose()}}},[e._v("\n "+e._s(e.$t("oper.cancel"))+"\n ")]),e._v(" "),a("el-button",{attrs:{size:"mini",type:"success"},on:{click:function(t){return e.handleDisconnect(s,i,l)}}},[e._v("\n "+e._s(e.$t("oper.confirm"))+"\n ")])],1),e._v(" "),a("el-button",{attrs:{slot:"reference",size:"mini",type:"danger",plain:""},slot:"reference"},[e._v("\n "+e._s(s.connected?e.$t("clients.kickOut"):e.$t("websocket.cleanSession"))+"\n ")])],1)]}}])})],1),e._v(" "),a("el-table",{directives:[{name:"show",rawName:"v-show",value:"topics"===e.activeTab,expression:"activeTab === 'topics'"},{name:"loading",rawName:"v-loading",value:e.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:e.topics}},[a("el-table-column",{attrs:{prop:"topic",label:e.$t("topics.topic")}}),e._v(" "),a("el-table-column",{attrs:{prop:"node",label:e.$t("topics.node")}})],1),e._v(" "),a("el-table",{directives:[{name:"show",rawName:"v-show",value:"subscriptions"===e.activeTab,expression:"activeTab === 'subscriptions'"},{name:"loading",rawName:"v-loading",value:e.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:e.subscriptions}},[e.cluster?a("el-table-column",{attrs:{prop:"node","min-width":"160",label:e.$t("clients.node")}}):e._e(),e._v(" "),a("el-table-column",{attrs:{prop:"clientid",label:e.$t("subscriptions.clientId")}}),e._v(" "),a("el-table-column",{attrs:{prop:"topic",label:e.$t("subscriptions.topic")}}),e._v(" "),a("el-table-column",{attrs:{prop:"qos",label:e.$t("subscriptions.qoS")}})],1),e._v(" "),a("div",{staticClass:"center-align"},[e.count>10?a("el-pagination",{attrs:{background:"",layout:"total, sizes, prev, pager, next","page-sizes":[10,50,100,300,500],"current-page":e.params._page,"page-size":e.params._limit,total:e.count},on:{"update:currentPage":function(t){return e.$set(e.params,"_page",t)},"update:current-page":function(t){return e.$set(e.params,"_page",t)},"size-change":e.handleSizeChange,"current-change":e.loadChild}}):e._e(),e._v(" "),-1===e.count&&(e.clients.length||e.subscriptions.length)?a("div",{staticClass:"custom-pagination"},[a("a",{class:["prev",1===e.params._page?"disabled":""],attrs:{href:"javascript:;"},on:{click:e.handlePrevClick}},[a("i",{staticClass:"el-icon-arrow-left"}),e._v("\n "+e._s(e.$t("oper.prev"))+"\n ")]),e._v(" "),a("a",{class:["next",e.hasnext?"":"disabled"],attrs:{href:"javascript:;"},on:{click:e.handleNextClick}},[e._v("\n "+e._s(e.$t("oper.next"))+"\n "),a("i",{staticClass:"el-icon-arrow-right"})])]):e._e()],1)],1)},staticRenderFns:[]};var c=a("VU/8")(o,r,!1,function(e){a("3WKI")},null,null);t.default=c.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/10.d4e397588153f0046f0b.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/10.d4e397588153f0046f0b.js deleted file mode 100644 index ddf776847a..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/10.d4e397588153f0046f0b.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([10],{"1RJS":function(e,s){},QSR2:function(e,s,r){"use strict";Object.defineProperty(s,"__esModule",{value:!0});var t=r("Dd8w"),a=r.n(t),o=r("zL8q"),n=r("NYxO"),i={name:"users-view",components:{"el-dialog":o.Dialog,"el-input":o.Input,"el-button":o.Button,"el-table":o.Table,"el-table-column":o.TableColumn,"el-popover":o.Popover,"el-form":o.Form,"el-form-item":o.FormItem,"el-row":o.Row,"el-col":o.Col},data:function(){var e=this;return{changePassword:!1,dialogVisible:!1,oper:"new",users:[],record:{username:"",password:"",newPassword:"",repeatPassword:"",tags:""},rules:{username:[{required:!0,message:this.$t("users.usernameRequired")},{min:2,max:32,message:this.$t("users.usernameIllegal"),trigger:"change"}],tags:[{required:!0,message:this.$t("users.remarkRequired")}],password:[{required:!0,message:this.$t("users.passwordRequired")},{min:3,max:255,message:this.$t("users.passwordIllegal"),trigger:"change"}],newPassword:[{required:!0,message:this.$t("users.passwordRequired")},{min:3,max:255,message:this.$t("users.passwordIllegal"),trigger:"change"}],repeatPassword:[{required:!0,message:this.$t("users.passwordRequired")},{validator:function(s,r,t){r!==e.record.newPassword?t(new Error(e.$t("users.passwordInconsistent"))):t()},trigger:"change"}]}}},computed:{username:function(){return this.$store.state.user.username}},methods:a()({},Object(n.b)(["USER_LOGIN"]),{handleOperation:function(){var e=this,s=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],r=arguments[1];this.changePassword=!1,this.dialogVisible=!0,s?(this.oper="new",this.record={username:"",password:"",newPassword:"",repeatPassword:"",tags:"viewer"},setTimeout(function(){e.$refs.record.clearValidate()},10)):(this.oper="edit",this.record=a()({},r),this.$set(this.record,"password",""))},loadData:function(){var e=this;this.$httpGet("/users").then(function(s){e.users=s.data}).catch(function(s){e.$message.error(s||e.$t("error.networkError"))})},createUser:function(){var e=this;"edit"!==this.oper?this.$refs.record.validate(function(s){s&&e.$httpPost("/users",e.record).then(function(){e.$message.success(""+e.$t("users.createUser")),e.loadData(),e.dialogVisible=!1}).catch(function(s){e.$message.error(s||e.$t("error.networkError"))})}):this.updateUser()},updateUser:function(){var e=this;this.$refs.record.validate(function(s){if(s)if(e.changePassword){var r={old_pwd:e.record.password,new_pwd:e.record.newPassword};e.$httpPut("/users/"+e.record.username,e.record).then(function(){e.$httpPut("/change_pwd/"+e.record.username,r).then(function(){e.$store.state.user.username===e.record.username&&e.record.password!==e.record.newPassword?(e.$message.error(e.$t("users.authenticate")),e.USER_LOGIN({isLogOut:!0}),e.$router.push("/login")):(e.$message.success(""+e.$t("oper.edit")+e.$t("alert.success")),e.dialogVisible=!1,e.loadData())}).catch(function(s){e.$message.error(s||e.$t("error.networkError"))})})}else e.$httpPut("/users/"+e.record.username,e.record).then(function(){e.$message.success(""+e.$t("oper.edit")+e.$t("alert.success")),e.dialogVisible=!1,e.loadData()}).catch(function(s){e.$message.error(s||e.$t("error.networkError"))})})},deleteUser:function(e,s,r){var t=this;this.$httpDelete("/users/"+e.username).then(function(){t.$message.success(""+t.$t("oper.delete")+t.$t("alert.success")),t.loadData(),r.$refs["popover-"+s].doClose()}).catch(function(e){t.$message.error(e||t.$t("error.networkError"))})}}),created:function(){this.loadData()}},l={render:function(){var e=this,s=e.$createElement,r=e._self._c||s;return r("div",{staticClass:"users-view"},[r("div",{staticClass:"page-title"},[e._v("\n "+e._s(e.$t("leftbar.users"))+"\n "),r("el-button",{staticClass:"confirm-btn",staticStyle:{float:"right"},attrs:{round:"",plain:"",type:"success",icon:"el-icon-plus",size:"medium",disabled:e.$store.state.loading},on:{click:function(s){return e.handleOperation(!0)}}},[e._v("\n "+e._s(e.$t("users.newUser"))+"\n ")])],1),e._v(" "),r("el-table",{directives:[{name:"loading",rawName:"v-loading",value:e.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:e.users}},[r("el-table-column",{attrs:{prop:"username",label:e.$t("users.username")}}),e._v(" "),r("el-table-column",{attrs:{prop:"tags",label:e.$t("users.remark")}}),e._v(" "),r("el-table-column",{attrs:{width:"140",label:e.$t("oper.oper")},scopedSlots:e._u([{key:"default",fn:function(s){var t=s.row,a=s.$index,o=s._self;return[r("el-button",{attrs:{size:"mini",type:"warning",plain:""},on:{click:function(s){return e.handleOperation(!1,t)}}},[e._v("\n "+e._s(e.$t("oper.edit"))+"\n ")]),e._v(" "),r("el-popover",{ref:"popover-"+a,attrs:{placement:"right",trigger:"click"}},[r("p",[e._v(e._s(e.$t("oper.confirmDelete")))]),e._v(" "),r("div",{staticStyle:{"text-align":"right"}},[r("el-button",{staticClass:"cache-btn",attrs:{size:"mini",type:"text"},on:{click:function(e){o.$refs["popover-"+a].doClose()}}},[e._v("\n "+e._s(e.$t("oper.cancel"))+"\n ")]),e._v(" "),r("el-button",{attrs:{size:"mini",type:"success"},on:{click:function(s){return e.deleteUser(t,a,o)}}},[e._v("\n "+e._s(e.$t("oper.confirm"))+"\n ")])],1),e._v(" "),r("el-button",{directives:[{name:"show",rawName:"v-show",value:"admin"!==t.username&&e.username!==t.username,expression:"row.username !== 'admin' && username !== row.username"}],attrs:{slot:"reference",size:"mini",type:"danger",plain:""},slot:"reference"},[e._v("\n "+e._s(e.$t("oper.delete"))+"\n ")])],1)]}}])})],1),e._v(" "),r("el-dialog",{attrs:{width:"500px",visible:e.dialogVisible,title:"new"===e.oper?e.$t("users.newUser"):e.$t("users.editUser")},on:{"update:visible":function(s){e.dialogVisible=s}},nativeOn:{keyup:function(s){return!s.type.indexOf("key")&&e._k(s.keyCode,"enter",13,s.key,"Enter")?null:e.createUser(s)}}},[r("el-form",{ref:"record",staticClass:"el-form--public",attrs:{"label-position":"top",size:"medium",model:e.record,rules:e.rules}},[r("el-row",{attrs:{gutter:20}},[r("el-col",{attrs:{span:24}},[r("el-form-item",{attrs:{prop:"username",label:e.$t("users.username")}},[r("el-input",{attrs:{disabled:"edit"===e.oper},model:{value:e.record.username,callback:function(s){e.$set(e.record,"username",s)},expression:"record.username"}})],1)],1),e._v(" "),"new"===e.oper?r("el-col",{attrs:{span:24}},[r("el-form-item",{attrs:{prop:"password",label:e.$t("users.password")}},[r("el-input",{attrs:{type:"password"},model:{value:e.record.password,callback:function(s){e.$set(e.record,"password",s)},expression:"record.password"}})],1)],1):e._e(),e._v(" "),e.changePassword&&"edit"===e.oper?r("div",[r("el-col",{attrs:{span:24}},[r("el-form-item",{attrs:{prop:"password",label:e.$t("users.oldPassword")}},[r("el-input",{attrs:{type:"password"},model:{value:e.record.password,callback:function(s){e.$set(e.record,"password",s)},expression:"record.password"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:24}},[r("el-form-item",{attrs:{prop:"newPassword",label:e.$t("users.newPassword")}},[r("el-input",{attrs:{type:"password"},model:{value:e.record.newPassword,callback:function(s){e.$set(e.record,"newPassword",s)},expression:"record.newPassword"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:24}},[r("el-form-item",{attrs:{prop:"repeatPassword",label:e.$t("users.confirmNewPassword")}},[r("el-input",{attrs:{type:"password"},model:{value:e.record.repeatPassword,callback:function(s){e.$set(e.record,"repeatPassword",s)},expression:"record.repeatPassword"}})],1)],1)],1):e._e(),e._v(" "),r("el-col",{attrs:{span:24}},[r("el-form-item",{attrs:{prop:"tags",label:e.$t("users.remark")}},[r("el-input",{model:{value:e.record.tags,callback:function(s){e.$set(e.record,"tags",s)},expression:"record.tags"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:24}},[r("el-form-item",["edit"===e.oper?r("el-button",{staticClass:"cache-btn change-password",attrs:{type:"text"},on:{click:function(s){e.changePassword=!e.changePassword}}},[e._v("\n "+e._s(e.changePassword?e.$t("users.dontChangePassword"):e.$t("users.changePassword"))+"\n ")]):e._e()],1)],1)],1)],1),e._v(" "),r("div",{attrs:{slot:"footer"},slot:"footer"},[r("el-button",{staticClass:"cache-btn",attrs:{type:"text"},on:{click:function(s){e.dialogVisible=!1}}},[e._v("\n "+e._s(e.$t("oper.cancel"))+"\n ")]),e._v(" "),r("el-button",{staticClass:"confirm-btn",attrs:{type:"success",loading:e.$store.state.loading},on:{click:e.createUser}},[e._v("\n "+e._s(e.$t("oper.save"))+"\n ")])],1)],1)],1)},staticRenderFns:[]};var c=r("VU/8")(i,l,!1,function(e){r("1RJS")},null,null);s.default=c.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/11.a25bdc9445a685a0b097.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/11.a25bdc9445a685a0b097.js deleted file mode 100644 index 50b7d84076..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/11.a25bdc9445a685a0b097.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([11],{GQ4E:function(t,e,s){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var a=s("woOf"),n=s.n(a),o={name:"topic-metrics",components:{},props:{},watch:{currentExpandRow:{deep:!0,handler:function(){clearInterval(this.timer)}}},data:function(){return{expands:[],addVisible:!1,popoverVisible:!1,modClosed:!1,topicQos:"all",timer:0,topics:[],currentExpandRow:{},currentTopic:{},record:{},rules:{topic:{required:!0,message:this.$t("oper.pleaseEnter")}}}},methods:{getRowKeys:function(t){return t.topic},loadData:function(){var t=this;this.$httpGet("/topic-metrics").then(function(e){var s=e.data;t.topics=s.map(function(t){var e=t.metrics;return{topic:t.topic,messageIn:e["messages.in.count"],messageOut:e["messages.out.count"],messageDrop:e["messages.dropped.count"]}}),t.modClosed=!1}).catch(function(e){t.$message.warning(t.$t("error."+e.message)),t.modClosed=!0})},hidePopover:function(){var t=this;this.popoverVisible=!0,setTimeout(function(){t.popoverVisible=!1},0)},handleOperation:function(){this.addVisible=!0},handleModLoad:function(){var t=this;this.$httpPut("/modules/emqx_mod_topic_metrics/load").then(function(){t.$message.success(t.$t("oper.enableSuccess")),t.loadData(),t.modClosed=!1}).catch(function(e){t.$message.error(e||t.$t("error.networkError"))})},deleteTopicMetric:function(t){var e=this;this.$httpDelete("/topic-metrics/"+encodeURIComponent(t.topic)).then(function(){e.loadData(),e.hidePopover()}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})},handleAdd:function(){var t=this;this.$refs.record.validate(function(e){if(e){var s={};n()(s,t.record),t.$httpPost("/topic-metrics",s).then(function(){t.handleClose(),t.loadData()}).catch(function(){})}})},handleClose:function(){this.addVisible=!1,this.$refs.record.resetFields()},viewTopicDetails:function(t,e){var s=document.querySelectorAll(".el-table__expand-icon")[e];s&&s.click()},loadDetail:function(){var t=this;this.$httpGet("/topic-metrics/"+encodeURIComponent(this.currentTopic.topic)).then(function(e){t.currentTopic=e.data,t.loadData()}).catch(function(){})},setLoadDetailInterval:function(){var t=this;this.timer=setInterval(function(){t.$httpGet("/topic-metrics/"+encodeURIComponent(t.currentExpandRow.topic)).then(function(e){t.currentTopic=e.data}).catch(function(){})},1e4)},handleExpandChange:function(t,e){var s=this;if(!e.length)return this.currentExpandRow={},void clearInterval(this.timer);this.currentExpandRow=t,this.currentTopic={},this.$httpGet("/topic-metrics/"+encodeURIComponent(t.topic)).then(function(a){s.currentTopic=a.data,s.$refs.crudTable.store.states.expandRows=e.length?[t]:[],s.loadData(),s.setLoadDetailInterval()}).catch(function(){})},getCurrentTopicData:function(t,e){var s={all:"messages",qos0:"messages.qos0",qos1:"messages.qos1",qos2:"messages.qos2"}[this.topicQos],a=this.currentTopic[s+"."+t+"."+e];return"rate"===e&&a?a.toFixed(2):a},getCurrentTopicDropRate:function(t){return t?t.toFixed(2):t}},created:function(){this.loadData()},beforeRouteLeave:function(t,e,s){clearInterval(this.timer),s()},beforeDestroy:function(){clearInterval(this.timer)}},i={render:function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"topic-metrics"},[s("div",{staticClass:"page-title"},[t._v("\n "+t._s(t.$t("analysis.topicMetrics"))+"\n "),s("span",{staticClass:"sub-tip"},[t._v(t._s(t.$t("analysis.metricsTip")))]),t._v(" "),t.modClosed?s("el-button",{staticClass:"confirm-btn",staticStyle:{float:"right"},attrs:{round:"",plain:"",type:"success",size:"medium",disable:t.$store.state.loading},on:{click:t.handleModLoad}},[t._v("\n "+t._s(t.$t("modules.enable"))+"\n ")]):s("el-button",{staticClass:"confirm-btn",staticStyle:{float:"right"},attrs:{round:"",plain:"",type:"success",icon:"el-icon-plus",size:"medium",disable:t.$store.state.loading},on:{click:t.handleOperation}},[t._v("\n "+t._s(t.$t("rule.create"))+"\n ")])],1),t._v(" "),s("el-table",{directives:[{name:"loading",rawName:"v-loading",value:t.$store.state.loading,expression:"$store.state.loading"}],ref:"crudTable",attrs:{border:"",data:t.topics,"row-key":t.getRowKeys,"expand-row-keys":t.expands},on:{"expand-change":t.handleExpandChange}},[s("el-table-column",{attrs:{type:"expand"},scopedSlots:t._u([{key:"default",fn:function(e){return[s("div",{staticClass:"expand-header"},[t._v("\n "+t._s(t.$t("analysis.details"))+"\n "),s("el-radio-group",{staticClass:"topic-qos-radio",attrs:{prop:e,size:"mini"},model:{value:t.topicQos,callback:function(e){t.topicQos=e},expression:"topicQos"}},[s("el-radio-button",{attrs:{label:"all"}},[t._v(t._s(t.$t("analysis.all")))]),t._v(" "),s("el-radio-button",{attrs:{label:"qos0"}},[t._v("QoS 0")]),t._v(" "),s("el-radio-button",{attrs:{label:"qos1"}},[t._v("QoS 1")]),t._v(" "),s("el-radio-button",{attrs:{label:"qos2"}},[t._v("QoS 2")])],1)],1),t._v(" "),s("el-row",{staticClass:"expand-body",attrs:{gutter:20}},[s("el-col",{attrs:{span:8}},[s("div",{staticClass:"message-card in"},[s("div",[t._v("\n "+t._s(t.$t("analysis.messageIn"))+"\n "),s("span",{staticClass:"message-rate"},[t._v("\n "+t._s(t.$t("analysis.rateItem",[t.getCurrentTopicData("in","rate")]))+"\n "+t._s(t.$t("analysis.rate"))+"\n ")])]),t._v(" "),s("div",{staticClass:"message-card--body"},[t._v("\n "+t._s(t.getCurrentTopicData("in","count"))+"\n ")])])]),t._v(" "),s("el-col",{attrs:{span:8}},[s("div",{staticClass:"message-card out"},[s("div",[t._v("\n "+t._s(t.$t("analysis.messageOut"))+"\n "),s("span",{staticClass:"message-rate"},[t._v("\n "+t._s(t.$t("analysis.rateItem",[t.getCurrentTopicData("out","rate")]))+"\n "+t._s(t.$t("analysis.rate"))+"\n ")])]),t._v(" "),s("div",{staticClass:"message-card--body"},[t._v("\n "+t._s(t.getCurrentTopicData("out","count"))+"\n ")])])]),t._v(" "),s("el-col",{attrs:{span:8}},[s("div",{staticClass:"message-card drop"},[s("div",[t._v("\n "+t._s(t.$t("analysis.messageDrop"))+"\n "),s("span",{staticClass:"message-rate"},[t._v("\n "+t._s(t.$t("analysis.rateItem",[t.getCurrentTopicDropRate(t.currentTopic["messages.dropped.rate"])]))+"\n "+t._s(t.$t("analysis.rate"))+"\n ")])]),t._v(" "),s("div",{staticClass:"message-card--body"},[t._v("\n "+t._s(t.currentTopic["messages.dropped.count"])+"\n ")])])])],1)]}}])}),t._v(" "),s("el-table-column",{attrs:{prop:"topic",label:t.$t("topics.topic")}}),t._v(" "),s("el-table-column",{attrs:{prop:"messageIn",label:t.$t("analysis.messageIn")}}),t._v(" "),s("el-table-column",{attrs:{prop:"messageOut",label:t.$t("analysis.messageOut")}}),t._v(" "),s("el-table-column",{attrs:{prop:"messageDrop",label:t.$t("analysis.messageDrop")}}),t._v(" "),s("el-table-column",{attrs:{width:"180px",label:t.$t("oper.oper")},scopedSlots:t._u([{key:"default",fn:function(e){return[s("el-button",{attrs:{type:"success",size:"mini",plain:""},on:{click:function(s){return t.viewTopicDetails(e.row,e.$index)}}},[t._v("\n "+t._s(t.$t("oper.view"))+"\n ")]),t._v(" "),s("el-popover",{attrs:{placement:"right",trigger:"click",value:t.popoverVisible}},[s("p",[t._v(t._s(t.$t("oper.confirmDelete")))]),t._v(" "),s("div",{staticStyle:{"text-align":"right"}},[s("el-button",{staticClass:"cache-btn",attrs:{size:"mini",type:"text"},on:{click:t.hidePopover}},[t._v("\n "+t._s(t.$t("oper.cancel"))+"\n ")]),t._v(" "),s("el-button",{attrs:{size:"mini",type:"success"},on:{click:function(s){return t.deleteTopicMetric(e.row)}}},[t._v("\n "+t._s(t.$t("oper.confirm"))+"\n ")])],1),t._v(" "),s("el-button",{attrs:{slot:"reference",size:"mini",type:"danger",plain:""},slot:"reference"},[t._v("\n "+t._s(t.$t("oper.delete"))+"\n ")])],1)]}}])})],1),t._v(" "),s("el-dialog",{staticClass:"create-subscribe",attrs:{title:t.$t("analysis.addTopic"),width:"400px",visible:t.addVisible},on:{"update:visible":function(e){t.addVisible=e}},nativeOn:{keyup:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"enter",13,e.key,"Enter")?null:t.handleAdd(e)}}},[s("el-form",{ref:"record",staticClass:"el-form--public",attrs:{model:t.record,rules:t.rules,size:"small","label-position":"top"}},[s("el-form-item",{attrs:{prop:"topic",label:t.$t("subscriptions.topic")}},[s("el-input",{attrs:{placeholder:"Topic"},model:{value:t.record.topic,callback:function(e){t.$set(t.record,"topic",e)},expression:"record.topic"}})],1)],1),t._v(" "),s("div",{attrs:{slot:"footer"},slot:"footer"},[s("el-button",{staticClass:"cache-btn",attrs:{type:"text"},on:{click:t.handleClose}},[t._v("\n "+t._s(t.$t("oper.cancel"))+"\n ")]),t._v(" "),s("el-button",{staticClass:"confirm-btn",attrs:{type:"success",loading:t.$store.state.loading},on:{click:t.handleAdd}},[t._v("\n "+t._s(t.$t("oper.add"))+"\n ")])],1)],1)],1)},staticRenderFns:[]};var r=s("VU/8")(o,i,!1,function(t){s("g17P")},null,null);e.default=r.exports},g17P:function(t,e){}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/12.61ad9e0afab97e6dbda5.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/12.61ad9e0afab97e6dbda5.js deleted file mode 100644 index f8eac06171..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/12.61ad9e0afab97e6dbda5.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([12],{SFPK:function(t,e){},VKKr:function(t,e,s){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=s("mvHQ"),a=s.n(o),i=s("zL8q"),n=s("VOAv"),l={name:"settings-view",components:{"el-radio":i.Radio,"el-radio-group":i.RadioGroup,"el-button":i.Button,"el-form":i.Form,"el-form-item":i.FormItem,"el-row":i.Row,"el-col":i.Col,"el-card":i.Card},data:function(){return{options:{themes:"",language:""},defaultConfig:"",defaultThemes:"",defaultLanguage:""}},computed:{notChanged:function(){return this.defaultConfig===a()(this.options)}},methods:{init:function(){var t=window.localStorage.getItem("themes")||"dark-themes";t="light-themes"===t?"light-themes":"dark-themes",this.options.themes=t,this.defaultThemes=t,this.options.language=window.localStorage.getItem("language")||"en",this.options.language="zh"===this.options.language?"zh":"en",this.defaultLanguage=this.options.language,this.defaultConfig=a()(this.options)},themesToggle:function(){Object(n.b)(this.options.themes)},applySetting:function(){this.$message.success(this.$t("settings.success")),this.themesToggle(),this.defaultThemes=this.options.themes,window.localStorage.setItem("language",this.options.language),window.localStorage.setItem("themes",this.options.themes),this.defaultLanguage!==this.options.language&&setTimeout(function(){location.reload()},600),this.defaultConfig=a()(this.options)}},created:function(){this.init()},beforeRouteLeave:function(t,e,s){this.defaultThemes!==this.options.themes&&Object(n.b)(this.defaultThemes),s()}},r={render:function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"settings-view"},[s("div",{staticClass:"page-title"},[t._v(t._s(t.$t("leftbar.settings")))]),t._v(" "),s("el-card",{staticClass:"el-card--self"},[s("el-row",{attrs:{gutter:20}},[s("el-form",{ref:"options",attrs:{model:t.options,"label-width":"100px","label-position":"top"}},[s("el-col",{attrs:{span:12}},[s("el-form-item",{attrs:{label:t.$t("settings.themes")}},[s("el-radio-group",{on:{change:t.themesToggle},model:{value:t.options.themes,callback:function(e){t.$set(t.options,"themes",e)},expression:"options.themes"}},[s("el-radio",{attrs:{label:"dark-themes"}},[t._v("Dark")]),t._v(" "),s("el-radio",{attrs:{label:"light-themes"}},[t._v("Light")])],1)],1)],1),t._v(" "),s("el-col",{attrs:{span:12}},[s("el-form-item",{attrs:{label:t.$t("settings.language")}},[s("el-radio-group",{model:{value:t.options.language,callback:function(e){t.$set(t.options,"language",e)},expression:"options.language"}},[s("el-radio",{attrs:{label:"en"}},[t._v("EN")]),t._v(" "),s("el-radio",{attrs:{label:"zh"}},[t._v("中文")])],1)],1)],1),t._v(" "),s("el-col",{staticClass:"operation-area",attrs:{span:24}},[s("el-form-item",[s("el-button",{staticClass:"confirm-btn",attrs:{type:"success",disabled:t.notChanged},on:{click:t.applySetting}},[t._v("\n "+t._s(t.$t("settings.apply"))+"\n ")])],1)],1)],1)],1)],1)],1)},staticRenderFns:[]};var g=s("VU/8")(l,r,!1,function(t){s("SFPK")},null,null);e.default=g.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/13.8256223b47c5c8d6f77d.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/13.8256223b47c5c8d6f77d.js deleted file mode 100644 index 97655b2a7e..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/13.8256223b47c5c8d6f77d.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([13],{IhqM:function(t,e){},IvP6:function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=i("Xxa5"),a=i.n(n),s=i("exGp"),l=i.n(s),r={name:"rules-view",components:{RuleActions:i("eDC2").a},props:{},data:function(){return{ruleDialogLoading:!1,timer:0,rule:{for:[],metrics:{}},dialogVisible:!1,tableData:[]}},methods:{getMatchedCount:function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).metrics,e=0;return(void 0===t?[]:t).forEach(function(t){var i=t.matched;e+=i}),e},getHitRate:function(t){var e=t.matched,i=void 0===e?0:e,n=t.nomatch,a=i/(i+(void 0===n?0:n))*100;return a.toString().split(".")[1]&&a.toString().split(".")[1].length>2?a.toFixed(2):a},viewRule:function(t){var e=this;return l()(a.a.mark(function i(){var n;return a.a.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:if(!t.id){i.next=3;break}return e.$router.push("/rules/"+t.id),i.abrupt("return");case 3:return i.next=5,e.$httpGet("/rules/"+t.id);case 5:if(i.t1=i.sent,i.t1){i.next=8;break}i.t1={};case 8:if(i.t0=i.t1.data,i.t0){i.next=11;break}i.t0={};case 11:n=i.t0,e.rule=n||t,e.dialogVisible=!0,clearTimeout(e.timer),e.timer=setTimeout(function(){e.viewRule(t)},1e4);case 16:case"end":return i.stop()}},i,e)}))()},editRule:function(t){this.$router.push("/rules/create?rule="+t.id)},loadDetails:function(t){var e=this;this.ruleDialogLoading=!0,this.$httpGet("/rules/"+t).then(function(t){var i=t.data;e.rule=i,setTimeout(function(){e.ruleDialogLoading=!1},500)}).catch(function(){e.ruleDialogLoading=!1})},closeDialog:function(){clearInterval(this.timer),this.loadData()},handleDelete:function(t){var e=this;this.$confirm(this.$t("rule.confirm_stop_delete"),"Notice",{confirmButtonClass:"confirm-btn",confirmButtonText:this.$t("oper.confirm"),cancelButtonClass:"cache-btn el-button--text",cancelButtonText:this.$t("oper.cancel"),type:"warning"}).then(function(){e.$httpDelete("/rules/"+t.id).then(function(){e.$message.success(e.$t("rule.delete_success")),e.loadData()})}).catch()},handleOperation:function(){this.$router.push("/rules/create")},loadData:function(){var t=this;this.$httpGet("/rules").then(function(e){t.tableData=e.data;var i=t.tableData.find(function(e){return e.id===t.rule.id});i&&(t.rule=i)})},updateRule:function(t){var e=this,i=t.id,n=t.enabled;this.$httpPut("/rules/"+i,{enabled:n}).then(function(){e.$message.success(e.$t("oper.editSuccess"))})}},filters:{actionsFilter:function(t){return t.map(function(t){return t.name}).join(", ")}},created:function(){this.loadData(),clearInterval(this.timer)},beforeRouteLeave:function(t,e,i){clearInterval(this.timer),i()}},o={render:function(){var t=this,e=t.$createElement,i=t._self._c||e;return i("div",{staticClass:"rules-view"},[i("div",{staticClass:"page-title"},[t._v("\n "+t._s(t.$t("rule.message_rule"))+"\n "),i("el-button",{staticClass:"confirm-btn",staticStyle:{float:"right"},attrs:{round:"",plain:"",type:"success",icon:"el-icon-plus",size:"medium",disable:t.$store.state.loading},on:{click:t.handleOperation}},[t._v("\n "+t._s(t.$t("rule.create"))+"\n ")])],1),t._v(" "),i("el-table",{directives:[{name:"loading",rawName:"v-loading",value:t.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:t.tableData}},[i("el-table-column",{attrs:{prop:"id",label:t.$t("rule.id")},scopedSlots:t._u([{key:"default",fn:function(e){var n=e.row;return[i("span",{staticClass:"btn",on:{click:function(e){return t.viewRule(n)}}},[t._v("\n "+t._s(n.id)+"\n ")])]}}])}),t._v(" "),i("el-table-column",{attrs:{prop:"for",label:t.$t("rule.topic")}}),t._v(" "),i("el-table-column",{attrs:{prop:"rawsql","min-width":"150px",label:"SQL"}}),t._v(" "),i("el-table-column",{attrs:{prop:"actions",label:t.$t("rule.actions")},scopedSlots:t._u([{key:"default",fn:function(e){var n=e.row;return t._l(n.actions,function(e,n){return i("div",{key:n,staticClass:"action-item"},[t._v("\n "+t._s(e.name)+"\n ")])})}}])}),t._v(" "),i("el-table-column",{attrs:{prop:"metrics.matched","min-width":"110px",label:t.$t("rule.rule_matched_1"),formatter:t.getMatchedCount}}),t._v(" "),i("el-table-column",{attrs:{label:t.$t("rule.viewStates")},scopedSlots:t._u([{key:"default",fn:function(e){return[i("el-tooltip",{attrs:{content:e.row.enabled?t.$t("rule.ruleEnabled"):t.$t("rule.ruleDisabled"),placement:"left"}},[i("el-switch",{attrs:{"active-text":"","inactive-text":"","active-color":"#13ce66","inactive-color":"#ff4949"},on:{change:function(i){return t.updateRule(e.row)}},model:{value:e.row.enabled,callback:function(i){t.$set(e.row,"enabled",i)},expression:"props.row.enabled"}})],1)]}}])}),t._v(" "),i("el-table-column",{attrs:{label:t.$t("rule.oper"),"min-width":"120px"},scopedSlots:t._u([{key:"default",fn:function(e){var n=e.row;return[i("el-button",{attrs:{type:"success",size:"mini",plain:""},on:{click:function(e){return t.editRule(n)}}},[t._v("\n "+t._s(t.$t("rule.edit"))+"\n ")]),t._v(" "),i("el-button",{attrs:{size:"mini",type:"danger",plain:""},on:{click:function(e){return t.handleDelete(n)}}},[t._v("\n "+t._s(t.$t("rule.delete"))+"\n ")])]}}])})],1),t._v(" "),i("el-dialog",{attrs:{title:t.$t("rule.rule_details"),visible:t.dialogVisible},on:{"update:visible":function(e){t.dialogVisible=e},close:t.closeDialog}},[i("div",{staticClass:"dialog-preview"},[i("div",{staticClass:"option-item"},[i("div",{staticClass:"option-title"},[t._v(t._s(t.$t("rule.id")))]),t._v(" "),i("div",{staticClass:"option-value"},[t._v(t._s(t.rule.id))])]),t._v(" "),i("div",{staticClass:"option-item"},[i("div",{staticClass:"option-title"},[t._v(t._s(t.$t("rule.trigger_events")))]),t._v(" "),i("div",{staticClass:"option-value"},[t._v(t._s((t.rule.for||[]).join(",")))])]),t._v(" "),i("div",{staticClass:"option-item"},[i("div",{staticClass:"option-title"},[t._v(t._s(t.$t("rule.rule_desc")))]),t._v(" "),i("div",{staticClass:"option-value"},[t._v(t._s(t.rule.description))])]),t._v(" "),i("div",{staticClass:"option-item"},[i("div",{staticClass:"option-title"},[t._v("SQL")]),t._v(" "),i("div",{staticClass:"option-all"},[i("code",[t._v("\n "+t._s(t.rule.rawsql)+"\n ")])])]),t._v(" "),i("div",{staticClass:"option-item"},[i("div",{staticClass:"option-title"},[t._v("\n "+t._s(t.$t("rule.metrics"))+"\n "),i("i",{directives:[{name:"show",rawName:"v-show",value:t.ruleDialogLoading,expression:"ruleDialogLoading"}],staticClass:"el-icon-loading"})]),t._v(" "),i("div",{staticClass:"option-all"},[i("span",{attrs:{size:"mini",type:"info"}},[t._v("\n "+t._s(t.$t("rule.rule_matched_1"))+": "),i("span",[t._v(t._s(t.rule.metrics.matched))]),t._v(" "+t._s(t.$t("rule.match_unit"))+"\n ")]),t._v(" "),i("span",{attrs:{size:"mini",type:"info"}},[t._v("\n "+t._s(t.$t("rule.speed_current"))+": "),i("span",[t._v(t._s(t.rule.metrics.speed))]),t._v(" "+t._s(t.$t("rule.speed_unit"))+"\n ")]),t._v(" "),i("span",{attrs:{size:"mini",type:"info"}},[t._v("\n "+t._s(t.$t("rule.speed_max_1"))+": "),i("span",[t._v(t._s(t.rule.metrics.speed_max))]),t._v(" "+t._s(t.$t("rule.speed_unit"))+"\n ")]),t._v(" "),i("span",{attrs:{size:"mini",type:"info"}},[t._v("\n "+t._s(t.$t("rule.speed_last5m_1"))+": "),i("span",[t._v(t._s(t.rule.metrics.speed_last5m))]),t._v(" "+t._s(t.$t("rule.speed_unit"))+"\n ")])])]),t._v(" "),i("el-table-column",{attrs:{prop:"description",label:t.$t("rule.description")}}),t._v(" "),i("div",{staticClass:"option-item"},[i("div",{staticClass:"option-title"},[t._v("\n "+t._s(t.$t("rule.actions"))+"\n "),i("i",{directives:[{name:"show",rawName:"v-show",value:t.ruleDialogLoading,expression:"ruleDialogLoading"}],staticClass:"el-icon-loading"})]),t._v(" "),i("div",{staticClass:"option-all"},[i("rule-actions",{attrs:{"in-dialog":"",record:t.rule,operations:[]}})],1)])],1),t._v(" "),i("div",{attrs:{slot:"footer"},slot:"footer"},[i("el-button",{staticClass:"confirm-btn",attrs:{type:"success"},on:{click:function(e){t.dialogVisible=!1}}},[t._v("\n "+t._s(t.$t("rule.confirm"))+"\n ")])],1)])],1)},staticRenderFns:[]};var u=i("VU/8")(r,o,!1,function(t){i("IhqM")},null,null);e.default=u.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/14.ef8c67f93678b65855f9.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/14.ef8c67f93678b65855f9.js deleted file mode 100644 index a538853fde..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/14.ef8c67f93678b65855f9.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([14],{"B/3Q":function(e,t){},JWuK:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=r("Xxa5"),s=r.n(a),l=r("exGp"),n=r.n(l),o={name:"RuleView",components:{RuleActions:r("eDC2").a},props:{},data:function(){return{record:{actions:[{id:"inspect_1562305995013447740",metrics:[{failed:0,node:"emqx@127.0.0.1",success:0}],name:"inspect",params:{}}],description:"",enabled:!0,for:["message.publish"],id:"rule:b35e3e59",metrics:[{matched:0,node:"emqx@127.0.0.1",speed:0,speed_last5m:0,speed_max:0}],rawsql:"SELECT\n *\nFROM\n \"message.publish\"\nWHERE\n topic =~ '#'"}}},methods:{loadData:function(){var e=this;return n()(s.a.mark(function t(){var r;return s.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(e.id){t.next=2;break}return t.abrupt("return");case 2:return t.next=4,e.$httpGet("/rules/"+e.id);case 4:r=t.sent,e.record=r.data;case 6:case"end":return t.stop()}},t,e)}))()}},created:function(){this.loadData()},computed:{id:function(){return this.$route.params.id}}},c={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("div",{staticClass:"rule-view"},[r("div",{staticClass:"page-title"},[r("el-breadcrumb",{attrs:{separator:"/"}},[r("el-breadcrumb-item",{attrs:{to:{path:"/rules"}}},[e._v("\n "+e._s(e.$t("rule.message_rule"))+"\n ")]),e._v(" "),r("el-breadcrumb-item",{staticClass:"breadcrumb-name"},[e._v(e._s(e.id))])],1)],1),e._v(" "),r("el-card",{staticClass:"el-card--self"},[r("div",{staticClass:"config-dialog",attrs:{slot:"header"},slot:"header"},[e._v("\n "+e._s(e.$t("rule.basic_info"))+"\n ")]),e._v(" "),r("el-form",{attrs:{model:e.record,"label-position":"left","label-width":"100px","label-suffix":":"}},[r("el-form-item",{attrs:{label:e.$t("rule.topic")}},[r("span",[e._v(e._s(e.record.for.join(",")))])]),e._v(" "),r("el-form-item",{attrs:{label:e.$t("rule.description")}},[r("span",[e._v(e._s(e.record.description))])]),e._v(" "),r("el-form-item",{attrs:{label:e.$t("rule.rule_sql")}},[r("code",[e._v(e._s(e.record.rawsql))])])],1)],1),e._v(" "),r("el-card",{staticClass:"el-card--self"},[r("div",{staticClass:"config-dialog",attrs:{slot:"header"},slot:"header"},[e._v("\n "+e._s(e.$t("rule.metrics"))+"\n ")]),e._v(" "),r("el-table",{attrs:{border:"",data:e.record.metrics}},[r("el-table-column",{attrs:{prop:"node",label:e.$t("rule.node")}}),e._v(" "),r("el-table-column",{attrs:{prop:"matched",sortable:"",label:e.$t("rule.rule_matched_1")}}),e._v(" "),r("el-table-column",{attrs:{prop:"speed",sortable:"",label:e.$t("rule.speed_current")}}),e._v(" "),r("el-table-column",{attrs:{prop:"speed_max",label:e.$t("rule.speed_max_1")}}),e._v(" "),r("el-table-column",{attrs:{prop:"speed_last5m",label:e.$t("rule.speed_last5m_1")}})],1)],1),e._v(" "),r("el-card",{staticClass:"el-card--self"},[r("div",{staticClass:"config-dialog",attrs:{slot:"header"},slot:"header"},[e._v("\n "+e._s(e.$t("rule.set_action"))+"\n ")]),e._v(" "),r("rule-actions",{attrs:{record:e.record,operations:[]}})],1)],1)},staticRenderFns:[]};var i=r("VU/8")(o,c,!1,function(e){r("B/3Q")},null,null);t.default=i.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/15.b9733bdf5c9d0e15c082.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/15.b9733bdf5c9d0e15c082.js deleted file mode 100644 index 7ef92af756..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/15.b9733bdf5c9d0e15c082.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([15],{"6vbc":function(t,e){},xPbZ:function(t,e,s){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=s("Dd8w"),n=s.n(i),a={name:"resources-view",components:{ResourceDialog:s("SHGx").a},props:{},data:function(){return{dialogVisible:!1,viewDialogVisible:!1,tableData:[],res:{},reloadLoading:!1,currentResource:""}},methods:{viewRunningStatus:function(t,e){var s=document.querySelectorAll(".el-table__expand-icon")[e];s&&s.click&&s.click()},handleReconnect:function(t,e){var s=this;this.reloadLoading=!0,this.currentResource=t.id,this.$httpPost("/resources/"+t.id).then(function(){setTimeout(function(){s.reloadLoading=!1,s.$message.success(s.$t("rule.connectSuccess"));try{t.status[e].is_alive=!0}catch(t){console.log(t)}},300)}).catch(function(){s.reloadLoading=!1})},handleDelete:function(t){var e=this;this.$confirm(this.$t("rule.confirm_stop_delete"),"Notice",{confirmButtonClass:"confirm-btn",confirmButtonText:this.$t("oper.confirm"),cancelButtonClass:"cache-btn el-button--text",cancelButtonText:this.$t("oper.cancel"),type:"warning"}).then(function(){e.$httpDelete("/resources/"+t.id).then(function(){e.$message.success(e.$t("rule.delete_success")),e.loadData()})}).catch()},viewResource:function(t){this.res=n()({},t),this.viewDialogVisible=!0},handleOperation:function(){this.dialogVisible=!0},loadData:function(){var t=this;this.$httpGet("/resources").then(function(e){var s=e.data;t.tableData=s.map(function(t){return t.status=t.status||[],t})})},handExpand:function(t){var e=this;t.status&&t.status.length>0||this.$httpGet("/resources/"+t.id).then(function(s){e.$set(t,"status",s.data.status)})}},created:function(){this.loadData()}},o={render:function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"resources-view"},[s("div",{staticClass:"page-title"},[t._v("\n "+t._s(t.$t("rule.resource_title"))+"\n "),s("el-button",{staticClass:"confirm-btn",staticStyle:{float:"right"},attrs:{round:"",plain:"",type:"success",icon:"el-icon-plus",size:"medium",disable:t.$store.state.loading},on:{click:t.handleOperation}},[t._v("\n "+t._s(t.$t("rule.create"))+"\n ")])],1),t._v(" "),s("el-table",{attrs:{border:"",data:t.tableData},on:{"expand-change":t.handExpand}},[s("el-table-column",{attrs:{prop:"id",type:"expand","class-name":"expand-column",width:"1px"},scopedSlots:t._u([{key:"default",fn:function(e){var i=e.row;return[s("ul",{staticClass:"status-wrapper"},t._l(i.status||[],function(e,n){return s("li",{key:n,staticClass:"status-item"},[s("span",{staticClass:"key"},[t._v("\n "+t._s(e.node)+"\n ")]),t._v(" "),s("span",{class:[e.is_alive?"running":"stopped danger","status"]},[t._v("\n "+t._s(e.is_alive?t.$t("rule.enabled"):t.$t("rule.disabled"))+"\n ")]),t._v(" "),e.is_alive?t._e():s("el-button",{attrs:{loading:t.reloadLoading&&t.currentResource===i.id,plain:"",type:"success",size:"mini"},on:{click:function(e){return t.handleReconnect(i,n)}}},[t._v("\n "+t._s(t.$t("rule.reconnect"))+"\n ")])],1)}),0)]}}])}),t._v(" "),s("el-table-column",{attrs:{prop:"id",label:t.$t("rule.id")},scopedSlots:t._u([{key:"default",fn:function(e){var i=e.row;return[s("span",{on:{click:function(e){return t.viewResource(i)}}},[t._v("\n "+t._s(i.id)+"\n ")])]}}])}),t._v(" "),s("el-table-column",{attrs:{prop:"description",label:t.$t("rule.resource_name")}}),t._v(" "),s("el-table-column",{attrs:{prop:"type",label:t.$t("rule.resource_type")}}),t._v(" "),s("el-table-column",{attrs:{label:t.$t("rule.oper")},scopedSlots:t._u([{key:"default",fn:function(e){var i=e.row,n=e.$index;return[s("el-button",{attrs:{plain:"",type:"success",size:"mini"},on:{click:function(e){return t.viewResource(i)}}},[t._v("\n "+t._s(t.$t("rule.view"))+"\n ")]),t._v(" "),s("el-button",{attrs:{plain:"",size:"mini",type:"warning"},on:{click:function(e){return t.handleDelete(i)}}},[t._v("\n "+t._s(t.$t("rule.delete"))+"\n ")]),t._v(" "),s("el-button",{attrs:{plain:"",type:"success",size:"mini"},on:{click:function(e){return t.viewRunningStatus(i,n)}}},[t._v("\n "+t._s(t.$t("rule.viewStates"))+"\n ")])]}}])})],1),t._v(" "),s("resource-dialog",{ref:"resourceDialog",attrs:{visible:t.dialogVisible},on:{"update:visible":function(e){t.dialogVisible=e},confirm:t.loadData}}),t._v(" "),s("el-dialog",{attrs:{title:t.$t("rule.resource_details"),visible:t.viewDialogVisible},on:{"update:visible":function(e){t.viewDialogVisible=e}}},[s("div",{staticClass:"dialog-preview"},[s("div",{staticClass:"option-item"},[s("div",{staticClass:"option-title"},[t._v("\n "+t._s(t.$t("rule.id"))+"\n ")]),t._v(" "),s("div",{staticClass:"option-value"},[t._v(t._s(t.res.id))])]),t._v(" "),s("div",{staticClass:"option-item"},[s("div",{staticClass:"option-title"},[t._v("\n "+t._s(t.$t("rule.resource_type"))+"\n ")]),t._v(" "),s("div",{staticClass:"option-value"},[t._v(t._s(t.res.type))])]),t._v(" "),s("div",{staticClass:"option-item"},[s("div",{staticClass:"option-title"},[t._v("\n "+t._s(t.$t("rule.resource_name"))+"\n ")]),t._v(" "),s("div",{staticClass:"option-value"},[t._v(t._s(t.res.description))])]),t._v(" "),t.res.config&&Object.keys(t.res.config).length>0?s("div",{staticClass:"option-item"},[s("div",{staticClass:"option-title"},[t._v("\n "+t._s(t.$t("rule.config_info"))+"\n ")]),t._v(" "),s("div",{staticClass:"option-all"},t._l(Object.entries(t.res.config),function(e,i){return s("div",{key:i,staticClass:"option-item"},["object"!=typeof e[1]||Array.isArray(e[1])?[s("div",{staticClass:"option-title"},[t._v("\n "+t._s(e[0])+"\n ")]),t._v(" "),s("div",{staticClass:"option-value"},[t._v("\n "+t._s(e[1])+"\n ")])]:[s("div",{staticClass:"option-title"},[t._v("\n "+t._s(e[0])+"\n ")]),t._v(" "),s("div",{staticClass:"option-value"},[e[1]&&0!==Object.keys(e[1]).length?s("data-table",{staticStyle:{"margin-top":"0"},attrs:{disabled:""},model:{value:e[1],callback:function(s){t.$set(e,1,s)},expression:"item[1]"}}):s("span",[t._v("\n N/A\n ")])],1)]],2)}),0)]):t._e()]),t._v(" "),s("div",{attrs:{slot:"footer"},slot:"footer"},[s("el-button",{staticClass:"confirm-btn",attrs:{type:"success"},on:{click:function(e){t.viewDialogVisible=!1}}},[t._v("\n "+t._s(t.$t("rule.confirm"))+"\n ")])],1)])],1)},staticRenderFns:[]};var l=s("VU/8")(a,o,!1,function(t){s("6vbc")},null,null);e.default=l.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/16.cac14bf01c2463f006f8.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/16.cac14bf01c2463f006f8.js deleted file mode 100644 index 251588a7bc..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/16.cac14bf01c2463f006f8.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([16],{RjBg:function(e,t,s){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=s("fZjL"),l=s.n(a),o=s("d7EF"),n=s.n(o),r=s("W3Iv"),i=s.n(r),c=s("Dd8w"),d=s.n(c),v=s("zL8q"),u=s("NYxO"),m={name:"overview-view",components:{"el-select":v.Select,"el-option":v.Option,"el-table":v.Table,"el-table-column":v.TableColumn,"el-row":v.Row,"el-col":v.Col},data:function(){return{nodeName:"",brokers:{},nodes:[],stats:[],timer:0,metrics:{packets:[],messages:[],bytes:[],client:[],session:[],delivery:[]}}},methods:d()({},Object(u.b)(["CURRENT_NODE"]),{init:function(){var e=this;this.$httpGet("/nodes").then(function(t){e.nodeName=e.$store.state.nodeName||t.data[0].node,e.nodes=t.data,e.CURRENT_NODE(e.nodeName),e.refreshInterval()}).catch(function(t){e.$message.error(t||e.$t("error.networkError")),setTimeout(function(){e.init()},2e4)})},refreshInterval:function(){this.loadData(),clearInterval(this.timer),this.timer=setInterval(this.loadData,1e4)},loadData:function(){var e=this;this.CURRENT_NODE(this.nodeName),this.$httpGet("/nodes").then(function(t){e.nodes=t.data.sort(function(t,s){return t.node===e.nodeName?-1:t.uptime>s.uptime?-1:1})}),this.$httpGet("/stats").then(function(t){var s=t.data;s.forEach(function(e){var t=d()({node:e.node},e.stats);i()(t).forEach(function(t){var s=n()(t,2),a=s[0],l=s[1],o=a.replace(/\./g,"_");e[o]=l,a.includes(".")&&delete e[a]})}),e.stats=s}),this.$httpGet("/brokers/"+this.nodeName).then(function(t){e.brokers=t.data}),this.$httpGet("/nodes/"+this.nodeName+"/metrics").then(function(t){e.metrics={packets:[],messages:[],bytes:[],client:[],session:[],delivery:[]};var s=d()({},t.data),a={packets:["received","sent","connect","connack","auth","disconnect.sent","disconnect.received","pingreq","pingresp","publish.received","publish.sent","puback.received","puback.sent","puback.missed","pubcomp.received","pubcomp.sent","pubcomp.missed","pubrec.received","pubrec.sent","pubrec.missed","pubrel.received","pubrel.sent","pubrel.missed","subscribe","suback","unsubscribe","unsuback"],messages:["received","sent","dropped","retained","qos0.received","qos0.sent","qos1.received","qos1.sent","qos2.received","qos2.expired","qos2.sent","qos2.dropped"],bytes:["received","sent"],client:["connected","authenticate","auth.anonymous","check_acl","subscribe","unsubscribe","disconnected"],session:["created","resumed","takeovered","discarded","terminated"],delivery:["dropped","dropped.no_local","dropped.too_large","dropped.qos0_msg","dropped.queue_full","dropped.expired"]};l()(a).forEach(function(l){a[l].forEach(function(a){var o=l+"."+a;delete s[o],void 0!==t.data[o]&&e.metrics[l].push({key:a,value:t.data[o]})})}),l()(s).forEach(function(t){var a=t.split(".")[0];e.metrics[a]&&void 0!==s[t]&&e.metrics[a].push({key:t.split(".").slice(1).join("."),value:s[t]})})})}}),created:function(){this.init()},beforeRouteLeave:function(e,t,s){clearInterval(this.timer),s()},beforeDestroy:function(){clearInterval(this.timer)}},p={render:function(){var e=this,t=e.$createElement,s=e._self._c||t;return s("div",{staticClass:"overview-view"},[s("div",{staticClass:"page-title"},[e._v("\n "+e._s(e.$t("leftbar.overview"))+"\n "),s("el-select",{staticClass:"select-radius",attrs:{placeholder:e.$t("select.placeholder")},on:{change:e.loadData},model:{value:e.nodeName,callback:function(t){e.nodeName=t},expression:"nodeName"}},e._l(e.nodes,function(e){return s("el-option",{key:e.node,attrs:{label:e.node,value:e.node}})}),1)],1),e._v(" "),s("div",{staticClass:"card-box",staticStyle:{"margin-top":"54px"}},[s("div",{staticClass:"card-title"},[e._v(e._s(e.$t("overview.broker")))]),e._v(" "),s("el-row",{staticClass:"broker-card",attrs:{gutter:10}},[s("el-col",{attrs:{span:6}},[s("div",{staticClass:"card-item"},[s("div",{staticClass:"icon"},[s("i",{staticClass:"iconfont icon-systemname"})]),e._v(" "),s("div",{staticClass:"desc"},[s("h3",[e._v(e._s(e.$t("overview.systemName")))]),e._v(" "),s("p",[e._v(e._s(e.brokers.sysdescr))])])])]),e._v(" "),s("el-col",{attrs:{span:6}},[s("div",{staticClass:"card-item"},[s("div",{staticClass:"icon"},[s("i",{staticClass:"iconfont icon-version",staticStyle:{"font-weight":"600"}})]),e._v(" "),s("div",{staticClass:"desc"},[s("h3",[e._v(e._s(e.$t("overview.version")))]),e._v(" "),s("p",[e._v(e._s(e.brokers.version))])])])]),e._v(" "),s("el-col",{attrs:{span:6}},[s("div",{staticClass:"card-item"},[s("div",{staticClass:"icon"},[s("i",{staticClass:"iconfont icon-uptime"})]),e._v(" "),s("div",{staticClass:"desc"},[s("h3",[e._v(e._s(e.$t("overview.uptime")))]),e._v(" "),s("p",[e._v(e._s(e.brokers.uptime))])])])]),e._v(" "),s("el-col",{attrs:{span:6}},[s("div",{staticClass:"card-item"},[s("div",{staticClass:"icon",staticStyle:{"line-height":"46px"}},[s("i",{staticClass:"iconfont icon-Systemtime",staticStyle:{"font-size":"36px",top:"2px"}})]),e._v(" "),s("div",{staticClass:"desc"},[s("h3",[e._v(e._s(e.$t("overview.systemTime")))]),e._v(" "),s("p",[e._v(e._s(e.brokers.datetime))])])])])],1)],1),e._v(" "),s("div",{staticClass:"card-box"},[s("div",{staticClass:"card-title"},[e._v(e._s(e.$t("overview.nodes"))+"("+e._s(e.nodes.length)+")")]),e._v(" "),s("el-table",{attrs:{data:e.nodes,border:""}},[s("el-table-column",{attrs:{prop:"node","min-width":"200",label:e.$t("overview.name")}}),e._v(" "),s("el-table-column",{attrs:{prop:"otp_release","min-width":"200",label:e.$t("overview.erlangOTPRelease")}}),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.erlangProcesses")}},[s("el-table-column",{attrs:{"min-width":"150",prop:"process",label:"(used/avaliable)"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v("\n "+e._s(t.row.process_used+" / "+t.row.process_available)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.cpuInfo")}},[s("el-table-column",{attrs:{"min-width":"180",label:" (1load/5load/15load)"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v("\n "+e._s(t.row.load1+" / "+t.row.load5+" / "+t.row.load15)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{"min-width":"200",label:e.$t("overview.memoryInfo")}},[s("el-table-column",{attrs:{"min-width":"180",label:" (used/total)"},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v("\n "+e._s(t.row.memory_used+" / "+t.row.memory_total)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{prop:"max_fds","min-width":"120",label:e.$t("overview.maxFds")}}),e._v(" "),s("el-table-column",{attrs:{"min-width":"120",label:e.$t("overview.status")},scopedSlots:e._u([{key:"default",fn:function(t){return[s("span",{class:["Running"===t.row.node_status?"running":"stopped","status"]},[e._v("\n "+e._s(t.row.node_status)+"\n ")])]}}])})],1)],1),e._v(" "),s("div",{staticClass:"card-box"},[s("div",{staticClass:"card-title"},[e._v(e._s(e.$t("overview.stats"))+"("+e._s(e.stats.length)+")")]),e._v(" "),s("el-table",{staticClass:"stats-table",attrs:{data:e.stats,border:""}},[s("el-table-column",{attrs:{prop:"node","min-width":"150",label:e.$t("overview.name")}}),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.connectionsCount")}},[s("el-table-column",{attrs:{"min-width":"150",label:"(count/max)"},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[e._v("\n "+e._s(s.connections_count)+" / "+e._s(s.connections_max)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.topicsCount")}},[s("el-table-column",{attrs:{"min-width":"150",label:"(count/max)"},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[e._v("\n "+e._s(s.topics_count)+" / "+e._s(s.topics_max)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.retainedCount")}},[s("el-table-column",{attrs:{"min-width":"150",label:"(count/max)"},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[e._v("\n "+e._s(s.retained_count)+" / "+e._s(s.retained_max)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.sessionsCount")}},[s("el-table-column",{attrs:{"min-width":"150",label:"(count/max)"},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[e._v("\n "+e._s(s.sessions_count)+" / "+e._s(s.sessions_max)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.subscriptionsCount")}},[s("el-table-column",{attrs:{"min-width":"150",label:"(count/max)"},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[e._v("\n "+e._s(s.subscriptions_count)+" / "+e._s(s.subscriptions_max)+"\n ")]}}])})],1),e._v(" "),s("el-table-column",{attrs:{label:e.$t("overview.subscriptionsSharedCount")}},[s("el-table-column",{attrs:{"min-width":"150",label:"(count/max)"},scopedSlots:e._u([{key:"default",fn:function(t){var s=t.row;return[e._v("\n "+e._s(s.subscriptions_shared_count)+" / "+e._s(s.subscriptions_shared_max)+"\n ")]}}])})],1)],1)],1),e._v(" "),s("div",{staticClass:"card-box"},[s("div",{staticClass:"card-title"},[e._v(e._s(e.$t("overview.metrics")))]),e._v(" "),s("el-row",{attrs:{gutter:20}},[s("el-col",{attrs:{span:8}},[s("el-table",{attrs:{data:e.metrics.client}},[s("el-table-column",{attrs:{"min-width":"200",prop:"key",label:e.$t("overview.client")}}),e._v(" "),s("el-table-column",{attrs:{sortable:"",prop:"value",label:""}})],1)],1),e._v(" "),s("el-col",{attrs:{span:8}},[s("el-table",{attrs:{data:e.metrics.delivery}},[s("el-table-column",{attrs:{"min-width":"160",prop:"key",label:e.$t("overview.delivery")}}),e._v(" "),s("el-table-column",{attrs:{sortable:"",prop:"value",label:""}})],1)],1),e._v(" "),s("el-col",{attrs:{span:8}},[s("el-table",{attrs:{data:e.metrics.session}},[s("el-table-column",{attrs:{"min-width":"200",prop:"key",label:e.$t("overview.session")}}),e._v(" "),s("el-table-column",{attrs:{sortable:"",prop:"value",label:""}})],1)],1)],1),e._v(" "),s("el-row",{attrs:{gutter:20}},[s("el-col",{attrs:{span:8}},[s("el-table",{attrs:{data:e.metrics.packets}},[s("el-table-column",{attrs:{"min-width":"200",prop:"key",label:e.$t("overview.packetsData")}}),e._v(" "),s("el-table-column",{attrs:{sortable:"",prop:"value",label:""}})],1)],1),e._v(" "),s("el-col",{attrs:{span:8}},[s("el-table",{attrs:{data:e.metrics.messages}},[s("el-table-column",{attrs:{"min-width":"200",prop:"key",label:e.$t("overview.messagesData")}}),e._v(" "),s("el-table-column",{attrs:{sortable:"",prop:"value",label:""}})],1)],1),e._v(" "),s("el-col",{attrs:{span:8}},[s("el-table",{attrs:{data:e.metrics.bytes}},[s("el-table-column",{attrs:{"min-width":"160",prop:"key",label:e.$t("overview.bytesData")}}),e._v(" "),s("el-table-column",{attrs:{sortable:"",prop:"value",label:""}})],1)],1)],1)],1)])},staticRenderFns:[]};var b=s("VU/8")(m,p,!1,function(e){s("xOct")},null,null);t.default=b.exports},xOct:function(e,t){}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/17.76a240d156c8ad7d6537.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/17.76a240d156c8ad7d6537.js deleted file mode 100644 index 83d3e225ea..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/17.76a240d156c8ad7d6537.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([17],{rF5L:function(t,e){},wkqA:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"not-found"},[n("p",[t._v("404 Not Found")]),t._v(" "),n("router-link",{attrs:{to:"/"}},[t._v("Homepage")]),t._v(" "),n("router-link",{attrs:{to:"#"},on:{click:function(e){return t.$router.go(-2)}}},[t._v("Back up")])],1)},staticRenderFns:[]};var o=n("VU/8")({name:"NotFound"},r,!1,function(t){n("rF5L")},null,null);e.default=o.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/18.ed75dc87f1bcbbb0877e.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/18.ed75dc87f1bcbbb0877e.js deleted file mode 100644 index c596e7b31e..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/18.ed75dc87f1bcbbb0877e.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([18],{lmfZ:function(e,r,s){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var o=s("Dd8w"),t=s.n(o),n=s("zL8q"),l=s("NYxO"),i={name:"login-view",components:{"el-col":n.Col,"el-row":n.Row,"el-card":n.Card,"el-form":n.Form,"el-form-item":n.FormItem,"el-input":n.Input,"el-checkbox":n.Checkbox,"el-button":n.Button},data:function(){return{remember:!1,user:{username:"",password:""},loginError:{username:"",password:""}}},methods:t()({},Object(l.b)(["USER_LOGIN"]),{login:function(){var e=this;return this.user.username?this.user.password?void this.$axios.post("/auth",this.user).then(function(){e.USER_LOGIN({user:e.user,remember:e.remember}),e.$router.push(e.$route.query.redirect||"/")}).catch(function(){e.loginError.username=e.$t("login.error"),e.user={username:"",password:""}}):(this.loginError.password=this.$t("login.passwordRequired"),!1):(this.loginError.username=this.$t("login.usernameRequired"),!1)}})},a={render:function(){var e=this,r=e.$createElement,s=e._self._c||r;return s("div",{staticClass:"login-view"},[s("el-card",[s("div",{attrs:{slot:"header"},slot:"header"},[e._v("\n "+e._s(e.$t("login.title"))+"\n ")]),e._v(" "),s("el-form",{staticClass:"el-form--public",attrs:{size:"medium","label-position":"top",model:e.user},nativeOn:{keyup:function(r){return!r.type.indexOf("key")&&e._k(r.keyCode,"enter",13,r.key,"Enter")?null:e.login(r)}}},[s("el-form-item",{attrs:{label:e.$t("login.username")}},[s("el-input",{class:{error:e.loginError.username},attrs:{placeholder:e.loginError.username},on:{focus:function(r){e.loginError.username=""}},model:{value:e.user.username,callback:function(r){e.$set(e.user,"username",r)},expression:"user.username"}})],1),e._v(" "),s("el-form-item",{attrs:{label:e.$t("login.password")}},[s("el-input",{class:{error:e.loginError.password},attrs:{type:"password",placeholder:e.loginError.password},on:{focus:function(r){e.loginError.password=""}},model:{value:e.user.password,callback:function(r){e.$set(e.user,"password",r)},expression:"user.password"}})],1)],1),e._v(" "),s("div",{staticClass:"login-footer"},[s("el-checkbox",{model:{value:e.remember,callback:function(r){e.remember=r},expression:"remember"}},[e._v("\n "+e._s(e.$t("login.remember"))+"\n ")]),e._v(" "),s("el-button",{staticClass:"confirm-btn",attrs:{type:"success",loading:e.$store.state.loading,disabled:e.$store.state.loading},on:{click:e.login}},[e._v(e._s(e.$t("login.loginButton"))+"\n ")])],1),e._v(" "),s("div",{staticClass:"clear-fix"})],1)],1)},staticRenderFns:[]};var u=s("VU/8")(i,a,!1,function(e){s("pcrU")},null,null);r.default=u.exports},pcrU:function(e,r){}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/19.e3716ab3b0f6ffc6b9b9.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/19.e3716ab3b0f6ffc6b9b9.js deleted file mode 100644 index 96c34afe2f..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/19.e3716ab3b0f6ffc6b9b9.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([19],{tz6M:function(e,t){},uuOo:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n("Dd8w"),a=n.n(s),o=n("NYxO"),l=n("zL8q"),r={name:"listeners-view",components:{"el-select":l.Select,"el-option":l.Option,"el-table":l.Table,"el-table-column":l.TableColumn},data:function(){return{nodeName:"",nodes:[],listeners:[]}},methods:a()({},Object(o.b)(["CURRENT_NODE"]),{loadData:function(){var e=this;this.$httpGet("/nodes").then(function(t){e.nodeName=e.$store.state.nodeName||t.data[0].node,e.nodes=t.data,e.loadListeners()}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})},loadListeners:function(){var e=this;this.CURRENT_NODE(this.nodeName),this.$httpGet("/nodes/"+this.nodeName+"/listeners").then(function(t){e.listeners=t.data}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})}}),created:function(){this.loadData()}},i={render:function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"listeners-view"},[n("div",{staticClass:"page-title"},[e._v("\n "+e._s(e.$t("leftbar.listeners"))+"\n "),n("el-select",{staticClass:"select-radius",attrs:{placeholder:e.$t("select.placeholder"),disabled:e.$store.state.loading},on:{change:e.loadListeners},model:{value:e.nodeName,callback:function(t){e.nodeName=t},expression:"nodeName"}},e._l(e.nodes,function(e){return n("el-option",{key:e.node,attrs:{label:e.node,value:e.node}})}),1)],1),e._v(" "),n("el-table",{directives:[{name:"loading",rawName:"v-loading",value:e.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:e.listeners}},[n("el-table-column",{attrs:{prop:"protocol",width:"240",label:e.$t("listeners.protocol")}}),e._v(" "),n("el-table-column",{attrs:{prop:"listen_on","min-width":"240",label:e.$t("listeners.listenOn")}}),e._v(" "),n("el-table-column",{attrs:{prop:"max_conns","min-width":"180",label:e.$t("listeners.maxConnections")}}),e._v(" "),n("el-table-column",{attrs:{prop:"current_conns","min-width":"120",label:e.$t("listeners.currentConnections")}})],1)],1)},staticRenderFns:[]};var c=n("VU/8")(r,i,!1,function(e){n("tz6M")},null,null);t.default=c.exports}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/2.c752e72435f46ed413fb.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/2.c752e72435f46ed413fb.js deleted file mode 100644 index e254086baa..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/2.c752e72435f46ed413fb.js +++ /dev/null @@ -1,8 +0,0 @@ -webpackJsonp([2],{"+0Qw":function(e,t){},"+HRN":function(e,t,n){"use strict";var i=n("kkc6").Buffer,r=n(2);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},e.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t,n,r,o=i.allocUnsafe(e>>>0),s=this.head,a=0;s;)t=s.data,n=o,r=a,t.copy(n,r),a+=s.data.length,s=s.next;return o},e}(),r&&r.inspect&&r.inspect.custom&&(e.exports.prototype[r.inspect.custom]=function(){var e=r.inspect({length:this.length});return this.constructor.name+" "+e})},"+Tn7":function(e,t){},"+e0g":function(e,t,n){"use strict";var i=n("3PYz"),r=n("lZ6o"),o=r.utils,s=o.assert,a=o.parseBytes,u=n("RzOE"),c=n("hkfz");function l(e){if(s("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof l))return new l(e);e=r.curves[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=i.sha512}e.exports=l,l.prototype.sign=function(e,t){e=a(e);var n=this.keyFromSecret(t),i=this.hashInt(n.messagePrefix(),e),r=this.g.mul(i),o=this.encodePoint(r),s=this.hashInt(o,n.pubBytes(),e).mul(n.priv()),u=i.add(s).umod(this.curve.n);return this.makeSignature({R:r,S:u,Rencoded:o})},l.prototype.verify=function(e,t,n){e=a(e),t=this.makeSignature(t);var i=this.keyFromPublic(n),r=this.hashInt(t.Rencoded(),i.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(i.pub().mul(r)).eq(o)},l.prototype.hashInt=function(){for(var e=this.hash(),t=0;t16)throw new Error("unable to decrypt data");var n=-1;for(;++n16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},d.prototype.flush=function(){if(this.cache.length)return this.cache},t.createDecipher=function(e,t){var n=o[e.toLowerCase()];if(!n)throw new TypeError("invalid suite type");var i=c(t,!1,n.key,n.iv);return h(e,i.key,i.iv)},t.createDecipheriv=h},"+jct":function(e,t,n){"use strict";n.d(t,"b",function(){return i}),n.d(t,"a",function(){return r}),t.c=function(e){var t=r;if(e&&e instanceof RegExp)if(e.global)t=e;else{var n="g";e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.unicode&&(n+="u"),t=new RegExp(e.source,n)}return t.lastIndex=0,t},t.d=function(e,t,n,i){t.lastIndex=0;var r=t.exec(n);if(!r)return null;var o=r[0].indexOf(" ")>=0?function(e,t,n,i){var r,o=e-1-i;t.lastIndex=0;for(;r=t.exec(n);){var s=r.index||0;if(s>o)return null;if(t.lastIndex>=o)return{word:r[0],startColumn:i+1+s,endColumn:i+1+t.lastIndex}}return null}(e,t,n,i):function(e,t,n,i){var r,o=e-1-i,s=n.lastIndexOf(" ",o-1)+1;t.lastIndex=s;for(;r=t.exec(n);){var a=r.index||0;if(a<=o&&t.lastIndex>=o)return{word:r[0],startColumn:i+1+a,endColumn:i+1+t.lastIndex}}return null}(e,t,n,i);return t.lastIndex=0,o};var i="`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";var r=function(e){void 0===e&&(e="");for(var t="(-?\\d*\\.\\d\\w*)|([^",n=0,r=i;n=0||(t+="\\"+o)}return t+="\\s]+)",new RegExp(t,"g")}()},"+oh4":function(e,t,n){"use strict";var i;n.d(t,"a",function(){return i}),n.d(t,"b",function(){return r}),function(e){e[e.None=0]="None",e[e.Indent=1]="Indent",e[e.IndentOutdent=2]="IndentOutdent",e[e.Outdent=3]="Outdent"}(i||(i={}));var r=function(){function e(e){if(this.open=e.open,this.close=e.close,this._standardTokenMask=0,Array.isArray(e.notIn))for(var t=0,n=e.notIn.length;t200)return t;if("object"==typeof t){switch(t.$mid){case 1:return i.a.revive(t);case 2:return new RegExp(t.source,t.flags)}for(var r in t)Object.hasOwnProperty.call(t,r)&&(t[r]=e(t[r],n+1))}return t}(t,0)};var i=n("mrx5")},"/9db":function(e,t,n){"use strict";n.d(t,"a",function(){return i});var i,r=n("7g0X");!function(e){e.editorTextFocus=new r.d("editorTextFocus",!1),e.focus=new r.d("editorFocus",!1),e.textInputFocus=new r.d("textInputFocus",!1),e.readOnly=new r.d("editorReadonly",!1),e.writable=e.readOnly.toNegated(),e.hasNonEmptySelection=new r.d("editorHasSelection",!1),e.hasOnlyEmptySelection=e.hasNonEmptySelection.toNegated(),e.hasMultipleSelections=new r.d("editorHasMultipleSelections",!1),e.hasSingleSelection=e.hasMultipleSelections.toNegated(),e.tabMovesFocus=new r.d("editorTabMovesFocus",!1),e.tabDoesNotMoveFocus=e.tabMovesFocus.toNegated(),e.isInEmbeddedEditor=new r.d("isInEmbeddedEditor",!1),e.canUndo=new r.d("canUndo",!1),e.canRedo=new r.d("canRedo",!1),e.languageId=new r.d("editorLangId",""),e.hasCompletionItemProvider=new r.d("editorHasCompletionItemProvider",!1),e.hasCodeActionsProvider=new r.d("editorHasCodeActionsProvider",!1),e.hasCodeLensProvider=new r.d("editorHasCodeLensProvider",!1),e.hasDefinitionProvider=new r.d("editorHasDefinitionProvider",!1),e.hasDeclarationProvider=new r.d("editorHasDeclarationProvider",!1),e.hasImplementationProvider=new r.d("editorHasImplementationProvider",!1),e.hasTypeDefinitionProvider=new r.d("editorHasTypeDefinitionProvider",!1),e.hasHoverProvider=new r.d("editorHasHoverProvider",!1),e.hasDocumentHighlightProvider=new r.d("editorHasDocumentHighlightProvider",!1),e.hasDocumentSymbolProvider=new r.d("editorHasDocumentSymbolProvider",!1),e.hasReferenceProvider=new r.d("editorHasReferenceProvider",!1),e.hasRenameProvider=new r.d("editorHasRenameProvider",!1),e.hasSignatureHelpProvider=new r.d("editorHasSignatureHelpProvider",!1),e.hasDocumentFormattingProvider=new r.d("editorHasDocumentFormattingProvider",!1),e.hasDocumentSelectionFormattingProvider=new r.d("editorHasDocumentSelectionFormattingProvider",!1),e.hasMultipleDocumentFormattingProvider=new r.d("editorHasMultipleDocumentFormattingProvider",!1),e.hasMultipleDocumentSelectionFormattingProvider=new r.d("editorHasMultipleDocumentSelectionFormattingProvider",!1)}(i||(i={}))},"/MLu":function(e,t,n){e.exports=n("cSWu").PassThrough},"/bUF":function(module,exports){var indexOf=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n=s&&e<=u||e>=a&&e<=c}function _(e,t,n,i){for(var r,o="",s=0,a=-1,u=0,c=0;c<=e.length;++c){if(c2){var h=o.lastIndexOf(n);-1===h?(o="",s=0):s=(o=o.slice(0,h)).length-1-o.lastIndexOf(n),a=c,u=0;continue}if(2===o.length||1===o.length){o="",s=0,a=c,u=0;continue}}t&&(o.length>0?o+=n+"..":o="..",s=2)}else o.length>0?o+=n+e.slice(a+1,c):o=e.slice(a+1,c),s=c-a-1;a=c,u=0}else r===l&&-1!==u?++u:u=-1}return o}function b(e,t){var n=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+i:n+e+i:i}var y={resolve:function(){for(var e=[],t=0;t=-1;s--){var a=void 0;if(s>=0?a=e[s]:n?void 0!==(a=r.b["="+n]||r.a())&&a.slice(0,3).toLowerCase()===n.toLowerCase()+"\\"||(a=n+"\\"):a=r.a(),p(a,"path"),0!==a.length){var u=a.length,c=0,l="",d=!1,h=a.charCodeAt(0);if(u>1)if(g(h))if(d=!0,g(a.charCodeAt(1))){for(var f=2,m=f;f2&&g(a.charCodeAt(2))&&(d=!0,c=3));else g(h)&&(c=1,d=!0);if(!(l.length>0&&n.length>0&&l.toLowerCase()!==n.toLowerCase())&&(0===n.length&&l.length>0&&(n=l),o||(i=a.slice(c)+"\\"+i,o=d),n.length>0&&o))break}}return i=_(i,!o,"\\",g),n+(o?"\\":"")+i||"."},normalize:function(e){p(e,"path");var t=e.length;if(0===t)return".";var n,i,r=0,o=!1,s=e.charCodeAt(0);if(t>1)if(g(s))if(o=!0,g(e.charCodeAt(1))){for(var a=2,u=a;a2&&g(e.charCodeAt(2))&&(o=!0,r=3));else if(g(s))return"\\";return 0!==(i=r0&&g(e.charCodeAt(t-1))&&(i+="\\"),void 0===n?o?i.length>0?"\\"+i:"\\":i.length>0?i:"":o?i.length>0?n+"\\"+i:n+"\\":i.length>0?n+i:n},isAbsolute:function(e){p(e,"path");var t=e.length;if(0===t)return!1;var n=e.charCodeAt(0);return!!g(n)||!!(v(n)&&t>2&&58===e.charCodeAt(1)&&g(e.charCodeAt(2)))},join:function(){for(var e,t,n=[],i=0;i0&&(void 0===e?e=t=o:e+="\\"+o)}if(void 0===e)return".";var s=!0,a=0;if("string"==typeof t&&g(t.charCodeAt(0))){++a;var u=t.length;u>1&&g(t.charCodeAt(1))&&(++a,u>2&&(g(t.charCodeAt(2))?++a:s=!1))}if(s){for(;a=2&&(e="\\"+e.slice(a))}return y.normalize(e)},relative:function(e,t){if(p(e,"from"),p(t,"to"),e===t)return"";var n=y.resolve(e),i=y.resolve(t);if(n===i)return"";if((e=n.toLowerCase())===(t=i.toLowerCase()))return"";for(var r=0;rr&&e.charCodeAt(o-1)===h;--o);for(var s=o-r,a=0;aa&&t.charCodeAt(u-1)===h;--u);for(var c=u-a,l=sl){if(t.charCodeAt(a+f)===h)return i.slice(a+f+1);if(2===f)return i.slice(a+f)}s>l&&(e.charCodeAt(r+f)===h?d=f:2===f&&(d=3));break}var g=e.charCodeAt(r+f);if(g!==t.charCodeAt(a+f))break;g===h&&(d=f)}if(f!==l&&-1===d)return i;var m="";for(-1===d&&(d=0),f=r+d+1;f<=o;++f)f!==o&&e.charCodeAt(f)!==h||(0===m.length?m+="..":m+="\\..");return m.length>0?m+i.slice(a+d,u):(a+=d,i.charCodeAt(a)===h&&++a,i.slice(a,u))},toNamespacedPath:function(e){if("string"!=typeof e)return e;if(0===e.length)return"";var t=y.resolve(e);if(t.length>=3)if(t.charCodeAt(0)===h){if(t.charCodeAt(1)===h){var n=t.charCodeAt(2);if(63!==n&&n!==l)return"\\\\?\\UNC\\"+t.slice(2)}}else if(v(t.charCodeAt(0))&&58===t.charCodeAt(1)&&t.charCodeAt(2)===h)return"\\\\?\\"+t;return e},dirname:function(e){p(e,"path");var t=e.length;if(0===t)return".";var n=-1,i=-1,r=!0,o=0,s=e.charCodeAt(0);if(t>1)if(g(s)){if(n=o=1,g(e.charCodeAt(1))){for(var a=2,u=a;a2&&g(e.charCodeAt(2))&&(n=o=3));else if(g(s))return e;for(var c=t-1;c>=o;--c)if(g(e.charCodeAt(c))){if(!r){i=c;break}}else r=!1;if(-1===i){if(-1===n)return".";i=n}return e.slice(0,i)},basename:function(e,t){void 0!==t&&p(t,"ext"),p(e,"path");var n,i=0,r=-1,o=!0;e.length>=2&&(v(e.charCodeAt(0))&&58===e.charCodeAt(1)&&(i=2));if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var s=t.length-1,a=-1;for(n=e.length-1;n>=i;--n){var u=e.charCodeAt(n);if(g(u)){if(!o){i=n+1;break}}else-1===a&&(o=!1,a=n+1),s>=0&&(u===t.charCodeAt(s)?-1==--s&&(r=n):(s=-1,r=a))}return i===r?r=a:-1===r&&(r=e.length),e.slice(i,r)}for(n=e.length-1;n>=i;--n)if(g(e.charCodeAt(n))){if(!o){i=n+1;break}}else-1===r&&(o=!1,r=n+1);return-1===r?"":e.slice(i,r)},extname:function(e){p(e,"path");var t=0,n=-1,i=0,r=-1,o=!0,s=0;e.length>=2&&58===e.charCodeAt(1)&&v(e.charCodeAt(0))&&(t=i=2);for(var a=e.length-1;a>=t;--a){var u=e.charCodeAt(a);if(g(u)){if(!o){i=a+1;break}}else-1===r&&(o=!1,r=a+1),u===l?-1===n?n=a:1!==s&&(s=1):-1!==n&&(s=-1)}return-1===n||-1===r||0===s||1===s&&n===r-1&&n===i+1?"":e.slice(n,r)},format:function(e){if(null===e||"object"!=typeof e)throw new f("pathObject","Object",e);return b("\\",e)},parse:function(e){p(e,"path");var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var n=e.length,i=0,r=e.charCodeAt(0);if(n>1){if(g(r)){if(i=1,g(e.charCodeAt(1))){for(var o=2,s=o;o2))return t.root=t.dir=e,t;if(g(e.charCodeAt(2))){if(3===n)return t.root=t.dir=e,t;i=3}}}else if(g(r))return t.root=t.dir=e,t;i>0&&(t.root=e.slice(0,i));for(var a=-1,u=i,c=-1,d=!0,h=e.length-1,f=0;h>=i;--h)if(g(r=e.charCodeAt(h))){if(!d){u=h+1;break}}else-1===c&&(d=!1,c=h+1),r===l?-1===a?a=h:1!==f&&(f=1):-1!==a&&(f=-1);return-1===a||-1===c||0===f||1===f&&a===c-1&&a===u+1?-1!==c&&(t.base=t.name=e.slice(u,c)):(t.name=e.slice(u,a),t.base=e.slice(u,c),t.ext=e.slice(a,c)),t.dir=u>0&&u!==i?e.slice(0,u-1):t.root,t},sep:"\\",delimiter:";",win32:null,posix:null},w={resolve:function(){for(var e=[],t=0;t=-1&&!i;o--){var s=void 0;p(s=o>=0?e[o]:r.a(),"path"),0!==s.length&&(n=s+"/"+n,i=s.charCodeAt(0)===d)}return n=_(n,!i,"/",m),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(e){if(p(e,"path"),0===e.length)return".";var t=e.charCodeAt(0)===d,n=e.charCodeAt(e.length-1)===d;return 0!==(e=_(e,!t,"/",m)).length||t||(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return p(e,"path"),e.length>0&&e.charCodeAt(0)===d},join:function(){for(var e,t=[],n=0;n0&&(void 0===e?e=r:e+="/"+r)}return void 0===e?".":w.normalize(e)},relative:function(e,t){if(p(e,"from"),p(t,"to"),e===t)return"";if((e=w.resolve(e))===(t=w.resolve(t)))return"";for(var n=1;na){if(t.charCodeAt(o+c)===d)return t.slice(o+c+1);if(0===c)return t.slice(o+c)}else r>a&&(e.charCodeAt(n+c)===d?u=c:0===c&&(u=0));break}var l=e.charCodeAt(n+c);if(l!==t.charCodeAt(o+c))break;l===d&&(u=c)}var h="";for(c=n+u+1;c<=i;++c)c!==i&&e.charCodeAt(c)!==d||(0===h.length?h+="..":h+="/..");return h.length>0?h+t.slice(o+u):(o+=u,t.charCodeAt(o)===d&&++o,t.slice(o))},toNamespacedPath:function(e){return e},dirname:function(e){if(p(e,"path"),0===e.length)return".";for(var t=e.charCodeAt(0)===d,n=-1,i=!0,r=e.length-1;r>=1;--r)if(e.charCodeAt(r)===d){if(!i){n=r;break}}else i=!1;return-1===n?t?"/":".":t&&1===n?"//":e.slice(0,n)},basename:function(e,t){void 0!==t&&p(t,"ext"),p(e,"path");var n,i=0,r=-1,o=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var s=t.length-1,a=-1;for(n=e.length-1;n>=0;--n){var u=e.charCodeAt(n);if(u===d){if(!o){i=n+1;break}}else-1===a&&(o=!1,a=n+1),s>=0&&(u===t.charCodeAt(s)?-1==--s&&(r=n):(s=-1,r=a))}return i===r?r=a:-1===r&&(r=e.length),e.slice(i,r)}for(n=e.length-1;n>=0;--n)if(e.charCodeAt(n)===d){if(!o){i=n+1;break}}else-1===r&&(o=!1,r=n+1);return-1===r?"":e.slice(i,r)},extname:function(e){p(e,"path");for(var t=-1,n=0,i=-1,r=!0,o=0,s=e.length-1;s>=0;--s){var a=e.charCodeAt(s);if(a!==d)-1===i&&(r=!1,i=s+1),a===l?-1===t?t=s:1!==o&&(o=1):-1!==t&&(o=-1);else if(!r){n=s+1;break}}return-1===t||-1===i||0===o||1===o&&t===i-1&&t===n+1?"":e.slice(t,i)},format:function(e){if(null===e||"object"!=typeof e)throw new f("pathObject","Object",e);return b("/",e)},parse:function(e){p(e,"path");var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var n,i=e.charCodeAt(0)===d;i?(t.root="/",n=1):n=0;for(var r=-1,o=0,s=-1,a=!0,u=e.length-1,c=0;u>=n;--u){var h=e.charCodeAt(u);if(h!==d)-1===s&&(a=!1,s=u+1),h===l?-1===r?r=u:1!==c&&(c=1):-1!==r&&(c=-1);else if(!a){o=u+1;break}}return-1===r||-1===s||0===c||1===c&&r===s-1&&r===o+1?-1!==s&&(t.base=t.name=0===o&&i?e.slice(1,s):e.slice(o,s)):(0===o&&i?(t.name=e.slice(1,r),t.base=e.slice(1,s)):(t.name=e.slice(o,r),t.base=e.slice(o,s)),t.ext=e.slice(r,s)),o>0?t.dir=e.slice(0,o-1):i&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};w.win32=y.win32=y,w.posix=y.posix=w;var C="win32"===r.c?y.normalize:w.normalize,S="win32"===r.c?y.join:w.join,x="win32"===r.c?y.relative:w.relative,L="win32"===r.c?y.dirname:w.dirname,O="win32"===r.c?y.basename:w.basename,k="win32"===r.c?y.extname:w.extname,N="win32"===r.c?y.sep:w.sep},"/vd3":function(e,t,n){t.pbkdf2=n("GUE9"),t.pbkdf2Sync=n("Zq1s")},"/y0r":function(e,t,n){var i=n("BEbT"),r=n("X3l8").Buffer,o=n("z+8S"),s=n("LC74"),a=n("UPHp"),u=n("H2Pp"),c=n("4sPJ");function l(e,t,n,s){o.call(this);var u=r.alloc(4,0);this._cipher=new i.AES(t);var l=this._cipher.encryptBlock(u);this._ghash=new a(l),n=function(e,t,n){if(12===t.length)return e._finID=r.concat([t,r.from([0,0,0,1])]),r.concat([t,r.from([0,0,0,2])]);var i=new a(n),o=t.length,s=o%16;i.update(t),s&&(s=16-s,i.update(r.alloc(s,0))),i.update(r.alloc(8,0));var u=8*o,l=r.alloc(8);l.writeUIntBE(u,0,8),i.update(l),e._finID=i.state;var d=r.from(e._finID);return c(d),d}(this,n,l),this._prev=r.from(n),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=s,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}s(l,o),l.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=r.alloc(t,0),this._ghash.update(t))}this._called=!0;var n=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(n),this._len+=e.length,n},l.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var n=0;e.length!==t.length&&n++;for(var i=Math.min(e.length,t.length),r=0;r0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},k=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}};!function(e){e.Hidden=new(function(){return function(){this.type=0}}());var t=function(){return function(e,t,n){this.actions=e,this.editorPosition=t,this.widgetPosition=n,this.type=1}}();e.Showing=t}(r||(r={}));var N,E=function(e){function t(t,n,i){var o=e.call(this)||this;return o._editor=t,o._quickFixActionId=n,o._keybindingService=i,o._onClick=o._register(new C.a),o.onClick=o._onClick.event,o._state=r.Hidden,o._domNode=document.createElement("div"),o._domNode.className="lightbulb-glyph",o._editor.addContentWidget(o),o._register(o._editor.onDidChangeModelContent(function(e){var t=o._editor.getModel();(1!==o._state.type||!t||o._state.editorPosition.lineNumber>=t.getLineCount())&&o.hide()})),o._register(p.k(o._domNode,"mousedown",function(e){if(1===o._state.type){o._editor.focus(),e.preventDefault();var t=p.x(o._domNode),n=t.top,i=t.height,r=o._editor.getConfiguration().lineHeight,s=Math.floor(r/3);null!==o._state.widgetPosition.position&&o._state.widgetPosition.position.lineNumber2&&i._editor.getTopForLineNumber(e)===i._editor.getTopForLineNumber(e-1)},f=s;if(!(o.fontInfo.spaceWidth*d>22))if(s>1&&!h(s-1))f-=1;else if(h(s+1)){if(a*o.fontInfo.spaceWidth<22)return this.hide()}else f+=1;this._state=new r.Showing(e,n,{position:{lineNumber:f,column:1},preference:t._posPref}),p.R(this._domNode,"autofixable",e.hasAutoFix),this._editor.layoutContentWidget(this)},Object.defineProperty(t.prototype,"title",{set:function(e){this._domNode.title=e},enumerable:!0,configurable:!0}),t.prototype.hide=function(){this._state=r.Hidden,this._editor.layoutContentWidget(this)},t.prototype._updateLightBulbTitle=function(){var e,t=this._keybindingService.lookupKeybinding(this._quickFixActionId);e=t?x.a("quickFixWithKb","Show Fixes ({0})",t.getLabel()):x.a("quickFix","Show Fixes"),this.title=e},t._posPref=[0],t=O([k(2,f.a)],t)}(o.a),I=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),D=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},M=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},T=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},P=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0))return[3,9];if(1!==e.trigger.autoApply&&(0!==e.trigger.autoApply||1!==t.actions.length))return[3,9];i.label=5;case 5:return i.trys.push([5,,7,8]),[4,this.delegate.applyCodeAction(t.actions[0],!1)];case 6:return i.sent(),[3,8];case 7:return t.dispose(),[7];case 8:return[2];case 9:return this._activeCodeActions.value=t,this._codeActionWidget.show(t,e.position),[3,11];case 10:this._codeActionWidget.isVisible?t.dispose():this._activeCodeActions.value=t,i.label=11;case 11:return[2]}})})},t.prototype.showCodeActionList=function(e,t){return T(this,void 0,void 0,function(){return P(this,function(n){return this._codeActionWidget.show(e,t),[2]})})},t.prototype._handleLightBulbSelect=function(e){this._codeActionWidget.show(e.actions,e)},t=D([M(3,h.a),M(4,f.a)],t)}(o.a),R=n("ItKl"),F=n("7g0X"),j=n("OHx0"),W=n("DBt1"),B=n("odeJ"),V=n("vTy2"),H=n("PCC9"),z=n("OBuU"),U=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),K=new F.d("supportedCodeAction",""),q=function(e){function t(t,n,i,r){void 0===r&&(r=250);var o=e.call(this)||this;return o._editor=t,o._markerService=n,o._signalChange=i,o._delay=r,o._autoTriggerTimer=o._register(new B.e),o._register(o._markerService.onMarkerChanged(function(e){return o._onMarkerChanges(e)})),o._register(o._editor.onDidChangeCursorPosition(function(){return o._onCursorChange()})),o}return U(t,e),t.prototype.trigger=function(e){var t=this._getRangeOfSelectionUnlessWhitespaceEnclosed(e);return this._createEventAndSignalChange(e,t)},t.prototype._onMarkerChanges=function(e){var t=this,n=this._editor.getModel();n&&e.some(function(e){return e.toString()===n.uri.toString()})&&this._autoTriggerTimer.cancelAndSet(function(){t.trigger({type:"auto"})},this._delay)},t.prototype._onCursorChange=function(){var e=this;this._autoTriggerTimer.cancelAndSet(function(){e.trigger({type:"auto"})},this._delay)},t.prototype._getRangeOfMarker=function(e){var t=this._editor.getModel();if(t)for(var n=0,i=this._markerService.read({resource:t.uri});n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},$=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},J=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},Q=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0;t--)this.editOperations[t]={operations:e.applyEdits(this.editOperations[t].operations)}},e.prototype.redo=function(e){for(var t=0;t0){var e=this.past.pop();try{e.undo(this.model)}catch(e){return Object(i.e)(e),this.clear(),null}return this.future.push(e),{selections:e.beforeCursorState,recordedVersionId:e.beforeVersionId}}return null},e.prototype.canUndo=function(){return this.past.length>0||null!==this.currentOpenStackElement},e.prototype.redo=function(){if(this.future.length>0){var e=this.future.pop();try{e.redo(this.model)}catch(e){return Object(i.e)(e),this.clear(),null}return this.past.push(e),{selections:e.afterCursorState,recordedVersionId:e.afterVersionId}}return null},e.prototype.canRedo=function(){return this.future.length>0},e}(),v=function(){return function(){this.spacesDiff=0,this.looksLikeAlignment=!1}}();function _(e,t,n,i,r){var o;for(r.spacesDiff=0,r.looksLikeAlignment=!1,o=0;o0&&a>0||c>0&&l>0)){var d=Math.abs(a-l),h=Math.abs(s-c);if(0===d)return r.spacesDiff=h,void(h>0&&0<=c-1&&c-10?r++:m>1&&o++,_(s,a,h,g,c),!c.looksLikeAlignment||n&&t===c.spacesDiff)){var S=c.spacesDiff;S<=8&&u[S]++,s=h,a=g}}var x=n;r!==o&&(x=rO&&(O=t,L=e)}),4===L&&u[4]>0&&u[2]>0&&u[2]>=u[4]/2&&(L=2)}return{insertSpaces:x,tabSize:L}}function y(e){return(1&e.metadata)>>>0}function w(e,t){e.metadata=254&e.metadata|t<<0}function C(e){return(2&e.metadata)>>>1==1}function S(e,t){e.metadata=253&e.metadata|(t?1:0)<<1}function x(e){return(4&e.metadata)>>>2==1}function L(e,t){e.metadata=251&e.metadata|(t?1:0)<<2}function O(e){return(8&e.metadata)>>>3==1}function k(e,t){e.metadata=247&e.metadata|(t?1:0)<<3}function N(e,t){e.metadata=207&e.metadata|t<<4}function E(e,t){e.metadata=191&e.metadata|(t?1:0)<<6}var I=function(){function e(e,t,n){this.metadata=0,this.parent=this,this.left=this,this.right=this,w(this,1),this.start=t,this.end=n,this.delta=0,this.maxEnd=n,this.id=e,this.ownerId=0,this.options=null,L(this,!1),N(this,1),k(this,!1),E(this,!1),this.cachedVersionId=0,this.cachedAbsoluteStart=t,this.cachedAbsoluteEnd=n,this.range=null,S(this,!1)}return e.prototype.reset=function(e,t,n,i){this.start=t,this.end=n,this.maxEnd=n,this.cachedVersionId=e,this.cachedAbsoluteStart=t,this.cachedAbsoluteEnd=n,this.range=i},e.prototype.setOptions=function(e){this.options=e;var t=this.options.className;L(this,"squiggly-error"===t||"squiggly-warning"===t||"squiggly-info"===t),N(this,this.options.stickiness),k(this,!(!this.options.overviewRuler||!this.options.overviewRuler.color)),E(this,this.options.collapseOnReplaceEdit)},e.prototype.setCachedOffsets=function(e,t,n){this.cachedVersionId!==n&&(this.range=null),this.cachedVersionId=n,this.cachedAbsoluteStart=e,this.cachedAbsoluteEnd=t},e.prototype.detach=function(){this.parent=null,this.left=null,this.right=null},e}(),D=new I(null,0,0);D.parent=D,D.left=D,D.right=D,w(D,0);var M=function(){function e(){this.root=D,this.requestNormalizeDelta=!1}return e.prototype.intervalSearch=function(e,t,n,i,r){return this.root===D?[]:function(e,t,n,i,r,o){var s=e.root,a=0,u=0,c=0,l=[],d=0;for(;s!==D;)if(C(s))S(s.left,!1),S(s.right,!1),s===s.parent.right&&(a-=s.parent.delta),s=s.parent;else{if(!C(s.left)){if(a+s.maxEndn)S(s,!0);else{if((c=a+s.end)>=t){s.setCachedOffsets(u,c,o);var h=!0;i&&s.ownerId&&s.ownerId!==i&&(h=!1),r&&x(s)&&(h=!1),h&&(l[d++]=s)}S(s,!0),s.right===D||C(s.right)||(a+=s.delta,s=s.right)}}return S(e.root,!1),l}(this,e,t,n,i,r)},e.prototype.search=function(e,t,n){return this.root===D?[]:function(e,t,n,i){var r=e.root,o=0,s=0,a=0,u=[],c=0;for(;r!==D;)if(C(r))S(r.left,!1),S(r.right,!1),r===r.parent.right&&(o-=r.parent.delta),r=r.parent;else if(r.left===D||C(r.left)){s=o+r.start,a=o+r.end,r.setCachedOffsets(s,a,i);var l=!0;t&&r.ownerId&&r.ownerId!==t&&(l=!1),n&&x(r)&&(l=!1),l&&(u[c++]=r),S(r,!0),r.right===D||C(r.right)||(o+=r.delta,r=r.right)}else r=r.left;return S(e.root,!1),u}(this,e,t,n)},e.prototype.collectNodesFromOwner=function(e){return function(e,t){var n=e.root,i=[],r=0;for(;n!==D;)C(n)?(S(n.left,!1),S(n.right,!1),n=n.parent):n.left===D||C(n.left)?(n.ownerId===t&&(i[r++]=n),S(n,!0),n.right===D||C(n.right)||(n=n.right)):n=n.left;return S(e.root,!1),i}(this,e)},e.prototype.collectNodesPostOrder=function(){return function(e){var t=e.root,n=[],i=0;for(;t!==D;)C(t)?(S(t.left,!1),S(t.right,!1),t=t.parent):t.left===D||C(t.left)?t.right===D||C(t.right)?(n[i++]=t,S(t,!0)):t=t.right:t=t.left;return S(e.root,!1),n}(this)},e.prototype.insert=function(e){A(this,e),this._normalizeDeltaIfNecessary()},e.prototype.delete=function(e){R(this,e),this._normalizeDeltaIfNecessary()},e.prototype.resolveNode=function(e,t){for(var n=e,i=0;e!==this.root;)e===e.parent.right&&(i+=e.parent.delta),e=e.parent;var r=n.start+i,o=n.end+i;n.setCachedOffsets(r,o,t)},e.prototype.acceptReplace=function(e,t,n,i){for(var r=function(e,t,n){var i=e.root,r=0,o=0,s=0,a=[],u=0;for(;i!==D;)if(C(i))S(i.left,!1),S(i.right,!1),i===i.parent.right&&(r-=i.parent.delta),i=i.parent;else{if(!C(i.left)){if(r+i.maxEndn?S(i,!0):((s=r+i.end)>=t&&(i.setCachedOffsets(o,s,0),a[u++]=i),S(i,!0),i.right===D||C(i.right)||(r+=i.delta,i=i.right))}return S(e.root,!1),a}(this,e,e+t),o=0,s=r.length;on?(r.start+=s,r.end+=s,r.delta+=s,(r.delta<-1073741824||r.delta>1073741824)&&(e.requestNormalizeDelta=!0),S(r,!0)):(S(r,!0),r.right===D||C(r.right)||(o+=r.delta,r=r.right))}S(e.root,!1)}(this,e,e+t,n),this._normalizeDeltaIfNecessary();for(o=0,s=r.length;on)&&(1!==i&&(2===i||t))}function P(e,t,n,i,r){var o=function(e){return(48&e.metadata)>>>4}(e),s=0===o||2===o,a=1===o||2===o,u=n-t,c=i,l=Math.min(u,c),d=e.start,h=!1,f=e.end,p=!1;t<=d&&f<=n&&function(e){return(64&e.metadata)>>>6==1}(e)&&(e.start=t,h=!0,e.end=t,p=!0);var g=r?1:u>0?2:0;if(!h&&T(d,s,t,g)&&(h=!0),!p&&T(f,a,t,g)&&(p=!0),l>0&&!r){g=u>c?2:0;!h&&T(d,s,t+l,g)&&(h=!0),!p&&T(f,a,t+l,g)&&(p=!0)}g=r?1:0;!h&&T(d,s,n,g)&&(e.start=t+c,h=!0),!p&&T(f,a,n,g)&&(e.end=t+c,p=!0);var m=c-u;h||(e.start=Math.max(0,d+m)),p||(e.end=Math.max(0,f+m)),e.start>e.end&&(e.end=e.start)}function A(e,t){if(e.root===D)return t.parent=D,t.left=D,t.right=D,w(t,0),e.root=t,e.root;!function(e,t){var n=0,i=e.root,r=t.start,o=t.end;for(;;){var s=z(r,o,i.start+n,i.end+n);if(s<0){if(i.left===D){t.start-=n,t.end-=n,t.maxEnd-=n,i.left=t;break}i=i.left}else{if(i.right===D){t.start-=n+i.delta,t.end-=n+i.delta,t.maxEnd-=n+i.delta,i.right=t;break}n+=i.delta,i=i.right}}t.parent=i,t.left=D,t.right=D,w(t,1)}(e,t),H(t.parent);for(var n=t;n!==e.root&&1===y(n.parent);){var i;if(n.parent===n.parent.parent.left)1===y(i=n.parent.parent.right)?(w(n.parent,0),w(i,0),w(n.parent.parent,1),n=n.parent.parent):(n===n.parent.right&&j(e,n=n.parent),w(n.parent,0),w(n.parent.parent,1),W(e,n.parent.parent));else 1===y(i=n.parent.parent.left)?(w(n.parent,0),w(i,0),w(n.parent.parent,1),n=n.parent.parent):(n===n.parent.left&&W(e,n=n.parent),w(n.parent,0),w(n.parent.parent,1),j(e,n.parent.parent))}return w(e.root,0),t}function R(e,t){var n,i;if(t.left===D?(i=t,(n=t.right).delta+=t.delta,(n.delta<-1073741824||n.delta>1073741824)&&(e.requestNormalizeDelta=!0),n.start+=t.delta,n.end+=t.delta):t.right===D?(n=t.left,i=t):((n=(i=function(e){for(;e.left!==D;)e=e.left;return e}(t.right)).right).start+=i.delta,n.end+=i.delta,n.delta+=i.delta,(n.delta<-1073741824||n.delta>1073741824)&&(e.requestNormalizeDelta=!0),i.start+=t.delta,i.end+=t.delta,i.delta=t.delta,(i.delta<-1073741824||i.delta>1073741824)&&(e.requestNormalizeDelta=!0)),i===e.root)return e.root=n,w(n,0),t.detach(),F(),V(n),void(e.root.parent=D);var r,o=1===y(i);if(i===i.parent.left?i.parent.left=n:i.parent.right=n,i===t?n.parent=i.parent:(i.parent===t?n.parent=i:n.parent=i.parent,i.left=t.left,i.right=t.right,i.parent=t.parent,w(i,y(t)),t===e.root?e.root=i:t===t.parent.left?t.parent.left=i:t.parent.right=i,i.left!==D&&(i.left.parent=i),i.right!==D&&(i.right.parent=i)),t.detach(),o)return H(n.parent),i!==t&&(H(i),H(i.parent)),void F();for(H(n),H(n.parent),i!==t&&(H(i),H(i.parent));n!==e.root&&0===y(n);)n===n.parent.left?(1===y(r=n.parent.right)&&(w(r,0),w(n.parent,1),j(e,n.parent),r=n.parent.right),0===y(r.left)&&0===y(r.right)?(w(r,1),n=n.parent):(0===y(r.right)&&(w(r.left,0),w(r,1),W(e,r),r=n.parent.right),w(r,y(n.parent)),w(n.parent,0),w(r.right,0),j(e,n.parent),n=e.root)):(1===y(r=n.parent.left)&&(w(r,0),w(n.parent,1),W(e,n.parent),r=n.parent.left),0===y(r.left)&&0===y(r.right)?(w(r,1),n=n.parent):(0===y(r.left)&&(w(r.right,0),w(r,1),j(e,r),r=n.parent.left),w(r,y(n.parent)),w(n.parent,0),w(r.left,0),W(e,n.parent),n=e.root));w(n,0),F()}function F(){D.parent=D,D.delta=0,D.start=0,D.end=0}function j(e,t){var n=t.right;n.delta+=t.delta,(n.delta<-1073741824||n.delta>1073741824)&&(e.requestNormalizeDelta=!0),n.start+=t.delta,n.end+=t.delta,t.right=n.left,n.left!==D&&(n.left.parent=t),n.parent=t.parent,t.parent===D?e.root=n:t===t.parent.left?t.parent.left=n:t.parent.right=n,n.left=t,t.parent=n,V(t),V(n)}function W(e,t){var n=t.left;t.delta-=n.delta,(t.delta<-1073741824||t.delta>1073741824)&&(e.requestNormalizeDelta=!0),t.start-=n.delta,t.end-=n.delta,t.left=n.right,n.right!==D&&(n.right.parent=t),n.parent=t.parent,t.parent===D?e.root=n:t===t.parent.right?t.parent.right=n:t.parent.left=n,n.right=t,t.parent=n,V(t),V(n)}function B(e){var t=e.end;if(e.left!==D){var n=e.left.maxEnd;n>t&&(t=n)}if(e.right!==D){var i=e.right.maxEnd+e.delta;i>t&&(t=i)}return t}function V(e){e.maxEnd=B(e)}function H(e){for(;e!==D;){var t=B(e);if(e.maxEnd===t)return;e.maxEnd=t,e=e.parent}}function z(e,t,n,i){return e===n?t-i:e-n}var U=function(){function e(e,t){this.piece=e,this.color=t,this.size_left=0,this.lf_left=0,this.parent=this,this.left=this,this.right=this}return e.prototype.next=function(){if(this.right!==K)return q(this.right);for(var e=this;e.parent!==K&&e.parent.left!==e;)e=e.parent;return e.parent===K?K:e.parent},e.prototype.prev=function(){if(this.left!==K)return G(this.left);for(var e=this;e.parent!==K&&e.parent.right!==e;)e=e.parent;return e.parent===K?K:e.parent},e.prototype.detach=function(){this.parent=null,this.left=null,this.right=null},e}(),K=new U(null,0);function q(e){for(;e.left!==K;)e=e.left;return e}function G(e){for(;e.right!==K;)e=e.right;return e}function Z(e){return e===K?0:e.size_left+e.piece.length+Z(e.right)}function Y(e){return e===K?0:e.lf_left+e.piece.lineFeedCnt+Y(e.right)}function X(){K.parent=K}function $(e,t){var n=t.right;n.size_left+=t.size_left+(t.piece?t.piece.length:0),n.lf_left+=t.lf_left+(t.piece?t.piece.lineFeedCnt:0),t.right=n.left,n.left!==K&&(n.left.parent=t),n.parent=t.parent,t.parent===K?e.root=n:t.parent.left===t?t.parent.left=n:t.parent.right=n,n.left=t,t.parent=n}function J(e,t){var n=t.left;t.left=n.right,n.right!==K&&(n.right.parent=t),n.parent=t.parent,t.size_left-=n.size_left+(n.piece?n.piece.length:0),t.lf_left-=n.lf_left+(n.piece?n.piece.lineFeedCnt:0),t.parent===K?e.root=n:t===t.parent.right?t.parent.right=n:t.parent.left=n,n.right=t,t.parent=n}function Q(e,t){var n,i;if(n=t.left===K?(i=t).right:t.right===K?(i=t).left:(i=q(t.right)).right,i===e.root)return e.root=n,n.color=0,t.detach(),X(),void(e.root.parent=K);var r=1===i.color;if(i===i.parent.left?i.parent.left=n:i.parent.right=n,i===t?(n.parent=i.parent,ne(e,n)):(i.parent===t?n.parent=i:n.parent=i.parent,ne(e,n),i.left=t.left,i.right=t.right,i.parent=t.parent,i.color=t.color,t===e.root?e.root=i:t===t.parent.left?t.parent.left=i:t.parent.right=i,i.left!==K&&(i.left.parent=i),i.right!==K&&(i.right.parent=i),i.size_left=t.size_left,i.lf_left=t.lf_left,ne(e,i)),t.detach(),n.parent.left===n){var o=Z(n),s=Y(n);if(o!==n.parent.size_left||s!==n.parent.lf_left){var a=o-n.parent.size_left,u=s-n.parent.lf_left;n.parent.size_left=o,n.parent.lf_left=s,te(e,n.parent,a,u)}}if(ne(e,n.parent),r)X();else{for(var c;n!==e.root&&0===n.color;)n===n.parent.left?(1===(c=n.parent.right).color&&(c.color=0,n.parent.color=1,$(e,n.parent),c=n.parent.right),0===c.left.color&&0===c.right.color?(c.color=1,n=n.parent):(0===c.right.color&&(c.left.color=0,c.color=1,J(e,c),c=n.parent.right),c.color=n.parent.color,n.parent.color=0,c.right.color=0,$(e,n.parent),n=e.root)):(1===(c=n.parent.left).color&&(c.color=0,n.parent.color=1,J(e,n.parent),c=n.parent.left),0===c.left.color&&0===c.right.color?(c.color=1,n=n.parent):(0===c.left.color&&(c.right.color=0,c.color=1,$(e,c),c=n.parent.left),c.color=n.parent.color,n.parent.color=0,c.left.color=0,J(e,n.parent),n=e.root));n.color=0,X()}}function ee(e,t){for(ne(e,t);t!==e.root&&1===t.parent.color;){var n;if(t.parent===t.parent.parent.left)1===(n=t.parent.parent.right).color?(t.parent.color=0,n.color=0,t.parent.parent.color=1,t=t.parent.parent):(t===t.parent.right&&$(e,t=t.parent),t.parent.color=0,t.parent.parent.color=1,J(e,t.parent.parent));else 1===(n=t.parent.parent.left).color?(t.parent.color=0,n.color=0,t.parent.parent.color=1,t=t.parent.parent):(t===t.parent.left&&J(e,t=t.parent),t.parent.color=0,t.parent.parent.color=1,$(e,t.parent.parent))}e.root.color=0}function te(e,t,n,i){for(;t!==e.root&&t!==K;)t.parent.left===t&&(t.parent.size_left+=n,t.parent.lf_left+=i),t=t.parent}function ne(e,t){var n=0,i=0;if(t!==e.root){if(0===n){for(;t!==e.root&&t===t.parent.right;)t=t.parent;if(t===e.root)return;n=Z((t=t.parent).left)-t.size_left,i=Y(t.left)-t.lf_left,t.size_left+=n,t.lf_left+=i}for(;t!==e.root&&(0!==n||0!==i);)t.parent.left===t&&(t.parent.size_left+=n,t.parent.lf_left+=i),t=t.parent}}K.parent=K,K.left=K,K.right=K,K.color=0;var ie=n("IErJ");function re(e){var t;return(t=e[e.length-1]<65536?new Uint16Array(e.length):new Uint32Array(e.length)).set(e,0),t}var oe=function(){return function(e,t,n,i,r){this.lineStarts=e,this.cr=t,this.lf=n,this.crlf=i,this.isBasicASCII=r}}();function se(e,t){void 0===t&&(t=!0);for(var n=[0],i=1,r=0,o=e.length;r=0;t--){var n=this._cache[t];if(n.nodeStartOffset<=e&&n.nodeStartOffset+n.node.piece.length>=e)return n}return null},e.prototype.get2=function(e){for(var t=this._cache.length-1;t>=0;t--){var n=this._cache[t];if(n.nodeStartLineNumber&&n.nodeStartLineNumber=e)return n}return null},e.prototype.set=function(e){this._cache.length>=this._limit&&this._cache.shift(),this._cache.push(e)},e.prototype.valdiate=function(e){for(var t=!1,n=this._cache,i=0;i=e)&&(n[i]=null,t=!0)}if(t){for(var o=[],s=0,a=n;s0){e[r].lineStarts||(e[r].lineStarts=se(e[r].buffer));var s=new ae(r+1,{line:0,column:0},{line:e[r].lineStarts.length-1,column:e[r].buffer.length-e[r].lineStarts[e[r].lineStarts.length-1]},e[r].lineStarts.length-1,e[r].buffer.length);this._buffers.push(e[r]),i=this.rbInsertRight(i,s)}this._searchCache=new ce(1),this._lastVisitedLine={lineNumber:0,value:""},this.computeBufferMetadata()},e.prototype.normalizeEOL=function(e){var t=this,n=65535-Math.floor(21845),i=2*n,r="",o=0,s=[];if(this.iterate(this.root,function(a){var u=t.getNodeContent(a),c=u.length;if(o<=n||o+c0){var a=r.replace(/\r\n|\r|\n/g,e);s.push(new ue(a,se(a)))}this.create(s,e,!0)},e.prototype.getEOL=function(){return this._EOL},e.prototype.setEOL=function(e){this._EOL=e,this._EOLLength=this._EOL.length,this.normalizeEOL(e)},e.prototype.getOffsetAt=function(e,t){for(var n=0,i=this.root;i!==K;)if(i.left!==K&&i.lf_left+1>=e)i=i.left;else{if(i.lf_left+i.piece.lineFeedCnt+1>=e)return(n+=i.size_left)+(this.getAccumulatedValue(i,e-i.lf_left-2)+t-1);e-=i.lf_left+i.piece.lineFeedCnt,n+=i.size_left+i.piece.length,i=i.right}return n},e.prototype.getPositionAt=function(e){e=Math.floor(e),e=Math.max(0,e);for(var t=this.root,n=0,i=e;t!==K;)if(0!==t.size_left&&t.size_left>=e)t=t.left;else{if(t.size_left+t.piece.length>=e){var r=this.getIndexOf(t,e-t.size_left);if(n+=t.lf_left+r.index,0===r.index){var o=i-this.getOffsetAt(n+1,1);return new c.a(n+1,o+1)}return new c.a(n+1,r.remainder+1)}if(e-=t.size_left+t.piece.length,n+=t.lf_left+t.piece.lineFeedCnt,t.right===K){o=i-e-this.getOffsetAt(n+1,1);return new c.a(n+1,o+1)}t=t.right}return new c.a(1,1)},e.prototype.getValueInRange=function(e,t){if(e.startLineNumber===e.endLineNumber&&e.startColumn===e.endColumn)return"";var n=this.nodeAt2(e.startLineNumber,e.startColumn),i=this.nodeAt2(e.endLineNumber,e.endColumn),r=this.getValueInRange2(n,i);return t?t===this._EOL&&this._EOLNormalized&&t===this.getEOL()&&this._EOLNormalized?r:r.replace(/\r\n|\r|\n/g,t):r},e.prototype.getValueInRange2=function(e,t){if(e.node===t.node){var n=e.node,i=this._buffers[n.piece.bufferIndex].buffer,r=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);return i.substring(r+e.remainder,r+t.remainder)}var o=e.node,s=this._buffers[o.piece.bufferIndex].buffer,a=this.offsetInBuffer(o.piece.bufferIndex,o.piece.start),u=s.substring(a+e.remainder,a+o.piece.length);for(o=o.next();o!==K;){var c=this._buffers[o.piece.bufferIndex].buffer,l=this.offsetInBuffer(o.piece.bufferIndex,o.piece.start);if(o===t.node){u+=c.substring(l,l+t.remainder);break}u+=c.substr(l,o.piece.length),o=o.next()}return u},e.prototype.getLinesContent=function(){return this.getContentOfSubTree(this.root).split(/\r\n|\r|\n/)},e.prototype.getLength=function(){return this._length},e.prototype.getLineCount=function(){return this._lineCnt},e.prototype.getLineContent=function(e){return this._lastVisitedLine.lineNumber===e?this._lastVisitedLine.value:(this._lastVisitedLine.lineNumber=e,e===this._lineCnt?this._lastVisitedLine.value=this.getLineRawContent(e):this._EOLNormalized?this._lastVisitedLine.value=this.getLineRawContent(e,this._EOLLength):this._lastVisitedLine.value=this.getLineRawContent(e).replace(/(\r\n|\r|\n)$/,""),this._lastVisitedLine.value)},e.prototype.getLineCharCode=function(e,t){var n=this.nodeAt2(e,t+1);if(n.remainder===n.node.piece.length){var i=n.node.next();if(!i)return 0;var r=this._buffers[i.piece.bufferIndex],o=this.offsetInBuffer(i.piece.bufferIndex,i.piece.start);return r.buffer.charCodeAt(o)}r=this._buffers[n.node.piece.bufferIndex];var s=(o=this.offsetInBuffer(n.node.piece.bufferIndex,n.node.piece.start))+n.remainder;return r.buffer.charCodeAt(s)},e.prototype.getLineLength=function(e){if(e===this.getLineCount()){var t=this.getOffsetAt(e,1);return this.getLength()-t}return this.getOffsetAt(e+1,1)-this.getOffsetAt(e,1)-this._EOLLength},e.prototype.findMatchesInNode=function(e,t,n,i,r,o,s,a,u,c,d){var h,f=this._buffers[e.piece.bufferIndex],p=this.offsetInBuffer(e.piece.bufferIndex,e.piece.start),g=this.offsetInBuffer(e.piece.bufferIndex,r),m=this.offsetInBuffer(e.piece.bufferIndex,o);t.reset(g);var v={line:0,column:0};do{if(h=t.next(f.buffer)){if(h.index>=m)return c;this.positionInBuffer(e,h.index-p,v);var _=this.getLineFeedCnt(e.piece.bufferIndex,r,v),b=v.line===r.line?v.column-r.column+i:v.column+1,y=b+h[0].length;if(d[c++]=Object(ie.d)(new l.a(n+_,b,n+_,y),h,a),h.index+h[0].length>=m)return c;if(c>=u)return c}}while(h);return c},e.prototype.findMatchesLineByLine=function(e,t,n,i){var r=[],o=0,s=new ie.b(t.wordSeparators,t.regex),a=this.nodeAt2(e.startLineNumber,e.startColumn);if(null===a)return[];var u=this.nodeAt2(e.endLineNumber,e.endColumn);if(null===u)return[];var c=this.positionInBuffer(a.node,a.remainder),l=this.positionInBuffer(u.node,u.remainder);if(a.node===u.node)return this.findMatchesInNode(a.node,s,e.startLineNumber,e.startColumn,c,l,t,n,i,o,r),r;for(var d=e.startLineNumber,h=a.node;h!==u.node;){var f=this.getLineFeedCnt(h.piece.bufferIndex,c,h.piece.end);if(f>=1){var p=this._buffers[h.piece.bufferIndex].lineStarts,g=this.offsetInBuffer(h.piece.bufferIndex,h.piece.start),m=p[c.line+f],v=d===e.startLineNumber?e.startColumn:1;if((o=this.findMatchesInNode(h,s,d,v,c,this.positionInBuffer(h,m-g),t,n,i,o,r))>=i)return r;d+=f}var _=d===e.startLineNumber?e.startColumn-1:0;if(d===e.endLineNumber){var b=this.getLineContent(d).substring(_,e.endColumn-1);return o=this._findMatchesInLine(t,s,b,e.endLineNumber,_,o,r,n,i),r}if((o=this._findMatchesInLine(t,s,this.getLineContent(d).substr(_),d,_,o,r,n,i))>=i)return r;d++,h=(a=this.nodeAt2(d,1)).node,c=this.positionInBuffer(a.node,a.remainder)}if(d===e.endLineNumber){var y=d===e.startLineNumber?e.startColumn-1:0;b=this.getLineContent(d).substring(y,e.endColumn-1);return o=this._findMatchesInLine(t,s,b,e.endLineNumber,y,o,r,n,i),r}var w=d===e.startLineNumber?e.startColumn:1;return o=this.findMatchesInNode(u.node,s,d,w,c,l,t,n,i,o,r),r},e.prototype._findMatchesInLine=function(e,t,n,i,r,o,s,a,u){var c,d=e.wordSeparators;if(!a&&e.simpleSearch){for(var f=e.simpleSearch,p=f.length,g=n.length,m=-p;-1!==(m=n.indexOf(f,m+p));)if((!d||Object(ie.e)(d,n,g,m,p))&&(s[o++]=new h.b(new l.a(i,m+1+r,i,m+1+p+r),null),o>=u))return o;return o}t.reset(0);do{if((c=t.next(n))&&(s[o++]=Object(ie.d)(new l.a(i,c.index+1+r,i,c.index+1+c[0].length+r),c,a),o>=u))return o}while(c);return o},e.prototype.insert=function(e,t,n){if(void 0===n&&(n=!1),this._EOLNormalized=this._EOLNormalized&&n,this._lastVisitedLine.lineNumber=0,this._lastVisitedLine.value="",this.root!==K){var i=this.nodeAt(e),r=i.node,o=i.remainder,s=i.nodeStartOffset,a=r.piece,u=a.bufferIndex,c=this.positionInBuffer(r,o);if(0===r.piece.bufferIndex&&a.end.line===this._lastChangeBufferPos.line&&a.end.column===this._lastChangeBufferPos.column&&s+a.length===e&&t.length<65535)return this.appendToNode(r,t),void this.computeBufferMetadata();if(s===e)this.insertContentToNodeLeft(t,r),this._searchCache.valdiate(e);else if(s+r.piece.length>e){var l=[],d=new ae(a.bufferIndex,c,a.end,this.getLineFeedCnt(a.bufferIndex,c,a.end),this.offsetInBuffer(u,a.end)-this.offsetInBuffer(u,c));if(this.shouldCheckCRLF()&&this.endWithCR(t))if(10===this.nodeCharCodeAt(r,o)){var h={line:d.start.line+1,column:0};d=new ae(d.bufferIndex,h,d.end,this.getLineFeedCnt(d.bufferIndex,h,d.end),d.length-1),t+="\n"}if(this.shouldCheckCRLF()&&this.startWithLF(t))if(13===this.nodeCharCodeAt(r,o-1)){var f=this.positionInBuffer(r,o-1);this.deleteNodeTail(r,f),t="\r"+t,0===r.piece.length&&l.push(r)}else this.deleteNodeTail(r,c);else this.deleteNodeTail(r,c);var p=this.createNewPieces(t);d.length>0&&this.rbInsertRight(r,d);for(var g=r,m=0;m=0;u--)a=this.rbInsertLeft(a,s[u]);this.validateCRLFWithPrevNode(a),this.deleteNodes(n)},e.prototype.insertContentToNodeRight=function(e,t){this.adjustCarriageReturnFromNext(e,t)&&(e+="\n");for(var n=this.createNewPieces(e),i=this.rbInsertRight(t,n[0]),r=i,o=1;o=l))break;a=c+1}return n?(n.line=c,n.column=s-d,null):{line:c,column:s-d}},e.prototype.getLineFeedCnt=function(e,t,n){if(0===n.column)return n.line-t.line;var i=this._buffers[e].lineStarts;if(n.line===i.length-1)return n.line-t.line;var r=i[n.line+1],o=i[n.line]+n.column;if(r>o+1)return n.line-t.line;var s=o-1;return 13===this._buffers[e].buffer.charCodeAt(s)?n.line-t.line+1:n.line-t.line},e.prototype.offsetInBuffer=function(e,t){return this._buffers[e].lineStarts[t.line]+t.column},e.prototype.deleteNodes=function(e){for(var t=0;t65535){for(var t=[];e.length>65535;){var n=e.charCodeAt(65534),i=void 0;13===n||n>=55296&&n<=56319?(i=e.substring(0,65534),e=e.substring(65534)):(i=e.substring(0,65535),e=e.substring(65535));var r=se(i);t.push(new ae(this._buffers.length,{line:0,column:0},{line:r.length-1,column:i.length-r[r.length-1]},r.length-1,i.length)),this._buffers.push(new ue(i,r))}var o=se(e);return t.push(new ae(this._buffers.length,{line:0,column:0},{line:o.length-1,column:e.length-o[o.length-1]},o.length-1,e.length)),this._buffers.push(new ue(e,o)),t}var s=this._buffers[0].buffer.length,a=se(e,!1),u=this._lastChangeBufferPos;if(this._buffers[0].lineStarts[this._buffers[0].lineStarts.length-1]===s&&0!==s&&this.startWithLF(e)&&this.endWithCR(this._buffers[0].buffer)){this._lastChangeBufferPos={line:this._lastChangeBufferPos.line,column:this._lastChangeBufferPos.column+1},u=this._lastChangeBufferPos;for(var c=0;c=e-1)n=n.left;else{if(n.lf_left+n.piece.lineFeedCnt>e-1){o=this.getAccumulatedValue(n,e-n.lf_left-2),u=this.getAccumulatedValue(n,e-n.lf_left-1),s=this._buffers[n.piece.bufferIndex].buffer,a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);return c+=n.size_left,this._searchCache.set({node:n,nodeStartOffset:c,nodeStartLineNumber:l-(e-1-n.lf_left)}),s.substring(a+o,a+u-t)}if(n.lf_left+n.piece.lineFeedCnt===e-1){o=this.getAccumulatedValue(n,e-n.lf_left-2),s=this._buffers[n.piece.bufferIndex].buffer,a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);i=s.substring(a+o,a+n.piece.length);break}e-=n.lf_left+n.piece.lineFeedCnt,c+=n.size_left+n.piece.length,n=n.right}for(n=n.next();n!==K;){s=this._buffers[n.piece.bufferIndex].buffer;if(n.piece.lineFeedCnt>0){u=this.getAccumulatedValue(n,0),a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);return i+=s.substring(a,a+u-t)}a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);i+=s.substr(a,n.piece.length),n=n.next()}return i},e.prototype.computeBufferMetadata=function(){for(var e=this.root,t=1,n=0;e!==K;)t+=e.lf_left+e.piece.lineFeedCnt,n+=e.size_left+e.piece.length,e=e.right;this._lineCnt=t,this._length=n,this._searchCache.valdiate(this._length)},e.prototype.getIndexOf=function(e,t){var n=e.piece,i=this.positionInBuffer(e,t),r=i.line-n.start.line;if(this.offsetInBuffer(n.bufferIndex,n.end)-this.offsetInBuffer(n.bufferIndex,n.start)===t){var o=this.getLineFeedCnt(e.piece.bufferIndex,n.start,i);if(o!==r)return{index:o,remainder:0}}return{index:r,remainder:i.column}},e.prototype.getAccumulatedValue=function(e,t){if(t<0)return 0;var n=e.piece,i=this._buffers[n.bufferIndex].lineStarts,r=n.start.line+t+1;return r>n.end.line?i[n.end.line]+n.end.column-i[n.start.line]-n.start.column:i[r]-i[n.start.line]-n.start.column},e.prototype.deleteNodeTail=function(e,t){var n=e.piece,i=n.lineFeedCnt,r=this.offsetInBuffer(n.bufferIndex,n.end),o=t,s=this.offsetInBuffer(n.bufferIndex,o),a=this.getLineFeedCnt(n.bufferIndex,n.start,o),u=a-i,c=s-r,l=n.length+c;e.piece=new ae(n.bufferIndex,n.start,o,a,l),te(this,e,c,u)},e.prototype.deleteNodeHead=function(e,t){var n=e.piece,i=n.lineFeedCnt,r=this.offsetInBuffer(n.bufferIndex,n.start),o=t,s=this.getLineFeedCnt(n.bufferIndex,o,n.end),a=s-i,u=r-this.offsetInBuffer(n.bufferIndex,o),c=n.length+u;e.piece=new ae(n.bufferIndex,o,n.end,s,c),te(this,e,u,a)},e.prototype.shrinkNode=function(e,t,n){var i=e.piece,r=i.start,o=i.end,s=i.length,a=i.lineFeedCnt,u=t,c=this.getLineFeedCnt(i.bufferIndex,i.start,u),l=this.offsetInBuffer(i.bufferIndex,t)-this.offsetInBuffer(i.bufferIndex,r);e.piece=new ae(i.bufferIndex,i.start,u,c,l),te(this,e,l-s,c-a);var d=new ae(i.bufferIndex,n,o,this.getLineFeedCnt(i.bufferIndex,n,o),this.offsetInBuffer(i.bufferIndex,o)-this.offsetInBuffer(i.bufferIndex,n)),h=this.rbInsertRight(e,d);this.validateCRLFWithPrevNode(h)},e.prototype.appendToNode=function(e,t){this.adjustCarriageReturnFromNext(t,e)&&(t+="\n");var n=this.shouldCheckCRLF()&&this.startWithLF(t)&&this.endWithCR(e),i=this._buffers[0].buffer.length;this._buffers[0].buffer+=t;for(var r=se(t,!1),o=0;oe)t=t.left;else{if(t.size_left+t.piece.length>=e){i+=t.size_left;var r={node:t,remainder:e-t.size_left,nodeStartOffset:i};return this._searchCache.set(r),r}e-=t.size_left+t.piece.length,i+=t.size_left+t.piece.length,t=t.right}return null},e.prototype.nodeAt2=function(e,t){for(var n=this.root,i=0;n!==K;)if(n.left!==K&&n.lf_left>=e-1)n=n.left;else{if(n.lf_left+n.piece.lineFeedCnt>e-1){var r=this.getAccumulatedValue(n,e-n.lf_left-2),o=this.getAccumulatedValue(n,e-n.lf_left-1);return i+=n.size_left,{node:n,remainder:Math.min(r+t-1,o),nodeStartOffset:i}}if(n.lf_left+n.piece.lineFeedCnt===e-1){if((r=this.getAccumulatedValue(n,e-n.lf_left-2))+t-1<=n.piece.length)return{node:n,remainder:r+t-1,nodeStartOffset:i};t-=n.piece.length-r;break}e-=n.lf_left+n.piece.lineFeedCnt,i+=n.size_left+n.piece.length,n=n.right}for(n=n.next();n!==K;){if(n.piece.lineFeedCnt>0){o=this.getAccumulatedValue(n,0);var s=this.offsetOfNode(n);return{node:n,remainder:Math.min(t-1,o),nodeStartOffset:s}}if(n.piece.length>=t-1)return{node:n,remainder:t-1,nodeStartOffset:this.offsetOfNode(n)};t-=n.piece.length,n=n.next()}return null},e.prototype.nodeCharCodeAt=function(e,t){if(e.piece.lineFeedCnt<1)return-1;var n=this._buffers[e.piece.bufferIndex],i=this.offsetInBuffer(e.piece.bufferIndex,e.piece.start)+t;return n.buffer.charCodeAt(i)},e.prototype.offsetOfNode=function(e){if(!e)return 0;for(var t=e.size_left;e!==this.root;)e.parent.right===e&&(t+=e.parent.size_left+e.parent.piece.length),e=e.parent;return t},e.prototype.shouldCheckCRLF=function(){return!(this._EOLNormalized&&"\n"===this._EOL)},e.prototype.startWithLF=function(e){if("string"==typeof e)return 10===e.charCodeAt(0);if(e===K||0===e.piece.lineFeedCnt)return!1;var t=e.piece,n=this._buffers[t.bufferIndex].lineStarts,i=t.start.line,r=n[i]+t.start.column;return i!==n.length-1&&(!(n[i+1]>r+1)&&10===this._buffers[t.bufferIndex].buffer.charCodeAt(r))},e.prototype.endWithCR=function(e){return"string"==typeof e?13===e.charCodeAt(e.length-1):e!==K&&0!==e.piece.lineFeedCnt&&13===this.nodeCharCodeAt(e,e.piece.length-1)},e.prototype.validateCRLFWithPrevNode=function(e){if(this.shouldCheckCRLF()&&this.startWithLF(e)){var t=e.prev();this.endWithCR(t)&&this.fixCRLF(t,e)}},e.prototype.validateCRLFWithNextNode=function(e){if(this.shouldCheckCRLF()&&this.endWithCR(e)){var t=e.next();this.startWithLF(t)&&this.fixCRLF(e,t)}},e.prototype.fixCRLF=function(e,t){var n,i=[],r=this._buffers[e.piece.bufferIndex].lineStarts;n=0===e.piece.end.column?{line:e.piece.end.line-1,column:r[e.piece.end.line]-r[e.piece.end.line-1]-1}:{line:e.piece.end.line,column:e.piece.end.column-1};var o=e.piece.length-1,s=e.piece.lineFeedCnt-1;e.piece=new ae(e.piece.bufferIndex,e.piece.start,n,s,o),te(this,e,-1,-1),0===e.piece.length&&i.push(e);var a={line:t.piece.start.line+1,column:0},u=t.piece.length-1,c=this.getLineFeedCnt(t.piece.bufferIndex,a,t.piece.end);t.piece=new ae(t.piece.bufferIndex,a,t.piece.end,c,u),te(this,t,-1,-1),0===t.piece.length&&i.push(t);var l=this.createNewPieces("\r\n");this.rbInsertRight(e,l[0]);for(var d=0;d0){v.sort(function(e,t){return t.lineNumber-e.lineNumber}),S=[];u=0;for(var x=v.length;u0&&v[u-1].lineNumber===b)){var L=v[u].oldContent,O=this.getLineContent(b);0!==O.length&&O!==L&&-1===s.q(O)&&S.push(b)}}}return new h.a(w,C,S)},e.prototype._reduceOperations=function(e){return e.length<1e3?e:[this._toSingleEditOperation(e)]},e.prototype._toSingleEditOperation=function(e){for(var t=!1,n=e[0].range,i=e[e.length-1].range,r=new l.a(n.startLineNumber,n.startColumn,i.endLineNumber,i.endColumn),o=n.startLineNumber,s=n.startColumn,a=[],u=0,c=e.length;u0){var h=a.lines.length,f=a.lines[0],p=a.lines[h-1];d=1===h?new l.a(u,c,u,c+f.length):new l.a(u,c,u+h-1,p.length+1)}else d=new l.a(u,c,u,c);n=d.endLineNumber,i=d.endColumn,t.push(d),r=a}return t},e._sortOpsAscending=function(e,t){var n=l.a.compareRangesUsingEnds(e.range,t.range);return 0===n?e.sortIndex-t.sortIndex:n},e._sortOpsDescending=function(e,t){var n=l.a.compareRangesUsingEnds(e.range,t.range);return 0===n?t.sortIndex-e.sortIndex:-n},e}(),he=function(){function e(e,t,n,i,r,o,s,a){this._chunks=e,this._bom=t,this._cr=n,this._lf=i,this._crlf=r,this._containsRTL=o,this._isBasicASCII=s,this._normalizeEOL=a}return e.prototype._getEOL=function(e){var t=this._cr+this._lf+this._crlf,n=this._cr+this._crlf;return 0===t?1===e?"\n":"\r\n":n>t/2?"\r\n":"\n"},e.prototype.create=function(e){var t=this._getEOL(e),n=this._chunks;if(this._normalizeEOL&&("\r\n"===t&&(this._cr>0||this._lf>0)||"\n"===t&&(this._cr>0||this._crlf>0)))for(var i=0,r=n.length;i=55296&&t<=56319?(this._acceptChunk1(e.substr(0,e.length-1),!1),this._hasPreviousChar=!0,this._previousChar=t):(this._acceptChunk1(e,!1),this._hasPreviousChar=!1,this._previousChar=t)}},e.prototype._acceptChunk1=function(e,t){(t||0!==e.length)&&(this._hasPreviousChar?this._acceptChunk2(String.fromCharCode(this._previousChar)+e):this._acceptChunk2(e))},e.prototype._acceptChunk2=function(e){var t=function(e,t){e.length=0,e[0]=0;for(var n=1,i=0,r=0,o=0,s=!0,a=0,u=t.length;a126)&&(s=!1)}var l=new oe(re(e),i,r,o,s);return e.length=0,l}(this._tmpLineStarts,e);this.chunks.push(new ue(e,t.lineStarts)),this.cr+=t.cr,this.lf+=t.lf,this.crlf+=t.crlf,this.isBasicASCII&&(this.isBasicASCII=t.isBasicASCII),this.isBasicASCII||this.containsRTL||(this.containsRTL=s.h(e))},e.prototype.finish=function(e){return void 0===e&&(e=!0),this._finish(),new he(this.chunks,this.BOM,this.cr,this.lf,this.crlf,this.containsRTL,this.isBasicASCII,e)},e.prototype._finish=function(){if(0===this.chunks.length&&this._acceptChunk1("",!0),this._hasPreviousChar){this._hasPreviousChar=!1;var e=this.chunks[this.chunks.length-1];e.buffer+=String.fromCharCode(this._previousChar);var t=se(e.buffer);e.lineStarts=t,13===this._previousChar&&this.cr++}},e}(),pe=function(){return function(){this.changeType=1}}(),ge=function(){return function(e,t){this.changeType=2,this.lineNumber=e,this.detail=t}}(),me=function(){return function(e,t){this.changeType=3,this.fromLineNumber=e,this.toLineNumber=t}}(),ve=function(){return function(e,t,n){this.changeType=4,this.fromLineNumber=e,this.toLineNumber=t,this.detail=n}}(),_e=function(){return function(){this.changeType=5}}(),be=function(){function e(e,t,n,i){this.changes=e,this.versionId=t,this.isUndoing=n,this.isRedoing=i}return e.prototype.containsEvent=function(e){for(var t=0,n=this.changes.length;t>>0}var Ne=new Uint32Array(0).buffer,Ee=function(){function e(){this.tokens=[]}return e.prototype.add=function(e,t){if(this.tokens.length>0){var n=this.tokens[this.tokens.length-1];if(n.startLineNumber+n.tokens.length-1+1===e)return void n.tokens.push(t)}this.tokens.push(new Ie(e,[t]))},e}(),Ie=function(){return function(e,t){this.startLineNumber=e,this.tokens=t}}();function De(e){return e instanceof Uint32Array?e:new Uint32Array(e)}var Me,Te=function(){function e(){this._lineTokens=[],this._len=0}return e.prototype.flush=function(){this._lineTokens=[],this._len=0},e.prototype.getTokens=function(e,t,n){var i=null;if(t1&&(r=Se.x.getLanguageId(i[1])!==e),!r)return Ne}if(!i||0===i.length){var o=new Uint32Array(2);return o[0]=t,o[1]=ke(e),o.buffer}return i[i.length-2]=t,0===i.byteOffset&&i.byteLength===i.buffer.byteLength?i.buffer:i},e.prototype._ensureLine=function(e){for(;e>=this._len;)this._lineTokens[this._len]=null,this._len++},e.prototype._deleteLines=function(e,t){0!==t&&(e+t>this._len&&(t=this._len-e),this._lineTokens.splice(e,t),this._len-=t)},e.prototype._insertLines=function(e,t){if(0!==t){for(var n=[],i=0;i=this._len))if(t.startLineNumber!==t.endLineNumber){this._lineTokens[n]=e._deleteEnding(this._lineTokens[n],t.startColumn-1);var i=t.endLineNumber-1,r=null;i=this._len||(0!==n?(this._lineTokens[r]=e._deleteEnding(this._lineTokens[r],t.column-1),this._lineTokens[r]=e._insert(this._lineTokens[r],t.column-1,i),this._insertLines(t.lineNumber,n)):this._lineTokens[r]=e._insert(this._lineTokens[r],t.column-1,i))}},e._deleteBeginning=function(t,n){return null===t||t===Ne?t:e._delete(t,0,n)},e._deleteEnding=function(t,n){if(null===t||t===Ne)return t;var i=De(t),r=i[i.length-2];return e._delete(t,n,r)},e._delete=function(e,t,n){if(null===e||e===Ne||t===n)return e;var i=De(e),r=i.length>>>1;if(0===t&&i[i.length-2]===n)return Ne;var o,s,a=Ce.a.findIndexInTokensArray(i,t),u=a>0?i[a-1<<1]:0;if(ns&&(i[o++]=f,i[o++]=i[1+(h<<1)],s=f)}if(o===i.length)return e;var p=new Uint32Array(o);return p.set(i.subarray(0,o),0),p.buffer},e._append=function(e,t){if(t===Ne)return e;if(e===Ne)return t;if(null===e)return e;if(null===t)return null;var n=De(e),i=De(t),r=i.length>>>1,o=new Uint32Array(n.length+i.length);o.set(n,0);for(var s=n.length,a=n[n.length-2],u=0;u>>1,o=Ce.a.findIndexInTokensArray(i,t);o>0&&(i[o-1<<1]===t&&o--);for(var s=o;s=this._len;)this._beginState[this._len]=null,this._valid[this._len]=!1,this._len++},e.prototype._deleteLines=function(e,t){0!==t&&(e+t>this._len&&(t=this._len-e),this._beginState.splice(e,t),this._valid.splice(e,t),this._len-=t)},e.prototype._insertLines=function(e,t){if(0!==t){for(var n=[],i=[],r=0;r=0;r--)this._invalidateLine(e.startLineNumber+r-1);this._acceptDeleteRange(e),this._acceptInsertText(new c.a(e.startLineNumber,e.startColumn),t)},e.prototype._acceptDeleteRange=function(e){e.startLineNumber-1>=this._len||this._deleteLines(e.startLineNumber,e.endLineNumber-e.startLineNumber)},e.prototype._acceptInsertText=function(e,t){e.lineNumber-1>=this._len||this._insertLines(e.lineNumber,t)},e}(),Re=function(e){function t(t){var n=e.call(this)||this;return n._textModel=t,n._tokenizationStateStore=new Ae,n._revalidateTokensTimeout=-1,n._tokenizationSupport=null,n._register(Se.y.onDidChange(function(e){var t=n._textModel.getLanguageIdentifier();-1!==e.changedLanguages.indexOf(t.language)&&(n._resetTokenizationState(),n._textModel.clearTokens())})),n._register(n._textModel.onDidChangeRawContentFast(function(e){e.containsEvent(1)&&n._resetTokenizationState()})),n._register(n._textModel.onDidChangeContentFast(function(e){for(var t=0,i=e.changes.length;t20);){if(this._tokenizeOneInvalidLine(t)>=e)break}this._beginBackgroundTokenization(),this._textModel.setTokens(t.tokens)},t.prototype.tokenizeViewport=function(e,t){var n=new Ee;this._tokenizeViewport(n,e,t),this._textModel.setTokens(n.tokens)},t.prototype.reset=function(){this._resetTokenizationState(),this._textModel.clearTokens()},t.prototype.forceTokenization=function(e){var t=new Ee;this._updateTokensUntilLine(t,e),this._textModel.setTokens(t.tokens)},t.prototype.isCheapToTokenize=function(e){if(!this._tokenizationSupport)return!0;var t=this._tokenizationStateStore.invalidLineStartIndex+1;return!(e>t)&&(e0&&s>=1;s--){var a=this._textModel.getLineFirstNonWhitespaceColumn(s);if(0!==a&&a=0;s--){c=(h=Fe(u,this._tokenizationSupport,r[s],c)).endState}for(var l=t;l<=n;l++){var d=this._textModel.getLineContent(l),h=Fe(u,this._tokenizationSupport,d,c);e.add(l,h.tokens),this._tokenizationStateStore.setFakeTokens(l-1),c=h.endState}}},t}(o.a);function Fe(e,t,n,r){var o=null;if(t)try{o=t.tokenize2(n,r.clone(),0)}catch(e){Object(i.e)(e)}return o||(o=Object(xe.e)(e.id,n,r,0)),Ce.a.convertToEndOffset(o.tokens,n.length),o}var je=n("+jct"),We=n("Fllr"),Be=n("Eeyw"),Ve=n("iNUG"),He=n("KIxu"),ze=n("TNPA");n.d(t,"b",function(){return Ye}),n.d(t,"a",function(){return tt});var Ue=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();function Ke(e){var t=new fe;return t.acceptChunk(e),t.finish()}function qe(e,t){return("string"==typeof e?Ke(e):e).create(t)}var Ge=0,Ze=function(){throw new Error("Invalid change accessor")},Ye=function(e){function t(n,i,o,u){void 0===u&&(u=null);var c=e.call(this)||this;c._onWillDispose=c._register(new r.a),c.onWillDispose=c._onWillDispose.event,c._onDidChangeDecorations=c._register(new rt),c.onDidChangeDecorations=c._onDidChangeDecorations.event,c._onDidChangeLanguage=c._register(new r.a),c.onDidChangeLanguage=c._onDidChangeLanguage.event,c._onDidChangeLanguageConfiguration=c._register(new r.a),c.onDidChangeLanguageConfiguration=c._onDidChangeLanguageConfiguration.event,c._onDidChangeTokens=c._register(new r.a),c.onDidChangeTokens=c._onDidChangeTokens.event,c._onDidChangeOptions=c._register(new r.a),c.onDidChangeOptions=c._onDidChangeOptions.event,c._onDidChangeAttached=c._register(new r.a),c.onDidChangeAttached=c._onDidChangeAttached.event,c._eventEmitter=c._register(new ot),Ge++,c.id="$model"+Ge,c.isForSimpleWidget=i.isForSimpleWidget,c._associatedResource=void 0===u||null===u?a.a.parse("inmemory://model/"+Ge):u,c._attachedEditorCount=0,c._buffer=qe(n,i.defaultEOL),c._options=t.resolveOptions(c._buffer,i);var d=c._buffer.getLineCount(),h=c._buffer.getValueLengthInRange(new l.a(1,1,d,c._buffer.getLineLength(d)+1),0);return i.largeFileOptimizations?c._isTooLargeForTokenization=h>t.LARGE_FILE_SIZE_THRESHOLD||d>t.LARGE_FILE_LINE_COUNT_THRESHOLD:c._isTooLargeForTokenization=!1,c._isTooLargeForSyncing=h>t.MODEL_SYNC_LIMIT,c._versionId=1,c._alternativeVersionId=1,c._isDisposed=!1,c._isDisposing=!1,c._languageIdentifier=o||xe.a,c._languageRegistryListener=We.a.onDidChange(function(e){e.languageIdentifier.id===c._languageIdentifier.id&&c._onDidChangeLanguageConfiguration.fire({})}),c._instanceId=s.I(Ge),c._lastDecorationId=0,c._decorations=Object.create(null),c._decorationsTree=new Xe,c._commandManager=new m(c),c._isUndoing=!1,c._isRedoing=!1,c._trimAutoWhitespaceLines=null,c._tokens=new Te,c._tokenization=new Re(c),c}return Ue(t,e),t.createFromString=function(e,n,i,r){return void 0===n&&(n=t.DEFAULT_CREATION_OPTIONS),void 0===i&&(i=null),void 0===r&&(r=null),new t(e,n,i,r)},t.resolveOptions=function(e,t){if(t.detectIndentation){var n=b(e,t.tabSize,t.insertSpaces);return new h.e({tabSize:n.tabSize,indentSize:n.tabSize,insertSpaces:n.insertSpaces,trimAutoWhitespace:t.trimAutoWhitespace,defaultEOL:t.defaultEOL})}return new h.e({tabSize:t.tabSize,indentSize:t.indentSize,insertSpaces:t.insertSpaces,trimAutoWhitespace:t.trimAutoWhitespace,defaultEOL:t.defaultEOL})},t.prototype.onDidChangeRawContentFast=function(e){return this._eventEmitter.fastEvent(function(t){return e(t.rawContentChangedEvent)})},t.prototype.onDidChangeRawContent=function(e){return this._eventEmitter.slowEvent(function(t){return e(t.rawContentChangedEvent)})},t.prototype.onDidChangeContentFast=function(e){return this._eventEmitter.fastEvent(function(t){return e(t.contentChangedEvent)})},t.prototype.onDidChangeContent=function(e){return this._eventEmitter.slowEvent(function(t){return e(t.contentChangedEvent)})},t.prototype.dispose=function(){this._isDisposing=!0,this._onWillDispose.fire(),this._languageRegistryListener.dispose(),this._tokenization.dispose(),this._isDisposed=!0,e.prototype.dispose.call(this),this._isDisposing=!1},t.prototype._assertNotDisposed=function(){if(this._isDisposed)throw new Error("Model is disposed!")},t.prototype._emitContentChangedEvent=function(e,t){this._isDisposing||this._eventEmitter.fire(new ye(e,t))},t.prototype.setValue=function(e){if(this._assertNotDisposed(),null!==e){var t=qe(e,this._options.defaultEOL);this.setValueFromTextBuffer(t)}},t.prototype._createContentChanged2=function(e,t,n,i,r,o,s){return{changes:[{range:e,rangeOffset:t,rangeLength:n,text:i}],eol:this._buffer.getEOL(),versionId:this.getVersionId(),isUndoing:r,isRedoing:o,isFlush:s}},t.prototype.setValueFromTextBuffer=function(e){if(this._assertNotDisposed(),null!==e){var t=this.getFullModelRange(),n=this.getValueLengthInRange(t),i=this.getLineCount(),r=this.getLineMaxColumn(i);this._buffer=e,this._increaseVersionId(),this._tokens.flush(),this._decorations=Object.create(null),this._decorationsTree=new Xe,this._commandManager=new m(this),this._trimAutoWhitespaceLines=null,this._emitContentChangedEvent(new be([new pe],this._versionId,!1,!1),this._createContentChanged2(new l.a(1,1,i,r),0,n,this.getValue(),!1,!1,!0))}},t.prototype.setEOL=function(e){this._assertNotDisposed();var t=1===e?"\r\n":"\n";if(this._buffer.getEOL()!==t){var n=this.getFullModelRange(),i=this.getValueLengthInRange(n),r=this.getLineCount(),o=this.getLineMaxColumn(r);this._onBeforeEOLChange(),this._buffer.setEOL(t),this._increaseVersionId(),this._onAfterEOLChange(),this._emitContentChangedEvent(new be([new _e],this._versionId,!1,!1),this._createContentChanged2(new l.a(1,1,r,o),0,i,this.getValue(),!1,!1,!1))}},t.prototype._onBeforeEOLChange=function(){var e=this.getVersionId(),t=this._decorationsTree.search(0,!1,!1,e);this._ensureNodesHaveRanges(t)},t.prototype._onAfterEOLChange=function(){for(var e=this.getVersionId(),t=this._decorationsTree.collectNodesPostOrder(),n=0,i=t.length;n0},t.prototype.getAttachedEditorCount=function(){return this._attachedEditorCount},t.prototype.isTooLargeForSyncing=function(){return this._isTooLargeForSyncing},t.prototype.isTooLargeForTokenization=function(){return this._isTooLargeForTokenization},t.prototype.isDisposed=function(){return this._isDisposed},t.prototype.isDominatedByLongLines=function(){if(this._assertNotDisposed(),this.isTooLargeForTokenization())return!1;for(var e=0,t=0,n=this._buffer.getLineCount(),i=1;i<=n;i++){var r=this._buffer.getLineLength(i);r>=1e4?t+=r:e+=r}return t>e},Object.defineProperty(t.prototype,"uri",{get:function(){return this._associatedResource},enumerable:!0,configurable:!0}),t.prototype.getOptions=function(){return this._assertNotDisposed(),this._options},t.prototype.getFormattingOptions=function(){return{tabSize:this._options.indentSize,insertSpaces:this._options.insertSpaces}},t.prototype.updateOptions=function(e){this._assertNotDisposed();var t=void 0!==e.tabSize?e.tabSize:this._options.tabSize,n=void 0!==e.indentSize?e.indentSize:this._options.indentSize,i=void 0!==e.insertSpaces?e.insertSpaces:this._options.insertSpaces,r=void 0!==e.trimAutoWhitespace?e.trimAutoWhitespace:this._options.trimAutoWhitespace,o=new h.e({tabSize:t,indentSize:n,insertSpaces:i,defaultEOL:this._options.defaultEOL,trimAutoWhitespace:r});if(!this._options.equals(o)){var s=this._options.createChangeEvent(o);this._options=o,this._onDidChangeOptions.fire(s)}},t.prototype.detectIndentation=function(e,t){this._assertNotDisposed();var n=b(this._buffer,t,e);this.updateOptions({insertSpaces:n.insertSpaces,tabSize:n.tabSize,indentSize:n.tabSize})},t._normalizeIndentationFromWhitespace=function(e,t,n){for(var i=0,r=0;rthis.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineContent(e)},t.prototype.getLineLength=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineLength(e)},t.prototype.getLinesContent=function(){return this._assertNotDisposed(),this._buffer.getLinesContent()},t.prototype.getEOL=function(){return this._assertNotDisposed(),this._buffer.getEOL()},t.prototype.getLineMinColumn=function(e){return this._assertNotDisposed(),1},t.prototype.getLineMaxColumn=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineLength(e)+1},t.prototype.getLineFirstNonWhitespaceColumn=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineFirstNonWhitespaceColumn(e)},t.prototype.getLineLastNonWhitespaceColumn=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineLastNonWhitespaceColumn(e)},t.prototype._validateRangeRelaxedNoAllocations=function(e){var t,n,i=this._buffer.getLineCount(),r=e.startLineNumber,o=e.startColumn;if(r<1)t=1,n=1;else if(r>i)t=i,n=this.getLineMaxColumn(t);else{if(t=0|r,o<=1)n=1;else n=o>=(h=this.getLineMaxColumn(t))?h:0|o}var s,a,u=e.endLineNumber,c=e.endColumn;if(u<1)s=1,a=1;else if(u>i)s=i,a=this.getLineMaxColumn(s);else{var h;if(s=0|u,c<=1)a=1;else a=c>=(h=this.getLineMaxColumn(s))?h:0|c}return r===t&&o===n&&u===s&&c===a&&e instanceof l.a&&!(e instanceof d.a)?e:new l.a(t,n,s,a)},t.prototype._isValidPosition=function(e,t,n){if("number"!=typeof e||"number"!=typeof t)return!1;if(isNaN(e)||isNaN(t))return!1;if(e<1||t<1)return!1;if((0|e)!==e||(0|t)!==t)return!1;if(e>this._buffer.getLineCount())return!1;if(t>this.getLineMaxColumn(e))return!1;if(n&&t>1){var i=this._buffer.getLineCharCode(e,t-2);if(s.w(i))return!1}return!0},t.prototype._validatePosition=function(e,t,n){var i=Math.floor("number"!=typeof e||isNaN(e)?1:e),r=Math.floor("number"!=typeof t||isNaN(t)?1:t),o=this._buffer.getLineCount();if(i<1)return new c.a(1,1);if(i>o)return new c.a(o,this.getLineMaxColumn(o));if(r<=1)return new c.a(i,1);var a=this.getLineMaxColumn(i);if(r>=a)return new c.a(i,a);if(n){var u=this._buffer.getLineCharCode(i,r-2);if(s.w(u))return new c.a(i,r-1)}return new c.a(i,r)},t.prototype.validatePosition=function(e){return this._assertNotDisposed(),e instanceof c.a&&this._isValidPosition(e.lineNumber,e.column,!0)?e:this._validatePosition(e.lineNumber,e.column,!0)},t.prototype._isValidRange=function(e,t){var n=e.startLineNumber,i=e.startColumn,r=e.endLineNumber,o=e.endColumn;if(!this._isValidPosition(n,i,!1))return!1;if(!this._isValidPosition(r,o,!1))return!1;if(t){var a=i>1?this._buffer.getLineCharCode(n,i-2):0,u=o>1&&o<=this._buffer.getLineLength(r)?this._buffer.getLineCharCode(r,o-2):0,c=s.w(a),l=s.w(u);return!c&&!l}return!0},t.prototype.validateRange=function(e){if(this._assertNotDisposed(),e instanceof l.a&&!(e instanceof d.a)&&this._isValidRange(e,!0))return e;var t=this._validatePosition(e.startLineNumber,e.startColumn,!1),n=this._validatePosition(e.endLineNumber,e.endColumn,!1),i=t.lineNumber,r=t.column,o=n.lineNumber,a=n.column,u=r>1?this._buffer.getLineCharCode(i,r-2):0,c=a>1&&a<=this._buffer.getLineLength(o)?this._buffer.getLineCharCode(o,a-2):0,h=s.w(u),f=s.w(c);return h||f?i===o&&r===a?new l.a(i,r-1,o,a-1):h&&f?new l.a(i,r-1,o,a+1):h?new l.a(i,r-1,o,a):new l.a(i,r,o,a+1):new l.a(i,r,o,a)},t.prototype.modifyPosition=function(e,t){this._assertNotDisposed();var n=this.getOffsetAt(e)+t;return this.getPositionAt(Math.min(this._buffer.getLength(),Math.max(0,n)))},t.prototype.getFullModelRange=function(){this._assertNotDisposed();var e=this.getLineCount();return new l.a(1,1,e,this.getLineMaxColumn(e))},t.prototype.findMatchesLineByLine=function(e,t,n,i){return this._buffer.findMatchesLineByLine(e,t,n,i)},t.prototype.findMatches=function(e,t,n,i,r,o,s){var a;if(void 0===s&&(s=999),this._assertNotDisposed(),a=l.a.isIRange(t)?this.validateRange(t):this.getFullModelRange(),!n&&e.indexOf("\n")<0){var u=new ie.a(e,n,i,r).parseSearchRequest();return u?this.findMatchesLineByLine(a,u,o,s):[]}return ie.c.findMatches(this,new ie.a(e,n,i,r),a,o,s)},t.prototype.findNextMatch=function(e,t,n,i,r,o){this._assertNotDisposed();var s=this.validatePosition(t);if(!n&&e.indexOf("\n")<0){var a=new ie.a(e,n,i,r).parseSearchRequest();if(!a)return null;var u=this.getLineCount(),c=new l.a(s.lineNumber,s.column,u,this.getLineMaxColumn(u)),d=this.findMatchesLineByLine(c,a,o,1);return ie.c.findNextMatch(this,new ie.a(e,n,i,r),s,o),d.length>0?d[0]:(c=new l.a(1,1,s.lineNumber,this.getLineMaxColumn(s.lineNumber)),(d=this.findMatchesLineByLine(c,a,o,1)).length>0?d[0]:null)}return ie.c.findNextMatch(this,new ie.a(e,n,i,r),s,o)},t.prototype.findPreviousMatch=function(e,t,n,i,r,o){this._assertNotDisposed();var s=this.validatePosition(t);return ie.c.findPreviousMatch(this,new ie.a(e,n,i,r),s,o)},t.prototype.pushStackElement=function(){this._commandManager.pushStackElement()},t.prototype.pushEOL=function(e){if(("\n"===this.getEOL()?0:1)!==e)try{this._onDidChangeDecorations.beginDeferredEmit(),this._eventEmitter.beginDeferredEmit(),this._commandManager.pushEOL(e)}finally{this._eventEmitter.endDeferredEmit(),this._onDidChangeDecorations.endDeferredEmit()}},t.prototype.pushEditOperations=function(e,t,n){try{return this._onDidChangeDecorations.beginDeferredEmit(),this._eventEmitter.beginDeferredEmit(),this._pushEditOperations(e,t,n)}finally{this._eventEmitter.endDeferredEmit(),this._onDidChangeDecorations.endDeferredEmit()}},t.prototype._pushEditOperations=function(e,t,n){var i=this;if(this._options.trimAutoWhitespace&&this._trimAutoWhitespaceLines){for(var r=t.map(function(e){return{range:i.validateRange(e.range),text:e.text}}),o=!0,s=0,a=e.length;su.endLineNumber,p=u.startLineNumber>_.endLineNumber;if(!f&&!p){c=!0;break}}if(!c){o=!1;break}}if(o)for(s=0,a=this._trimAutoWhitespaceLines.length;s_.endLineNumber)&&!(g===_.startLineNumber&&_.startColumn===m&&_.isEmpty()&&b&&b.length>0&&"\n"===b.charAt(0)||g===_.startLineNumber&&1===_.startColumn&&_.isEmpty()&&b&&b.length>0&&"\n"===b.charAt(b.length-1))){v=!1;break}}v&&t.push({range:new l.a(g,1,g,m),text:null})}this._trimAutoWhitespaceLines=null}return this._commandManager.pushEditOperation(e,t,n)},t.prototype.applyEdits=function(e){try{return this._onDidChangeDecorations.beginDeferredEmit(),this._eventEmitter.beginDeferredEmit(),this._applyEdits(e)}finally{this._eventEmitter.endDeferredEmit(),this._onDidChangeDecorations.endDeferredEmit()}},t.prototype._applyEdits=function(e){for(var t=0,n=e.length;t=0;b--){var y=f+b,w=o-u-_+y;a.push(new ge(y,this.getLineContent(w)))}if(vthis.getLineCount()?[]:this.getLinesDecorations(e,e,t,n)},t.prototype.getLinesDecorations=function(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=!1);var r=this.getLineCount(),o=Math.min(r,Math.max(1,e)),s=Math.min(r,Math.max(1,t)),a=this.getLineMaxColumn(s);return this._getDecorationsInRange(new l.a(o,1,s,a),n,i)},t.prototype.getDecorationsInRange=function(e,t,n){void 0===t&&(t=0),void 0===n&&(n=!1);var i=this.validateRange(e);return this._getDecorationsInRange(i,t,n)},t.prototype.getOverviewRulerDecorations=function(e,t){void 0===e&&(e=0),void 0===t&&(t=!1);var n=this.getVersionId(),i=this._decorationsTree.search(e,t,!0,n);return this._ensureNodesHaveRanges(i)},t.prototype.getAllDecorations=function(e,t){void 0===e&&(e=0),void 0===t&&(t=!1);var n=this.getVersionId(),i=this._decorationsTree.search(e,t,!1,n);return this._ensureNodesHaveRanges(i)},t.prototype._getDecorationsInRange=function(e,t,n){var i=this._buffer.getOffsetAt(e.startLineNumber,e.startColumn),r=this._buffer.getOffsetAt(e.endLineNumber,e.endColumn),o=this.getVersionId(),s=this._decorationsTree.intervalSearch(i,r,t,n,o);return this._ensureNodesHaveRanges(s)},t.prototype._ensureNodesHaveRanges=function(e){for(var t=0,n=e.length;tthis.getLineCount())throw new Error("Illegal value for lineNumber");this._tokens.setTokens(this._languageIdentifier.id,e-1,this._buffer.getLineLength(e),t)},t.prototype.setTokens=function(e){if(0!==e.length){for(var t=[],n=0,i=e.length;nthis.getLineCount())throw new Error("Illegal value for lineNumber");this._tokenization.forceTokenization(e)},t.prototype.isCheapToTokenize=function(e){return this._tokenization.isCheapToTokenize(e)},t.prototype.tokenizeIfCheap=function(e){this.isCheapToTokenize(e)&&this.forceTokenization(e)},t.prototype.getLineTokens=function(e){if(e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._getLineTokens(e)},t.prototype._getLineTokens=function(e){var t=this.getLineContent(e);return this._tokens.getTokens(this._languageIdentifier.id,e-1,t)},t.prototype.getLanguageIdentifier=function(){return this._languageIdentifier},t.prototype.getModeId=function(){return this._languageIdentifier.language},t.prototype.setMode=function(e){if(this._languageIdentifier.id!==e.id){var t={oldLanguage:this._languageIdentifier.language,newLanguage:e.language};this._languageIdentifier=e,this._onDidChangeLanguage.fire(t),this._onDidChangeLanguageConfiguration.fire({})}},t.prototype.getLanguageIdAtPosition=function(e,t){var n=this.validatePosition(new c.a(e,t)),i=this.getLineTokens(n.lineNumber);return i.getLanguageId(i.findTokenIndexAtOffset(n.column-1))},t.prototype.getWordAtPosition=function(e){this._assertNotDisposed();var n=this.validatePosition(e),i=this.getLineContent(n.lineNumber),r=this._getLineTokens(n.lineNumber),o=r.findTokenIndexAtOffset(n.column-1),s=t._findLanguageBoundaries(r,o),a=s[0],u=s[1],c=Object(je.d)(n.column,We.a.getWordDefinition(r.getLanguageId(o)),i.substring(a,u),a);if(c&&c.startColumn<=e.column&&e.column<=c.endColumn)return c;if(o>0&&a===n.column-1){var l=t._findLanguageBoundaries(r,o-1),d=l[0],h=l[1],f=Object(je.d)(n.column,We.a.getWordDefinition(r.getLanguageId(o-1)),i.substring(d,h),d);if(f&&f.startColumn<=e.column&&e.column<=f.endColumn)return f}return null},t._findLanguageBoundaries=function(e,t){for(var n=e.getLanguageId(t),i=0,r=t;r>=0&&e.getLanguageId(r)===n;r--)i=e.getStartOffset(r);for(var o=e.getLineContent().length,s=(r=t,e.getCount());r0&&n.getStartOffset(r)===e.column-1){a=n.getStartOffset(r);r--;var c=We.a.getBracketsSupport(n.getLanguageId(r));if(c&&!Object(Be.b)(n.getStandardTokenType(r))){var l,d,h;s=Math.max(n.getStartOffset(r),e.column-1-c.maxBracketLength);if((l=Ve.a.findPrevBracketInToken(c.reversedRegex,t,i,s,a))&&l.startColumn<=e.column&&e.column<=l.endColumn)if(d=(d=i.substring(l.startColumn-1,l.endColumn-1)).toLowerCase(),h=this._matchFoundBracket(l,c.textIsBracket[d],c.textIsOpenBracket[d]))return h}}return null},t.prototype._matchFoundBracket=function(e,t,n){if(!t)return null;var i;if(n){if(i=this._findMatchingBracketDown(t,e.getEndPosition()))return[e,i]}else if(i=this._findMatchingBracketUp(t,e.getStartPosition()))return[e,i];return null},t.prototype._findMatchingBracketUp=function(e,t){for(var n=e.languageIdentifier.id,i=e.reversedRegex,r=-1,o=t.lineNumber;o>=1;o--){var s=this._getLineTokens(o),a=s.getCount(),u=this._buffer.getLineContent(o),c=a-1,l=-1;for(o===t.lineNumber&&(c=s.findTokenIndexAtOffset(t.column-1),l=t.column-1);c>=0;c--){var d=s.getLanguageId(c),h=s.getStandardTokenType(c),f=s.getStartOffset(c),p=s.getEndOffset(c);if(-1===l&&(l=p),d===n&&!Object(Be.b)(h))for(;;){var g=Ve.a.findPrevBracketInToken(i,o,u,f,l);if(!g)break;var m=u.substring(g.startColumn-1,g.endColumn-1);if((m=m.toLowerCase())===e.open?r++:m===e.close&&r--,0===r)return g;l=g.startColumn-1}l=-1}}return null},t.prototype._findMatchingBracketDown=function(e,t){for(var n=e.languageIdentifier.id,i=e.forwardRegex,r=1,o=t.lineNumber,s=this.getLineCount();o<=s;o++){var a=this._getLineTokens(o),u=a.getCount(),c=this._buffer.getLineContent(o),l=0,d=0;for(o===t.lineNumber&&(l=a.findTokenIndexAtOffset(t.column-1),d=t.column-1);l=1;r--){var o=this._getLineTokens(r),s=o.getCount(),a=this._buffer.getLineContent(r),u=s-1,c=-1;for(r===t.lineNumber&&(u=o.findTokenIndexAtOffset(t.column-1),c=t.column-1);u>=0;u--){var l=o.getLanguageId(u),d=o.getStandardTokenType(u),h=o.getStartOffset(u),f=o.getEndOffset(u);if(-1===c&&(c=f),n!==l&&(n=l,i=We.a.getBracketsSupport(n)),i&&!Object(Be.b)(d)){var p=Ve.a.findPrevBracketInToken(i.reversedRegex,r,a,h,c);if(p)return this._toFoundBracket(i,p)}c=-1}}return null},t.prototype.findNextBracket=function(e){for(var t=this.validatePosition(e),n=-1,i=null,r=t.lineNumber,o=this.getLineCount();r<=o;r++){var s=this._getLineTokens(r),a=s.getCount(),u=this._buffer.getLineContent(r),c=0,l=0;for(r===t.lineNumber&&(c=s.findTokenIndexAtOffset(t.column-1),l=t.column-1);cr)throw new Error("Illegal value for lineNumber");for(var o=We.a.getFoldingRules(this._languageIdentifier.id),s=Boolean(o&&o.offSide),a=-2,u=-1,c=-2,l=-1,d=function(e){if(-1!==a&&(-2===a||a>e-1)){a=-1,u=-1;for(var t=e-2;t>=0;t--){var n=i._computeIndentLevel(t);if(n>=0){a=t,u=n;break}}}if(-2===c){c=-1,l=-1;for(t=e;t=0){c=t,l=o;break}}}},h=-2,f=-1,p=-2,g=-1,m=function(e){if(-2===h){h=-1,f=-1;for(var t=e-2;t>=0;t--){var n=i._computeIndentLevel(t);if(n>=0){h=t,f=n;break}}}if(-1!==p&&(-2===p||p=0){p=t,g=o;break}}}},v=0,_=!0,b=0,y=!0,w=0,C=0;_||y;C++){var S=e-C,x=e+C;if(0!==C&&(S<1||Sr||x>n)&&(y=!1),C>5e4&&(_=!1,y=!1),_){var L=void 0;if((O=this._computeIndentLevel(S-1))>=0?(c=S-1,l=O,L=Math.ceil(O/this._options.indentSize)):(d(S),L=this._getIndentLevelForWhitespaceLine(s,u,l)),0===C){if(v=S,b=x,0===(w=L))return{startLineNumber:v,endLineNumber:b,indent:w};continue}L>=w?v=S:_=!1}if(y){var O,k=void 0;(O=this._computeIndentLevel(x-1))>=0?(h=x-1,f=O,k=Math.ceil(O/this._options.indentSize)):(m(x),k=this._getIndentLevelForWhitespaceLine(s,f,g)),k>=w?b=x:y=!1}}return{startLineNumber:v,endLineNumber:b,indent:w}},t.prototype.getLinesIndentGuides=function(e,t){this._assertNotDisposed();var n=this.getLineCount();if(e<1||e>n)throw new Error("Illegal value for startLineNumber");if(t<1||t>n)throw new Error("Illegal value for endLineNumber");for(var i=We.a.getFoldingRules(this._languageIdentifier.id),r=Boolean(i&&i.offSide),o=new Array(t-e+1),s=-2,a=-1,u=-2,c=-1,l=e;l<=t;l++){var d=l-e,h=this._computeIndentLevel(l-1);if(h>=0)s=l-1,a=h,o[d]=Math.ceil(h/this._options.indentSize);else{if(-2===s){s=-1,a=-1;for(var f=l-2;f>=0;f--){if((p=this._computeIndentLevel(f))>=0){s=f,a=p;break}}}if(-1!==u&&(-2===u||u=0){u=f,c=p;break}}}o[d]=this._getIndentLevelForWhitespaceLine(r,a,c)}}return o},t.prototype._getIndentLevelForWhitespaceLine=function(e,t,n){return-1===t||-1===n?0:t0?this._deferredEvent?this._deferredEvent=this._deferredEvent.merge(e):this._deferredEvent=e:(this._fastEmitter.fire(e),this._slowEmitter.fire(e))},t}(o.a)},"0u1n":function(e,t){},1:function(e,t){},"16On":function(e,t,n){var i=n("LC74");function r(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}t.Reporter=r,r.prototype.isError=function(e){return e instanceof o},r.prototype.save=function(){var e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},r.prototype.restore=function(e){var t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},r.prototype.enterKey=function(e){return this._reporterState.path.push(e)},r.prototype.exitKey=function(e){var t=this._reporterState;t.path=t.path.slice(0,e-1)},r.prototype.leaveKey=function(e,t,n){var i=this._reporterState;this.exitKey(e),null!==i.obj&&(i.obj[t]=n)},r.prototype.path=function(){return this._reporterState.path.join("/")},r.prototype.enterObject=function(){var e=this._reporterState,t=e.obj;return e.obj={},t},r.prototype.leaveObject=function(e){var t=this._reporterState,n=t.obj;return t.obj=e,n},r.prototype.error=function(e){var t,n=this._reporterState,i=e instanceof o;if(t=i?e:new o(n.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!n.options.partial)throw t;return i||n.errors.push(t),t},r.prototype.wrapResult=function(e){var t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},i(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},"19bf":function(e,t,n){"use strict";var i=n("KDHK");t.certificate=n("lQBd");var r=i.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});t.RSAPrivateKey=r;var o=i.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});t.RSAPublicKey=o;var s=i.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())});t.PublicKey=s;var a=i.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),u=i.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(a),this.key("subjectPrivateKey").octstr())});t.PrivateKey=u;var c=i.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});t.EncryptedPrivateKey=c;var l=i.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});t.DSAPrivateKey=l,t.DSAparam=i.define("DSAparam",function(){this.int()});var d=i.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(h),this.key("publicKey").optional().explicit(1).bitstr())});t.ECPrivateKey=d;var h=i.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});t.signature=i.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},"1Ccl":function(e,t){},"1LBi":function(e,t){},"1O6n":function(e,t){},"1Z8u":function(e,t){},"1lLf":function(e,t,n){"use strict";var i=n("08Lv"),r=n("LC74");function o(e,t){return 55296==(64512&e.charCodeAt(t))&&(!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1)))}function s(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function u(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}t.inherits=r,t.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var n=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),r=0;r>6|192,n[i++]=63&s|128):o(e,r)?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++r)),n[i++]=s>>18|240,n[i++]=s>>12&63|128,n[i++]=s>>6&63|128,n[i++]=63&s|128):(n[i++]=s>>12|224,n[i++]=s>>6&63|128,n[i++]=63&s|128)}else for(r=0;r>>0}return s},t.split32=function(e,t){for(var n=new Array(4*e.length),i=0,r=0;i>>24,n[r+1]=o>>>16&255,n[r+2]=o>>>8&255,n[r+3]=255&o):(n[r+3]=o>>>24,n[r+2]=o>>>16&255,n[r+1]=o>>>8&255,n[r]=255&o)}return n},t.rotr32=function(e,t){return e>>>t|e<<32-t},t.rotl32=function(e,t){return e<>>32-t},t.sum32=function(e,t){return e+t>>>0},t.sum32_3=function(e,t,n){return e+t+n>>>0},t.sum32_4=function(e,t,n,i){return e+t+n+i>>>0},t.sum32_5=function(e,t,n,i,r){return e+t+n+i+r>>>0},t.sum64=function(e,t,n,i){var r=e[t],o=i+e[t+1]>>>0,s=(o>>0,e[t+1]=o},t.sum64_hi=function(e,t,n,i){return(t+i>>>0>>0},t.sum64_lo=function(e,t,n,i){return t+i>>>0},t.sum64_4_hi=function(e,t,n,i,r,o,s,a){var u=0,c=t;return u+=(c=c+i>>>0)>>0)>>0)>>0},t.sum64_4_lo=function(e,t,n,i,r,o,s,a){return t+i+o+a>>>0},t.sum64_5_hi=function(e,t,n,i,r,o,s,a,u,c){var l=0,d=t;return l+=(d=d+i>>>0)>>0)>>0)>>0)>>0},t.sum64_5_lo=function(e,t,n,i,r,o,s,a,u,c){return t+i+o+a+c>>>0},t.rotr64_hi=function(e,t,n){return(t<<32-n|e>>>n)>>>0},t.rotr64_lo=function(e,t,n){return(e<<32-n|t>>>n)>>>0},t.shr64_hi=function(e,t,n){return e>>>n},t.shr64_lo=function(e,t,n){return(e<<32-n|t>>>n)>>>0}},"1mBN":function(e,t){},"1sup":function(e,t,n){"use strict";t.b=function(e,t,n){"string"==typeof e&&(e=i.a.file(e));if(n){var h=n.getWorkspaceFolder(e);if(h){var f=n.getWorkspace().folders.length>1,p=void 0;if(p=Object(u.e)(h.uri,e)?"":Object(u.h)(h.uri,e),f){var g=h&&h.name?h.name:Object(u.b)(h.uri);p=p?g+" • "+p:g}return p}}if(e.scheme!==s.b.file&&e.scheme!==s.b.untitled)return e.with({query:null,fragment:null}).toString(!0);if(c(e.fsPath))return Object(r.normalize)(l(e.fsPath));var m=Object(r.normalize)(e.fsPath);!a.g&&t&&(m=function(e,t){if(a.g||!e||!t)return e;var n=d.original===t?d.normalized:void 0;n||(n=""+Object(o.G)(t,r.posix.sep)+r.posix.sep,d={original:t,normalized:n});(a.c?Object(o.J)(e,n):Object(o.K)(e,n))&&(e="~/"+e.substr(n.length));return e}(m,t.userHome));return m},t.a=function(e){if(!e)return;"string"==typeof e&&(e=i.a.file(e));var t=Object(u.b)(e)||(e.scheme===s.b.file?e.fsPath:e.path);if(c(t))return l(t);return t};var i=n("mrx5"),r=n("/uRs"),o=n("aL7J"),s=n("lapT"),a=n("ZfGv"),u=n("ZYUE");function c(e){return!(!a.g||!e||":"!==e[1])}function l(e){return c(e)?e.charAt(0).toUpperCase()+e.slice(1):e}var d=Object.create(null)},"1xIj":function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return o});var i=n("JVO/"),r=Object(i.c)("logService"),o=function(){function e(){}return e.prototype.trace=function(e){for(var t=[],n=1;n":""},l.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},l.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),n=this.z.redSqr();n=n.redIAdd(n);var i=this.curve._mulA(e),r=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=i.redAdd(t),s=o.redSub(n),a=i.redSub(t),u=r.redMul(s),c=o.redMul(a),l=r.redMul(a),d=s.redMul(o);return this.curve.point(u,c,d,l)},l.prototype._projDbl=function(){var e,t,n,i=this.x.redAdd(this.y).redSqr(),r=this.x.redSqr(),o=this.y.redSqr();if(this.curve.twisted){var s=(c=this.curve._mulA(r)).redAdd(o);if(this.zOne)e=i.redSub(r).redSub(o).redMul(s.redSub(this.curve.two)),t=s.redMul(c.redSub(o)),n=s.redSqr().redSub(s).redSub(s);else{var a=this.z.redSqr(),u=s.redSub(a).redISub(a);e=i.redSub(r).redISub(o).redMul(u),t=s.redMul(c.redSub(o)),n=s.redMul(u)}}else{var c=r.redAdd(o);a=this.curve._mulC(this.z).redSqr(),u=c.redSub(a).redSub(a);e=this.curve._mulC(i.redISub(c)).redMul(u),t=this.curve._mulC(c).redMul(r.redISub(o)),n=c.redMul(u)}return this.curve.point(e,t,n)},l.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},l.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),n=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),i=this.t.redMul(this.curve.dd).redMul(e.t),r=this.z.redMul(e.z.redAdd(e.z)),o=n.redSub(t),s=r.redSub(i),a=r.redAdd(i),u=n.redAdd(t),c=o.redMul(s),l=a.redMul(u),d=o.redMul(u),h=s.redMul(a);return this.curve.point(c,l,h,d)},l.prototype._projAdd=function(e){var t,n,i=this.z.redMul(e.z),r=i.redSqr(),o=this.x.redMul(e.x),s=this.y.redMul(e.y),a=this.curve.d.redMul(o).redMul(s),u=r.redSub(a),c=r.redAdd(a),l=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(s),d=i.redMul(u).redMul(l);return this.curve.twisted?(t=i.redMul(c).redMul(s.redSub(this.curve._mulA(o))),n=u.redMul(c)):(t=i.redMul(c).redMul(s.redSub(o)),n=this.curve._mulC(u).redMul(c)),this.curve.point(d,t,n)},l.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},l.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},l.prototype.mulAdd=function(e,t,n){return this.curve._wnafMulAdd(1,[this,t],[e,n],2,!1)},l.prototype.jmulAdd=function(e,t,n){return this.curve._wnafMulAdd(1,[this,t],[e,n],2,!0)},l.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},l.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},l.prototype.getX=function(){return this.normalize(),this.x.fromRed()},l.prototype.getY=function(){return this.normalize(),this.y.fromRed()},l.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},l.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var n=e.clone(),i=this.curve.redN.redMul(this.z);;){if(n.iadd(this.curve.n),n.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(i),0===this.x.cmp(t))return!0}},l.prototype.toP=l.prototype.normalize,l.prototype.mixedAdd=l.prototype.add},"2Ayt":function(e,t,n){"use strict";n.d(t,"a",function(){return u});var i=n("aL7J"),r=n("Ao9X"),o=n("6boo"),s=n("ZSmM"),a=n("vTy2"),u=function(){function e(){}return e.deleteRight=function(e,t,n,i){for(var o=[],u=3!==e,c=0,l=i.length;c1){var m=n.getLineContent(g.lineNumber),v=i.q(m),_=-1===v?m.length+1:v+1;if(g.column<=_){var b=o.a.visibleColumnFromColumn2(t,n,g),y=o.a.prevIndentTabStop(b,t.indentSize),w=o.a.columnFromVisibleColumn2(t,n,g.lineNumber,y);p=new a.a(g.lineNumber,w,g.lineNumber,g.column)}else p=new a.a(g.lineNumber,g.column-1,g.lineNumber,g.column)}else{var C=s.a.left(t,n,g.lineNumber,g.column);p=new a.a(C.lineNumber,C.column,g.lineNumber,g.column)}}p.isEmpty()?c[d]=null:(p.startLineNumber!==p.endLineNumber&&(l=!0),c[d]=new r.a(p,""))}return[l,c]},e.cut=function(e,t,n){for(var i=[],s=0,u=n.length;s1?(d=l.lineNumber-1,h=t.getLineMaxColumn(l.lineNumber-1),f=l.lineNumber,p=t.getLineMaxColumn(l.lineNumber)):(d=l.lineNumber,h=1,f=l.lineNumber,p=t.getLineMaxColumn(l.lineNumber));var g=new a.a(d,h,f,p);g.isEmpty()?i[s]=null:i[s]=new r.a(g,"")}else i[s]=null;else i[s]=new r.a(c,"")}return new o.e(0,i,{shouldPushStackElementBefore:!0,shouldPushStackElementAfter:!0})},e}()},"2JY6":function(e,t,n){(function(t){var n=Math.pow(2,30)-1;function i(e,n){if("string"!=typeof e&&!t.isBuffer(e))throw new TypeError(n+" must be a buffer or string")}e.exports=function(e,t,r,o){if(i(e,"Password"),i(t,"Salt"),"number"!=typeof r)throw new TypeError("Iterations not a number");if(r<0)throw new TypeError("Bad iterations");if("number"!=typeof o)throw new TypeError("Key length not a number");if(o<0||o>n||o!=o)throw new TypeError("Bad key length")}}).call(t,n("EuP9").Buffer)},"2LSJ":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"InsertCursorAbove",function(){return y}),n.d(t,"InsertCursorBelow",function(){return w}),n.d(t,"MultiCursorSessionResult",function(){return L}),n.d(t,"MultiCursorSession",function(){return O}),n.d(t,"MultiCursorSelectionController",function(){return k}),n.d(t,"MultiCursorSelectionControllerAction",function(){return N}),n.d(t,"AddSelectionToNextFindMatchAction",function(){return E}),n.d(t,"AddSelectionToPreviousFindMatchAction",function(){return I}),n.d(t,"MoveSelectionToNextFindMatchAction",function(){return D}),n.d(t,"MoveSelectionToPreviousFindMatchAction",function(){return M}),n.d(t,"SelectHighlightsAction",function(){return T}),n.d(t,"CompatChangeAll",function(){return P}),n.d(t,"SelectionHighlighter",function(){return R});var i,r=n("hK2W"),o=n("odeJ"),s=n("uNfg"),a=n("tqet"),u=n("03Zz"),c=n("HAT9"),l=n("vTy2"),d=n("iHM7"),h=n("/9db"),f=n("D2uo"),p=n("0ly5"),g=n("PCC9"),m=n("T1Qz"),v=n("L5KM"),_=n("eoic"),b=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),y=function(e){function t(){return e.call(this,{id:"editor.action.insertCursorAbove",label:r.a("mutlicursor.insertAbove","Add Cursor Above"),alias:"Add Cursor Above",precondition:void 0,kbOpts:{kbExpr:h.a.editorTextFocus,primary:2576,linux:{primary:1552,secondary:[3088]},weight:100},menubarOpts:{menuId:22,group:"3_multi",title:r.a({key:"miInsertCursorAbove",comment:["&& denotes a mnemonic"]},"&&Add Cursor Above"),order:2}})||this}return b(t,e),t.prototype.run=function(e,t,n){if(t.hasModel()){var i=n&&!0===n.logicalLine,r=t._getCursors(),o=r.context;o.config.readOnly||(o.model.pushStackElement(),r.setStates(n.source,3,c.b.addCursorUp(o,r.getAll(),i)),r.reveal(!0,1,0))}},t}(u.b),w=function(e){function t(){return e.call(this,{id:"editor.action.insertCursorBelow",label:r.a("mutlicursor.insertBelow","Add Cursor Below"),alias:"Add Cursor Below",precondition:void 0,kbOpts:{kbExpr:h.a.editorTextFocus,primary:2578,linux:{primary:1554,secondary:[3090]},weight:100},menubarOpts:{menuId:22,group:"3_multi",title:r.a({key:"miInsertCursorBelow",comment:["&& denotes a mnemonic"]},"A&&dd Cursor Below"),order:3}})||this}return b(t,e),t.prototype.run=function(e,t,n){if(t.hasModel()){var i=n&&!0===n.logicalLine,r=t._getCursors(),o=r.context;o.config.readOnly||(o.model.pushStackElement(),r.setStates(n.source,3,c.b.addCursorDown(o,r.getAll(),i)),r.reveal(!0,2,0))}},t}(u.b),C=function(e){function t(){return e.call(this,{id:"editor.action.insertCursorAtEndOfEachLineSelected",label:r.a("mutlicursor.insertAtEndOfEachLineSelected","Add Cursors to Line Ends"),alias:"Add Cursors to Line Ends",precondition:void 0,kbOpts:{kbExpr:h.a.editorTextFocus,primary:1575,weight:100},menubarOpts:{menuId:22,group:"3_multi",title:r.a({key:"miInsertCursorAtEndOfEachLineSelected",comment:["&& denotes a mnemonic"]},"Add C&&ursors to Line Ends"),order:4}})||this}return b(t,e),t.prototype.getCursorsForSelection=function(e,t,n){if(!e.isEmpty()){for(var i=e.startLineNumber;i1&&n.push(new d.a(e.endLineNumber,e.endColumn,e.endLineNumber,e.endColumn))}},t.prototype.run=function(e,t){var n=this;if(t.hasModel()){var i=t.getModel(),r=[];t.getSelections().forEach(function(e){return n.getCursorsForSelection(e,i,r)}),r.length>0&&t.setSelections(r)}},t}(u.b),S=function(e){function t(){return e.call(this,{id:"editor.action.addCursorsToBottom",label:r.a("mutlicursor.addCursorsToBottom","Add Cursors To Bottom"),alias:"Add Cursors To Bottom",precondition:void 0})||this}return b(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getSelections(),i=t.getModel().getLineCount(),r=[],o=n[0].startLineNumber;o<=i;o++)r.push(new d.a(o,n[0].startColumn,o,n[0].endColumn));r.length>0&&t.setSelections(r)}},t}(u.b),x=function(e){function t(){return e.call(this,{id:"editor.action.addCursorsToTop",label:r.a("mutlicursor.addCursorsToTop","Add Cursors To Top"),alias:"Add Cursors To Top",precondition:void 0})||this}return b(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getSelections(),i=[],r=n[0].startLineNumber;r>=1;r--)i.push(new d.a(r,n[0].startColumn,r,n[0].endColumn));i.length>0&&t.setSelections(i)}},t}(u.b),L=function(){return function(e,t,n){this.selections=e,this.revealRange=t,this.revealScrollType=n}}(),O=function(){function e(e,t,n,i,r,o,s){this._editor=e,this.findController=t,this.isDisconnectedFromFindController=n,this.searchText=i,this.wholeWord=r,this.matchCase=o,this.currentMatch=s}return e.create=function(t,n){if(!t.hasModel())return null;var i=n.getState();if(!t.hasTextFocus()&&i.isRevealed&&i.searchString.length>0)return new e(t,n,!1,i.searchString,i.wholeWord,i.matchCase,null);var r,o,s=!1,a=t.getSelections();1===a.length&&a[0].isEmpty()?(s=!0,r=!0,o=!0):(r=i.wholeWord,o=i.matchCase);var u,c=t.getSelection(),l=null;if(c.isEmpty()){var h=t.getModel().getWordAtPosition(c.getStartPosition());if(!h)return null;u=h.word,l=new d.a(c.startLineNumber,h.startColumn,c.startLineNumber,h.endColumn)}else u=t.getModel().getValueInRange(c).replace(/\r\n/g,"\n");return new e(t,n,s,u,r,o,l)},e.prototype.addSelectionToNextFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getNextMatch();if(!e)return null;var t=this._editor.getSelections();return new L(t.concat(e),e,0)},e.prototype.moveSelectionToNextFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getNextMatch();if(!e)return null;var t=this._editor.getSelections();return new L(t.slice(0,t.length-1).concat(e),e,0)},e.prototype._getNextMatch=function(){if(!this._editor.hasModel())return null;if(this.currentMatch){var e=this.currentMatch;return this.currentMatch=null,e}this.findController.highlightFindOptions();var t=this._editor.getSelections(),n=t[t.length-1],i=this._editor.getModel().findNextMatch(this.searchText,n.getEndPosition(),!1,this.matchCase,this.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1);return i?new d.a(i.range.startLineNumber,i.range.startColumn,i.range.endLineNumber,i.range.endColumn):null},e.prototype.addSelectionToPreviousFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getPreviousMatch();if(!e)return null;var t=this._editor.getSelections();return new L(t.concat(e),e,0)},e.prototype.moveSelectionToPreviousFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getPreviousMatch();if(!e)return null;var t=this._editor.getSelections();return new L(t.slice(0,t.length-1).concat(e),e,0)},e.prototype._getPreviousMatch=function(){if(!this._editor.hasModel())return null;if(this.currentMatch){var e=this.currentMatch;return this.currentMatch=null,e}this.findController.highlightFindOptions();var t=this._editor.getSelections(),n=t[t.length-1],i=this._editor.getModel().findPreviousMatch(this.searchText,n.getStartPosition(),!1,this.matchCase,this.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1);return i?new d.a(i.range.startLineNumber,i.range.startColumn,i.range.endLineNumber,i.range.endColumn):null},e.prototype.selectAll=function(){return this._editor.hasModel()?(this.findController.highlightFindOptions(),this._editor.getModel().findMatches(this.searchText,!0,!1,this.matchCase,this.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1,1073741824)):[]},e}(),k=function(e){function t(t){var n=e.call(this)||this;return n._sessionDispose=n._register(new a.b),n._editor=t,n._ignoreSelectionChange=!1,n._session=null,n}return b(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype.dispose=function(){this._endSession(),e.prototype.dispose.call(this)},t.prototype.getId=function(){return t.ID},t.prototype._beginSessionIfNeeded=function(e){var t=this;if(!this._session){var n=O.create(this._editor,e);if(!n)return;this._session=n;var i={searchString:this._session.searchText};this._session.isDisconnectedFromFindController&&(i.wholeWordOverride=1,i.matchCaseOverride=1,i.isRegexOverride=2),e.getState().change(i,!1),this._sessionDispose.add(this._editor.onDidChangeCursorSelection(function(e){t._ignoreSelectionChange||t._endSession()})),this._sessionDispose.add(this._editor.onDidBlurEditorText(function(){t._endSession()})),this._sessionDispose.add(e.getState().onFindReplaceStateChange(function(e){(e.matchCase||e.wholeWord)&&t._endSession()}))}},t.prototype._endSession=function(){if(this._sessionDispose.clear(),this._session&&this._session.isDisconnectedFromFindController){this._session.findController.getState().change({wholeWordOverride:0,matchCaseOverride:0,isRegexOverride:0},!1)}this._session=null},t.prototype._setSelections=function(e){this._ignoreSelectionChange=!0,this._editor.setSelections(e),this._ignoreSelectionChange=!1},t.prototype._expandEmptyToWord=function(e,t){if(!t.isEmpty())return t;var n=e.getWordAtPosition(t.getStartPosition());return n?new d.a(t.startLineNumber,n.startColumn,t.startLineNumber,n.endColumn):t},t.prototype._applySessionResult=function(e){e&&(this._setSelections(e.selections),e.revealRange&&this._editor.revealRangeInCenterIfOutsideViewport(e.revealRange,e.revealScrollType))},t.prototype.getSession=function(e){return this._session},t.prototype.addSelectionToNextFindMatch=function(e){if(this._editor.hasModel()){if(!this._session){var t=this._editor.getSelections();if(t.length>1){var n=e.getState().matchCase;if(!F(this._editor.getModel(),t,n)){for(var i=this._editor.getModel(),r=[],o=0,s=t.length;o0&&n.isRegex)t=this._editor.getModel().findMatches(n.searchString,!0,n.isRegex,n.matchCase,n.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1,1073741824);else{if(this._beginSessionIfNeeded(e),!this._session)return;t=this._session.selectAll()}if(t.length>0){for(var i=this._editor.getSelection(),r=0,o=t.length;r1){var a=r.getState().matchCase;if(!F(t.getModel(),s,a))return null}o=O.create(t,r)}if(!o)return null;if(o.currentMatch)return null;if(/^[ \t]+$/.test(o.searchText))return null;if(o.searchText.length>200)return null;var u=r.getState(),c=u.matchCase;if(u.isRevealed){var l=u.searchString;c||(l=l.toLowerCase());var d=o.searchText;if(c||(d=d.toLowerCase()),l===d&&o.matchCase===u.matchCase&&o.wholeWord===u.wholeWord&&!u.isRegex)return null}return new A(o.searchText,o.matchCase,o.wholeWord?t.getConfiguration().wordSeparators:null)},t.prototype._setState=function(e){if(A.softEquals(this.state,e))this.state=e;else if(this.state=e,this.state){if(this.editor.hasModel()){var n=this.editor.getModel();if(!n.isTooLargeForTokenization()){var i=g.i.has(n),r=n.findMatches(this.state.searchText,!0,!1,this.state.matchCase,this.state.wordSeparators,!1).map(function(e){return e.range});r.sort(l.a.compareRangesUsingStarts);var o=this.editor.getSelections();o.sort(l.a.compareRangesUsingStarts);for(var s=[],a=0,u=0,c=r.length,d=o.length;a=d)s.push(h),a++;else{var f=l.a.compareRangesUsingStarts(h,o[u]);f<0?(!o[u].isEmpty()&&l.a.areIntersecting(h,o[u])||s.push(h),a++):f>0?u++:(a++,u++)}}var p=s.map(function(e){return{range:e,options:i?t._SELECTION_HIGHLIGHT:t._SELECTION_HIGHLIGHT_OVERVIEW}});this.decorations=this.editor.deltaDecorations(this.decorations,p)}}}else this.decorations=this.editor.deltaDecorations(this.decorations,[])},t.prototype.dispose=function(){this._setState(null),e.prototype.dispose.call(this)},t.ID="editor.contrib.selectionHighlighter",t._SELECTION_HIGHLIGHT_OVERVIEW=p.a.register({stickiness:1,className:"selectionHighlight",overviewRuler:{color:Object(_.g)(v._32),position:f.d.Center}}),t._SELECTION_HIGHLIGHT=p.a.register({stickiness:1,className:"selectionHighlight"}),t}(a.a);function F(e,t,n){for(var i=j(e,t[0],!n),r=1,o=t.length;r=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},w=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},C=Object(v._36)("editor.wordHighlightBackground",{dark:"#575757B8",light:"#57575740",hc:null},r.a("wordHighlight","Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations."),!0),S=Object(v._36)("editor.wordHighlightStrongBackground",{dark:"#004972B8",light:"#0e639c40",hc:null},r.a("wordHighlightStrong","Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations."),!0),x=Object(v._36)("editor.wordHighlightBorder",{light:null,dark:null,hc:v.b},r.a("wordHighlightBorder","Border color of a symbol during read-access, like reading a variable.")),L=Object(v._36)("editor.wordHighlightStrongBorder",{light:null,dark:null,hc:v.b},r.a("wordHighlightStrongBorder","Border color of a symbol during write-access, like writing to a variable.")),O=Object(v._36)("editorOverviewRuler.wordHighlightForeground",{dark:"#A0A0A0CC",light:"#A0A0A0CC",hc:"#A0A0A0CC"},r.a("overviewRulerWordHighlightForeground","Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations."),!0),k=Object(v._36)("editorOverviewRuler.wordHighlightStrongForeground",{dark:"#C0A0C0CC",light:"#C0A0C0CC",hc:"#C0A0C0CC"},r.a("overviewRulerWordHighlightStrongForeground","Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations."),!0),N=new m.d("hasWordHighlights",!1);function E(e,t,n){var i=g.i.ordered(e);return Object(s.h)(i.map(function(i){return function(){return Promise.resolve(i.provideDocumentHighlights(e,t,n)).then(void 0,u.f)}}),o.n)}var I=function(){function e(e,t,n){var i=this;this._wordRange=this._getCurrentWordRange(e,t),this.result=Object(s.f)(function(r){return i._compute(e,t,n,r)})}return e.prototype._getCurrentWordRange=function(e,t){var n=e.getWordAtPosition(t.getPosition());return n?new d.a(t.startLineNumber,n.startColumn,t.startLineNumber,n.endColumn):null},e.prototype.isValid=function(e,t,n){for(var i=t.startLineNumber,r=t.startColumn,o=t.endColumn,s=this._getCurrentWordRange(e,t),a=Boolean(this._wordRange&&this._wordRange.equalsRange(s)),u=0,c=n.length;!a&&u=o&&(a=!0)}return a},e.prototype.cancel=function(){this.result.cancel()},e}(),D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return b(t,e),t.prototype._compute=function(e,t,n,i){return E(e,t.getPosition(),i).then(function(e){return e||[]})},t}(I),M=function(e){function t(t,n,i){var r=e.call(this,t,n,i)||this;return r._selectionIsEmpty=n.isEmpty(),r}return b(t,e),t.prototype._compute=function(e,t,n,i){return Object(s.l)(250,i).then(function(){if(!t.isEmpty())return[];var i=e.getWordAtPosition(t.getPosition());return i?e.findMatches(i.word,!0,!1,!0,n,!1).map(function(e){return{range:e.range,kind:g.h.Text}}):[]})},t.prototype.isValid=function(t,n,i){var r=n.isEmpty();return this._selectionIsEmpty===r&&e.prototype.isValid.call(this,t,n,i)},t}(I);Object(l.e)("_executeDocumentHighlights",function(e,t){return E(e,t,a.a.None)});var T=function(){function e(e,t){var n=this;this.toUnhook=new c.b,this.workerRequestTokenId=0,this.workerRequestCompleted=!1,this.workerRequestValue=[],this.lastCursorPositionChangeTime=0,this.renderDecorationsTimer=-1,this.editor=e,this._hasWordHighlights=N.bindTo(t),this._ignorePositionChangeEvent=!1,this.occurrencesHighlight=this.editor.getConfiguration().contribInfo.occurrencesHighlight,this.model=this.editor.getModel(),this.toUnhook.add(e.onDidChangeCursorPosition(function(e){n._ignorePositionChangeEvent||n.occurrencesHighlight&&n._onPositionChanged(e)})),this.toUnhook.add(e.onDidChangeModelContent(function(e){n._stopAll()})),this.toUnhook.add(e.onDidChangeConfiguration(function(e){var t=n.editor.getConfiguration().contribInfo.occurrencesHighlight;n.occurrencesHighlight!==t&&(n.occurrencesHighlight=t,n._stopAll())})),this._decorationIds=[],this.workerRequestTokenId=0,this.workerRequest=null,this.workerRequestCompleted=!1,this.lastCursorPositionChangeTime=0,this.renderDecorationsTimer=-1}return e.prototype.hasDecorations=function(){return this._decorationIds.length>0},e.prototype.restore=function(){this.occurrencesHighlight&&this._run()},e.prototype._getSortedHighlights=function(){var e=this;return o.d(this._decorationIds.map(function(t){return e.model.getDecorationRange(t)}).sort(d.a.compareRangesUsingStarts))},e.prototype.moveNext=function(){var e=this,t=this._getSortedHighlights(),n=t[(o.j(t,function(t){return t.containsPosition(e.editor.getPosition())})+1)%t.length];try{this._ignorePositionChangeEvent=!0,this.editor.setPosition(n.getStartPosition()),this.editor.revealRangeInCenterIfOutsideViewport(n)}finally{this._ignorePositionChangeEvent=!1}},e.prototype.moveBack=function(){var e=this,t=this._getSortedHighlights(),n=t[(o.j(t,function(t){return t.containsPosition(e.editor.getPosition())})-1+t.length)%t.length];try{this._ignorePositionChangeEvent=!0,this.editor.setPosition(n.getStartPosition()),this.editor.revealRangeInCenterIfOutsideViewport(n)}finally{this._ignorePositionChangeEvent=!1}},e.prototype._removeDecorations=function(){this._decorationIds.length>0&&(this._decorationIds=this.editor.deltaDecorations(this._decorationIds,[]),this._hasWordHighlights.set(!1))},e.prototype._stopAll=function(){this._removeDecorations(),-1!==this.renderDecorationsTimer&&(clearTimeout(this.renderDecorationsTimer),this.renderDecorationsTimer=-1),null!==this.workerRequest&&(this.workerRequest.cancel(),this.workerRequest=null),this.workerRequestCompleted||(this.workerRequestTokenId++,this.workerRequestCompleted=!0)},e.prototype._onPositionChanged=function(e){this.occurrencesHighlight&&3===e.reason?this._run():this._stopAll()},e.prototype._run=function(){var e=this,t=this.editor.getSelection();if(t.startLineNumber===t.endLineNumber){var n=t.startLineNumber,i=t.startColumn,r=t.endColumn,o=this.model.getWordAtPosition({lineNumber:n,column:i});if(!o||o.startColumn>i||o.endColumn=n?(this.renderDecorationsTimer=-1,this.renderDecorations()):this.renderDecorationsTimer=setTimeout(function(){e.renderDecorations()},n-t)},e.prototype.renderDecorations=function(){this.renderDecorationsTimer=-1;for(var t=[],n=0,i=this.workerRequestValue.length;n=6?"utf-8":"binary";e.exports=n}).call(t,n("W2nU"))},"3Clc":function(e,t){},"3PYz":function(e,t,n){var i=t;i.utils=n("1lLf"),i.common=n("YSDb"),i.sha=n("NCTB"),i.ripemd=n("CKAI"),i.hmac=n("3kRU"),i.sha1=i.sha.sha1,i.sha256=i.sha.sha256,i.sha224=i.sha.sha224,i.sha384=i.sha.sha384,i.sha512=i.sha.sha512,i.ripemd160=i.ripemd.ripemd160},"3UJ8":function(e,t,n){"use strict";n.d(t,"a",function(){return i});var i=function(){function e(){for(var e=[],t=0;te;)n.ishrn(1);if(n.isEven()&&n.iadd(a),n.testn(1)||n.iadd(u),t.cmp(u)){if(!t.cmp(c))for(;n.mod(l).cmp(d);)n.iadd(f)}else for(;n.mod(o).cmp(h);)n.iadd(f);if(m(p=n.shrn(1))&&m(n)&&v(p)&&v(n)&&s.test(p)&&s.test(n))return n}}},"3j2o":function(e,t){},"3kRU":function(e,t,n){"use strict";var i=n("1lLf"),r=n("08Lv");function o(e,t,n){if(!(this instanceof o))return new o(e,t,n);this.Hash=e,this.blockSize=e.blockSize/8,this.outSize=e.outSize/8,this.inner=null,this.outer=null,this._init(i.toArray(t,n))}e.exports=o,o.prototype._init=function(e){e.length>this.blockSize&&(e=(new this.Hash).update(e).digest()),r(e.length<=this.blockSize);for(var t=e.length;t>>3},t.g1_256=function(e){return i(e,17)^i(e,19)^e>>>10}},"3uSZ":function(e,t,n){"use strict";n.d(t,"a",function(){return r}),t.b=function e(t){return o(t)?!t.value:!Array.isArray(t)||t.every(e)},t.c=function(e,t){return!e&&!t||!(!e||!t)&&(Array.isArray(e)&&Array.isArray(t)?Object(i.g)(e,t,s):!(!o(e)||!o(t))&&s(e,t))},t.e=function(e){if(!e)return e;return e.replace(/\\([\\`*_{}[\]()#+\-.!])/g,"$1")},t.d=function(e){var t=[],n=e.split("|").map(function(e){return e.trim()});e=n[0];var i=n[1];if(i){var r=/height=(\d+)/.exec(i),o=/width=(\d+)/.exec(i),s=r?r[1]:"",a=o?o[1]:"",u=isFinite(parseInt(a)),c=isFinite(parseInt(s));u&&t.push('width="'+a+'"'),c&&t.push('height="'+s+'"')}return{href:e,dimensions:t}};var i=n("X6iQ"),r=function(){function e(e){void 0===e&&(e=""),this.value=e}return e.prototype.appendText=function(e){return this.value+=e.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&"),this},e.prototype.appendMarkdown=function(e){return this.value+=e,this},e.prototype.appendCodeblock=function(e,t){return this.value+="\n```",this.value+=e,this.value+="\n",this.value+=t,this.value+="\n```\n",this},e}();function o(e){return e instanceof r||!(!e||"object"!=typeof e)&&("string"==typeof e.value&&("boolean"==typeof e.isTrusted||void 0===e.isTrusted))}function s(e,t){return e===t||!(!e||!t)&&(e.value===t.value&&e.isTrusted===t.isTrusted)}},4:function(e,t){},"4/4u":function(e,t,n){e.exports=n("cSWu").Transform},"44YW":function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("clipboardService")},"4JIo":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("3j2o"),o=(n.n(r),n("hK2W")),s=n("lAcG"),a=n("ZfGv"),u=n("4QaN"),c=n("03Zz"),l=n("vORD"),d=n("/9db"),h=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),f="9_cutcopypaste",p=a.e||document.queryCommandSupported("cut"),g=a.e||document.queryCommandSupported("copy"),m=g&&!s.g,v=a.e||!s.e&&document.queryCommandSupported("paste"),_=function(e){function t(t,n){var i=e.call(this,n)||this;return i.browserCommand=t,i}return h(t,e),t.prototype.runCommand=function(e,t){var n=e.get(l.a).getFocusedCodeEditor();n&&n.hasTextFocus()?n.trigger("keyboard",this.id,t):document.execCommand(this.browserCommand)},t.prototype.run=function(e,t){t.focus(),document.execCommand(this.browserCommand)},t}(c.b),b=function(e){function t(){var t={kbExpr:d.a.textInputFocus,primary:2102,win:{primary:2102,secondary:[1044]},weight:100};return a.e||(t=void 0),e.call(this,"cut",{id:"editor.action.clipboardCutAction",label:o.a("actions.clipboard.cutLabel","Cut"),alias:"Cut",precondition:d.a.writable,kbOpts:t,menuOpts:{group:f,order:1},menubarOpts:{menuId:14,group:"2_ccp",title:o.a({key:"miCut",comment:["&& denotes a mnemonic"]},"Cu&&t"),order:1}})||this}return h(t,e),t.prototype.run=function(t,n){n.hasModel()&&(!n.getConfiguration().emptySelectionClipboard&&n.getSelection().isEmpty()||e.prototype.run.call(this,t,n))},t}(_),y=function(e){function t(){var t={kbExpr:d.a.textInputFocus,primary:2081,win:{primary:2081,secondary:[2067]},weight:100};return a.e||(t=void 0),e.call(this,"copy",{id:"editor.action.clipboardCopyAction",label:o.a("actions.clipboard.copyLabel","Copy"),alias:"Copy",precondition:void 0,kbOpts:t,menuOpts:{group:f,order:2},menubarOpts:{menuId:14,group:"2_ccp",title:o.a({key:"miCopy",comment:["&& denotes a mnemonic"]},"&&Copy"),order:2}})||this}return h(t,e),t.prototype.run=function(t,n){n.hasModel()&&(!n.getConfiguration().emptySelectionClipboard&&n.getSelection().isEmpty()||e.prototype.run.call(this,t,n))},t}(_),w=function(e){function t(){var t={kbExpr:d.a.textInputFocus,primary:2100,win:{primary:2100,secondary:[1043]},weight:100};return a.e||(t=void 0),e.call(this,"paste",{id:"editor.action.clipboardPasteAction",label:o.a("actions.clipboard.pasteLabel","Paste"),alias:"Paste",precondition:d.a.writable,kbOpts:t,menuOpts:{group:f,order:3},menubarOpts:{menuId:14,group:"2_ccp",title:o.a({key:"miPaste",comment:["&& denotes a mnemonic"]},"&&Paste"),order:3}})||this}return h(t,e),t}(_),C=function(e){function t(){return e.call(this,"copy",{id:"editor.action.clipboardCopyWithSyntaxHighlightingAction",label:o.a("actions.clipboard.copyWithSyntaxHighlightingLabel","Copy With Syntax Highlighting"),alias:"Copy With Syntax Highlighting",precondition:void 0,kbOpts:{kbExpr:d.a.textInputFocus,primary:0,weight:100}})||this}return h(t,e),t.prototype.run=function(t,n){n.hasModel()&&(!n.getConfiguration().emptySelectionClipboard&&n.getSelection().isEmpty()||(u.a.forceCopyWithSyntaxHighlighting=!0,e.prototype.run.call(this,t,n),u.a.forceCopyWithSyntaxHighlighting=!1))},t}(_);p&&Object(c.f)(b),g&&Object(c.f)(y),v&&Object(c.f)(w),m&&Object(c.f)(C)},"4QaN":function(e,t,n){"use strict";n.d(t,"a",function(){return p}),n.d(t,"b",function(){return g});var i,r=n("lAcG"),o=n("7/Cv"),s=n("odeJ"),a=n("Kp7x"),u=n("tqet"),c=n("ZfGv"),l=n("aL7J"),d=n("ZWAj"),h=n("iHM7"),f=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),p={forceCopyWithSyntaxHighlighting:!1},g=function(e){function t(t,n){var i=e.call(this)||this;i._onFocus=i._register(new a.a),i.onFocus=i._onFocus.event,i._onBlur=i._register(new a.a),i.onBlur=i._onBlur.event,i._onKeyDown=i._register(new a.a),i.onKeyDown=i._onKeyDown.event,i._onKeyUp=i._register(new a.a),i.onKeyUp=i._onKeyUp.event,i._onCut=i._register(new a.a),i.onCut=i._onCut.event,i._onPaste=i._register(new a.a),i.onPaste=i._onPaste.event,i._onType=i._register(new a.a),i.onType=i._onType.event,i._onCompositionStart=i._register(new a.a),i.onCompositionStart=i._onCompositionStart.event,i._onCompositionUpdate=i._register(new a.a),i.onCompositionUpdate=i._onCompositionUpdate.event,i._onCompositionEnd=i._register(new a.a),i.onCompositionEnd=i._onCompositionEnd.event,i._onSelectionChangeRequest=i._register(new a.a),i.onSelectionChangeRequest=i._onSelectionChangeRequest.event,i._host=t,i._textArea=i._register(new v(n)),i._lastTextAreaEvent=0,i._asyncTriggerCut=i._register(new s.d(function(){return i._onCut.fire()},0)),i._textAreaState=d.b.EMPTY,i._selectionChangeListener=null,i.writeScreenReaderContent("ctor"),i._hasFocus=!1,i._isDoingComposition=!1,i._nextCommand=0,i._register(o.k(n.domNode,"keydown",function(e){!i._isDoingComposition||109!==e.keyCode&&1!==e.keyCode||e.stopPropagation(),e.equals(9)&&e.preventDefault(),i._onKeyDown.fire(e)})),i._register(o.k(n.domNode,"keyup",function(e){i._onKeyUp.fire(e)})),i._register(o.h(n.domNode,"compositionstart",function(e){i._lastTextAreaEvent=1,i._isDoingComposition||(i._isDoingComposition=!0,r.g||i._setAndWriteTextAreaState("compositionstart",d.b.EMPTY),i._onCompositionStart.fire())}));var u=function(e,t){var n=i._textAreaState,r=d.b.readFromTextArea(i._textArea);return[r,d.b.deduceInput(n,r,e,t)]},h=function(e){var t=i._textAreaState,n=d.b.selectedText(e);return[n,{text:n.value,replaceCharCnt:t.selectionEnd-t.selectionStart}]},f=function(e){return!(!r.g||"ja"!==e)||!(!r.j||0!==e.indexOf("zh-Han"))};return i._register(o.h(n.domNode,"compositionupdate",function(e){if(i._lastTextAreaEvent=2,f(e.locale)){var t=u(!1,!1),n=t[0],r=t[1];return i._textAreaState=n,i._onType.fire(r),void i._onCompositionUpdate.fire(e)}var o=h(e.data),s=o[0],a=o[1];i._textAreaState=s,i._onType.fire(a),i._onCompositionUpdate.fire(e)})),i._register(o.h(n.domNode,"compositionend",function(e){if(i._lastTextAreaEvent=3,f(e.locale)){var t=u(!1,!1),n=t[0],o=t[1];i._textAreaState=n,i._onType.fire(o)}else{var s=h(e.data);n=s[0],o=s[1];i._textAreaState=n,i._onType.fire(o)}(r.g||r.e)&&(i._textAreaState=d.b.readFromTextArea(i._textArea)),i._isDoingComposition&&(i._isDoingComposition=!1,i._onCompositionEnd.fire())})),i._register(o.h(n.domNode,"input",function(){var e=8===i._lastTextAreaEvent;if(i._lastTextAreaEvent=4,i._textArea.setIgnoreSelectionChangeTime("received input event"),!i._isDoingComposition){var t=u(c.d,e&&c.d),n=t[0],r=t[1];0===r.replaceCharCnt&&1===r.text.length&&l.w(r.text.charCodeAt(0))||(i._textAreaState=n,0===i._nextCommand?""!==r.text&&i._onType.fire(r):(""!==r.text&&i._onPaste.fire({text:r.text}),i._nextCommand=0))}})),i._register(o.h(n.domNode,"cut",function(e){i._lastTextAreaEvent=5,i._textArea.setIgnoreSelectionChangeTime("received cut event"),i._ensureClipboardGetsEditorSelection(e),i._asyncTriggerCut.schedule()})),i._register(o.h(n.domNode,"copy",function(e){i._lastTextAreaEvent=6,i._ensureClipboardGetsEditorSelection(e)})),i._register(o.h(n.domNode,"paste",function(e){if(i._lastTextAreaEvent=7,i._textArea.setIgnoreSelectionChangeTime("received paste event"),m.canUseTextData(e)){var t=m.getTextData(e);""!==t&&i._onPaste.fire({text:t})}else i._textArea.getSelectionStart()!==i._textArea.getSelectionEnd()&&i._setAndWriteTextAreaState("paste",d.b.EMPTY),i._nextCommand=1})),i._register(o.h(n.domNode,"focus",function(){i._lastTextAreaEvent=8,i._setHasFocus(!0)})),i._register(o.h(n.domNode,"blur",function(){i._lastTextAreaEvent=9,i._setHasFocus(!1)})),i}return f(t,e),t.prototype._installSelectionChangeListener=function(){var e=this,t=0;return o.h(document,"selectionchange",function(n){if(e._hasFocus&&!e._isDoingComposition&&r.e&&c.g){var i=Date.now(),o=i-t;if(t=i,!(o<5)){var s=i-e._textArea.getIgnoreSelectionChangeTime();if(e._textArea.resetSelectionChangeTime(),!(s<100)&&e._textAreaState.selectionStartPosition&&e._textAreaState.selectionEndPosition){var a=e._textArea.getValue();if(e._textAreaState.value===a){var u=e._textArea.getSelectionStart(),l=e._textArea.getSelectionEnd();if(e._textAreaState.selectionStart!==u||e._textAreaState.selectionEnd!==l){var d=e._textAreaState.deduceEditorPosition(u),f=e._host.deduceModelPosition(d[0],d[1],d[2]),p=e._textAreaState.deduceEditorPosition(l),g=e._host.deduceModelPosition(p[0],p[1],p[2]),m=new h.a(f.lineNumber,f.column,g.lineNumber,g.column);e._onSelectionChangeRequest.fire(m)}}}}}})},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._selectionChangeListener&&(this._selectionChangeListener.dispose(),this._selectionChangeListener=null)},t.prototype.focusTextArea=function(){this._setHasFocus(!0)},t.prototype.isFocused=function(){return this._hasFocus},t.prototype._setHasFocus=function(e){this._hasFocus!==e&&(this._hasFocus=e,this._selectionChangeListener&&(this._selectionChangeListener.dispose(),this._selectionChangeListener=null),this._hasFocus&&(this._selectionChangeListener=this._installSelectionChangeListener()),this._hasFocus&&(r.f?this._setAndWriteTextAreaState("focusgain",d.b.EMPTY):this.writeScreenReaderContent("focusgain")),this._hasFocus?this._onFocus.fire():this._onBlur.fire())},t.prototype._setAndWriteTextAreaState=function(e,t){this._hasFocus||(t=t.collapseSelection()),t.writeToTextArea(e,this._textArea,this._hasFocus),this._textAreaState=t},t.prototype.writeScreenReaderContent=function(e){this._isDoingComposition||this._setAndWriteTextAreaState(e,this._host.getScreenReaderContent(this._textAreaState))},t.prototype._ensureClipboardGetsEditorSelection=function(e){var t=this._host.getPlainTextToCopy();if(m.canUseTextData(e)){var n=null;r.d()&&(t.length<65536||p.forceCopyWithSyntaxHighlighting)&&(n=this._host.getHTMLToCopy()),m.setTextData(e,t,n)}else this._setAndWriteTextAreaState("copy or cut",d.b.selectedText(t))},t}(u.a),m=function(){function e(){}return e.canUseTextData=function(e){return!!e.clipboardData||!!window.clipboardData},e.getTextData=function(e){if(e.clipboardData)return e.preventDefault(),e.clipboardData.getData("text/plain");if(window.clipboardData)return e.preventDefault(),window.clipboardData.getData("Text");throw new Error("ClipboardEventUtils.getTextData: Cannot use text data!")},e.setTextData=function(e,t,n){if(e.clipboardData)return e.clipboardData.setData("text/plain",t),null!==n&&e.clipboardData.setData("text/html",n),void e.preventDefault();if(window.clipboardData)return window.clipboardData.setData("Text",t),void e.preventDefault();throw new Error("ClipboardEventUtils.setTextData: Cannot use text data!")},e}(),v=function(e){function t(t){var n=e.call(this)||this;return n._actual=t,n._ignoreSelectionChangeTime=0,n}return f(t,e),t.prototype.setIgnoreSelectionChangeTime=function(e){this._ignoreSelectionChangeTime=Date.now()},t.prototype.getIgnoreSelectionChangeTime=function(){return this._ignoreSelectionChangeTime},t.prototype.resetSelectionChangeTime=function(){this._ignoreSelectionChangeTime=0},t.prototype.getValue=function(){return this._actual.domNode.value},t.prototype.setValue=function(e,t){var n=this._actual.domNode;n.value!==t&&(this.setIgnoreSelectionChangeTime("setValue"),n.value=t)},t.prototype.getSelectionStart=function(){return this._actual.domNode.selectionStart},t.prototype.getSelectionEnd=function(){return this._actual.domNode.selectionEnd},t.prototype.setSelectionRange=function(e,t,n){var i=this._actual.domNode,s=document.activeElement===i,a=i.selectionStart,u=i.selectionEnd;if(s&&a===t&&u===n)r.i&&window.parent!==window&&i.focus();else{if(s)return this.setIgnoreSelectionChangeTime("setSelectionRange"),i.setSelectionRange(t,n),void(r.i&&window.parent!==window&&i.focus());try{var c=o.O(i);this.setIgnoreSelectionChangeTime("setSelectionRange"),i.focus(),i.setSelectionRange(t,n),o.M(i,c)}catch(e){}}},t}(u.a)},"4R/o":function(e,t,n){"use strict";(function(e,i){function r(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=n("X3l8"),s=n("rOku"),a=o.Buffer,u=o.kMaxLength,c=e.crypto||e.msCrypto,l=Math.pow(2,32)-1;function d(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>l||e<0)throw new TypeError("offset must be a uint32");if(e>u||e>t)throw new RangeError("offset out of range")}function h(e,t,n){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>l||e<0)throw new TypeError("size must be a uint32");if(e+t>n||e>u)throw new RangeError("buffer too small")}function f(e,t,n,r){if(i.browser){var o=e.buffer,a=new Uint8Array(o,t,n);return c.getRandomValues(a),r?void i.nextTick(function(){r(null,e)}):e}if(!r)return s(n).copy(e,t),e;s(n,function(n,i){if(n)return r(n);i.copy(e,t),r(null,e)})}c&&c.getRandomValues||!i.browser?(t.randomFill=function(t,n,i,r){if(!(a.isBuffer(t)||t instanceof e.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof n)r=n,n=0,i=t.length;else if("function"==typeof i)r=i,i=t.length-n;else if("function"!=typeof r)throw new TypeError('"cb" argument must be a function');return d(n,t.length),h(i,n,t.length),f(t,n,i,r)},t.randomFillSync=function(t,n,i){void 0===n&&(n=0);if(!(a.isBuffer(t)||t instanceof e.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');d(n,t.length),void 0===i&&(i=t.length-n);return h(i,n,t.length),f(t,n,i)}):(t.randomFill=r,t.randomFillSync=r)}).call(t,n("DuR2"),n("W2nU"))},"4Vh3":function(e,t){e.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},"4Yhh":function(e,t){},"4sPJ":function(e,t){e.exports=function(e){for(var t,n=e.length;n--;){if(255!==(t=e.readUInt8(n))){t++,e.writeUInt8(t,n);break}e.writeUInt8(0,n)}}},"4tuZ":function(e,t,n){"use strict";var i,r=n("aL7J"),o=n("80kS"),s=n("tqet"),a=n("03Zz"),u=n("7g0X"),c=n("EMhq"),l=n("JVO/"),d=n("8xpx"),h=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),f=Object(l.c)("IEditorCancelService"),p=new u.d("cancellableOperation",!1);Object(d.b)(f,function(){function e(){this._tokens=new WeakMap}return e.prototype.add=function(e,t){var n,i=this._tokens.get(e);return i||(i=e.invokeWithinContext(function(e){return{key:p.bindTo(e.get(u.c)),tokens:new c.a}}),this._tokens.set(e,i)),i.key.set(!0),n=i.tokens.push(t),function(){n&&(n(),i.key.set(!i.tokens.isEmpty()),n=void 0)}},e.prototype.cancel=function(e){var t=this._tokens.get(e);if(t){var n=t.tokens.pop();n&&(n.cancel(),t.key.set(!t.tokens.isEmpty()))}},e}(),!0);var g=function(e){function t(t,n){var i=e.call(this,n)||this;return i.editor=t,i._unregister=t.invokeWithinContext(function(e){return e.get(f).add(t,i)}),i}return h(t,e),t.prototype.dispose=function(){this._unregister(),e.prototype.dispose.call(this)},t}(o.b);Object(a.g)(new(function(e){function t(){return e.call(this,{id:"editor.cancelOperation",kbOpts:{weight:100,primary:9},precondition:p})||this}return h(t,e),t.prototype.runEditorCommand=function(e,t){e.get(f).cancel(t)},t}(a.c))),n.d(t,"a",function(){return v}),n.d(t,"b",function(){return _}),n.d(t,"d",function(){return b}),n.d(t,"c",function(){return y});var m=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),v=function(){function e(e,t){if(this.flags=t,0!=(1&this.flags)){var n=e.getModel();this.modelVersionId=n?r.r("{0}#{1}",n.uri.toString(),n.getVersionId()):null}else this.modelVersionId=null;0!=(4&this.flags)?this.position=e.getPosition():this.position=null,0!=(2&this.flags)?this.selection=e.getSelection():this.selection=null,0!=(8&this.flags)?(this.scrollLeft=e.getScrollLeft(),this.scrollTop=e.getScrollTop()):(this.scrollLeft=-1,this.scrollTop=-1)}return e.prototype._equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.modelVersionId===n.modelVersionId&&(this.scrollLeft===n.scrollLeft&&this.scrollTop===n.scrollTop&&(!(!this.position&&n.position||this.position&&!n.position||this.position&&n.position&&!this.position.equals(n.position))&&!(!this.selection&&n.selection||this.selection&&!n.selection||this.selection&&n.selection&&!this.selection.equalsRange(n.selection))))},e.prototype.validate=function(t){return this._equals(new e(t,this.flags))},e}(),_=function(e){function t(t,n,i){var r=e.call(this,t,i)||this;return r.editor=t,r._listener=new s.b,4&n&&r._listener.add(t.onDidChangeCursorPosition(function(e){return r.cancel()})),2&n&&r._listener.add(t.onDidChangeCursorSelection(function(e){return r.cancel()})),8&n&&r._listener.add(t.onDidScrollChange(function(e){return r.cancel()})),1&n&&(r._listener.add(t.onDidChangeModel(function(e){return r.cancel()})),r._listener.add(t.onDidChangeModelContent(function(e){return r.cancel()}))),r}return m(t,e),t.prototype.dispose=function(){this._listener.dispose(),e.prototype.dispose.call(this)},t}(g),b=function(e){function t(t,n){var i=e.call(this,n)||this;return i._listener=t.onDidChangeContent(function(){return i.cancel()}),i}return m(t,e),t.prototype.dispose=function(){this._listener.dispose(),e.prototype.dispose.call(this)},t}(o.b),y=function(){function e(e,t){this._visiblePosition=e,this._visiblePositionScrollDelta=t}return e.capture=function(t){var n=null,i=0;if(0!==t.getScrollTop()){var r=t.getVisibleRanges();if(r.length>0){n=r[0].getStartPosition();var o=t.getTopForPosition(n.lineNumber,n.column);i=t.getScrollTop()-o}}return new e(n,i)},e.prototype.restore=function(e){if(this._visiblePosition){var t=e.getTopForPosition(this._visiblePosition.lineNumber,this._visiblePosition.column);e.setScrollTop(t+this._visiblePositionScrollDelta)}},e}()},"5QAX":function(e,t,n){var i=n("geuY"),r=n("X3l8").Buffer;e.exports=function(e,t){return r.from(e.toRed(i.mont(t.modulus)).redPow(new i(t.publicExponent)).fromRed().toArray())}},"5RGO":function(e,t){},"5TlO":function(e,t,n){"use strict";t.a=function(e,t){if(!e)throw new Error(t?"Assertion failed ("+t+")":"Assertion Failed")}},"5VRF":function(e,t,n){"use strict";n.d(t,"c",function(){return s}),n.d(t,"d",function(){return r}),t.f=function(e){return Array.isArray(e)?r.fromArray(e):e},n.d(t,"a",function(){return a}),n.d(t,"b",function(){return u}),n.d(t,"e",function(){return c});var i,r,o=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s={done:!0,value:void 0};!function(e){var t={next:function(){return s}};e.empty=function(){return t},e.single=function(e){var t=!1;return{next:function(){return t?s:(t=!0,{done:!1,value:e})}}},e.fromArray=function(e,t,n){return void 0===t&&(t=0),void 0===n&&(n=e.length),{next:function(){return t>=n?s:{done:!1,value:e[t++]}}}},e.from=function(t){return t?Array.isArray(t)?e.fromArray(t):t:e.empty()},e.map=function(e,t){return{next:function(){var n=e.next();return n.done?s:{done:!1,value:t(n.value)}}}},e.filter=function(e,t){return{next:function(){for(;;){var n=e.next();if(n.done)return s;if(t(n.value))return{done:!1,value:n.value}}}}},e.forEach=function(e,t){for(var n=e.next();!n.done;n=e.next())t(n.value)},e.collect=function(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY);var n=[];if(0===t)return n;for(var i=0,r=e.next();!(r.done||(n.push(r.value),++i>=t));r=e.next());return n},e.concat=function(){for(var e=[],t=0;t=e.length)return s;var t=e[n].next();return t.done?(n++,this.next()):t}}}}(r||(r={}));var a=function(){function e(e,t,n,i){void 0===t&&(t=0),void 0===n&&(n=e.length),void 0===i&&(i=t-1),this.items=e,this.start=t,this.end=n,this.index=i}return e.prototype.first=function(){return this.index=this.start,this.current()},e.prototype.next=function(){return this.index=Math.min(this.index+1,this.end),this.current()},e.prototype.current=function(){return this.index===this.start-1||this.index===this.end?null:this.items[this.index]},e}(),u=function(e){function t(t,n,i,r){return void 0===n&&(n=0),void 0===i&&(i=t.length),void 0===r&&(r=n-1),e.call(this,t,n,i,r)||this}return o(t,e),t.prototype.current=function(){return e.prototype.current.call(this)},t.prototype.previous=function(){return this.index=Math.max(this.index-1,this.start-1),this.current()},t.prototype.first=function(){return this.index=this.start,this.current()},t.prototype.last=function(){return this.index=this.end-1,this.current()},t.prototype.parent=function(){return null},t}(a),c=function(){function e(e,t){this.iterator=e,this.fn=t}return e.prototype.next=function(){return this.fn(this.iterator.next())},e}()},"5kgg":function(e,t){},"5lao":function(e,t,n){"use strict";n.d(t,"a",function(){return h}),n.d(t,"b",function(){return f});var i,r=n("ZfGv"),o=n("iXRW"),s=n("G8r4"),a=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),u=r.d?1.5:1.35;function c(e,t){if("number"==typeof e)return e;if(void 0===e)return t;var n=parseFloat(e);return isNaN(n)?t:n}function l(e,t,n){return en?n:e}function d(e,t){return"string"!=typeof e?t:e}var h=function(){function e(e){this.zoomLevel=e.zoomLevel,this.fontFamily=String(e.fontFamily),this.fontWeight=String(e.fontWeight),this.fontSize=e.fontSize,this.lineHeight=0|e.lineHeight,this.letterSpacing=e.letterSpacing}return e.createFromRawSettings=function(t,n,i){void 0===i&&(i=!1);var r=d(t.fontFamily,o.b.fontFamily),a=d(t.fontWeight,o.b.fontWeight),h=c(t.fontSize,o.b.fontSize);0===(h=l(h,0,100))?h=o.b.fontSize:h<8&&(h=8);var f=function(e,t){if("number"==typeof e)return Math.round(e);if(void 0===e)return t;var n=parseInt(e);return isNaN(n)?t:n}(t.lineHeight,0);0===(f=l(f,0,150))?f=Math.round(u*h):f<8&&(f=8);var p=c(t.letterSpacing,0);p=l(p,-5,20);var g=1+(i?0:.1*s.a.getZoomLevel());return new e({zoomLevel:n,fontFamily:r,fontWeight:a,fontSize:h*=g,lineHeight:f*=g,letterSpacing:p})},e.prototype.getId=function(){return this.zoomLevel+"-"+this.fontFamily+"-"+this.fontWeight+"-"+this.fontSize+"-"+this.lineHeight+"-"+this.letterSpacing},e.prototype.getMassagedFontFamily=function(){return/[,"']/.test(this.fontFamily)?this.fontFamily:/[+ ]/.test(this.fontFamily)?'"'+this.fontFamily+'"':this.fontFamily},e}(),f=function(e){function t(t,n){var i=e.call(this,t)||this;return i.isTrusted=n,i.isMonospace=t.isMonospace,i.typicalHalfwidthCharacterWidth=t.typicalHalfwidthCharacterWidth,i.typicalFullwidthCharacterWidth=t.typicalFullwidthCharacterWidth,i.canUseHalfwidthRightwardsArrow=t.canUseHalfwidthRightwardsArrow,i.spaceWidth=t.spaceWidth,i.maxDigitWidth=t.maxDigitWidth,i}return a(t,e),t.prototype.equals=function(e){return this.fontFamily===e.fontFamily&&this.fontWeight===e.fontWeight&&this.fontSize===e.fontSize&&this.lineHeight===e.lineHeight&&this.letterSpacing===e.letterSpacing&&this.typicalHalfwidthCharacterWidth===e.typicalHalfwidthCharacterWidth&&this.typicalFullwidthCharacterWidth===e.typicalFullwidthCharacterWidth&&this.canUseHalfwidthRightwardsArrow===e.canUseHalfwidthRightwardsArrow&&this.spaceWidth===e.spaceWidth&&this.maxDigitWidth===e.maxDigitWidth},t}(h)},"5tK6":function(e,t,n){"use strict";n.d(t,"a",function(){return m});var i,r=n("LCUL"),o=(n.n(r),n("tqet")),s=n("lAcG"),a=n("ZfGv"),u=n("KIxu"),c=n("Bug4"),l=n("b1X/"),d=n("Kp7x"),h=n("7/Cv"),f=n("Gxst"),p=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=!1,m=function(e){function t(t,n,i){void 0===i&&(i={});var r=e.call(this)||this;return r._state=3,r._onDidEnablementChange=r._register(new d.a),r.onDidEnablementChange=r._onDidEnablementChange.event,r._onDidStart=r._register(new d.a),r.onDidStart=r._onDidStart.event,r._onDidChange=r._register(new d.a),r.onDidChange=r._onDidChange.event,r._onDidReset=r._register(new d.a),r.onDidReset=r._onDidReset.event,r._onDidEnd=r._register(new d.a),r.onDidEnd=r._onDidEnd.event,r.linkedSash=void 0,r.orthogonalStartSashDisposables=r._register(new o.b),r.orthogonalEndSashDisposables=r._register(new o.b),r.el=Object(h.m)(t,Object(h.a)(".monaco-sash")),a.d&&Object(h.f)(r.el,"mac"),r._register(Object(f.a)(r.el,"mousedown")(r.onMouseDown,r)),r._register(Object(f.a)(r.el,"dblclick")(r.onMouseDoubleClick,r)),c.b.addTarget(r.el),r._register(Object(f.a)(r.el,c.a.Start)(r.onTouchStart,r)),s.k&&Object(h.f)(r.el,"touch"),r.setOrientation(i.orientation||0),r.hidden=!1,r.layoutProvider=n,r.orthogonalStartSash=i.orthogonalStartSash,r.orthogonalEndSash=i.orthogonalEndSash,Object(h.R)(r.el,"debug",g),r}return p(t,e),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},set:function(e){this._state!==e&&(Object(h.R)(this.el,"disabled",0===e),Object(h.R)(this.el,"minimum",1===e),Object(h.R)(this.el,"maximum",2===e),this._state=e,this._onDidEnablementChange.fire(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"orthogonalStartSash",{get:function(){return this._orthogonalStartSash},set:function(e){this.orthogonalStartSashDisposables.clear(),e?(this.orthogonalStartSashDisposables.add(e.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange,this)),this.onOrthogonalStartSashEnablementChange(e.state)):this.onOrthogonalStartSashEnablementChange(0),this._orthogonalStartSash=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"orthogonalEndSash",{get:function(){return this._orthogonalEndSash},set:function(e){this.orthogonalEndSashDisposables.clear(),e?(this.orthogonalEndSashDisposables.add(e.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange,this)),this.onOrthogonalEndSashEnablementChange(e.state)):this.onOrthogonalEndSashEnablementChange(0),this._orthogonalEndSash=e},enumerable:!0,configurable:!0}),t.prototype.setOrientation=function(e){this.orientation=e,1===this.orientation?(Object(h.f)(this.el,"horizontal"),Object(h.I)(this.el,"vertical")):(Object(h.I)(this.el,"horizontal"),Object(h.f)(this.el,"vertical")),this.layoutProvider&&this.layout()},t.prototype.onMouseDown=function(e){var t=this;h.c.stop(e,!1);var n=!1;if(!e.__orthogonalSashEvent){var i=this.getOrthogonalSash(e);i&&(n=!0,e.__orthogonalSashEvent=!0,i.onMouseDown(e))}if(this.linkedSash&&!e.__linkedSashEvent&&(e.__linkedSashEvent=!0,this.linkedSash.onMouseDown(e)),this.state){for(var r=Object(h.y)("iframe").concat(Object(h.y)("webview")),s=0,u=r;s=this.el.clientHeight-4)return this.orthogonalEndSash}else{if(e.offsetX<=4)return this.orthogonalStartSash;if(e.offsetX>=this.el.clientWidth-4)return this.orthogonalEndSash}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.el&&this.el.parentElement&&this.el.parentElement.removeChild(this.el),this.el=null},t}(o.a)},"5zde":function(e,t,n){n("zQR9"),n("qyJz"),e.exports=n("FeBl").Array.from},"606G":function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("editorWorkerService")},"67ys":function(e,t){},"6Hge":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("X6iQ"),r=n("80kS"),o=n("03Zz"),s=n("artP"),a=n("vTy2"),u=n("iHM7"),c=n("/9db"),l=n("PCC9"),d=n("hK2W"),h=n("tqet"),f=n("aL7J"),p=function(){function e(){}return e.prototype.provideSelectionRanges=function(e,t){for(var n=[],i=0,r=t;i=0;u--){if(95===(d=r.charCodeAt(u))||45===d)break;if(Object(f.y)(d)&&Object(f.z)(l))break;l=d}for(u+=1;c0&&0===t.getLineFirstNonWhitespaceColumn(n.lineNumber)&&0===t.getLineLastNonWhitespaceColumn(n.lineNumber)&&e.push({range:new a.a(n.lineNumber,1,n.lineNumber,t.getLineMaxColumn(n.lineNumber))})},e}(),g=n("NjuD"),m=n("ItKl"),v=n("zxiH");t.provideSelectionRanges=k;var _,b=this&&this.__extends||(_=function(e,t){return(_=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}_(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),y=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},w=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=this.ranges.length)return this;var i=new e(n,this.ranges);return i.ranges[n].equalsRange(this.ranges[this.index])?i.mov(t):i},e}(),S=function(){function e(e){this._ignoreSelection=!1,this._editor=e}return e.get=function(t){return t.getContribution(e._id)},e.prototype.dispose=function(){Object(h.f)(this._selectionListener)},e.prototype.getId=function(){return e._id},e.prototype.run=function(e){var t=this;if(this._editor.hasModel()){var n=this._editor.getSelections(),o=this._editor.getModel();if(l.u.has(o)){var s=Promise.resolve(void 0);return this._state||(s=k(o,n.map(function(e){return e.getPosition()}),r.a.None).then(function(e){if(i.n(e)&&e.length===n.length&&t._editor.hasModel()&&i.g(t._editor.getSelections(),n,function(e,t){return e.equalsSelection(t)})){for(var r=function(t){e[t]=e[t].filter(function(e){return e.containsPosition(n[t].getStartPosition())&&e.containsPosition(n[t].getEndPosition())}),e[t].unshift(n[t])},o=0;o)?=?)";var L=u++;a[L]=a[l]+"|x|X|\\*";var O=u++;a[O]=a[c]+"|x|X|\\*";var k=u++;a[k]="[v=\\s]*("+a[O]+")(?:\\.("+a[O]+")(?:\\.("+a[O]+")(?:"+a[m]+")?"+a[b]+"?)?)?";var N=u++;a[N]="[v=\\s]*("+a[L]+")(?:\\.("+a[L]+")(?:\\.("+a[L]+")(?:"+a[v]+")?"+a[b]+"?)?)?";var E=u++;a[E]="^"+a[x]+"\\s*"+a[k]+"$";var I=u++;a[I]="^"+a[x]+"\\s*"+a[N]+"$";var D=u++;a[D]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var M=u++;a[M]="(?:~>?)";var T=u++;a[T]="(\\s*)"+a[M]+"\\s+",s[T]=new RegExp(a[T],"g");var P=u++;a[P]="^"+a[M]+a[k]+"$";var A=u++;a[A]="^"+a[M]+a[N]+"$";var R=u++;a[R]="(?:\\^)";var F=u++;a[F]="(\\s*)"+a[R]+"\\s+",s[F]=new RegExp(a[F],"g");var j=u++;a[j]="^"+a[R]+a[k]+"$";var W=u++;a[W]="^"+a[R]+a[N]+"$";var B=u++;a[B]="^"+a[x]+"\\s*("+C+")$|^$";var V=u++;a[V]="^"+a[x]+"\\s*("+w+")$|^$";var H=u++;a[H]="(\\s*)"+a[x]+"\\s*("+C+"|"+a[k]+")",s[H]=new RegExp(a[H],"g");var z=u++;a[z]="^\\s*("+a[k]+")\\s+-\\s+("+a[k]+")\\s*$";var U=u++;a[U]="^\\s*("+a[N]+")\\s+-\\s+("+a[N]+")\\s*$";var K=u++;a[K]="(<|>)?=?\\s*\\*";for(var q=0;qr)return null;if(!(t.loose?s[S]:s[y]).test(e))return null;try{return new Z(e,t)}catch(e){return null}}function Z(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof Z){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>r)throw new TypeError("version is longer than "+r+" characters");if(!(this instanceof Z))return new Z(e,t);i("SemVer",e,t),this.options=t,this.loose=!!t.loose;var n=e.trim().match(t.loose?s[S]:s[y]);if(!n)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>o||this.major<0)throw new TypeError("Invalid major version");if(this.minor>o||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>o||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);-1===n&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,n,i){"string"==typeof n&&(i=n,n=void 0);try{return new Z(e,n).inc(t,i).version}catch(e){return null}},t.diff=function(e,t){if(ee(e,t))return null;var n=G(e),i=G(t),r="";if(n.prerelease.length||i.prerelease.length){r="pre";var o="prerelease"}for(var s in n)if(("major"===s||"minor"===s||"patch"===s)&&n[s]!==i[s])return r+s;return o},t.compareIdentifiers=X;var Y=/^[0-9]+$/;function X(e,t){var n=Y.test(e),i=Y.test(t);return n&&i&&(e=+e,t=+t),e===t?0:n&&!i?-1:i&&!n?1:e0}function Q(e,t,n){return $(e,t,n)<0}function ee(e,t,n){return 0===$(e,t,n)}function te(e,t,n){return 0!==$(e,t,n)}function ne(e,t,n){return $(e,t,n)>=0}function ie(e,t,n){return $(e,t,n)<=0}function re(e,t,n,i){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return ee(e,n,i);case"!=":return te(e,n,i);case">":return J(e,n,i);case">=":return ne(e,n,i);case"<":return Q(e,n,i);case"<=":return ie(e,n,i);default:throw new TypeError("Invalid operator: "+t)}}function oe(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof oe){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof oe))return new oe(e,t);i("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===se?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}t.rcompareIdentifiers=function(e,t){return X(t,e)},t.major=function(e,t){return new Z(e,t).major},t.minor=function(e,t){return new Z(e,t).minor},t.patch=function(e,t){return new Z(e,t).patch},t.compare=$,t.compareLoose=function(e,t){return $(e,t,!0)},t.rcompare=function(e,t,n){return $(t,e,n)},t.sort=function(e,n){return e.sort(function(e,i){return t.compare(e,i,n)})},t.rsort=function(e,n){return e.sort(function(e,i){return t.rcompare(e,i,n)})},t.gt=J,t.lt=Q,t.eq=ee,t.neq=te,t.gte=ne,t.lte=ie,t.cmp=re,t.Comparator=oe;var se={};function ae(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof ae)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new ae(e.raw,t);if(e instanceof oe)return new ae(e.value,t);if(!(this instanceof ae))return new ae(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map(function(e){return this.parseRange(e.trim())},this).filter(function(e){return e.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ue(e){return!e||"x"===e.toLowerCase()||"*"===e}function ce(e,t,n,i,r,o,s,a,u,c,l,d,h){return((t=ue(n)?"":ue(i)?">="+n+".0.0":ue(r)?">="+n+"."+i+".0":">="+t)+" "+(a=ue(u)?"":ue(c)?"<"+(+u+1)+".0.0":ue(l)?"<"+u+"."+(+c+1)+".0":d?"<="+u+"."+c+"."+l+"-"+d:"<="+a)).trim()}function le(e,t,n){for(var r=0;r0){var o=e[r].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}function de(e,t,n){try{t=new ae(t,n)}catch(e){return!1}return t.test(e)}function he(e,t,n,i){var r,o,s,a,u;switch(e=new Z(e,i),t=new ae(t,i),n){case">":r=J,o=ie,s=Q,a=">",u=">=";break;case"<":r=Q,o=ne,s=J,a="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(de(e,t,i))return!1;for(var c=0;c=0.0.0")),l=l||e,d=d||e,r(e.semver,l.semver,i)?l=e:s(e.semver,d.semver,i)&&(d=e)}),l.operator===a||l.operator===u)return!1;if((!d.operator||d.operator===a)&&o(e,d.semver))return!1;if(d.operator===u&&s(e,d.semver))return!1}return!0}oe.prototype.parse=function(e){var t=this.options.loose?s[B]:s[V],n=e.match(t);if(!n)throw new TypeError("Invalid comparator: "+e);this.operator=n[1],"="===this.operator&&(this.operator=""),n[2]?this.semver=new Z(n[2],this.options.loose):this.semver=se},oe.prototype.toString=function(){return this.value},oe.prototype.test=function(e){return i("Comparator.test",e,this.options.loose),this.semver===se||("string"==typeof e&&(e=new Z(e,this.options)),re(e,this.operator,this.semver,this.options))},oe.prototype.intersects=function(e,t){if(!(e instanceof oe))throw new TypeError("a Comparator is required");var n;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return n=new ae(e.value,t),de(this.value,n,t);if(""===e.operator)return n=new ae(this.value,t),de(e.semver,n,t);var i=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),r=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),o=this.semver.version===e.semver.version,s=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=re(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),u=re(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return i||r||o&&s||a||u},t.Range=ae,ae.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range},ae.prototype.toString=function(){return this.range},ae.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var n=t?s[U]:s[z];e=e.replace(n,ce),i("hyphen replace",e),e=e.replace(s[H],"$1$2$3"),i("comparator trim",e,s[H]),e=(e=(e=e.replace(s[T],"$1~")).replace(s[F],"$1^")).split(/\s+/).join(" ");var r=t?s[B]:s[V],o=e.split(" ").map(function(e){return function(e,t){return i("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map(function(e){return function(e,t){i("caret",e,t);var n=t.loose?s[W]:s[j];return e.replace(n,function(t,n,r,o,s){var a;return i("caret",e,t,n,r,o,s),ue(n)?a="":ue(r)?a=">="+n+".0.0 <"+(+n+1)+".0.0":ue(o)?a="0"===n?">="+n+"."+r+".0 <"+n+"."+(+r+1)+".0":">="+n+"."+r+".0 <"+(+n+1)+".0.0":s?(i("replaceCaret pr",s),a="0"===n?"0"===r?">="+n+"."+r+"."+o+"-"+s+" <"+n+"."+r+"."+(+o+1):">="+n+"."+r+"."+o+"-"+s+" <"+n+"."+(+r+1)+".0":">="+n+"."+r+"."+o+"-"+s+" <"+(+n+1)+".0.0"):(i("no pr"),a="0"===n?"0"===r?">="+n+"."+r+"."+o+" <"+n+"."+r+"."+(+o+1):">="+n+"."+r+"."+o+" <"+n+"."+(+r+1)+".0":">="+n+"."+r+"."+o+" <"+(+n+1)+".0.0"),i("caret return",a),a})}(e,t)}).join(" ")}(e,t),i("caret",e),e=function(e,t){return e.trim().split(/\s+/).map(function(e){return function(e,t){var n=t.loose?s[A]:s[P];return e.replace(n,function(t,n,r,o,s){var a;return i("tilde",e,t,n,r,o,s),ue(n)?a="":ue(r)?a=">="+n+".0.0 <"+(+n+1)+".0.0":ue(o)?a=">="+n+"."+r+".0 <"+n+"."+(+r+1)+".0":s?(i("replaceTilde pr",s),a=">="+n+"."+r+"."+o+"-"+s+" <"+n+"."+(+r+1)+".0"):a=">="+n+"."+r+"."+o+" <"+n+"."+(+r+1)+".0",i("tilde return",a),a})}(e,t)}).join(" ")}(e,t),i("tildes",e),e=function(e,t){return i("replaceXRanges",e,t),e.split(/\s+/).map(function(e){return function(e,t){e=e.trim();var n=t.loose?s[I]:s[E];return e.replace(n,function(t,n,r,o,s,a){i("xRange",e,t,n,r,o,s,a);var u=ue(r),c=u||ue(o),l=c||ue(s),d=l;return"="===n&&d&&(n=""),u?t=">"===n||"<"===n?"<0.0.0":"*":n&&d?(c&&(o=0),s=0,">"===n?(n=">=",c?(r=+r+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",c?r=+r+1:o=+o+1),t=n+r+"."+o+"."+s):c?t=">="+r+".0.0 <"+(+r+1)+".0.0":l&&(t=">="+r+"."+o+".0 <"+r+"."+(+o+1)+".0"),i("xRange return",t),t})}(e,t)}).join(" ")}(e,t),i("xrange",e),e=function(e,t){return i("replaceStars",e,t),e.trim().replace(s[K],"")}(e,t),i("stars",e),e}(e,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(o=o.filter(function(e){return!!e.match(r)})),o=o.map(function(e){return new oe(e,this.options)},this)},ae.prototype.intersects=function(e,t){if(!(e instanceof ae))throw new TypeError("a Range is required");return this.set.some(function(n){return n.every(function(n){return e.set.some(function(e){return e.every(function(e){return n.intersects(e,t)})})})})},t.toComparators=function(e,t){return new ae(e,t).set.map(function(e){return e.map(function(e){return e.value}).join(" ").trim().split(" ")})},ae.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new Z(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":n&&!J(n,t)||(n=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}})}if(n&&e.test(n))return n;return null},t.validRange=function(e,t){try{return new ae(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,n){return he(e,t,"<",n)},t.gtr=function(e,t,n){return he(e,t,">",n)},t.outside=he,t.prerelease=function(e,t){var n=G(e,t);return n&&n.prerelease.length?n.prerelease:null},t.intersects=function(e,t,n){return e=new ae(e,n),t=new ae(t,n),e.intersects(t)},t.coerce=function(e){if(e instanceof Z)return e;if("string"!=typeof e)return null;var t=e.match(s[D]);if(null==t)return null;return G(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}}).call(t,n("W2nU"))},"6TMp":function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("modeService")},"6ZSt":function(e,t){e.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}},"6boo":function(e,t,n){"use strict";n.d(t,"b",function(){return p}),n.d(t,"f",function(){return g}),n.d(t,"c",function(){return m}),n.d(t,"d",function(){return b}),n.d(t,"e",function(){return y}),n.d(t,"a",function(){return w}),t.g=function(e){return"'"===e||'"'===e||"`"===e};var i=n("zxiH"),r=n("aL7J"),o=n("artP"),s=n("vTy2"),a=n("iHM7"),u=n("0ly5"),c=n("Fllr"),l=function(){return!0},d=function(){return!1},h=function(e){return" "===e||"\t"===e};function f(e,t,n){e.has(t)?e.get(t).push(n):e.set(t,[n])}var p=function(){function e(t,n,i){this._languageIdentifier=t;var r=i.editor;this.readOnly=r.readOnly,this.tabSize=n.tabSize,this.indentSize=n.indentSize,this.insertSpaces=n.insertSpaces,this.pageSize=Math.max(1,Math.floor(r.layoutInfo.height/r.fontInfo.lineHeight)-2),this.lineHeight=r.lineHeight,this.useTabStops=r.useTabStops,this.wordSeparators=r.wordSeparators,this.emptySelectionClipboard=r.emptySelectionClipboard,this.copyWithSyntaxHighlighting=r.copyWithSyntaxHighlighting,this.multiCursorMergeOverlapping=r.multiCursorMergeOverlapping,this.autoClosingBrackets=r.autoClosingBrackets,this.autoClosingQuotes=r.autoClosingQuotes,this.autoClosingOvertype=r.autoClosingOvertype,this.autoSurround=r.autoSurround,this.autoIndent=r.autoIndent,this.autoClosingPairsOpen2=new Map,this.autoClosingPairsClose2=new Map,this.surroundingPairs={},this._electricChars=null,this.shouldAutoCloseBefore={quote:e._getShouldAutoClose(t,this.autoClosingQuotes),bracket:e._getShouldAutoClose(t,this.autoClosingBrackets)};var o=e._getAutoClosingPairs(t);if(o)for(var s=0,a=o;s=i.length)&&r.x(i.charCodeAt(n))},e.isHighSurrogate=function(e,t,n){var i=e.getLineContent(t);return!(n<0||n>=i.length)&&r.w(i.charCodeAt(n))},e.isInsideSurrogatePair=function(e,t,n){return this.isHighSurrogate(e,t,n-2)},e.visibleColumnFromColumn=function(e,t,n){var i=e.length;i>t-1&&(i=t-1);for(var o=0,s=0;s=t)return u-ts?s:r},e.nextRenderTabStop=function(e,t){return e+t-e%t},e.nextIndentTabStop=function(e,t){return e+t-e%t},e.prevRenderTabStop=function(e,t){return e-1-(e-1)%t},e.prevIndentTabStop=function(e,t){return e-1-(e-1)%t},e}()},"6hW9":function(e,t,n){var i=n("BEbT"),r=n("X3l8").Buffer,o=n("z+8S");function s(e,t,n,s){o.call(this),this._cipher=new i.AES(t),this._prev=r.from(n),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=s,this._mode=e}n("LC74")(s,o),s.prototype._update=function(e){return this._mode.encrypt(this,e,this._decrypt)},s.prototype._final=function(){this._cipher.scrub()},e.exports=s},"6jTg":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("odeJ"),r=n("zxiH"),o=n("tqet"),s=n("4tuZ"),a=n("03Zz"),u=n("PCC9"),c=n("X6iQ"),l=n("80kS"),d=n("mrx5"),h=n("jIdl"),f=function(){function e(){this.lenses=[],this._dispoables=new o.b}return e.prototype.dispose=function(){this._dispoables.dispose()},e.prototype.add=function(e,t){this._dispoables.add(e);for(var n=0,i=e.lenses;nt.symbol.range.startLineNumber?1:i.get(e.provider)i.get(t.provider)?1:e.symbol.range.startColumnt.symbol.range.startColumn?1:0}),o})}Object(a.j)("_executeCodeLensProvider",function(e,t){var n=t.resource,i=t.itemResolveCount;if(!(n instanceof d.a))throw Object(r.b)();var s=e.get(h.a).getModel(n);if(!s)throw Object(r.b)();var a=[],u=new o.b;return p(s,l.a.None).then(function(e){u.add(e);for(var t=[],n=function(e){void 0===i||Boolean(e.symbol.command)?a.push(e.symbol):i-- >0&&e.provider.resolveCodeLens&&t.push(Promise.resolve(e.provider.resolveCodeLens(s,e.symbol,l.a.None)).then(function(t){return a.push(t||e.symbol)}))},r=0,o=e.lenses;rno commands";else{for(var i=[],r=0;r"+s+"",this._commands.set(String(r),o)):a=""+s+"",i.push(a)}}var u=""===this._domNode.innerHTML||" "===this._domNode.innerHTML;this._domNode.innerHTML=i.join(" | "),this._editor.layoutContentWidget(this),u&&t&&g.f(this._domNode,"fadein")}},e.prototype.getCommand=function(e){return e.parentElement===this._domNode?this._commands.get(e.id):void 0},e.prototype.getId=function(){return this._id},e.prototype.getDomNode=function(){return this._domNode},e.prototype.setSymbolRange=function(e){if(this._editor.hasModel()){var t=e.startLineNumber,n=this._editor.getModel().getLineFirstNonWhitespaceColumn(t);this._widgetPosition={position:{lineNumber:t,column:n},preference:[1]}}},e.prototype.getPosition=function(){return this._widgetPosition||null},e.prototype.isVisible=function(){return this._domNode.hasAttribute("monaco-visible-content-widget")},e._idPool=0,e}(),x=function(){function e(){this._removeDecorations=[],this._addDecorations=[],this._addDecorationsCallbacks=[]}return e.prototype.addDecoration=function(e,t){this._addDecorations.push(e),this._addDecorationsCallbacks.push(t)},e.prototype.removeDecoration=function(e){this._removeDecorations.push(e)},e.prototype.commit=function(e){for(var t=e.deltaDecorations(this._removeDecorations,this._addDecorations),n=0,i=t.length;n a:hover { color: "+i+" !important; }")});var O=n("ItKl"),k=n("fAkY"),N=n("JVO/"),E=n("8xpx"),I=n("WTFd"),D=n("Cfmk"),M=n("dwjm"),T=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},P=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},A=Object(N.c)("ICodeLensCache"),R=function(){return function(e,t){this.lineCount=e,this.data=t}}(),F=function(){function e(e){var t=this;this._fakeProvider=new(function(){function e(){}return e.prototype.provideCodeLenses=function(){throw new Error("not supported")},e}()),this._cache=new I.a(20,.75);Object(i.k)(function(){return e.remove("codelens/cache",1)});var n="codelens/cache2",r=e.get(n,1,"{}");this._deserialize(r),Object(M.a)(e.onWillSaveState)(function(i){i.reason===D.c.SHUTDOWN&&e.store(n,t._serialize(),1)})}return e.prototype.put=function(e,t){var n=new f;n.add({lenses:t.lenses.map(function(e){return e.symbol}),dispose:function(){}},this._fakeProvider);var i=new R(e.getLineCount(),n);this._cache.set(e.uri.toString(),i)},e.prototype.get=function(e){var t=this._cache.get(e.uri.toString());return t&&t.lineCount===e.getLineCount()?t.data:void 0},e.prototype.delete=function(e){this._cache.delete(e.uri.toString())},e.prototype._serialize=function(){var e=Object.create(null);return this._cache.forEach(function(t,n){for(var i=new Set,r=0,o=t.data.lenses;r=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},W=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},B=function(){function e(e,t,n,i){var r=this;this._editor=e,this._commandService=t,this._notificationService=n,this._codeLensCache=i,this._globalToDispose=new o.b,this._localToDispose=new o.b,this._lenses=[],this._oldCodeLensModels=new o.b,this._modelChangeCounter=0,this._isEnabled=this._editor.getConfiguration().contribInfo.codeLens,this._globalToDispose.add(this._editor.onDidChangeModel(function(){return r._onModelChange()})),this._globalToDispose.add(this._editor.onDidChangeModelLanguage(function(){return r._onModelChange()})),this._globalToDispose.add(this._editor.onDidChangeConfiguration(function(){var e=r._isEnabled;r._isEnabled=r._editor.getConfiguration().contribInfo.codeLens,e!==r._isEnabled&&r._onModelChange()})),this._globalToDispose.add(u.b.onDidChange(this._onModelChange,this)),this._onModelChange()}return e.prototype.dispose=function(){this._localDispose(),this._globalToDispose.dispose(),this._oldCodeLensModels.dispose(),Object(o.f)(this._currentCodeLensModel)},e.prototype._localDispose=function(){this._currentFindCodeLensSymbolsPromise&&(this._currentFindCodeLensSymbolsPromise.cancel(),this._currentFindCodeLensSymbolsPromise=void 0,this._modelChangeCounter++),this._currentResolveCodeLensSymbolsPromise&&(this._currentResolveCodeLensSymbolsPromise.cancel(),this._currentResolveCodeLensSymbolsPromise=void 0),this._localToDispose.clear(),this._oldCodeLensModels.clear(),Object(o.f)(this._currentCodeLensModel)},e.prototype.getId=function(){return e.ID},e.prototype._onModelChange=function(){var e=this;this._localDispose();var t=this._editor.getModel();if(t&&this._isEnabled){var n=this._codeLensCache.get(t);if(n&&this._renderCodeLensSymbols(n),u.b.has(t)){for(var a=0,c=u.b.all(t);a0&&h.schedule()})),this._localToDispose.add(this._editor.onDidLayoutChange(function(){h.schedule()})),this._localToDispose.add(Object(o.h)(function(){if(e._editor.getModel()){var t=s.c.capture(e._editor);e._editor.changeDecorations(function(t){e._editor.changeViewZones(function(n){e._disposeAllLenses(t,n)})}),t.restore(e._editor)}else e._disposeAllLenses(void 0,void 0)})),this._localToDispose.add(this._editor.onDidChangeConfiguration(function(t){if(t.fontInfo)for(var n=0,i=e._lenses;ni||(n&&n[n.length-1].symbol.range.startLineNumber===c?n.push(u):(n=[u],r.push(n)))}var l=s.c.capture(this._editor);this._editor.changeDecorations(function(e){t._editor.changeViewZones(function(n){for(var i=new x,o=0,s=0;s=0;r--)t.sheet.deleteRule(i[r])},t.F=function(e){if("object"==typeof HTMLElement)return e instanceof HTMLElement;return e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.nodeName},n.d(t,"d",function(){return Y}),n.d(t,"c",function(){return X}),t.O=function(e){for(var t=[],n=0;e&&e.nodeType===e.ELEMENT_NODE;n++)t[n]=e.scrollTop,e=e.parentNode;return t},t.M=function(e,t){for(var n=0;e&&e.nodeType===e.ELEMENT_NODE;n++)e.scrollTop!==t[n]&&(e.scrollTop=t[n]),e=e.parentNode},t.S=function(e){return new $(e)},t.m=function(e){for(var t=[],n=1;n=0;){if(o=s+r,(0===s||32===n.charCodeAt(s-1))&&32===n.charCodeAt(o))return this._lastStart=s,void(this._lastEnd=o+1);if(s>0&&32===n.charCodeAt(s-1)&&o===i)return this._lastStart=s-1,void(this._lastEnd=o);if(0===s&&o===i)return this._lastStart=0,void(this._lastEnd=o)}this._lastStart=-1}else this._lastStart=-1}else this._lastStart=-1},e.prototype.hasClass=function(e,t){return this._findClassName(e,t),-1!==this._lastStart},e.prototype.addClasses=function(e){for(var t=this,n=[],i=1;i0;){T.sort(F.sort),T.shift().execute()}A=!1},I=function(e,t){void 0===t&&(t=0);var n,i=new F(e,t);return M.push(i),P||(P=!0,n=R,D||(D=self.requestAnimationFrame||self.msRequestAnimationFrame||self.webkitRequestAnimationFrame||self.mozRequestAnimationFrame||self.oRequestAnimationFrame||function(e){return setTimeout(function(){return e((new Date).getTime())},0)}),D.call(self,n)),i},E=function(e,t){if(A){var n=new F(e,t);return T.push(n),n}return I(e,t)};var j=16,W=function(e,t){return t},B=function(e){function t(t,n,i,r,o){void 0===r&&(r=W),void 0===o&&(o=j);var s=e.call(this)||this,a=null,c=0,l=s._register(new u.e),d=function(){c=(new Date).getTime(),i(a),a=null};return s._register(k(t,n,function(e){a=r(a,e);var t=(new Date).getTime()-c;t>=o?(l.cancel(),d()):l.setIfNotSet(d,o-t)})),s}return g(t,e),t}(d.a);function V(e){return document.defaultView.getComputedStyle(e,null)}var H=function(){function e(){}return e.convertToPixels=function(e,t){return parseFloat(t)||0},e.getDimension=function(t,n,i){var r=V(t),o="0";return r&&(o=r.getPropertyValue?r.getPropertyValue(n):r.getAttribute(i)),e.convertToPixels(t,o)},e.getBorderLeftWidth=function(t){return e.getDimension(t,"border-left-width","borderLeftWidth")},e.getBorderRightWidth=function(t){return e.getDimension(t,"border-right-width","borderRightWidth")},e.getBorderTopWidth=function(t){return e.getDimension(t,"border-top-width","borderTopWidth")},e.getBorderBottomWidth=function(t){return e.getDimension(t,"border-bottom-width","borderBottomWidth")},e.getPaddingLeft=function(t){return e.getDimension(t,"padding-left","paddingLeft")},e.getPaddingRight=function(t){return e.getDimension(t,"padding-right","paddingRight")},e.getPaddingTop=function(t){return e.getDimension(t,"padding-top","paddingTop")},e.getPaddingBottom=function(t){return e.getDimension(t,"padding-bottom","paddingBottom")},e.getMarginLeft=function(t){return e.getDimension(t,"margin-left","marginLeft")},e.getMarginTop=function(t){return e.getDimension(t,"margin-top","marginTop")},e.getMarginRight=function(t){return e.getDimension(t,"margin-right","marginRight")},e.getMarginBottom=function(t){return e.getDimension(t,"margin-bottom","marginBottom")},e}(),z=function(){return function(e,t){this.width=e,this.height=t}}();var U=new(function(){function e(){}return Object.defineProperty(e.prototype,"scrollX",{get:function(){return"number"==typeof window.scrollX?window.scrollX:document.body.scrollLeft+document.documentElement.scrollLeft},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollY",{get:function(){return"number"==typeof window.scrollY?window.scrollY:document.body.scrollTop+document.documentElement.scrollTop},enumerable:!0,configurable:!0}),e}());function K(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function q(e){void 0===e&&(e=document.getElementsByTagName("head")[0]);var t=document.createElement("style");return t.type="text/css",t.media="screen",e.appendChild(t),t}var G=null;function Z(){return G||(G=q()),G}var Y={CLICK:"click",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:r.m?"webkitAnimationStart":"animationstart",ANIMATION_END:r.m?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:r.m?"webkitAnimationIteration":"animationiteration"},X={stop:function(e,t){e.preventDefault?e.preventDefault():e.returnValue=!1,t&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0)}};var $=function(e){function t(t){var n=e.call(this)||this;n._onDidFocus=n._register(new l.a),n.onDidFocus=n._onDidFocus.event,n._onDidBlur=n._register(new l.a),n.onDidBlur=n._onDidBlur.event;var i=K(document.activeElement,t),r=!1;return n._register(Object(o.a)(t,Y.FOCUS,!0)(function(){r=!1,i||(i=!0,n._onDidFocus.fire())})),n._register(Object(o.a)(t,Y.BLUR,!0)(function(){i&&(r=!0,window.setTimeout(function(){r&&(r=!1,i=!1,n._onDidBlur.fire())},0))})),n}return g(t,e),t}(d.a);var J,Q=/([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;function ee(e,t,n){for(var i=[],r=3;r=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},S=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},x=function(){function e(){}return e.prototype.select=function(e,t,n){if(0===n.length)return 0;for(var i=n[0].score[0],r=1;ru&&d.type===i[c].completion.kind&&d.insertText===i[c].completion.insertText&&(u=d.touch,a=c),i[c].completion.preselect&&-1===s)return c}return-1!==a?a:-1!==s?s:0},t.prototype.toJSON=function(){var e=[];return this._cache.forEach(function(t,n){e.push([n,t])}),e},t.prototype.fromJSON=function(e){this._cache.clear();for(var t=0,n=e;t0){this._seq=e[0][1].touch+1;for(var t=0,n=e;t=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},R=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},F=function(){function e(t,n){this._editor=t,this._index=0,this._ckOtherSuggestions=e.OtherSuggestions.bindTo(n)}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this._ckOtherSuggestions.reset(),Object(a.f)(this._listener),this._model=void 0,this._acceptNext=void 0,this._ignore=!1},e.prototype.set=function(t,n){var i=this,r=t.model,o=t.index;0!==r.items.length?e._moveIndex(!0,r,o)!==o?(this._acceptNext=n,this._model=r,this._index=o,this._listener=this._editor.onDidChangeCursorPosition(function(){i._ignore||i.reset()}),this._ckOtherSuggestions.set(!0)):this.reset():this.reset()},e._moveIndex=function(e,t,n){for(var i=n;(i=(i+t.items.length+(e?1:-1))%t.items.length)!==n&&t.items[i].completion.additionalTextEdits;);return i},e.prototype.next=function(){this._move(!0)},e.prototype.prev=function(){this._move(!1)},e.prototype._move=function(t){if(this._model)try{this._ignore=!0,this._index=e._moveIndex(t,this._model,this._index),this._acceptNext({index:this._index,item:this._model.items[this._index],model:this._model})}finally{this._ignore=!1}},e.OtherSuggestions=new T.d("hasOtherSuggestions",!1),e=A([R(1,T.c)],e)}(),j=n("Kp7x"),W=n("iHM7"),B=n("GYOr"),V=n("iXRW"),H=n("aL7J"),z=(function(){}(),function(){function e(t,n,i,r,o){void 0===o&&(o=V.a.contribInfo.suggest),this._snippetCompareFn=e._compareCompletionItems,this._items=t,this._column=n,this._wordDistance=r,this._options=o,this._refilterKind=1,this._lineContext=i,"top"===o.snippets?this._snippetCompareFn=e._compareCompletionItemsSnippetsUp:"bottom"===o.snippets&&(this._snippetCompareFn=e._compareCompletionItemsSnippetsDown)}return Object.defineProperty(e.prototype,"lineContext",{get:function(){return this._lineContext},set:function(e){this._lineContext.leadingLineContent===e.leadingLineContent&&this._lineContext.characterCountDelta===e.characterCountDelta||(this._refilterKind=this._lineContext.characterCountDelta2e3?B.d:B.e,u=0;u=d)c.score=B.a.Default;else if("string"==typeof c.completion.filterText){if(!(p=a(i,r,h,c.completion.filterText,c.filterTextLow,0,!1)))continue;0===Object(H.e)(c.completion.filterText,c.completion.label)?c.score=p:(c.score=Object(B.b)(i,r,h,c.completion.label,c.labelLow,0),c.score[0]=p[0])}else{var p;if(!(p=a(i,r,h,c.completion.label,c.labelLow,0,!1)))continue;c.score=p}}switch(c.idx=u,c.distance=this._wordDistance.distance(c.position,c.completion),s.push(c),this._stats.suggestionCount++,c.completion.kind){case 25:this._stats.snippetCount++;break;case 18:this._stats.textCount++}}this._filteredItems=s.sort(this._snippetCompareFn),this._refilterKind=0},e._compareCompletionItems=function(e,t){return e.score[0]>t.score[0]?-1:e.score[0]t.distance?1:e.idxt.idx?1:0},e._compareCompletionItemsSnippetsDown=function(t,n){if(t.completion.kind!==n.completion.kind){if(25===t.completion.kind)return 1;if(25===n.completion.kind)return-1}return e._compareCompletionItems(t,n)},e._compareCompletionItemsSnippetsUp=function(t,n){if(t.completion.kind!==n.completion.kind){if(25===t.completion.kind)return-1;if(25===n.completion.kind)return 1}return e._compareCompletionItems(t,n)},e}()),U=n("80kS"),K=n("NjuD"),q=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),G=function(){function e(){}return e.create=function(t,n){if(!n.getConfiguration().contribInfo.suggest.localityBonus)return Promise.resolve(e.None);if(!n.hasModel())return Promise.resolve(e.None);var i=n.getModel(),r=n.getPosition();return t.canComputeWordRanges(i.uri)?(new K.a).provideSelectionRanges(i,[r]).then(function(s){return s&&0!==s.length&&0!==s[0].length?t.computeWordRanges(i.uri,s[0][0].range).then(function(t){return new(function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return q(i,e),i.prototype.distance=function(e,i){if(!t||!r.equals(n.getPosition()))return 0;if(17===i.kind)return 2<<20;var a=i.label,u=t[a];if(Object(o.m)(u))return 2<<20;for(var c=Object(o.c)(u,l.a.fromPositions(e),l.a.compareRangesUsingStarts),d=c>=0?u[c]:u[Math.max(0,~c-1)],h=s.length,f=0,p=s[0];f0?{triggerKind:2}:{triggerKind:0},this._requestToken=new U.b;var h=this._editor.getConfiguration().contribInfo,f=new Set,p=1;switch(h.suggest.snippets){case"top":p=0;break;case"bottom":p=2;break;case"none":f.add(25)}for(var g in h.suggest.filteredTypes){var v=Object(m.A)(g,!0);void 0!==v&&!1===h.suggest.filteredTypes[g]&&f.add(v)}var _=G.create(this._editorWorker,this._editor),b=Object(P.e)(c,this._editor.getPosition(),new P.a(p,f,n),u,this._requestToken.token);Promise.all([b,_]).then(function(t){var n=t[0],s=t[1];if(Object(a.f)(r._requestToken),0!==r._state&&r._editor.hasModel()){var u=r._editor.getModel();if(Object(o.n)(i)){var c=Object(P.d)(p);n=n.concat(i).sort(c)}var d=new Z(u,r._editor.getPosition(),l,e.shy);r._completionModel=new z(n,r._context.column,{leadingLineContent:d.leadingLineContent,characterCountDelta:d.column-r._context.column},s,r._editor.getConfiguration().contribInfo.suggest);for(var h=0,f=n;hthis._context.column&&this._completionModel.incomplete.size>0&&0!==e.leadingWord.word.length){var t=this._completionModel.incomplete,n=this._completionModel.adopt(t);this.trigger({auto:2===this._state,shy:!1},!0,t,n)}else{var i=this._completionModel.lineContext,r=!1;if(this._completionModel.lineContext={leadingLineContent:e.leadingLineContent,characterCountDelta:e.column-this._context.column},0===this._completionModel.items.length){if(Z.shouldAutoTrigger(this._editor)&&this._context.leadingWord.endColumn0)&&0===e.leadingWord.word.length)return void this.cancel()}this._onDidSuggest.fire({completionModel:this._completionModel,auto:this._context.auto,shy:this._context.shy,isFrozen:r})}}else this.cancel()},e}(),X=(n("YUwp"),n("7/Cv")),$=n("SWdJ"),J=n("qecS"),Q=n("NqM+"),ee=n("3ciN"),te=n("Yqb6"),ne=n("eoic"),ie=n("L5KM"),re=n("VBCr"),oe=n("6TMp"),se=n("GsV8"),ae=n("tpa8"),ue=n("lapT"),ce=n("ZYUE"),le=n("9XyG");function de(e,t,n,i){var r=i===I.ROOT_FOLDER?["rootfolder-icon"]:i===I.FOLDER?["folder-icon"]:["file-icon"];if(n){var o;if(n.scheme===ue.b.data)o=ce.a.parseMetaData(n).get(ce.a.META_DATA_LABEL);else o=he(Object(ce.c)(n).toLowerCase());if(i===I.FOLDER)r.push(o+"-name-folder-icon");else{if(o){r.push(o+"-name-file-icon");for(var s=o.split("."),a=1;a=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},_e=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},be=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},ye=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0&&(c.extraClasses=(c.extraClasses||[]).concat(["deprecated"]),c.matches=[]),r.iconLabel.setLabel(s.label,void 0,c),r.typeLabel.textContent=(s.detail||"").replace(/\n.*$/m,""),ke(e)?(Object(X.Q)(r.readMore),r.readMore.onmousedown=function(e){e.stopPropagation(),e.preventDefault()},r.readMore.onclick=function(e){e.stopPropagation(),e.preventDefault(),i.widget.toggleDetails()}):(Object(X.D)(r.readMore),r.readMore.onmousedown=null,r.readMore.onclick=null)},e.prototype.disposeTemplate=function(e){e.disposables.dispose()},e=ve([_e(3,fe.a),_e(4,oe.a),_e(5,ne.c)],e)}(),Ee=function(){function e(e,t,n,i,r){var o=this;this.widget=t,this.editor=n,this.markdownRenderer=i,this.triggerKeybindingLabel=r,this.borderWidth=1,this.disposables=new a.b,this.el=Object(X.m)(e,Object(X.a)(".details")),this.disposables.add(Object(a.h)(function(){return e.removeChild(o.el)})),this.body=Object(X.a)(".body"),this.scrollbar=new J.a(this.body,{}),Object(X.m)(this.el,this.scrollbar.getDomNode()),this.disposables.add(this.scrollbar),this.header=Object(X.m)(this.body,Object(X.a)(".header")),this.close=Object(X.m)(this.header,Object(X.a)("span.close")),this.close.title=D.a("readLess","Read less...{0}",this.triggerKeybindingLabel),this.type=Object(X.m)(this.header,Object(X.a)("p.type")),this.docs=Object(X.m)(this.body,Object(X.a)("p.docs")),this.ariaLabel=null,this.configureFont(),j.b.chain(this.editor.onDidChangeConfiguration.bind(this.editor)).filter(function(e){return e.fontInfo}).on(this.configureFont,this,this.disposables),i.onDidRenderCodeBlock(function(){return o.scrollbar.scanDomNode()},this,this.disposables)}return Object.defineProperty(e.prototype,"element",{get:function(){return this.el},enumerable:!0,configurable:!0}),e.prototype.renderLoading=function(){this.type.textContent=D.a("loading","Loading..."),this.docs.textContent=""},e.prototype.renderItem=function(e,t){var n=this;this.renderDisposeable=Object(a.f)(this.renderDisposeable);var i=e.completion,r=i.documentation,o=i.detail;if(t){var s="";s+="score: "+e.score[0]+(e.word?", compared '"+(e.completion.filterText&&e.completion.filterText+" (filterText)"||e.completion.label)+"' with '"+e.word+"'":" (no prefix)")+"\n",s+="distance: "+e.distance+", see localityBonus-setting\n",s+="index: "+e.idx+", based on "+(e.completion.sortText&&'sortText: "'+e.completion.sortText+'"'||"label")+"\n",r=(new ge.a).appendCodeblock("empty",s),o="Provider: "+e.provider._debugDisplayName}if(!t&&!ke(e))return this.type.textContent="",this.docs.textContent="",Object(X.f)(this.el,"no-docs"),void(this.ariaLabel=null);if(Object(X.I)(this.el,"no-docs"),"string"==typeof r)Object(X.I)(this.docs,"markdown-docs"),this.docs.textContent=r;else{Object(X.f)(this.docs,"markdown-docs"),this.docs.innerHTML="";var u=this.markdownRenderer.render(r);this.renderDisposeable=u,this.docs.appendChild(u.element)}o?(this.type.innerText=o,Object(X.Q)(this.type)):(this.type.innerText="",Object(X.D)(this.type)),this.el.style.height=this.header.offsetHeight+this.docs.offsetHeight+2*this.borderWidth+"px",this.close.onmousedown=function(e){e.preventDefault(),e.stopPropagation()},this.close.onclick=function(e){e.preventDefault(),e.stopPropagation(),n.widget.toggleDetails()},this.body.scrollTop=0,this.scrollbar.scanDomNode(),this.ariaLabel=H.r("{0}{1}",o||"",r?"string"==typeof r?r:r.value:"")},e.prototype.getAriaLabel=function(){return this.ariaLabel},e.prototype.scrollDown=function(e){void 0===e&&(e=8),this.body.scrollTop+=e},e.prototype.scrollUp=function(e){void 0===e&&(e=8),this.body.scrollTop-=e},e.prototype.scrollTop=function(){this.body.scrollTop=0},e.prototype.scrollBottom=function(){this.body.scrollTop=this.body.scrollHeight},e.prototype.pageDown=function(){this.scrollDown(80)},e.prototype.pageUp=function(){this.scrollUp(80)},e.prototype.setBorderWidth=function(e){this.borderWidth=e},e.prototype.configureFont=function(){var e=this.editor.getConfiguration(),t=e.fontInfo.fontFamily,n=e.contribInfo.suggestFontSize||e.fontInfo.fontSize,i=e.contribInfo.suggestLineHeight||e.fontInfo.lineHeight,r=e.fontInfo.fontWeight,o=n+"px",s=i+"px";this.el.style.fontSize=o,this.el.style.fontWeight=r,this.type.style.fontFamily=t,this.close.style.height=s,this.close.style.width=s},e.prototype.dispose=function(){this.disposables.dispose(),this.renderDisposeable=Object(a.f)(this.renderDisposeable)},e}(),Ie=function(){function e(e,t,n,i,r,o,s,u,c){var l=this;this.editor=e,this.telemetryService=t,this.allowEditorOverflow=!0,this.suppressMouseDown=!0,this.state=null,this.isAuto=!1,this.loadingTimeout=a.a.None,this.currentSuggestionDetails=null,this.ignoreFocusEvents=!1,this.completionModel=null,this.showTimeout=new v.e,this.toDispose=new a.b,this.onDidSelectEmitter=new j.a,this.onDidFocusEmitter=new j.a,this.onDidHideEmitter=new j.a,this.onDidShowEmitter=new j.a,this.onDidSelect=this.onDidSelectEmitter.event,this.onDidFocus=this.onDidFocusEmitter.event,this.onDidHide=this.onDidHideEmitter.event,this.onDidShow=this.onDidShowEmitter.event,this.maxWidgetWidth=660,this.listWidth=330,this.firstFocusInCurrentList=!1,this.preferDocPositionTop=!1,this.docsPositionPreviousWidgetY=null,this.explainMode=!1,this._lastAriaAlertLabel=null;var d=o.lookupKeybinding("editor.action.triggerSuggest"),h=d?" ("+d.getLabel()+")":"",f=this.toDispose.add(new re.a(e,s,u));this.isAuto=!1,this.focusedItem=null,this.storageService=r,this.element=Object(X.a)(".editor-widget.suggest-widget"),this.toDispose.add(Object(X.h)(this.element,"click",function(e){e.target===l.element&&l.hideWidget()})),this.messageElement=Object(X.m)(this.element,Object(X.a)(".message")),this.listElement=Object(X.m)(this.element,Object(X.a)(".tree")),this.details=c.createInstance(Ee,this.element,this,this.editor,f,h);var p=function(){return Object(X.R)(l.element,"no-icons",!l.editor.getConfiguration().contribInfo.suggest.showIcons)};p();var g=c.createInstance(Ne,this,this.editor,h);this.list=new $.b(this.listElement,this,[g],{useShadows:!1,openController:{shouldOpen:function(){return!1}},mouseSupport:!1}),this.toDispose.add(Object(te.b)(this.list,i,{listInactiveFocusBackground:xe,listInactiveFocusOutline:ie.b})),this.toDispose.add(i.onThemeChange(function(e){return l.onThemeChange(e)})),this.toDispose.add(e.onDidLayoutChange(function(){return l.onEditorLayoutChange()})),this.toDispose.add(this.list.onMouseDown(function(e){return l.onListMouseDown(e)})),this.toDispose.add(this.list.onSelectionChange(function(e){return l.onListSelection(e)})),this.toDispose.add(this.list.onFocusChange(function(e){return l.onListFocus(e)})),this.toDispose.add(this.editor.onDidChangeCursorSelection(function(){return l.onCursorSelectionChanged()})),this.toDispose.add(this.editor.onDidChangeConfiguration(function(e){return e.contribInfo&&p()})),this.suggestWidgetVisible=P.b.Visible.bindTo(n),this.suggestWidgetMultipleSuggestions=P.b.MultipleSuggestions.bindTo(n),this.editor.addContentWidget(this),this.setState(0),this.onThemeChange(i.getTheme())}return e.prototype.onCursorSelectionChanged=function(){0!==this.state&&this.editor.layoutContentWidget(this)},e.prototype.onEditorLayoutChange=function(){3!==this.state&&5!==this.state||!this.expandDocsSettingFromStorage()||this.expandSideOrBelow()},e.prototype.onListMouseDown=function(e){void 0!==e.element&&void 0!==e.index&&(e.browserEvent.preventDefault(),e.browserEvent.stopPropagation(),this.select(e.element,e.index))},e.prototype.onListSelection=function(e){e.elements.length&&this.select(e.elements[0],e.indexes[0])},e.prototype.select=function(e,t){var n=this.completionModel;n&&(this.onDidSelectEmitter.fire({item:e,index:t,model:n}),this.editor.focus())},e.prototype._getSuggestionAriaAlertLabel=function(e){return this.expandDocsSettingFromStorage()?D.a("ariaCurrenttSuggestionReadDetails","Item {0}, docs: {1}",e.completion.label,this.details.getAriaLabel()):e.completion.label},e.prototype._ariaAlert=function(e){this._lastAriaAlertLabel!==e&&(this._lastAriaAlertLabel=e,this._lastAriaAlertLabel&&Object(r.a)(this._lastAriaAlertLabel,!0))},e.prototype.onThemeChange=function(e){var t=e.getColor(we);t&&(this.listElement.style.backgroundColor=t.toString(),this.details.element.style.backgroundColor=t.toString(),this.messageElement.style.backgroundColor=t.toString());var n=e.getColor(Ce);n&&(this.listElement.style.borderColor=n.toString(),this.details.element.style.borderColor=n.toString(),this.messageElement.style.borderColor=n.toString(),this.detailsBorderColor=n.toString());var i=e.getColor(ie.S);i&&(this.detailsFocusBorderColor=i.toString()),this.details.setBorderWidth("hc"===e.type?2:1)},e.prototype.onListFocus=function(e){var t=this;if(!this.ignoreFocusEvents){if(!e.elements.length)return this.currentSuggestionDetails&&(this.currentSuggestionDetails.cancel(),this.currentSuggestionDetails=null,this.focusedItem=null),void this._ariaAlert(null);if(this.completionModel){var n=e.elements[0],i=e.indexes[0];this.firstFocusInCurrentList=!this.focusedItem,n!==this.focusedItem&&(this.currentSuggestionDetails&&(this.currentSuggestionDetails.cancel(),this.currentSuggestionDetails=null),this.focusedItem=n,this.list.reveal(i),this.currentSuggestionDetails=Object(v.f)(function(e){return be(t,void 0,void 0,function(){var t,i,r=this;return ye(this,function(o){switch(o.label){case 0:return t=Object(v.g)(function(){return r.showDetails(!0)},250),e.onCancellationRequested(function(){return t.dispose()}),[4,n.resolve(e)];case 1:return i=o.sent(),t.dispose(),[2,i]}})})}),this.currentSuggestionDetails.then(function(){i>=t.list.length||n!==t.list.element(i)||(t.ignoreFocusEvents=!0,t.list.splice(i,1,[n]),t.list.setFocus([i]),t.ignoreFocusEvents=!1,t.expandDocsSettingFromStorage()?t.showDetails(!1):Object(X.I)(t.element,"docs-side"),t._ariaAlert(t._getSuggestionAriaAlertLabel(n)))}).catch(s.e)),this.onDidFocusEmitter.fire({item:n,index:i,model:this.completionModel})}}},e.prototype.setState=function(t){if(this.element){var n=this.state!==t;switch(this.state=t,Object(X.R)(this.element,"frozen",4===t),t){case 0:Object(X.D)(this.messageElement,this.details.element,this.listElement),this.hide(),this.listHeight=0,n&&this.list.splice(0,this.list.length),this.focusedItem=null;break;case 1:this.messageElement.textContent=e.LOADING_MESSAGE,Object(X.D)(this.listElement,this.details.element),Object(X.Q)(this.messageElement),Object(X.I)(this.element,"docs-side"),this.show(),this.focusedItem=null;break;case 2:this.messageElement.textContent=e.NO_SUGGESTIONS_MESSAGE,Object(X.D)(this.listElement,this.details.element),Object(X.Q)(this.messageElement),Object(X.I)(this.element,"docs-side"),this.show(),this.focusedItem=null;break;case 3:case 4:Object(X.D)(this.messageElement),Object(X.Q)(this.listElement),this.show();break;case 5:Object(X.D)(this.messageElement),Object(X.Q)(this.details.element,this.listElement),this.show(),this._ariaAlert(this.details.getAriaLabel())}}},e.prototype.showTriggered=function(e,t){var n=this;0===this.state&&(this.isAuto=!!e,this.isAuto||(this.loadingTimeout=Object(v.g)(function(){return n.setState(1)},t)))},e.prototype.showSuggestions=function(e,t,n,i){if(this.preferDocPositionTop=!1,this.docsPositionPreviousWidgetY=null,this.loadingTimeout.dispose(),this.currentSuggestionDetails&&(this.currentSuggestionDetails.cancel(),this.currentSuggestionDetails=null),this.completionModel!==e&&(this.completionModel=e),n&&2!==this.state&&0!==this.state)this.setState(4);else{var r=this.completionModel.items.length,o=0===r;if(this.suggestWidgetMultipleSuggestions.set(r>1),o)i?this.setState(0):this.setState(2),this.completionModel=null;else{if(3!==this.state){var s=this.completionModel.stats;s.wasAutomaticallyTriggered=!!i,this.telemetryService.publicLog("suggestWidget",me({},s))}this.focusedItem=null,this.list.splice(0,this.list.length,this.completionModel.items),n?this.setState(4):this.setState(3),this.list.reveal(t,0),this.list.setFocus([t]),this.detailsBorderColor&&(this.details.element.style.borderColor=this.detailsBorderColor)}}},e.prototype.selectNextPage=function(){switch(this.state){case 0:return!1;case 5:return this.details.pageDown(),!0;case 1:return!this.isAuto;default:return this.list.focusNextPage(),!0}},e.prototype.selectNext=function(){switch(this.state){case 0:return!1;case 1:return!this.isAuto;default:return this.list.focusNext(1,!0),!0}},e.prototype.selectLast=function(){switch(this.state){case 0:return!1;case 5:return this.details.scrollBottom(),!0;case 1:return!this.isAuto;default:return this.list.focusLast(),!0}},e.prototype.selectPreviousPage=function(){switch(this.state){case 0:return!1;case 5:return this.details.pageUp(),!0;case 1:return!this.isAuto;default:return this.list.focusPreviousPage(),!0}},e.prototype.selectPrevious=function(){switch(this.state){case 0:return!1;case 1:return!this.isAuto;default:return this.list.focusPrevious(1,!0),!1}},e.prototype.selectFirst=function(){switch(this.state){case 0:return!1;case 5:return this.details.scrollTop(),!0;case 1:return!this.isAuto;default:return this.list.focusFirst(),!0}},e.prototype.getFocusedItem=function(){if(0!==this.state&&2!==this.state&&1!==this.state&&this.completionModel)return{item:this.list.getFocusedElements()[0],index:this.list.getFocus()[0],model:this.completionModel}},e.prototype.toggleDetailsFocus=function(){5===this.state?(this.setState(3),this.detailsBorderColor&&(this.details.element.style.borderColor=this.detailsBorderColor)):3===this.state&&this.expandDocsSettingFromStorage()&&(this.setState(5),this.detailsFocusBorderColor&&(this.details.element.style.borderColor=this.detailsFocusBorderColor)),this.telemetryService.publicLog2("suggestWidget:toggleDetailsFocus")},e.prototype.toggleDetails=function(){if(ke(this.list.getFocusedElements()[0]))if(this.expandDocsSettingFromStorage())this.updateExpandDocsSetting(!1),Object(X.D)(this.details.element),Object(X.I)(this.element,"docs-side"),Object(X.I)(this.element,"docs-below"),this.editor.layoutContentWidget(this),this.telemetryService.publicLog2("suggestWidget:collapseDetails");else{if(3!==this.state&&5!==this.state&&4!==this.state)return;this.updateExpandDocsSetting(!0),this.showDetails(!1),this._ariaAlert(this.details.getAriaLabel()),this.telemetryService.publicLog2("suggestWidget:expandDetails")}},e.prototype.showDetails=function(e){this.expandSideOrBelow(),Object(X.Q)(this.details.element),this.details.element.style.maxHeight=this.maxWidgetHeight+"px",e?this.details.renderLoading():this.details.renderItem(this.list.getFocusedElements()[0],this.explainMode),this.listElement.style.marginTop="0px",this.editor.layoutContentWidget(this),this.adjustDocsPosition(),this.editor.focus()},e.prototype.toggleExplainMode=function(){this.list.getFocusedElements()[0]&&this.expandDocsSettingFromStorage()&&(this.explainMode=!this.explainMode,this.showDetails(!1))},e.prototype.show=function(){var e=this,t=this.updateListHeight();t!==this.listHeight&&(this.editor.layoutContentWidget(this),this.listHeight=t),this.suggestWidgetVisible.set(!0),this.showTimeout.cancelAndSet(function(){Object(X.f)(e.element,"visible"),e.onDidShowEmitter.fire(e)},100)},e.prototype.hide=function(){this.suggestWidgetVisible.reset(),this.suggestWidgetMultipleSuggestions.reset(),Object(X.I)(this.element,"visible")},e.prototype.hideWidget=function(){this.loadingTimeout.dispose(),this.setState(0),this.onDidHideEmitter.fire(this)},e.prototype.getPosition=function(){if(0===this.state)return null;var e=[2,1];return this.preferDocPositionTop&&(e=[1]),{position:this.editor.getPosition(),preference:e}},e.prototype.getDomNode=function(){return this.element},e.prototype.getId=function(){return e.ID},e.prototype.updateListHeight=function(){var e=0;if(2===this.state||1===this.state)e=this.unfocusedHeight;else{var t=this.list.contentHeight/this.unfocusedHeight,n=this.editor.getConfiguration().contribInfo.suggest.maxVisibleSuggestions;e=Math.min(t,n)*this.unfocusedHeight}return this.element.style.lineHeight=this.unfocusedHeight+"px",this.listElement.style.height=e+"px",this.list.layout(e),e},e.prototype.adjustDocsPosition=function(){if(this.editor.hasModel()){var e=this.editor.getConfiguration().fontInfo.lineHeight,t=this.editor.getScrolledVisiblePosition(this.editor.getPosition()),n=Object(X.x)(this.editor.getDomNode()),i=n.left+t.left,r=n.top+t.top+t.height,o=Object(X.x)(this.element),s=o.left,a=o.top;if(this.docsPositionPreviousWidgetY&&this.docsPositionPreviousWidgetYa&&this.details.element.offsetHeight>this.listElement.offsetHeight&&(this.listElement.style.marginTop=this.details.element.offsetHeight-this.listElement.offsetHeight+"px")}},e.prototype.expandSideOrBelow=function(){if(!ke(this.focusedItem)&&this.firstFocusInCurrentList)return Object(X.I)(this.element,"docs-side"),void Object(X.I)(this.element,"docs-below");var e=this.element.style.maxWidth.match(/(\d+)px/);!e||Number(e[1])=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},Te=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Pe=function(e){function t(n,i){var r=e.call(this)||this;return r._editor=n,r._enabled=!1,r._ckAtEnd=t.AtEnd.bindTo(i),r._register(r._editor.onDidChangeConfiguration(function(e){return e.contribInfo&&r._update()})),r._update(),r}return De(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),Object(a.f)(this._selectionListener),this._ckAtEnd.reset()},t.prototype._update=function(){var e=this,t="on"===this._editor.getConfiguration().contribInfo.tabCompletion;if(this._enabled!==t)if(this._enabled=t,this._enabled){var n=function(){if(e._editor.hasModel()){var t=e._editor.getModel(),n=e._editor.getSelection(),i=t.getWordAtPosition(n.getStartPosition());i?e._ckAtEnd.set(i.endColumn===n.getStartPosition().column):e._ckAtEnd.set(!1)}else e._ckAtEnd.set(!1)};this._selectionListener=this._editor.onDidChangeCursorSelection(n),n()}else this._selectionListener&&(this._ckAtEnd.reset(),this._selectionListener.dispose(),this._selectionListener=void 0)},t.AtEnd=new T.d("atEndOfWord",!1),t=Me([Te(1,T.c)],t)}(a.a),Ae=n("606G"),Re=n("KIxu"),Fe=n("GfE5"),je=function(){function e(e,t,n){var i=this;this._disposables=new a.b,this._disposables.add(t.onDidShow(function(){return i._onItem(t.getFocusedItem())})),this._disposables.add(t.onDidFocus(this._onItem,this)),this._disposables.add(t.onDidHide(this.reset,this)),this._disposables.add(e.onWillType(function(t){if(i._active){var r=t.charCodeAt(t.length-1);i._active.acceptCharacters.has(r)&&e.getConfiguration().contribInfo.acceptSuggestionOnCommitCharacter&&n(i._active.item)}}))}return e.prototype._onItem=function(e){if(e&&Object(o.n)(e.item.completion.commitCharacters)){if(!this._active||this._active.item.item!==e.item){for(var t=new Fe.b,n=0,i=e.item.completion.commitCharacters;n0&&t.add(r.charCodeAt(0))}this._active={acceptCharacters:t,item:e}}}else this.reset()},e.prototype.reset=function(){this._active=void 0},e.prototype.dispose=function(){this._disposables.dispose()},e}();n.d(t,"SuggestController",function(){return Ke}),n.d(t,"TriggerSuggestAction",function(){return qe});var We=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Be=this&&this.__assign||function(){return(Be=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},He=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ze=!1,Ue=function(){function e(e,t){if(this._model=e,this._position=t,e.getLineMaxColumn(t.lineNumber)!==t.column){var n=e.getOffsetAt(t),i=e.getPositionAt(n+1);this._marker=e.deltaDecorations([],[{range:l.a.fromPositions(t,i),options:{stickiness:1}}])}}return e.prototype.dispose=function(){this._marker&&!this._model.isDisposed()&&this._model.deltaDecorations(this._marker,[])},e.prototype.delta=function(e){if(this._model.isDisposed()||this._position.lineNumber!==e.lineNumber)return 0;if(this._marker){var t=this._model.getDecorationRange(this._marker[0]);return this._model.getOffsetAt(t.getStartPosition())-this._model.getOffsetAt(e)}return this._model.getLineMaxColumn(e.lineNumber)-e.column},e}(),Ke=function(){function e(e,t,n,i,r,o){var s=this;this._editor=e,this._memoryService=n,this._commandService=i,this._contextKeyService=r,this._instantiationService=o,this._lineSuffix=new a.d,this._toDispose=new a.b,this._model=new Y(this._editor,t),this._widget=new v.b(function(){var e=s._instantiationService.createInstance(Ie,s._editor);s._toDispose.add(e),s._toDispose.add(e.onDidSelect(function(e){return s._insertSuggestion(e,!1,!0)},s));var t=new je(s._editor,e,function(e){return s._insertSuggestion(e,!1,!0)});s._toDispose.add(t),s._toDispose.add(s._model.onDidSuggest(function(e){0===e.completionModel.items.length&&t.reset()}));var n=P.b.MakesTextEdit.bindTo(s._contextKeyService);return s._toDispose.add(e.onDidFocus(function(e){var t=e.item,i=s._editor.getPosition(),r=t.completion.range.startColumn,o=i.column,a=!0;"smart"!==s._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter||2!==s._model.state||t.completion.command||t.completion.additionalTextEdits||4&t.completion.insertTextRules||o-r!==t.completion.insertText.length||(a=s._editor.getModel().getValueInRange({startLineNumber:i.lineNumber,startColumn:r,endLineNumber:i.lineNumber,endColumn:o})!==t.completion.insertText);n.set(a)})),s._toDispose.add(Object(a.h)(function(){return n.reset()})),e}),this._alternatives=new v.b(function(){return s._toDispose.add(new F(s._editor,s._contextKeyService))}),this._toDispose.add(o.createInstance(Pe,e)),this._toDispose.add(this._model.onDidTrigger(function(e){s._widget.getValue().showTriggered(e.auto,e.shy?250:50),s._lineSuffix.value=new Ue(s._editor.getModel(),e.position)})),this._toDispose.add(this._model.onDidSuggest(function(e){if(!e.shy){var t=s._memoryService.select(s._editor.getModel(),s._editor.getPosition(),e.completionModel.items);s._widget.getValue().showSuggestions(e.completionModel,t,e.isFrozen,e.auto)}})),this._toDispose.add(this._model.onDidCancel(function(e){e.retrigger||s._widget.getValue().hideWidget()})),this._toDispose.add(this._editor.onDidBlurEditorWidget(function(){ze||(s._model.cancel(),s._model.clear())}));var u=P.b.AcceptSuggestionsOnEnter.bindTo(r),c=function(){var e=s._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter;u.set("on"===e||"smart"===e)};this._toDispose.add(this._editor.onDidChangeConfiguration(function(){return c()})),c()}return e.get=function(t){return t.getContribution(e.ID)},e.prototype.getId=function(){return e.ID},e.prototype.dispose=function(){this._alternatives.dispose(),this._toDispose.dispose(),this._widget.dispose(),this._model.dispose(),this._lineSuffix.dispose()},e.prototype._insertSuggestion=function(e,t,n){var i,r=this;if(!e||!e.item)return this._alternatives.getValue().reset(),this._model.cancel(),void this._model.clear();if(this._editor.hasModel()){var o=this._editor.getModel(),a=o.getAlternativeVersionId(),u=e.item,d=u.completion,p=u.position,g=this._editor.getPosition().column-p.column;n&&this._editor.pushUndoStop(),Array.isArray(d.additionalTextEdits)&&this._editor.executeEdits("suggestController.additionalTextEdits",d.additionalTextEdits.map(function(e){return c.a.replace(l.a.lift(e.range),e.text)})),this._memoryService.memorize(o,this._editor.getPosition(),e.item);var m=d.insertText;4&d.insertTextRules||(m=f.c.escape(m));var v=p.column-d.range.startColumn,_=d.range.endColumn-p.column,b=this._lineSuffix.value?this._lineSuffix.value.delta(this._editor.getPosition()):0;h.SnippetController2.get(this._editor).insert(m,{overwriteBefore:v+g,overwriteAfter:_+b,undoStopBefore:!1,undoStopAfter:!1,adjustWhitespace:!(1&d.insertTextRules)}),n&&this._editor.pushUndoStop(),d.command?d.command.id===qe.id?this._model.trigger({auto:!0,shy:!1},!0):((i=this._commandService).executeCommand.apply(i,[d.command.id].concat(d.command.arguments?d.command.arguments.slice():[])).catch(s.e).finally(function(){return r._model.clear()}),this._model.cancel()):(this._model.cancel(),this._model.clear()),t&&this._alternatives.getValue().set(e,function(e){for(;o.canUndo();){a!==o.getAlternativeVersionId()&&o.undo(),r._insertSuggestion(e,!1,!1);break}}),this._alertCompletionItem(e.item)}},e.prototype._alertCompletionItem=function(e){var t=e.completion;if(Object(o.n)(t.additionalTextEdits)){var n=D.a("arai.alert.snippet","Accepting '{0}' made {1} additional edits",t.label,t.additionalTextEdits.length);Object(r.a)(n)}},e.prototype.triggerSuggest=function(e){this._editor.hasModel()&&(this._model.trigger({auto:!1,shy:!1},!1,e),this._editor.revealLine(this._editor.getPosition().lineNumber,0),this._editor.focus())},e.prototype.triggerSuggestAndAcceptBest=function(e){var t=this;if(this._editor.hasModel()){var n=this._editor.getPosition(),i=function(){n.equals(t._editor.getPosition())&&t._commandService.executeCommand(e.fallback)};j.b.once(this._model.onDidTrigger)(function(e){var n=[];j.b.any(t._model.onDidTrigger,t._model.onDidCancel)(function(){Object(a.f)(n),i()},void 0,n),t._model.onDidSuggest(function(e){var r=e.completionModel;if(Object(a.f)(n),0!==r.items.length){var o=t._memoryService.select(t._editor.getModel(),t._editor.getPosition(),r.items),s=r.items[o];!function(e){if(4&e.completion.insertTextRules||e.completion.additionalTextEdits)return!0;var n=t._editor.getPosition(),i=e.completion.range.startColumn,r=n.column;return r-i!==e.completion.insertText.length||t._editor.getModel().getValueInRange({startLineNumber:n.lineNumber,startColumn:i,endLineNumber:n.lineNumber,endColumn:r})!==e.completion.insertText}(s)?i():(t._editor.pushUndoStop(),t._insertSuggestion({index:o,item:s,model:r},!0,!1))}else i()},void 0,n)}),this._model.trigger({auto:!1,shy:!0}),this._editor.revealLine(n.lineNumber,0),this._editor.focus()}},e.prototype.acceptSelectedSuggestion=function(e){var t=this._widget.getValue().getFocusedItem();this._insertSuggestion(t,!!e,!0)},e.prototype.acceptNextSuggestion=function(){this._alternatives.getValue().next()},e.prototype.acceptPrevSuggestion=function(){this._alternatives.getValue().prev()},e.prototype.cancelSuggestWidget=function(){this._model.cancel(),this._model.clear(),this._widget.getValue().hideWidget()},e.prototype.selectNextSuggestion=function(){this._widget.getValue().selectNext()},e.prototype.selectNextPageSuggestion=function(){this._widget.getValue().selectNextPage()},e.prototype.selectLastSuggestion=function(){this._widget.getValue().selectLast()},e.prototype.selectPrevSuggestion=function(){this._widget.getValue().selectPrevious()},e.prototype.selectPrevPageSuggestion=function(){this._widget.getValue().selectPreviousPage()},e.prototype.selectFirstSuggestion=function(){this._widget.getValue().selectFirst()},e.prototype.toggleSuggestionDetails=function(){this._widget.getValue().toggleDetails()},e.prototype.toggleExplainMode=function(){this._widget.getValue().toggleExplainMode()},e.prototype.toggleSuggestionFocus=function(){this._widget.getValue().toggleDetailsFocus()},e.ID="editor.contrib.suggestController",e=Ve([He(1,Ae.a),He(2,E),He(3,M.b),He(4,T.c),He(5,_.a)],e)}(),qe=function(e){function t(){return e.call(this,{id:t.id,label:D.a("suggest.trigger.label","Trigger Suggest"),alias:"Trigger Suggest",precondition:T.a.and(d.a.writable,d.a.hasCompletionItemProvider),kbOpts:{kbExpr:d.a.textInputFocus,primary:2058,mac:{primary:266},weight:100}})||this}return We(t,e),t.prototype.run=function(e,t){var n=Ke.get(t);n&&n.triggerSuggest()},t.id="editor.action.triggerSuggest",t}(u.b);Object(u.h)(Ke),Object(u.f)(qe);var Ge=u.c.bindToContribution(Ke.get);Object(u.g)(new Ge({id:"acceptSelectedSuggestion",precondition:P.b.Visible,handler:function(e){return e.acceptSelectedSuggestion(!0)},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2}})),Object(u.g)(new Ge({id:"acceptSelectedSuggestionOnEnter",precondition:P.b.Visible,handler:function(e){return e.acceptSelectedSuggestion(!1)},kbOpts:{weight:190,kbExpr:T.a.and(d.a.textInputFocus,P.b.AcceptSuggestionsOnEnter,P.b.MakesTextEdit),primary:3}})),Object(u.g)(new Ge({id:"hideSuggestWidget",precondition:P.b.Visible,handler:function(e){return e.cancelSuggestWidget()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:9,secondary:[1033]}})),Object(u.g)(new Ge({id:"selectNextSuggestion",precondition:T.a.and(P.b.Visible,P.b.MultipleSuggestions),handler:function(e){return e.selectNextSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:18,secondary:[2066],mac:{primary:18,secondary:[2066,300]}}})),Object(u.g)(new Ge({id:"selectNextPageSuggestion",precondition:T.a.and(P.b.Visible,P.b.MultipleSuggestions),handler:function(e){return e.selectNextPageSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:12,secondary:[2060]}})),Object(u.g)(new Ge({id:"selectLastSuggestion",precondition:T.a.and(P.b.Visible,P.b.MultipleSuggestions),handler:function(e){return e.selectLastSuggestion()}})),Object(u.g)(new Ge({id:"selectPrevSuggestion",precondition:T.a.and(P.b.Visible,P.b.MultipleSuggestions),handler:function(e){return e.selectPrevSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:16,secondary:[2064],mac:{primary:16,secondary:[2064,302]}}})),Object(u.g)(new Ge({id:"selectPrevPageSuggestion",precondition:T.a.and(P.b.Visible,P.b.MultipleSuggestions),handler:function(e){return e.selectPrevPageSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:11,secondary:[2059]}})),Object(u.g)(new Ge({id:"selectFirstSuggestion",precondition:T.a.and(P.b.Visible,P.b.MultipleSuggestions),handler:function(e){return e.selectFirstSuggestion()}})),Object(u.g)(new Ge({id:"toggleSuggestionDetails",precondition:P.b.Visible,handler:function(e){return e.toggleSuggestionDetails()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2058,mac:{primary:266}}})),Object(u.g)(new Ge({id:"toggleExplainMode",precondition:P.b.Visible,handler:function(e){return e.toggleExplainMode()},kbOpts:{weight:100,primary:2133}})),Object(u.g)(new Ge({id:"toggleSuggestionFocus",precondition:P.b.Visible,handler:function(e){return e.toggleSuggestionFocus()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2570,mac:{primary:778}}})),Object(u.g)(new Ge({id:"insertBestCompletion",precondition:T.a.and(T.a.equals("config.editor.tabCompletion","on"),Pe.AtEnd,P.b.Visible.toNegated(),F.OtherSuggestions.toNegated(),h.SnippetController2.InSnippetMode.toNegated()),handler:function(e,t){e.triggerSuggestAndAcceptBest(Object(Re.h)(t)?Be({fallback:"tab"},t):{fallback:"tab"})},kbOpts:{weight:190,primary:2}})),Object(u.g)(new Ge({id:"insertNextSuggestion",precondition:T.a.and(T.a.equals("config.editor.tabCompletion","on"),F.OtherSuggestions,P.b.Visible.toNegated(),h.SnippetController2.InSnippetMode.toNegated()),handler:function(e){return e.acceptNextSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2}})),Object(u.g)(new Ge({id:"insertPrevSuggestion",precondition:T.a.and(T.a.equals("config.editor.tabCompletion","on"),F.OtherSuggestions,P.b.Visible.toNegated(),h.SnippetController2.InSnippetMode.toNegated()),handler:function(e){return e.acceptPrevSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:1026}}))},"7dSG":function(e,t,n){"use strict";(function(t,i){var r=n("ypnx");function o(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var i=e.entry;e.entry=null;for(;i;){var r=i.callback;t.pendingcb--,r(n),i=i.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}(t,e)}}e.exports=v;var s,a=!t.browser&&["v0.10","v0.9."].indexOf(t.version.slice(0,5))>-1?setImmediate:r.nextTick;v.WritableState=m;var u=n("jOgh");u.inherits=n("LC74");var c={deprecate:n("iP15")},l=n("UcPO"),d=n("kkc6").Buffer,h=i.Uint8Array||function(){};var f,p=n("x0Ha");function g(){}function m(e,t){s=s||n("DsFX"),e=e||{};var i=t instanceof s;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var u=e.highWaterMark,c=e.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=u||0===u?u:i&&(c||0===c)?c:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var d=!1===e.decodeStrings;this.decodeStrings=!d,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,i=n.sync,o=n.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,i,o){--t.pendingcb,n?(r.nextTick(o,i),r.nextTick(S,e,t),e._writableState.errorEmitted=!0,e.emit("error",i)):(o(i),e._writableState.errorEmitted=!0,e.emit("error",i),S(e,t))}(e,n,i,t,o);else{var s=w(n);s||n.corked||n.bufferProcessing||!n.bufferedRequest||y(e,n),i?a(b,e,n,s,o):b(e,n,s,o)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function v(e){if(s=s||n("DsFX"),!(f.call(v,this)||this instanceof s))return new v(e);this._writableState=new m(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),l.call(this)}function _(e,t,n,i,r,o,s){t.writelen=i,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(r,t.onwrite):e._write(r,o,t.onwrite),t.sync=!1}function b(e,t,n,i){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,i(),S(e,t)}function y(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var i=t.bufferedRequestCount,r=new Array(i),s=t.corkedRequestsFree;s.entry=n;for(var a=0,u=!0;n;)r[a]=n,n.isBuf||(u=!1),n=n.next,a+=1;r.allBuffers=u,_(e,t,!0,t.length,r,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var c=n.chunk,l=n.encoding,d=n.callback;if(_(e,t,!1,t.objectMode?1:c.length,c,l,d),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function w(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function C(e,t){e._final(function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),S(e,t)})}function S(e,t){var n=w(t);return n&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,r.nextTick(C,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}u.inherits(v,l),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(f=Function.prototype[Symbol.hasInstance],Object.defineProperty(v,Symbol.hasInstance,{value:function(e){return!!f.call(this,e)||this===v&&(e&&e._writableState instanceof m)}})):f=function(e){return e instanceof this},v.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},v.prototype.write=function(e,t,n){var i,o=this._writableState,s=!1,a=!o.objectMode&&(i=e,d.isBuffer(i)||i instanceof h);return a&&!d.isBuffer(e)&&(e=function(e){return d.from(e)}(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof n&&(n=g),o.ended?function(e,t){var n=new Error("write after end");e.emit("error",n),r.nextTick(t,n)}(this,n):(a||function(e,t,n,i){var o=!0,s=!1;return null===n?s=new TypeError("May not write null values to stream"):"string"==typeof n||void 0===n||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),r.nextTick(i,s),o=!1),o}(this,o,e,n))&&(o.pendingcb++,s=function(e,t,n,i,r,o){if(!n){var s=function(e,t,n){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=d.from(t,n));return t}(t,i,r);i!==s&&(n=!0,r="buffer",i=s)}var a=t.objectMode?1:i.length;t.length+=a;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(v.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),v.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},v.prototype._writev=null,v.prototype.end=function(e,t,n){var i=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(e,t,n){t.ending=!0,S(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n)},Object.defineProperty(v.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),v.prototype.destroy=p.destroy,v.prototype._undestroy=p.undestroy,v.prototype._destroy=function(e,t){this.end(),t(e)}}).call(t,n("W2nU"),n("DuR2"))},"7flL":function(e,t,n){var i=n("q5VG"),r=n("X3l8").Buffer,o=n("VI/i"),s=n("annC"),a=n("OMJi"),u="secret must be a string or buffer",c="key must be a string or a buffer",l="key must be a string, a buffer or an object",d="function"==typeof o.createPublicKey;function h(e){if(!r.isBuffer(e)&&"string"!=typeof e){if(!d)throw m(c);if("object"!=typeof e)throw m(c);if("string"!=typeof e.type)throw m(c);if("string"!=typeof e.asymmetricKeyType)throw m(c);if("function"!=typeof e.export)throw m(c)}}function f(e){if(!r.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw m(l)}function p(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function g(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var n=0;n=0){var n=e.split("!=");return d.create(n[0].trim(),this._deserializeValue(n[1],t))}if(e.indexOf("==")>=0){n=e.split("==");return l.create(n[0].trim(),this._deserializeValue(n[1],t))}if(e.indexOf("=~")>=0){n=e.split("=~");return f.create(n[0].trim(),this._deserializeRegexValue(n[1],t))}return/^\!\s*/.test(e)?h.create(e.substr(1).trim()):c.create(e)},e._deserializeValue=function(e,t){if("true"===(e=e.trim()))return!0;if("false"===e)return!1;var n=/^'([^']*)'$/.exec(e);return n?n[1].trim():e},e._deserializeRegexValue=function(e,t){if(Object(r.u)(e)){if(t)throw new Error("missing regexp-value for =~-expression");return console.warn("missing regexp-value for =~-expression"),null}var n=e.indexOf("/"),i=e.lastIndexOf("/");if(n===i||n<0){if(t)throw new Error("bad regexp-value '"+e+"', missing /-enclosure");return console.warn("bad regexp-value '"+e+"', missing /-enclosure"),null}var o=e.slice(n+1,i),s="i"===e[i+1]?"i":"";try{return new RegExp(o,s)}catch(n){if(t)throw new Error("bad regexp-value '"+e+"', parse error: "+n);return console.warn("bad regexp-value '"+e+"', parse error: "+n),null}},e}();function u(e,t){var n=e.getType(),i=t.getType();if(n!==i)return n-i;switch(n){case 1:case 2:case 3:case 4:case 6:case 7:case 5:return e.cmp(t);default:throw new Error("Unknown ContextKeyExpr!")}}var c=function(){function e(e){this.key=e}return e.create=function(t){return new e(t)},e.prototype.getType=function(){return 1},e.prototype.cmp=function(e){return this.keye.key?1:0},e.prototype.equals=function(t){return t instanceof e&&this.key===t.key},e.prototype.evaluate=function(e){return!!e.getValue(this.key)},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return h.create(this.key)},e}(),l=function(){function e(e,t){this.key=e,this.value=t}return e.create=function(t,n){return"boolean"==typeof n?n?c.create(t):h.create(t):new e(t,n)},e.prototype.getType=function(){return 3},e.prototype.cmp=function(e){return this.keye.key?1:this.valuee.value?1:0},e.prototype.equals=function(t){return t instanceof e&&(this.key===t.key&&this.value===t.value)},e.prototype.evaluate=function(e){return e.getValue(this.key)==this.value},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return d.create(this.key,this.value)},e}(),d=function(){function e(e,t){this.key=e,this.value=t}return e.create=function(t,n){return"boolean"==typeof n?n?h.create(t):c.create(t):new e(t,n)},e.prototype.getType=function(){return 4},e.prototype.cmp=function(e){return this.keye.key?1:this.valuee.value?1:0},e.prototype.equals=function(t){return t instanceof e&&(this.key===t.key&&this.value===t.value)},e.prototype.evaluate=function(e){return e.getValue(this.key)!=this.value},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return l.create(this.key,this.value)},e}(),h=function(){function e(e){this.key=e}return e.create=function(t){return new e(t)},e.prototype.getType=function(){return 2},e.prototype.cmp=function(e){return this.keye.key?1:0},e.prototype.equals=function(t){return t instanceof e&&this.key===t.key},e.prototype.evaluate=function(e){return!e.getValue(this.key)},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return c.create(this.key)},e}(),f=function(){function e(e,t){this.key=e,this.regexp=t}return e.create=function(t,n){return new e(t,n)},e.prototype.getType=function(){return 6},e.prototype.cmp=function(e){if(this.keye.key)return 1;var t=this.regexp?this.regexp.source:"",n=e.regexp?e.regexp.source:"";return tn?1:0},e.prototype.equals=function(t){if(t instanceof e){var n=this.regexp?this.regexp.source:"",i=t.regexp?t.regexp.source:"";return this.key===t.key&&n===i}return!1},e.prototype.evaluate=function(e){var t=e.getValue(this.key);return!!this.regexp&&this.regexp.test(t)},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return p.create(this)},e}(),p=function(){function e(e){this._actual=e}return e.create=function(t){return new e(t)},e.prototype.getType=function(){return 7},e.prototype.cmp=function(e){return this._actual.cmp(e._actual)},e.prototype.equals=function(t){return t instanceof e&&this._actual.equals(t._actual)},e.prototype.evaluate=function(e){return!this._actual.evaluate(e)},e.prototype.keys=function(){return this._actual.keys()},e.prototype.negate=function(){return this._actual},e}(),g=function(){function e(e){this.expr=e}return e.create=function(t){var n=e._normalizeArr(t);if(0!==n.length)return 1===n.length?n[0]:new e(n)},e.prototype.getType=function(){return 5},e.prototype.cmp=function(e){if(this.expr.lengthe.expr.length)return 1;for(var t=0,n=this.expr.length;t1;){for(var s=t.shift(),u=t.shift(),c=[],l=0,d=o(s);l0&&(n._decorations=n._editor.deltaDecorations(n._decorations,[])),n._updateBracketsSoon.schedule()})),n}return _(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype.getId=function(){return t.ID},t.prototype.jumpToBracket=function(){if(this._editor.hasModel()){var e=this._editor.getModel(),t=this._editor.getSelections().map(function(t){var n=t.getStartPosition(),i=e.matchBracket(n),r=null;if(i)i[0].containsPosition(n)?r=i[1].getStartPosition():i[1].containsPosition(n)&&(r=i[0].getStartPosition());else{var o=e.findNextBracket(n);o&&o.range&&(r=o.range.getStartPosition())}return r?new l.a(r.lineNumber,r.column,r.lineNumber,r.column):new l.a(n.lineNumber,n.column,n.lineNumber,n.column)});this._editor.setSelections(t),this._editor.revealRange(t[0])}},t.prototype.selectToBracket=function(){if(this._editor.hasModel()){var e=this._editor.getModel(),t=[];this._editor.getSelections().forEach(function(n){var i=n.getStartPosition(),r=e.matchBracket(i),o=null,s=null;if(!r){var a=e.findNextBracket(i);a&&a.range&&(r=e.matchBracket(a.range.getStartPosition()))}r&&(r[0].startLineNumber===r[1].startLineNumber?(o=r[1].startColumn0&&(this._editor.setSelections(t),this._editor.revealRange(t[0]))}},t.prototype._updateBrackets=function(){if(this._matchBrackets){this._recomputeBrackets();for(var e=[],n=0,i=0,r=this._lastBracketsData.length;i1&&r.sort(c.a.compare);var l=[],d=0,h=0,f=n.length;for(s=0,a=r.length;s0&&void 0!==arguments[0]&&arguments[0];var e=[].concat(r()(this.provider));return"sql"===this.lang&&e.push.apply(e,r()(this.sqlHints)),e},registerCustomHintsProvider:function(){var e=this;this.providerDisposeID=o.languages.registerCompletionItemProvider(this.lang,{provideCompletionItems:function(t,n,i){var r=t.getWordUntilPosition(n);return{suggestions:function(e,t,n){n.word;var i=[];return e.length&&(i=e.map(function(e){return{label:e.name,kind:e.type?o.languages.CompletionItemKind[e.type]:o.languages.CompletionItemKind.Function,documentation:e.documentation,insertText:(n=e.name,n),detail:e.detail||"EMQX",range:t};var n})),i}(e.getHints(r),{startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:r.startColumn,endColumn:r.endColumn},r)}},triggerCharacters:[" "]})},registerCustomHoverProvider:function(){var e=this;o.languages.register({id:this.lang}),this.hoverDisposeID=o.languages.registerHoverProvider(this.lang,{provideHover:function(t,n){if(!t.getWordAtPosition(n))return{};var i,r,o,s=t.getWordAtPosition(n).word;return{contents:(i=s,r=e.provider,o=[],r.forEach(function(e){var t=e.name;e.name.match(/\$events\//)&&(t=e.name.split("/")[1].replace('"',"")),i===t&&o.push({value:function(e){var t=e.name,n=e.default,i=e.valueType;return i&&(t=t+": "+i),n?t+", value: "+n:t}(e)},{value:e.documentation})}),o)}}})}},mounted:function(){this.initEditor()},created:function(){var e=this;this.defineTheme(),window.onresize=function(){e.editor&&e.editor.layout()},this.provider.length&&(this.registerCustomHintsProvider(),this.registerCustomHoverProvider())},beforeDestroy:function(){this.editor&&(this.editor.getModel().dispose(),this.editor.dispose(),this.editor=null),this.providerDisposeID&&this.providerDisposeID.dispose(),this.hoverDisposeID&&this.hoverDisposeID.dispose()}},c={render:function(){var e=this.$createElement;return(this._self._c||e)("div",{staticClass:"monaco-view",attrs:{id:"monaco-"+this.id}})},staticRenderFns:[]};var l=n("VU/8")(u,c,!1,function(e){n("1Ccl")},null,null);t.a=l.exports},"9Io0":function(e,t,n){var i=n("X3l8").Buffer,r=n("sDkV"),o=n("7flL"),s=n("9DG0"),a=n("nOGB"),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(e))return e;try{return JSON.parse(e)}catch(e){return}}function l(e){var t=e.split(".",1)[0];return c(i.from(t,"base64").toString("binary"))}function d(e){return e.split(".")[2]}function h(e){return u.test(e)&&!!l(e)}function f(e,t,n){if(!t){var i=new Error("Missing algorithm parameter for jws.verify");throw i.code="MISSING_ALGORITHM",i}var r=d(e=a(e)),s=function(e){return e.split(".",2).join(".")}(e);return o(t).verify(s,r,n)}function p(e,t){if(t=t||{},!h(e=a(e)))return null;var n=l(e);if(!n)return null;var r=function(e,t){t=t||"utf8";var n=e.split(".")[1];return i.from(n,"base64").toString(t)}(e);return("JWT"===n.typ||t.json)&&(r=JSON.parse(r,t.encoding)),{header:n,payload:r,signature:d(e)}}function g(e){var t=(e=e||{}).secret||e.publicKey||e.key,n=new r(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=n,this.signature=new r(e.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}n("OMJi").inherits(g,s),g.prototype.verify=function(){try{var e=f(this.signature.buffer,this.algorithm,this.key.buffer),t=p(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},g.decode=p,g.isValid=h,g.verify=f,e.exports=g},"9P96":function(e,t,n){t.publicEncrypt=n("9hYg"),t.privateDecrypt=n("fxuI"),t.privateEncrypt=function(e,n){return t.publicEncrypt(e,n,!0)},t.publicDecrypt=function(e,n){return t.privateDecrypt(e,n,!0)}},"9XyG":function(e,t,n){"use strict";n.d(t,"a",function(){return u}),n.d(t,"c",function(){return c}),n.d(t,"b",function(){return l});var i=n("hK2W"),r=n("Kp7x"),o=n("PCC9"),s=n("Fllr"),a=n("RWr8"),u=new(function(){function e(){this._onDidChangeLanguages=new r.a,this.onDidChangeLanguages=this._onDidChangeLanguages.event,this._languages=[],this._dynamicLanguages=[]}return e.prototype.registerLanguage=function(e){this._languages.push(e),this._onDidChangeLanguages.fire(void 0)},e.prototype.getLanguages=function(){return[].concat(this._languages).concat(this._dynamicLanguages)},e}());a.a.add("editor.modesRegistry",u);var c="plaintext",l=new o.p(c,1);u.registerLanguage({id:c,extensions:[".txt",".gitignore"],aliases:[i.a("plainText.alias","Plain Text"),"text"],mimetypes:["text/plain"]}),s.a.register(l,{brackets:[["(",")"],["[","]"],["{","}"]]})},"9bHL":function(e,t,n){"use strict";var i=n("TU7t"),r=n("tqet"),o=n("Bug4"),s=n("7/Cv"),a=n("Kp7x"),u=n("Gxst"),c=n("qecS"),l=n("vbff");function d(e,t){for(var n=[],i=0,r=t;i=o.range.end)){if(e.end=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},C={useShadows:!0,verticalScrollMode:1,setRowLineHeight:!0,supportDynamicHeights:!1,dnd:{getDragElements:function(e){return[e]},getDragURI:function(){return null},onDragStart:function(){},onDragOver:function(){return!1},drop:function(){}},horizontalScrolling:!1},S=function(){function e(e){this.elements=e}return e.prototype.update=function(){},e.prototype.getData=function(){return this.elements},e}(),x=function(){function e(e){this.elements=e}return e.prototype.update=function(){},e.prototype.getData=function(){return this.elements},e}(),L=function(){function e(){this.types=[],this.files=[]}return e.prototype.update=function(e){var t;if(e.types&&(t=this.types).splice.apply(t,[0,this.types.length].concat(e.types)),e.files){this.files.splice(0,this.files.length);for(var n=0;n=this.items.length?(this.rangeMap=new f,this.rangeMap.splice(0,0,v),this.items=v,d=[]):(this.rangeMap.splice(e,t,v),d=(i=this.items).splice.apply(i,[e,t].concat(v)));var _=n.length-t,b=this.getRenderRange(this.lastRenderTop,this.lastRenderHeight),y=h(g,_),w=l.a.intersect(b,y);for(c=w.start;c=-1&&en&&(this.scrollTop+=Math.min(14,Math.floor(.3*(t-n))))}},e.prototype.teardownDragAndDropScrollTopAnimation=function(){this.dragOverAnimationStopDisposable.dispose(),this.dragOverAnimationDisposable&&(this.dragOverAnimationDisposable.dispose(),this.dragOverAnimationDisposable=void 0)},e.prototype.getItemIndexFromEventTarget=function(e){for(var t=e;t instanceof HTMLElement&&t!==this.rowsContainer;){var n=t.getAttribute("data-index");if(n){var i=Number(n);if(!isNaN(i))return i}t=t.parentElement}},e.prototype.getRenderRange=function(e,t){return{start:this.rangeMap.indexAt(e),end:this.rangeMap.indexAfter(e+t-1)}},e.prototype._rerender=function(e,t){var n,i,r=this.getRenderRange(e,t);e===this.elementTop(r.start)?(n=r.start,i=0):r.end-r.start>1&&(n=r.start+1,i=this.elementTop(n)-e);for(var o=0;;){for(var s=this.getRenderRange(e,t),a=!1,u=s.start;un-h-2)throw new Error("message too long");var f=d.alloc(n-i-h-2),p=n-l-1,g=r(l),m=a(d.concat([c,f,d.alloc(1,1),t],p),s(g,p)),v=a(g,s(m,l));return new u(d.concat([d.alloc(1),v,m],n))}(p,t);else if(1===h)f=function(e,t,n){var i,o=t.length,s=e.modulus.byteLength();if(o>s-11)throw new Error("message too long");i=n?d.alloc(s-o-3,255):function(e){var t,n=d.allocUnsafe(e),i=0,o=r(2*e),s=0;for(;i=0)throw new Error("data too long for modulus")}return n?l(f,p):c(f,p)}},"9uVW":function(e,t,n){"use strict";n.d(t,"b",function(){return l}),n.d(t,"a",function(){return h}),n.d(t,"c",function(){return f});var i=n("hK2W"),r=n("Kp7x"),o=n("ZYUE"),s=n("tqet"),a=n("aL7J"),u=n("ZNRA"),c=n("vTy2"),l=function(){function e(e,t,n){this.parent=e,this._range=t,this.isProviderFirst=n,this._onRefChanged=new r.a,this.onRefChanged=this._onRefChanged.event,this.id=u.b.nextId()}return Object.defineProperty(e.prototype,"uri",{get:function(){return this.parent.uri},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"range",{get:function(){return this._range},set:function(e){this._range=e,this._onRefChanged.fire(this)},enumerable:!0,configurable:!0}),e.prototype.getAriaMessage=function(){return Object(i.a)("aria.oneReference","symbol in {0} on line {1} at column {2}",Object(o.b)(this.uri),this.range.startLineNumber,this.range.startColumn)},e}(),d=function(){function e(e){this._modelReference=e}return e.prototype.dispose=function(){Object(s.f)(this._modelReference)},e.prototype.preview=function(e,t){void 0===t&&(t=8);var n=this._modelReference.object.textEditorModel;if(n){var i=e.startLineNumber,r=e.startColumn,o=e.endLineNumber,s=e.endColumn,u=n.getWordUntilPosition({lineNumber:i,column:r-t}),l=new c.a(i,u.startColumn,i,r),d=new c.a(o,s,o,Number.MAX_VALUE),h=n.getValueInRange(l).replace(/^\s+/,a.l),f=n.getValueInRange(e);return{value:h+f+n.getValueInRange(d).replace(/\s+$/,a.l),highlight:{start:h.length,end:h.length+f.length}}}},e}(),h=function(){function e(e,t){this._parent=e,this._uri=t,this._children=[]}return Object.defineProperty(e.prototype,"id",{get:function(){return this._uri.toString()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"children",{get:function(){return this._children},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"preview",{get:function(){return this._preview},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"failure",{get:function(){return this._loadFailure},enumerable:!0,configurable:!0}),e.prototype.getAriaMessage=function(){var e=this.children.length;return 1===e?Object(i.a)("aria.fileReferences.1","1 symbol in {0}, full path {1}",Object(o.b)(this.uri),this.uri.fsPath):Object(i.a)("aria.fileReferences.N","{0} symbols in {1}, full path {2}",e,Object(o.b)(this.uri),this.uri.fsPath)},e.prototype.resolve=function(e){var t=this;return this._resolved?Promise.resolve(this):Promise.resolve(e.createModelReference(this._uri).then(function(e){if(!e.object)throw e.dispose(),new Error;return t._preview=new d(e),t._resolved=!0,t},function(e){return t._children=[],t._resolved=!0,t._loadFailure=e,t}))},e.prototype.dispose=function(){this._preview&&(this._preview.dispose(),this._preview=void 0)},e}(),f=function(){function e(t){var n=this;this._disposables=new s.b,this.groups=[],this.references=[],this._onDidChangeReferenceRange=new r.a,this.onDidChangeReferenceRange=this._onDidChangeReferenceRange.event;var i,o=t[0];t.sort(e._compareReferences);for(var a=0,u=t;a0?(i=t?(i+1)%r:(i+r-1)%r,n.children[i]):(i=n.parent.groups.indexOf(n),t?(i=(i+1)%o,n.parent.groups[i].children[0]):(i=(i+o-1)%o,n.parent.groups[i].children[n.parent.groups[i].children.length-1]))},e.prototype.nearestReference=function(e,t){var n=this.references.map(function(n,i){return{idx:i,prefixLen:a.b(n.uri.toString(),e.toString()),offsetDist:100*Math.abs(n.range.startLineNumber-t.lineNumber)+Math.abs(n.range.startColumn-t.column)}}).sort(function(e,t){return e.prefixLen>t.prefixLen?-1:e.prefixLent.offsetDist?1:0})[0];if(n)return this.references[n.idx]},e.prototype.firstReference=function(){for(var e=0,t=this.references;ei?1:c.a.compareRangesUsingStarts(e.range,t.range)},e}()},"9vcT":function(e,t){},AKCZ:function(e,t,n){"use strict";n.d(t,"a",function(){return c}),n.d(t,"b",function(){return l});var i,r=n("tqet"),o=n("Kp7x"),s=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),a=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},u=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]n)?t=("rmd160"===e?new u:c(e)).update(t).digest():t.length0;i--)t+=this._buffer(e,t),n+=this._flushBuffer(r,n);return t+=this._buffer(e,t),r},r.prototype.final=function(e){var t,n;return e&&(t=this.update(e)),n="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(n):n},r.prototype._pad=function(e,t){if(0===t)return!1;for(;t0?n.actionBar.push(o,{icon:!0,label:!1}):n.actionBar.isEmpty()||o&&0!==o.length||n.actionBar.clear(),e instanceof b&&e.getGroupLabel()?u.f(n.container,"has-group-label"):u.I(n.container,"has-group-label"),e instanceof b){var s=e,a=n;s.showBorder()?(u.f(a.container,"results-group-separator"),i.pickerGroupBorder&&(a.container.style.borderTopColor=i.pickerGroupBorder.toString())):(u.I(a.container,"results-group-separator"),a.container.style.borderTopColor=null);var c=s.getGroupLabel()||"";a.group&&(a.group.textContent=c,i.pickerGroupForeground&&(a.group.style.color=i.pickerGroupForeground.toString()))}if(e instanceof _){var l=e.getHighlights(),d=l[0],h=l[1],f=l[2],p=e.getIcon()?"quick-open-entry-icon "+e.getIcon():"";n.icon.className=p;var g=e.getLabelOptions()||Object.create(null);g.matches=d||[],g.title=e.getTooltip(),g.descriptionTitle=e.getDescriptionTooltip()||e.getDescription(),g.descriptionMatches=h||[],n.label.setLabel(r.m(e.getLabel()),e.getDescription(),g),n.detail.set(e.getDetail(),f),n.keybinding.set(e.getKeybinding())}},e.prototype.disposeTemplate=function(e,t){t.actionBar.dispose(),t.actionBar=null,t.container=null,t.entry=null,t.keybinding=null,t.detail=null,t.group=null,t.icon=null,t.label.dispose(),t.label=null},e}(),C=function(){function e(e,t){void 0===e&&(e=[]),void 0===t&&(t=new y),this._entries=e,this._dataSource=this,this._renderer=new w(t),this._filter=this,this._runner=this,this._accessibilityProvider=this}return Object.defineProperty(e.prototype,"entries",{get:function(){return this._entries},set:function(e){this._entries=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dataSource",{get:function(){return this._dataSource},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderer",{get:function(){return this._renderer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filter",{get:function(){return this._filter},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"runner",{get:function(){return this._runner},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"accessibilityProvider",{get:function(){return this._accessibilityProvider},enumerable:!0,configurable:!0}),e.prototype.getId=function(e){return e.getId()},e.prototype.getLabel=function(e){return r.n(e.getLabel())},e.prototype.getAriaLabel=function(e){return e.getAriaLabel()?i.a("quickOpenAriaLabelEntry","{0}, picker",e.getAriaLabel()):i.a("quickOpenAriaLabel","picker")},e.prototype.isVisible=function(e){return!e.isHidden()},e.prototype.run=function(e,t,n){return e.run(t,n)},e}()},Ao9X:function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"d",function(){return o}),n.d(t,"c",function(){return s}),n.d(t,"b",function(){return a});var i=n("iHM7"),r=function(){function e(e,t,n){void 0===n&&(n=!1),this._range=e,this._text=t,this.insertsAutoWhitespace=n}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._range,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return new i.a(n.endLineNumber,n.endColumn,n.endLineNumber,n.endColumn)},e}(),o=function(){function e(e,t,n){void 0===n&&(n=!1),this._range=e,this._text=t,this.insertsAutoWhitespace=n}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._range,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return new i.a(n.startLineNumber,n.startColumn,n.startLineNumber,n.startColumn)},e}(),s=function(){function e(e,t,n,i,r){void 0===r&&(r=!1),this._range=e,this._text=t,this._columnDeltaOffset=i,this._lineNumberDeltaOffset=n,this.insertsAutoWhitespace=r}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._range,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return new i.a(n.endLineNumber+this._lineNumberDeltaOffset,n.endColumn+this._columnDeltaOffset,n.endLineNumber+this._lineNumberDeltaOffset,n.endColumn+this._columnDeltaOffset)},e}(),a=function(){function e(e,t,n){this._range=e,this._text=t,this._initialSelection=n,this._selectionId=null}return e.prototype.getEditOperations=function(e,t){t.addEditOperation(this._range,this._text),this._selectionId=t.trackSelection(this._initialSelection)},e.prototype.computeCursorState=function(e,t){return t.getTrackedSelection(this._selectionId)},e}()},"B/Xy":function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("textModelService")},B6Bn:function(e,t,n){"use strict";var i=n("geuY"),r=n("lZ6o").utils,o=r.getNAF,s=r.getJSF,a=r.assert;function u(e,t){this.type=e,this.p=new i(t.p,16),this.red=t.prime?i.red(t.prime):i.mont(this.p),this.zero=new i(0).toRed(this.red),this.one=new i(1).toRed(this.red),this.two=new i(2).toRed(this.red),this.n=t.n&&new i(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4);var n=this.n&&this.p.div(this.n);!n||n.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}e.exports=u,u.prototype.point=function(){throw new Error("Not implemented")},u.prototype.validate=function(){throw new Error("Not implemented")},u.prototype._fixedNafMul=function(e,t){a(e.precomputed);var n=e._getDoubles(),i=o(t,1),r=(1<=u;t--)c=(c<<1)+i[t];s.push(c)}for(var l=this.jpoint(null,null,null),d=this.jpoint(null,null,null),h=r;h>0;h--){for(u=0;u=0;c--){for(t=0;c>=0&&0===s[c];c--)t++;if(c>=0&&t++,u=u.dblp(t),c<0)break;var l=s[c];a(0!==l),u="affine"===e.type?l>0?u.mixedAdd(r[l-1>>1]):u.mixedAdd(r[-l-1>>1].neg()):l>0?u.add(r[l-1>>1]):u.add(r[-l-1>>1].neg())}return"affine"===e.type?u.toP():u},u.prototype._wnafMulAdd=function(e,t,n,i,r){for(var a=this._wnafT1,u=this._wnafT2,c=this._wnafT3,l=0,d=0;d=1;d-=2){var f=d-1,p=d;if(1===a[f]&&1===a[p]){var g=[t[f],null,null,t[p]];0===t[f].y.cmp(t[p].y)?(g[1]=t[f].add(t[p]),g[2]=t[f].toJ().mixedAdd(t[p].neg())):0===t[f].y.cmp(t[p].y.redNeg())?(g[1]=t[f].toJ().mixedAdd(t[p]),g[2]=t[f].add(t[p].neg())):(g[1]=t[f].toJ().mixedAdd(t[p]),g[2]=t[f].toJ().mixedAdd(t[p].neg()));var m=[-3,-1,-5,-7,0,7,5,1,3],v=s(n[f],n[p]);l=Math.max(v[0].length,l),c[f]=new Array(l),c[p]=new Array(l);for(var _=0;_=0;d--){for(var S=0;d>=0;){var x=!0;for(_=0;_=0&&S++,w=w.dblp(S),d<0)break;for(_=0;_0?L=u[_][O-1>>1]:O<0&&(L=u[_][-O-1>>1].neg()),w="affine"===L.type?w.mixedAdd(L):w.add(L))}}for(d=0;d=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var n=[this],i=this,r=0;r>>24]^l[p>>>16&255]^d[g>>>8&255]^h[255&m]^t[v++],s=c[p>>>24]^l[g>>>16&255]^d[m>>>8&255]^h[255&f]^t[v++],a=c[g>>>24]^l[m>>>16&255]^d[f>>>8&255]^h[255&p]^t[v++],u=c[m>>>24]^l[f>>>16&255]^d[p>>>8&255]^h[255&g]^t[v++],f=o,p=s,g=a,m=u;return o=(i[f>>>24]<<24|i[p>>>16&255]<<16|i[g>>>8&255]<<8|i[255&m])^t[v++],s=(i[p>>>24]<<24|i[g>>>16&255]<<16|i[m>>>8&255]<<8|i[255&f])^t[v++],a=(i[g>>>24]<<24|i[m>>>16&255]<<16|i[f>>>8&255]<<8|i[255&p])^t[v++],u=(i[m>>>24]<<24|i[f>>>16&255]<<16|i[p>>>8&255]<<8|i[255&g])^t[v++],[o>>>=0,s>>>=0,a>>>=0,u>>>=0]}var a=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var n=[],i=[],r=[[],[],[],[]],o=[[],[],[],[]],s=0,a=0,u=0;u<256;++u){var c=a^a<<1^a<<2^a<<3^a<<4;c=c>>>8^255&c^99,n[s]=c,i[c]=s;var l=e[s],d=e[l],h=e[d],f=257*e[c]^16843008*c;r[0][s]=f<<24|f>>>8,r[1][s]=f<<16|f>>>16,r[2][s]=f<<8|f>>>24,r[3][s]=f,f=16843009*h^65537*d^257*l^16843008*s,o[0][c]=f<<24|f>>>8,o[1][c]=f<<16|f>>>16,o[2][c]=f<<8|f>>>24,o[3][c]=f,0===s?s=a=1:(s=l^e[e[e[h^l]]],a^=e[e[a]])}return{SBOX:n,INV_SBOX:i,SUB_MIX:r,INV_SUB_MIX:o}}();function c(e){this._key=r(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,n=t+6,i=4*(n+1),r=[],o=0;o>>24,s=u.SBOX[s>>>24]<<24|u.SBOX[s>>>16&255]<<16|u.SBOX[s>>>8&255]<<8|u.SBOX[255&s],s^=a[o/t|0]<<24):t>6&&o%t==4&&(s=u.SBOX[s>>>24]<<24|u.SBOX[s>>>16&255]<<16|u.SBOX[s>>>8&255]<<8|u.SBOX[255&s]),r[o]=r[o-t]^s}for(var c=[],l=0;l>>24]]^u.INV_SUB_MIX[1][u.SBOX[h>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[h>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&h]]}this._nRounds=n,this._keySchedule=r,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return s(e=r(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),n=i.allocUnsafe(16);return n.writeUInt32BE(t[0],0),n.writeUInt32BE(t[1],4),n.writeUInt32BE(t[2],8),n.writeUInt32BE(t[3],12),n},c.prototype.decryptBlock=function(e){var t=(e=r(e))[1];e[1]=e[3],e[3]=t;var n=s(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=i.allocUnsafe(16);return o.writeUInt32BE(n[0],0),o.writeUInt32BE(n[3],4),o.writeUInt32BE(n[2],8),o.writeUInt32BE(n[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},e.exports.AES=c},BO8W:function(e,t,n){"use strict";t.utils=n("iNQt"),t.Cipher=n("AWjC"),t.DES=n("Icsf"),t.CBC=n("nyV4"),t.EDE=n("YePo")},BVsN:function(e,t,n){"use strict";var i=n("LC74"),r=n("eCz2"),o=n("LYGd"),s=n("JaR3"),a=n("z+8S");function u(e){a.call(this,"digest"),this._hash=e}i(u,a),u.prototype._update=function(e){this._hash.update(e)},u.prototype._final=function(){return this._hash.digest()},e.exports=function(e){return"md5"===(e=e.toLowerCase())?new r:"rmd160"===e||"ripemd160"===e?new o:new u(s(e))}},Bug4:function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return d});var i,r,o=n("X6iQ"),s=n("tqet"),a=n("7/Cv"),u=n("2VYG"),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),l=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};!function(e){e.Tap="-monaco-gesturetap",e.Change="-monaco-gesturechange",e.Start="-monaco-gesturestart",e.End="-monaco-gesturesend",e.Contextmenu="-monaco-gesturecontextmenu"}(r||(r={}));var d=function(e){function t(){var t=e.call(this)||this;return t.dispatched=!1,t.activeTouches={},t.handle=null,t.targets=[],t._register(a.h(document,"touchstart",function(e){return t.onTouchStart(e)})),t._register(a.h(document,"touchend",function(e){return t.onTouchEnd(e)})),t._register(a.h(document,"touchmove",function(e){return t.onTouchMove(e)})),t}return c(t,e),t.addTarget=function(e){t.isTouchDevice()&&(t.INSTANCE||(t.INSTANCE=new t),t.INSTANCE.targets.push(e))},t.isTouchDevice=function(){return"ontouchstart"in window||navigator.maxTouchPoints>0||window.navigator.msMaxTouchPoints>0},t.prototype.dispose=function(){this.handle&&(this.handle.dispose(),this.handle=null),e.prototype.dispose.call(this)},t.prototype.onTouchStart=function(e){var t=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(var n=0,i=e.targetTouches.length;n=t.HOLD_DELAY&&Math.abs(l.initialPageX-o.s(l.rollingPageX))<30&&Math.abs(l.initialPageY-o.s(l.rollingPageY))<30){var h;(h=a.newGestureEvent(r.Contextmenu,l.initialTarget)).pageX=o.s(l.rollingPageX),h.pageY=o.s(l.rollingPageY),a.dispatchEvent(h)}else if(1===i){var f=o.s(l.rollingPageX),p=o.s(l.rollingPageY),g=o.s(l.rollingTimestamps)-l.rollingTimestamps[0],m=f-l.rollingPageX[0],v=p-l.rollingPageY[0],_=a.targets.filter(function(e){return l.initialTarget instanceof Node&&e.contains(l.initialTarget)});a.inertia(_,n,Math.abs(m)/g,m>0?1:-1,f,Math.abs(v)/g,v>0?1:-1,p)}a.dispatchEvent(a.newGestureEvent(r.End,l.initialTarget)),delete a.activeTouches[c.identifier]},a=this,u=0,c=e.changedTouches.length;u0&&(g=!1,f=o*i*h),u>0&&(g=!1,p=c*u*h);var m=d.newGestureEvent(r.Change);m.translationX=f,m.translationY=p,e.forEach(function(e){return e.dispatchEvent(m)}),g||d.inertia(e,a,i,o,s+f,u,c,l+p)})},t.prototype.onTouchMove=function(e){for(var t=Date.now(),n=0,i=e.changedTouches.length;n3&&(a.rollingPageX.shift(),a.rollingPageY.shift(),a.rollingTimestamps.shift()),a.rollingPageX.push(s.pageX),a.rollingPageY.push(s.pageY),a.rollingTimestamps.push(t)}else console.warn("end of an UNKNOWN touch",s)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)},t.SCROLL_FRICTION=-.005,t.HOLD_DELAY=700,l([u.a],t,"isTouchDevice",null),t}(s.a)},Bv73:function(e,t){},BwcV:function(e,t,n){"use strict";n.d(t,"a",function(){return c});var i,r=n("GfE5"),o=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=function(e){function t(t){for(var n=e.call(this,0)||this,i=0,r=t.length;i=0){for(var i=[],r=0,o=this._placeholderGroups[this._placeholderGroupsIdx];r0&&this._editor.executeEdits("snippet.placeholderTransform",i)}var d=!1;!0===t&&this._placeholderGroupsIdx0&&(this._placeholderGroupsIdx-=1,d=!0);var h=this._editor.getModel().changeDecorations(function(t){for(var i=new Set,r=[],o=0,s=n._placeholderGroups[n._placeholderGroupsIdx];o0)return!0}t=t.parent}return!1},Object.defineProperty(e.prototype,"isAtFirstPlaceholder",{get:function(){return this._placeholderGroupsIdx<=0||0===this._placeholderGroups.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAtLastPlaceholder",{get:function(){return this._placeholderGroupsIdx===this._placeholderGroups.length-1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasPlaceholder",{get:function(){return this._snippet.placeholders.length>0},enumerable:!0,configurable:!0}),e.prototype.computePossibleSelections=function(){for(var e=new Map,t=0,n=this._placeholderGroups;t0&&S!==d.getLineFirstNonWhitespaceColumn(F.positionLineNumber))&&e.adjustWhitespace(d,z,H),H.resolveVariables(new x([p,new k(u,j,D.length),new L(d,F),new N(d),new E,new I(h)]));var U=d.getOffsetAt(z)+y;y+=H.toString().length-d.getValueLengthInRange(V),c[j]=f.a.replace(V,H.toString()),l[j]=new P(t,H,U)}return{edits:c,snippets:l}},e.prototype.dispose=function(){Object(i.f)(this._snippets)},e.prototype._logInfo=function(){return'template="'+this._template+'", merged_templates="'+this._templateMerges.join(" -> ")+'"'},e.prototype.insert=function(){var t=this;if(this._editor.hasModel()){var n=e.createEditsAndSnippets(this._editor,this._template,this._options.overwriteBefore,this._options.overwriteAfter,!1,this._options.adjustWhitespace,this._options.clipboardText),i=n.edits,r=n.snippets;this._snippets=r,this._editor.executeEdits("snippet",i,function(e){return t._snippets[0].hasPlaceholder?t._move(!0):e.map(function(e){return a.a.fromPositions(e.range.getEndPosition())})}),this._editor.revealRange(this._editor.getSelections()[0])}},e.prototype.merge=function(t,n){var i=this;if(void 0===n&&(n=A),this._editor.hasModel()){this._templateMerges.push([this._snippets[0]._nestingLevel,this._snippets[0]._placeholderGroupsIdx,t]);var r=e.createEditsAndSnippets(this._editor,t,n.overwriteBefore,n.overwriteAfter,!0,n.adjustWhitespace,n.clipboardText),o=r.edits,s=r.snippets;this._editor.executeEdits("snippet",o,function(e){for(var t=0,n=i._snippets;t0},e}();n.d(t,"SnippetController2",function(){return V});var F=this&&this.__assign||function(){return(F=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},W=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},B={overwriteBefore:0,overwriteAfter:0,undoStopBefore:!0,undoStopAfter:!0,adjustWhitespace:!0,clipboardText:void 0},V=function(){function e(t,n,r){this._editor=t,this._logService=n,this._snippetListener=new i.b,this._modelVersionId=-1,this._inSnippet=e.InSnippetMode.bindTo(r),this._hasNextTabstop=e.HasNextTabstop.bindTo(r),this._hasPrevTabstop=e.HasPrevTabstop.bindTo(r)}return e.get=function(e){return e.getContribution("snippetController2")},e.prototype.dispose=function(){this._inSnippet.reset(),this._hasPrevTabstop.reset(),this._hasNextTabstop.reset(),Object(i.f)(this._session),this._snippetListener.dispose()},e.prototype.getId=function(){return"snippetController2"},e.prototype.insert=function(e,t){try{this._doInsert(e,void 0===t?B:F({},B,t))}catch(t){this.cancel(),this._logService.error(t),this._logService.error("snippet_error"),this._logService.error("insert_template=",e),this._logService.error("existing_template=",this._session?this._session._logInfo():"")}},e.prototype._doInsert=function(e,t){var n=this;this._editor.hasModel()&&(this._snippetListener.clear(),t.undoStopBefore&&this._editor.getModel().pushStackElement(),this._session?this._session.merge(e,t):(this._modelVersionId=this._editor.getModel().getAlternativeVersionId(),this._session=new R(this._editor,e,t),this._session.insert()),t.undoStopAfter&&this._editor.getModel().pushStackElement(),this._updateState(),this._snippetListener.add(this._editor.onDidChangeModelContent(function(e){return e.isFlush&&n.cancel()})),this._snippetListener.add(this._editor.onDidChangeModel(function(){return n.cancel()})),this._snippetListener.add(this._editor.onDidChangeCursorSelection(function(){return n._updateState()})))},e.prototype._updateState=function(){if(this._session&&this._editor.hasModel()){if(this._modelVersionId===this._editor.getModel().getAlternativeVersionId())return this.cancel();if(!this._session.hasPlaceholder)return this.cancel();if(this._session.isAtLastPlaceholder||!this._session.isSelectionWithinPlaceholders())return this.cancel();this._inSnippet.set(!0),this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder),this._hasNextTabstop.set(!this._session.isAtLastPlaceholder),this._handleChoice()}},e.prototype._handleChoice=function(){var e=this;if(this._session&&this._editor.hasModel()){var t=this._session.choice;if(t){if(this._currentChoice!==t){this._currentChoice=t,this._editor.setSelections(this._editor.getSelections().map(function(e){return a.a.fromPositions(e.getStartPosition())}));var n=t.options[0];Object(c.f)(this._editor,t.options.map(function(t,i){return{kind:13,label:t.value,insertText:t.value,sortText:Object(r.F)("a",i+1),range:s.a.fromPositions(e._editor.getPosition(),e._editor.getPosition().delta(0,n.value.length))}}))}}else this._currentChoice=void 0}else this._currentChoice=void 0},e.prototype.finish=function(){for(;this._inSnippet.get();)this.next()},e.prototype.cancel=function(e){void 0===e&&(e=!1),this._inSnippet.reset(),this._hasPrevTabstop.reset(),this._hasNextTabstop.reset(),this._snippetListener.clear(),Object(i.f)(this._session),this._session=void 0,this._modelVersionId=-1,e&&this._editor.setSelections([this._editor.getSelection()])},e.prototype.prev=function(){this._session&&this._session.prev(),this._updateState()},e.prototype.next=function(){this._session&&this._session.next(),this._updateState()},e.prototype.isInSnippet=function(){return Boolean(this._inSnippet.get())},e.InSnippetMode=new l.d("inSnippetMode",!1),e.HasNextTabstop=new l.d("hasNextTabstop",!1),e.HasPrevTabstop=new l.d("hasPrevTabstop",!1),e=j([W(1,d.a),W(2,l.c)],e)}();Object(o.h)(V);var H=o.c.bindToContribution(V.get);Object(o.g)(new H({id:"jumpToNextSnippetPlaceholder",precondition:l.a.and(V.InSnippetMode,V.HasNextTabstop),handler:function(e){return e.next()},kbOpts:{weight:130,kbExpr:u.a.editorTextFocus,primary:2}})),Object(o.g)(new H({id:"jumpToPrevSnippetPlaceholder",precondition:l.a.and(V.InSnippetMode,V.HasPrevTabstop),handler:function(e){return e.prev()},kbOpts:{weight:130,kbExpr:u.a.editorTextFocus,primary:1026}})),Object(o.g)(new H({id:"leaveSnippet",precondition:V.InSnippetMode,handler:function(e){return e.cancel(!0)},kbOpts:{weight:130,kbExpr:u.a.editorTextFocus,primary:9,secondary:[1033]}})),Object(o.g)(new H({id:"acceptSnippet",precondition:V.InSnippetMode,handler:function(e){return e.finish()}}))},C015:function(e,t,n){var i=n("LC74"),r=n("CzQx"),o=n("X3l8").Buffer,s=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);function u(){this.init(),this._w=a,r.call(this,128,112)}function c(e,t,n){return n^e&(t^n)}function l(e,t,n){return e&t|n&(e|t)}function d(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function h(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function f(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function g(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function m(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function v(e,t){return e>>>0>>0?1:0}i(u,r),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,n=0|this._ah,i=0|this._bh,r=0|this._ch,o=0|this._dh,a=0|this._eh,u=0|this._fh,_=0|this._gh,b=0|this._hh,y=0|this._al,w=0|this._bl,C=0|this._cl,S=0|this._dl,x=0|this._el,L=0|this._fl,O=0|this._gl,k=0|this._hl,N=0;N<32;N+=2)t[N]=e.readInt32BE(4*N),t[N+1]=e.readInt32BE(4*N+4);for(;N<160;N+=2){var E=t[N-30],I=t[N-30+1],D=f(E,I),M=p(I,E),T=g(E=t[N-4],I=t[N-4+1]),P=m(I,E),A=t[N-14],R=t[N-14+1],F=t[N-32],j=t[N-32+1],W=M+R|0,B=D+A+v(W,M)|0;B=(B=B+T+v(W=W+P|0,P)|0)+F+v(W=W+j|0,j)|0,t[N]=B,t[N+1]=W}for(var V=0;V<160;V+=2){B=t[V],W=t[V+1];var H=l(n,i,r),z=l(y,w,C),U=d(n,y),K=d(y,n),q=h(a,x),G=h(x,a),Z=s[V],Y=s[V+1],X=c(a,u,_),$=c(x,L,O),J=k+G|0,Q=b+q+v(J,k)|0;Q=(Q=(Q=Q+X+v(J=J+$|0,$)|0)+Z+v(J=J+Y|0,Y)|0)+B+v(J=J+W|0,W)|0;var ee=K+z|0,te=U+H+v(ee,K)|0;b=_,k=O,_=u,O=L,u=a,L=x,a=o+Q+v(x=S+J|0,S)|0,o=r,S=C,r=i,C=w,i=n,w=y,n=Q+te+v(y=J+ee|0,J)|0}this._al=this._al+y|0,this._bl=this._bl+w|0,this._cl=this._cl+C|0,this._dl=this._dl+S|0,this._el=this._el+x|0,this._fl=this._fl+L|0,this._gl=this._gl+O|0,this._hl=this._hl+k|0,this._ah=this._ah+n+v(this._al,y)|0,this._bh=this._bh+i+v(this._bl,w)|0,this._ch=this._ch+r+v(this._cl,C)|0,this._dh=this._dh+o+v(this._dl,S)|0,this._eh=this._eh+a+v(this._el,x)|0,this._fh=this._fh+u+v(this._fl,L)|0,this._gh=this._gh+_+v(this._gl,O)|0,this._hh=this._hh+b+v(this._hl,k)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,n,i){e.writeInt32BE(t,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},e.exports=u},C1C2:function(e,t,n){var i=n("TnCn");t.tagClass={0:"universal",1:"application",2:"context",3:"private"},t.tagClassByName=i._reverse(t.tagClass),t.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},t.tagByName=i._reverse(t.tag)},C3c5:function(e,t,n){"use strict";t.e=h,n.d(t,"a",function(){return f}),n.d(t,"c",function(){return p}),n.d(t,"d",function(){return m}),n.d(t,"b",function(){return v});var i,r=n("AKCZ"),o=n("JVO/"),s=n("7g0X"),a=n("ItKl"),u=n("Kp7x"),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),l=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},d=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}};function h(e){return void 0!==e.command}var f=Object(o.c)("menuService"),p=new(function(){function e(){this._commands=new Map,this._menuItems=new Map,this._onDidChangeMenu=new u.a,this.onDidChangeMenu=this._onDidChangeMenu.event}return e.prototype.addCommand=function(e){var t=this;return this._commands.set(e.id,e),this._onDidChangeMenu.fire(0),{dispose:function(){t._commands.delete(e.id)&&t._onDidChangeMenu.fire(0)}}},e.prototype.getCommand=function(e){return this._commands.get(e)},e.prototype.getCommands=function(){var e=new Map;return this._commands.forEach(function(t,n){return e.set(n,t)}),e},e.prototype.appendMenuItem=function(e,t){var n=this,i=this._menuItems.get(e);return i?i.push(t):(i=[t],this._menuItems.set(e,i)),this._onDidChangeMenu.fire(e),{dispose:function(){var r=i.indexOf(t);r>=0&&(i.splice(r,1),n._onDidChangeMenu.fire(e))}}},e.prototype.getMenuItems=function(e){var t=(this._menuItems.get(e)||[]).slice(0);return 0===e&&this._appendImplicitItems(t),t},e.prototype._appendImplicitItems=function(e){for(var t=new Set,n=0,i=e.filter(function(e){return h(e)});n=0;r--){var o=e.charCodeAt(r),s=t.get(o);if(0===s){if(2===i)return this._createWord(e,i,s,r+1,this._findEndOfWord(e,t,i,r+1));i=1}else if(2===s){if(1===i)return this._createWord(e,i,s,r+1,this._findEndOfWord(e,t,i,r+1));i=2}else if(1===s&&0!==i)return this._createWord(e,i,s,r+1,this._findEndOfWord(e,t,i,r+1))}return 0!==i?this._createWord(e,i,1,0,this._findEndOfWord(e,t,i,0)):null},e._findEndOfWord=function(e,t,n,i){for(var r=e.length,o=i;o=0;r--){var o=e.charCodeAt(r),s=t.get(o);if(1===s)return r+1;if(1===n&&2===s)return r+1;if(2===n&&0===s)return r+1}return 0},e.moveWordLeft=function(t,n,i,r){var o=i.lineNumber,s=i.column,u=!1;1===s&&o>1&&(u=!0,o-=1,s=n.getLineMaxColumn(o));var c=e._findPreviousWordOnLine(t,n,new a.a(o,s));if(0===r){if(c&&!u)if(n.getLineLastNonWhitespaceColumn(o)1?new a.a(n-1,e.getLineMaxColumn(n-1)):t;for(var o=e.getLineContent(n),s=t.column-1;s>1;s--){var u=o.charCodeAt(s-2),c=o.charCodeAt(s-1);if(95!==u&&95===c)return new a.a(n,s);if(r.y(u)&&r.z(c))return new a.a(n,s);if(r.z(u)&&r.z(c)&&s+1=c.start+1&&(c=e._findNextWordOnLine(t,n,new a.a(o,c.end+1))),s=c?c.start+1:n.getLineMaxColumn(o);return new a.a(o,s)},e._moveWordPartRight=function(e,t){var n=t.lineNumber,i=e.getLineMaxColumn(n);if(t.column===i)return n1?l=1:(c--,l=n.getLineMaxColumn(c)):(h&&l<=h.end+1&&(h=e._findPreviousWordOnLine(t,n,new a.a(c,h.start+1))),h?l=h.end+1:l>1?l=1:(c--,l=n.getLineMaxColumn(c))),new u.a(c,l,s.lineNumber,s.column)},e._deleteWordPartLeft=function(t,n){if(!n.isEmpty())return n;var i=n.getPosition(),r=e._moveWordPartLeft(t,i);return new u.a(i.lineNumber,i.column,r.lineNumber,r.column)},e._findFirstNonWhitespaceChar=function(e,t){for(var n=e.length,i=t;i=p.start+1&&(p=e._findNextWordOnLine(t,n,new a.a(c,p.end+1))),p?l=p.start+1:l255)return 255;return 0|e},t.b=r,t.c=function(e){for(var t=e.length,n=new Uint32Array(t),i=0;i4294967295?4294967295:0|e}},CX1u:function(e,t,n){"use strict";t.c=function(e,t){void 0===t&&(t={});var n=r(t);return n.textContent=e,n},t.b=function(e,t){void 0===t&&(t={});var n=r(t);return function e(t,n,r){var o;if(2===n.type)o=document.createTextNode(n.content||"");else if(3===n.type)o=document.createElement("b");else if(4===n.type)o=document.createElement("i");else if(5===n.type&&r){var s=document.createElement("a");s.href="#",r.disposeables.add(i.k(s,"click",function(e){r.callback(String(n.index),e)})),o=s}else 7===n.type?o=document.createElement("br"):1===n.type&&(o=t);o&&t!==o&&t.appendChild(o),o&&Array.isArray(n.children)&&n.children.forEach(function(t){e(o,t,r)})}(n,function(e){for(var t={type:1,children:[]},n=0,i=t,r=[],a=new o(e);!a.eos();){var u=a.next(),c="\\"===u&&0!==s(a.peek());if(c&&(u=a.next()),c||0===s(u)||u!==a.peek())if("\n"===u)2===i.type&&(i=r.pop()),i.children.push({type:7});else if(2!==i.type){var l={type:2,content:u};i.children.push(l),r.push(i),i=l}else i.content+=u;else{a.advance(),2===i.type&&(i=r.pop());var d=s(u);if(i.type===d||5===i.type&&6===d)i=r.pop();else{var h={type:d,children:[]};5===d&&(h.index=n,n++),i.children.push(h),r.push(i),i=h}}}return 2===i.type&&(i=r.pop()),r.length,t}(e),t.actionHandler),n},t.a=r;var i=n("7/Cv");function r(e){var t=e.inline?"span":"div",n=document.createElement(t);return e.className&&(n.className=e.className),n}var o=function(){function e(e){this.source=e,this.index=0}return e.prototype.eos=function(){return this.index>=this.source.length},e.prototype.next=function(){var e=this.peek();return this.advance(),e},e.prototype.peek=function(){return this.source[this.index]},e.prototype.advance=function(){this.index++},e}();function s(e){switch(e){case"*":return 3;case"_":return 4;case"[":return 5;case"]":return 6;default:return 0}}},Cfmk:function(e,t,n){"use strict";n.d(t,"a",function(){return l}),n.d(t,"c",function(){return r}),n.d(t,"b",function(){return d});var i,r,o=n("JVO/"),s=n("Kp7x"),a=n("tqet"),u=n("KIxu"),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),l=Object(o.c)("storageService");!function(e){e[e.NONE=0]="NONE",e[e.SHUTDOWN=1]="SHUTDOWN"}(r||(r={}));var d=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._serviceBrand=null,t._onDidChangeStorage=t._register(new s.a),t.onDidChangeStorage=t._onDidChangeStorage.event,t.onWillSaveState=s.b.None,t.globalCache=new Map,t.workspaceCache=new Map,t}return c(t,e),t.prototype.getCache=function(e){return 0===e?this.globalCache:this.workspaceCache},t.prototype.get=function(e,t,n){var i=this.getCache(t).get(e);return Object(u.k)(i)?n:i},t.prototype.getBoolean=function(e,t,n){var i=this.getCache(t).get(e);return Object(u.k)(i)?n:"true"===i},t.prototype.store=function(e,t,n){if(Object(u.k)(t))return this.remove(e,n);var i=String(t);return this.getCache(n).get(e)===i?Promise.resolve():(this.getCache(n).set(e,i),this._onDidChangeStorage.fire({scope:n,key:e}),Promise.resolve())},t.prototype.remove=function(e,t){return this.getCache(t).delete(e)?(this._onDidChangeStorage.fire({scope:t,key:e}),Promise.resolve()):Promise.resolve()},t}(a.a)},Cgw8:function(e,t,n){var i=n("X3l8").Buffer,r=n("eCz2");e.exports=function(e,t,n,o){if(i.isBuffer(e)||(e=i.from(e,"binary")),t&&(i.isBuffer(t)||(t=i.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var s=n/8,a=i.alloc(s),u=i.alloc(o||0),c=i.alloc(0);s>0||o>0;){var l=new r;l.update(c),l.update(e),t&&l.update(t),c=l.digest();var d=0;if(s>0){var h=a.length-s;d=Math.min(s,c.length),c.copy(a,h,0,d),s-=d}if(d0){var f=u.length-o,p=Math.min(o,c.length-d);c.copy(u,f,d,d+p),o-=p}}return c.fill(0),{key:a,iv:u}}},Crnc:function(e,t,n){"use strict";n.d(t,"a",function(){return a});var i=!1,r=null;function o(e){if(!e.parent||e.parent===e)return null;try{var t=e.location,n=e.parent.location;if(t.protocol!==n.protocol||t.hostname!==n.hostname||t.port!==n.port)return i=!0,null}catch(e){return i=!0,null}return e.parent}function s(e,t){for(var n,i=e.document.getElementsByTagName("iframe"),r=0,o=i.length;r=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},m=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},v=function(e){function t(n,i){var r=e.call(this)||this;return r.closeTimeout=3e3,r._messageWidget=r._register(new a.d),r._messageListeners=r._register(new a.b),r._editor=n,r._visible=t.MESSAGE_VISIBLE.bindTo(i),r._register(r._editor.onDidAttemptReadOnlyEdit(function(){return r._onDidAttemptReadOnlyEdit()})),r}return p(t,e),t.get=function(e){return e.getContribution(t._id)},t.prototype.getId=function(){return t._id},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._visible.reset()},t.prototype.showMessage=function(e,t){var n,i=this;Object(u.a)(e),this._visible.set(!0),this._messageWidget.clear(),this._messageListeners.clear(),this._messageWidget.value=new b(this._editor,t,e),this._messageListeners.add(this._editor.onDidBlurEditorText(function(){return i.closeMessage()})),this._messageListeners.add(this._editor.onDidChangeCursorPosition(function(){return i.closeMessage()})),this._messageListeners.add(this._editor.onDidDispose(function(){return i.closeMessage()})),this._messageListeners.add(this._editor.onDidChangeModel(function(){return i.closeMessage()})),this._messageListeners.add(new s.e(function(){return i.closeMessage()},this.closeTimeout)),this._messageListeners.add(this._editor.onMouseMove(function(e){e.target.position&&(n?n.containsPosition(e.target.position)||i.closeMessage():n=new c.a(t.lineNumber-3,1,e.target.position.lineNumber+3,1))}))},t.prototype.closeMessage=function(){this._visible.reset(),this._messageListeners.clear(),this._messageWidget.value&&this._messageListeners.add(b.fadeOut(this._messageWidget.value))},t.prototype._onDidAttemptReadOnlyEdit=function(){this._editor.hasModel()&&this.showMessage(o.a("editor.readonly","Cannot edit in read-only editor"),this._editor.getPosition())},t._id="editor.contrib.messageController",t.MESSAGE_VISIBLE=new d.d("messageVisible",!1),t=g([m(1,d.c)],t)}(a.a),_=l.c.bindToContribution(v.get);Object(l.g)(new _({id:"leaveEditorMessage",precondition:v.MESSAGE_VISIBLE,handler:function(e){return e.closeMessage()},kbOpts:{weight:130,primary:9}}));var b=function(){function e(e,t,n){var i=t.lineNumber,r=t.column;this.allowEditorOverflow=!0,this.suppressMouseDown=!1,this._editor=e,this._editor.revealLinesInCenterIfOutsideViewport(i,i,0),this._position={lineNumber:i,column:r-1},this._domNode=document.createElement("div"),this._domNode.classList.add("monaco-editor-overlaymessage");var o=document.createElement("div");o.classList.add("message"),o.textContent=n,this._domNode.appendChild(o);var s=document.createElement("div");s.classList.add("anchor"),this._domNode.appendChild(s),this._editor.addContentWidget(this),this._domNode.classList.add("fadeIn")}return e.fadeOut=function(e){var t,n=function(){e.dispose(),clearTimeout(t),e.getDomNode().removeEventListener("animationend",n)};return t=setTimeout(n,110),e.getDomNode().addEventListener("animationend",n),e.getDomNode().classList.add("fadeOut"),{dispose:n}},e.prototype.dispose=function(){this._editor.removeContentWidget(this)},e.prototype.getId=function(){return"messageoverlay"},e.prototype.getDomNode=function(){return this._domNode},e.prototype.getPosition=function(){return{position:this._position,preference:[1]}},e}();Object(l.h)(v),Object(h.f)(function(e,t){var n=e.getColor(f._3);if(n){var i=e.type===h.b?2:1;t.addRule(".monaco-editor .monaco-editor-overlaymessage .anchor { border-top-color: "+n+"; }"),t.addRule(".monaco-editor .monaco-editor-overlaymessage .message { border: "+i+"px solid "+n+"; }")}var r=e.getColor(f._2);r&&t.addRule(".monaco-editor .monaco-editor-overlaymessage .message { background-color: "+r+"; }");var o=e.getColor(f._4);o&&t.addRule(".monaco-editor .monaco-editor-overlaymessage .message { color: "+o+"; }")})},Cwo9:function(e,t){},CzQx:function(e,t,n){var i=n("X3l8").Buffer;function r(e,t){this._block=i.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}r.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=i.from(e,t));for(var n=this._block,r=this._blockSize,o=e.length,s=this._len,a=0;a=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=8*this._len;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var i=(4294967295&n)>>>0,r=(n-i)/4294967296;this._block.writeUInt32BE(r,this._blockSize-8),this._block.writeUInt32BE(i,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},e.exports=r},D1Va:function(e,t,n){"use strict";e.exports=o;var i=n("DsFX"),r=n("jOgh");function o(e){if(!(this instanceof o))return new o(e);i.call(this,e),this._transformState={afterTransform:function(e,t){var n=this._transformState;n.transforming=!1;var i=n.writecb;if(!i)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),i(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length0?i-4:i,d=0;d>16&255,a[u++]=t>>8&255,a[u++]=255&t;2===s&&(t=r[e.charCodeAt(d)]<<2|r[e.charCodeAt(d+1)]>>4,a[u++]=255&t);1===s&&(t=r[e.charCodeAt(d)]<<10|r[e.charCodeAt(d+1)]<<4|r[e.charCodeAt(d+2)]>>2,a[u++]=t>>8&255,a[u++]=255&t);return a},t.fromByteArray=function(e){for(var t,n=e.length,r=n%3,o=[],s=0,a=n-r;sa?a:s+16383));1===r?(t=e[n-1],o.push(i[t>>2]+i[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],o.push(i[t>>10]+i[t>>4&63]+i[t<<2&63]+"="));return o.join("")};for(var i=[],r=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function l(e,t,n){for(var r,o,s=[],a=t;a>18&63]+i[o>>12&63]+i[o>>6&63]+i[63&o]);return s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},EMDP:function(e,t,n){"use strict";n.d(t,"a",function(){return c}),n.d(t,"b",function(){return l});var i,r,o=n("mrx5"),s=n("ZYUE"),a=n("JVO/"),u=n("WTFd"),c=Object(a.c)("contextService");!function(e){e.isIWorkspace=function(e){return e&&"object"==typeof e&&"string"==typeof e.id&&Array.isArray(e.folders)}}(i||(i={})),function(e){e.isIWorkspaceFolder=function(e){return e&&"object"==typeof e&&o.a.isUri(e.uri)&&"string"==typeof e.name&&"function"==typeof e.toResource}}(r||(r={}));!function(){function e(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=null),this._id=e,this._configuration=n,this._foldersMap=u.c.forPaths(),this.folders=t}Object.defineProperty(e.prototype,"folders",{get:function(){return this._folders},set:function(e){this._folders=e,this.updateFoldersMap()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"configuration",{get:function(){return this._configuration},set:function(e){this._configuration=e},enumerable:!0,configurable:!0}),e.prototype.getFolder=function(e){return e&&this._foldersMap.findSubstr(e.with({scheme:e.scheme,authority:e.authority,path:e.path}).toString())||null},e.prototype.updateFoldersMap=function(){this._foldersMap=u.c.forPaths();for(var e=0,t=this.folders;e=1.5*n;return Math.round(e/n)+" "+i+(r?"s":"")}e.exports=function(e,t){t=t||{};var c=typeof e;if("string"===c&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var u=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return u*a;case"weeks":case"week":case"w":return u*s;case"days":case"day":case"d":return u*o;case"hours":case"hour":case"hrs":case"hr":case"h":return u*r;case"minutes":case"minute":case"mins":case"min":case"m":return u*i;case"seconds":case"second":case"secs":case"sec":case"s":return u*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}(e);if("number"===c&&!1===isNaN(e))return t.long?function(e){var t=Math.abs(e);if(t>=o)return u(e,t,o,"day");if(t>=r)return u(e,t,r,"hour");if(t>=i)return u(e,t,i,"minute");if(t>=n)return u(e,t,n,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=o)return Math.round(e/o)+"d";if(t>=r)return Math.round(e/r)+"h";if(t>=i)return Math.round(e/i)+"m";if(t>=n)return Math.round(e/n)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},Eawl:function(e,t){},Eeyw:function(e,t,n){"use strict";t.a=function(e,t){var n=e.getCount(),r=e.findTokenIndexAtOffset(t),o=e.getLanguageId(r),s=r;for(;s+10&&e.getLanguageId(a-1)===o;)a--;return new i(e,o,a,s+1,e.getStartOffset(a),e.getEndOffset(s))},t.b=function(e){return 0!=(7&e)};var i=function(){function e(e,t,n,i,r,o){this._actual=e,this.languageId=t,this._firstTokenIndex=n,this._lastTokenIndex=i,this.firstCharOffset=r,this._lastCharOffset=o}return e.prototype.getLineContent=function(){return this._actual.getLineContent().substring(this.firstCharOffset,this._lastCharOffset)},e.prototype.getTokenCount=function(){return this._lastTokenIndex-this._firstTokenIndex},e.prototype.findTokenIndexAtOffset=function(e){return this._actual.findTokenIndexAtOffset(e+this.firstCharOffset)-this._firstTokenIndex},e.prototype.getStandardTokenType=function(e){return this._actual.getStandardTokenType(e+this._firstTokenIndex)},e}()},EfIu:function(e,t,n){"use strict";n.d(t,"a",function(){return i}),n.d(t,"c",function(){return r}),n.d(t,"b",function(){return o}),n.d(t,"d",function(){return s}),n.d(t,"e",function(){return a}),n.d(t,"g",function(){return u}),n.d(t,"h",function(){return c}),n.d(t,"f",function(){return l});var i,r,o,s,a,u,c,l,d=n("hK2W");!function(e){e.noSelection=d.a("noSelection","No selection"),e.singleSelectionRange=d.a("singleSelectionRange","Line {0}, Column {1} ({2} selected)"),e.singleSelection=d.a("singleSelection","Line {0}, Column {1}"),e.multiSelectionRange=d.a("multiSelectionRange","{0} selections ({1} characters selected)"),e.multiSelection=d.a("multiSelection","{0} selections"),e.emergencyConfOn=d.a("emergencyConfOn","Now changing the setting `accessibilitySupport` to 'on'."),e.openingDocs=d.a("openingDocs","Now opening the Editor Accessibility documentation page."),e.readonlyDiffEditor=d.a("readonlyDiffEditor"," in a read-only pane of a diff editor."),e.editableDiffEditor=d.a("editableDiffEditor"," in a pane of a diff editor."),e.readonlyEditor=d.a("readonlyEditor"," in a read-only code editor"),e.editableEditor=d.a("editableEditor"," in a code editor"),e.changeConfigToOnMac=d.a("changeConfigToOnMac","To configure the editor to be optimized for usage with a Screen Reader press Command+E now."),e.changeConfigToOnWinLinux=d.a("changeConfigToOnWinLinux","To configure the editor to be optimized for usage with a Screen Reader press Control+E now."),e.auto_on=d.a("auto_on","The editor is configured to be optimized for usage with a Screen Reader."),e.auto_off=d.a("auto_off","The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time."),e.tabFocusModeOnMsg=d.a("tabFocusModeOnMsg","Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}."),e.tabFocusModeOnMsgNoKb=d.a("tabFocusModeOnMsgNoKb","Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding."),e.tabFocusModeOffMsg=d.a("tabFocusModeOffMsg","Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}."),e.tabFocusModeOffMsgNoKb=d.a("tabFocusModeOffMsgNoKb","Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding."),e.openDocMac=d.a("openDocMac","Press Command+H now to open a browser window with more information related to editor accessibility."),e.openDocWinLinux=d.a("openDocWinLinux","Press Control+H now to open a browser window with more information related to editor accessibility."),e.outroMsg=d.a("outroMsg","You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape."),e.showAccessibilityHelpAction=d.a("showAccessibilityHelpAction","Show Accessibility Help")}(i||(i={})),function(e){e.inspectTokensAction=d.a("inspectTokens","Developer: Inspect Tokens")}(r||(r={})),function(e){e.gotoLineLabelValidLineAndColumn=d.a("gotoLineLabelValidLineAndColumn","Go to line {0} and character {1}"),e.gotoLineLabelValidLine=d.a("gotoLineLabelValidLine","Go to line {0}"),e.gotoLineLabelEmptyWithLineLimit=d.a("gotoLineLabelEmptyWithLineLimit","Type a line number between 1 and {0} to navigate to"),e.gotoLineLabelEmptyWithLineAndColumnLimit=d.a("gotoLineLabelEmptyWithLineAndColumnLimit","Type a character between 1 and {0} to navigate to"),e.gotoLineAriaLabel=d.a("gotoLineAriaLabel","Current Line: {0}. Go to line {1}."),e.gotoLineActionInput=d.a("gotoLineActionInput","Type a line number, followed by an optional colon and a character number to navigate to"),e.gotoLineActionLabel=d.a("gotoLineActionLabel","Go to Line...")}(o||(o={})),function(e){e.ariaLabelEntryWithKey=d.a("ariaLabelEntryWithKey","{0}, {1}, commands"),e.ariaLabelEntry=d.a("ariaLabelEntry","{0}, commands"),e.quickCommandActionInput=d.a("quickCommandActionInput","Type the name of an action you want to execute"),e.quickCommandActionLabel=d.a("quickCommandActionLabel","Command Palette")}(s||(s={})),function(e){e.entryAriaLabel=d.a("entryAriaLabel","{0}, symbols"),e.quickOutlineActionInput=d.a("quickOutlineActionInput","Type the name of an identifier you wish to navigate to"),e.quickOutlineActionLabel=d.a("quickOutlineActionLabel","Go to Symbol..."),e._symbols_=d.a("symbols","symbols ({0})"),e._modules_=d.a("modules","modules ({0})"),e._class_=d.a("class","classes ({0})"),e._interface_=d.a("interface","interfaces ({0})"),e._method_=d.a("method","methods ({0})"),e._function_=d.a("function","functions ({0})"),e._property_=d.a("property","properties ({0})"),e._variable_=d.a("variable","variables ({0})"),e._variable2_=d.a("variable2","variables ({0})"),e._constructor_=d.a("_constructor","constructors ({0})"),e._call_=d.a("call","calls ({0})")}(a||(a={})),function(e){e.editorViewAccessibleLabel=d.a("editorViewAccessibleLabel","Editor content"),e.accessibilityHelpMessageIE=d.a("accessibilityHelpMessageIE","Press Ctrl+F1 for Accessibility Options."),e.accessibilityHelpMessage=d.a("accessibilityHelpMessage","Press Alt+F1 for Accessibility Options.")}(u||(u={})),function(e){e.toggleHighContrast=d.a("toggleHighContrast","Toggle High Contrast Theme")}(c||(c={})),function(e){e.bulkEditServiceSummary=d.a("bulkEditServiceSummary","Made {0} edits in {1} files")}(l||(l={}))},EfRI:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"DeleteWordPartLeft",function(){return d}),n.d(t,"DeleteWordPartRight",function(){return h}),n.d(t,"WordPartLeftCommand",function(){return f}),n.d(t,"CursorWordPartLeft",function(){return p}),n.d(t,"CursorWordPartLeftSelect",function(){return g}),n.d(t,"WordPartRightCommand",function(){return m}),n.d(t,"CursorWordPartRight",function(){return v}),n.d(t,"CursorWordPartRightSelect",function(){return _});var i,r=n("03Zz"),o=n("CIBl"),s=n("vTy2"),a=n("/9db"),u=n("I8T6"),c=n("ItKl"),l=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),d=function(e){function t(){return e.call(this,{whitespaceHeuristics:!0,wordNavigationType:0,id:"deleteWordPartLeft",precondition:a.a.writable,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:769},weight:100}})||this}return l(t,e),t.prototype._delete=function(e,t,n,i,r){var a=o.b.deleteWordPartLeft(e,t,n,i);return a||new s.a(1,1,1,1)},t}(u.DeleteWordCommand),h=function(e){function t(){return e.call(this,{whitespaceHeuristics:!0,wordNavigationType:2,id:"deleteWordPartRight",precondition:a.a.writable,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:788},weight:100}})||this}return l(t,e),t.prototype._delete=function(e,t,n,i,r){var a=o.b.deleteWordPartRight(e,t,n,i);if(a)return a;var u=t.getLineCount(),c=t.getLineMaxColumn(u);return new s.a(u,c,u,c)},t}(u.DeleteWordCommand),f=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype._move=function(e,t,n,i){return o.b.moveWordPartLeft(e,t,n)},t}(u.MoveWordCommand),p=function(e){function t(){return e.call(this,{inSelectionMode:!1,wordNavigationType:0,id:"cursorWordPartLeft",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:783},weight:100}})||this}return l(t,e),t}(f);c.a.registerCommandAlias("cursorWordPartStartLeft","cursorWordPartLeft");var g=function(e){function t(){return e.call(this,{inSelectionMode:!0,wordNavigationType:0,id:"cursorWordPartLeftSelect",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:1807},weight:100}})||this}return l(t,e),t}(f);c.a.registerCommandAlias("cursorWordPartStartLeftSelect","cursorWordPartLeftSelect");var m=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype._move=function(e,t,n,i){return o.b.moveWordPartRight(e,t,n)},t}(u.MoveWordCommand),v=function(e){function t(){return e.call(this,{inSelectionMode:!1,wordNavigationType:2,id:"cursorWordPartRight",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:785},weight:100}})||this}return l(t,e),t}(m),_=function(e){function t(){return e.call(this,{inSelectionMode:!0,wordNavigationType:2,id:"cursorWordPartRightSelect",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:1809},weight:100}})||this}return l(t,e),t}(m);Object(r.g)(new d),Object(r.g)(new h),Object(r.g)(new p),Object(r.g)(new g),Object(r.g)(new v),Object(r.g)(new _)},EuP9:function(e,t,n){"use strict";(function(e){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var i=n("EKta"),r=n("ujcs"),o=n("sOR5");function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function p(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return V(e).length;default:if(i)return B(e).length;t=(""+t).toLowerCase(),i=!0}}function g(e,t,n){var i=e[t];e[t]=e[n],e[n]=i}function m(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=u.from(t,i)),u.isBuffer(t))return 0===t.length?-1:v(e,t,n,i,r);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):v(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function v(e,t,n,i,r){var o,s=1,a=e.length,u=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,n/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var l=-1;for(o=n;oa&&(n=a-u),o=n;o>=0;o--){for(var d=!0,h=0;hr&&(i=r):i=r;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");i>o/2&&(i=o/2);for(var s=0;s>8,r=n%256,o.push(r),o.push(i);return o}(t,e.length-n),e,n,i)}function x(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function L(e,t,n){n=Math.min(e.length,n);for(var i=[],r=t;r239?4:c>223?3:c>191?2:1;if(r+d<=n)switch(d){case 1:c<128&&(l=c);break;case 2:128==(192&(o=e[r+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=e[r+1],s=e[r+2],128==(192&o)&&128==(192&s)&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[r+1],s=e[r+2],a=e[r+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,d=1):l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|1023&l),i.push(l),r+=d}return function(e){var t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);var n="",i=0;for(;ithis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,n);case"utf8":case"utf-8":return L(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return x(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}.apply(this,arguments)},u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},u.prototype.compare=function(e,t,n,i,r){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,r>>>=0,this===e)return 0;for(var o=r-i,s=n-t,a=Math.min(o,s),c=this.slice(i,r),l=e.slice(t,n),d=0;dr)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var o=!1;;)switch(i){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return y(this,e,t,n);case"latin1":case"binary":return w(this,e,t,n);case"base64":return C(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var O=4096;function k(e,t,n){var i="";n=Math.min(e.length,n);for(var r=t;ri)&&(n=i);for(var r="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function M(e,t,n,i,r,o){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function T(e,t,n,i){t<0&&(t=65535+t+1);for(var r=0,o=Math.min(e.length-n,2);r>>8*(i?r:1-r)}function P(e,t,n,i){t<0&&(t=4294967295+t+1);for(var r=0,o=Math.min(e.length-n,4);r>>8*(i?r:3-r)&255}function A(e,t,n,i,r,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,n,i,o){return o||A(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function F(e,t,n,i,o){return o||A(e,0,n,8),r.write(e,t,n,i,52,8),n+8}u.prototype.slice=function(e,t){var n,i=this.length;if(e=~~e,t=void 0===t?i:~~t,e<0?(e+=i)<0&&(e=0):e>i&&(e=i),t<0?(t+=i)<0&&(t=0):t>i&&(t=i),t0&&(r*=256);)i+=this[e+--t]*r;return i},u.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||D(e,t,this.length);for(var i=this[e],r=1,o=0;++o=(r*=128)&&(i-=Math.pow(2,8*t)),i},u.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||D(e,t,this.length);for(var i=t,r=1,o=this[e+--i];i>0&&(r*=256);)o+=this[e+--i]*r;return o>=(r*=128)&&(o-=Math.pow(2,8*t)),o},u.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},u.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),r.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),r.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),r.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),r.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,n,i){(e=+e,t|=0,n|=0,i)||M(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+r]=e/o&255;return t+n},u.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):P(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):P(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t|=0,!i){var r=Math.pow(2,8*n-1);M(this,e,t,n,r-1,-r)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+n},u.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t|=0,!i){var r=Math.pow(2,8*n-1);M(this,e,t,n,r-1,-r)}var o=n-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+n},u.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):P(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||M(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):P(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},u.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},u.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},u.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},u.prototype.copy=function(e,t,n,i){if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t=0;--r)e[r+t]=this[r+n];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function V(e){return i.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(e,t,n,i){for(var r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}}).call(t,n("DuR2"))},Evjx:function(e,t,n){"use strict";n.d(t,"d",function(){return u}),n.d(t,"b",function(){return l}),n.d(t,"a",function(){return d}),n.d(t,"c",function(){return v});var i,r,o=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=function(){function e(){this.value="",this.pos=0}return e.isDigitCharacter=function(e){return e>=48&&e<=57},e.isVariableCharacter=function(e){return 95===e||e>=97&&e<=122||e>=65&&e<=90},e.prototype.text=function(e){this.value=e,this.pos=0},e.prototype.tokenText=function(e){return this.value.substr(e.pos,e.len)},e.prototype.next=function(){if(this.pos>=this.value.length)return{type:14,pos:this.pos,len:0};var t,n=this.pos,i=0,r=this.value.charCodeAt(n);if("number"==typeof(t=e._table[r]))return this.pos+=1,{type:t,pos:n,len:1};if(e.isDigitCharacter(r)){t=8;do{i+=1,r=this.value.charCodeAt(n+i)}while(e.isDigitCharacter(r));return this.pos+=i,{type:t,pos:n,len:i}}if(e.isVariableCharacter(r)){t=9;do{r=this.value.charCodeAt(n+ ++i)}while(e.isVariableCharacter(r)||e.isDigitCharacter(r));return this.pos+=i,{type:t,pos:n,len:i}}t=10;do{i+=1,r=this.value.charCodeAt(n+i)}while(!isNaN(r)&&void 0===e._table[r]&&!e.isDigitCharacter(r)&&!e.isVariableCharacter(r));return this.pos+=i,{type:t,pos:n,len:i}},e._table=((r={})[36]=0,r[58]=1,r[44]=2,r[123]=3,r[125]=4,r[92]=5,r[47]=6,r[124]=7,r[43]=11,r[45]=12,r[63]=13,r),e}(),a=function(){function e(){this._children=[]}return e.prototype.appendChild=function(e){return e instanceof u&&this._children[this._children.length-1]instanceof u?this._children[this._children.length-1].value+=e.value:(e.parent=this,this._children.push(e)),this},e.prototype.replace=function(e,t){var n=e.parent,i=n.children.indexOf(e),r=n.children.slice(0);r.splice.apply(r,[i,1].concat(t)),n._children=r,function e(t,n){for(var i=0,r=t;it.index?1:0},Object.defineProperty(t.prototype,"isFinalTabstop",{get:function(){return 0===this.index},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"choice",{get:function(){return 1===this._children.length&&this._children[0]instanceof d?this._children[0]:void 0},enumerable:!0,configurable:!0}),t.prototype.clone=function(){var e=new t(this.index);return this.transform&&(e.transform=this.transform.clone()),e._children=this.children.map(function(e){return e.clone()}),e},t}(c),d=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.options=[],t}return o(t,e),t.prototype.appendChild=function(e){return e instanceof u&&(e.parent=this,this.options.push(e)),this},t.prototype.toString=function(){return this.options[0].value},t.prototype.len=function(){return this.options[0].len()},t.prototype.clone=function(){var e=new t;return this.options.forEach(e.appendChild,e),e},t}(a),h=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.regexp=new RegExp(""),t}return o(t,e),t.prototype.resolve=function(e){var t=this,n=!1,i=e.replace(this.regexp,function(){return n=!0,t._replace(Array.prototype.slice.call(arguments,0,-2))});return!n&&this._children.some(function(e){return e instanceof f&&Boolean(e.elseValue)})&&(i=this._replace([])),i},t.prototype._replace=function(e){for(var t="",n=0,i=this._children;n0;){var i=n.shift();if(!t(i))break;n.unshift.apply(n,i.children)}}var m=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return o(t,e),Object.defineProperty(t.prototype,"placeholderInfo",{get:function(){if(!this._placeholders){var e,t=[];this.walk(function(n){return n instanceof l&&(t.push(n),e=!e||e.index0?r.set(e.index,e.children):o.push(e)),!0});for(var a=0,u=o;a0&&t),!r.has(0)&&n&&i.appendChild(new l(0)),i},e.prototype._accept=function(e,t){if(void 0===e||this._token.type===e){var n=!t||this._scanner.tokenText(this._token);return this._token=this._scanner.next(),n}return!1},e.prototype._backTo=function(e){return this._scanner.pos=e.pos+e.len,this._token=e,!1},e.prototype._until=function(e){if(14===this._token.type)return!1;for(var t="",n=this._token.pos,i={type:14,pos:0,len:0};this._token.type!==e||5===i.type;)if(this._token.type===e&&(t+=this._scanner.value.substring(n,i.pos),n=this._token.pos),i=this._token,this._token=this._scanner.next(),14===this._token.type)return!1;return t+=this._scanner.value.substring(n,this._token.pos),this._token=this._scanner.next(),t},e.prototype._parse=function(e){return this._parseEscaped(e)||this._parseTabstopOrVariableName(e)||this._parseComplexPlaceholder(e)||this._parseComplexVariable(e)||this._parseAnything(e)},e.prototype._parseEscaped=function(e){var t;return!!(t=this._accept(5,!0))&&(t=this._accept(0,!0)||this._accept(4,!0)||this._accept(5,!0)||t,e.appendChild(new u(t)),!0)},e.prototype._parseTabstopOrVariableName=function(e){var t,n=this._token;return this._accept(0)&&(t=this._accept(9,!0)||this._accept(8,!0))?(e.appendChild(/^\d+$/.test(t)?new l(Number(t)):new p(t)),!0):this._backTo(n)},e.prototype._parseComplexPlaceholder=function(e){var t,n=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(8,!0))))return this._backTo(n);var i=new l(Number(t));if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(i),!0;if(!this._parse(i))return e.appendChild(new u("${"+t+":")),i.children.forEach(e.appendChild,e),!0}else{if(!(i.index>0&&this._accept(7)))return this._accept(6)?this._parseTransform(i)?(e.appendChild(i),!0):(this._backTo(n),!1):this._accept(4)?(e.appendChild(i),!0):this._backTo(n);for(var r=new d;;){if(this._parseChoiceElement(r)){if(this._accept(2))continue;if(this._accept(7)&&(i.appendChild(r),this._accept(4)))return e.appendChild(i),!0}return this._backTo(n),!1}}},e.prototype._parseChoiceElement=function(e){for(var t=this._token,n=[];2!==this._token.type&&7!==this._token.type;){var i=void 0;if(!(i=(i=this._accept(5,!0))?this._accept(2,!0)||this._accept(7,!0)||this._accept(5,!0)||i:this._accept(void 0,!0)))return this._backTo(t),!1;n.push(i)}return 0===n.length?(this._backTo(t),!1):(e.appendChild(new u(n.join(""))),!0)},e.prototype._parseComplexVariable=function(e){var t,n=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(9,!0))))return this._backTo(n);var i=new p(t);if(!this._accept(1))return this._accept(6)?this._parseTransform(i)?(e.appendChild(i),!0):(this._backTo(n),!1):this._accept(4)?(e.appendChild(i),!0):this._backTo(n);for(;;){if(this._accept(4))return e.appendChild(i),!0;if(!this._parse(i))return e.appendChild(new u("${"+t+":")),i.children.forEach(e.appendChild,e),!0}},e.prototype._parseTransform=function(e){for(var t=new h,n="",i="";!this._accept(6);){var r=void 0;if(r=this._accept(5,!0))n+=r=this._accept(6,!0)||r;else{if(14===this._token.type)return!1;n+=this._accept(void 0,!0)}}for(;!this._accept(6);){r=void 0;if(r=this._accept(5,!0))r=this._accept(5,!0)||this._accept(6,!0)||r,t.appendChild(new u(r));else if(!this._parseFormatString(t)&&!this._parseAnything(t))return!1}for(;!this._accept(4);){if(14===this._token.type)return!1;i+=this._accept(void 0,!0)}try{t.regexp=new RegExp(n,i)}catch(e){return!1}return e.transform=t,!0},e.prototype._parseFormatString=function(e){var t=this._token;if(!this._accept(0))return!1;var n=!1;this._accept(3)&&(n=!0);var i=this._accept(8,!0);if(!i)return this._backTo(t),!1;if(!n)return e.appendChild(new f(Number(i))),!0;if(this._accept(4))return e.appendChild(new f(Number(i))),!0;if(!this._accept(1))return this._backTo(t),!1;if(this._accept(6)){var r=this._accept(9,!0);return r&&this._accept(4)?(e.appendChild(new f(Number(i),r)),!0):(this._backTo(t),!1)}if(this._accept(11)){if(o=this._until(4))return e.appendChild(new f(Number(i),void 0,o,void 0)),!0}else if(this._accept(12)){if(s=this._until(4))return e.appendChild(new f(Number(i),void 0,void 0,s)),!0}else if(this._accept(13)){var o;if(o=this._until(1))if(s=this._until(4))return e.appendChild(new f(Number(i),void 0,o,s)),!0}else{var s;if(s=this._until(4))return e.appendChild(new f(Number(i),void 0,void 0,s)),!0}return this._backTo(t),!1},e.prototype._parseAnything=function(e){return 14!==this._token.type&&(e.appendChild(new u(this._scanner.tokenText(this._token))),this._accept(void 0),!0)},e}()},F11g:function(e,t,n){"use strict";var i=n("geuY"),r=n("HzeT"),o=n("lZ6o"),s=o.utils.assert,a=n("yMmo"),u=n("NMED");function c(e){if(!(this instanceof c))return new c(e);"string"==typeof e&&(s(o.curves.hasOwnProperty(e),"Unknown curve "+e),e=o.curves[e]),e instanceof o.curves.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}e.exports=c,c.prototype.keyPair=function(e){return new a(this,e)},c.prototype.keyFromPrivate=function(e,t){return a.fromPrivate(this,e,t)},c.prototype.keyFromPublic=function(e,t){return a.fromPublic(this,e,t)},c.prototype.genKeyPair=function(e){e||(e={});for(var t=new r({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||o.rand(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),n=this.n.byteLength(),s=this.n.sub(new i(2));;){var a=new i(t.generate(n));if(!(a.cmp(s)>0))return a.iaddn(1),this.keyFromPrivate(a)}},c.prototype._truncateToN=function(e,t){var n=8*e.byteLength()-this.n.bitLength();return n>0&&(e=e.ushrn(n)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},c.prototype.sign=function(e,t,n,o){"object"==typeof n&&(o=n,n=null),o||(o={}),t=this.keyFromPrivate(t,n),e=this._truncateToN(new i(e,16));for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),c=e.toArray("be",s),l=new r({hash:this.hash,entropy:a,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),d=this.n.sub(new i(1)),h=0;;h++){var f=o.k?o.k(h):new i(l.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(d)>=0)){var p=this.g.mul(f);if(!p.isInfinity()){var g=p.getX(),m=g.umod(this.n);if(0!==m.cmpn(0)){var v=f.invm(this.n).mul(m.mul(t.getPrivate()).iadd(e));if(0!==(v=v.umod(this.n)).cmpn(0)){var _=(p.getY().isOdd()?1:0)|(0!==g.cmp(m)?2:0);return o.canonical&&v.cmp(this.nh)>0&&(v=this.n.sub(v),_^=1),new u({r:m,s:v,recoveryParam:_})}}}}}},c.prototype.verify=function(e,t,n,r){e=this._truncateToN(new i(e,16)),n=this.keyFromPublic(n,r);var o=(t=new u(t,"hex")).r,s=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var a,c=s.invm(this.n),l=c.mul(e).umod(this.n),d=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(l,n.getPublic(),d)).isInfinity()&&a.eqXToP(o):!(a=this.g.mulAdd(l,n.getPublic(),d)).isInfinity()&&0===a.getX().umod(this.n).cmp(o)},c.prototype.recoverPubKey=function(e,t,n,r){s((3&n)===n,"The recovery param is more than two bits"),t=new u(t,r);var o=this.n,a=new i(e),c=t.r,l=t.s,d=1&n,h=n>>1;if(c.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");c=h?this.curve.pointFromX(c.add(this.curve.n),d):this.curve.pointFromX(c,d);var f=t.r.invm(o),p=o.sub(a).mul(f).umod(o),g=l.mul(f).umod(o);return this.g.mulAdd(p,c,g)},c.prototype.getKeyRecoveryParam=function(e,t,n,i){if(null!==(t=new u(t,i)).recoveryParam)return t.recoveryParam;for(var r=0;r<4;r++){var o;try{o=this.recoverPubKey(e,t,r)}catch(e){continue}if(o.eq(n))return r}throw new Error("Unable to find valid recovery factor")}},F5mM:function(e,t){},Fllr:function(e,t,n){"use strict";var i=n("zxiH"),r=n("Kp7x"),o=n("tqet"),s=n("aL7J"),a=n("vTy2"),u=n("+jct"),c=n("+oh4"),l=n("Eeyw"),d=function(){function e(t){if(t.autoClosingPairs?this._autoClosingPairs=t.autoClosingPairs.map(function(e){return new c.b(e)}):t.brackets?this._autoClosingPairs=t.brackets.map(function(e){return new c.b({open:e[0],close:e[1]})}):this._autoClosingPairs=[],t.__electricCharacterSupport&&t.__electricCharacterSupport.docComment){var n=t.__electricCharacterSupport.docComment;this._autoClosingPairs.push(new c.b({open:n.open,close:n.close||""}))}this._autoCloseBefore="string"==typeof t.autoCloseBefore?t.autoCloseBefore:e.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED,this._surroundingPairs=t.surroundingPairs||this._autoClosingPairs}return e.prototype.getAutoClosingPairs=function(){return this._autoClosingPairs},e.prototype.getAutoCloseBeforeSet=function(){return this._autoCloseBefore},e.shouldAutoClosePair=function(e,t,n){if(0===t.getTokenCount())return!0;var i=t.findTokenIndexAtOffset(n-2),r=t.getStandardTokenType(i);return e.isOK(r)},e.prototype.getSurroundingPairs=function(){return this._surroundingPairs},e.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED=";:.,=}])> \n\t",e}(),h=n("iNUG"),f=function(){function e(e){this._richEditBrackets=e}return e.prototype.getElectricCharacters=function(){var e=[];if(this._richEditBrackets)for(var t=0,n=this._richEditBrackets.brackets.length;t0&&n.length>0)for(i=0,r=this._brackets.length;i0)for(i=0,r=this._brackets.length;i1){var r=void 0,o=-1;for(r=t-1;r>=1;r--){if(e.getLanguageIdAtPosition(r,0)!==i)return o;var s=e.getLineContent(r);if(!n.shouldIgnore(s)&&!/^\s+$/.test(s)&&""!==s)return r;o=r}}return-1},e.prototype.getInheritIndentForLine=function(e,t,n){void 0===n&&(n=!0);var i=this.getIndentRulesSupport(e.getLanguageIdentifier().id);if(!i)return null;if(t<=1)return{indentation:"",action:null};var r=this.getPrecedingValidLine(e,t,i);if(r<0)return null;if(r<1)return{indentation:"",action:null};var o=e.getLineContent(r);if(i.shouldIncrease(o)||i.shouldIndentNextLine(o))return{indentation:s.s(o),action:c.a.Indent,line:r};if(i.shouldDecrease(o))return{indentation:s.s(o),action:null,line:r};if(1===r)return{indentation:s.s(e.getLineContent(r)),action:null,line:r};var a=r-1,u=i.getIndentMetadata(e.getLineContent(a));if(!(3&u)&&4&u){for(var l=0,d=a-1;d>0;d--)if(!i.shouldIndentNextLine(e.getLineContent(d))){l=d;break}return{indentation:s.s(e.getLineContent(l+1)),action:null,line:l+1}}if(n)return{indentation:s.s(e.getLineContent(r)),action:null,line:r};for(d=r;d>0;d--){var h=e.getLineContent(d);if(i.shouldIncrease(h))return{indentation:s.s(h),action:c.a.Indent,line:d};if(i.shouldIndentNextLine(h)){l=0;for(var f=d-1;f>0;f--)if(!i.shouldIndentNextLine(e.getLineContent(d))){l=f;break}return{indentation:s.s(e.getLineContent(l+1)),action:null,line:l+1}}if(i.shouldDecrease(h))return{indentation:s.s(h),action:null,line:d}}return{indentation:s.s(e.getLineContent(1)),action:null,line:1}},e.prototype.getGoodIndentForLine=function(e,t,n,r){var o=this.getIndentRulesSupport(t);if(!o)return null;var a=this.getInheritIndentForLine(e,n),u=e.getLineContent(n);if(a){var l=a.line;if(void 0!==l){var d=this._getOnEnterSupport(t),h=null;try{d&&(h=d.onEnter("",e.getLineContent(l),""))}catch(e){Object(i.e)(e)}if(h){var f=s.s(e.getLineContent(l));return h.removeText&&(f=f.substring(0,f.length-h.removeText)),h.indentAction===c.a.Indent||h.indentAction===c.a.IndentOutdent?f=r.shiftIndent(f):h.indentAction===c.a.Outdent&&(f=r.unshiftIndent(f)),o.shouldDecrease(u)&&(f=r.unshiftIndent(f)),h.appendText&&(f+=h.appendText),s.s(f)}}return o.shouldDecrease(u)?a.action===c.a.Indent?a.indentation:r.unshiftIndent(a.indentation):a.action===c.a.Indent?r.shiftIndent(a.indentation):a.indentation}return null},e.prototype.getIndentForEnter=function(e,t,n,i){e.forceTokenization(t.startLineNumber);var r,o,a=e.getLineTokens(t.startLineNumber),u=Object(l.a)(a,t.startColumn-1),d=u.getLineContent(),h=!1;(u.firstCharOffset>0&&a.getLanguageId(0)!==u.languageId?(h=!0,r=d.substr(0,t.startColumn-1-u.firstCharOffset)):r=a.getLineContent().substring(0,t.startColumn-1),t.isEmpty())?o=d.substr(t.startColumn-1-u.firstCharOffset):o=this.getScopedLineTokens(e,t.endLineNumber,t.endColumn).getLineContent().substr(t.endColumn-1-u.firstCharOffset);var f=this.getIndentRulesSupport(u.languageId);if(!f)return null;var p=r,g=s.s(r);if(!i&&!h){var m=this.getInheritIndentForLine(e,t.startLineNumber);f.shouldDecrease(r)&&m&&(g=m.indentation,m.action!==c.a.Indent&&(g=n.unshiftIndent(g))),p=g+s.B(s.B(r," "),"\t")}var v={getLineTokens:function(t){return e.getLineTokens(t)},getLanguageIdentifier:function(){return e.getLanguageIdentifier()},getLanguageIdAtPosition:function(t,n){return e.getLanguageIdAtPosition(t,n)},getLineContent:function(n){return n===t.startLineNumber?p:e.getLineContent(n)}},_=s.s(a.getLineContent()),b=this.getInheritIndentForLine(v,t.startLineNumber+1);if(!b){var y=h?_:g;return{beforeEnter:y,afterEnter:y}}var w=h?_:b.indentation;return b.action===c.a.Indent&&(w=n.shiftIndent(w)),f.shouldDecrease(o)&&(w=n.unshiftIndent(w)),{beforeEnter:h?_:g,afterEnter:w}},e.prototype.getIndentActionForType=function(e,t,n,i){var r=this.getScopedLineTokens(e,t.startLineNumber,t.startColumn),o=this.getIndentRulesSupport(r.languageId);if(!o)return null;var s,a=r.getLineContent(),u=a.substr(0,t.startColumn-1-r.firstCharOffset);t.isEmpty()?s=a.substr(t.startColumn-1-r.firstCharOffset):s=this.getScopedLineTokens(e,t.endLineNumber,t.endColumn).getLineContent().substr(t.endColumn-1-r.firstCharOffset);if(!o.shouldDecrease(u+s)&&o.shouldDecrease(u+n+s)){var l=this.getInheritIndentForLine(e,t.startLineNumber,!1);if(!l)return null;var d=l.indentation;return l.action!==c.a.Indent&&(d=i.unshiftIndent(d)),d}return null},e.prototype.getIndentMetadata=function(e,t){var n=this.getIndentRulesSupport(e.getLanguageIdentifier().id);return n?t<1||t>e.getLineCount()?null:n.getIndentMetadata(e.getLineContent(t)):null},e.prototype._getOnEnterSupport=function(e){var t=this._getRichEditSupport(e);return t&&t.onEnter||null},e.prototype.getRawEnterActionAtPosition=function(e,t,n){var i=this.getEnterAction(e,new a.a(t,n,t,n));return i?i.enterAction:null},e.prototype.getEnterAction=function(e,t){var n=this.getIndentationAtPosition(e,t.startLineNumber,t.startColumn),r=this.getScopedLineTokens(e,t.startLineNumber,t.startColumn),o=this._getOnEnterSupport(r.languageId);if(!o)return null;var s,a=r.getLineContent(),u=a.substr(0,t.startColumn-1-r.firstCharOffset);t.isEmpty()?s=a.substr(t.startColumn-1-r.firstCharOffset):s=this.getScopedLineTokens(e,t.endLineNumber,t.endColumn).getLineContent().substr(t.endColumn-1-r.firstCharOffset);var l=t.startLineNumber,d="";if(l>1&&0===r.firstCharOffset){var h=this.getScopedLineTokens(e,l-1);h.languageId===r.languageId&&(d=h.getLineContent())}var f=null;try{f=o.onEnter(d,u,s)}catch(e){Object(i.e)(e)}return f?(f.appendText||(f.indentAction===c.a.Indent||f.indentAction===c.a.IndentOutdent?f.appendText="\t":f.appendText=""),f.removeText&&(n=n.substring(0,n.length-f.removeText)),{enterAction:f,indentation:n}):null},e.prototype.getIndentationAtPosition=function(e,t,n){var i=e.getLineContent(t),r=s.s(i);return r.length>n-1&&(r=r.substring(0,n-1)),r},e.prototype.getScopedLineTokens=function(e,t,n){e.forceTokenization(t);var i=e.getLineTokens(t),r=void 0===n?e.getLineMaxColumn(t)-1:n-1;return Object(l.a)(i,r)},e.prototype.getBracketsSupport=function(e){var t=this._getRichEditSupport(e);return t&&t.brackets||null},e}())},G7Ib:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("03Zz"),r=n("0Td8");Object(i.h)(r.f),Object(i.f)(r.e),Object(i.f)(r.g),Object(i.f)(r.h),Object(i.f)(r.d),Object(i.f)(r.a),Object(i.f)(r.c),Object(i.g)(new r.b)},G8r4:function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("Kp7x"),r=new(function(){function e(){this._zoomLevel=0,this._onDidChangeZoomLevel=new i.a,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event}return e.prototype.getZoomLevel=function(){return this._zoomLevel},e.prototype.setZoomLevel=function(e){e=Math.min(Math.max(-5,e),20),this._zoomLevel!==e&&(this._zoomLevel=e,this._onDidChangeZoomLevel.fire(this._zoomLevel))},e}())},GUE9:function(e,t,n){(function(t,i){var r,o=n("2JY6"),s=n("35aj"),a=n("Zq1s"),u=n("X3l8").Buffer,c=t.crypto&&t.crypto.subtle,l={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},d=[];function h(e,t,n,i,r){return c.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then(function(e){return c.deriveBits({name:"PBKDF2",salt:t,iterations:n,hash:{name:r}},e,i<<3)}).then(function(e){return u.from(e)})}e.exports=function(e,n,f,p,g,m){"function"==typeof g&&(m=g,g=void 0);var v=l[(g=g||"sha1").toLowerCase()];if(!v||"function"!=typeof t.Promise)return i.nextTick(function(){var t;try{t=a(e,n,f,p,g)}catch(e){return m(e)}m(null,t)});if(o(e,n,f,p),"function"!=typeof m)throw new Error("No callback provided to pbkdf2");u.isBuffer(e)||(e=u.from(e,s)),u.isBuffer(n)||(n=u.from(n,s)),function(e,t){e.then(function(e){i.nextTick(function(){t(null,e)})},function(e){i.nextTick(function(){t(e)})})}(function(e){if(t.process&&!t.process.browser)return Promise.resolve(!1);if(!c||!c.importKey||!c.deriveBits)return Promise.resolve(!1);if(void 0!==d[e])return d[e];var n=h(r=r||u.alloc(8),r,10,128,e).then(function(){return!0}).catch(function(){return!1});return d[e]=n,n}(v).then(function(t){return t?h(e,n,f,p,v):a(e,n,f,p,g)}),m)}}).call(t,n("DuR2"),n("W2nU"))},GV5w:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"GotoLineEntry",function(){return g}),n.d(t,"GotoLineAction",function(){return m});var i,r=n("wtJh"),o=(n.n(r),n("aL7J")),s=n("Al6Q"),a=n("P1SM"),u=n("03Zz"),c=n("artP"),l=n("vTy2"),d=n("/9db"),h=n("zwZj"),f=n("EfIu"),p=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=function(e){function t(t,n,i){var r=e.call(this)||this;return r.editor=n,r.decorator=i,r.parseResult=r.parseInput(t),r}return p(t,e),t.prototype.parseInput=function(e){var t,n,i=e.split(",").map(function(e){return parseInt(e,10)}).filter(function(e){return!isNaN(e)});if(t=0===i.length?new c.a(-1,-1):1===i.length?new c.a(i[0],1):new c.a(i[0],i[1]),Object(a.a)(this.editor))n=this.editor.getModel();else{var r=this.editor.getModel();n=r?r.modified:null}var s=!!n&&n.validatePosition(t).equals(t);return{position:t,isValid:s,label:s?t.column&&t.column>1?o.r(f.b.gotoLineLabelValidLineAndColumn,t.lineNumber,t.column):o.r(f.b.gotoLineLabelValidLine,t.lineNumber):t.lineNumber<1||t.lineNumber>(n?n.getLineCount():0)?o.r(f.b.gotoLineLabelEmptyWithLineLimit,n?n.getLineCount():0):o.r(f.b.gotoLineLabelEmptyWithLineAndColumnLimit,n?n.getLineMaxColumn(t.lineNumber):0)}},t.prototype.getLabel=function(){return this.parseResult.label},t.prototype.getAriaLabel=function(){var e=this.editor.getPosition(),t=e?e.lineNumber:0;return o.r(f.b.gotoLineAriaLabel,t,this.parseResult.label)},t.prototype.run=function(e,t){return 1===e?this.runOpen():this.runPreview()},t.prototype.runOpen=function(){if(!this.parseResult.isValid)return!1;var e=this.toSelection();return this.editor.setSelection(e),this.editor.revealRangeInCenter(e,0),this.editor.focus(),!0},t.prototype.runPreview=function(){if(!this.parseResult.isValid)return this.decorator.clearDecorations(),!1;var e=this.toSelection();return this.editor.revealRangeInCenter(e,0),this.decorator.decorateLine(e,this.editor),!1},t.prototype.toSelection=function(){return new l.a(this.parseResult.position.lineNumber,this.parseResult.position.column,this.parseResult.position.lineNumber,this.parseResult.position.column)},t}(s.a),m=function(e){function t(){return e.call(this,f.b.gotoLineActionInput,{id:"editor.action.gotoLine",label:f.b.gotoLineActionLabel,alias:"Go to Line...",precondition:void 0,kbOpts:{kbExpr:d.a.focus,primary:2085,mac:{primary:293},weight:100}})||this}return p(t,e),t.prototype.run=function(e,t){var n=this;this._show(this.getController(t),{getModel:function(e){return new s.c([new g(e,t,n.getController(t))])},getAutoFocus:function(e){return{autoFocusFirstEntry:e.length>0}}})},t}(h.a);Object(u.f)(m)},GYOr:function(e,t,n){"use strict";n.d(t,"g",function(){return s}),t.f=function(e,t,n){void 0===n&&(n=!1);if("string"!=typeof e||"string"!=typeof t)return null;var i=b.get(e);i||(i=new RegExp(r.j(e),"i"),b.set(e,i));var o=i.exec(t);if(o)return[{start:o.index,end:o.index+o[0].length}];return n?_(e,t):v(e,t)},t.b=function(e,t,n,i,r,o){var s=I(e,t,0,i,r,0,!0);if(s)return s;for(var a=0,u=0,c=o,l=0;l=0)u+=1,a+=Math.pow(2,d),c=d+1;else if(0!==a)break}return[u,a,o]},t.c=function(e){if(void 0===e)return[];for(var t=e[1].toString(2),n=[],i=e[2];i=3)for(var c=Math.min(7,e.length-1),l=n+1;lu[0])&&(u=h))}}return u}(e,t,n,i,r,o,!0,s)};var i=n("WTFd"),r=n("aL7J");function o(){for(var e=[],t=0;t0?[{start:0,end:t.length}]:[]}.bind(void 0,!0);function a(e){return 97<=e&&e<=122}function u(e){return 65<=e&&e<=90}function c(e){return 48<=e&&e<=57}function l(e){return 32===e||9===e||10===e||13===e}var d=new Set;function h(e){return a(e)||u(e)||c(e)}function f(e,t){return 0===t.length?t=[e]:e.end===t[0].start?t[0].start=e.start:t.unshift(e),t}function p(e,t){for(var n=t;n0&&!h(e.charCodeAt(n-1)))return n}return e.length}function g(e,t,n,i){if(n===e.length)return[];if(i===t.length)return null;if(e[n]!==t[i].toLowerCase())return null;var r=null,o=i+1;for(r=g(e,t,n+1,i+1);!r&&(o=p(t,o))60)return null;var n=function(e){for(var t=0,n=0,i=0,r=0,o=0,s=0;s.2&&t<.8&&i>.6&&r<.2}(n)){if(!function(e){var t=e.upperPercent;return 0===e.lowerPercent&&t>.6}(n))return null;t=t.toLowerCase()}var i=null,r=0;for(e=e.toLowerCase();r/?".split("").forEach(function(e){return d.add(e.charCodeAt(0))});var v=o(s,m,function(e,t){var n=t.toLowerCase().indexOf(e.toLowerCase());return-1===n?null:[{start:n,end:n+e.length}]}),_=o(s,m,function(e,t){return function e(t,n,i,r){if(i===t.length)return[];if(r===n.length)return null;if(t[i]===n[r]){var o=null;return(o=e(t,n,i+1,r+1))?f({start:r,end:r+1},o):null}return e(t,n,i,r+1)}(e.toLowerCase(),t.toLowerCase(),0,0)}),b=new i.a(1e4);var y=128;function w(){for(var e=[],t=[0],n=1;n<=y;n++)t.push(-n);for(n=0;n<=y;n++){var i=t.slice(0);i[0]=-n,e.push(i)}return e}var C,S=w(),x=w(),L=w(),O=!1;function k(e,t,n,i,r){function o(e,t,n){for(void 0===n&&(n=" ");e.length=e.length)return!1;switch(e.charCodeAt(t)){case 95:case 45:case 46:case 32:case 47:case 92:case 39:case 34:case 58:case 36:return!0;default:return!1}}function E(e,t,n){return t[e]!==n[e]}function I(e,t,n,i,r,o,s){var a=e.length>y?y:e.length,u=i.length>y?y:i.length;if(!(n>=a||o>=u||a>u)&&function(e,t,n,i,r,o){for(;t1?1:f),g=S[c-1][l]+-1,m=S[c][l-1]+-1;m>=g?m>p?(S[c][l]=m,L[c][l]=4):m===p?(S[c][l]=m,L[c][l]=6):(S[c][l]=p,L[c][l]=2):g>p?(S[c][l]=g,L[c][l]=1):g===p?(S[c][l]=g,L[c][l]=3):(S[c][l]=p,L[c][l]=2)}if(O&&function(e,t,n,i){e=e.substr(t),n=n.substr(i),console.log(k(S,e,e.length,n,n.length)),console.log(k(L,e,e.length,n,n.length)),console.log(k(x,e,e.length,n,n.length))}(e,n,i,o),M=0,P=-100,A=o,R=s,function e(t,n,i,r,o){if(M>=10||i<-25)return;var s=0;for(;t>0&&n>0;){var a=x[t][n],u=L[t][n];if(4===u)n-=1,o?i-=5:0!==r&&(i-=1),o=!1,s=0;else{if(!(2&u))return;if(4&u&&e(t,n-1,0!==r?i-1:i,r,o),i+=a,t-=1,n-=1,o=!0,r+=Math.pow(2,n+A),1===a){if(s+=1,0===t&&!R)return}else i+=1+s*(a-1),s=0}}i-=n>=3?9:3*n;M+=1;i>P&&(P=i,T=r)}(c-1,l-1,a===u?1:0,0,!1),0!==M)return[P,T,o]}}function D(e,t,n,i,r,o,s){return t[n]!==o[s]?-1:s===n-i?e[n]===r[s]?7:5:!E(s,r,o)||0!==s&&E(s-1,r,o)?!N(o,s)||0!==s&&N(o,s-1)?N(o,s-1)||function(e,t){if(t<0||t>=e.length)return!1;switch(e.charCodeAt(t)){case 32:case 9:return!0;default:return!1}}(o,s-1)?5:1:5:e[n]===r[s]?7:5}!function(e){e.Default=Object.freeze([-100,0,0]),e.isDefault=function(e){return!e||-100===e[0]&&0===e[1]&&0===e[2]}}(C||(C={}));var M=0,T=0,P=0,A=0,R=!1;function F(e,t){if(!(t+1>=e.length)){var n=e[t],i=e[t+1];if(n!==i)return e.slice(0,t)+i+n+e.slice(t+2)}}},GZKt:function(e,t){},GfE5:function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return o});var i=n("CQAd"),r=function(){function e(t){var n=Object(i.d)(t);this._defaultValue=n,this._asciiMap=e._createAsciiMap(n),this._map=new Map}return e._createAsciiMap=function(e){for(var t=new Uint8Array(256),n=0;n<256;n++)t[n]=e;return t},e.prototype.set=function(e,t){var n=Object(i.d)(t);e>=0&&e<256?this._asciiMap[e]=n:this._map.set(e,n)},e.prototype.get=function(e){return e>=0&&e<256?this._asciiMap[e]:this._map.get(e)||this._defaultValue},e}(),o=function(){function e(){this._actual=new r(0)}return e.prototype.add=function(e){this._actual.set(e,1)},e.prototype.has=function(e){return 1===this._actual.get(e)},e}()},GgF8:function(e,t){var n="[object String]",i=Object.prototype.toString,r=Array.isArray;e.exports=function(e){return"string"==typeof e||!r(e)&&function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},GsV8:function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return o});var i=n("JVO/"),r=Object(i.c)("openerService"),o=Object.freeze({_serviceBrand:void 0,registerOpener:function(){return{dispose:function(){}}},registerValidator:function(){return{dispose:function(){}}},open:function(){return Promise.resolve(!1)}})},Gu5N:function(e,t){},Gu7T:function(e,t,n){"use strict";t.__esModule=!0;var i,r=n("c/Tr"),o=(i=r)&&i.__esModule?i:{default:i};t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);tl&&(d=l,h=e.model.getLineMaxColumn(d)),o.d.fromModelState(new o.f(new c.a(s.lineNumber,1,d,h),0,new u.a(d,h),0))}var f=t.modelState.selectionStart.getStartPosition().lineNumber;if(s.lineNumberf){l=e.viewModel.getLineCount();var p=a.lineNumber+1,g=1;return p>l&&(p=l,g=e.viewModel.getLineMaxColumn(p)),o.d.fromViewState(t.viewState.move(t.modelState.hasSelection(),p,g,0))}var m=t.modelState.selectionStart.getEndPosition();return o.d.fromModelState(t.modelState.move(t.modelState.hasSelection(),m.lineNumber,m.column,0))},e.word=function(e,t,n,i){var r=e.model.validatePosition(i);return o.d.fromModelState(a.a.word(e.config,e.model,t.modelState,n,r))},e.cancelSelection=function(e,t){if(!t.modelState.hasSelection())return new o.d(t.modelState,t.viewState);var n=t.viewState.position.lineNumber,i=t.viewState.position.column;return o.d.fromViewState(new o.f(new c.a(n,i,n,i),0,new u.a(n,i),0))},e.moveTo=function(e,t,n,i,r){var s=e.model.validatePosition(i),a=r?e.validateViewPosition(new u.a(r.lineNumber,r.column),s):e.convertModelPositionToViewPosition(s);return o.d.fromViewState(t.viewState.move(n,a.lineNumber,a.column,0))},e.move=function(e,t,n){var i=n.select,r=n.value;switch(n.direction){case 0:return 4===n.unit?this._moveHalfLineLeft(e,t,i):this._moveLeft(e,t,i,r);case 1:return 4===n.unit?this._moveHalfLineRight(e,t,i):this._moveRight(e,t,i,r);case 2:return 2===n.unit?this._moveUpByViewLines(e,t,i,r):this._moveUpByModelLines(e,t,i,r);case 3:return 2===n.unit?this._moveDownByViewLines(e,t,i,r):this._moveDownByModelLines(e,t,i,r);case 4:return this._moveToViewMinColumn(e,t,i);case 5:return this._moveToViewFirstNonWhitespaceColumn(e,t,i);case 6:return this._moveToViewCenterColumn(e,t,i);case 7:return this._moveToViewMaxColumn(e,t,i);case 8:return this._moveToViewLastNonWhitespaceColumn(e,t,i);case 9:var o=t[0],s=e.getCompletelyVisibleModelRange(),a=this._firstLineNumberInRange(e.model,s,r),u=e.model.getLineFirstNonWhitespaceColumn(a);return[this._moveToModelPosition(e,o,i,a,u)];case 11:o=t[0],s=e.getCompletelyVisibleModelRange(),a=this._lastLineNumberInRange(e.model,s,r),u=e.model.getLineFirstNonWhitespaceColumn(a);return[this._moveToModelPosition(e,o,i,a,u)];case 10:o=t[0],s=e.getCompletelyVisibleModelRange(),a=Math.round((s.startLineNumber+s.endLineNumber)/2),u=e.model.getLineFirstNonWhitespaceColumn(a);return[this._moveToModelPosition(e,o,i,a,u)];case 12:for(var c=e.getCompletelyVisibleViewRange(),l=[],d=0,h=t.length;dn.endLineNumber-1&&(r=n.endLineNumber-1),rr,d=i>o,h=io)continue;if(bi)continue;if(_1&&r--,e.columnSelect(t,n,i.fromViewLineNumber,i.fromViewVisualColumn,i.toViewLineNumber,r)},e.columnSelectRight=function(e,t,n){for(var i=0,r=Math.min(n.fromViewLineNumber,n.toViewLineNumber),o=Math.max(n.fromViewLineNumber,n.toViewLineNumber),s=r;s<=o;s++){var c=t.getLineMaxColumn(s),l=a.a.visibleColumnFromColumn2(e,t,new u.a(s,c));i=Math.max(i,l)}var d=n.toViewVisualColumn;return d1)for(var o=n.modelState?n.modelState.position:null,s=n.viewState?n.viewState.position:null,a=0,u=r.length;ar&&(i=r);var o=new c.a(i,1,i,e.context.model.getLineMaxColumn(i)),s=0;if(n.at)switch(n.at){case b.RawAtArgument.Top:s=3;break;case b.RawAtArgument.Center:s=1;break;case b.RawAtArgument.Bottom:s=4}var a=e.context.convertModelRangeToViewRange(o);e.revealRange(!1,a,s,0)},t}(k))),e.SelectAll=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"selectAll",precondition:void 0})||this}return L(t,e),t.prototype.runCoreEditorCommand=function(e,t){e.context.model.pushStackElement(),e.setStates(t.source,3,[h.b.selectAll(e.context,e.getPrimaryCursor())])},t}(k))),e.SetSelection=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"setSelection",precondition:void 0})||this}return L(t,e),t.prototype.runCoreEditorCommand=function(e,t){e.context.model.pushStackElement(),e.setStates(t.source,3,[a.d.fromModelSelection(t.selection)])},t}(k)))}(w||(w={})),S=C||(C={}),x=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return L(t,e),t.prototype.runEditorCommand=function(e,t,n){var i=t._getCursors();i&&this.runCoreEditingCommand(t,i,n||{})},t}(o.c),S.CoreEditingCommand=x,S.LineBreakInsert=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"lineBreakInsert",precondition:g.a.writable,kbOpts:{weight:O,kbExpr:g.a.textInputFocus,primary:0,mac:{primary:301}}})||this}return L(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){e.pushUndoStop(),e.executeCommands(this.id,f.a.lineBreakInsert(t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection})))},t}(x))),S.Outdent=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"outdent",precondition:g.a.writable,kbOpts:{weight:O,kbExpr:m.a.and(g.a.editorTextFocus,g.a.tabDoesNotMoveFocus),primary:1026}})||this}return L(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){e.pushUndoStop(),e.executeCommands(this.id,f.a.outdent(t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection}))),e.pushUndoStop()},t}(x))),S.Tab=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"tab",precondition:g.a.writable,kbOpts:{weight:O,kbExpr:m.a.and(g.a.editorTextFocus,g.a.tabDoesNotMoveFocus),primary:2}})||this}return L(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){e.pushUndoStop(),e.executeCommands(this.id,f.a.tab(t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection}))),e.pushUndoStop()},t}(x))),S.DeleteLeft=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"deleteLeft",precondition:g.a.writable,kbOpts:{weight:O,kbExpr:g.a.textInputFocus,primary:1,secondary:[1025],mac:{primary:1,secondary:[1025,294,257]}}})||this}return L(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){var i=d.a.deleteLeft(t.getPrevEditOperationType(),t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection})),r=i[0],o=i[1];r&&e.pushUndoStop(),e.executeCommands(this.id,o),t.setPrevEditOperationType(2)},t}(x))),S.DeleteRight=Object(o.g)(new(function(e){function t(){return e.call(this,{id:"deleteRight",precondition:g.a.writable,kbOpts:{weight:O,kbExpr:g.a.textInputFocus,primary:20,mac:{primary:20,secondary:[290,276]}}})||this}return L(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){var i=d.a.deleteRight(t.getPrevEditOperationType(),t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection})),r=i[0],o=i[1];r&&e.pushUndoStop(),e.executeCommands(this.id,o),t.setPrevEditOperationType(3)},t}(x)));var E=function(e){function t(t){var n=e.call(this,t)||this;return n._editorHandler=t.editorHandler,n._inputHandler=t.inputHandler,n}return L(t,e),t.prototype.runCommand=function(e,t){var n=e.get(s.a).getFocusedCodeEditor();if(n&&n.hasTextFocus())return this._runEditorHandler(e,n,t);var i=document.activeElement;if(!(i&&["input","textarea"].indexOf(i.tagName.toLowerCase())>=0)){var r=e.get(s.a).getActiveCodeEditor();return r?(r.focus(),this._runEditorHandler(e,r,t)):void 0}document.execCommand(this._inputHandler)},t.prototype._runEditorHandler=function(e,t,n){var i=this._editorHandler;"string"==typeof i?t.trigger("keyboard",i,n):((n=n||{}).source="keyboard",i.runEditorCommand(e,t,n))},t}(o.a),I=function(e){function t(t,n,i){var r=e.call(this,{id:t,precondition:void 0,description:i})||this;return r._handlerId=n,r}return L(t,e),t.prototype.runCommand=function(e,t){var n=e.get(s.a).getFocusedCodeEditor();n&&n.trigger("keyboard",this._handlerId,t)},t}(o.a);function D(e,t){N(new I("default:"+e,e)),N(new I(e,e,t))}N(new E({editorHandler:w.SelectAll,inputHandler:"selectAll",id:"editor.action.selectAll",precondition:g.a.textInputFocus,kbOpts:{weight:O,kbExpr:null,primary:2079},menubarOpts:{menuId:22,group:"1_basic",title:i.a({key:"miSelectAll",comment:["&& denotes a mnemonic"]},"&&Select All"),order:1}})),N(new E({editorHandler:p.b.Undo,inputHandler:"undo",id:p.b.Undo,precondition:g.a.writable,kbOpts:{weight:O,kbExpr:g.a.textInputFocus,primary:2104},menubarOpts:{menuId:14,group:"1_do",title:i.a({key:"miUndo",comment:["&& denotes a mnemonic"]},"&&Undo"),order:1}})),N(new I("default:"+p.b.Undo,p.b.Undo)),N(new E({editorHandler:p.b.Redo,inputHandler:"redo",id:p.b.Redo,precondition:g.a.writable,kbOpts:{weight:O,kbExpr:g.a.textInputFocus,primary:2103,secondary:[3128],mac:{primary:3128}},menubarOpts:{menuId:14,group:"1_do",title:i.a({key:"miRedo",comment:["&& denotes a mnemonic"]},"&&Redo"),order:2}})),N(new I("default:"+p.b.Redo,p.b.Redo)),D(p.b.Type,{description:"Type",args:[{name:"args",schema:{type:"object",required:["text"],properties:{text:{type:"string"}}}}]}),D(p.b.ReplacePreviousChar),D(p.b.CompositionStart),D(p.b.CompositionEnd),D(p.b.Paste),D(p.b.Cut)},Hv4S:function(e,t){},HzeT:function(e,t,n){"use strict";var i=n("3PYz"),r=n("tpuU"),o=n("08Lv");function s(e){if(!(this instanceof s))return new s(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=r.toArray(e.entropy,e.entropyEnc||"hex"),n=r.toArray(e.nonce,e.nonceEnc||"hex"),i=r.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,n,i)}e.exports=s,s.prototype._init=function(e,t,n){var i=e.concat(t).concat(n);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var r=0;r=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(n||[])),this._reseed=1},s.prototype.generate=function(e,t,n,i){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(i=n,n=t,t=null),n&&(n=r.toArray(n,i||"hex"),this._update(n));for(var o=[];o.length=n)break;var r=e.charCodeAt(t);if(110===r||114===r||87===r)return!0}}return!1}(this.searchString):this.searchString.indexOf("\n")>=0;var t=null;try{t=i.k(this.searchString,this.isRegex,{matchCase:this.matchCase,wholeWord:!1,multiline:e,global:!0})}catch(e){return null}if(!t)return null;var n=!this.isRegex&&!e;return n&&this.searchString.toLowerCase()!==this.searchString.toUpperCase()&&(n=this.matchCase),new c(t,this.wordSeparators?Object(r.a)(this.wordSeparators):null,n?this.searchString:null)},e}();var c=function(){return function(e,t,n){this.regex=e,this.wordSeparators=t,this.simpleSearch=n}}();function l(e,t,n){if(!n)return new a.b(e,null);for(var i=[],r=0,o=t.length;r>0);t[r]>=e?i=r-1:t[r+1]>=e?(n=r,i=r):n=r+1}return n+1},e}(),h=function(){function e(){}return e.findMatches=function(e,t,n,i,r){var o=t.parseSearchRequest();return o?o.regex.multiline?this._doFindMatchesMultiline(e,n,new p(o.wordSeparators,o.regex),i,r):this._doFindMatchesLineByLine(e,n,o,i,r):[]},e._getMultilineMatchRange=function(e,t,n,i,r,o){var a,u,c=0;if(a=i?t+r+(c=i.findLineFeedCountBeforeOffset(r)):t+r,i){var l=i.findLineFeedCountBeforeOffset(r+o.length)-c;u=a+o.length+l}else u=a+o.length;var d=e.getPositionAt(a),h=e.getPositionAt(u);return new s.a(d.lineNumber,d.column,h.lineNumber,h.column)},e._doFindMatchesMultiline=function(e,t,n,i,r){var o,s=e.getOffsetAt(t.getStartPosition()),a=e.getValueInRange(t,1),u="\r\n"===e.getEOL()?new d(a):null,c=[],h=0;for(n.reset(0);o=n.next(a);)if(c[h++]=l(this._getMultilineMatchRange(e,s,a,u,o.index,o[0]),o,i),h>=r)return c;return c},e._doFindMatchesLineByLine=function(e,t,n,i,r){var o=[],s=0;if(t.startLineNumber===t.endLineNumber){var a=e.getLineContent(t.startLineNumber).substring(t.startColumn-1,t.endColumn-1);return s=this._findMatchesInLine(n,a,t.startLineNumber,t.startColumn-1,s,o,i,r),o}var u=e.getLineContent(t.startLineNumber).substring(t.startColumn-1);s=this._findMatchesInLine(n,u,t.startLineNumber,t.startColumn-1,s,o,i,r);for(var c=t.startLineNumber+1;c=c))return r;return r}var _,b=new p(e.wordSeparators,e.regex);b.reset(0);do{if((_=b.next(t))&&(o[r++]=l(new s.a(n,_.index+1+i,n,_.index+1+_[0].length+i),_,u),r>=c))return r}while(_);return r},e.findNextMatch=function(e,t,n,i){var r=t.parseSearchRequest();if(!r)return null;var o=new p(r.wordSeparators,r.regex);return r.regex.multiline?this._doFindNextMatchMultiline(e,n,o,i):this._doFindNextMatchLineByLine(e,n,o,i)},e._doFindNextMatchMultiline=function(e,t,n,i){var r=new o.a(t.lineNumber,1),a=e.getOffsetAt(r),u=e.getLineCount(),c=e.getValueInRange(new s.a(r.lineNumber,r.column,u,e.getLineMaxColumn(u)),1),h="\r\n"===e.getEOL()?new d(c):null;n.reset(t.column-1);var f=n.next(c);return f?l(this._getMultilineMatchRange(e,a,c,h,f.index,f[0]),f,i):1!==t.lineNumber||1!==t.column?this._doFindNextMatchMultiline(e,new o.a(1,1),n,i):null},e._doFindNextMatchLineByLine=function(e,t,n,i){var r=e.getLineCount(),o=t.lineNumber,s=e.getLineContent(o),a=this._findFirstMatchInLine(n,s,o,t.column,i);if(a)return a;for(var u=1;u<=r;u++){var c=(o+u-1)%r,l=e.getLineContent(c+1),d=this._findFirstMatchInLine(n,l,c+1,1,i);if(d)return d}return null},e._findFirstMatchInLine=function(e,t,n,i,r){e.reset(i-1);var o=e.next(t);return o?l(new s.a(n,o.index+1,n,o.index+1+o[0].length),o,r):null},e.findPreviousMatch=function(e,t,n,i){var r=t.parseSearchRequest();if(!r)return null;var o=new p(r.wordSeparators,r.regex);return r.regex.multiline?this._doFindPreviousMatchMultiline(e,n,o,i):this._doFindPreviousMatchLineByLine(e,n,o,i)},e._doFindPreviousMatchMultiline=function(e,t,n,i){var r=this._doFindMatchesMultiline(e,new s.a(1,1,t.lineNumber,t.column),n,i,9990);if(r.length>0)return r[r.length-1];var a=e.getLineCount();return t.lineNumber!==a||t.column!==e.getLineMaxColumn(a)?this._doFindPreviousMatchMultiline(e,new o.a(a,e.getLineMaxColumn(a)),n,i):null},e._doFindPreviousMatchLineByLine=function(e,t,n,i){var r=e.getLineCount(),o=t.lineNumber,s=e.getLineContent(o).substring(0,t.column-1),a=this._findLastMatchInLine(n,s,o,i);if(a)return a;for(var u=1;u<=r;u++){var c=(r+o-u-1)%r,l=e.getLineContent(c+1),d=this._findLastMatchInLine(n,l,c+1,i);if(d)return d}return null},e._findLastMatchInLine=function(e,t,n,i){var r,o=null;for(e.reset(0);r=e.next(t);)o=l(new s.a(n,r.index+1,n,r.index+1+r[0].length),r,i);return o},e}();function f(e,t,n,i,r){return function(e,t,n,i,r){if(0===i)return!0;var o=t.charCodeAt(i-1);if(0!==e.get(o))return!0;if(13===o||10===o)return!0;if(r>0){var s=t.charCodeAt(i);if(0!==e.get(s))return!0}return!1}(e,t,0,i,r)&&function(e,t,n,i,r){if(i+r===n)return!0;var o=t.charCodeAt(i+r);if(0!==e.get(o))return!0;if(13===o||10===o)return!0;if(r>0){var s=t.charCodeAt(i+r-1);if(0!==e.get(s))return!0}return!1}(e,t,n,i,r)}var p=function(){function e(e,t){this._wordSeparators=e,this._searchRegex=t,this._prevMatchStartIndex=-1,this._prevMatchLength=0}return e.prototype.reset=function(e){this._searchRegex.lastIndex=e,this._prevMatchStartIndex=-1,this._prevMatchLength=0},e.prototype.next=function(e){var t,n=e.length;do{if(this._prevMatchStartIndex+this._prevMatchLength===n)return null;if(!(t=this._searchRegex.exec(e)))return null;var i=t.index,r=t[0].length;if(i===this._prevMatchStartIndex&&r===this._prevMatchLength){if(0===r){this._searchRegex.lastIndex+=1;continue}return null}if(this._prevMatchStartIndex=i,this._prevMatchLength=r,!this._wordSeparators||f(this._wordSeparators,e,n,i,r))return t}while(t);return null},e}()},IG52:function(e,t,n){"use strict";n.d(t,"c",function(){return g}),n.d(t,"d",function(){return m}),n.d(t,"b",function(){return v}),n.d(t,"a",function(){return b});var i,r=n("LC7R"),o=(n.n(r),n("ZfGv")),s=n("hK2W"),a=n("tqet"),u=n("AKCZ"),c=n("7/Cv"),l=n("KIxu"),d=n("Bug4"),h=n("gzF+"),f=n("Kp7x"),p=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=function(e){function t(t,n,i){var r=e.call(this)||this;return r.options=i,r._context=t||r,r._action=n,n instanceof u.a&&r._register(n.onDidChange(function(e){r.element&&r.handleActionChangeEvent(e)})),r}return p(t,e),t.prototype.handleActionChangeEvent=function(e){void 0!==e.enabled&&this.updateEnabled(),void 0!==e.checked&&this.updateChecked(),void 0!==e.class&&this.updateClass(),void 0!==e.label&&(this.updateLabel(),this.updateTooltip()),void 0!==e.tooltip&&this.updateTooltip()},Object.defineProperty(t.prototype,"actionRunner",{get:function(){return this._actionRunner},set:function(e){this._actionRunner=e},enumerable:!0,configurable:!0}),t.prototype.getAction=function(){return this._action},t.prototype.isEnabled=function(){return this._action.enabled},t.prototype.setActionContext=function(e){this._context=e},t.prototype.render=function(e){var t=this;this.element=e,d.b.addTarget(e);var n=this.options&&this.options.draggable;n&&(e.draggable=!0),this._register(c.h(this.element,d.a.Tap,function(e){return t.onClick(e)})),this._register(c.h(this.element,c.d.MOUSE_DOWN,function(e){n||c.c.stop(e,!0),t._action.enabled&&0===e.button&&t.element&&c.f(t.element,"active")})),this._register(c.h(this.element,c.d.CLICK,function(e){c.c.stop(e,!0),t.options&&t.options.isMenu?t.onClick(e):o.h(function(){return t.onClick(e)})})),this._register(c.h(this.element,c.d.DBLCLICK,function(e){c.c.stop(e,!0)})),[c.d.MOUSE_UP,c.d.MOUSE_OUT].forEach(function(e){t._register(c.h(t.element,e,function(e){c.c.stop(e),c.I(t.element,"active")}))})},t.prototype.onClick=function(e){var t;c.c.stop(e,!0),l.k(this._context)?t=e:(t=this._context,l.h(t)&&(t.event=e)),this._actionRunner.run(this._action,t)},t.prototype.focus=function(){this.element&&(this.element.focus(),c.f(this.element,"focused"))},t.prototype.blur=function(){this.element&&(this.element.blur(),c.I(this.element,"focused"))},t.prototype.updateEnabled=function(){},t.prototype.updateLabel=function(){},t.prototype.updateTooltip=function(){},t.prototype.updateClass=function(){},t.prototype.updateChecked=function(){},t.prototype.dispose=function(){this.element&&(c.K(this.element),this.element=void 0),e.prototype.dispose.call(this)},t}(a.a),m=function(e){function t(n){var i=e.call(this,t.ID,n,n?"separator text":"separator")||this;return i.checked=!1,i.radio=!1,i.enabled=!1,i}return p(t,e),t.ID="vs.actions.separator",t}(u.a),v=function(e){function t(t,n,i){void 0===i&&(i={});var r=e.call(this,t,n,i)||this;return r.options=i,r.options.icon=void 0!==i.icon&&i.icon,r.options.label=void 0===i.label||i.label,r.cssClass="",r}return p(t,e),t.prototype.render=function(t){e.prototype.render.call(this,t),this.element&&(this.label=c.m(this.element,c.a("a.action-label"))),this._action.id===m.ID?this.label.setAttribute("role","presentation"):this.options.isMenu?this.label.setAttribute("role","menuitem"):this.label.setAttribute("role","button"),this.options.label&&this.options.keybinding&&this.element&&(c.m(this.element,c.a("span.keybinding")).textContent=this.options.keybinding),this.updateClass(),this.updateLabel(),this.updateTooltip(),this.updateEnabled(),this.updateChecked()},t.prototype.focus=function(){e.prototype.focus.call(this),this.label.focus()},t.prototype.updateLabel=function(){this.options.label&&(this.label.textContent=this.getAction().label)},t.prototype.updateTooltip=function(){var e=null;this.getAction().tooltip?e=this.getAction().tooltip:!this.options.label&&this.getAction().label&&this.options.icon&&(e=this.getAction().label,this.options.keybinding&&(e=s.a({key:"titleLabel",comment:["action title","action keybinding"]},"{0} ({1})",e,this.options.keybinding))),e&&(this.label.title=e)},t.prototype.updateClass=function(){this.cssClass&&c.J(this.label,this.cssClass),this.options.icon?(this.cssClass=this.getAction().class,c.f(this.label,"icon"),this.cssClass&&c.g(this.label,this.cssClass),this.updateEnabled()):c.I(this.label,"icon")},t.prototype.updateEnabled=function(){this.getAction().enabled?(this.label.removeAttribute("aria-disabled"),this.element&&c.I(this.element,"disabled"),c.I(this.label,"disabled"),this.label.tabIndex=0):(this.label.setAttribute("aria-disabled","true"),this.element&&c.f(this.element,"disabled"),c.f(this.label,"disabled"),c.L(this.label))},t.prototype.updateChecked=function(){this.getAction().checked?c.f(this.label,"checked"):c.I(this.label,"checked")},t}(g),_={orientation:0,context:null,triggerKeys:{keys:[3,10],keyDown:!1}},b=function(e){function t(t,n){void 0===n&&(n=_);var i,r,o=e.call(this)||this;switch(o._onDidBlur=o._register(new f.a),o.onDidBlur=o._onDidBlur.event,o._onDidCancel=o._register(new f.a),o.onDidCancel=o._onDidCancel.event,o._onDidRun=o._register(new f.a),o.onDidRun=o._onDidRun.event,o._onDidBeforeRun=o._register(new f.a),o.onDidBeforeRun=o._onDidBeforeRun.event,o.options=n,o._context=n.context,o.options.triggerKeys||(o.options.triggerKeys=_.triggerKeys),o.options.actionRunner?o._actionRunner=o.options.actionRunner:(o._actionRunner=new u.b,o._register(o._actionRunner)),o._register(o._actionRunner.onDidRun(function(e){return o._onDidRun.fire(e)})),o._register(o._actionRunner.onDidBeforeRun(function(e){return o._onDidBeforeRun.fire(e)})),o.viewItems=[],o.focusedItem=void 0,o.domNode=document.createElement("div"),o.domNode.className="monaco-action-bar",!1!==n.animated&&c.f(o.domNode,"animated"),o.options.orientation){case 0:i=15,r=17;break;case 1:i=17,r=15,o.domNode.className+=" reverse";break;case 2:i=16,r=18,o.domNode.className+=" vertical";break;case 3:i=18,r=16,o.domNode.className+=" vertical reverse"}return o._register(c.h(o.domNode,c.d.KEY_DOWN,function(e){var t=new h.a(e),n=!0;t.equals(i)?o.focusPrevious():t.equals(r)?o.focusNext():t.equals(9)?o.cancel():o.isTriggerKeyEvent(t)?o.options.triggerKeys&&o.options.triggerKeys.keyDown&&o.doTrigger(t):n=!1,n&&(t.preventDefault(),t.stopPropagation())})),o._register(c.h(o.domNode,c.d.KEY_UP,function(e){var t=new h.a(e);o.isTriggerKeyEvent(t)?(o.options.triggerKeys&&!o.options.triggerKeys.keyDown&&o.doTrigger(t),t.preventDefault(),t.stopPropagation()):(t.equals(2)||t.equals(1026))&&o.updateFocusedItem()})),o.focusTracker=o._register(c.S(o.domNode)),o._register(o.focusTracker.onDidBlur(function(){document.activeElement!==o.domNode&&c.E(document.activeElement,o.domNode)||(o._onDidBlur.fire(),o.focusedItem=void 0)})),o._register(o.focusTracker.onDidFocus(function(){return o.updateFocusedItem()})),o.actionsList=document.createElement("ul"),o.actionsList.className="actions-container",o.actionsList.setAttribute("role","toolbar"),o.options.ariaLabel&&o.actionsList.setAttribute("aria-label",o.options.ariaLabel),o.domNode.appendChild(o.actionsList),t.appendChild(o.domNode),o}return p(t,e),t.prototype.isTriggerKeyEvent=function(e){var t=!1;return this.options.triggerKeys&&this.options.triggerKeys.keys.forEach(function(n){t=t||e.equals(n)}),t},t.prototype.updateFocusedItem=function(){for(var e=0;e=n.actionsList.children.length?(n.actionsList.appendChild(o),n.viewItems.push(i)):(n.actionsList.insertBefore(o,n.actionsList.children[r]),n.viewItems.splice(r,0,i),r++)})},t.prototype.clear=function(){this.viewItems=Object(a.f)(this.viewItems),c.p(this.actionsList)},t.prototype.isEmpty=function(){return 0===this.viewItems.length},t.prototype.focus=function(e){var t=!1,n=void 0;void 0===e?t=!0:"number"==typeof e?n=e:"boolean"==typeof e&&(t=e),t&&void 0===this.focusedItem?(this.focusedItem=this.viewItems.length-1,this.focusNext()):(void 0!==n&&(this.focusedItem=n),this.updateFocus())},t.prototype.focusNext=function(){void 0===this.focusedItem&&(this.focusedItem=this.viewItems.length-1);var e,t=this.focusedItem;do{this.focusedItem=(this.focusedItem+1)%this.viewItems.length,e=this.viewItems[this.focusedItem]}while(this.focusedItem!==t&&!e.isEnabled());this.focusedItem!==t||e.isEnabled()||(this.focusedItem=void 0),this.updateFocus()},t.prototype.focusPrevious=function(){void 0===this.focusedItem&&(this.focusedItem=0);var e,t=this.focusedItem;do{this.focusedItem=this.focusedItem-1,this.focusedItem<0&&(this.focusedItem=this.viewItems.length-1),e=this.viewItems[this.focusedItem]}while(this.focusedItem!==t&&!e.isEnabled());this.focusedItem!==t||e.isEnabled()||(this.focusedItem=void 0),this.updateFocus(!0)},t.prototype.updateFocus=function(e){void 0===this.focusedItem&&this.actionsList.focus();for(var t=0;t>>1];n=s.r28shl(n,a),r=s.r28shl(r,a),s.pc2(n,r,e.keys,o)}},u.prototype._update=function(e,t,n,i){var r=this._desState,o=s.readUInt32BE(e,t),a=s.readUInt32BE(e,t+4);s.ip(o,a,r.tmp,0),o=r.tmp[0],a=r.tmp[1],"encrypt"===this.type?this._encrypt(r,o,a,r.tmp,0):this._decrypt(r,o,a,r.tmp,0),o=r.tmp[0],a=r.tmp[1],s.writeUInt32BE(n,o,i),s.writeUInt32BE(n,a,i+4)},u.prototype._pad=function(e,t){for(var n=e.length-t,i=t;i>>0,o=h}s.rip(a,o,i,r)},u.prototype._decrypt=function(e,t,n,i,r){for(var o=n,a=t,u=e.keys.length-2;u>=0;u-=2){var c=e.keys[u],l=e.keys[u+1];s.expand(o,e.tmp,0),c^=e.tmp[0],l^=e.tmp[1];var d=s.substitute(c,l),h=o;o=(a^s.permute(d))>>>0,a=h}s.rip(o,a,i,r)}},IrTV:function(e,t,n){"use strict";n.d(t,"a",function(){return m});var i,r=n("TU7t"),o=n("vORD"),s=n("vZcR"),a=n("ItKl"),u=n("7g0X"),c=n("JVO/"),l=n("fAkY"),d=n("eoic"),h=n("xJaW"),f=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),p=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},g=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},m=function(e){function t(t,n,i,r,o,s,a,u,c,l){var d=e.call(this,t,i.getRawConfiguration(),{},r,o,s,a,u,c,l)||this;return d._parentEditor=i,d._overwriteOptions=n,e.prototype.updateOptions.call(d,d._overwriteOptions),d._register(i.onDidChangeConfiguration(function(e){return d._onParentConfigurationChanged(e)})),d}return f(t,e),t.prototype.getParentEditor=function(){return this._parentEditor},t.prototype._onParentConfigurationChanged=function(t){e.prototype.updateOptions.call(this,this._parentEditor.getRawConfiguration()),e.prototype.updateOptions.call(this,this._overwriteOptions)},t.prototype.updateOptions=function(t){r.g(this._overwriteOptions,t,!0),e.prototype.updateOptions.call(this,this._overwriteOptions)},t=p([g(3,c.a),g(4,o.a),g(5,a.b),g(6,u.c),g(7,d.c),g(8,l.a),g(9,h.b)],t)}(s.a)},ItKl:function(e,t,n){"use strict";n.d(t,"b",function(){return c}),n.d(t,"a",function(){return l});var i=n("tqet"),r=n("KIxu"),o=n("JVO/"),s=n("Kp7x"),a=n("EMhq"),u=n("WTFd"),c=Object(o.c)("commandService"),l=new(function(){function e(){this._commands=new Map,this._onDidRegisterCommand=new s.a,this.onDidRegisterCommand=this._onDidRegisterCommand.event}return e.prototype.registerCommand=function(e,t){var n=this;if(!e)throw new Error("invalid command");if("string"==typeof e){if(!t)throw new Error("invalid command");return this.registerCommand({id:e,handler:t})}if(e.description){for(var o=[],s=0,u=e.description.args;s0&&(f=t.apply(this,arguments)),e<=1&&(t=void 0),f}}function p(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=function(e){return f(2,e)}},"JVO/":function(e,t,n){"use strict";var i;n.d(t,"b",function(){return i}),n.d(t,"a",function(){return r}),t.c=s,t.d=function(e){return function(t,n,i){if(3!==arguments.length)throw new Error("@optional-decorator can only be used to decorate a parameter");o(e,t,i,!0)}},function(e){e.serviceIds=new Map,e.DI_TARGET="$di$target",e.DI_DEPENDENCIES="$di$dependencies",e.getServiceDependencies=function(t){return t[e.DI_DEPENDENCIES]||[]}}(i||(i={}));var r=s("instantiationService");function o(e,t,n,r){t[i.DI_TARGET]===t?t[i.DI_DEPENDENCIES].push({id:e,index:n,optional:r}):(t[i.DI_DEPENDENCIES]=[{id:e,index:n,optional:r}],t[i.DI_TARGET]=t)}function s(e){if(i.serviceIds.has(e))return i.serviceIds.get(e);var t=function(e,n,i){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");o(t,e,i,!1)};return t.toString=function(){return e},i.serviceIds.set(e,t),t}},JaR3:function(e,t,n){(t=e.exports=function(e){e=e.toLowerCase();var n=t[e];if(!n)throw new Error(e+" is not supported (we accept pull requests)");return new n}).sha=n("N1es"),t.sha1=n("KQ4j"),t.sha224=n("lXn8"),t.sha256=n("zvjZ"),t.sha384=n("aY2F"),t.sha512=n("C015")},JbsQ:function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("markerDecorationsService")},K8Am:function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("ZfGv"),r=i.b.performance&&"function"==typeof i.b.performance.now,o=function(){function e(e){this._highResolution=r&&e,this._startTime=this._now(),this._stopTime=-1}return e.create=function(t){return void 0===t&&(t=!0),new e(t)},e.prototype.stop=function(){this._stopTime=this._now()},e.prototype.elapsed=function(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime},e.prototype._now=function(){return this._highResolution?i.b.performance.now():(new Date).getTime()},e}()},KCUl:function(e,t,n){(function(t){var i=n("geuY"),r=n("lZ6o").ec,o=n("jkjm"),s=n("QDfD");function a(e,t){if(e.cmpn(0)<=0)throw new Error("invalid sig");if(e.cmp(t)>=t)throw new Error("invalid sig")}e.exports=function(e,n,u,c,l){var d=o(u);if("ec"===d.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,n){var i=s[n.data.algorithm.curve.join(".")];if(!i)throw new Error("unknown curve "+n.data.algorithm.curve.join("."));var o=new r(i),a=n.data.subjectPrivateKey.data;return o.verify(t,e,a)}(e,n,d)}if("dsa"===d.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,n){var r=n.data.p,s=n.data.q,u=n.data.g,c=n.data.pub_key,l=o.signature.decode(e,"der"),d=l.s,h=l.r;a(d,s),a(h,s);var f=i.mont(r),p=d.invm(s);return 0===u.toRed(f).redPow(new i(t).mul(p).mod(s)).fromRed().mul(c.toRed(f).redPow(h.mul(p).mod(s)).fromRed()).mod(r).mod(s).cmp(h)}(e,n,d)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");n=t.concat([l,n]);for(var h=d.modulus.byteLength(),f=[1],p=0;n.length+f.length+2>>27}function l(e){return e<<30|e>>>2}function d(e,t,n,i){return 0===e?t&n|~t&i:2===e?t&n|t&i|n&i:t^n^i}i(u,r),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,n=this._w,i=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,u=0|this._e,h=0;h<16;++h)n[h]=e.readInt32BE(4*h);for(;h<80;++h)n[h]=(t=n[h-3]^n[h-8]^n[h-14]^n[h-16])<<1|t>>>31;for(var f=0;f<80;++f){var p=~~(f/20),g=c(i)+d(p,r,o,a)+u+n[f]+s[p]|0;u=a,a=o,o=l(r),r=i,i=g}this._a=i+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},KU51:function(e,t){},KYqO:function(e,t){e.exports={name:"elliptic",version:"6.4.1",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny ",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"}}},"KeN/":function(e,t,n){(function(t){var i=n("BVsN"),r=n("9DG0"),o=n("LC74"),s=n("pn+s"),a=n("KCUl"),u=n("ejIc");function c(e){r.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function l(e){r.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hash=i(t.hash),this._tag=t.id,this._signType=t.sign}function d(e){return new c(e)}function h(e){return new l(e)}Object.keys(u).forEach(function(e){u[e].id=new t(u[e].id,"hex"),u[e.toLowerCase()]=u[e]}),o(c,r.Writable),c.prototype._write=function(e,t,n){this._hash.update(e),n()},c.prototype.update=function(e,n){return"string"==typeof e&&(e=new t(e,n)),this._hash.update(e),this},c.prototype.sign=function(e,t){this.end();var n=this._hash.digest(),i=s(n,e,this._hashType,this._signType,this._tag);return t?i.toString(t):i},o(l,r.Writable),l.prototype._write=function(e,t,n){this._hash.update(e),n()},l.prototype.update=function(e,n){return"string"==typeof e&&(e=new t(e,n)),this._hash.update(e),this},l.prototype.verify=function(e,n,i){"string"==typeof n&&(n=new t(n,i)),this.end();var r=this._hash.digest();return a(n,r,e,this._signType,this._tag)},e.exports={Sign:d,Verify:h,createSign:d,createVerify:h}}).call(t,n("EuP9").Buffer)},Kp7x:function(e,t,n){"use strict";n.d(t,"b",function(){return r}),n.d(t,"a",function(){return h}),n.d(t,"e",function(){return f}),n.d(t,"d",function(){return p}),n.d(t,"c",function(){return g}),n.d(t,"f",function(){return m});var i,r,o=n("zxiH"),s=n("dwjm"),a=n("tqet"),u=n("EMhq"),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});!function(e){function t(e){return function(t,n,i){void 0===n&&(n=null);var r,o=!1;return r=e(function(e){if(!o)return r?r.dispose():o=!0,t.call(n,e)},null,i),o&&r.dispose(),r}}function n(e,t){return s(function(n,i,r){return void 0===i&&(i=null),e(function(e){return n.call(i,t(e))},null,r)})}function i(e,t){return s(function(n,i,r){return void 0===i&&(i=null),e(function(e){t(e),n.call(i,e)},null,r)})}function r(e,t){return s(function(n,i,r){return void 0===i&&(i=null),e(function(e){return t(e)&&n.call(i,e)},null,r)})}function o(e,t,i){var r=i;return n(e,function(e){return r=t(r,e)})}function s(e){var t,n=new h({onFirstListenerAdd:function(){t=e(n.fire,n)},onLastListenerRemove:function(){t.dispose()}});return n.event}function u(e){var t,n=!0;return r(e,function(e){var i=n||e!==t;return n=!1,t=e,i})}e.None=function(){return a.a.None},e.once=t,e.map=n,e.forEach=i,e.filter=r,e.signal=function(e){return e},e.any=function(){for(var e=[],t=0;t1)&&c.fire(e),u=0},n)})},onLastListenerRemove:function(){o.dispose()}});return c.event},e.stopwatch=function(e){var i=(new Date).getTime();return n(t(e),function(e){return(new Date).getTime()-i})},e.latch=u,e.buffer=function(e,t,n){void 0===t&&(t=!1),void 0===n&&(n=[]);var i=n.slice(),r=e(function(e){i?i.push(e):s.fire(e)}),o=function(){i&&i.forEach(function(e){return s.fire(e)}),i=null},s=new h({onFirstListenerAdd:function(){r||(r=e(function(e){return s.fire(e)}))},onFirstListenerDidAdd:function(){i&&(t?setTimeout(o):o())},onLastListenerRemove:function(){r&&r.dispose(),r=null}});return s.event};var c=function(){function e(e){this.event=e}return e.prototype.map=function(t){return new e(n(this.event,t))},e.prototype.forEach=function(t){return new e(i(this.event,t))},e.prototype.filter=function(t){return new e(r(this.event,t))},e.prototype.reduce=function(t,n){return new e(o(this.event,t,n))},e.prototype.latch=function(){return new e(u(this.event))},e.prototype.on=function(e,t,n){return this.event(e,t,n)},e.prototype.once=function(e,n,i){return t(this.event)(e,n,i)},e}();e.chain=function(e){return new c(e)},e.fromNodeEventEmitter=function(e,t,n){void 0===n&&(n=function(e){return e});var i=function(){for(var e=[],t=0;t0?new d(this._options&&this._options.leakWarningThreshold):void 0}return Object.defineProperty(e.prototype,"event",{get:function(){var t=this;return this._event||(this._event=function(n,i,r){t._listeners||(t._listeners=new u.a);var o=t._listeners.isEmpty();o&&t._options&&t._options.onFirstListenerAdd&&t._options.onFirstListenerAdd(t);var s,c,l=t._listeners.push(i?[n,i]:n);return o&&t._options&&t._options.onFirstListenerDidAdd&&t._options.onFirstListenerDidAdd(t),t._options&&t._options.onListenerDidAdd&&t._options.onListenerDidAdd(t,n,i),t._leakageMon&&(s=t._leakageMon.check(t._listeners.size)),c={dispose:function(){(s&&s(),c.dispose=e._noop,t._disposed)||(l(),t._options&&t._options.onLastListenerRemove&&(t._listeners&&!t._listeners.isEmpty()||t._options.onLastListenerRemove(t)))}},r instanceof a.b?r.add(c):Array.isArray(r)&&r.push(c),c}),this._event},enumerable:!0,configurable:!0}),e.prototype.fire=function(e){if(this._listeners){this._deliveryQueue||(this._deliveryQueue=new u.a);for(var t=this._listeners.iterator(),n=t.next();!n.done;n=t.next())this._deliveryQueue.push([n.value,e]);for(;this._deliveryQueue.size>0;){var i=this._deliveryQueue.shift(),r=i[0],s=i[1];try{"function"==typeof r?r.call(void 0,s):r[0].call(r[1],s)}catch(n){Object(o.e)(n)}}}},e.prototype.dispose=function(){this._listeners&&this._listeners.clear(),this._deliveryQueue&&this._deliveryQueue.clear(),this._leakageMon&&this._leakageMon.dispose(),this._disposed=!0},e._noop=function(){},e}(),f=function(e){function t(t){var n=e.call(this,t)||this;return n._isPaused=0,n._eventQueue=new u.a,n._mergeFn=t&&t.merge,n}return c(t,e),t.prototype.pause=function(){this._isPaused++},t.prototype.resume=function(){if(0!==this._isPaused&&0==--this._isPaused)if(this._mergeFn){var t=this._eventQueue.toArray();this._eventQueue.clear(),e.prototype.fire.call(this,this._mergeFn(t))}else for(;!this._isPaused&&0!==this._eventQueue.size;)e.prototype.fire.call(this,this._eventQueue.shift())},t.prototype.fire=function(t){this._listeners&&(0!==this._isPaused?this._eventQueue.push(t):e.prototype.fire.call(this,t))},t}(h),p=function(){function e(){var e=this;this.hasListeners=!1,this.events=[],this.emitter=new h({onFirstListenerAdd:function(){return e.onFirstListenerAdd()},onLastListenerRemove:function(){return e.onLastListenerRemove()}})}return Object.defineProperty(e.prototype,"event",{get:function(){return this.emitter.event},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this,n={event:e,listener:null};this.events.push(n),this.hasListeners&&this.hook(n);return Object(a.h)(Object(s.a)(function(){t.hasListeners&&t.unhook(n);var e=t.events.indexOf(n);t.events.splice(e,1)}))},e.prototype.onFirstListenerAdd=function(){var e=this;this.hasListeners=!0,this.events.forEach(function(t){return e.hook(t)})},e.prototype.onLastListenerRemove=function(){var e=this;this.hasListeners=!1,this.events.forEach(function(t){return e.unhook(t)})},e.prototype.hook=function(e){var t=this;e.listener=e.event(function(e){return t.emitter.fire(e)})},e.prototype.unhook=function(e){e.listener&&e.listener.dispose(),e.listener=null},e.prototype.dispose=function(){this.emitter.dispose()},e}(),g=function(){function e(){this.buffers=[]}return e.prototype.wrapEvent=function(e){var t=this;return function(n,i,r){return e(function(e){var r=t.buffers[t.buffers.length-1];r?r.push(function(){return n.call(i,e)}):n.call(i,e)},void 0,r)}},e.prototype.bufferEvents=function(e){var t=[];this.buffers.push(t);var n=e();return this.buffers.pop(),t.forEach(function(e){return e()}),n},e}(),m=function(){function e(){var e=this;this.listening=!1,this.inputEvent=r.None,this.inputEventListener=a.a.None,this.emitter=new h({onFirstListenerDidAdd:function(){e.listening=!0,e.inputEventListener=e.inputEvent(e.emitter.fire,e.emitter)},onLastListenerRemove:function(){e.listening=!1,e.inputEventListener.dispose()}}),this.event=this.emitter.event}return Object.defineProperty(e.prototype,"input",{set:function(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.inputEventListener.dispose(),this.emitter.dispose()},e}()},Kx4b:function(e,t,n){"use strict";n.d(t,"a",function(){return a});var i=n("uNfg"),r=n("ZfGv"),o=n("ItKl"),s=n("RWr8"),a=new(function(){function e(){this._coreKeybindings=[],this._extensionKeybindings=[],this._cachedMergedKeybindings=null}return e.bindToCurrentPlatform=function(e){if(1===r.a){if(e&&e.win)return e.win}else if(2===r.a){if(e&&e.mac)return e.mac}else if(e&&e.linux)return e.linux;return e},e.prototype.registerKeybindingRule=function(t){var n=e.bindToCurrentPlatform(t);n&&n.primary&&((a=Object(i.f)(n.primary,r.a))&&this._registerDefaultKeybinding(a,t.id,void 0,t.weight,0,t.when));if(n&&Array.isArray(n.secondary))for(var o=0,s=n.secondary.length;o=21&&e<=30||(e>=31&&e<=56||(80===e||81===e||82===e||83===e||84===e||85===e||86===e||110===e||111===e||87===e||88===e||89===e||90===e||91===e||92===e))},e.prototype._assertNoCtrlAlt=function(t,n){t.ctrlKey&&t.altKey&&!t.metaKey&&e._mightProduceChar(t.keyCode)&&console.warn("Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ",t," for ",n)},e.prototype._registerDefaultKeybinding=function(e,t,n,i,o,s){1===r.a&&this._assertNoCtrlAlt(e.parts[0],t),this._coreKeybindings.push({keybinding:e,command:t,commandArgs:n,when:s,weight1:i,weight2:o}),this._cachedMergedKeybindings=null},e.prototype.getDefaultKeybindings=function(){return this._cachedMergedKeybindings||(this._cachedMergedKeybindings=[].concat(this._coreKeybindings).concat(this._extensionKeybindings),this._cachedMergedKeybindings.sort(u)),this._cachedMergedKeybindings.slice(0)},e}());function u(e,t){return e.weight1!==t.weight1?e.weight1-t.weight1:e.commandt.command?1:e.weight2-t.weight2}s.a.add("platform.keybindingsRegistry",a)},L5KM:function(e,t,n){"use strict";n.d(t,"a",function(){return c}),t._36=d,n.d(t,"T",function(){return p}),n.d(t,"R",function(){return g}),n.d(t,"S",function(){return m}),n.d(t,"e",function(){return v}),n.d(t,"b",function(){return _}),n.d(t,"_46",function(){return b}),n.d(t,"_45",function(){return y}),n.d(t,"_48",function(){return w}),n.d(t,"W",function(){return C}),n.d(t,"Y",function(){return S}),n.d(t,"X",function(){return x}),n.d(t,"V",function(){return L}),n.d(t,"U",function(){return O}),n.d(t,"_2",function(){return k}),n.d(t,"_4",function(){return N}),n.d(t,"_3",function(){return E}),n.d(t,"_5",function(){return I}),n.d(t,"_7",function(){return D}),n.d(t,"_6",function(){return M}),n.d(t,"Z",function(){return T}),n.d(t,"_1",function(){return P}),n.d(t,"_0",function(){return A}),n.d(t,"_14",function(){return j}),n.d(t,"_15",function(){return W}),n.d(t,"_8",function(){return B}),n.d(t,"_9",function(){return V}),n.d(t,"_20",function(){return H}),n.d(t,"_21",function(){return z}),n.d(t,"_19",function(){return U}),n.d(t,"_17",function(){return K}),n.d(t,"_18",function(){return q}),n.d(t,"_10",function(){return G}),n.d(t,"_16",function(){return Z}),n.d(t,"_11",function(){return Y}),n.d(t,"_13",function(){return X}),n.d(t,"_12",function(){return $}),n.d(t,"_47",function(){return J}),n.d(t,"_34",function(){return Q}),n.d(t,"_33",function(){return ee}),n.d(t,"c",function(){return te}),n.d(t,"d",function(){return ne}),n.d(t,"_37",function(){return ie}),n.d(t,"_39",function(){return re}),n.d(t,"_40",function(){return oe}),n.d(t,"_38",function(){return se}),n.d(t,"_35",function(){return ae}),n.d(t,"_23",function(){return ue}),n.d(t,"_24",function(){return ce}),n.d(t,"_22",function(){return le}),n.d(t,"_27",function(){return de}),n.d(t,"_25",function(){return he}),n.d(t,"_26",function(){return fe}),n.d(t,"_28",function(){return pe}),n.d(t,"q",function(){return ge}),n.d(t,"p",function(){return me}),n.d(t,"M",function(){return ve}),n.d(t,"L",function(){return _e}),n.d(t,"G",function(){return be}),n.d(t,"F",function(){return ye}),n.d(t,"z",function(){return we}),n.d(t,"y",function(){return Ce}),n.d(t,"o",function(){return Se}),n.d(t,"x",function(){return xe}),n.d(t,"N",function(){return Le}),n.d(t,"P",function(){return Oe}),n.d(t,"O",function(){return ke}),n.d(t,"Q",function(){return Ne}),n.d(t,"H",function(){return Ee}),n.d(t,"I",function(){return Ie}),n.d(t,"E",function(){return De}),n.d(t,"J",function(){return Me}),n.d(t,"K",function(){return Te}),n.d(t,"r",function(){return Pe}),n.d(t,"t",function(){return Ae}),n.d(t,"v",function(){return Re}),n.d(t,"s",function(){return Fe}),n.d(t,"u",function(){return je}),n.d(t,"w",function(){return We}),n.d(t,"C",function(){return Be}),n.d(t,"A",function(){return Ve}),n.d(t,"B",function(){return He}),n.d(t,"D",function(){return ze}),n.d(t,"n",function(){return Ue}),n.d(t,"g",function(){return Ke}),n.d(t,"h",function(){return qe}),n.d(t,"j",function(){return Ge}),n.d(t,"l",function(){return Ze}),n.d(t,"k",function(){return Ye}),n.d(t,"m",function(){return Xe}),n.d(t,"i",function(){return $e}),n.d(t,"_43",function(){return Je}),n.d(t,"_44",function(){return Qe}),n.d(t,"_41",function(){return et}),n.d(t,"_42",function(){return tt}),n.d(t,"_31",function(){return nt}),n.d(t,"_32",function(){return it}),n.d(t,"_29",function(){return rt}),t.f=ot,t._30=function(){for(var e=[],t=0;te.length)return!1;for(var r=0;r=65&&o<=90&&o+32===s||s>=65&&s<=90&&s+32===o))return!1}return!0},e.prototype._createOperationsForBlockComment=function(t,n,i,r,o){var s,a=t.startLineNumber,u=t.startColumn,c=t.endLineNumber,d=t.endColumn,h=r.getLineContent(a),f=r.getLineContent(c),p=h.lastIndexOf(n,u-1+n.length),g=f.indexOf(i,d-1-i.length);if(-1!==p&&-1!==g)if(a===c){h.substring(p+n.length,g).indexOf(i)>=0&&(p=-1,g=-1)}else{var m=h.substring(p+n.length),v=f.substring(0,g);(m.indexOf(i)>=0||v.indexOf(i)>=0)&&(p=-1,g=-1)}-1!==p&&-1!==g?(p+n.length0&&32===f.charCodeAt(g-1)&&(i=" "+i,g-=1),s=e._createRemoveBlockCommentOperations(new l.a(a,p+n.length+1,c,g+1),n,i)):(s=e._createAddBlockCommentOperations(t,n,i),this._usedEndToken=1===s.length?i:null);for(var _=0,b=s;_a?o-1:o}},e}(),m=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),v=function(e){function t(t,n){var i=e.call(this,n)||this;return i._type=t,i}return m(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getModel(),i=[],r=t.getSelections(),o=n.getOptions(),s=0,a=r;s0&&"#"===n.charAt(n.length-1)?n.substring(0,n.length-1):n)]=t,this._onDidChangeSchema.fire(e)},e.prototype.notifySchemaChanged=function(e){this._onDidChangeSchema.fire(e)},e}());i.a.add(o.JSONContribution,s)},LYGd:function(e,t,n){"use strict";var i=n("EuP9").Buffer,r=n("LC74"),o=n("yDvu"),s=new Array(16),a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],u=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],c=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],l=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],d=[0,1518500249,1859775393,2400959708,2840853838],h=[1352829926,1548603684,1836072691,2053994217,0];function f(){o.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function p(e,t){return e<>>32-t}function g(e,t,n,i,r,o,s,a){return p(e+(t^n^i)+o+s|0,a)+r|0}function m(e,t,n,i,r,o,s,a){return p(e+(t&n|~t&i)+o+s|0,a)+r|0}function v(e,t,n,i,r,o,s,a){return p(e+((t|~n)^i)+o+s|0,a)+r|0}function _(e,t,n,i,r,o,s,a){return p(e+(t&i|n&~i)+o+s|0,a)+r|0}function b(e,t,n,i,r,o,s,a){return p(e+(t^(n|~i))+o+s|0,a)+r|0}r(f,o),f.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var n=0|this._a,i=0|this._b,r=0|this._c,o=0|this._d,f=0|this._e,y=0|this._a,w=0|this._b,C=0|this._c,S=0|this._d,x=0|this._e,L=0;L<80;L+=1){var O,k;L<16?(O=g(n,i,r,o,f,e[a[L]],d[0],c[L]),k=b(y,w,C,S,x,e[u[L]],h[0],l[L])):L<32?(O=m(n,i,r,o,f,e[a[L]],d[1],c[L]),k=_(y,w,C,S,x,e[u[L]],h[1],l[L])):L<48?(O=v(n,i,r,o,f,e[a[L]],d[2],c[L]),k=v(y,w,C,S,x,e[u[L]],h[2],l[L])):L<64?(O=_(n,i,r,o,f,e[a[L]],d[3],c[L]),k=m(y,w,C,S,x,e[u[L]],h[3],l[L])):(O=b(n,i,r,o,f,e[a[L]],d[4],c[L]),k=g(y,w,C,S,x,e[u[L]],h[4],l[L])),n=f,f=o,o=p(r,10),r=i,i=O,y=x,x=S,S=p(C,10),C=w,w=k}var N=this._b+r+S|0;this._b=this._c+o+x|0,this._c=this._d+f+y|0,this._d=this._e+n+w|0,this._e=this._a+i+C|0,this._a=N},f.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=i.alloc?i.alloc(20):new i(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},e.exports=f},MOjS:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("hK2W"),o=n("Kp7x"),s=n("tqet"),a=n("7g0X"),u=n("OHx0"),c=n("vTy2"),l=n("03Zz"),d=n("eoic"),h=n("/9db"),f=(n("OV+G"),n("7/Cv")),p=n("L5KM"),g=n("TNPA"),m=n("qecS"),v=n("1sup"),_=n("X6iQ"),b=n("fw2Z"),y=n("ZYUE"),w=n("ni2T"),C=n("Nr0y"),S=encodeURIComponent(''),L=encodeURIComponent(''),k=encodeURIComponent(''),E=encodeURIComponent(''),D=encodeURIComponent(''),T=encodeURIComponent('');function A(e,t){return"."+i.className(e).split(" ").join(".")+' { background: url("data:image/svg+xml,'+i.getSVGData(e,t)+'") center center no-repeat; height: 16px; width: 16px; }'}!function(e){e.getSVGData=function(e,t){switch(e){case C.a.Ignore:var n=t.type===d.d?g.a.fromHex("#75BEFF"):g.a.fromHex("#007ACC");return t.type===d.d?D+encodeURIComponent(n.toString())+M:T+encodeURIComponent(n.toString())+P;case C.a.Info:var i=t.type===d.d?g.a.fromHex("#007ACC"):g.a.fromHex("#75BEFF");return t.type===d.d?D+encodeURIComponent(i.toString())+M:T+encodeURIComponent(i.toString())+P;case C.a.Warning:var r=t.type===d.d?g.a.fromHex("#DDB100"):g.a.fromHex("#fc0");return t.type===d.d?k+encodeURIComponent(r.toString())+N:E+encodeURIComponent(r.toString())+I;case C.a.Error:var o=t.type===d.d?g.a.fromHex("#A1260D"):g.a.fromHex("#F48771");return t.type===d.d?S+encodeURIComponent(o.toString())+x:L+encodeURIComponent(o.toString())+O}return""},e.className=function(e){switch(e){case C.a.Ignore:return"severity-icon severity-ignore";case C.a.Info:return"severity-icon severity-info";case C.a.Warning:return"severity-icon severity-warning";case C.a.Error:return"severity-icon severity-error"}return""}}(i||(i={})),Object(d.f)(function(e,t){t.addRule(A(C.a.Error,e)),t.addRule(A(C.a.Warning,e)),t.addRule(A(C.a.Info,e)),t.addRule(A(C.a.Ignore,e))});var R,F=this&&this.__extends||(R=function(e,t){return(R=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}R(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),j=function(){function e(e,t,n){var i=this;this._lines=0,this._longestLineLength=0,this._relatedDiagnostics=new WeakMap,this._disposables=[],this._editor=t;var r=document.createElement("div");r.className="descriptioncontainer",r.setAttribute("aria-live","assertive"),r.setAttribute("role","alert"),this._messageBlock=document.createElement("div"),f.f(this._messageBlock,"message"),r.appendChild(this._messageBlock),this._relatedBlock=document.createElement("div"),r.appendChild(this._relatedBlock),this._disposables.push(f.k(this._relatedBlock,"click",function(e){e.preventDefault();var t=i._relatedDiagnostics.get(e.target);t&&n(t)})),this._scrollable=new m.b(r,{horizontal:1,vertical:1,useShadows:!1,horizontalScrollbarSize:3,verticalScrollbarSize:3}),e.appendChild(this._scrollable.getDomNode()),this._disposables.push(this._scrollable.onScroll(function(e){r.style.left="-"+e.scrollLeft+"px",r.style.top="-"+e.scrollTop+"px"})),this._disposables.push(this._scrollable)}return e.prototype.dispose=function(){Object(s.f)(this._disposables)},e.prototype.update=function(e){var t=e.source,n=e.message,i=e.relatedInformation,r=e.code,o=n.split(/\r\n|\r|\n/g);this._lines=o.length,this._longestLineLength=0;for(var s=0,a=o;s1?r.a("problems","{0} of {1} problems",n,o):r.a("change","{0} of {1} problem",n,o);this.setTitle(Object(y.b)(d.uri),h)}this._icon.className=i.className(u.c.toSeverity(this._severity)),this.editor.revealPositionInCenter(l,0)},t.prototype.updateMarker=function(e){this._container.classList.remove("stale"),this._message.update(e)},t.prototype.showStale=function(){this._container.classList.add("stale"),this._relayout()},t.prototype._doLayoutBody=function(t,n){e.prototype._doLayoutBody.call(this,t,n),this._heightInPixel=t,this._message.layout(t,n),this._container.style.height=t+"px"},t.prototype._onWidth=function(e){this._message.layout(this._heightInPixel,e)},t.prototype._relayout=function(){e.prototype._relayout.call(this,this.computeRequiredHeight())},t.prototype.computeRequiredHeight=function(){return 3+this._message.getHeightInLines()},t}(b.c),B=Object(p._30)(p.q,p.p),V=Object(p._30)(p.M,p.L),H=Object(p._30)(p.G,p.F),z=Object(p._36)("editorMarkerNavigationError.background",{dark:B,light:B,hc:B},r.a("editorMarkerNavigationError","Editor marker navigation widget error color.")),U=Object(p._36)("editorMarkerNavigationWarning.background",{dark:V,light:V,hc:V},r.a("editorMarkerNavigationWarning","Editor marker navigation widget warning color.")),K=Object(p._36)("editorMarkerNavigationInfo.background",{dark:H,light:H,hc:H},r.a("editorMarkerNavigationInfo","Editor marker navigation widget info color.")),q=Object(p._36)("editorMarkerNavigation.background",{dark:"#2D2D30",light:g.a.white,hc:"#0C141F"},r.a("editorMarkerNavigationBackground","Editor marker navigation widget background."));Object(d.f)(function(e,t){var n=e.getColor(p._46);n&&t.addRule(".monaco-editor .marker-widget a { color: "+n+"; }")});var G=n("aL7J"),Z=n("vORD"),Y=n("zxiH"),X=n("C3c5"),$=n("AKCZ"),J=n("NqM+");n.d(t,"MarkerController",function(){return oe}),n.d(t,"NextMarkerAction",function(){return ae});var Q=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),ee=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},te=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ne=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},ie=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0?this._markers[this._nextIdx]:void 0;this._markers=e||[],this._markers.sort(se.compareMarker),this._nextIdx=t?Math.max(-1,Object(_.c)(this._markers,t,se.compareMarker)):-1,this._onMarkerSetChanged.fire(this)},e.prototype.withoutWatchingEditorPosition=function(e){this._ignoreSelectionChange=!0;try{e()}finally{this._ignoreSelectionChange=!1}},e.prototype._initIdx=function(e){for(var t=!1,n=this._editor.getPosition(),i=0;i0?this._nextIdx=(this._nextIdx-1+this._markers.length)%this._markers.length:i=!0),n!==this._nextIdx){var r=this._markers[this._nextIdx];this._onCurrentMarkerChanged.fire(r)}return i},e.prototype.canNavigate=function(){return this._markers.length>0},e.prototype.findMarkerAtPosition=function(e){for(var t=0,n=this._markers;t=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},y=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},w=function(e){function t(t,n,i){var r=e.call(this)||this;return r._editor=t,r._codeEditorService=n,r._configurationService=i,r._localToDispose=r._register(new c.b),r._decorationsIds=[],r._colorDatas=new Map,r._colorDecoratorIds=[],r._decorationsTypes=new Set,r._register(t.onDidChangeModel(function(e){r._isEnabled=r.isEnabled(),r.onModelChanged()})),r._register(t.onDidChangeModelLanguage(function(e){return r.onModelChanged()})),r._register(p.c.onDidChange(function(e){return r.onModelChanged()})),r._register(t.onDidChangeConfiguration(function(e){var t=r._isEnabled;r._isEnabled=r.isEnabled(),t!==r._isEnabled&&(r._isEnabled?r.onModelChanged():r.removeAllDecorations())})),r._timeoutTimer=null,r._computePromise=null,r._isEnabled=r.isEnabled(),r.onModelChanged(),r}return _(t,e),t.prototype.isEnabled=function(){var e=this._editor.getModel();if(!e)return!1;var t=e.getLanguageIdentifier(),n=this._configurationService.getValue(t.language);if(n){var i=n.colorDecorators;if(i&&void 0!==i.enable&&!i.enable)return i.enable}return this._editor.getConfiguration().contribInfo.colorDecorators},t.prototype.getId=function(){return t.ID},t.get=function(e){return e.getContribution(this.ID)},t.prototype.dispose=function(){this.stop(),this.removeAllDecorations(),e.prototype.dispose.call(this)},t.prototype.onModelChanged=function(){var e=this;if(this.stop(),this._isEnabled){var n=this._editor.getModel();n&&p.c.has(n)&&(this._localToDispose.add(this._editor.onDidChangeModelContent(function(n){e._timeoutTimer||(e._timeoutTimer=new i.e,e._timeoutTimer.cancelAndSet(function(){e._timeoutTimer=null,e.beginCompute()},t.RECOMPUTE_TIME))})),this.beginCompute())}},t.prototype.beginCompute=function(){var e=this;this._computePromise=Object(i.f)(function(t){var n=e._editor.getModel();return n?Object(g.b)(n,t):Promise.resolve([])}),this._computePromise.then(function(t){e.updateDecorations(t),e.updateColorDecorators(t),e._computePromise=null},o.e)},t.prototype.stop=function(){this._timeoutTimer&&(this._timeoutTimer.cancel(),this._timeoutTimer=null),this._computePromise&&(this._computePromise.cancel(),this._computePromise=null),this._localToDispose.clear()},t.prototype.updateDecorations=function(e){var t=this,n=e.map(function(e){return{range:{startLineNumber:e.colorInfo.range.startLineNumber,startColumn:e.colorInfo.range.startColumn,endLineNumber:e.colorInfo.range.endLineNumber,endColumn:e.colorInfo.range.endColumn},options:f.a.EMPTY}});this._decorationsIds=this._editor.deltaDecorations(this._decorationsIds,n),this._colorDatas=new Map,this._decorationsIds.forEach(function(n,i){return t._colorDatas.set(n,e[i])})},t.prototype.updateColorDecorators=function(e){for(var t=this,n=[],i={},o=0;o>>2}function l(e,t,n,i){return 0===e?t&n|~t&i:2===e?t&n|t&i|n&i:t^n^i}i(u,r),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,n=this._w,i=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,u=0|this._e,d=0;d<16;++d)n[d]=e.readInt32BE(4*d);for(;d<80;++d)n[d]=n[d-3]^n[d-8]^n[d-14]^n[d-16];for(var h=0;h<80;++h){var f=~~(h/20),p=0|((t=i)<<5|t>>>27)+l(f,r,o,a)+u+n[h]+s[f];u=a,a=o,o=c(r),r=i,i=p}this._a=i+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},e.exports=u},NBYJ:function(e,t){},NCTB:function(e,t,n){"use strict";t.sha1=n("bMQ9"),t.sha224=n("fWB8"),t.sha256=n("Q48P"),t.sha384=n("EH7o"),t.sha512=n("8/0b")},NMED:function(e,t,n){"use strict";var i=n("geuY"),r=n("lZ6o").utils,o=r.assert;function s(e,t){if(e instanceof s)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new i(e.r,16),this.s=new i(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function a(e,t){var n=e[t.place++];if(!(128&n))return n;for(var i=15&n,r=0,o=0,s=t.place;o>>3);for(e.push(128|n);--n;)e.push(t>>>(n<<3)&255);e.push(t)}}e.exports=s,s.prototype._importDER=function(e,t){e=r.toArray(e,t);var n=new function(){this.place=0};if(48!==e[n.place++])return!1;if(a(e,n)+n.place!==e.length)return!1;if(2!==e[n.place++])return!1;var o=a(e,n),s=e.slice(n.place,o+n.place);if(n.place+=o,2!==e[n.place++])return!1;var u=a(e,n);if(e.length!==u+n.place)return!1;var c=e.slice(n.place,u+n.place);return 0===s[0]&&128&s[1]&&(s=s.slice(1)),0===c[0]&&128&c[1]&&(c=c.slice(1)),this.r=new i(s),this.s=new i(c),this.recoveryParam=null,!0},s.prototype.toDER=function(e){var t=this.r.toArray(),n=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&n[0]&&(n=[0].concat(n)),t=u(t),n=u(n);!(n[0]||128&n[1]);)n=n.slice(1);var i=[2];c(i,t.length),(i=i.concat(t)).push(2),c(i,n.length);var o=i.concat(n),s=[48];return c(s,o.length),s=s.concat(o),r.encode(s,e)}},NjkW:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});n("WUwp");var i=n("tqet"),r=n("ZfGv"),o=n("03Zz"),s=n("artP"),a=n("vTy2"),u=n("iHM7"),c=function(){function e(e,t,n){this.selection=e,this.targetPosition=t,this.copy=n,this.targetSelection=null}return e.prototype.getEditOperations=function(e,t){var n=e.getValueInRange(this.selection);this.copy||t.addEditOperation(this.selection,null),t.addEditOperation(new a.a(this.targetPosition.lineNumber,this.targetPosition.column,this.targetPosition.lineNumber,this.targetPosition.column),n),!this.selection.containsPosition(this.targetPosition)||this.copy&&(this.selection.getEndPosition().equals(this.targetPosition)||this.selection.getStartPosition().equals(this.targetPosition))?this.copy?this.targetSelection=new u.a(this.targetPosition.lineNumber,this.targetPosition.column,this.selection.endLineNumber-this.selection.startLineNumber+this.targetPosition.lineNumber,this.selection.startLineNumber===this.selection.endLineNumber?this.targetPosition.column+this.selection.endColumn-this.selection.startColumn:this.selection.endColumn):this.targetPosition.lineNumber>this.selection.endLineNumber?this.targetSelection=new u.a(this.targetPosition.lineNumber-this.selection.endLineNumber+this.selection.startLineNumber,this.targetPosition.column,this.targetPosition.lineNumber,this.selection.startLineNumber===this.selection.endLineNumber?this.targetPosition.column+this.selection.endColumn-this.selection.startColumn:this.selection.endColumn):this.targetPosition.lineNumber0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=e._maxRounds){t();break}if(!r){t();break}var c=i.findNextBracket(r);if(!c){t();break}if(Date.now()-u>e._maxDuration){setTimeout(function(){return e._bracketsRightYield(t,n+1,i,r,s)});break}var l=c.close;if(c.isOpen){var d=a.has(l)?a.get(l):0;a.set(l,d+1)}else{d=a.has(l)?a.get(l):0;if(d-=1,a.set(l,Math.max(0,d)),d<0){var h=s.get(l);h||(h=new o.a,s.set(l,h)),h.push(c.range)}}r=c.range.getEndPosition()}},e._bracketsLeftYield=function(t,n,i,o,s,a){for(var u=new Map,c=Date.now();;){if(n>=e._maxRounds&&0===s.size){t();break}if(!o){t();break}var l=i.findPrevBracket(o);if(!l){t();break}if(Date.now()-c>e._maxDuration){setTimeout(function(){return e._bracketsLeftYield(t,n+1,i,o,s,a)});break}var d=l.close;if(l.isOpen){m=u.has(d)?u.get(d):0;if(m-=1,u.set(d,Math.max(0,m)),m<0){var h=s.get(d);if(h){var f=h.shift();0===h.size&&s.delete(d);var p=r.a.fromPositions(l.range.getEndPosition(),f.getStartPosition()),g=r.a.fromPositions(l.range.getStartPosition(),f.getEndPosition());a.push({range:p}),a.push({range:g}),e._addBracketLeading(i,g,a)}}}else{var m=u.has(d)?u.get(d):0;u.set(d,m+1)}o=l.range.getStartPosition()}},e._addBracketLeading=function(e,t,n){if(t.startLineNumber!==t.endLineNumber){var o=t.startLineNumber,s=e.getLineFirstNonWhitespaceColumn(o);0!==s&&s!==t.startColumn&&(n.push({range:r.a.fromPositions(new i.a(o,s),t.getEndPosition())}),n.push({range:r.a.fromPositions(new i.a(o,1),t.getEndPosition())}));var a=o-1;if(a>0){var u=e.getLineFirstNonWhitespaceColumn(a);u===t.startColumn&&u!==e.getLineLastNonWhitespaceColumn(a)&&(n.push({range:r.a.fromPositions(new i.a(a,u),t.getEndPosition())}),n.push({range:r.a.fromPositions(new i.a(a,1),t.getEndPosition())}))}}},e._maxDuration=30,e._maxRounds=2,e}()},"NqM+":function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("keybindingService")},Nr0y:function(e,t,n){"use strict";var i,r=n("hK2W"),o=n("aL7J");!function(e){e[e.Ignore=0]="Ignore",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(i||(i={})),function(e){var t="error",n="warning",i="warn",s="info",a=Object.create(null);a[e.Error]=r.a("sev.error","Error"),a[e.Warning]=r.a("sev.warning","Warning"),a[e.Info]=r.a("sev.info","Info"),e.fromValue=function(r){return r?o.n(t,r)?e.Error:o.n(n,r)||o.n(i,r)?e.Warning:o.n(s,r)?e.Info:e.Ignore:e.Ignore}}(i||(i={})),t.a=i},Ny4g:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r,o,s,a,u,c,l,d,h,f,p,g,m,v,_,b,y,w,C,S,x,L,O,k,N,E,I,D,M,T=n("iXRW"),P=(n("tZcU"),n("80kS")),A=n("Kp7x"),R=n("uNfg"),F=n("mrx5"),j=n("artP"),W=n("vTy2"),B=n("iHM7"),V=n("c6Qy");!function(e){e[e.Unnecessary=1]="Unnecessary",e[e.Deprecated=2]="Deprecated"}(i||(i={})),function(e){e[e.Hint=1]="Hint",e[e.Info=2]="Info",e[e.Warning=4]="Warning",e[e.Error=8]="Error"}(r||(r={})),function(e){e[e.Unknown=0]="Unknown",e[e.Backspace=1]="Backspace",e[e.Tab=2]="Tab",e[e.Enter=3]="Enter",e[e.Shift=4]="Shift",e[e.Ctrl=5]="Ctrl",e[e.Alt=6]="Alt",e[e.PauseBreak=7]="PauseBreak",e[e.CapsLock=8]="CapsLock",e[e.Escape=9]="Escape",e[e.Space=10]="Space",e[e.PageUp=11]="PageUp",e[e.PageDown=12]="PageDown",e[e.End=13]="End",e[e.Home=14]="Home",e[e.LeftArrow=15]="LeftArrow",e[e.UpArrow=16]="UpArrow",e[e.RightArrow=17]="RightArrow",e[e.DownArrow=18]="DownArrow",e[e.Insert=19]="Insert",e[e.Delete=20]="Delete",e[e.KEY_0=21]="KEY_0",e[e.KEY_1=22]="KEY_1",e[e.KEY_2=23]="KEY_2",e[e.KEY_3=24]="KEY_3",e[e.KEY_4=25]="KEY_4",e[e.KEY_5=26]="KEY_5",e[e.KEY_6=27]="KEY_6",e[e.KEY_7=28]="KEY_7",e[e.KEY_8=29]="KEY_8",e[e.KEY_9=30]="KEY_9",e[e.KEY_A=31]="KEY_A",e[e.KEY_B=32]="KEY_B",e[e.KEY_C=33]="KEY_C",e[e.KEY_D=34]="KEY_D",e[e.KEY_E=35]="KEY_E",e[e.KEY_F=36]="KEY_F",e[e.KEY_G=37]="KEY_G",e[e.KEY_H=38]="KEY_H",e[e.KEY_I=39]="KEY_I",e[e.KEY_J=40]="KEY_J",e[e.KEY_K=41]="KEY_K",e[e.KEY_L=42]="KEY_L",e[e.KEY_M=43]="KEY_M",e[e.KEY_N=44]="KEY_N",e[e.KEY_O=45]="KEY_O",e[e.KEY_P=46]="KEY_P",e[e.KEY_Q=47]="KEY_Q",e[e.KEY_R=48]="KEY_R",e[e.KEY_S=49]="KEY_S",e[e.KEY_T=50]="KEY_T",e[e.KEY_U=51]="KEY_U",e[e.KEY_V=52]="KEY_V",e[e.KEY_W=53]="KEY_W",e[e.KEY_X=54]="KEY_X",e[e.KEY_Y=55]="KEY_Y",e[e.KEY_Z=56]="KEY_Z",e[e.Meta=57]="Meta",e[e.ContextMenu=58]="ContextMenu",e[e.F1=59]="F1",e[e.F2=60]="F2",e[e.F3=61]="F3",e[e.F4=62]="F4",e[e.F5=63]="F5",e[e.F6=64]="F6",e[e.F7=65]="F7",e[e.F8=66]="F8",e[e.F9=67]="F9",e[e.F10=68]="F10",e[e.F11=69]="F11",e[e.F12=70]="F12",e[e.F13=71]="F13",e[e.F14=72]="F14",e[e.F15=73]="F15",e[e.F16=74]="F16",e[e.F17=75]="F17",e[e.F18=76]="F18",e[e.F19=77]="F19",e[e.NumLock=78]="NumLock",e[e.ScrollLock=79]="ScrollLock",e[e.US_SEMICOLON=80]="US_SEMICOLON",e[e.US_EQUAL=81]="US_EQUAL",e[e.US_COMMA=82]="US_COMMA",e[e.US_MINUS=83]="US_MINUS",e[e.US_DOT=84]="US_DOT",e[e.US_SLASH=85]="US_SLASH",e[e.US_BACKTICK=86]="US_BACKTICK",e[e.US_OPEN_SQUARE_BRACKET=87]="US_OPEN_SQUARE_BRACKET",e[e.US_BACKSLASH=88]="US_BACKSLASH",e[e.US_CLOSE_SQUARE_BRACKET=89]="US_CLOSE_SQUARE_BRACKET",e[e.US_QUOTE=90]="US_QUOTE",e[e.OEM_8=91]="OEM_8",e[e.OEM_102=92]="OEM_102",e[e.NUMPAD_0=93]="NUMPAD_0",e[e.NUMPAD_1=94]="NUMPAD_1",e[e.NUMPAD_2=95]="NUMPAD_2",e[e.NUMPAD_3=96]="NUMPAD_3",e[e.NUMPAD_4=97]="NUMPAD_4",e[e.NUMPAD_5=98]="NUMPAD_5",e[e.NUMPAD_6=99]="NUMPAD_6",e[e.NUMPAD_7=100]="NUMPAD_7",e[e.NUMPAD_8=101]="NUMPAD_8",e[e.NUMPAD_9=102]="NUMPAD_9",e[e.NUMPAD_MULTIPLY=103]="NUMPAD_MULTIPLY",e[e.NUMPAD_ADD=104]="NUMPAD_ADD",e[e.NUMPAD_SEPARATOR=105]="NUMPAD_SEPARATOR",e[e.NUMPAD_SUBTRACT=106]="NUMPAD_SUBTRACT",e[e.NUMPAD_DECIMAL=107]="NUMPAD_DECIMAL",e[e.NUMPAD_DIVIDE=108]="NUMPAD_DIVIDE",e[e.KEY_IN_COMPOSITION=109]="KEY_IN_COMPOSITION",e[e.ABNT_C1=110]="ABNT_C1",e[e.ABNT_C2=111]="ABNT_C2",e[e.MAX_VALUE=112]="MAX_VALUE"}(o||(o={})),function(e){e[e.LTR=0]="LTR",e[e.RTL=1]="RTL"}(s||(s={})),function(e){e[e.Auto=1]="Auto",e[e.Hidden=2]="Hidden",e[e.Visible=3]="Visible"}(a||(a={})),function(e){e[e.Left=1]="Left",e[e.Center=2]="Center",e[e.Right=4]="Right",e[e.Full=7]="Full"}(u||(u={})),function(e){e[e.Inline=1]="Inline"}(c||(c={})),function(e){e[e.TextDefined=0]="TextDefined",e[e.LF=1]="LF",e[e.CRLF=2]="CRLF"}(l||(l={})),function(e){e[e.LF=1]="LF",e[e.CRLF=2]="CRLF"}(d||(d={})),function(e){e[e.LF=0]="LF",e[e.CRLF=1]="CRLF"}(h||(h={})),function(e){e[e.AlwaysGrowsWhenTypingAtEdges=0]="AlwaysGrowsWhenTypingAtEdges",e[e.NeverGrowsWhenTypingAtEdges=1]="NeverGrowsWhenTypingAtEdges",e[e.GrowsOnlyWhenTypingBefore=2]="GrowsOnlyWhenTypingBefore",e[e.GrowsOnlyWhenTypingAfter=3]="GrowsOnlyWhenTypingAfter"}(f||(f={})),function(e){e[e.Smooth=0]="Smooth",e[e.Immediate=1]="Immediate"}(p||(p={})),function(e){e[e.NotSet=0]="NotSet",e[e.ContentFlush=1]="ContentFlush",e[e.RecoverFromMarkers=2]="RecoverFromMarkers",e[e.Explicit=3]="Explicit",e[e.Paste=4]="Paste",e[e.Undo=5]="Undo",e[e.Redo=6]="Redo"}(g||(g={})),function(e){e[e.None=0]="None",e[e.Small=1]="Small",e[e.Large=2]="Large",e[e.SmallBlocks=3]="SmallBlocks",e[e.LargeBlocks=4]="LargeBlocks"}(m||(m={})),function(e){e[e.None=0]="None",e[e.Same=1]="Same",e[e.Indent=2]="Indent",e[e.DeepIndent=3]="DeepIndent"}(v||(v={})),function(e){e[e.Hidden=0]="Hidden",e[e.Blink=1]="Blink",e[e.Smooth=2]="Smooth",e[e.Phase=3]="Phase",e[e.Expand=4]="Expand",e[e.Solid=5]="Solid"}(_||(_={})),function(e){e[e.Line=1]="Line",e[e.Block=2]="Block",e[e.Underline=3]="Underline",e[e.LineThin=4]="LineThin",e[e.BlockOutline=5]="BlockOutline",e[e.UnderlineThin=6]="UnderlineThin"}(b||(b={})),function(e){e[e.Off=0]="Off",e[e.On=1]="On",e[e.Relative=2]="Relative",e[e.Interval=3]="Interval",e[e.Custom=4]="Custom"}(y||(y={})),function(e){e[e.EXACT=0]="EXACT",e[e.ABOVE=1]="ABOVE",e[e.BELOW=2]="BELOW"}(w||(w={})),function(e){e[e.TOP_RIGHT_CORNER=0]="TOP_RIGHT_CORNER",e[e.BOTTOM_RIGHT_CORNER=1]="BOTTOM_RIGHT_CORNER",e[e.TOP_CENTER=2]="TOP_CENTER"}(C||(C={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXTAREA=1]="TEXTAREA",e[e.GUTTER_GLYPH_MARGIN=2]="GUTTER_GLYPH_MARGIN",e[e.GUTTER_LINE_NUMBERS=3]="GUTTER_LINE_NUMBERS",e[e.GUTTER_LINE_DECORATIONS=4]="GUTTER_LINE_DECORATIONS",e[e.GUTTER_VIEW_ZONE=5]="GUTTER_VIEW_ZONE",e[e.CONTENT_TEXT=6]="CONTENT_TEXT",e[e.CONTENT_EMPTY=7]="CONTENT_EMPTY",e[e.CONTENT_VIEW_ZONE=8]="CONTENT_VIEW_ZONE",e[e.CONTENT_WIDGET=9]="CONTENT_WIDGET",e[e.OVERVIEW_RULER=10]="OVERVIEW_RULER",e[e.SCROLLBAR=11]="SCROLLBAR",e[e.OVERLAY_WIDGET=12]="OVERLAY_WIDGET",e[e.OUTSIDE_EDITOR=13]="OUTSIDE_EDITOR"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Indent=1]="Indent",e[e.IndentOutdent=2]="IndentOutdent",e[e.Outdent=3]="Outdent"}(x||(x={})),function(e){e[e.Method=0]="Method",e[e.Function=1]="Function",e[e.Constructor=2]="Constructor",e[e.Field=3]="Field",e[e.Variable=4]="Variable",e[e.Class=5]="Class",e[e.Struct=6]="Struct",e[e.Interface=7]="Interface",e[e.Module=8]="Module",e[e.Property=9]="Property",e[e.Event=10]="Event",e[e.Operator=11]="Operator",e[e.Unit=12]="Unit",e[e.Value=13]="Value",e[e.Constant=14]="Constant",e[e.Enum=15]="Enum",e[e.EnumMember=16]="EnumMember",e[e.Keyword=17]="Keyword",e[e.Text=18]="Text",e[e.Color=19]="Color",e[e.File=20]="File",e[e.Reference=21]="Reference",e[e.Customcolor=22]="Customcolor",e[e.Folder=23]="Folder",e[e.TypeParameter=24]="TypeParameter",e[e.Snippet=25]="Snippet"}(L||(L={})),function(e){e[e.Deprecated=1]="Deprecated"}(O||(O={})),function(e){e[e.KeepWhitespace=1]="KeepWhitespace",e[e.InsertAsSnippet=4]="InsertAsSnippet"}(k||(k={})),function(e){e[e.Invoke=0]="Invoke",e[e.TriggerCharacter=1]="TriggerCharacter",e[e.TriggerForIncompleteCompletions=2]="TriggerForIncompleteCompletions"}(N||(N={})),function(e){e[e.Invoke=1]="Invoke",e[e.TriggerCharacter=2]="TriggerCharacter",e[e.ContentChange=3]="ContentChange"}(E||(E={})),function(e){e[e.Text=0]="Text",e[e.Read=1]="Read",e[e.Write=2]="Write"}(I||(I={})),function(e){e[e.File=0]="File",e[e.Module=1]="Module",e[e.Namespace=2]="Namespace",e[e.Package=3]="Package",e[e.Class=4]="Class",e[e.Method=5]="Method",e[e.Property=6]="Property",e[e.Field=7]="Field",e[e.Constructor=8]="Constructor",e[e.Enum=9]="Enum",e[e.Interface=10]="Interface",e[e.Function=11]="Function",e[e.Variable=12]="Variable",e[e.Constant=13]="Constant",e[e.String=14]="String",e[e.Number=15]="Number",e[e.Boolean=16]="Boolean",e[e.Array=17]="Array",e[e.Object=18]="Object",e[e.Key=19]="Key",e[e.Null=20]="Null",e[e.EnumMember=21]="EnumMember",e[e.Struct=22]="Struct",e[e.Event=23]="Event",e[e.Operator=24]="Operator",e[e.TypeParameter=25]="TypeParameter"}(D||(D={})),function(e){e[e.Deprecated=1]="Deprecated"}(M||(M={}));var H=function(){function e(){}return e.chord=function(e,t){return Object(R.a)(e,t)},e.CtrlCmd=2048,e.Shift=1024,e.Alt=512,e.WinCtrl=256,e}();function z(){return{editor:void 0,languages:void 0,CancellationTokenSource:P.b,Emitter:A.a,KeyCode:o,KeyMod:H,Position:j.a,Range:W.a,Selection:B.a,SelectionDirection:s,MarkerSeverity:r,MarkerTag:i,Uri:F.a,Token:V.a}}n("gvGx");var U,K=n("vORD"),q=n("7/Cv"),G=n("tqet"),Z=n("EMhq"),Y=n("+vUW"),X=n("lapT"),$=n("ZYUE"),J=n("aL7J"),Q=n("ItKl"),ee=this&&this.__extends||(U=function(e,t){return(U=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}U(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),te=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},ne=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ie=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},re=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=this.ranges.length&&(this.nextIdx=0)):(this.nextIdx-=1,this.nextIdx<0&&(this.nextIdx=this.ranges.length-1));var n=this.ranges[this.nextIdx];this.ignoreSelectionChange=!0;try{var i=n.range.getStartPosition();this._editor.setPosition(i),this._editor.revealPositionInCenter(i,t)}finally{this.ignoreSelectionChange=!1}}},t.prototype.canNavigate=function(){return this.ranges&&this.ranges.length>0},t.prototype.next=function(e){void 0===e&&(e=0),this._move(!0,e)},t.prototype.previous=function(e){void 0===e&&(e=0),this._move(!1,e)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.ranges=[],this.disposed=!0},t}(G.a),de=n("5lao"),he=n("33h2"),fe=n("D2uo"),pe=n("PCC9"),ge=n("jUH2"),me=n("606G"),ve=n("B/Xy"),_e=n("odeJ"),be=n("zxiH"),ye=n("ZfGv"),we=n("KIxu"),Ce=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Se="$initialize",xe=!1;function Le(e){ye.f&&(xe||(xe=!0,console.warn("Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/Microsoft/monaco-editor#faq")),console.warn(e.message))}var Oe=function(){function e(e){this._workerId=-1,this._handler=e,this._lastSentReq=0,this._pendingReplies=Object.create(null)}return e.prototype.setWorkerId=function(e){this._workerId=e},e.prototype.sendMessage=function(e,t){var n=this,i=String(++this._lastSentReq);return new Promise(function(r,o){n._pendingReplies[i]={resolve:r,reject:o},n._send({vsWorker:n._workerId,req:i,method:e,args:t})})},e.prototype.handleMessage=function(e){e&&e.vsWorker&&(-1!==this._workerId&&e.vsWorker!==this._workerId||this._handleMessage(e))},e.prototype._handleMessage=function(e){var t=this;if(e.seq){var n=e;if(!this._pendingReplies[n.seq])return void console.warn("Got reply to unknown seq");var i=this._pendingReplies[n.seq];if(delete this._pendingReplies[n.seq],n.err){var r=n.err;return n.err.$isError&&((r=new Error).name=n.err.name,r.message=n.err.message,r.stack=n.err.stack),void i.reject(r)}i.resolve(n.res)}else{var o=e,s=o.req;this._handler.handleMessage(o.method,o.args).then(function(e){t._send({vsWorker:t._workerId,seq:s,res:e,err:void 0})},function(e){e.detail instanceof Error&&(e.detail=Object(be.g)(e.detail)),t._send({vsWorker:t._workerId,seq:s,res:void 0,err:Object(be.g)(e)})})}},e.prototype._send=function(e){var t=[];if(e.req)for(var n=e,i=0;i1&&p>1;){if(d.charCodeAt(f-2)!==h.charCodeAt(p-2))break;f--,p--}(f>1||p>1)&&this._pushTrimWhitespaceCharChange(r,o+1,1,f,s+1,1,p);for(var g=Fe._getLastNonBlankColumn(d,1),m=Fe._getLastNonBlankColumn(h,1),v=d.length+1,_=h.length+1;gt&&(t=a),s>n&&(n=s),u>n&&(n=u)}t++,n++;var c=new qe.a(n,t,0);for(i=0,r=e.length;i=this._maxCharCode?0:this._states.get(e,t)},e}(),Ze=null;var Ye=null;var Xe=function(){function e(){}return e._createLink=function(e,t,n,i,r){var o=r-1;do{var s=t.charCodeAt(o);if(2!==e.get(s))break;o--}while(o>i);if(i>0){var a=t.charCodeAt(i-1),u=t.charCodeAt(o);(40===a&&41===u||91===a&&93===u||123===a&&125===u)&&o--}return{range:{startLineNumber:n,startColumn:i+1,endLineNumber:n,endColumn:o+2},url:t.substring(i,o+1)}},e.computeLinks=function(t,n){void 0===n&&(null===Ze&&(Ze=new Ge([[1,104,2],[1,72,2],[1,102,6],[1,70,6],[2,116,3],[2,84,3],[3,116,4],[3,84,4],[4,112,5],[4,80,5],[5,115,9],[5,83,9],[5,58,10],[6,105,7],[6,73,7],[7,108,8],[7,76,8],[8,101,9],[8,69,9],[9,58,10],[10,47,11],[11,47,12]])),n=Ze);for(var i=function(){if(null===Ye){Ye=new Ke.a(0);for(var e=0;e<" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…".length;e++)Ye.set(" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…".charCodeAt(e),1);for(e=0;e<".,;".length;e++)Ye.set(".,;".charCodeAt(e),2)}return Ye}(),r=[],o=1,s=t.getLineCount();o<=s;o++){for(var a=t.getLineContent(o),u=a.length,c=0,l=0,d=0,h=1,f=!1,p=!1,g=!1;c=0?((i+=n?1:-1)<0?i=e.length-1:i%=e.length,e[i]):null},e.INSTANCE=new e,e}(),Je=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Qe=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Je(t,e),Object.defineProperty(t.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"version",{get:function(){return this._versionId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"eol",{get:function(){return this._eol},enumerable:!0,configurable:!0}),t.prototype.getValue=function(){return this.getText()},t.prototype.getLinesContent=function(){return this._lines.slice(0)},t.prototype.getLineCount=function(){return this._lines.length},t.prototype.getLineContent=function(e){return this._lines[e-1]},t.prototype.getWordAtPosition=function(e,t){var n=Object(Ue.d)(e.column,Object(Ue.c)(t),this._lines[e.lineNumber-1],0);return n?new W.a(e.lineNumber,n.startColumn,e.lineNumber,n.endColumn):null},t.prototype.getWordUntilPosition=function(e,t){var n=this.getWordAtPosition(e,t);return n?{word:this._lines[e.lineNumber-1].substring(n.startColumn-1,e.column-1),startColumn:n.startColumn,endColumn:e.column}:{word:"",startColumn:e.column,endColumn:e.column}},t.prototype.createWordIterator=function(e){var t,n,i=this,r=0,o=0,s=[],a=function(){if(o=i._lines.length?Te.c:(n=i._lines[r],s=i._wordenize(n,e),o=0,r+=1,a())};return{next:a}},t.prototype.getLineWords=function(e,t){for(var n=this._lines[e-1],i=[],r=0,o=this._wordenize(n,t);rthis._lines.length)t=this._lines.length,n=this._lines[t-1].length+1,i=!0;else{var r=this._lines[t-1].length+1;n<1?(n=1,i=!0):n>r&&(n=r,i=!0)}return i?{lineNumber:t,column:n}:e},t}(ze),et=function(){function e(e,t){this._host=e,this._models=Object.create(null),this._foreignModuleFactory=t,this._foreignModule=null}return e.prototype.dispose=function(){this._models=Object.create(null)},e.prototype._getModel=function(e){return this._models[e]},e.prototype._getModels=function(){var e=this,t=[];return Object.keys(this._models).forEach(function(n){return t.push(e._models[n])}),t},e.prototype.acceptNewModel=function(e){this._models[e.url]=new Qe(F.a.parse(e.url),e.lines,e.EOL,e.versionId)},e.prototype.acceptModelChanged=function(e,t){this._models[e]&&this._models[e].onEvents(t)},e.prototype.acceptRemovedModel=function(e){this._models[e]&&delete this._models[e]},e.prototype.computeDiff=function(e,t,n){var i=this._getModel(e),r=this._getModel(t);if(!i||!r)return Promise.resolve(null);var o=i.getLinesContent(),s=r.getLinesContent(),a=new Ve(o,s,{shouldComputeCharChanges:!0,shouldPostProcessCharChanges:!0,shouldIgnoreTrimWhitespace:n,shouldMakePrettyDiff:!0}).computeDiff(),u=!(a.length>0)&&this._modelsAreIdentical(i,r);return Promise.resolve({identical:u,changes:a})},e.prototype._modelsAreIdentical=function(e,t){var n=e.getLineCount();if(n!==t.getLineCount())return!1;for(var i=1;i<=n;i++){if(e.getLineContent(i)!==t.getLineContent(i))return!1}return!0},e.prototype.computeMoreMinimalEdits=function(t,n){var i=this._getModel(t);if(!i)return Promise.resolve(n);for(var r=[],o=void 0,s=0,a=n=Object(De.o)(n,function(e,t){return e.range&&t.range?W.a.compareRangesUsingStarts(e.range,t.range):(e.range?0:1)-(t.range?0:1)});se._diffLimit)r.push({range:c,text:l});else for(var f=Object(Me.b)(h,l,!1),p=i.offsetAt(W.a.lift(c).getStartPosition()),g=0,m=f;g=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},ct=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},lt=6e4,dt=3e5;function ht(e,t){var n=e.getModel(t);return!!n&&!n.isTooLargeForSyncing()}var ft=function(e){function t(t,n,i){var r=e.call(this)||this;return r._modelService=t,r._workerManager=r._register(new gt(r._modelService)),r._logService=i,r._register(pe.q.register("*",{provideLinks:function(e,t){return ht(r._modelService,e.uri)?r._workerManager.withWorker().then(function(t){return t.computeLinks(e.uri)}).then(function(e){return e&&{links:e}}):Promise.resolve({links:[]})}})),r._register(pe.d.register("*",new pt(r._workerManager,n,r._modelService))),r}return at(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.canComputeDiff=function(e,t){return ht(this._modelService,e)&&ht(this._modelService,t)},t.prototype.computeDiff=function(e,t,n){return this._workerManager.withWorker().then(function(i){return i.computeDiff(e,t,n)})},t.prototype.computeMoreMinimalEdits=function(e,t){var n=this;if(Object(De.n)(t)){if(!ht(this._modelService,e))return Promise.resolve(t);var i=st.a.create(!0),r=this._workerManager.withWorker().then(function(n){return n.computeMoreMinimalEdits(e,t)});return r.finally(function(){return n._logService.trace("FORMAT#computeMoreMinimalEdits",e.toString(!0),i.elapsed())}),r}return Promise.resolve(void 0)},t.prototype.canNavigateValueSet=function(e){return ht(this._modelService,e)},t.prototype.navigateValueSet=function(e,t,n){return this._workerManager.withWorker().then(function(i){return i.navigateValueSet(e,t,n)})},t.prototype.canComputeWordRanges=function(e){return ht(this._modelService,e)},t.prototype.computeWordRanges=function(e,t){return this._workerManager.withWorker().then(function(n){return n.computeWordRanges(e,t)})},t=ut([ct(0,tt.a),ct(1,it),ct(2,ot.a)],t)}(G.a),pt=function(){function e(e,t,n){this._debugDisplayName="wordbasedCompletions",this._workerManager=e,this._configurationService=t,this._modelService=n}return e.prototype.provideCompletionItems=function(e,t){if(this._configurationService.getValue(e.uri,t,"editor").wordBasedSuggestions&&ht(this._modelService,e.uri))return this._workerManager.withWorker().then(function(n){return n.textualSuggest(e.uri,t)})},e}(),gt=function(e){function t(t){var n=e.call(this)||this;return n._modelService=t,n._editorWorkerClient=null,n._lastWorkerUsedTime=(new Date).getTime(),n._register(new _e.c).cancelAndSet(function(){return n._checkStopIdleWorker()},Math.round(dt/2)),n._register(n._modelService.onModelRemoved(function(e){return n._checkStopEmptyWorker()})),n}return at(t,e),t.prototype.dispose=function(){this._editorWorkerClient&&(this._editorWorkerClient.dispose(),this._editorWorkerClient=null),e.prototype.dispose.call(this)},t.prototype._checkStopEmptyWorker=function(){this._editorWorkerClient&&(0===this._modelService.getModels().length&&(this._editorWorkerClient.dispose(),this._editorWorkerClient=null))},t.prototype._checkStopIdleWorker=function(){this._editorWorkerClient&&((new Date).getTime()-this._lastWorkerUsedTime>dt&&(this._editorWorkerClient.dispose(),this._editorWorkerClient=null))},t.prototype.withWorker=function(){return this._lastWorkerUsedTime=(new Date).getTime(),this._editorWorkerClient||(this._editorWorkerClient=new bt(this._modelService,"editorWorkerService")),Promise.resolve(this._editorWorkerClient)},t}(G.a),mt=function(e){function t(t,n,i){var r=e.call(this)||this;if(r._syncedModels=Object.create(null),r._syncedModelsLastUsedTime=Object.create(null),r._proxy=t,r._modelService=n,!i){var o=new _e.c;o.cancelAndSet(function(){return r._checkStopModelSync()},Math.round(lt/2)),r._register(o)}return r}return at(t,e),t.prototype.dispose=function(){for(var t in this._syncedModels)Object(G.f)(this._syncedModels[t]);this._syncedModels=Object.create(null),this._syncedModelsLastUsedTime=Object.create(null),e.prototype.dispose.call(this)},t.prototype.ensureSyncedResources=function(e){for(var t=0,n=e;tlt&&t.push(n)}for(var i=0,r=t;i'"_]/g,"-")}function Dt(e,t){return new Error(e.languageId+": "+t)}function Mt(e,t,n,i,r){var o=null;return t.replace(/\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g,function(t,s,a,u,c,l,d,h,f){return Nt(a)?Nt(u)?!Nt(c)&&c0;){var i=e.tokenizer[n];if(i)return i;var r=n.lastIndexOf(".");n=r<0?null:n.substr(0,r)}return null}var Pt=function(){function e(e){this._maxCacheDepth=e,this._entries=Object.create(null)}return e.create=function(e,t){return this._INSTANCE.create(e,t)},e.prototype.create=function(e,t){if(null!==e&&e.depth>=this._maxCacheDepth)return new At(e,t);var n=At.getStackElementId(e);n.length>0&&(n+="|"),n+=t;var i=this._entries[n];return i||(i=new At(e,t),this._entries[n]=i,i)},e._INSTANCE=new e(5),e}(),At=function(){function e(e,t){this.parent=e,this.state=t,this.depth=(this.parent?this.parent.depth:0)+1}return e.getStackElementId=function(e){for(var t="";null!==e;)t.length>0&&(t+="|"),t+=e.state,e=e.parent;return t},e._equals=function(e,t){for(;null!==e&&null!==t;){if(e===t)return!0;if(e.state!==t.state)return!1;e=e.parent,t=t.parent}return null===e&&null===t},e.prototype.equals=function(t){return e._equals(this,t)},e.prototype.push=function(e){return Pt.create(this,e)},e.prototype.pop=function(){return this.parent},e.prototype.popall=function(){for(var e=this;e.parent;)e=e.parent;return e},e.prototype.switchTo=function(e){return Pt.create(this.parent,e)},e}(),Rt=function(){function e(e,t){this.modeId=e,this.state=t}return e.prototype.equals=function(e){return this.modeId===e.modeId&&this.state.equals(e.state)},e.prototype.clone=function(){return this.state.clone()===this.state?this:new e(this.modeId,this.state)},e}(),Ft=function(){function e(e){this._maxCacheDepth=e,this._entries=Object.create(null)}return e.create=function(e,t){return this._INSTANCE.create(e,t)},e.prototype.create=function(e,t){if(null!==t)return new jt(e,t);if(null!==e&&e.depth>=this._maxCacheDepth)return new jt(e,t);var n=At.getStackElementId(e),i=this._entries[n];return i||(i=new jt(e,null),this._entries[n]=i,i)},e._INSTANCE=new e(5),e}(),jt=function(){function e(e,t){this.stack=e,this.embeddedModeData=t}return e.prototype.clone=function(){return(this.embeddedModeData?this.embeddedModeData.clone():null)===this.embeddedModeData?this:Ft.create(this.stack,this.embeddedModeData)},e.prototype.equals=function(t){return t instanceof e&&(!!this.stack.equals(t.stack)&&(null===this.embeddedModeData&&null===t.embeddedModeData||null!==this.embeddedModeData&&null!==t.embeddedModeData&&this.embeddedModeData.equals(t.embeddedModeData)))},e}(),Wt=function(){function e(){this._tokens=[],this._language=null,this._lastTokenType=null,this._lastTokenLanguage=null}return e.prototype.enterMode=function(e,t){this._language=t},e.prototype.emit=function(e,t){this._lastTokenType===t&&this._lastTokenLanguage===this._language||(this._lastTokenType=t,this._lastTokenLanguage=this._language,this._tokens.push(new V.a(e,t,this._language)))},e.prototype.nestedModeTokenize=function(e,t,n){var i=t.modeId,r=t.state,o=pe.y.get(i);if(!o)return this.enterMode(n,i),this.emit(n,""),r;var s=o.tokenize(e,r,n);return this._tokens=this._tokens.concat(s.tokens),this._lastTokenType=null,this._lastTokenLanguage=null,this._language=null,s.endState},e.prototype.finalize=function(e){return new V.b(this._tokens,e)},e}(),Bt=function(){function e(e,t){this._modeService=e,this._theme=t,this._prependTokens=null,this._tokens=[],this._currentLanguageId=0,this._lastTokenMetadata=0}return e.prototype.enterMode=function(e,t){this._currentLanguageId=this._modeService.getLanguageIdentifier(t).id},e.prototype.emit=function(e,t){var n=this._theme.match(this._currentLanguageId,t);this._lastTokenMetadata!==n&&(this._lastTokenMetadata=n,this._tokens.push(e),this._tokens.push(n))},e._merge=function(e,t,n){var i=null!==e?e.length:0,r=t.length,o=null!==n?n.length:0;if(0===i&&0===r&&0===o)return new Uint32Array(0);if(0===i&&0===r)return n;if(0===r&&0===o)return e;var s=new Uint32Array(i+r+o);null!==e&&s.set(e);for(var a=0;a0&&i.nestedModeTokenize(s,t.embeddedModeData,n);var a=e.substring(r);return this._myTokenize(a,t,n+r,i)},e.prototype._safeRuleName=function(e){return e?e.name:"(unknown)"},e.prototype._myTokenize=function(e,t,n,i){i.enterMode(n,this._modeId);for(var r,o,s=e.length,a=t.embeddedModeData,u=t.stack,c=0,l=null,d=!0;d||c=s)break;d=!1;var C=this._lexer.tokenizer[g];if(!C&&!(C=Tt(this._lexer,g)))throw Dt(this._lexer,"tokenizer state is not defined: "+g);for(var S=e.substr(c),x=0,L=C;x=this._lexer.maxStack)throw Dt(this._lexer,"maximum tokenizer stack size reached: ["+u.state+","+u.parent.state+",...]");u=u.push(g)}else if("@pop"===_.next){if(u.depth<=1)throw Dt(this._lexer,"trying to pop an empty stack in rule: "+this._safeRuleName(b));u=u.pop()}else if("@popall"===_.next)u=u.popall();else{var N;if("@"===(N=Mt(this._lexer,_.next,v,m,g))[0]&&(N=N.substr(1)),!Tt(this._lexer,N))throw Dt(this._lexer,"trying to set a next state '"+N+"' that is undefined in rule: "+this._safeRuleName(b));u=u.push(N)}}_.log&&"string"==typeof _.log&&(r=this._lexer,o=this._lexer.languageId+": "+Mt(this._lexer,_.log,v,m,g),console.log(r.languageId+": "+o))}if(null===k)throw Dt(this._lexer,"lexer rule has no well-defined action in rule: "+this._safeRuleName(b));if(Array.isArray(k)){if(l&&l.groups.length>0)throw Dt(this._lexer,"groups cannot be nested: "+this._safeRuleName(b));if(m.length!==k.length+1)throw Dt(this._lexer,"matched number of groups does not match the number of actions in rule: "+this._safeRuleName(b));for(var E=0,I=1;I=0&&a()})})},e.colorizeLine=function(e,t,n,i,r){void 0===r&&(r=4);var o=xt.d.isBasicASCII(e,t),s=xt.d.containsRTL(e,o,n);return Object(St.e)(new St.c(!1,!0,e,!1,o,s,0,i,[],r,0,-1,"none",!1,!1,null)).html},e.colorizeModelLine=function(e,t,n){void 0===n&&(n=4);var i=e.getLineContent(t);e.forceTokenization(t);var r=e.getLineTokens(t).inflate();return this.colorizeLine(i,e.mightContainNonBasicASCII(),e.mightContainRTL(),r,n)},e}();function Ut(e,t,n){return new Promise(function(i,r){var o=function(){var s=function(e,t,n){for(var i=[],r=n.getInitialState(),o=0,s=e.length;o"),r=u.endState}return i.join("")}(e,t,n);if(n instanceof Vt){var a=n.getLoadStatus();if(!1===a.loaded)return void a.promise.then(o,r)}i(s)};o()})}function Kt(e,t){var n=[],i=new Uint32Array(2);i[0]=0,i[1]=16793600;for(var r=0,o=e.length;r")}return n.join("")}var qt=n("gzF+"),Gt=n("Nr0y"),Zt=n("P1SM"),Yt=n("TeKV"),Xt=n("0WPX"),$t=n("Gzpe"),Jt=n("WTFd"),Qt=n("rHGw"),en=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),tn=function(){function e(e,t,n){void 0===e&&(e={}),void 0===t&&(t=[]),void 0===n&&(n=[]),this._contents=e,this._keys=t,this._overrides=n,this.isFrozen=!1}return Object.defineProperty(e.prototype,"contents",{get:function(){return this.checkAndFreeze(this._contents)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"overrides",{get:function(){return this.checkAndFreeze(this._overrides)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"keys",{get:function(){return this.checkAndFreeze(this._keys)},enumerable:!0,configurable:!0}),e.prototype.isEmpty=function(){return 0===this._keys.length&&0===Object.keys(this._contents).length&&0===this._overrides.length},e.prototype.getValue=function(e){return e?Object($t.d)(this.contents,e):this.contents},e.prototype.override=function(t){var n=this.getContentsForOverrideIdentifer(t);if(!n||"object"!=typeof n||!Object.keys(n).length)return this;for(var i={},r=0,o=De.e(Object.keys(this.contents).concat(Object.keys(n)));r5e3&&n._leaveChordMode():n._leaveChordMode()},500)},t.prototype._leaveChordMode=function(){this._currentChordStatusMessage&&(this._currentChordStatusMessage.dispose(),this._currentChordStatusMessage=null),this._currentChordChecker.cancel(),this._currentChord=null},t.prototype._dispatch=function(e,t){return this._doDispatch(this.resolveKeyboardEvent(e),t)},t.prototype._doDispatch=function(e,t){var n=this,i=!1;if(e.isChord())return console.warn("Unexpected keyboard event mapped to a chord"),!1;var r=e.getDispatchParts()[0];if(null===r)return i;var o=this._contextKeyService.getContext(t),s=this._currentChord?this._currentChord.keypress:null,a=e.getLabel(),u=this._getResolver().resolve(o,s,r);return u&&u.enterChord?(i=!0,this._enterChordMode(r,a),i):(this._currentChord&&(u&&u.commandId||(this._notificationService.status(on.a("missing.chord","The key combination ({0}, {1}) is not a command.",this._currentChord.label,a),{hideAfter:1e4}),i=!0)),this._leaveChordMode(),u&&u.commandId&&(u.bubble||(i=!0),void 0===u.commandArgs?this._commandService.executeCommand(u.commandId).then(void 0,function(e){return n._notificationService.warn(e)}):this._commandService.executeCommand(u.commandId,u.commandArgs).then(void 0,function(e){return n._notificationService.warn(e)}),this._telemetryService.publicLog2("workbenchActionExecuted",{id:u.commandId,from:"keybinding"})),i)},t.prototype.mightProducePrintableCharacter=function(e){return!e.ctrlKey&&!e.metaKey&&(e.keyCode>=31&&e.keyCode<=56||e.keyCode>=21&&e.keyCode<=30)},t}(G.a),un=n("7g0X"),cn=function(){function e(t,n){this._defaultKeybindings=t,this._defaultBoundCommands=new Map;for(var i=0,r=t.length;i=0;l--)this._isTargetedForRemoval(e[l],a,u,s,c)&&e.splice(l,1);else n.push(o)}return e.concat(n)},e.prototype._addKeyPress=function(t,n){var i=this._map.get(t);if(void 0===i)return this._map.set(t,[n]),void this._addToLookupMap(n);for(var r=i.length-1;r>=0;r--){var o=i[r];if(o.command!==n.command){var s=o.keypressParts.length>1,a=n.keypressParts.length>1;s&&a&&o.keypressParts[1]!==n.keypressParts[1]||e.whenIsEntirelyIncluded(o.when,n.when)&&this._removeFromLookupMap(o)}}i.push(n),this._addToLookupMap(n)},e.prototype._addToLookupMap=function(e){if(e.command){var t=this._lookupMap.get(e.command);void 0===t?(t=[e],this._lookupMap.set(e.command,t)):t.push(e)}},e.prototype._removeFromLookupMap=function(e){if(e.command){var t=this._lookupMap.get(e.command);if(void 0!==t)for(var n=0,i=t.length;n1&&null!==u.keypressParts[1]?{enterChord:!0,commandId:null,commandArgs:null,bubble:!1}:{enterChord:!1,commandId:u.command,commandArgs:u.commandArgs,bubble:u.bubble}:null},e.prototype._findCommand=function(t,n){for(var i=n.length-1;i>=0;i--){var r=n[i];if(e.contextMatchesRules(t,r.when))return r}return null},e.contextMatchesRules=function(e,t){return!t||t.evaluate(e)},e}(),ln=n("Kx4b"),dn=function(){return function(e,t,n,i,r){this.resolvedKeybinding=e,this.keypressParts=e?function(e){for(var t=[],n=0,i=e.length;n1},t.prototype.getParts=function(){var e=this;return this._parts.map(function(t){return e._getPart(t)})},t.prototype._getPart=function(e){return new R.d(e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,this._getLabel(e),this._getAriaLabel(e))},t.prototype.getDispatchParts=function(){var e=this;return this._parts.map(function(t){return e._getDispatchPart(t)})},t}(R.c),gn=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),mn=function(e){function t(t,n){return e.call(this,n,t.parts)||this}return gn(t,e),t.prototype._keyCodeToUILabel=function(e){if(2===this._os)switch(e){case 15:return"←";case 16:return"↑";case 17:return"→";case 18:return"↓"}return R.b.toString(e)},t.prototype._getLabel=function(e){return e.isDuplicateModifierCase()?"":this._keyCodeToUILabel(e.keyCode)},t.prototype._getAriaLabel=function(e){return e.isDuplicateModifierCase()?"":R.b.toString(e.keyCode)},t.prototype._getDispatchPart=function(e){return t.getDispatchStr(e)},t.getDispatchStr=function(e){if(e.isModifierKey())return null;var t="";return e.ctrlKey&&(t+="ctrl+"),e.shiftKey&&(t+="shift+"),e.altKey&&(t+="alt+"),e.metaKey&&(t+="meta+"),t+=R.b.toString(e.keyCode)},t}(pn),vn=n("fAkY"),_n=n("EMDP"),bn=n("EfIu"),yn=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),wn=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},Cn=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Sn=function(){function e(e){this.model=e,this._onDispose=new A.a}return Object.defineProperty(e.prototype,"textEditorModel",{get:function(){return this.model},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._onDispose.fire()},e}();var xn=function(){function e(){}return e.prototype.setEditor=function(e){this.editor=e},e.prototype.createModelReference=function(e){var t,n,i,r=this,o=null;return this.editor&&(t=this.editor,n=function(t){return r.findModel(t,e)},i=function(t){return r.findModel(t.getOriginalEditor(),e)||r.findModel(t.getModifiedEditor(),e)},o=Object(Zt.a)(t)?n(t):i(t)),o?Promise.resolve(new G.c(new Sn(o))):Promise.reject(new Error("Model not found"))},e.prototype.findModel=function(e,t){var n=e.getModel();return n&&n.uri.toString()!==t.toString()?null:n},e}(),Ln=function(){function e(){}return e.prototype.showWhile=function(e,t){return Promise.resolve(void 0)},e}(),On=function(){return function(){}}(),kn=function(){function e(){}return e.prototype.info=function(e){return this.notify({severity:Gt.a.Info,message:e})},e.prototype.warn=function(e){return this.notify({severity:Gt.a.Warning,message:e})},e.prototype.error=function(e){return this.notify({severity:Gt.a.Error,message:e})},e.prototype.notify=function(t){switch(t.severity){case Gt.a.Error:console.error(t.message);break;case Gt.a.Warning:console.warn(t.message);break;default:console.log(t.message)}return e.NO_OP},e.prototype.status=function(e,t){return G.a.None},e.NO_OP=new vn.b,e}(),Nn=function(){function e(e){this._onWillExecuteCommand=new A.a,this._onDidExecuteCommand=new A.a,this._instantiationService=e,this._dynamicCommands=Object.create(null)}return e.prototype.addCommand=function(e){var t=this,n=e.id;return this._dynamicCommands[n]=e,Object(G.h)(function(){delete t._dynamicCommands[n]})},e.prototype.executeCommand=function(e){for(var t=[],n=1;n0){var _=e[o-1];m=0===_.originalEndLineNumber?_.originalStartLineNumber+1:_.originalEndLineNumber+1,v=0===_.modifiedEndLineNumber?_.modifiedStartLineNumber+1:_.modifiedEndLineNumber+1}var b=p-3+1,y=g-3+1;if(bS)k+=O=S-k,N+=O;if(N>x)k+=O=x-N,N+=O;h[f++]=new ti(w,k,C,N),i[r++]=new ni(h)}var E=i[0].entries,I=[],D=0;for(o=1,s=i.length;od)&&(d=v),0!==_&&(0===h||_f)&&(f=b)}var y=document.createElement("div");y.className="diff-review-row";var w=document.createElement("div");w.className="diff-review-cell diff-review-summary";var C=d-l+1,S=f-h+1;w.appendChild(document.createTextNode(a+1+"/"+this._diffs.length+": @@ -"+l+","+C+" +"+h+","+S+" @@")),y.setAttribute("data-line",String(h));var x=function(e){return 0===e?on.a("no_lines","no lines"):1===e?on.a("one_line","1 line"):on.a("more_lines","{0} lines",e)},L=x(C),O=x(S);y.setAttribute("aria-label",on.a({key:"header",comment:["This is the ARIA label for a git diff header.","A git diff header looks like this: @@ -154,12 +159,39 @@.","That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.","Variables 0 and 1 refer to the diff index out of total number of diffs.","Variables 2 and 4 will be numbers (a line number).",'Variables 3 and 5 will be "no lines", "1 line" or "X lines", localized separately.']},"Difference {0} of {1}: original {2}, {3}, modified {4}, {5}",a+1,this._diffs.length,l,L,h,O)),y.appendChild(w),y.setAttribute("role","listitem"),c.appendChild(y);var k=h;for(p=0,g=u.length;p0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]r.modifiedStartLineNumber?on.a("diff.clipboard.copyDeletedLinesContent.label","Copy deleted lines"):on.a("diff.clipboard.copyDeletedLinesContent.single.label","Copy deleted line"),void 0,!0,function(){return pi(a,void 0,void 0,function(){return gi(this,function(e){switch(e.label){case 0:return[4,this._clipboardService.writeText(r.originalContent.join(c)+c)];case 1:return e.sent(),[2]}})})}));var d=0,h=void 0;return r.originalEndLineNumber>r.modifiedStartLineNumber&&(h=new Yn.a("diff.clipboard.copyDeletedLineContent",on.a("diff.clipboard.copyDeletedLineContent.label","Copy deleted line ({0})",r.originalStartLineNumber),void 0,!0,function(){return pi(a,void 0,void 0,function(){return gi(this,function(e){switch(e.label){case 0:return[4,this._clipboardService.writeText(r.originalContent[d])];case 1:return e.sent(),[2]}})})}),l.push(h)),i.getConfiguration().readOnly||l.push(new Yn.a("diff.inline.revertChange",on.a("diff.inline.revertChange.label","Revert this change"),void 0,!0,function(){return pi(a,void 0,void 0,function(){var e;return gi(this,function(t){return 0===r.modifiedEndLineNumber?(e=i.getModel().getLineMaxColumn(r.modifiedStartLineNumber),i.executeEdits("diffEditor",[{range:new W.a(r.modifiedStartLineNumber,e,r.modifiedStartLineNumber,e),text:c+r.originalContent.join(c)}])):(e=i.getModel().getLineMaxColumn(r.modifiedEndLineNumber),i.executeEdits("diffEditor",[{range:new W.a(r.modifiedStartLineNumber,1,r.modifiedEndLineNumber,e),text:r.originalContent.join(c)}])),[2]})})})),a._register(q.k(a._diffActions,"mousedown",function(e){var t=q.x(a._diffActions),n=t.top,i=t.height,o=Math.floor(u/3);e.preventDefault(),a._contextMenuService.showContextMenu({getAnchor:function(){return{x:e.posx,y:n+i+o}},getActions:function(){return h&&(h.label=on.a("diff.clipboard.copyDeletedLineContent.label","Copy deleted line ({0})",r.originalStartLineNumber+d)),l},autoSelectFirstItem:!0})})),a._register(i.onMouseMove(function(e){8===e.target.type||5===e.target.type?e.target.detail.viewZoneId===a._viewZoneId?(a.visibility=!0,d=a._updateLightBulbPosition(a._marginDomNode,e.event.browserEvent.y,u)):a.visibility=!1:a.visibility=!1})),a}return fi(t,e),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility!==e&&(this._visibility=e,this._diffActions.style.visibility=e?"visible":"hidden")},enumerable:!0,configurable:!0}),t.prototype._updateLightBulbPosition=function(e,t,n){var i=t-q.x(e).top,r=Math.floor(i/n),o=r*n;return this._diffActions.style.top=o+"px",r},t}(G.a),vi=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),_i=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},bi=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},yi=function(){function e(e,t){this._contextMenuService=e,this._clipboardService=t,this._zones=[],this.inlineDiffMargins=[],this._zonesMap={},this._decorations=[]}return e.prototype.getForeignViewZones=function(e){var t=this;return e.filter(function(e){return!t._zonesMap[String(e.id)]})},e.prototype.clean=function(e){var t=this;this._zones.length>0&&e.changeViewZones(function(e){for(var n=0,i=t._zones.length;n0?r/n:0;return{height:Math.max(0,Math.floor(e.contentHeight*o)),top:Math.floor(t*o)}},t.prototype._createDataSource=function(){var e=this;return{getWidth:function(){return e._width},getHeight:function(){return e._height-e._reviewHeight},getContainerDomNode:function(){return e._containerDomElement},relayoutEditors:function(){e._doLayout()},getOriginalEditor:function(){return e.originalEditor},getModifiedEditor:function(){return e.modifiedEditor}}},t.prototype._setStrategy=function(e){this._strategy&&this._strategy.dispose(),this._strategy=e,e.applyColors(this._themeService.getTheme()),this._diffComputationResult&&this._updateDecorations(),this._measureDomElement(!0)},t.prototype._getLineChangeAtOrBeforeLineNumber=function(e,t){var n=this._diffComputationResult?this._diffComputationResult.changes:[];if(0===n.length||e=a?i=o+1:(i=o,r=o)}return n[i]},t.prototype._getEquivalentLineForOriginalLineNumber=function(e){var t=this._getLineChangeAtOrBeforeLineNumber(e,function(e){return e.originalStartLineNumber});if(!t)return e;var n=t.originalStartLineNumber+(t.originalEndLineNumber>0?-1:0),i=t.modifiedStartLineNumber+(t.modifiedEndLineNumber>0?-1:0),r=t.originalEndLineNumber>0?t.originalEndLineNumber-t.originalStartLineNumber+1:0,o=t.modifiedEndLineNumber>0?t.modifiedEndLineNumber-t.modifiedStartLineNumber+1:0,s=e-n;return s<=r?i+Math.min(s,o):i+o-r+s},t.prototype._getEquivalentLineForModifiedLineNumber=function(e){var t=this._getLineChangeAtOrBeforeLineNumber(e,function(e){return e.modifiedStartLineNumber});if(!t)return e;var n=t.originalStartLineNumber+(t.originalEndLineNumber>0?-1:0),i=t.modifiedStartLineNumber+(t.modifiedEndLineNumber>0?-1:0),r=t.originalEndLineNumber>0?t.originalEndLineNumber-t.originalStartLineNumber+1:0,o=t.modifiedEndLineNumber>0?t.modifiedEndLineNumber-t.modifiedStartLineNumber+1:0,s=e-i;return s<=o?n+Math.min(s,r):n+r-o+s},t.prototype.getDiffLineInformationForOriginal=function(e){return this._diffComputationResult?{equivalentLineNumber:this._getEquivalentLineForOriginalLineNumber(e)}:null},t.prototype.getDiffLineInformationForModified=function(e){return this._diffComputationResult?{equivalentLineNumber:this._getEquivalentLineForModifiedLineNumber(e)}:null},t.ONE_OVERVIEW_WIDTH=15,t.ENTIRE_DIFF_OVERVIEW_WIDTH=30,t.UPDATE_DIFF_DECORATIONS_DELAY=200,t=_i([bi(3,me.a),bi(4,un.c),bi(5,nt.a),bi(6,K.a),bi(7,Qn.c),bi(8,vn.a),bi(9,hi.a)],t)}(G.a),Si=function(e){function t(t){var n=e.call(this)||this;return n._dataSource=t,n._insertColor=null,n._removeColor=null,n}return vi(t,e),t.prototype.applyColors=function(e){var t=(e.getColor(Jn.j)||Jn.g).transparent(2),n=(e.getColor(Jn.l)||Jn.h).transparent(2),i=!t.equals(this._insertColor)||!n.equals(this._removeColor);return this._insertColor=t,this._removeColor=n,i},t.prototype.getEditorsDiffDecorations=function(e,t,n,i,r,o,s){r=r.sort(function(e,t){return e.afterLineNumber-t.afterLineNumber}),i=i.sort(function(e,t){return e.afterLineNumber-t.afterLineNumber});var a=this._getViewZones(e,i,r,o,s,n),u=this._getOriginalEditorDecorations(e,t,n,o,s),c=this._getModifiedEditorDecorations(e,t,n,o,s);return{original:{decorations:u.decorations,overviewZones:u.overviewZones,zones:a.original},modified:{decorations:c.decorations,overviewZones:c.overviewZones,zones:a.modified}}},t}(G.a),xi=function(){function e(e){this._source=e,this._index=-1,this.current=null,this.advance()}return e.prototype.advance=function(){this._index++,this._index0){var n=e[e.length-1];if(n.afterLineNumber===t.afterLineNumber&&null===n.domNode)return void(n.heightInLines+=t.heightInLines)}e.push(t)},d=new xi(this.modifiedForeignVZ),h=new xi(this.originalForeignVZ),f=0,p=this.lineChanges.length;f<=p;f++){var g=f0?-1:0),s=g.modifiedStartLineNumber+(g.modifiedEndLineNumber>0?-1:0),r=g.originalEndLineNumber>0?g.originalEndLineNumber-g.originalStartLineNumber+1:0,i=g.modifiedEndLineNumber>0?g.modifiedEndLineNumber-g.modifiedStartLineNumber+1:0,a=Math.max(g.originalStartLineNumber,g.originalEndLineNumber),u=Math.max(g.modifiedStartLineNumber,g.modifiedEndLineNumber)):(a=o+=1e7+r,u=s+=1e7+i);for(var m,v=[],_=[];d.current&&d.current.afterLineNumber<=u;){var b=void 0;b=d.current.afterLineNumber<=s?o-s+d.current.afterLineNumber:a;var y=null;g&&g.modifiedStartLineNumber<=d.current.afterLineNumber&&d.current.afterLineNumber<=g.modifiedEndLineNumber&&(y=this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion()),v.push({afterLineNumber:b,heightInLines:d.current.heightInLines,domNode:null,marginDomNode:y}),d.advance()}for(;h.current&&h.current.afterLineNumber<=a;){b=void 0;b=h.current.afterLineNumber<=o?s-o+h.current.afterLineNumber:u,_.push({afterLineNumber:b,heightInLines:h.current.heightInLines,domNode:null}),h.advance()}if(null!==g&&Mi(g))(m=this._produceOriginalFromDiff(g,r,i))&&v.push(m);if(null!==g&&Ti(g))(m=this._produceModifiedFromDiff(g,r,i))&&_.push(m);var w=0,C=0;for(v=v.sort(c),_=_.sort(c);w=x.heightInLines?(S.heightInLines-=x.heightInLines,C++):(x.heightInLines-=S.heightInLines,w++)}for(;w2*t.MINIMUM_EDITOR_WIDTH?(in-t.MINIMUM_EDITOR_WIDTH&&(i=n-t.MINIMUM_EDITOR_WIDTH)):i=r,this._sashPosition!==i&&(this._sashPosition=i,this._sash.layout()),this._sashPosition},t.prototype.onSashDragStart=function(){this._startSashPosition=this._sashPosition},t.prototype.onSashDrag=function(e){var t=this._dataSource.getWidth()-Ci.ENTIRE_DIFF_OVERVIEW_WIDTH,n=this.layout((this._startSashPosition+(e.currentX-e.startX))/t);this._sashRatio=n/t,this._dataSource.relayoutEditors()},t.prototype.onSashDragEnd=function(){this._sash.layout()},t.prototype.onSashReset=function(){this._sashRatio=.5,this._dataSource.relayoutEditors(),this._sash.layout()},t.prototype.getVerticalSashTop=function(e){return 0},t.prototype.getVerticalSashLeft=function(e){return this._sashPosition},t.prototype.getVerticalSashHeight=function(e){return this._dataSource.getHeight()},t.prototype._getViewZones=function(e,t,n,i,r){return new Ei(e,t,n).getViewZones()},t.prototype._getOriginalEditorDecorations=function(e,t,n,i,r){for(var o=String(this._removeColor),s={decorations:[],overviewZones:[]},a=i.getModel(),u=0,c=e.length;ut?{afterLineNumber:Math.max(e.originalStartLineNumber,e.originalEndLineNumber),heightInLines:n-t,domNode:null}:null},t.prototype._produceModifiedFromDiff=function(e,t,n){return t>n?{afterLineNumber:Math.max(e.modifiedStartLineNumber,e.modifiedEndLineNumber),heightInLines:t-n,domNode:null}:null},t}(Li),Ii=function(e){function t(t,n){var i=e.call(this,t)||this;return i.decorationsLeft=t.getOriginalEditor().getLayoutInfo().decorationsLeft,i._register(t.getOriginalEditor().onDidLayoutChange(function(e){i.decorationsLeft!==e.decorationsLeft&&(i.decorationsLeft=e.decorationsLeft,t.relayoutEditors())})),i}return vi(t,e),t.prototype.setEnableSplitViewResizing=function(e){},t.prototype._getViewZones=function(e,t,n,i,r,o){return new Di(e,t,n,i,r,o).getViewZones()},t.prototype._getOriginalEditorDecorations=function(e,t,n,i,r){for(var o=String(this._removeColor),s={decorations:[],overviewZones:[]},a=0,u=e.length;a
      '])}h+=this.modifiedEditorConfiguration.viewInfo.scrollBeyondLastColumn;var m=document.createElement("div");m.className="view-lines line-delete",m.innerHTML=a.build(),Kn.a.applyFontInfoSlow(m,this.modifiedEditorConfiguration.fontInfo);var v=document.createElement("div");return v.className="inline-deleted-margin-view-zone",v.innerHTML=u.join(""),Kn.a.applyFontInfoSlow(v,this.modifiedEditorConfiguration.fontInfo),{shouldNotShrink:!0,afterLineNumber:0===e.modifiedEndLineNumber?e.modifiedStartLineNumber:e.modifiedStartLineNumber-1,heightInLines:t,minWidthInPx:h*d,domNode:m,marginDomNode:v,diff:{originalStartLineNumber:e.originalStartLineNumber,originalEndLineNumber:e.originalEndLineNumber,modifiedStartLineNumber:e.modifiedStartLineNumber,modifiedEndLineNumber:e.modifiedEndLineNumber,originalContent:f}}},t.prototype._renderOriginalLine=function(e,t,n,i,r,o,s){var a=t.getLineTokens(r),u=a.getLineContent(),c=li.a.filter(o,r,1,u.length+1);s.appendASCIIString('
      ');var l=xt.d.isBasicASCII(u,t.mightContainNonBasicASCII()),d=xt.d.containsRTL(u,l,t.mightContainRTL()),h=Object(St.d)(new St.c(n.fontInfo.isMonospace&&!n.viewInfo.disableMonospaceOptimizations,n.fontInfo.canUseHalfwidthRightwardsArrow,u,!1,l,d,0,a,c,i,n.fontInfo.spaceWidth,n.viewInfo.stopRenderingLineAfter,n.viewInfo.renderWhitespace,n.viewInfo.renderControlCharacters,n.viewInfo.fontLigatures,null),s);s.appendASCIIString("
      ");var f=h.characterMapping.getAbsoluteOffsets();return f.length>0?f[f.length-1]:0},t}(Li);function Mi(e){return e.modifiedEndLineNumber>0}function Ti(e){return e.originalEndLineNumber>0}Object(Qn.f)(function(e,t){var n=e.getColor(Jn.j);n&&(t.addRule(".monaco-editor .line-insert, .monaco-editor .char-insert { background-color: "+n+"; }"),t.addRule(".monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: "+n+"; }"),t.addRule(".monaco-editor .inline-added-margin-view-zone { background-color: "+n+"; }"));var i=e.getColor(Jn.l);i&&(t.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { background-color: "+i+"; }"),t.addRule(".monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: "+i+"; }"),t.addRule(".monaco-editor .inline-deleted-margin-view-zone { background-color: "+i+"; }"));var r=e.getColor(Jn.k);r&&t.addRule(".monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px "+("hc"===e.type?"dashed":"solid")+" "+r+"; }");var o=e.getColor(Jn.m);o&&t.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px "+("hc"===e.type?"dashed":"solid")+" "+o+"; }");var s=e.getColor(Jn._37);s&&t.addRule(".monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px "+s+"; }");var a=e.getColor(Jn.i);a&&t.addRule(".monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid "+a+"; }")});var Pi=n("lthF"),Ai=n("sKqm"),Ri=n("C3c5"),Fi=n("NqM+"),ji=n("xJaW"),Wi=n("44YW"),Bi=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Vi=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},Hi=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},zi=0,Ui=!1;var Ki=function(e){function t(t,n,i,r,o,s,a,u,c,l){var d=this;return(n=n||{}).ariaLabel=n.ariaLabel||bn.g.editorViewAccessibleLabel,n.ariaLabel=n.ariaLabel+";"+(Bn.j?bn.g.accessibilityHelpMessageIE:bn.g.accessibilityHelpMessage),(d=e.call(this,t,n,{},i,r,o,s,u,c,l)||this)._standaloneKeybindingService=a instanceof En?a:null,Ui||(Ui=!0,Vn.b(document.body)),d}return Bi(t,e),t.prototype.addCommand=function(e,t,n){if(!this._standaloneKeybindingService)return console.warn("Cannot add command because the editor is configured with an unrecognized KeybindingService"),null;var i="DYNAMIC_"+ ++zi,r=un.a.deserialize(n);return this._standaloneKeybindingService.addDynamicKeybinding(i,e,t,r),i},t.prototype.createContextKey=function(e,t){return this._contextKeyService.createKey(e,t)},t.prototype.addAction=function(e){var t=this;if("string"!=typeof e.id||"string"!=typeof e.label||"function"!=typeof e.run)throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");if(!this._standaloneKeybindingService)return console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService"),G.a.None;var n=e.id,i=e.label,r=un.a.and(un.a.equals("editorId",this.getId()),un.a.deserialize(e.precondition)),o=e.keybindings,s=un.a.and(r,un.a.deserialize(e.keybindingContext)),a=e.contextMenuGroupId||null,u=e.contextMenuOrder||0,c=function(){return Promise.resolve(e.run(t))},l=new G.b,d=this.getId()+":"+n;if(l.add(Q.a.registerCommand(d,c)),a){var h={command:{id:d,title:i},when:r,group:a,order:u};l.add(Ri.c.appendMenuItem(7,h))}if(Array.isArray(o))for(var f=0,p=o;f=0}}(e);tr.push(n),n.userConfigured?ir.push(n):nr.push(n),t&&!n.userConfigured&&tr.forEach(function(e){e.mime===n.mime||e.userConfigured||(n.extension&&e.extension===n.extension&&console.warn("Overwriting extension <<"+n.extension+">> to now point to mime <<"+n.mime+">>"),n.filename&&e.filename===n.filename&&console.warn("Overwriting filename <<"+n.filename+">> to now point to mime <<"+n.mime+">>"),n.filepattern&&e.filepattern===n.filepattern&&console.warn("Overwriting filepattern <<"+n.filepattern+">> to now point to mime <<"+n.mime+">>"),n.firstline&&e.firstline===n.firstline&&console.warn("Overwriting firstline <<"+n.firstline+">> to now point to mime <<"+n.mime+">>"))})}function or(e,t){var n;if(e)switch(e.scheme){case X.b.file:n=e.fsPath;break;case X.b.data:n=$.a.parseMetaData(e).get($.a.META_DATA_LABEL);break;default:n=e.path}if(!n)return[er];n=n.toLowerCase();var i=Object($i.basename)(n),r=sr(n,i,ir);if(r)return[r,Qi];var o=sr(n,i,nr);if(o)return[o,Qi];if(t){var s=function(e){Object(J.L)(e)&&(e=e.substr(1));if(e.length>0)for(var t=tr.length-1;t>=0;t--){var n=tr[t];if(n.firstline){var i=e.match(n.firstline);if(i&&i.length>0)return n.mime}}return null}(t);if(s)return[s,Qi]}return[er]}function sr(e,t,n){for(var i=null,r=null,o=null,s=n.length-1;s>=0;s--){var a=n[s];if(t===a.filenameLowercase){i=a;break}if(a.filepattern&&(!r||a.filepattern.length>r.filepattern.length)){var u=a.filepatternOnPath?e:t;Object(Ji.a)(a.filepatternLowercase,u)&&(r=a)}a.extension&&(!o||a.extension.length>o.extension.length)&&Object(J.m)(t,a.extensionLowercase)&&(o=a)}return i?i.mime:r?r.mime:o?o.mime:null}var ar=n("9XyG"),ur=n("RWr8"),cr=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),lr=Object.prototype.hasOwnProperty,dr=function(e){function t(t,n){void 0===t&&(t=!0),void 0===n&&(n=!1);var i=e.call(this)||this;return i._onDidChange=i._register(new A.a),i.onDidChange=i._onDidChange.event,i._warnOnOverwrite=n,i._nextLanguageId2=1,i._languageIdToLanguage=[],i._languageToLanguageId=Object.create(null),i._languages={},i._mimeTypesMap={},i._nameMap={},i._lowercaseNameMap={},t&&(i._initializeFromRegistry(),i._register(ar.a.onDidChangeLanguages(function(e){return i._initializeFromRegistry()}))),i}return cr(t,e),t.prototype._initializeFromRegistry=function(){this._languages={},this._mimeTypesMap={},this._nameMap={},this._lowercaseNameMap={};var e=ar.a.getLanguages();this._registerLanguages(e)},t.prototype._registerLanguages=function(e){for(var t=this,n=0,i=e;n0&&((n=e.mimetypes).push.apply(n,t.mimetypes),r=t.mimetypes[0]),r||(r="text/x-"+i,e.mimetypes.push(r)),Array.isArray(t.extensions))for(var o=0,s=t.extensions;o0){var f=t.firstLine;"^"!==f.charAt(0)&&(f="^"+f);try{var p=new RegExp(f);J.E(p)||rr({id:i,mime:r,firstline:p},this._warnOnOverwrite)}catch(e){Object(be.e)(e)}}e.aliases.push(i);var g=null;if(void 0!==t.aliases&&Array.isArray(t.aliases)&&(g=0===t.aliases.length?[null]:t.aliases),null!==g)for(var m=0,v=g;m0;if(b&&null===g[0]);else{var y=(b?g[0]:null)||i;!b&&e.name||(e.name=y)}t.configuration&&e.configurationFiles.push(t.configuration)},t.prototype.isRegisteredMode=function(e){return!!lr.call(this._mimeTypesMap,e)||lr.call(this._languages,e)},t.prototype.getModeIdForLanguageNameLowercase=function(e){return lr.call(this._lowercaseNameMap,e)?this._lowercaseNameMap[e].language:null},t.prototype.extractModeIds=function(e){var t=this;return e?e.split(",").map(function(e){return e.trim()}).map(function(e){return lr.call(t._mimeTypesMap,e)?t._mimeTypesMap[e].language:e}).filter(function(e){return lr.call(t._languages,e)}):[]},t.prototype.getLanguageIdentifier=function(e){if(e===ge.b||0===e)return ge.a;var t;if("string"==typeof e)t=e;else if(!(t=this._languageIdToLanguage[e]))return null;return lr.call(this._languages,t)?this._languages[t].identifier:null},t.prototype.getModeIdsFromFilepathOrFirstLine=function(e,t){if(!e&&!t)return[];var n=or(e,t);return this.extractModeIds(n.join(","))},t}(G.a),hr=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),fr=function(e){function t(t,n){var i=e.call(this)||this;return i._onDidChange=i._register(new A.a),i.onDidChange=i._onDidChange.event,i._selector=n,i.languageIdentifier=i._selector(),i._register(t(function(){return i._evaluate()})),i}return hr(t,e),t.prototype._evaluate=function(){var e=this._selector();e.id!==this.languageIdentifier.id&&(this.languageIdentifier=e,this._onDidChange.fire(this.languageIdentifier))},t}(G.a),pr=function(){function e(e){var t=this;void 0===e&&(e=!1),this._onDidCreateMode=new A.a,this.onDidCreateMode=this._onDidCreateMode.event,this._onLanguagesMaybeChanged=new A.a,this.onLanguagesMaybeChanged=this._onLanguagesMaybeChanged.event,this._instantiatedModes={},this._registry=new dr(!0,e),this._registry.onDidChange(function(){return t._onLanguagesMaybeChanged.fire()})}return e.prototype.isRegisteredMode=function(e){return this._registry.isRegisteredMode(e)},e.prototype.getModeIdForLanguageName=function(e){return this._registry.getModeIdForLanguageNameLowercase(e)},e.prototype.getModeIdByFilepathOrFirstLine=function(e,t){var n=this._registry.getModeIdsFromFilepathOrFirstLine(e,t);return n.length>0?n[0]:null},e.prototype.getModeId=function(e){var t=this._registry.extractModeIds(e);return t.length>0?t[0]:null},e.prototype.getLanguageIdentifier=function(e){return this._registry.getLanguageIdentifier(e)},e.prototype.create=function(e){var t=this;return new fr(this.onLanguagesMaybeChanged,function(){var n=t.getModeId(e);return t._createModeAndGetLanguageIdentifier(n)})},e.prototype.createByFilepathOrFirstLine=function(e,t){var n=this;return new fr(this.onLanguagesMaybeChanged,function(){var i=n.getModeIdByFilepathOrFirstLine(e,t);return n._createModeAndGetLanguageIdentifier(i)})},e.prototype._createModeAndGetLanguageIdentifier=function(e){var t=this.getLanguageIdentifier(e||"plaintext")||ge.a;return this._getOrCreateMode(t.language),t},e.prototype.triggerMode=function(e){var t=this.getModeId(e);this._getOrCreateMode(t||"plaintext")},e.prototype._getOrCreateMode=function(e){if(!this._instantiatedModes.hasOwnProperty(e)){var t=this.getLanguageIdentifier(e)||ge.a;this._instantiatedModes[e]=new Xi(t),this._onDidCreateMode.fire(this._instantiatedModes[e])}return this._instantiatedModes[e]},e}(),gr=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),mr=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},vr=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}};function _r(e){return e.toString()}var br=function(){function e(e,t,n){this._modelEventListeners=new G.b,this.model=e,this._languageSelection=null,this._languageSelectionListener=null,this._modelEventListeners.add(e.onWillDispose(function(){return t(e)})),this._modelEventListeners.add(e.onDidChangeLanguage(function(t){return n(e,t)}))}return e.prototype._disposeLanguageSelection=function(){this._languageSelectionListener&&(this._languageSelectionListener.dispose(),this._languageSelectionListener=null),this._languageSelection&&(this._languageSelection.dispose(),this._languageSelection=null)},e.prototype.dispose=function(){this._modelEventListeners.dispose(),this._disposeLanguageSelection()},e.prototype.setLanguage=function(e){var t=this;this._disposeLanguageSelection(),this._languageSelection=e,this._languageSelectionListener=this._languageSelection.onDidChange(function(){return t.model.setMode(e.languageIdentifier)}),this.model.setMode(e.languageIdentifier)},e}(),yr=ye.c||ye.d?1:2,wr=function(e){function t(t,n){var i=e.call(this)||this;return i._onModelAdded=i._register(new A.a),i.onModelAdded=i._onModelAdded.event,i._onModelRemoved=i._register(new A.a),i.onModelRemoved=i._onModelRemoved.event,i._onModelModeChanged=i._register(new A.a),i.onModelModeChanged=i._onModelModeChanged.event,i._configurationService=t,i._resourcePropertiesService=n,i._models={},i._modelCreationOptionsByLanguageAndResource=Object.create(null),i._configurationServiceSubscription=i._configurationService.onDidChangeConfiguration(function(e){return i._updateModelOptions()}),i._updateModelOptions(),i}return gr(t,e),t._readModelOptions=function(e,t){var n=T.c.tabSize;if(e.editor&&void 0!==e.editor.tabSize){var i=parseInt(e.editor.tabSize,10);isNaN(i)||(n=i),n<1&&(n=1)}var r=n;if(e.editor&&void 0!==e.editor.indentSize&&"tabSize"!==e.editor.indentSize){var o=parseInt(e.editor.indentSize,10);isNaN(o)||(r=o),r<1&&(r=1)}var s=T.c.insertSpaces;e.editor&&void 0!==e.editor.insertSpaces&&(s="false"!==e.editor.insertSpaces&&Boolean(e.editor.insertSpaces));var a=yr,u=e.eol;"\r\n"===u?a=2:"\n"===u&&(a=1);var c=T.c.trimAutoWhitespace;e.editor&&void 0!==e.editor.trimAutoWhitespace&&(c="false"!==e.editor.trimAutoWhitespace&&Boolean(e.editor.trimAutoWhitespace));var l=T.c.detectIndentation;e.editor&&void 0!==e.editor.detectIndentation&&(l="false"!==e.editor.detectIndentation&&Boolean(e.editor.detectIndentation));var d=T.c.largeFileOptimizations;return e.editor&&void 0!==e.editor.largeFileOptimizations&&(d="false"!==e.editor.largeFileOptimizations&&Boolean(e.editor.largeFileOptimizations)),{isForSimpleWidget:t,tabSize:n,indentSize:r,insertSpaces:s,detectIndentation:l,defaultEOL:a,trimAutoWhitespace:c,largeFileOptimizations:d}},t.prototype.getCreationOptions=function(e,n,i){var r=this._modelCreationOptionsByLanguageAndResource[e+n];if(!r){var o=this._configurationService.getValue("editor",{overrideIdentifier:e,resource:n}),s=this._resourcePropertiesService.getEOL(n,e);r=t._readModelOptions({editor:o,eol:s},i),this._modelCreationOptionsByLanguageAndResource[e+n]=r}return r},t.prototype._updateModelOptions=function(){var e=this._modelCreationOptionsByLanguageAndResource;this._modelCreationOptionsByLanguageAndResource=Object.create(null);for(var n=Object.keys(this._models),i=0,r=n.length;i=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},Or=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},kr=function(e){function t(t,n){void 0===n&&(n=q.s());var i=e.call(this)||this;return i._decorationOptionProviders=new Map,i._styleSheet=n,i._themeService=t,i}return xr(t,e),t.prototype.registerDecorationType=function(e,t,n){var i=this._decorationOptionProviders.get(e);if(!i){var r={styleSheet:this._styleSheet,key:e,parentTypeKey:n,options:t||Object.create(null)};i=n?new Nr(this._themeService,r):new Er(this._themeService,r),this._decorationOptionProviders.set(e,i)}i.refCount++},t.prototype.removeDecorationType=function(e){var t=this._decorationOptionProviders.get(e);t&&(t.refCount--,t.refCount<=0&&(this._decorationOptionProviders.delete(e),t.dispose(),this.listCodeEditors().forEach(function(t){return t.removeDecorations(e)})))},t.prototype.resolveDecorationOptions=function(e,t){var n=this._decorationOptionProviders.get(e);if(!n)throw new Error("Unknown decoration type key: "+e);return n.getOptions(this,t)},t=Lr([Or(0,Qn.c)],t)}(Sr),Nr=function(){function e(e,t){this._parentTypeKey=t.parentTypeKey,this.refCount=0,this._beforeContentRules=new Dr(3,t,e),this._afterContentRules=new Dr(4,t,e)}return e.prototype.getOptions=function(e,t){var n=e.resolveDecorationOptions(this._parentTypeKey,!0);return this._beforeContentRules&&(n.beforeContentClassName=this._beforeContentRules.className),this._afterContentRules&&(n.afterContentClassName=this._afterContentRules.className),n},e.prototype.dispose=function(){this._beforeContentRules&&(this._beforeContentRules.dispose(),this._beforeContentRules=null),this._afterContentRules&&(this._afterContentRules.dispose(),this._afterContentRules=null)},e}(),Er=function(){function e(e,t){var n=this;this._disposables=new G.b,this.refCount=0;var i=function(i){var r=new Dr(i,t,e);if(n._disposables.add(r),r.hasContent)return r.className};this.className=i(0);var r,o=(r=new Dr(1,t,e),n._disposables.add(r),r.hasContent?{className:r.className,hasLetterSpacing:r.hasLetterSpacing}:null);o&&(this.inlineClassName=o.className,this.inlineClassNameAffectsLetterSpacing=o.hasLetterSpacing),this.beforeContentClassName=i(3),this.afterContentClassName=i(4),this.glyphMarginClassName=i(2);var s=t.options;this.isWholeLine=Boolean(s.isWholeLine),this.stickiness=s.rangeBehavior;var a=s.light&&s.light.overviewRulerColor||s.overviewRulerColor,u=s.dark&&s.dark.overviewRulerColor||s.overviewRulerColor;void 0===a&&void 0===u||(this.overviewRuler={color:a||u,darkColor:u||a,position:s.overviewRulerLane||fe.d.Center})}return e.prototype.getOptions=function(e,t){return t?{inlineClassName:this.inlineClassName,beforeContentClassName:this.beforeContentClassName,afterContentClassName:this.afterContentClassName,className:this.className,glyphMarginClassName:this.glyphMarginClassName,isWholeLine:this.isWholeLine,overviewRuler:this.overviewRuler,stickiness:this.stickiness}:this},e.prototype.dispose=function(){this._disposables.dispose()},e}(),Ir={color:"color:{0} !important;",opacity:"opacity:{0};",backgroundColor:"background-color:{0};",outline:"outline:{0};",outlineColor:"outline-color:{0};",outlineStyle:"outline-style:{0};",outlineWidth:"outline-width:{0};",border:"border:{0};",borderColor:"border-color:{0};",borderRadius:"border-radius:{0};",borderSpacing:"border-spacing:{0};",borderStyle:"border-style:{0};",borderWidth:"border-width:{0};",fontStyle:"font-style:{0};",fontWeight:"font-weight:{0};",textDecoration:"text-decoration:{0};",cursor:"cursor:{0};",letterSpacing:"letter-spacing:{0};",gutterIconPath:"background:{0} center center no-repeat;",gutterIconSize:"background-size:{0};",contentText:"content:'{0}';",contentIconPath:"content:{0};",margin:"margin:{0};",width:"width:{0};",height:"height:{0};"},Dr=function(){function e(e,t,n){var i=this;this._theme=n.getTheme(),this._ruleType=e,this._providerArgs=t,this._usesThemeColors=!1,this._hasContent=!1,this._hasLetterSpacing=!1;var r=Mr.getClassName(this._providerArgs.key,e);this._providerArgs.parentTypeKey&&(r=r+" "+Mr.getClassName(this._providerArgs.parentTypeKey,e)),this._className=r,this._unThemedSelector=Mr.getSelector(this._providerArgs.key,this._providerArgs.parentTypeKey,e),this._buildCSS(),this._usesThemeColors?this._themeListener=n.onThemeChange(function(e){i._theme=n.getTheme(),i._removeCSS(),i._buildCSS()}):this._themeListener=null}return e.prototype.dispose=function(){this._hasContent&&(this._removeCSS(),this._hasContent=!1),this._themeListener&&(this._themeListener.dispose(),this._themeListener=null)},Object.defineProperty(e.prototype,"hasContent",{get:function(){return this._hasContent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasLetterSpacing",{get:function(){return this._hasLetterSpacing},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),e.prototype._buildCSS=function(){var e,t,n,i=this._providerArgs.options;switch(this._ruleType){case 0:e=this.getCSSTextForModelDecorationClassName(i),t=this.getCSSTextForModelDecorationClassName(i.light),n=this.getCSSTextForModelDecorationClassName(i.dark);break;case 1:e=this.getCSSTextForModelDecorationInlineClassName(i),t=this.getCSSTextForModelDecorationInlineClassName(i.light),n=this.getCSSTextForModelDecorationInlineClassName(i.dark);break;case 2:e=this.getCSSTextForModelDecorationGlyphMarginClassName(i),t=this.getCSSTextForModelDecorationGlyphMarginClassName(i.light),n=this.getCSSTextForModelDecorationGlyphMarginClassName(i.dark);break;case 3:e=this.getCSSTextForModelDecorationContentClassName(i.before),t=this.getCSSTextForModelDecorationContentClassName(i.light&&i.light.before),n=this.getCSSTextForModelDecorationContentClassName(i.dark&&i.dark.before);break;case 4:e=this.getCSSTextForModelDecorationContentClassName(i.after),t=this.getCSSTextForModelDecorationContentClassName(i.light&&i.light.after),n=this.getCSSTextForModelDecorationContentClassName(i.dark&&i.dark.after);break;default:throw new Error("Unknown rule type: "+this._ruleType)}var r=this._providerArgs.styleSheet.sheet,o=!1;e.length>0&&(r.insertRule(this._unThemedSelector+" {"+e+"}",0),o=!0),t.length>0&&(r.insertRule(".vs"+this._unThemedSelector+" {"+t+"}",0),o=!0),n.length>0&&(r.insertRule(".vs-dark"+this._unThemedSelector+", .hc-black"+this._unThemedSelector+" {"+n+"}",0),o=!0),this._hasContent=o},e.prototype._removeCSS=function(){q.H(this._unThemedSelector,this._providerArgs.styleSheet)},e.prototype.getCSSTextForModelDecorationClassName=function(e){if(!e)return"";var t=[];return this.collectCSSText(e,["backgroundColor"],t),this.collectCSSText(e,["outline","outlineColor","outlineStyle","outlineWidth"],t),this.collectBorderSettingsCSSText(e,t),t.join("")},e.prototype.getCSSTextForModelDecorationInlineClassName=function(e){if(!e)return"";var t=[];return this.collectCSSText(e,["fontStyle","fontWeight","textDecoration","cursor","color","opacity","letterSpacing"],t),e.letterSpacing&&(this._hasLetterSpacing=!0),t.join("")},e.prototype.getCSSTextForModelDecorationContentClassName=function(e){if(!e)return"";var t=[];if(void 0!==e){if(this.collectBorderSettingsCSSText(e,t),void 0!==e.contentIconPath&&t.push(J.r(Ir.contentIconPath,q.n(F.a.revive(e.contentIconPath)))),"string"==typeof e.contentText){var n=e.contentText.match(/^.*$/m)[0].replace(/['\\]/g,"\\$&");t.push(J.r(Ir.contentText,n))}this.collectCSSText(e,["fontStyle","fontWeight","textDecoration","color","opacity","backgroundColor","margin"],t),this.collectCSSText(e,["width","height"],t)&&t.push("display:inline-block;")}return t.join("")},e.prototype.getCSSTextForModelDecorationGlyphMarginClassName=function(e){if(!e)return"";var t=[];return void 0!==e.gutterIconPath&&(t.push(J.r(Ir.gutterIconPath,q.n(F.a.revive(e.gutterIconPath)))),void 0!==e.gutterIconSize&&t.push(J.r(Ir.gutterIconSize,e.gutterIconSize))),t.join("")},e.prototype.collectBorderSettingsCSSText=function(e,t){return!!this.collectCSSText(e,["border","borderColor","borderRadius","borderSpacing","borderStyle","borderWidth"],t)&&(t.push(J.r("box-sizing: border-box;")),!0)},e.prototype.collectCSSText=function(e,t,n){for(var i=n.length,r=0,o=t;rt)return 1;return 0}(e.token,t.token);return 0!==n?n:e.index-t.index});for(var n=0,i="000000",r="ffffff";e.length>=1&&""===e[0].token;){var o=e.shift();-1!==o.fontStyle&&(n=o.fontStyle),null!==o.foreground&&(i=o.foreground),null!==o.background&&(r=o.background)}for(var s=new Wr,a=0,u=t;a>>0,this._cache.set(t,n)}return(n|e<<0)>>>0},e}(),Vr=/\b(comment|string|regex|regexp)\b/;var Hr,zr,Ur,Kr=function(){function e(e,t,n){this._fontStyle=e,this._foreground=t,this._background=n,this.metadata=(this._fontStyle<<11|this._foreground<<14|this._background<<23)>>>0}return e.prototype.clone=function(){return new e(this._fontStyle,this._foreground,this._background)},e.prototype.acceptOverwrite=function(e,t,n){-1!==e&&(this._fontStyle=e),0!==t&&(this._foreground=t),0!==n&&(this._background=n),this.metadata=(this._fontStyle<<11|this._foreground<<14|this._background<<23)>>>0},e}(),qr=function(){function e(e){this._mainRule=e,this._children=new Map}return e.prototype.match=function(e){if(""===e)return this._mainRule;var t,n,i=e.indexOf(".");-1===i?(t=e,n=""):(t=e.substring(0,i),n=e.substring(i+1));var r=this._children.get(t);return void 0!==r?r.match(n):this._mainRule},e.prototype.insert=function(t,n,i,r){if(""!==t){var o,s,a=t.indexOf(".");-1===a?(o=t,s=""):(o=t.substring(0,a),s=t.substring(a+1));var u=this._children.get(o);void 0===u&&(u=new e(this._mainRule.clone()),this._children.set(o,u)),u.insert(s,n,i,r)}else this._mainRule.acceptOverwrite(n,i,r)},e}();var Gr={base:"vs",inherit:!1,rules:[{token:"",foreground:"000000",background:"fffffe"},{token:"invalid",foreground:"cd3131"},{token:"emphasis",fontStyle:"italic"},{token:"strong",fontStyle:"bold"},{token:"variable",foreground:"001188"},{token:"variable.predefined",foreground:"4864AA"},{token:"constant",foreground:"dd0000"},{token:"comment",foreground:"008000"},{token:"number",foreground:"09885A"},{token:"number.hex",foreground:"3030c0"},{token:"regexp",foreground:"800000"},{token:"annotation",foreground:"808080"},{token:"type",foreground:"008080"},{token:"delimiter",foreground:"000000"},{token:"delimiter.html",foreground:"383838"},{token:"delimiter.xml",foreground:"0000FF"},{token:"tag",foreground:"800000"},{token:"tag.id.pug",foreground:"4F76AC"},{token:"tag.class.pug",foreground:"4F76AC"},{token:"meta.scss",foreground:"800000"},{token:"metatag",foreground:"e00000"},{token:"metatag.content.html",foreground:"FF0000"},{token:"metatag.html",foreground:"808080"},{token:"metatag.xml",foreground:"808080"},{token:"metatag.php",fontStyle:"bold"},{token:"key",foreground:"863B00"},{token:"string.key.json",foreground:"A31515"},{token:"string.value.json",foreground:"0451A5"},{token:"attribute.name",foreground:"FF0000"},{token:"attribute.value",foreground:"0451A5"},{token:"attribute.value.number",foreground:"09885A"},{token:"attribute.value.unit",foreground:"09885A"},{token:"attribute.value.html",foreground:"0000FF"},{token:"attribute.value.xml",foreground:"0000FF"},{token:"string",foreground:"A31515"},{token:"string.html",foreground:"0000FF"},{token:"string.sql",foreground:"FF0000"},{token:"string.yaml",foreground:"0451A5"},{token:"keyword",foreground:"0000FF"},{token:"keyword.json",foreground:"0451A5"},{token:"keyword.flow",foreground:"AF00DB"},{token:"keyword.flow.scss",foreground:"0000FF"},{token:"operator.scss",foreground:"666666"},{token:"operator.sql",foreground:"778899"},{token:"operator.swift",foreground:"666666"},{token:"predefined.sql",foreground:"FF00FF"}],colors:(Hr={},Hr[Jn.o]="#FFFFFE",Hr[Jn.x]="#000000",Hr[Jn.E]="#E5EBF1",Hr[$n.h]="#D3D3D3",Hr[$n.a]="#939393",Hr[Jn.J]="#ADD6FF4D",Hr)},Zr={base:"vs-dark",inherit:!1,rules:[{token:"",foreground:"D4D4D4",background:"1E1E1E"},{token:"invalid",foreground:"f44747"},{token:"emphasis",fontStyle:"italic"},{token:"strong",fontStyle:"bold"},{token:"variable",foreground:"74B0DF"},{token:"variable.predefined",foreground:"4864AA"},{token:"variable.parameter",foreground:"9CDCFE"},{token:"constant",foreground:"569CD6"},{token:"comment",foreground:"608B4E"},{token:"number",foreground:"B5CEA8"},{token:"number.hex",foreground:"5BB498"},{token:"regexp",foreground:"B46695"},{token:"annotation",foreground:"cc6666"},{token:"type",foreground:"3DC9B0"},{token:"delimiter",foreground:"DCDCDC"},{token:"delimiter.html",foreground:"808080"},{token:"delimiter.xml",foreground:"808080"},{token:"tag",foreground:"569CD6"},{token:"tag.id.pug",foreground:"4F76AC"},{token:"tag.class.pug",foreground:"4F76AC"},{token:"meta.scss",foreground:"A79873"},{token:"meta.tag",foreground:"CE9178"},{token:"metatag",foreground:"DD6A6F"},{token:"metatag.content.html",foreground:"9CDCFE"},{token:"metatag.html",foreground:"569CD6"},{token:"metatag.xml",foreground:"569CD6"},{token:"metatag.php",fontStyle:"bold"},{token:"key",foreground:"9CDCFE"},{token:"string.key.json",foreground:"9CDCFE"},{token:"string.value.json",foreground:"CE9178"},{token:"attribute.name",foreground:"9CDCFE"},{token:"attribute.value",foreground:"CE9178"},{token:"attribute.value.number.css",foreground:"B5CEA8"},{token:"attribute.value.unit.css",foreground:"B5CEA8"},{token:"attribute.value.hex.css",foreground:"D4D4D4"},{token:"string",foreground:"CE9178"},{token:"string.sql",foreground:"FF0000"},{token:"keyword",foreground:"569CD6"},{token:"keyword.flow",foreground:"C586C0"},{token:"keyword.json",foreground:"CE9178"},{token:"keyword.flow.scss",foreground:"569CD6"},{token:"operator.scss",foreground:"909090"},{token:"operator.sql",foreground:"778899"},{token:"operator.swift",foreground:"909090"},{token:"predefined.sql",foreground:"FF00FF"}],colors:(zr={},zr[Jn.o]="#1E1E1E",zr[Jn.x]="#D4D4D4",zr[Jn.E]="#3A3D41",zr[$n.h]="#404040",zr[$n.a]="#707070",zr[Jn.J]="#ADD6FF26",zr)},Yr={base:"hc-black",inherit:!1,rules:[{token:"",foreground:"FFFFFF",background:"000000"},{token:"invalid",foreground:"f44747"},{token:"emphasis",fontStyle:"italic"},{token:"strong",fontStyle:"bold"},{token:"variable",foreground:"1AEBFF"},{token:"variable.parameter",foreground:"9CDCFE"},{token:"constant",foreground:"569CD6"},{token:"comment",foreground:"608B4E"},{token:"number",foreground:"FFFFFF"},{token:"regexp",foreground:"C0C0C0"},{token:"annotation",foreground:"569CD6"},{token:"type",foreground:"3DC9B0"},{token:"delimiter",foreground:"FFFF00"},{token:"delimiter.html",foreground:"FFFF00"},{token:"tag",foreground:"569CD6"},{token:"tag.id.pug",foreground:"4F76AC"},{token:"tag.class.pug",foreground:"4F76AC"},{token:"meta",foreground:"D4D4D4"},{token:"meta.tag",foreground:"CE9178"},{token:"metatag",foreground:"569CD6"},{token:"metatag.content.html",foreground:"1AEBFF"},{token:"metatag.html",foreground:"569CD6"},{token:"metatag.xml",foreground:"569CD6"},{token:"metatag.php",fontStyle:"bold"},{token:"key",foreground:"9CDCFE"},{token:"string.key",foreground:"9CDCFE"},{token:"string.value",foreground:"CE9178"},{token:"attribute.name",foreground:"569CD6"},{token:"attribute.value",foreground:"3FF23F"},{token:"string",foreground:"CE9178"},{token:"string.sql",foreground:"FF0000"},{token:"keyword",foreground:"569CD6"},{token:"keyword.flow",foreground:"C586C0"},{token:"operator.sql",foreground:"778899"},{token:"operator.swift",foreground:"909090"},{token:"predefined.sql",foreground:"FF00FF"}],colors:(Ur={},Ur[Jn.o]="#000000",Ur[Jn.x]="#FFFFFF",Ur[$n.h]="#FFFFFF",Ur[$n.a]="#FFFFFF",Ur)},Xr="vs",$r="vs-dark",Jr="hc-black",Qr=ur.a.as(Jn.a.ColorContribution),eo=ur.a.as(Qn.a.ThemingContribution),to=function(){function e(e,t){this.themeData=t;var n=t.base;e.length>0?(this.id=n+" "+e,this.themeName=e):(this.id=n,this.themeName=n),this.colors=null,this.defaultColors=Object.create(null),this._tokenTheme=null}return Object.defineProperty(e.prototype,"base",{get:function(){return this.themeData.base},enumerable:!0,configurable:!0}),e.prototype.notifyBaseUpdated=function(){this.themeData.inherit&&(this.colors=null,this._tokenTheme=null)},e.prototype.getColors=function(){if(!this.colors){var e=new Map;for(var t in this.themeData.colors)e.set(t,Ar.a.fromHex(this.themeData.colors[t]));if(this.themeData.inherit){var n=io(this.themeData.base);for(var t in n.colors)e.has(t)||e.set(t,Ar.a.fromHex(n.colors[t]))}this.colors=e}return this.colors},e.prototype.getColor=function(e,t){var n=this.getColors().get(e);return n||(!1!==t?this.getDefault(e):void 0)},e.prototype.getDefault=function(e){var t=this.defaultColors[e];return t||(t=Qr.resolveDefaultColor(e,this),this.defaultColors[e]=t,t)},e.prototype.defines=function(e){return Object.prototype.hasOwnProperty.call(this.getColors(),e)},Object.defineProperty(e.prototype,"type",{get:function(){switch(this.base){case Xr:return"light";case Jr:return"hc";default:return"dark"}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tokenTheme",{get:function(){if(!this._tokenTheme){var e=[],t=[];if(this.themeData.inherit){var n=io(this.themeData.base);e=n.rules,n.encodedTokensColors&&(t=n.encodedTokensColors)}e=e.concat(this.themeData.rules),this.themeData.encodedTokensColors&&(t=this.themeData.encodedTokensColors),this._tokenTheme=Br.createFromRawTokenTheme(e,t)}return this._tokenTheme},enumerable:!0,configurable:!0}),e}();function no(e){return e===Xr||e===$r||e===Jr}function io(e){switch(e){case Xr:return Gr;case $r:return Zr;case Jr:return Yr}}function ro(e){var t=io(e);return new to(e,t)}var oo=function(){function e(){this.environment=Object.create(null),this._onThemeChange=new A.a,this._onIconThemeChange=new A.a,this._knownThemes=new Map,this._knownThemes.set(Xr,ro(Xr)),this._knownThemes.set($r,ro($r)),this._knownThemes.set(Jr,ro(Jr)),this._styleElement=q.s(),this._styleElement.className="monaco-colors",this.setTheme(Xr)}return Object.defineProperty(e.prototype,"onThemeChange",{get:function(){return this._onThemeChange.event},enumerable:!0,configurable:!0}),e.prototype.defineTheme=function(e,t){if(!/^[a-z0-9\-]+$/i.test(e))throw new Error("Illegal theme name!");if(!no(t.base)&&!no(e))throw new Error("Illegal theme base!");this._knownThemes.set(e,new to(e,t)),no(e)&&this._knownThemes.forEach(function(t){t.base===e&&t.notifyBaseUpdated()}),this._theme&&this._theme.themeName===e&&this.setTheme(e)},e.prototype.getTheme=function(){return this._theme},e.prototype.setTheme=function(e){var t,n=this;if(t=this._knownThemes.has(e)?this._knownThemes.get(e):this._knownThemes.get(Xr),this._theme===t)return t.id;this._theme=t;var i=[],r={},o={addRule:function(e){r[e]||(i.push(e),r[e]=!0)}};eo.getThemingParticipants().forEach(function(e){return e(t,o,n.environment)});var s=t.tokenTheme.getColorMap();return o.addRule(function(e){for(var t=[],n=1,i=e.length;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},uo=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},co="data-keybinding-context",lo=function(){function e(e,t){this._id=e,this._parent=t,this._value=Object.create(null),this._value._contextId=e}return e.prototype.setValue=function(e,t){return this._value[e]!==t&&(this._value[e]=t,!0)},e.prototype.removeValue=function(e){return e in this._value&&(delete this._value[e],!0)},e.prototype.getValue=function(e){var t=this._value[e];return void 0===t&&this._parent?this._parent.getValue(e):t},e}(),ho=function(e){function t(){return e.call(this,-1,null)||this}return so(t,e),t.prototype.setValue=function(e,t){return!1},t.prototype.removeValue=function(e){return!1},t.prototype.getValue=function(e){},t.INSTANCE=new t,t}(lo),fo=function(e){function t(t,n,i){var r=e.call(this,t,null)||this;return r._configurationService=n,r._values=new Map,r._listener=r._configurationService.onDidChangeConfiguration(function(e){if(6===e.source){var t=Object(Jt.d)(r._values);r._values.clear(),i.fire(new mo(t))}else{for(var n=[],o=0,s=e.affectedKeys;o1){var i=n.shift();i&&(r.focusItemByElement(i.container),n.push(i)),r.mnemonics.set(t,n)}}})),ye.c&&r._register(Object(q.h)(o,q.d.KEY_DOWN,function(e){var t=new qt.a(e);t.equals(14)||t.equals(11)?(r.focusedItem=r.viewItems.length-1,r.focusNext(),q.c.stop(e,!0)):(t.equals(13)||t.equals(12))&&(r.focusedItem=0,r.focusPrevious(),q.c.stop(e,!0))})),r._register(Object(q.h)(r.domNode,q.d.MOUSE_OUT,function(e){var t=e.relatedTarget;Object(q.E)(t,r.domNode)||(r.focusedItem=void 0,r.scrollTopHold=r.menuElement.scrollTop,r.updateFocus(),e.stopPropagation())})),r._register(Object(q.h)(r.domNode,q.d.MOUSE_UP,function(e){q.c.stop(e,!0)})),r._register(Object(q.h)(r.actionsList,q.d.MOUSE_OVER,function(e){var t=e.target;if(t&&Object(q.E)(t,r.actionsList)&&t!==r.actionsList){for(;t.parentElement!==r.actionsList&&null!==t.parentElement;)t=t.parentElement;if(Object(q.C)(t,"action-item")){var n=r.focusedItem;r.scrollTopHold=r.menuElement.scrollTop,r.setFocusedItem(t),n!==r.focusedItem&&r.updateFocus()}}}));var s={parent:r};return r.mnemonics=new Map,r.push(n,{icon:!0,label:!0,isMenu:!0}),r.scrollableElement=r._register(new Zn.a(o,{alwaysConsumeMouseWheel:!0,horizontal:2,vertical:3,verticalScrollbarSize:7,handleMouseWheel:!0,useShadows:!0})),r.scrollableElement.getDomNode().style.position=null,o.style.maxHeight=Math.max(10,window.innerHeight-t.getBoundingClientRect().top-30)+"px",r.menuDisposables.add(r.scrollableElement.onScroll(function(){r._onScroll.fire()},r)),r._register(Object(q.h)(r.menuElement,q.d.SCROLL,function(e){void 0!==r.scrollTopHold&&(r.menuElement.scrollTop=r.scrollTopHold,r.scrollTopHold=void 0),r.scrollableElement.scanDomNode()})),t.appendChild(r.scrollableElement.getDomNode()),r.scrollableElement.scanDomNode(),r.viewItems.filter(function(e){return!(e instanceof No)}).forEach(function(e,t,n){e.updatePositionInSet(t+1,n.length)}),r}return wo(t,e),t.prototype.style=function(e){var t=this.getContainer(),n=e.foregroundColor?""+e.foregroundColor:null,i=e.backgroundColor?""+e.backgroundColor:null,r=e.borderColor?"2px solid "+e.borderColor:null,o=e.shadowColor?"0 2px 4px "+e.shadowColor:null;t.style.border=r,this.domNode.style.color=n,this.domNode.style.backgroundColor=i,t.style.boxShadow=o,this.viewItems&&this.viewItems.forEach(function(t){(t instanceof Oo||t instanceof No)&&t.style(e)})},t.prototype.getContainer=function(){return this.scrollableElement.getDomNode()},Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scrollOffset",{get:function(){return this.menuElement.scrollTop},enumerable:!0,configurable:!0}),t.prototype.focusItemByElement=function(e){var t=this.focusedItem;this.setFocusedItem(e),t!==this.focusedItem&&this.updateFocus()},t.prototype.setFocusedItem=function(e){for(var t=0;t
      ',u+='",u+='",u+='",u+='",u+='",u+="",u+='
      ',n'+Object(a.o)(t.tokens1[n].type)+""),this._domNode.innerHTML=u,this._editor.layoutContentWidget(this)},t.prototype._decodeMetadata=function(e){var t=c.y.getColorMap(),n=c.x.getLanguageId(e),i=c.x.getTokenType(e),r=c.x.getFontStyle(e),o=c.x.getForeground(e),s=c.x.getBackground(e);return{languageIdentifier:this._modeService.getLanguageIdentifier(n),tokenType:i,fontStyle:r,foreground:t[o],background:t[s]}},t.prototype._tokenTypeToString=function(e){switch(e){case 0:return"Other";case 1:return"Comment";case 2:return"String";case 4:return"RegEx"}return"??"},t.prototype._fontStyleToString=function(e){var t="";return 1&e&&(t+="italic "),2&e&&(t+="bold "),4&e&&(t+="underline "),0===t.length&&(t="---"),t},t.prototype._getTokensAtLine=function(e){var t=this._getStateBeforeLine(e),n=this._tokenizationSupport.tokenize(this._model.getLineContent(e),t,0),i=this._tokenizationSupport.tokenize2(this._model.getLineContent(e),t,0);return{startState:t,tokens1:n.tokens,tokens2:i.tokens,endState:n.endState}},t.prototype._getStateBeforeLine=function(e){for(var t=this._tokenizationSupport.getInitialState(),n=1;n0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=o)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(e){return"[Circular]"}default:return e}}),u=i[n];n=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),p(n)?i.showHidden=n:n&&t._extend(i,n),_(i.showHidden)&&(i.showHidden=!1),_(i.depth)&&(i.depth=2),_(i.colors)&&(i.colors=!1),_(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=u),l(i,e,i.depth)}function u(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function c(e,t){return e}function l(e,n,i){if(e.customInspect&&n&&S(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var r=n.inspect(i,e);return v(r)||(r=l(e,r,i)),r}var o=function(e,t){if(_(t))return e.stylize("undefined","undefined");if(v(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(m(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(g(t))return e.stylize("null","null")}(e,n);if(o)return o;var s=Object.keys(n),a=function(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(n)),C(n)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return d(n);if(0===s.length){if(S(n)){var u=n.name?": "+n.name:"";return e.stylize("[Function"+u+"]","special")}if(b(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(w(n))return e.stylize(Date.prototype.toString.call(n),"date");if(C(n))return d(n)}var c,y="",x=!1,L=["{","}"];(f(n)&&(x=!0,L=["[","]"]),S(n))&&(y=" [Function"+(n.name?": "+n.name:"")+"]");return b(n)&&(y=" "+RegExp.prototype.toString.call(n)),w(n)&&(y=" "+Date.prototype.toUTCString.call(n)),C(n)&&(y=" "+d(n)),0!==s.length||x&&0!=n.length?i<0?b(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special"):(e.seen.push(n),c=x?function(e,t,n,i,r){for(var o=[],s=0,a=t.length;s=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1];return n[0]+t+" "+e.join(", ")+" "+n[1]}(c,y,L)):L[0]+y+L[1]}function d(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,n,i,r,o){var s,a,u;if((u=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(a=e.stylize("[Setter]","special")),k(i,r)||(s="["+r+"]"),a||(e.seen.indexOf(u.value)<0?(a=g(n)?l(e,u.value,null):l(e,u.value,n-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),_(s)){if(o&&r.match(/^\d+$/))return a;(s=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function f(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function v(e){return"string"==typeof e}function _(e){return void 0===e}function b(e){return y(e)&&"[object RegExp]"===x(e)}function y(e){return"object"==typeof e&&null!==e}function w(e){return y(e)&&"[object Date]"===x(e)}function C(e){return y(e)&&("[object Error]"===x(e)||e instanceof Error)}function S(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}function L(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(n){if(_(o)&&(o=Object({NODE_ENV:"production"}).NODE_DEBUG||""),n=n.toUpperCase(),!s[n])if(new RegExp("\\b"+n+"\\b","i").test(o)){var i=e.pid;s[n]=function(){var e=t.format.apply(t,arguments);console.error("%s %d: %s",n,i,e)}}else s[n]=function(){};return s[n]},t.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=f,t.isBoolean=p,t.isNull=g,t.isNullOrUndefined=function(e){return null==e},t.isNumber=m,t.isString=v,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=_,t.isRegExp=b,t.isObject=y,t.isDate=w,t.isError=C,t.isFunction=S,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=n("fC4T");var O=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,n;console.log("%s - %s",(e=new Date,n=[L(e.getHours()),L(e.getMinutes()),L(e.getSeconds())].join(":"),[e.getDate(),O[e.getMonth()],n].join(" ")),t.format.apply(t,arguments))},t.inherits=n("ONRY"),t._extend=function(e,t){if(!t||!y(t))return e;for(var n=Object.keys(t),i=n.length;i--;)e[n[i]]=t[n[i]];return e};var N="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function E(e,t){if(!e){var n=new Error("Promise was rejected with a falsy value");n.reason=e,e=n}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(N&&e[N]){var t;if("function"!=typeof(t=e[N]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,N,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,n,i=new Promise(function(e,i){t=e,n=i}),r=[],o=0;or&&(r=a)}return r}if("string"==typeof e)return i?"*"===e?5:e===n?10:0:0;if(e){var l=e.language,d=e.pattern,h=e.scheme,f=e.hasAccessToAllModels;if(!i&&!f)return 0;r=0;if(h)if(h===t.scheme)r=10;else{if("*"!==h)return 0;r=5}if(l)if(l===n)r=10;else{if("*"!==l)return 0;r=Math.max(r,5)}if(d){if(d!==t.fsPath&&!Object(u.a)(d,t.fsPath))return 0;r=10}return r}return 0}var l=n("jIdl");function d(e){return"string"!=typeof e&&(Array.isArray(e)?e.every(d):!!e.exclusive)}var h=function(){function e(){this._clock=0,this._entries=[],this._onDidChange=new s.a}return Object.defineProperty(e.prototype,"onDidChange",{get:function(){return this._onDidChange.event},enumerable:!0,configurable:!0}),e.prototype.register=function(e,t){var n=this,i={selector:e,provider:t,_score:-1,_time:this._clock++};return this._entries.push(i),this._lastCandidate=void 0,this._onDidChange.fire(this._entries.length),Object(a.h)(function(){if(i){var e=n._entries.indexOf(i);e>=0&&(n._entries.splice(e,1),n._lastCandidate=void 0,n._onDidChange.fire(n._entries.length),i=void 0)}})},e.prototype.has=function(e){return this.all(e).length>0},e.prototype.all=function(e){if(!e)return[];this._updateScores(e);for(var t=[],n=0,i=this._entries;n0&&t.push(r.provider)}return t},e.prototype.ordered=function(e){var t=[];return this._orderedForEach(e,function(e){return t.push(e.provider)}),t},e.prototype.orderedGroups=function(e){var t,n,i=[];return this._orderedForEach(e,function(e){t&&n===e._score?t.push(e.provider):(n=e._score,t=[e.provider],i.push(t))}),i},e.prototype._orderedForEach=function(e,t){if(e){this._updateScores(e);for(var n=0,i=this._entries;n0&&t(r)}}},e.prototype._updateScores=function(t){var n={uri:t.uri.toString(),language:t.getLanguageIdentifier().language};if(!this._lastCandidate||this._lastCandidate.language!==n.language||this._lastCandidate.uri!==n.uri){this._lastCandidate=n;for(var i=0,r=this._entries;i0){for(var s=0,a=this._entries;st._score?-1:e._timet._time?-1:0},e}(),f=n("WTFd"),p=function(){function e(){this._map=new Map,this._promises=new Map,this._onDidChange=new s.a,this.onDidChange=this._onDidChange.event,this._colorMap=null}return e.prototype.fire=function(e){this._onDidChange.fire({changedLanguages:e,changedColorMap:!1})},e.prototype.register=function(e,t){var n=this;return this._map.set(e,t),this.fire([e]),Object(a.h)(function(){n._map.get(e)===t&&(n._map.delete(e),n.fire([e]))})},e.prototype.registerPromise=function(e,t){var n=this,i=null,r=!1;return this._promises.set(e,t.then(function(t){n._promises.delete(e),!r&&t&&(i=n.register(e,t))})),Object(a.h)(function(){r=!0,i&&i.dispose()})},e.prototype.getPromise=function(e){var t=this,n=this.get(e);if(n)return Promise.resolve(n);var i=this._promises.get(e);return i?i.then(function(n){return t.get(e)}):null},e.prototype.get=function(e){return Object(i.n)(this._map.get(e))},e.prototype.setColorMap=function(e){this._colorMap=e,this._onDidChange.fire({changedLanguages:Object(f.d)(this._map),changedColorMap:!0})},e.prototype.getColorMap=function(){return this._colorMap},e.prototype.getDefaultBackground=function(){return this._colorMap&&this._colorMap.length>2?this._colorMap[2]:null},e}();n.d(t,"p",function(){return _}),n.d(t,"x",function(){return b}),n.d(t,"B",function(){return y}),n.d(t,"A",function(){return w}),n.d(t,"w",function(){return m}),n.d(t,"h",function(){return v}),t.C=function(e){return e&&r.a.isUri(e.uri)&&o.a.isIRange(e.range)&&(o.a.isIRange(e.originSelectionRange)||o.a.isIRange(e.targetSelectionRange))},n.d(t,"E",function(){return S}),n.d(t,"l",function(){return x}),t.D=function(e){return Object(i.h)(e)&&e.resource&&Array.isArray(e.edits)},n.d(t,"s",function(){return L}),n.d(t,"t",function(){return O}),n.d(t,"d",function(){return k}),n.d(t,"v",function(){return N}),n.d(t,"n",function(){return E}),n.d(t,"k",function(){return I}),n.d(t,"i",function(){return D}),n.d(t,"f",function(){return M}),n.d(t,"e",function(){return T}),n.d(t,"o",function(){return P}),n.d(t,"z",function(){return A}),n.d(t,"b",function(){return R}),n.d(t,"a",function(){return F}),n.d(t,"g",function(){return j}),n.d(t,"j",function(){return W}),n.d(t,"r",function(){return B}),n.d(t,"q",function(){return V}),n.d(t,"c",function(){return H}),n.d(t,"u",function(){return z}),n.d(t,"m",function(){return U}),n.d(t,"y",function(){return K});var g,m,v,_=function(){return function(e,t){this.language=e,this.id=t}}(),b=function(){function e(){}return e.getLanguageId=function(e){return(255&e)>>>0},e.getTokenType=function(e){return(1792&e)>>>8},e.getFontStyle=function(e){return(14336&e)>>>11},e.getForeground=function(e){return(8372224&e)>>>14},e.getBackground=function(e){return(4286578688&e)>>>23},e.getClassNameFromMetadata=function(e){var t="mtk"+this.getForeground(e),n=this.getFontStyle(e);return 1&n&&(t+=" mtki"),2&n&&(t+=" mtkb"),4&n&&(t+=" mtku"),t},e.getInlineStyleFromMetadata=function(e,t){var n=this.getForeground(e),i=this.getFontStyle(e),r="color: "+t[n]+";";return 1&i&&(r+="font-style: italic;"),2&i&&(r+="font-weight: bold;"),4&i&&(r+="text-decoration: underline;"),r},e}(),y=((g=Object.create(null))[0]="method",g[1]="function",g[2]="constructor",g[3]="field",g[4]="variable",g[5]="class",g[6]="struct",g[7]="interface",g[8]="module",g[9]="property",g[10]="event",g[11]="operator",g[12]="unit",g[13]="value",g[14]="constant",g[15]="enum",g[16]="enum-member",g[17]="keyword",g[25]="snippet",g[18]="text",g[19]="color",g[20]="file",g[21]="reference",g[22]="customcolor",g[23]="folder",g[24]="type-parameter",function(e){return g[e]||"property"}),w=function(){var e=Object.create(null);return e.method=0,e.function=1,e.constructor=2,e.field=3,e.variable=4,e.class=5,e.struct=6,e.interface=7,e.module=8,e.property=9,e.event=10,e.operator=11,e.unit=12,e.value=13,e.constant=14,e.enum=15,e["enum-member"]=16,e.enumMember=16,e.keyword=17,e.snippet=25,e.text=18,e.color=19,e.file=20,e.reference=21,e.customcolor=22,e.folder=23,e["type-parameter"]=24,e.typeParameter=24,function(t,n){var i=e[t];return void 0!==i||n||(i=9),i}}();!function(e){e[e.Invoke=1]="Invoke",e[e.TriggerCharacter=2]="TriggerCharacter",e[e.ContentChange=3]="ContentChange"}(m||(m={})),function(e){e[e.Text=0]="Text",e[e.Read=1]="Read",e[e.Write=2]="Write"}(v||(v={}));var C,S=((C=Object.create(null))[0]="file",C[1]="module",C[2]="namespace",C[3]="package",C[4]="class",C[5]="method",C[6]="property",C[7]="field",C[8]="constructor",C[9]="enum",C[10]="interface",C[11]="function",C[12]="variable",C[13]="constant",C[14]="string",C[15]="number",C[16]="boolean",C[17]="array",C[18]="object",C[19]="key",C[20]="null",C[21]="enum-member",C[22]="struct",C[23]="event",C[24]="operator",C[25]="type-parameter",function(e,t){return"symbol-icon "+(t?"inline":"block")+" "+(C[e]||"property")}),x=function(){function e(e){this.value=e}return e.Comment=new e("comment"),e.Imports=new e("imports"),e.Region=new e("region"),e}();var L=new h,O=new h,k=new h,N=new h,E=new h,I=new h,D=new h,M=new h,T=new h,P=new h,A=new h,R=new h,F=new h,j=new h,W=new h,B=new h,V=new h,H=new h,z=new h,U=new h,K=new p},Pb27:function(e,t,n){"use strict";n.d(t,"b",function(){return b}),n.d(t,"a",function(){return y});var i=n("hK2W"),r=n("zxiH"),o=n("tqet"),s=n("vORD"),a=n("JVO/"),u=n("7g0X"),c=n("Gzpe"),l=n("Cfmk"),d=n("ni2T"),h=n("vTy2"),f=n("artP"),p=n("fAkY"),g=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},m=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},v=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},_=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0&&0===n.indexOf(":")){for(var g=null,m=null,v=0,_=0;_0)):v++}m&&m.setGroupLabel(this.typeToLabel(g||"",v))}else r.length>0&&r[0].setGroupLabel(s.r(I.e._symbols_,r.length));return r},t.prototype.typeToLabel=function(e,t){switch(e){case"module":return s.r(I.e._modules_,t);case"class":return s.r(I.e._class_,t);case"interface":return s.r(I.e._interface_,t);case"method":return s.r(I.e._method_,t);case"function":return s.r(I.e._function_,t);case"property":return s.r(I.e._property_,t);case"variable":return s.r(I.e._variable_,t);case"var":return s.r(I.e._variable2_,t);case"constructor":return s.r(I.e._constructor_,t);case"call":return s.r(I.e._call_,t)}return e},t.prototype.sortNormal=function(e,t,n){var i=t.getLabel().toLowerCase(),r=n.getLabel().toLowerCase(),o=i.localeCompare(r);if(0!==o)return o;var s=t.getRange(),a=n.getRange();return s.startLineNumber-a.startLineNumber},t.prototype.sortScoped=function(e,t,n){e=e.substr(":".length);var i=t.getType(),r=n.getType(),o=i.localeCompare(r);if(0!==o)return o;if(e){var s=t.getLabel().toLowerCase(),a=n.getLabel().toLowerCase(),u=s.localeCompare(a);if(0!==u)return u}var c=t.getRange(),l=n.getRange();return c.startLineNumber-l.startLineNumber},t}(E.a);Object(u.f)(T)},QfwU:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("UqCF"),o=n("odeJ"),s=n("uNfg"),a=n("ZfGv"),u=n("03Zz"),c=n("vORD"),l=n("vTy2"),d=n("/9db"),h=n("PCC9"),f=n("Cv8t"),p=n("fw2Z"),g=n("Pb27"),m=n("9uVW"),v=n("hK2W"),_=n("C3c5"),b=n("7g0X"),y=n("fAkY"),w=n("DBt1"),C=n("iLE3"),S=n("ItKl"),x=n("4tuZ"),L=n("JVO/"),O=n("8xpx"),k=n("Kx4b"),N=n("tqet"),E=n("Kp7x"),I=n("NqM+"),D=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),M=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},T=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},P=new b.d("hasSymbols",!1),A=Object(L.c)("ISymbolNavigationService"),R=function(){function e(e,t,n,i){this._editorService=t,this._notificationService=n,this._keybindingService=i,this._currentModel=void 0,this._currentIdx=-1,this._ignoreEditorChange=!1,this._ctxHasSymbols=P.bindTo(e)}return e.prototype.reset=function(){this._ctxHasSymbols.reset(),Object(N.f)(this._currentState),Object(N.f)(this._currentMessage),this._currentModel=void 0,this._currentIdx=-1},e.prototype.put=function(e){var t=this,n=e.parent.parent;if(n.references.length<=1)this.reset();else{this._currentModel=n,this._currentIdx=n.references.indexOf(e),this._ctxHasSymbols.set(!0),this._showMessage();var i=new F(this._editorService),r=i.onDidChange(function(e){if(!t._ignoreEditorChange){var i=t._editorService.getActiveCodeEditor();if(i){var r=i.getModel(),o=i.getPosition();if(r&&o){for(var s=!1,a=!1,u=0,c=n.references;u0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]1?v.a("meta.title"," – {0} definitions",e.references.length):""},t.prototype._onResult=function(e,t,n,i){return W(this,void 0,void 0,function(){var o,s,a,u;return B(this,function(c){switch(c.label){case 0:return o=i.getAriaMessage(),Object(r.a)(o),s=n.getConfiguration().contribInfo.gotoLocation,this._configuration.openInPeek||"peek"===s.multiple&&i.references.length>1?(this._openInPeek(e,n,i),[3,3]):[3,1];case 1:return n.hasModel()?(a=i.firstReference())?[4,this._openReference(n,e,a,this._configuration.openToSide)]:[2]:[3,3];case 2:(u=c.sent())&&i.references.length>1&&"gotoAndPeek"===s.multiple?this._openInPeek(e,u,i):i.dispose(),"goto"===s.multiple&&t.put(a),c.label=3;case 3:return[2]}})})},t.prototype._openReference=function(e,t,n,i){var r=void 0;return Object(h.C)(n)&&(r=n.targetSelectionRange),r||(r=n.range),t.openCodeEditor({resource:n.uri,options:{selection:l.a.collapseToStart(r),revealInCenterIfOutsideViewport:!0}},e,i)},t.prototype._openInPeek=function(e,t,n){var i=this,r=g.a.get(t);r&&t.hasModel()?r.toggleWidget(t.getSelection(),Object(o.f)(function(e){return Promise.resolve(n)}),{getMetaTitle:function(e){return i._getMetaTitle(e)},onGoto:function(n){return r.closeWidget(),i._openReference(t,e,n,!1)}}):n.dispose()},t}(u.b),z=a.f?2118:70,U=function(e){function t(){var n=e.call(this,new V,{id:t.id,label:v.a("actions.goToDecl.label","Go to Definition"),alias:"Go to Definition",precondition:b.a.and(d.a.hasDefinitionProvider,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:z,weight:100},menuOpts:{group:"navigation",order:1.1}})||this;return S.a.registerCommandAlias("editor.action.goToDeclaration",t.id),n}return j(t,e),t.id="editor.action.revealDefinition",t}(H),K=function(e){function t(){var n=e.call(this,new V(!0),{id:t.id,label:v.a("actions.goToDeclToSide.label","Open Definition to the Side"),alias:"Open Definition to the Side",precondition:b.a.and(d.a.hasDefinitionProvider,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:Object(s.a)(2089,z),weight:100}})||this;return S.a.registerCommandAlias("editor.action.openDeclarationToTheSide",t.id),n}return j(t,e),t.id="editor.action.revealDefinitionAside",t}(H),q=function(e){function t(){var n=e.call(this,new V(void 0,!0,!1),{id:t.id,label:v.a("actions.previewDecl.label","Peek Definition"),alias:"Peek Definition",precondition:b.a.and(d.a.hasDefinitionProvider,p.b.notInPeekEditor,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:582,linux:{primary:3140},weight:100},menuOpts:{group:"navigation",order:1.2}})||this;return S.a.registerCommandAlias("editor.action.previewDeclaration",t.id),n}return j(t,e),t.id="editor.action.peekDefinition",t}(H),G=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return j(t,e),t.prototype._getTargetLocationForPosition=function(e,t,n){return Object(C.a)(e,t,n)},t.prototype._getNoResultFoundMessage=function(e){return e&&e.word?v.a("decl.noResultWord","No declaration found for '{0}'",e.word):v.a("decl.generic.noResults","No declaration found")},t.prototype._getMetaTitle=function(e){return e.references.length>1?v.a("decl.meta.title"," – {0} declarations",e.references.length):""},t}(H),Z=function(e){function t(){return e.call(this,new V,{id:t.id,label:v.a("actions.goToDeclaration.label","Go to Declaration"),alias:"Go to Declaration",precondition:b.a.and(d.a.hasDeclarationProvider,d.a.isInEmbeddedEditor.toNegated()),menuOpts:{group:"navigation",order:1.3}})||this}return j(t,e),t.prototype._getNoResultFoundMessage=function(e){return e&&e.word?v.a("decl.noResultWord","No declaration found for '{0}'",e.word):v.a("decl.generic.noResults","No declaration found")},t.prototype._getMetaTitle=function(e){return e.references.length>1?v.a("decl.meta.title"," – {0} declarations",e.references.length):""},t.id="editor.action.revealDeclaration",t}(G),Y=function(e){function t(){return e.call(this,new V(void 0,!0,!1),{id:"editor.action.peekDeclaration",label:v.a("actions.peekDecl.label","Peek Declaration"),alias:"Peek Declaration",precondition:b.a.and(d.a.hasDeclarationProvider,p.b.notInPeekEditor,d.a.isInEmbeddedEditor.toNegated()),menuOpts:{group:"navigation",order:1.31}})||this}return j(t,e),t}(G),X=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return j(t,e),t.prototype._getTargetLocationForPosition=function(e,t,n){return Object(C.c)(e,t,n)},t.prototype._getNoResultFoundMessage=function(e){return e&&e.word?v.a("goToImplementation.noResultWord","No implementation found for '{0}'",e.word):v.a("goToImplementation.generic.noResults","No implementation found")},t.prototype._getMetaTitle=function(e){return e.references.length>1?v.a("meta.implementations.title"," – {0} implementations",e.references.length):""},t}(H),$=function(e){function t(){return e.call(this,new V,{id:t.ID,label:v.a("actions.goToImplementation.label","Go to Implementation"),alias:"Go to Implementation",precondition:b.a.and(d.a.hasImplementationProvider,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:2118,weight:100}})||this}return j(t,e),t.ID="editor.action.goToImplementation",t}(X),J=function(e){function t(){return e.call(this,new V(!1,!0,!1),{id:t.ID,label:v.a("actions.peekImplementation.label","Peek Implementation"),alias:"Peek Implementation",precondition:b.a.and(d.a.hasImplementationProvider,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:3142,weight:100}})||this}return j(t,e),t.ID="editor.action.peekImplementation",t}(X),Q=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return j(t,e),t.prototype._getTargetLocationForPosition=function(e,t,n){return Object(C.d)(e,t,n)},t.prototype._getNoResultFoundMessage=function(e){return e&&e.word?v.a("goToTypeDefinition.noResultWord","No type definition found for '{0}'",e.word):v.a("goToTypeDefinition.generic.noResults","No type definition found")},t.prototype._getMetaTitle=function(e){return e.references.length>1?v.a("meta.typeDefinitions.title"," – {0} type definitions",e.references.length):""},t}(H),ee=function(e){function t(){return e.call(this,new V,{id:t.ID,label:v.a("actions.goToTypeDefinition.label","Go to Type Definition"),alias:"Go to Type Definition",precondition:b.a.and(d.a.hasTypeDefinitionProvider,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:0,weight:100},menuOpts:{group:"navigation",order:1.4}})||this}return j(t,e),t.ID="editor.action.goToTypeDefinition",t}(Q),te=function(e){function t(){return e.call(this,new V(!1,!0,!1),{id:t.ID,label:v.a("actions.peekTypeDefinition.label","Peek Type Definition"),alias:"Peek Type Definition",precondition:b.a.and(d.a.hasTypeDefinitionProvider,d.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:d.a.editorTextFocus,primary:0,weight:100}})||this}return j(t,e),t.ID="editor.action.peekTypeDefinition",t}(Q);Object(u.f)(U),Object(u.f)(K),Object(u.f)(q),Object(u.f)(Z),Object(u.f)(Y),Object(u.f)($),Object(u.f)(J),Object(u.f)(ee),Object(u.f)(te),_.c.appendMenuItem(16,{group:"4_symbol_nav",command:{id:"editor.action.goToDeclaration",title:v.a({key:"miGotoDefinition",comment:["&& denotes a mnemonic"]},"Go to &&Definition")},order:2}),_.c.appendMenuItem(16,{group:"4_symbol_nav",command:{id:"editor.action.goToTypeDefinition",title:v.a({key:"miGotoTypeDefinition",comment:["&& denotes a mnemonic"]},"Go to &&Type Definition")},order:3}),_.c.appendMenuItem(16,{group:"4_symbol_nav",command:{id:"editor.action.goToImplementation",title:v.a({key:"miGotoImplementation",comment:["&& denotes a mnemonic"]},"Go to &&Implementation")},order:4})},QgSF:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("hK2W"),r=n("uNfg"),o=n("HZsc"),s=n("03Zz"),a=n("Ao9X"),u=n("aL7J"),c=n("0WPX"),l=n("vTy2"),d=function(){function e(e,t){this._selection=e,this._cursors=t,this._selectionId=null}return e.prototype.getEditOperations=function(e,t){for(var n=function(e,t){t.sort(function(e,t){return e.lineNumber===t.lineNumber?e.column-t.column:e.lineNumber-t.lineNumber});for(var n=t.length-2;n>=0;n--)t[n].lineNumber===t[n+1].lineNumber&&t.splice(n,1);for(var i=[],r=0,o=0,s=t.length,a=1,d=e.getLineCount();a<=d;a++){var h=e.getLineContent(a),f=h.length+1,p=0;if(!(o=i.startLineNumber+1&&t<=i.endLineNumber+1?e.getLineContent(t-1):e.getLineContent(t)};var L=b.a.getGoodIndentForLine(d,e.getLanguageIdAtPosition(g,1),i.startLineNumber+1,c);if(null!==L){x=u.s(e.getLineContent(i.startLineNumber));if((E=y(L,o))!==(I=y(x,o))){var O=E-I;this.getIndentEditsOfMovingBlock(e,t,i,o,a,O)}}}}else t.addEditOperation(new l.a(i.startLineNumber,1,i.startLineNumber,1),v+"\n")}else{var k;if(g=i.startLineNumber-1,m=e.getLineContent(g),t.addEditOperation(new l.a(g,1,g+1,1),null),t.addEditOperation(new l.a(i.endLineNumber,e.getLineMaxColumn(i.endLineNumber),i.endLineNumber,e.getLineMaxColumn(i.endLineNumber)),"\n"+m),this.shouldAutoIndent(e,i))if(d.getLineContent=function(t){return t===g?e.getLineContent(i.startLineNumber):e.getLineContent(t)},null!==(k=this.matchEnterRule(e,c,o,i.startLineNumber,i.startLineNumber-2)))0!==k&&this.getIndentEditsOfMovingBlock(e,t,i,o,a,k);else{var N=b.a.getGoodIndentForLine(d,e.getLanguageIdAtPosition(i.startLineNumber,1),g,c);if(null!==N){var E,I,D=u.s(e.getLineContent(i.startLineNumber));if((E=y(N,o))!==(I=y(D,o))){O=E-I;this.getIndentEditsOfMovingBlock(e,t,i,o,a,O)}}}}}this._selectionId=t.trackSelection(i)}else this._selectionId=t.trackSelection(this._selection)},e.prototype.buildIndentConverter=function(e,t,n){return{shiftIndent:function(i){return v.a.shiftIndent(i,i.length+1,e,t,n)},unshiftIndent:function(i){return v.a.unshiftIndent(i,i.length+1,e,t,n)}}},e.prototype.matchEnterRule=function(e,t,n,i,r,o){for(var s=r;s>=1;){var a=void 0;if(a=s===r&&void 0!==o?o:e.getLineContent(s),u.A(a)>=0)break;s--}if(s<1||i>e.getLineCount())return null;var c=e.getLineMaxColumn(s),d=b.a.getEnterAction(e,new l.a(s,c,s,c));if(d){var h=d.indentation,f=d.enterAction;f.indentAction===_.a.None?h=d.indentation+f.appendText:f.indentAction===_.a.Indent?h=d.indentation+f.appendText:f.indentAction===_.a.IndentOutdent?h=d.indentation:f.indentAction===_.a.Outdent&&(h=t.unshiftIndent(d.indentation)+f.appendText);var p=e.getLineContent(i);if(this.trimLeft(p).indexOf(this.trimLeft(h))>=0){var g=u.s(e.getLineContent(i)),m=u.s(h),v=b.a.getIndentMetadata(e,i);return null!==v&&2&v&&(m=t.unshiftIndent(m)),y(m,n)-y(g,n)}}return null},e.prototype.trimLeft=function(e){return e.replace(/^\s+/,"")},e.prototype.shouldAutoIndent=function(e,t){if(!this._autoIndent)return!1;if(!e.isCheapToTokenize(t.startLineNumber))return!1;var n=e.getLanguageIdAtPosition(t.startLineNumber,1);return n===e.getLanguageIdAtPosition(t.endLineNumber,1)&&null!==b.a.getIndentRulesSupport(n)},e.prototype.getIndentEditsOfMovingBlock=function(e,t,n,i,r,o){for(var s=n.startLineNumber;s<=n.endLineNumber;s++){var a=e.getLineContent(s),c=u.s(a),d=w(y(c,i)+o,i,r);d!==c&&(t.addEditOperation(new l.a(s,1,s,c.length+1),d),s===n.endLineNumber&&n.endColumn<=c.length+1&&""===d&&(this._moveEndLineSelectionShrink=!0))}},e.prototype.computeCursorState=function(e,t){var n=t.getTrackedSelection(this._selectionId);return this._moveEndPositionDown&&(n=n.setEndPosition(n.endLineNumber+1,1)),this._moveEndLineSelectionShrink&&n.startLineNumber=r)return null;for(var o=[],s=i;s<=r;s++)o.push(e.getLineContent(s));var a=o.slice(0);return a.sort(function(e,t){return e.toLowerCase().localeCompare(t.toLowerCase())}),!0===n&&(a=a.reverse()),{startLineNumber:i,endLineNumber:r,before:o,after:a}}n.d(t,"AbstractSortLinesAction",function(){return T}),n.d(t,"SortLinesAscendingAction",function(){return P}),n.d(t,"SortLinesDescendingAction",function(){return A}),n.d(t,"TrimTrailingWhitespaceAction",function(){return R}),n.d(t,"DeleteLinesAction",function(){return F}),n.d(t,"IndentLinesAction",function(){return j}),n.d(t,"InsertLineBeforeAction",function(){return B}),n.d(t,"InsertLineAfterAction",function(){return V}),n.d(t,"AbstractDeleteAllToBoundaryAction",function(){return H}),n.d(t,"DeleteAllLeftAction",function(){return z}),n.d(t,"DeleteAllRightAction",function(){return U}),n.d(t,"JoinLinesAction",function(){return K}),n.d(t,"TransposeAction",function(){return q}),n.d(t,"AbstractCaseAction",function(){return G}),n.d(t,"UpperCaseAction",function(){return Z}),n.d(t,"LowerCaseAction",function(){return Y}),n.d(t,"TitleCaseAction",function(){return X});var L,O=this&&this.__extends||(L=function(e,t){return(L=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}L(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),k=function(e){function t(t,n){var i=e.call(this,n)||this;return i.down=t,i}return O(t,e),t.prototype.run=function(e,t){for(var n=[],i=0,r=t.getSelections()||[];i1&&(d-=1,f=i.getLineMaxColumn(d)),o.push(c.a.replace(new p.a(d,f,h,g),"")),s.push(new p.a(d-r,l.positionColumn,d-r,l.positionColumn)),r+=l.endLineNumber-l.startLineNumber+1}t.pushUndoStop(),t.executeEdits(this.id,o,s),t.pushUndoStop()}}},t.prototype._getLinesToRemove=function(e){var t=e.getSelections().map(function(e){var t=e.endLineNumber;return e.startLineNumber=t[r].startLineNumber?i.endLineNumber=t[r].endLineNumber:(n.push(i),i=t[r]);return n.push(i),n},t}(s.b),j=function(e){function t(){return e.call(this,{id:"editor.action.indentLines",label:i.a("lines.indent","Indent Line"),alias:"Indent Line",precondition:g.a.writable,kbOpts:{kbExpr:g.a.editorTextFocus,primary:2137,weight:100}})||this}return O(t,e),t.prototype.run=function(e,t){var n=t._getCursors();n&&(t.pushUndoStop(),t.executeCommands(this.id,h.a.indent(n.context.config,t.getModel(),t.getSelections())),t.pushUndoStop())},t}(s.b),W=function(e){function t(){return e.call(this,{id:"editor.action.outdentLines",label:i.a("lines.outdent","Outdent Line"),alias:"Outdent Line",precondition:g.a.writable,kbOpts:{kbExpr:g.a.editorTextFocus,primary:2135,weight:100}})||this}return O(t,e),t.prototype.run=function(e,t){o.CoreEditingCommands.Outdent.runEditorCommand(e,t,null)},t}(s.b),B=function(e){function t(){return e.call(this,{id:"editor.action.insertLineBefore",label:i.a("lines.insertBefore","Insert Line Above"),alias:"Insert Line Above",precondition:g.a.writable,kbOpts:{kbExpr:g.a.editorTextFocus,primary:3075,weight:100}})||this}return O(t,e),t.prototype.run=function(e,t){var n=t._getCursors();n&&(t.pushUndoStop(),t.executeCommands(this.id,h.a.lineInsertBefore(n.context.config,t.getModel(),t.getSelections())))},t}(s.b),V=function(e){function t(){return e.call(this,{id:"editor.action.insertLineAfter",label:i.a("lines.insertAfter","Insert Line Below"),alias:"Insert Line Below",precondition:g.a.writable,kbOpts:{kbExpr:g.a.editorTextFocus,primary:2051,weight:100}})||this}return O(t,e),t.prototype.run=function(e,t){var n=t._getCursors();n&&(t.pushUndoStop(),t.executeCommands(this.id,h.a.lineInsertAfter(n.context.config,t.getModel(),t.getSelections())))},t}(s.b),H=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return O(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getSelection(),i=this._getRangesToDelete(t),r=[],o=0,s=i.length-1;o0){var s=t.startLineNumber-r;o=new p.a(s,t.startColumn,s,t.startColumn)}else o=new p.a(t.startLineNumber,t.startColumn,t.startLineNumber,t.startColumn);r+=t.endLineNumber-t.startLineNumber,t.intersectRanges(e)?n=o:i.push(o)}),n&&i.unshift(n),i},t.prototype._getRangesToDelete=function(e){var t=e.getSelections();if(null===t)return[];var n=t,i=e.getModel();return null===i?[]:(n.sort(l.a.compareRangesUsingStarts),n=n.map(function(e){if(e.isEmpty()){if(1===e.startColumn){var t=Math.max(1,e.startLineNumber-1),n=1===e.startLineNumber?1:i.getLineContent(t).length+1;return new l.a(t,n,e.startLineNumber,1)}return new l.a(e.startLineNumber,1,e.startLineNumber,e.startColumn)}return new l.a(e.startLineNumber,1,e.endLineNumber,e.endColumn)}))},t}(H),U=function(e){function t(){return e.call(this,{id:"deleteAllRight",label:i.a("lines.deleteAllRight","Delete All Right"),alias:"Delete All Right",precondition:g.a.writable,kbOpts:{kbExpr:g.a.textInputFocus,primary:0,mac:{primary:297,secondary:[2068]},weight:100}})||this}return O(t,e),t.prototype._getEndCursorState=function(e,t){for(var n=null,i=[],r=0,o=t.length;re.endLineNumber+1?(r.push(e),t):new p.a(e.startLineNumber,e.startColumn,t.endLineNumber,t.endColumn):t.startLineNumber>e.endLineNumber?(r.push(e),t):new p.a(e.startLineNumber,e.startColumn,t.endLineNumber,t.endColumn)});r.push(o);var s=t.getModel();if(null!==s){for(var a=[],u=[],d=i,h=0,f=0,g=r.length;f=1){var k=!0;""===S&&(k=!1),!k||" "!==S.charAt(S.length-1)&&"\t"!==S.charAt(S.length-1)||(k=!1,S=S.replace(/[\s\uFEFF\xA0]+$/g," "));var N=L.substr(O-1);S+=(k?" ":"")+N,_=k?N.length+1:N.length}else _=0}var E=new l.a(v,1,b,y);if(!E.isEmpty()){var I=void 0;m.isEmpty()?(a.push(c.a.replace(E,S)),I=new p.a(E.startLineNumber-h,S.length-_+1,v-h,S.length-_+1)):m.startLineNumber===m.endLineNumber?(a.push(c.a.replace(E,S)),I=new p.a(m.startLineNumber-h,m.startColumn,m.endLineNumber-h,m.endColumn)):(a.push(c.a.replace(E,S)),I=new p.a(m.startLineNumber-h,m.startColumn,m.startLineNumber-h,S.length-w)),null!==l.a.intersectRanges(E,i)?d=I:u.push(I)}h+=E.endLineNumber-E.startLineNumber}u.unshift(d),t.pushUndoStop(),t.executeEdits(this.id,a,u),t.pushUndoStop()}}}},t}(s.b),q=function(e){function t(){return e.call(this,{id:"editor.action.transpose",label:i.a("editor.transpose","Transpose characters around the cursor"),alias:"Transpose characters around the cursor",precondition:g.a.writable})||this}return O(t,e),t.prototype.run=function(e,t){var n=t.getSelections();if(null!==n){var i=t.getModel();if(null!==i){for(var r=[],o=0,s=n.length;o=d){if(c.lineNumber===i.getLineCount())continue;var h=new l.a(c.lineNumber,Math.max(1,c.column-1),c.lineNumber+1,1),f=i.getValueInRange(h).split("").reverse().join("");r.push(new a.a(new p.a(c.lineNumber,Math.max(1,c.column-1),c.lineNumber+1,1),f))}else{h=new l.a(c.lineNumber,Math.max(1,c.column-1),c.lineNumber,c.column+1),f=i.getValueInRange(h).split("").reverse().join("");r.push(new a.b(h,f,new p.a(c.lineNumber,c.column+1,c.lineNumber,c.column+1)))}}}t.pushUndoStop(),t.executeCommands(this.id,r),t.pushUndoStop()}}},t}(s.b),G=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return O(t,e),t.prototype.run=function(e,t){var n=t.getSelections();if(null!==n){var i=t.getModel();if(null!==i){for(var r=t.getConfiguration().wordSeparators,o=[],s=0,u=n.length;s=0?(r=!0,i+=s):r?(r=!1,i+=s.toLocaleUpperCase()):i+=s.toLocaleLowerCase()}return i},t}(G);Object(s.f)(N),Object(s.f)(E),Object(s.f)(D),Object(s.f)(M),Object(s.f)(P),Object(s.f)(A),Object(s.f)(R),Object(s.f)(F),Object(s.f)(j),Object(s.f)(W),Object(s.f)(B),Object(s.f)(V),Object(s.f)(z),Object(s.f)(U),Object(s.f)(K),Object(s.f)(q),Object(s.f)(Z),Object(s.f)(Y),Object(s.f)(X)},Qv71:function(e,t,n){"use strict";n.d(t,"a",function(){return i});var i=function(){return function(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=!1),this.ctor=e,this.staticArguments=t,this.supportsDelayedInstantiation=n}}()},Qxje:function(e,t,n){"use strict";n.d(t,"b",function(){return a}),n.d(t,"c",function(){return u}),n.d(t,"a",function(){return c}),t.d=d,t.e=function(e){var t=Object(r.a)(1e4),n=d(e,t);return new h(n.characterMapping,t.build(),n.containsRTL,n.containsForeignElements)};var i=n("aL7J"),r=n("ftXN"),o=n("t7eM"),s=function(){return function(e,t){this.endIndex=e,this.type=t}}(),a=function(){function e(e,t){this.startOffset=e,this.endOffset=t}return e.prototype.equals=function(e){return this.startOffset===e.startOffset&&this.endOffset===e.endOffset},e}(),u=function(){function e(e,t,n,i,r,o,s,a,u,c,l,d,h,f,p,g){this.useMonospaceOptimizations=e,this.canUseHalfwidthRightwardsArrow=t,this.lineContent=n,this.continuesWithWrappedLine=i,this.isBasicASCII=r,this.containsRTL=o,this.fauxIndentLength=s,this.lineTokens=a,this.lineDecorations=u,this.tabSize=c,this.spaceWidth=l,this.stopRenderingLineAfter=d,this.renderWhitespace="all"===h?3:"boundary"===h?1:"selection"===h?2:0,this.renderControlCharacters=f,this.fontLigatures=p,this.selectionsOnLine=g&&g.sort(function(e,t){return e.startOffset>>16},e.getCharIndex=function(e){return(65535&e)>>>0},e.prototype.setPartData=function(e,t,n,i){var r=(t<<16|n<<0)>>>0;this._data[e]=r,this._absoluteOffsets[e]=i+n},e.prototype.getAbsoluteOffsets=function(){return this._absoluteOffsets},e.prototype.charOffsetToPartData=function(e){return 0===this.length?0:e<0?this._data[0]:e>=this.length?this._data[this.length-1]:this._data[e]},e.prototype.partDataToCharOffset=function(t,n,i){if(0===this.length)return 0;for(var r=(t<<16|i<<0)>>>0,o=0,s=this.length-1;o+1>>1,u=this._data[a];if(u===r)return a;u>r?s=a:o=a}if(o===s)return o;var c=this._data[o],l=this._data[s];if(c===r)return o;if(l===r)return s;var d=e.getPartIndex(c);return i-e.getCharIndex(c)<=(d!==e.getPartIndex(l)?n:e.getCharIndex(l))-i?o:s},e}(),l=function(){return function(e,t,n){this.characterMapping=e,this.containsRTL=t,this.containsForeignElements=n}}();function d(e,t){if(0===e.lineContent.length){var n=0,r=" ";if(e.lineDecorations.length>0){for(var a=[],u=0,d=e.lineDecorations.length;u')}return t.appendASCIIString(r),new l(new c(0,0),!1,n)}return function(e,t){var n=e.fontIsMonospace,r=e.canUseHalfwidthRightwardsArrow,o=e.containsForeignElements,s=e.lineContent,a=e.len,u=e.isOverflowing,d=e.parts,h=e.tabSize,f=e.containsRTL,p=e.spaceWidth,g=e.renderWhitespace,m=e.renderControlCharacters,v=new c(a+1,d.length),_=0,b=0,y=0,w=0,C=0;t.appendASCIIString("");for(var S=0,x=d.length;S=0;if(y=0,t.appendASCIIString('0&&(!r||T>1?t.write1(8594):t.write1(65515),T--);T>0;)t.write1(160),T--}else t.write1(183);y++}w=E}else{var E=0;for(f&&t.appendASCIIString(' dir="ltr"'),t.appendASCII(62);_0;)t.write1(160),E++,T--;break;case 32:t.write1(160),E++;break;case 60:t.appendASCIIString("<"),E++;break;case 62:t.appendASCIIString(">"),E++;break;case 38:t.appendASCIIString("&"),E++;break;case 0:t.appendASCIIString("�"),E++;break;case 65279:case 8232:t.write1(65533),E++;break;default:i.v(M)&&b++,m&&M<32?(t.write1(9216+M),E++):(t.write1(M),E++)}y++}w=E}t.appendASCIIString("")}v.setPartData(a,d.length-1,y,C),u&&t.appendASCIIString("");return t.appendASCIIString(""),new l(v,f,o)}(function(e){var t,n,r=e.useMonospaceOptimizations,a=e.lineContent;-1!==e.stopRenderingLineAfter&&e.stopRenderingLineAfter0&&(i[r++]=new s(t,""));for(var o=0,a=e.getCount();o=n){i[r++]=new s(n,c);break}i[r++]=new s(u,c)}}return i}(e.lineTokens,e.fauxIndentLength,n);(3===e.renderWhitespace||1===e.renderWhitespace||2===e.renderWhitespace&&e.selectionsOnLine)&&(u=function(e,t,n,r,o,a,u,c,l){var d,h=[],f=0,p=0,g=r[p].type,m=r[p].endIndex,v=r.length,_=i.q(e);-1===_?(_=t,d=t):d=i.A(e);for(var b=0,y=0;y=x.endOffset&&(S++,x=c&&c[S]);var L=void 0;if(y<_||y>d)L=!0;else if(9===w)L=!0;else if(32===w)if(l)if(C)L=!0;else{var O=y+1y),C?(!L||!u&&b>=a)&&(h[f++]=new s(y,"vs-whitespace"),b%=a):(y===m||L&&y>o)&&(h[f++]=new s(y,g),b%=a),9===w?b=a:i.v(w)?b+=2:b++,C=L,y===m&&++p0?e.charCodeAt(t-1):0,E=t>1?e.charCodeAt(t-2):0,I=32===N&&32!==E&&9!==E;I||(k=!0)}else k=!0;return h[f++]=new s(t,k?"vs-whitespace":g),h}(a,n,e.continuesWithWrappedLine,u,e.fauxIndentLength,e.tabSize,r,e.selectionsOnLine,1===e.renderWhitespace));var c=0;if(e.lineDecorations.length>0){for(var l=0,d=e.lineDecorations.length;ld&&(d=v.startOffset,c[l++]=new s(d,m)),!(v.endOffset+1<=g)){d=g,c[l++]=new s(d,m+" "+v.className);break}d=v.endOffset+1,c[l++]=new s(d,m+" "+v.className),u++}g>d&&(d=g,c[l++]=new s(d,m))}var _=n[n.length-1].endIndex;if(u=50&&(r[o++]=new s(h+1,d),f=h+1,h=-1);f!==l&&(r[o++]=new s(l,d))}else r[o++]=c;i=l}else for(var a=0,u=t.length;a50){for(var d=c.type,m=Math.ceil(g/50),p=1;p0;n--){var o=e.charCodeAt(n-1);if(47===o||92===o)break}t=e.substr(n)}var s=r.indexOf(t);return-1!==s?i[s]:null};a.basenames=r,a.patterns=i,a.allBasenames=r;var u=e.filter(function(e){return!e.basenames});return u.push(a),u}},Rfe2:function(e,t,n){"use strict";n.d(t,"i",function(){return a}),n.d(t,"j",function(){return u}),n.d(t,"g",function(){return d}),n.d(t,"f",function(){return h}),n.d(t,"h",function(){return p}),n.d(t,"a",function(){return g}),n.d(t,"k",function(){return m}),n.d(t,"b",function(){return _}),n.d(t,"m",function(){return b}),n.d(t,"e",function(){return y}),n.d(t,"c",function(){return w}),n.d(t,"d",function(){return C}),n.d(t,"l",function(){return S}),n.d(t,"n",function(){return L}),n.d(t,"o",function(){return O}),n.d(t,"p",function(){return k}),n.d(t,"r",function(){return N}),n.d(t,"q",function(){return E});var i=n("hK2W"),r=n("TNPA"),o=n("L5KM"),s=n("eoic"),a=Object(o._36)("editor.lineHighlightBackground",{dark:null,light:null,hc:null},i.a("lineHighlight","Background color for the highlight of line at the cursor position.")),u=Object(o._36)("editor.lineHighlightBorder",{dark:"#282828",light:"#eeeeee",hc:"#f38518"},i.a("lineHighlightBorderBox","Background color for the border around the line at the cursor position.")),c=Object(o._36)("editor.rangeHighlightBackground",{dark:"#ffffff0b",light:"#fdff0033",hc:null},i.a("rangeHighlight","Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations."),!0),l=Object(o._36)("editor.rangeHighlightBorder",{dark:null,light:null,hc:o.b},i.a("rangeHighlightBorder","Background color of the border around highlighted ranges."),!0),d=Object(o._36)("editorCursor.foreground",{dark:"#AEAFAD",light:r.a.black,hc:r.a.white},i.a("caret","Color of the editor cursor.")),h=Object(o._36)("editorCursor.background",null,i.a("editorCursorBackground","The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.")),f=Object(o._36)("editorWhitespace.foreground",{dark:"#e3e4e229",light:"#33333333",hc:"#e3e4e229"},i.a("editorWhitespaces","Color of whitespace characters in the editor.")),p=Object(o._36)("editorIndentGuide.background",{dark:f,light:f,hc:f},i.a("editorIndentGuides","Color of the editor indentation guides.")),g=Object(o._36)("editorIndentGuide.activeBackground",{dark:f,light:f,hc:f},i.a("editorActiveIndentGuide","Color of the active editor indentation guides.")),m=Object(o._36)("editorLineNumber.foreground",{dark:"#858585",light:"#237893",hc:r.a.white},i.a("editorLineNumbers","Color of editor line numbers.")),v=Object(o._36)("editorActiveLineNumber.foreground",{dark:"#c6c6c6",light:"#0B216F",hc:o.b},i.a("editorActiveLineNumber","Color of editor active line number"),!1,i.a("deprecatedEditorActiveLineNumber","Id is deprecated. Use 'editorLineNumber.activeForeground' instead.")),_=Object(o._36)("editorLineNumber.activeForeground",{dark:v,light:v,hc:v},i.a("editorActiveLineNumber","Color of editor active line number")),b=Object(o._36)("editorRuler.foreground",{dark:"#5A5A5A",light:r.a.lightgrey,hc:r.a.white},i.a("editorRuler","Color of the editor rulers.")),y=Object(o._36)("editorCodeLens.foreground",{dark:"#999999",light:"#999999",hc:"#999999"},i.a("editorCodeLensForeground","Foreground color of editor code lenses")),w=Object(o._36)("editorBracketMatch.background",{dark:"#0064001a",light:"#0064001a",hc:"#0064001a"},i.a("editorBracketMatchBackground","Background color behind matching brackets")),C=Object(o._36)("editorBracketMatch.border",{dark:"#888",light:"#B9B9B9",hc:o.e},i.a("editorBracketMatchBorder","Color for matching brackets boxes")),S=Object(o._36)("editorOverviewRuler.border",{dark:"#7f7f7f4d",light:"#7f7f7f4d",hc:"#7f7f7f4d"},i.a("editorOverviewRulerBorder","Color of the overview ruler border.")),x=Object(o._36)("editorGutter.background",{dark:o.o,light:o.o,hc:o.o},i.a("editorGutter","Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.")),L=Object(o._36)("editorUnnecessaryCode.border",{dark:null,light:null,hc:r.a.fromHex("#fff").transparent(.8)},i.a("unnecessaryCodeBorder","Border color of unnecessary (unused) source code in the editor.")),O=Object(o._36)("editorUnnecessaryCode.opacity",{dark:r.a.fromHex("#000a"),light:r.a.fromHex("#0007"),hc:null},i.a("unnecessaryCodeOpacity","Opacity of unnecessary (unused) source code in the editor. For example, \"#000000c0\" will render the code with 75% opacity. For high contrast themes, use the 'editorUnnecessaryCode.border' theme color to underline unnecessary code instead of fading it out.")),k=Object(o._36)("editorOverviewRuler.errorForeground",{dark:new r.a(new r.c(255,18,18,.7)),light:new r.a(new r.c(255,18,18,.7)),hc:new r.a(new r.c(255,50,50,1))},i.a("overviewRuleError","Overview ruler marker color for errors.")),N=Object(o._36)("editorOverviewRuler.warningForeground",{dark:o.M,light:o.M,hc:o.L},i.a("overviewRuleWarning","Overview ruler marker color for warnings.")),E=Object(o._36)("editorOverviewRuler.infoForeground",{dark:o.G,light:o.G,hc:o.F},i.a("overviewRuleInfo","Overview ruler marker color for infos."));Object(s.f)(function(e,t){var n=e.getColor(o.o);n&&t.addRule(".monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input { background-color: "+n+"; }");var i=e.getColor(o.x);i&&t.addRule(".monaco-editor, .monaco-editor .inputarea.ime-input { color: "+i+"; }");var r=e.getColor(x);r&&t.addRule(".monaco-editor .margin { background-color: "+r+"; }");var s=e.getColor(c);s&&t.addRule(".monaco-editor .rangeHighlight { background-color: "+s+"; }");var a=e.getColor(l);a&&t.addRule(".monaco-editor .rangeHighlight { border: 1px "+("hc"===e.type?"dotted":"solid")+" "+a+"; }");var u=e.getColor(f);u&&t.addRule(".vs-whitespace { color: "+u+" !important; }")})},Rt1F:function(e,t,n){"use strict";(function(t,i){var r=n("ypnx");e.exports=b;var o,s=n("sOR5");b.ReadableState=_;n("vzCy").EventEmitter;var a=function(e,t){return e.listeners(t).length},u=n("UcPO"),c=n("kkc6").Buffer,l=t.Uint8Array||function(){};var d=n("jOgh");d.inherits=n("LC74");var h=n(1),f=void 0;f=h&&h.debuglog?h.debuglog("stream"):function(){};var p,g=n("+HRN"),m=n("x0Ha");d.inherits(b,u);var v=["error","close","destroy","pause","resume"];function _(e,t){o=o||n("DsFX"),e=e||{};var i=t instanceof o;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,s=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new g,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(p||(p=n("X4X3").StringDecoder),this.decoder=new p(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n("DsFX"),!(this instanceof b))return new b(e);this._readableState=new _(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),u.call(this)}function y(e,t,n,i,r){var o,s=e._readableState;null===t?(s.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,x(e)}(e,s)):(r||(o=function(e,t){var n;i=t,c.isBuffer(i)||i instanceof l||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var i;return n}(s,t)),o?e.emit("error",o):s.objectMode||t&&t.length>0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),i?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):w(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?w(e,s,t,!1):O(e,s)):w(e,s,t,!1))):i||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=C?e=C:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(f("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r.nextTick(L,e):L(e))}function L(e){f("emit readable"),e.emit("readable"),I(e)}function O(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(k,e,t))}function k(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var i;eo.length?o.length:e;if(s===o.length?r+=o:r+=o.slice(0,e),0===(e-=s)){s===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(s));break}++i}return t.length-=i,r}(e,t):function(e,t){var n=c.allocUnsafe(e),i=t.head,r=1;i.data.copy(n),e-=i.data.length;for(;i=i.next;){var o=i.data,s=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,s),0===(e-=s)){s===o.length?(++r,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=o.slice(s));break}++r}return t.length-=r,n}(e,t);return i}(e,t.buffer,t.decoder),n);var n}function M(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r.nextTick(T,t,e))}function T(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function P(e,t){for(var n=0,i=e.length;n=t.highWaterMark||t.ended))return f("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?M(this):x(this),null;if(0===(e=S(e,t))&&t.ended)return 0===t.length&&M(this),null;var i,r=t.needReadable;return f("need readable",r),(0===t.length||t.length-e0?D(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&M(this)),null!==i&&this.emit("data",i),i},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,f("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?l:b;function c(t,i){f("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,f("cleanup"),e.removeListener("close",v),e.removeListener("finish",_),e.removeListener("drain",d),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",l),n.removeListener("end",b),n.removeListener("data",g),h=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||d())}function l(){f("onend"),e.end()}o.endEmitted?r.nextTick(u):n.once("end",u),e.on("unpipe",c);var d=function(e){return function(){var t=e._readableState;f("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,I(e))}}(n);e.on("drain",d);var h=!1;var p=!1;function g(t){f("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==P(o.pipes,e))&&!h&&(f("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function m(t){f("onerror",t),b(),e.removeListener("error",m),0===a(e,"error")&&e.emit("error",t)}function v(){e.removeListener("finish",_),b()}function _(){f("onfinish"),e.removeListener("close",v),b()}function b(){f("unpipe"),n.unpipe(e)}return n.on("data",g),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",v),e.once("finish",_),e.emit("pipe",n),o.flowing||(f("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var i=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},p=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},g=function(e){function t(t,n,i,r,o,s,a){return e.call(this,!0,t,n,i,r,o,s,a)||this}return h(t,e),t=f([p(1,u.c),p(2,o.a),p(3,l.a),p(4,c.a),p(5,d.a),p(6,a.a)],t)}(s.a);Object(r.h)(g)},SAez:function(e,t,n){var i=t;i.der=n("ps4E"),i.pem=n("VqvS")},SDM6:function(e,t,n){e.exports=n("DsFX")},SWdJ:function(e,t,n){"use strict";n("jF/U");var i,r=n("hK2W"),o=n("tqet"),s=n("KIxu"),a=n("X6iQ"),u=n("2VYG"),c=n("7/Cv"),l=n("ZfGv"),d=n("Bug4"),h=n("gzF+"),f=n("Kp7x"),p=n("Gxst");!function(e){e.TREE="tree",e.FORM="form"}(i||(i={}));var g=n("9bHL"),m=n("TNPA"),v=n("TU7t"),_=function(){function e(e){this.spliceables=e}return e.prototype.splice=function(e,t,n){this.spliceables.forEach(function(i){return i.splice(e,t,n)})},e}(),b=n("ot3f"),y=n("GYOr");t.f=M,t.e=A,t.d=R,n.d(t,"c",function(){return B}),n.d(t,"a",function(){return V}),n.d(t,"b",function(){return Y});var w,C=this&&this.__extends||(w=function(e,t){return(w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}w(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),S=this&&this.__assign||function(){return(S=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},L=function(){function e(e){this.trait=e,this.renderedElements=[]}return Object.defineProperty(e.prototype,"templateId",{get:function(){return"template:"+this.trait.trait},enumerable:!0,configurable:!0}),e.prototype.renderTemplate=function(e){return e},e.prototype.renderElement=function(e,t,n){var i=Object(a.j)(this.renderedElements,function(e){return e.templateData===n});if(i>=0){var r=this.renderedElements[i];this.trait.unrender(n),r.index=t}else{r={index:t,templateData:n};this.renderedElements.push(r)}this.trait.renderIndex(t,n)},e.prototype.splice=function(e,t,n){for(var i=[],r=0,o=this.renderedElements;r=e+t&&i.push({index:s.index+n-t,templateData:s.templateData})}this.renderedElements=i},e.prototype.renderIndexes=function(e){for(var t=0,n=this.renderedElements;t-1&&this.trait.renderIndex(r,o)}},e.prototype.disposeTemplate=function(e){var t=Object(a.j)(this.renderedElements,function(t){return t.templateData===e});t<0||this.renderedElements.splice(t,1)},e}(),O=function(){function e(e){this._trait=e,this.indexes=[],this.sortedIndexes=[],this._onChange=new f.a,this.onChange=this._onChange.event}return Object.defineProperty(e.prototype,"trait",{get:function(){return this._trait},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderer",{get:function(){return new L(this)},enumerable:!0,configurable:!0}),e.prototype.splice=function(e,t,n){var i=n.length-t,r=e+t,o=this.sortedIndexes.filter(function(t){return t=r}).map(function(e){return e+i}));this.renderer.splice(e,t,n.length),this._set(o,o)},e.prototype.renderIndex=function(e,t){c.R(t,this._trait,this.contains(e))},e.prototype.unrender=function(e){c.I(e,this._trait)},e.prototype.set=function(e,t){return this._set(e,e.slice().sort(K),t)},e.prototype._set=function(e,t,n){var i=this.indexes,r=this.sortedIndexes;this.indexes=e,this.sortedIndexes=t;var o=U(r,e);return this.renderer.renderIndexes(o),this._onChange.fire({indexes:e,browserEvent:n}),i},e.prototype.get=function(){return this.indexes},e.prototype.contains=function(e){return Object(a.c)(this.sortedIndexes,e,K)>=0},e.prototype.dispose=function(){this._onChange=Object(o.f)(this._onChange)},x([u.a],e.prototype,"renderer",null),e}(),k=function(e){function t(){return e.call(this,"focused")||this}return C(t,e),t.prototype.renderIndex=function(t,n){e.prototype.renderIndex.call(this,t,n),this.contains(t)?n.setAttribute("aria-selected","true"):n.removeAttribute("aria-selected")},t}(O),N=function(){function e(e,t,n){this.trait=e,this.view=t,this.identityProvider=n}return e.prototype.splice=function(e,t,n){var i=this;if(!this.identityProvider)return this.trait.splice(e,t,n.map(function(){return!1}));var r=this.trait.get().map(function(e){return i.identityProvider.getId(i.view.element(e)).toString()}),o=n.map(function(e){return r.indexOf(i.identityProvider.getId(e).toString())>-1});this.trait.splice(e,t,o)},e}();function E(e){return"INPUT"===e.tagName||"TEXTAREA"===e.tagName}var I,D=function(){function e(e,t,n){this.list=e,this.view=t,this.disposables=new o.b;var i=!1!==n.multipleSelectionSupport;this.openController=n.openController||W;var r=f.b.chain(Object(p.a)(t.domNode,"keydown")).filter(function(e){return!E(e.target)}).map(function(e){return new h.a(e)});r.filter(function(e){return 3===e.keyCode}).on(this.onEnter,this,this.disposables),r.filter(function(e){return 16===e.keyCode}).on(this.onUpArrow,this,this.disposables),r.filter(function(e){return 18===e.keyCode}).on(this.onDownArrow,this,this.disposables),r.filter(function(e){return 11===e.keyCode}).on(this.onPageUpArrow,this,this.disposables),r.filter(function(e){return 12===e.keyCode}).on(this.onPageDownArrow,this,this.disposables),r.filter(function(e){return 9===e.keyCode}).on(this.onEscape,this,this.disposables),i&&r.filter(function(e){return(l.d?e.metaKey:e.ctrlKey)&&31===e.keyCode}).on(this.onCtrlA,this,this.disposables)}return e.prototype.onEnter=function(e){e.preventDefault(),e.stopPropagation(),this.list.setSelection(this.list.getFocus(),e.browserEvent),this.openController.shouldOpen(e.browserEvent)&&this.list.open(this.list.getFocus(),e.browserEvent)},e.prototype.onUpArrow=function(e){e.preventDefault(),e.stopPropagation(),this.list.focusPrevious(1,!1,e.browserEvent),this.list.reveal(this.list.getFocus()[0]),this.view.domNode.focus()},e.prototype.onDownArrow=function(e){e.preventDefault(),e.stopPropagation(),this.list.focusNext(1,!1,e.browserEvent),this.list.reveal(this.list.getFocus()[0]),this.view.domNode.focus()},e.prototype.onPageUpArrow=function(e){e.preventDefault(),e.stopPropagation(),this.list.focusPreviousPage(e.browserEvent),this.list.reveal(this.list.getFocus()[0]),this.view.domNode.focus()},e.prototype.onPageDownArrow=function(e){e.preventDefault(),e.stopPropagation(),this.list.focusNextPage(e.browserEvent),this.list.reveal(this.list.getFocus()[0]),this.view.domNode.focus()},e.prototype.onCtrlA=function(e){e.preventDefault(),e.stopPropagation(),this.list.setSelection(Object(a.r)(this.list.length),e.browserEvent),this.view.domNode.focus()},e.prototype.onEscape=function(e){e.preventDefault(),e.stopPropagation(),this.list.setSelection([],e.browserEvent),this.view.domNode.focus()},e.prototype.dispose=function(){this.disposables.dispose()},e}();function M(e){return!(e.ctrlKey||e.metaKey||e.altKey)&&(e.keyCode>=31&&e.keyCode<=56||e.keyCode>=21&&e.keyCode<=30||e.keyCode>=93&&e.keyCode<=102||e.keyCode>=80&&e.keyCode<=90)}!function(e){e[e.Idle=0]="Idle",e[e.Typing=1]="Typing"}(I||(I={}));var T=function(){function e(e,t,n){this.list=e,this.view=t,this.keyboardNavigationLabelProvider=n,this.enabled=!1,this.state=I.Idle,this.automaticKeyboardNavigation=!0,this.triggered=!1,this.enabledDisposables=new o.b,this.disposables=new o.b,this.updateOptions(e.options)}return e.prototype.updateOptions=function(e){void 0===e.enableKeyboardNavigation||!!e.enableKeyboardNavigation?this.enable():this.disable(),void 0!==e.automaticKeyboardNavigation&&(this.automaticKeyboardNavigation=e.automaticKeyboardNavigation)},e.prototype.enable=function(){var e=this;if(!this.enabled){var t=f.b.chain(Object(p.a)(this.view.domNode,"keydown")).filter(function(e){return!E(e.target)}).filter(function(){return e.automaticKeyboardNavigation||e.triggered}).map(function(e){return new h.a(e)}).filter(this.keyboardNavigationLabelProvider.mightProducePrintableCharacter?function(t){return e.keyboardNavigationLabelProvider.mightProducePrintableCharacter(t)}:function(e){return M(e)}).forEach(function(e){e.stopPropagation(),e.preventDefault()}).map(function(e){return e.browserEvent.key}).event,n=f.b.debounce(t,function(){return null},800);f.b.reduce(f.b.any(t,n),function(e,t){return null===t?null:(e||"")+t})(this.onInput,this,this.enabledDisposables),this.enabled=!0,this.triggered=!1}},e.prototype.disable=function(){this.enabled&&(this.enabledDisposables.clear(),this.enabled=!1,this.triggered=!1)},e.prototype.onInput=function(e){if(!e)return this.state=I.Idle,void(this.triggered=!1);var t=this.list.getFocus(),n=t.length>0?t[0]:0,i=this.state===I.Idle?1:0;this.state=I.Typing;for(var r=0;r=0&&e[r]===t-(n-r);)i.push(e[r--]);i.reverse(),r=n;for(;r=e.length)n.push(t[r++]);else if(r>=t.length)n.push(e[i++]);else{if(e[i]===t[r]){i++,r++;continue}e[i]=e.length)n.push(t[r++]);else if(r>=t.length)n.push(e[i++]);else{if(e[i]===t[r]){n.push(e[i]),i++,r++;continue}e[i]-1?t:[e]},e.prototype.getDragURI=function(e){return this.dnd.getDragURI(e)},e.prototype.getDragLabel=function(e){if(this.dnd.getDragLabel)return this.dnd.getDragLabel(e)},e.prototype.onDragStart=function(e,t){this.dnd.onDragStart&&this.dnd.onDragStart(e,t)},e.prototype.onDragOver=function(e,t,n,i){return this.dnd.onDragOver(e,t,n,i)},e.prototype.drop=function(e,t,n,i){this.dnd.drop(e,t,n,i)},e}(),Y=function(){function e(e,t,n,s){void 0===s&&(s=z),this._options=s,this.eventBufferer=new f.c,this.disposables=new o.b,this._onDidOpen=new f.a,this.onDidOpen=this._onDidOpen.event,this._onPin=new f.a,this.didJustPressContextMenuKey=!1,this._onDidDispose=new f.a,this.onDidDispose=this._onDidDispose.event,this.focus=new k,this.selection=new O("selected"),Object(v.g)(s,H,!1);var a=[this.focus.renderer,this.selection.renderer];s.accessibilityProvider&&a.push(new G(s.accessibilityProvider)),n=n.map(function(e){return new q(e.templateId,a.concat([e]))});var u=S({},s,{dnd:s.dnd&&new Z(this,s.dnd)});if(this.view=new g.b(e,t,n,u),"string"!=typeof s.ariaRole?this.view.domNode.setAttribute("role",i.TREE):this.view.domNode.setAttribute("role",s.ariaRole),this.styleElement=c.s(this.view.domNode),this.styleController=s.styleController||new V(this.styleElement,this.view.domId),this.spliceable=new _([new N(this.focus,this.view,s.identityProvider),new N(this.selection,this.view,s.identityProvider),this.view]),this.disposables.add(this.focus),this.disposables.add(this.selection),this.disposables.add(this.view),this.disposables.add(this._onDidDispose),this.onDidFocus=f.b.map(Object(p.a)(this.view.domNode,"focus",!0),function(){return null}),this.onDidBlur=f.b.map(Object(p.a)(this.view.domNode,"blur",!0),function(){return null}),this.disposables.add(new P(this,this.view)),"boolean"!=typeof s.keyboardSupport||s.keyboardSupport){var l=new D(this,this.view,s);this.disposables.add(l)}s.keyboardNavigationLabelProvider&&(this.typeLabelController=new T(this,this.view,s.keyboardNavigationLabelProvider),this.disposables.add(this.typeLabelController)),this.disposables.add(this.createMouseController(s)),this.onFocusChange(this._onFocusChange,this,this.disposables),this.onSelectionChange(this._onSelectionChange,this,this.disposables),s.ariaLabel&&this.view.domNode.setAttribute("aria-label",Object(r.a)("aria list","{0}. Use the navigation keys to navigate.",s.ariaLabel)),this.style(s)}return Object.defineProperty(e.prototype,"onFocusChange",{get:function(){var e=this;return f.b.map(this.eventBufferer.wrapEvent(this.focus.onChange),function(t){return e.toListEvent(t)})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onSelectionChange",{get:function(){var e=this;return f.b.map(this.eventBufferer.wrapEvent(this.selection.onChange),function(t){return e.toListEvent(t)})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"domId",{get:function(){return this.view.domId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onMouseClick",{get:function(){return this.view.onMouseClick},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onMouseDblClick",{get:function(){return this.view.onMouseDblClick},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onMouseMiddleClick",{get:function(){return this.view.onMouseMiddleClick},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onMouseDown",{get:function(){return this.view.onMouseDown},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTouchStart",{get:function(){return this.view.onTouchStart},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onTap",{get:function(){return this.view.onTap},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onContextMenu",{get:function(){var e=this,t=f.b.chain(Object(p.a)(this.view.domNode,"keydown")).map(function(e){return new h.a(e)}).filter(function(t){return e.didJustPressContextMenuKey=58===t.keyCode||t.shiftKey&&68===t.keyCode}).filter(function(e){return e.preventDefault(),e.stopPropagation(),!1}).event,n=f.b.chain(Object(p.a)(this.view.domNode,"keyup")).filter(function(){var t=e.didJustPressContextMenuKey;return e.didJustPressContextMenuKey=!1,t}).filter(function(){return e.getFocus().length>0&&!!e.view.domElement(e.getFocus()[0])}).map(function(t){var n=e.getFocus()[0];return{index:n,element:e.view.element(n),anchor:e.view.domElement(n),browserEvent:t}}).event,i=f.b.chain(this.view.onContextMenu).filter(function(){return!e.didJustPressContextMenuKey}).map(function(e){var t=e.element,n=e.index,i=e.browserEvent;return{element:t,index:n,anchor:{x:i.clientX+1,y:i.clientY},browserEvent:i}}).event;return f.b.any(t,n,i)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onKeyDown",{get:function(){return Object(p.a)(this.view.domNode,"keydown")},enumerable:!0,configurable:!0}),e.prototype.createMouseController=function(e){return new B(this)},e.prototype.updateOptions=function(e){void 0===e&&(e={}),this._options=S({},this._options,e),this.typeLabelController&&this.typeLabelController.updateOptions(this._options)},Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!0,configurable:!0}),e.prototype.splice=function(e,t,n){var i=this;if(void 0===n&&(n=[]),e<0||e>this.view.length)throw new Error("Invalid start index: "+e);if(t<0)throw new Error("Invalid delete count: "+t);0===t&&0===n.length||this.eventBufferer.bufferEvents(function(){return i.spliceable.splice(e,t,n)})},e.prototype.rerender=function(){this.view.rerender()},e.prototype.element=function(e){return this.view.element(e)},Object.defineProperty(e.prototype,"length",{get:function(){return this.view.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"contentHeight",{get:function(){return this.view.contentHeight},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollTop",{get:function(){return this.view.getScrollTop()},set:function(e){this.view.setScrollTop(e)},enumerable:!0,configurable:!0}),e.prototype.domFocus=function(){this.view.domNode.focus()},e.prototype.layout=function(e,t){this.view.layout(e,t)},e.prototype.setSelection=function(e,t){for(var n=0,i=e;n=this.length)throw new Error("Invalid index "+r)}this.selection.set(e,t)},e.prototype.getSelection=function(){return this.selection.get()},e.prototype.getSelectedElements=function(){var e=this;return this.getSelection().map(function(t){return e.view.element(t)})},e.prototype.setFocus=function(e,t){for(var n=0,i=e;n=this.length)throw new Error("Invalid index "+r)}this.focus.set(e,t)},e.prototype.focusNext=function(e,t,n,i){if(void 0===e&&(e=1),void 0===t&&(t=!1),0!==this.length){var r=this.focus.get(),o=this.findNextIndex(r.length>0?r[0]+e:0,t,i);o>-1&&this.setFocus([o],n)}},e.prototype.focusPrevious=function(e,t,n,i){if(void 0===e&&(e=1),void 0===t&&(t=!1),0!==this.length){var r=this.focus.get(),o=this.findPreviousIndex(r.length>0?r[0]-e:0,t,i);o>-1&&this.setFocus([o],n)}},e.prototype.focusNextPage=function(e,t){var n=this,i=this.view.indexAt(this.view.getScrollTop()+this.view.renderHeight);i=0===i?0:i-1;var r=this.view.element(i),o=this.getFocusedElements()[0];if(o!==r){var s=this.findPreviousIndex(i,!1,t);s>-1&&o!==this.view.element(s)?this.setFocus([s],e):this.setFocus([i],e)}else{var a=this.view.getScrollTop();this.view.setScrollTop(a+this.view.renderHeight-this.view.elementHeight(i)),this.view.getScrollTop()!==a&&setTimeout(function(){return n.focusNextPage(e,t)},0)}},e.prototype.focusPreviousPage=function(e,t){var n,i=this,r=this.view.getScrollTop();n=0===r?this.view.indexAt(r):this.view.indexAfter(r-1);var o=this.view.element(n),s=this.getFocusedElements()[0];if(s!==o){var a=this.findNextIndex(n,!1,t);a>-1&&s!==this.view.element(a)?this.setFocus([a],e):this.setFocus([n],e)}else{var u=r;this.view.setScrollTop(r-this.view.renderHeight),this.view.getScrollTop()!==u&&setTimeout(function(){return i.focusPreviousPage(e,t)},0)}},e.prototype.focusLast=function(e,t){if(0!==this.length){var n=this.findPreviousIndex(this.length-1,!1,t);n>-1&&this.setFocus([n],e)}},e.prototype.focusFirst=function(e,t){if(0!==this.length){var n=this.findNextIndex(0,!1,t);n>-1&&this.setFocus([n],e)}},e.prototype.findNextIndex=function(e,t,n){void 0===t&&(t=!1);for(var i=0;i=this.length&&!t)return-1;if(e%=this.length,!n||n(this.element(e)))return e;e++}return-1},e.prototype.findPreviousIndex=function(e,t,n){void 0===t&&(t=!1);for(var i=0;i=this.length)throw new Error("Invalid index "+e);var n=this.view.getScrollTop(),i=this.view.elementTop(e),r=this.view.elementHeight(e);if(Object(s.g)(t)){var o=r-this.view.renderHeight;this.view.setScrollTop(o*Object(b.a)(t,0,1)+i)}else{var a=i+r,u=n+this.view.renderHeight;i=u&&this.view.setScrollTop(a-this.view.renderHeight)}},e.prototype.getRelativeTop=function(e){if(e<0||e>=this.length)throw new Error("Invalid index "+e);var t=this.view.getScrollTop(),n=this.view.elementTop(e),i=this.view.elementHeight(e);if(nt+this.view.renderHeight)return null;var r=i-this.view.renderHeight;return Math.abs((t-n)/r)},e.prototype.getHTMLElement=function(){return this.view.domNode},e.prototype.open=function(e,t){for(var n=this,i=0,r=e;i=this.length)throw new Error("Invalid index "+o)}this._onDidOpen.fire({indexes:e,elements:e.map(function(e){return n.view.element(e)}),browserEvent:t})},e.prototype.pin=function(e){for(var t=0,n=e;t=this.length)throw new Error("Invalid index "+i)}this._onPin.fire(e)},e.prototype.style=function(e){this.styleController.style(e)},e.prototype.toListEvent=function(e){var t=this,n=e.indexes,i=e.browserEvent;return{indexes:n,elements:n.map(function(e){return t.view.element(e)}),browserEvent:i}},e.prototype._onFocusChange=function(){var e=this.focus.get();e.length>0?this.view.domNode.setAttribute("aria-activedescendant",this.view.getElementDomId(e[0])):this.view.domNode.removeAttribute("aria-activedescendant"),this.view.domNode.setAttribute("role","tree"),c.R(this.view.domNode,"element-focused",e.length>0)},e.prototype._onSelectionChange=function(){var e=this.selection.get();c.R(this.view.domNode,"selection-none",0===e.length),c.R(this.view.domNode,"selection-single",1===e.length),c.R(this.view.domNode,"selection-multiple",e.length>1)},e.prototype.dispose=function(){this._onDidDispose.fire(),this.disposables.dispose(),this._onDidOpen.dispose(),this._onPin.dispose(),this._onDidDispose.dispose()},x([u.a],e.prototype,"onFocusChange",null),x([u.a],e.prototype,"onSelectionChange",null),x([u.a],e.prototype,"onContextMenu",null),e}()},Skdw:function(e,t,n){"use strict";t.b=function(e,t){void 0===t&&(t=s);return function(e,t){for(var n='
      ',o=e.split(/\r\n|\r|\n/),s=t.getInitialState(),a=0,u=o.length;a0&&(n+="
      ");var l=t.tokenize2(c,s,0);r.a.convertToEndOffset(l.tokens,c.length);for(var d=new r.a(l.tokens,c),h=d.inflate(),f=0,p=0,g=h.getCount();p'+i.o(c.substring(f,v))+"",f=v}s=l.endState}return n+="
      "}(e,t||s)},t.a=function(e,t,n,i,r,o){for(var s="
      ",a=i,u=0,c=0,l=t.getCount();c0;)h+=" ",p--;break;case 60:h+="<";break;case 62:h+=">";break;case 38:h+="&";break;case 0:h+="�";break;case 65279:case 8232:h+="�";break;case 13:h+="​";break;case 32:h+=" ";break;default:h+=String.fromCharCode(f)}}if(s+=''+h+"",d>r||a>=r)break}}return s+="
      "};var i=n("aL7J"),r=n("cLaT"),o=n("jUH2"),s={getInitialState:function(){return o.c},tokenize2:function(e,t,n){return Object(o.e)(0,e,t,n)}}},SoM9:function(e,t){},SsjP:function(e,t,n){var i=n("H2Pp"),r=n("X3l8").Buffer,o=n("4sPJ");function s(e){var t=e._cipher.encryptBlockRaw(e._prev);return o(e._prev),t}t.encrypt=function(e,t){var n=Math.ceil(t.length/16),o=e._cache.length;e._cache=r.concat([e._cache,r.allocUnsafe(16*n)]);for(var a=0;a=0?t+1:1},e.prototype.getCurrentMatchesPosition=function(t){for(var n=0,i=this._editor.getModel().getDecorationsInRange(t);n1e3){o=e._FIND_MATCH_NO_OVERVIEW_DECORATION;for(var a=i._editor.getModel().getLineCount(),u=i._editor.getLayoutInfo().height/a,c=Math.max(2,Math.ceil(3/u)),l=t[0].range.startLineNumber,h=t[0].range.endLineNumber,f=1,p=t.length;f=g.startLineNumber?g.endLineNumber>h&&(h=g.endLineNumber):(s.push({range:new d.a(l,1,h,1),options:e._FIND_MATCH_ONLY_OVERVIEW_DECORATION}),l=g.startLineNumber,h=g.endLineNumber)}s.push({range:new d.a(l,1,h,1),options:e._FIND_MATCH_ONLY_OVERVIEW_DECORATION})}var m=new Array(t.length);for(f=0,p=t.length;f=0;t--){var n=this._decorations[t],i=this._editor.getModel().getDecorationRange(n);if(i&&!(i.endLineNumber>e.lineNumber)){if(i.endLineNumbere.column))return i}}return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length-1])},e.prototype.matchAfterPosition=function(e){if(0===this._decorations.length)return null;for(var t=0,n=this._decorations.length;te.lineNumber)return r;if(!(r.startColumn0){for(var n=[],i=0;i0;){if(e0},e.prototype._cannotFind=function(){if(!this._hasMatches()){var e=this._decorations.getFindScope();return e&&this._editor.revealRangeInCenterIfOutsideViewport(e,0),!0}return!1},e.prototype._setCurrentFindMatch=function(e){var t=this._decorations.setCurrentFindMatch(e);this._state.changeMatchInfo(t,this._decorations.getCount(),e),this._editor.setSelection(e),this._editor.revealRangeInCenterIfOutsideViewport(e,0)},e.prototype._prevSearchPosition=function(e){var t=this._state.isRegex&&(this._state.searchString.indexOf("^")>=0||this._state.searchString.indexOf("$")>=0),n=e.lineNumber,i=e.column,r=this._editor.getModel();return t||1===i?(1===n?n=r.getLineCount():n--,i=r.getLineMaxColumn(n)):i--,new l.a(n,i)},e.prototype._moveToPrevMatch=function(t,n){if(void 0===n&&(n=!1),this._decorations.getCount()<19999){var i=this._decorations.matchBeforePosition(t);return i&&i.isEmpty()&&i.getStartPosition().equals(t)&&(t=this._prevSearchPosition(t),i=this._decorations.matchBeforePosition(t)),void(i&&this._setCurrentFindMatch(i))}if(!this._cannotFind()){var r=this._decorations.getFindScope(),o=e._getSearchRange(this._editor.getModel(),r);o.getEndPosition().isBefore(t)&&(t=o.getEndPosition()),t.isBefore(o.getStartPosition())&&(t=o.getEndPosition());var s=t.lineNumber,a=t.column,u=this._editor.getModel(),c=new l.a(s,a),d=u.findPreviousMatch(this._state.searchString,c,this._state.isRegex,this._state.matchCase,this._state.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1);if(d&&d.range.isEmpty()&&d.range.getStartPosition().equals(c)&&(c=this._prevSearchPosition(c),d=u.findPreviousMatch(this._state.searchString,c,this._state.isRegex,this._state.matchCase,this._state.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1)),d)return n||o.containsRange(d.range)?void this._setCurrentFindMatch(d.range):this._moveToPrevMatch(d.range.getStartPosition(),!0)}},e.prototype.moveToPrevMatch=function(){this._moveToPrevMatch(this._editor.getSelection().getStartPosition())},e.prototype._nextSearchPosition=function(e){var t=this._state.isRegex&&(this._state.searchString.indexOf("^")>=0||this._state.searchString.indexOf("$")>=0),n=e.lineNumber,i=e.column,r=this._editor.getModel();return t||i===r.getLineMaxColumn(n)?(n===r.getLineCount()?n=1:n++,i=1):i++,new l.a(n,i)},e.prototype._moveToNextMatch=function(e){if(this._decorations.getCount()<19999){var t=this._decorations.matchAfterPosition(e);return t&&t.isEmpty()&&t.getStartPosition().equals(e)&&(e=this._nextSearchPosition(e),t=this._decorations.matchAfterPosition(e)),void(t&&this._setCurrentFindMatch(t))}var n=this._getNextMatch(e,!1,!0);n&&this._setCurrentFindMatch(n.range)},e.prototype._getNextMatch=function(t,n,i,r){if(void 0===r&&(r=!1),this._cannotFind())return null;var o=this._decorations.getFindScope(),s=e._getSearchRange(this._editor.getModel(),o);s.getEndPosition().isBefore(t)&&(t=s.getStartPosition()),t.isBefore(s.getStartPosition())&&(t=s.getStartPosition());var a=t.lineNumber,u=t.column,c=this._editor.getModel(),d=new l.a(a,u),h=c.findNextMatch(this._state.searchString,d,this._state.isRegex,this._state.matchCase,this._state.wholeWord?this._editor.getConfiguration().wordSeparators:null,n);return i&&h&&h.range.isEmpty()&&h.range.getStartPosition().equals(d)&&(d=this._nextSearchPosition(d),h=c.findNextMatch(this._state.searchString,d,this._state.isRegex,this._state.matchCase,this._state.wholeWord?this._editor.getConfiguration().wordSeparators:null,n)),h?r||s.containsRange(h.range)?h:this._getNextMatch(h.range.getEndPosition(),n,i,!0):null},e.prototype.moveToNextMatch=function(){this._moveToNextMatch(this._editor.getSelection().getEndPosition())},e.prototype._getReplacePattern=function(){return this._state.isRegex?function(e){if(!e||0===e.length)return new S(null);for(var t=new L(e),n=0,i=e.length;n=i)break;if(36===(a=e.charCodeAt(n))){t.emitUnchanged(n-1),t.emitStatic("$",n+1);continue}if(48===a||38===a){t.emitUnchanged(n-1),t.emitMatchIndex(0,n+1);continue}if(49<=a&&a<=57){var o=a-48;if(n+1=i)break;var a;switch(a=e.charCodeAt(n)){case 92:t.emitUnchanged(n-1),t.emitStatic("\\",n+1);break;case 110:t.emitUnchanged(n-1),t.emitStatic("\n",n+1);break;case 116:t.emitUnchanged(n-1),t.emitStatic("\t",n+1)}}}return t.finalize()}(this._state.replaceString):S.fromStaticValue(this._state.replaceString)},e.prototype.replace=function(){if(this._hasMatches()){var e=this._getReplacePattern(),t=this._editor.getSelection(),n=this._getNextMatch(t.getStartPosition(),!0,!1);if(n)if(t.equalsRange(n.range)){var i=e.buildReplaceString(n.matches,this._state.preserveCase),r=new c.a(t,i);this._executeEditorCommand("replace",r),this._decorations.setStartPosition(new l.a(t.startLineNumber,t.startColumn+i.length)),this.research(!0)}else this._decorations.setStartPosition(this._editor.getPosition()),this._setCurrentFindMatch(n.range)}},e.prototype._findMatches=function(t,n,i){var r=e._getSearchRange(this._editor.getModel(),t);return this._editor.getModel().findMatches(this._state.searchString,r,this._state.isRegex,this._state.matchCase,this._state.wholeWord?this._editor.getConfiguration().wordSeparators:null,n,i)},e.prototype.replaceAll=function(){if(this._hasMatches()){var e=this._decorations.getFindScope();null===e&&this._state.matchesCount>=19999?this._largeReplaceAll():this._regularReplaceAll(e),this.research(!1)}},e.prototype._largeReplaceAll=function(){var e=new f.a(this._state.searchString,this._state.isRegex,this._state.matchCase,this._state.wholeWord?this._editor.getConfiguration().wordSeparators:null).parseSearchRequest();if(e){var t=e.regex;if(!t.multiline){var n="m";t.ignoreCase&&(n+="i"),t.global&&(n+="g"),t=new RegExp(t.source,n)}var i,r=this._editor.getModel(),o=r.getValue(1),s=r.getFullModelRange(),a=this._getReplacePattern(),u=this._state.preserveCase;i=a.hasReplacementPatterns||u?o.replace(t,function(){return a.buildReplaceString(arguments,u)}):o.replace(t,a.buildReplaceString(null,u));var l=new c.b(s,i,this._editor.getSelection());this._executeEditorCommand("replaceAll",l)}},e.prototype._regularReplaceAll=function(e){for(var t=this._getReplacePattern(),n=this._findMatches(e,t.hasReplacementPatterns||this._state.preserveCase,1073741824),i=[],r=0,o=n.length;rt&&(e=t),this._matchesPosition!==e&&(this._matchesPosition=e,i.matchesPosition=!0,r=!0),this._matchesCount!==t&&(this._matchesCount=t,i.matchesCount=!0,r=!0),void 0!==n&&(d.a.equalsRange(this._currentMatch,n)||(this._currentMatch=n,i.currentMatch=!0,r=!0)),r&&this._onFindReplaceStateChange.fire(i)},e.prototype.change=function(e,t,n){void 0===n&&(n=!0);var i={moveCursor:t,updateHistory:n,searchString:!1,replaceString:!1,isRevealed:!1,isReplaceRevealed:!1,isRegex:!1,wholeWord:!1,matchCase:!1,preserveCase:!1,searchScope:!1,matchesPosition:!1,matchesCount:!1,currentMatch:!1},r=!1,o=this.isRegex,s=this.wholeWord,a=this.matchCase,u=this.preserveCase;void 0!==e.searchString&&this._searchString!==e.searchString&&(this._searchString=e.searchString,i.searchString=!0,r=!0),void 0!==e.replaceString&&this._replaceString!==e.replaceString&&(this._replaceString=e.replaceString,i.replaceString=!0,r=!0),void 0!==e.isRevealed&&this._isRevealed!==e.isRevealed&&(this._isRevealed=e.isRevealed,i.isRevealed=!0,r=!0),void 0!==e.isReplaceRevealed&&this._isReplaceRevealed!==e.isReplaceRevealed&&(this._isReplaceRevealed=e.isReplaceRevealed,i.isReplaceRevealed=!0,r=!0),void 0!==e.isRegex&&(this._isRegex=e.isRegex),void 0!==e.wholeWord&&(this._wholeWord=e.wholeWord),void 0!==e.matchCase&&(this._matchCase=e.matchCase),void 0!==e.preserveCase&&(this._preserveCase=e.preserveCase),void 0!==e.searchScope&&(d.a.equalsRange(this._searchScope,e.searchScope)||(this._searchScope=e.searchScope,i.searchScope=!0,r=!0)),this._isRegexOverride=void 0!==e.isRegexOverride?e.isRegexOverride:0,this._wholeWordOverride=void 0!==e.wholeWordOverride?e.wholeWordOverride:0,this._matchCaseOverride=void 0!==e.matchCaseOverride?e.matchCaseOverride:0,this._preserveCaseOverride=void 0!==e.preserveCaseOverride?e.preserveCaseOverride:0,o!==this.isRegex&&(r=!0,i.isRegex=!0),s!==this.wholeWord&&(r=!0,i.wholeWord=!0),a!==this.matchCase&&(r=!0,i.matchCase=!0),u!==this.preserveCase&&(r=!0,i.preserveCase=!0),r&&this._onFindReplaceStateChange.fire(i)},e}(),ne=(n("s0RT"),n("UqCF")),ie=n("5tK6"),re=n("zxiH"),oe=n("ZfGv"),se=(n("NBYJ"),n("a6dA")),ae=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),ue=i.a("defaultLabel","input"),ce=function(e){function t(t,n,i,r){var o=e.call(this)||this;o._showOptionButtons=i,o.fixFocusOnOptionClickEnabled=!0,o._onDidOptionChange=o._register(new B.a),o.onDidOptionChange=o._onDidOptionChange.event,o._onKeyDown=o._register(new B.a),o.onKeyDown=o._onKeyDown.event,o._onMouseDown=o._register(new B.a),o.onMouseDown=o._onMouseDown.event,o._onInput=o._register(new B.a),o._onKeyUp=o._register(new B.a),o._onCaseSensitiveKeyDown=o._register(new B.a),o.onCaseSensitiveKeyDown=o._onCaseSensitiveKeyDown.event,o._onRegexKeyDown=o._register(new B.a),o.onRegexKeyDown=o._onRegexKeyDown.event,o._lastHighlightFindOptions=0,o.contextViewProvider=n,o.placeholder=r.placeholder||"",o.validation=r.validation,o.label=r.label||ue,o.inputActiveOptionBorder=r.inputActiveOptionBorder,o.inputActiveOptionBackground=r.inputActiveOptionBackground,o.inputBackground=r.inputBackground,o.inputForeground=r.inputForeground,o.inputBorder=r.inputBorder,o.inputValidationInfoBorder=r.inputValidationInfoBorder,o.inputValidationInfoBackground=r.inputValidationInfoBackground,o.inputValidationInfoForeground=r.inputValidationInfoForeground,o.inputValidationWarningBorder=r.inputValidationWarningBorder,o.inputValidationWarningBackground=r.inputValidationWarningBackground,o.inputValidationWarningForeground=r.inputValidationWarningForeground,o.inputValidationErrorBorder=r.inputValidationErrorBorder,o.inputValidationErrorBackground=r.inputValidationErrorBackground,o.inputValidationErrorForeground=r.inputValidationErrorForeground;var s=r.appendCaseSensitiveLabel||"",a=r.appendWholeWordsLabel||"",u=r.appendRegexLabel||"",c=r.history||[],l=!!r.flexibleHeight,d=!!r.flexibleWidth,h=r.flexibleMaxHeight;o.domNode=document.createElement("div"),F.f(o.domNode,"monaco-findInput"),o.inputBox=o._register(new se.a(o.domNode,o.contextViewProvider,{placeholder:o.placeholder||"",ariaLabel:o.label||"",validationOptions:{validation:o.validation},inputBackground:o.inputBackground,inputForeground:o.inputForeground,inputBorder:o.inputBorder,inputValidationInfoBackground:o.inputValidationInfoBackground,inputValidationInfoForeground:o.inputValidationInfoForeground,inputValidationInfoBorder:o.inputValidationInfoBorder,inputValidationWarningBackground:o.inputValidationWarningBackground,inputValidationWarningForeground:o.inputValidationWarningForeground,inputValidationWarningBorder:o.inputValidationWarningBorder,inputValidationErrorBackground:o.inputValidationErrorBackground,inputValidationErrorForeground:o.inputValidationErrorForeground,inputValidationErrorBorder:o.inputValidationErrorBorder,history:c,flexibleHeight:l,flexibleWidth:d,flexibleMaxHeight:h})),o.regex=o._register(new $({appendTitle:u,isChecked:!1,inputActiveOptionBorder:o.inputActiveOptionBorder,inputActiveOptionBackground:o.inputActiveOptionBackground})),o._register(o.regex.onChange(function(e){o._onDidOptionChange.fire(e),!e&&o.fixFocusOnOptionClickEnabled&&o.inputBox.focus(),o.validate()})),o._register(o.regex.onKeyDown(function(e){o._onRegexKeyDown.fire(e)})),o.wholeWords=o._register(new X({appendTitle:a,isChecked:!1,inputActiveOptionBorder:o.inputActiveOptionBorder,inputActiveOptionBackground:o.inputActiveOptionBackground})),o._register(o.wholeWords.onChange(function(e){o._onDidOptionChange.fire(e),!e&&o.fixFocusOnOptionClickEnabled&&o.inputBox.focus(),o.validate()})),o.caseSensitive=o._register(new Y({appendTitle:s,isChecked:!1,inputActiveOptionBorder:o.inputActiveOptionBorder,inputActiveOptionBackground:o.inputActiveOptionBackground})),o._register(o.caseSensitive.onChange(function(e){o._onDidOptionChange.fire(e),!e&&o.fixFocusOnOptionClickEnabled&&o.inputBox.focus(),o.validate()})),o._register(o.caseSensitive.onKeyDown(function(e){o._onCaseSensitiveKeyDown.fire(e)})),o._showOptionButtons&&(o.inputBox.paddingRight=o.caseSensitive.width()+o.wholeWords.width()+o.regex.width());var f=[o.caseSensitive.domNode,o.wholeWords.domNode,o.regex.domNode];o.onkeydown(o.domNode,function(e){if(e.equals(15)||e.equals(17)||e.equals(9)){var t=f.indexOf(document.activeElement);if(t>=0){var n=-1;e.equals(17)?n=(t+1)%f.length:e.equals(15)&&(n=0===t?f.length-1:t-1),e.equals(9)?f[t].blur():n>=0&&f[n].focus(),F.c.stop(e,!0)}}});var p=document.createElement("div");return p.className="controls",p.style.display=o._showOptionButtons?"block":"none",p.appendChild(o.caseSensitive.domNode),p.appendChild(o.wholeWords.domNode),p.appendChild(o.regex.domNode),o.domNode.appendChild(p),t&&t.appendChild(o.domNode),o.onkeydown(o.inputBox.inputElement,function(e){return o._onKeyDown.fire(e)}),o.onkeyup(o.inputBox.inputElement,function(e){return o._onKeyUp.fire(e)}),o.oninput(o.inputBox.inputElement,function(e){return o._onInput.fire()}),o.onmousedown(o.inputBox.inputElement,function(e){return o._onMouseDown.fire(e)}),o}return ae(t,e),t.prototype.enable=function(){F.I(this.domNode,"disabled"),this.inputBox.enable(),this.regex.enable(),this.wholeWords.enable(),this.caseSensitive.enable()},t.prototype.disable=function(){F.f(this.domNode,"disabled"),this.inputBox.disable(),this.regex.disable(),this.wholeWords.disable(),this.caseSensitive.disable()},t.prototype.setFocusInputOnOptionClick=function(e){this.fixFocusOnOptionClickEnabled=e},t.prototype.setEnabled=function(e){e?this.enable():this.disable()},t.prototype.getValue=function(){return this.inputBox.value},t.prototype.setValue=function(e){this.inputBox.value!==e&&(this.inputBox.value=e)},t.prototype.style=function(e){this.inputActiveOptionBorder=e.inputActiveOptionBorder,this.inputActiveOptionBackground=e.inputActiveOptionBackground,this.inputBackground=e.inputBackground,this.inputForeground=e.inputForeground,this.inputBorder=e.inputBorder,this.inputValidationInfoBackground=e.inputValidationInfoBackground,this.inputValidationInfoForeground=e.inputValidationInfoForeground,this.inputValidationInfoBorder=e.inputValidationInfoBorder,this.inputValidationWarningBackground=e.inputValidationWarningBackground,this.inputValidationWarningForeground=e.inputValidationWarningForeground,this.inputValidationWarningBorder=e.inputValidationWarningBorder,this.inputValidationErrorBackground=e.inputValidationErrorBackground,this.inputValidationErrorForeground=e.inputValidationErrorForeground,this.inputValidationErrorBorder=e.inputValidationErrorBorder,this.applyStyles()},t.prototype.applyStyles=function(){if(this.domNode){var e={inputActiveOptionBorder:this.inputActiveOptionBorder,inputActiveOptionBackground:this.inputActiveOptionBackground};this.regex.style(e),this.wholeWords.style(e),this.caseSensitive.style(e);var t={inputBackground:this.inputBackground,inputForeground:this.inputForeground,inputBorder:this.inputBorder,inputValidationInfoBackground:this.inputValidationInfoBackground,inputValidationInfoForeground:this.inputValidationInfoForeground,inputValidationInfoBorder:this.inputValidationInfoBorder,inputValidationWarningBackground:this.inputValidationWarningBackground,inputValidationWarningForeground:this.inputValidationWarningForeground,inputValidationWarningBorder:this.inputValidationWarningBorder,inputValidationErrorBackground:this.inputValidationErrorBackground,inputValidationErrorForeground:this.inputValidationErrorForeground,inputValidationErrorBorder:this.inputValidationErrorBorder};this.inputBox.style(t)}},t.prototype.select=function(){this.inputBox.select()},t.prototype.focus=function(){this.inputBox.focus()},t.prototype.getCaseSensitive=function(){return this.caseSensitive.checked},t.prototype.setCaseSensitive=function(e){this.caseSensitive.checked=e},t.prototype.getWholeWords=function(){return this.wholeWords.checked},t.prototype.setWholeWords=function(e){this.wholeWords.checked=e},t.prototype.getRegex=function(){return this.regex.checked},t.prototype.setRegex=function(e){this.regex.checked=e,this.validate()},t.prototype.focusOnCaseSensitive=function(){this.caseSensitive.focus()},t.prototype.highlightFindOptions=function(){F.I(this.domNode,"highlight-"+this._lastHighlightFindOptions),this._lastHighlightFindOptions=1-this._lastHighlightFindOptions,F.f(this.domNode,"highlight-"+this._lastHighlightFindOptions)},t.prototype.validate=function(){this.inputBox&&this.inputBox.validate()},t.prototype.clearMessage=function(){this.inputBox&&this.inputBox.hideMessage()},t.prototype.dispose=function(){e.prototype.dispose.call(this)},t}(j.a),le=n("Kx4b"),de=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),he=i.a("defaultLabel","input"),fe=i.a("label.preserveCaseCheckbox","Preserve Case"),pe=function(e){function t(t){return e.call(this,{actionClassName:"monaco-case-sensitive",title:fe+t.appendTitle,isChecked:t.isChecked,inputActiveOptionBorder:t.inputActiveOptionBorder})||this}return de(t,e),t}(U),ge=function(e){function t(t,n,i,r){var o=e.call(this)||this;o._showOptionButtons=i,o.fixFocusOnOptionClickEnabled=!0,o.cachedOptionsWidth=0,o._onDidOptionChange=o._register(new B.a),o.onDidOptionChange=o._onDidOptionChange.event,o._onKeyDown=o._register(new B.a),o.onKeyDown=o._onKeyDown.event,o._onMouseDown=o._register(new B.a),o._onInput=o._register(new B.a),o._onKeyUp=o._register(new B.a),o._onPreserveCaseKeyDown=o._register(new B.a),o.onPreserveCaseKeyDown=o._onPreserveCaseKeyDown.event,o.contextViewProvider=n,o.placeholder=r.placeholder||"",o.validation=r.validation,o.label=r.label||he,o.inputActiveOptionBorder=r.inputActiveOptionBorder,o.inputBackground=r.inputBackground,o.inputForeground=r.inputForeground,o.inputBorder=r.inputBorder,o.inputValidationInfoBorder=r.inputValidationInfoBorder,o.inputValidationInfoBackground=r.inputValidationInfoBackground,o.inputValidationInfoForeground=r.inputValidationInfoForeground,o.inputValidationWarningBorder=r.inputValidationWarningBorder,o.inputValidationWarningBackground=r.inputValidationWarningBackground,o.inputValidationWarningForeground=r.inputValidationWarningForeground,o.inputValidationErrorBorder=r.inputValidationErrorBorder,o.inputValidationErrorBackground=r.inputValidationErrorBackground,o.inputValidationErrorForeground=r.inputValidationErrorForeground;var s=!!r.flexibleHeight,a=!!r.flexibleWidth,u=r.flexibleMaxHeight;return o.buildDomNode(r.history||[],s,a,u),t&&t.appendChild(o.domNode),o.onkeydown(o.inputBox.inputElement,function(e){return o._onKeyDown.fire(e)}),o.onkeyup(o.inputBox.inputElement,function(e){return o._onKeyUp.fire(e)}),o.oninput(o.inputBox.inputElement,function(e){return o._onInput.fire()}),o.onmousedown(o.inputBox.inputElement,function(e){return o._onMouseDown.fire(e)}),o}return de(t,e),t.prototype.enable=function(){F.I(this.domNode,"disabled"),this.inputBox.enable(),this.preserveCase.enable()},t.prototype.disable=function(){F.f(this.domNode,"disabled"),this.inputBox.disable(),this.preserveCase.disable()},t.prototype.setEnabled=function(e){e?this.enable():this.disable()},t.prototype.style=function(e){this.inputActiveOptionBorder=e.inputActiveOptionBorder,this.inputBackground=e.inputBackground,this.inputForeground=e.inputForeground,this.inputBorder=e.inputBorder,this.inputValidationInfoBackground=e.inputValidationInfoBackground,this.inputValidationInfoForeground=e.inputValidationInfoForeground,this.inputValidationInfoBorder=e.inputValidationInfoBorder,this.inputValidationWarningBackground=e.inputValidationWarningBackground,this.inputValidationWarningForeground=e.inputValidationWarningForeground,this.inputValidationWarningBorder=e.inputValidationWarningBorder,this.inputValidationErrorBackground=e.inputValidationErrorBackground,this.inputValidationErrorForeground=e.inputValidationErrorForeground,this.inputValidationErrorBorder=e.inputValidationErrorBorder,this.applyStyles()},t.prototype.applyStyles=function(){if(this.domNode){var e={inputActiveOptionBorder:this.inputActiveOptionBorder};this.preserveCase.style(e);var t={inputBackground:this.inputBackground,inputForeground:this.inputForeground,inputBorder:this.inputBorder,inputValidationInfoBackground:this.inputValidationInfoBackground,inputValidationInfoForeground:this.inputValidationInfoForeground,inputValidationInfoBorder:this.inputValidationInfoBorder,inputValidationWarningBackground:this.inputValidationWarningBackground,inputValidationWarningForeground:this.inputValidationWarningForeground,inputValidationWarningBorder:this.inputValidationWarningBorder,inputValidationErrorBackground:this.inputValidationErrorBackground,inputValidationErrorForeground:this.inputValidationErrorForeground,inputValidationErrorBorder:this.inputValidationErrorBorder};this.inputBox.style(t)}},t.prototype.select=function(){this.inputBox.select()},t.prototype.focus=function(){this.inputBox.focus()},t.prototype.getPreserveCase=function(){return this.preserveCase.checked},t.prototype.setPreserveCase=function(e){this.preserveCase.checked=e},t.prototype.focusOnPreserve=function(){this.preserveCase.focus()},t.prototype.buildDomNode=function(e,t,n,i){var r=this;this.domNode=document.createElement("div"),F.f(this.domNode,"monaco-findInput"),this.inputBox=this._register(new se.a(this.domNode,this.contextViewProvider,{ariaLabel:this.label||"",placeholder:this.placeholder||"",validationOptions:{validation:this.validation},inputBackground:this.inputBackground,inputForeground:this.inputForeground,inputBorder:this.inputBorder,inputValidationInfoBackground:this.inputValidationInfoBackground,inputValidationInfoForeground:this.inputValidationInfoForeground,inputValidationInfoBorder:this.inputValidationInfoBorder,inputValidationWarningBackground:this.inputValidationWarningBackground,inputValidationWarningForeground:this.inputValidationWarningForeground,inputValidationWarningBorder:this.inputValidationWarningBorder,inputValidationErrorBackground:this.inputValidationErrorBackground,inputValidationErrorForeground:this.inputValidationErrorForeground,inputValidationErrorBorder:this.inputValidationErrorBorder,history:e,flexibleHeight:t,flexibleWidth:n,flexibleMaxHeight:i})),this.preserveCase=this._register(new pe({appendTitle:"",isChecked:!1,inputActiveOptionBorder:this.inputActiveOptionBorder})),this._register(this.preserveCase.onChange(function(e){r._onDidOptionChange.fire(e),!e&&r.fixFocusOnOptionClickEnabled&&r.inputBox.focus(),r.validate()})),this._register(this.preserveCase.onKeyDown(function(e){r._onPreserveCaseKeyDown.fire(e)})),this._showOptionButtons?this.cachedOptionsWidth=this.preserveCase.width():this.cachedOptionsWidth=0;var o=[this.preserveCase.domNode];this.onkeydown(this.domNode,function(e){if(e.equals(15)||e.equals(17)||e.equals(9)){var t=o.indexOf(document.activeElement);if(t>=0){var n=-1;e.equals(17)?n=(t+1)%o.length:e.equals(15)&&(n=0===t?o.length-1:t-1),e.equals(9)?o[t].blur():n>=0&&o[n].focus(),F.c.stop(e,!0)}}});var s=document.createElement("div");s.className="controls",s.style.display=this._showOptionButtons?"block":"none",s.appendChild(this.preserveCase.domNode),this.domNode.appendChild(s)},t.prototype.validate=function(){this.inputBox&&this.inputBox.validate()},Object.defineProperty(t.prototype,"width",{set:function(e){this.inputBox.paddingRight=this.cachedOptionsWidth,this.inputBox.width=e,this.domNode.style.width=e+"px"},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t}(j.a),me=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),ve=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},_e=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},be="historyNavigationWidget",ye="historyNavigationEnabled";function we(e,t){return e.getContext(document.activeElement).getValue(t)}function Ce(e,t){var n=function(e,t){return e.createScoped(t.target)}(e,t);return function(e,t,n){new k.d(n,t).bindTo(e)}(n,t,be),{scopedContextKeyService:n,historyNavigationEnablement:new k.d(ye,!0).bindTo(n)}}var Se=function(e){function t(t,n,i,r,o){void 0===o&&(o=!1);var s=e.call(this,t,n,o,i)||this;return s._register(Ce(r,{target:s.inputBox.element,historyNavigator:s.inputBox}).scopedContextKeyService),s}return me(t,e),t=ve([_e(3,k.c)],t)}(ce),xe=function(e){function t(t,n,i,r,o){void 0===o&&(o=!1);var s=e.call(this,t,n,o,i)||this;return s._register(Ce(r,{target:s.inputBox.element,historyNavigator:s.inputBox}).scopedContextKeyService),s}return me(t,e),t=ve([_e(3,k.c)],t)}(ge);le.a.registerCommandAndKeybindingRule({id:"history.showPrevious",weight:200,when:k.a.and(k.a.has(be),k.a.equals(ye,!0)),primary:16,secondary:[528],handler:function(e,t){var n=we(e.get(k.c),be);n&&n.historyNavigator.showPreviousValue()}}),le.a.registerCommandAndKeybindingRule({id:"history.showNext",weight:200,when:k.a.and(k.a.has(be),k.a.equals(ye,!0)),primary:18,secondary:[530],handler:function(e,t){var n=we(e.get(k.c),be);n&&n.historyNavigator.showNextValue()}});var Le=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Oe=i.a("label.find","Find"),ke=i.a("placeholder.find","Find"),Ne=i.a("label.previousMatchButton","Previous match"),Ee=i.a("label.nextMatchButton","Next match"),Ie=i.a("label.toggleSelectionFind","Find in selection"),De=i.a("label.closeButton","Close"),Me=i.a("label.replace","Replace"),Te=i.a("placeholder.replace","Replace"),Pe=i.a("label.replaceButton","Replace"),Ae=i.a("label.replaceAllButton","Replace All"),Re=i.a("label.toggleReplaceButton","Toggle Replace mode"),Fe=i.a("title.matchesCountLimit","Only the first {0} results are highlighted, but all find operations work on the entire text.",19999),je=i.a("label.matchesLocation","{0} of {1}"),We=i.a("label.noResults","No Results"),Be=69,Ve=17+(Be+3+1)+92+2,He=33,ze="ctrlEnterReplaceAll.windows.donotask",Ue=oe.d?256:2048,Ke=function(){return function(e){this.afterLineNumber=e,this.heightInPx=He,this.suppressMouseDown=!1,this.domNode=document.createElement("div"),this.domNode.className="dock-find-viewzone"}}();function qe(e,t,n){var i=!!t.match(/\n/);n&&i&&n.selectionStart>0&&e.stopPropagation()}function Ge(e,t,n){var i=!!t.match(/\n/);n&&i&&n.selectionEnd=0?F.f(this._domNode,"multipleline"):F.I(this._domNode,"multipleline");try{this._ignoreChangeEvent=!0,this._findInput.setValue(this._state.searchString)}finally{this._ignoreChangeEvent=!1}this._updateButtons()}if(e.replaceString&&(this._replaceInput.inputBox.value=this._state.replaceString),e.isRevealed&&(this._state.isRevealed?this._reveal():this._hide(!0)),e.isReplaceRevealed&&(this._state.isReplaceRevealed?this._codeEditor.getConfiguration().readOnly||this._isReplaceVisible||(this._isReplaceVisible=!0,this._replaceInput.width=F.B(this._findInput.domNode),this._updateButtons(),this._replaceInput.inputBox.layout()):this._isReplaceVisible&&(this._isReplaceVisible=!1,this._updateButtons())),(e.isRevealed||e.isReplaceRevealed)&&(this._state.isRevealed||this._state.isReplaceRevealed)&&this._tryUpdateHeight()&&this._showViewZone(),e.isRegex&&this._findInput.setRegex(this._state.isRegex),e.wholeWord&&this._findInput.setWholeWords(this._state.wholeWord),e.matchCase&&this._findInput.setCaseSensitive(this._state.matchCase),e.searchScope&&(this._state.searchScope?this._toggleSelectionFind.checked=!0:this._toggleSelectionFind.checked=!1,this._updateToggleSelectionFindButton()),e.searchString||e.matchesCount||e.matchesPosition){var t=this._state.searchString.length>0&&0===this._state.matchesCount;F.R(this._domNode,"no-results",t),this._updateMatchesCount(),this._updateButtons()}(e.searchString||e.currentMatch)&&this._layoutViewZone(),e.updateHistory&&this._delayedUpdateHistory()},t.prototype._delayedUpdateHistory=function(){this._updateHistoryDelayer.trigger(this._updateHistory.bind(this))},t.prototype._updateHistory=function(){this._state.searchString&&this._findInput.inputBox.addToHistory(),this._state.replaceString&&this._replaceInput.inputBox.addToHistory()},t.prototype._updateMatchesCount=function(){var e;if(this._matchesCount.style.minWidth=Be+"px",this._state.matchesCount>=19999?this._matchesCount.title=Fe:this._matchesCount.title="",this._matchesCount.firstChild&&this._matchesCount.removeChild(this._matchesCount.firstChild),this._state.matchesCount>0){var t=String(this._state.matchesCount);this._state.matchesCount>=19999&&(t+="+");var n=String(this._state.matchesPosition);"0"===n&&(n="?"),e=s.r(je,n,t)}else e=We;this._matchesCount.appendChild(document.createTextNode(e)),Object(ne.a)(this._getAriaLabel(e,this._state.currentMatch,this._state.searchString),!0),Be=Math.max(Be,this._matchesCount.clientWidth)},t.prototype._getAriaLabel=function(e,t,n){return e===We?""===n?i.a("ariaSearchNoResultEmpty","{0} found",e):i.a("ariaSearchNoResult","{0} found for {1}",e,n):t?i.a("ariaSearchNoResultWithLineNum","{0} found for {1} at {2}",e,n,t.startLineNumber+":"+t.startColumn):i.a("ariaSearchNoResultWithLineNumNoCurrentMatch","{0} found for {1}",e,n)},t.prototype._updateToggleSelectionFindButton=function(){var e=this._codeEditor.getSelection(),t=!!e&&(e.startLineNumber!==e.endLineNumber||e.startColumn!==e.endColumn),n=this._toggleSelectionFind.checked;this._toggleSelectionFind.setEnabled(this._isVisible&&(n||t))},t.prototype._updateButtons=function(){this._findInput.setEnabled(this._isVisible),this._replaceInput.setEnabled(this._isVisible&&this._isReplaceVisible),this._updateToggleSelectionFindButton(),this._closeBtn.setEnabled(this._isVisible);var e=this._state.searchString.length>0,t=!!this._state.matchesCount;this._prevBtn.setEnabled(this._isVisible&&e&&t),this._nextBtn.setEnabled(this._isVisible&&e&&t),this._replaceBtn.setEnabled(this._isVisible&&this._isReplaceVisible&&e),this._replaceAllBtn.setEnabled(this._isVisible&&this._isReplaceVisible&&e),F.R(this._domNode,"replaceToggled",this._isReplaceVisible),this._toggleReplaceBtn.toggleClass("collapse",!this._isReplaceVisible),this._toggleReplaceBtn.toggleClass("expand",this._isReplaceVisible),this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);var n=!this._codeEditor.getConfiguration().readOnly;this._toggleReplaceBtn.setEnabled(this._isVisible&&n)},t.prototype._reveal=function(){var e=this;if(!this._isVisible){this._isVisible=!0;var t=this._codeEditor.getSelection();!!t&&(t.startLineNumber!==t.endLineNumber||t.startColumn!==t.endColumn)&&this._codeEditor.getConfiguration().contribInfo.find.autoFindInSelection?this._toggleSelectionFind.checked=!0:this._toggleSelectionFind.checked=!1,this._tryUpdateWidgetWidth(),this._updateButtons(),setTimeout(function(){F.f(e._domNode,"visible"),e._domNode.setAttribute("aria-hidden","false")},0),setTimeout(function(){e._findInput.validate()},200),this._codeEditor.layoutOverlayWidget(this);var n=!0;if(this._codeEditor.getConfiguration().contribInfo.find.seedSearchStringFromSelection&&t){var i=this._codeEditor.getDomNode();if(i){var r=F.x(i),o=this._codeEditor.getScrolledVisiblePosition(t.getStartPosition()),s=r.left+(o?o.left:0),a=o?o.top:0;if(this._viewZone&&at.startLineNumber&&(n=!1);var u=F.z(this._domNode).left;s>u&&(n=!1);var c=this._codeEditor.getScrolledVisiblePosition(t.getEndPosition());r.left+(c?c.left:0)>u&&(n=!1)}}}this._showViewZone(n)}},t.prototype._hide=function(e){this._isVisible&&(this._isVisible=!1,this._updateButtons(),F.I(this._domNode,"visible"),this._domNode.setAttribute("aria-hidden","true"),this._findInput.clearMessage(),e&&this._codeEditor.focus(),this._codeEditor.layoutOverlayWidget(this),this._removeViewZone())},t.prototype._layoutViewZone=function(){var e=this;if(this._codeEditor.getConfiguration().contribInfo.find.addExtraSpaceOnTop){if(this._isVisible){var t=this._viewZone;void 0===this._viewZoneId&&t&&this._codeEditor.changeViewZones(function(n){t.heightInPx=e._getHeight(),e._viewZoneId=n.addZone(t),e._codeEditor.setScrollTop(e._codeEditor.getScrollTop()+t.heightInPx)})}}else this._removeViewZone()},t.prototype._showViewZone=function(e){var t=this;if((void 0===e&&(e=!0),this._isVisible)&&this._codeEditor.getConfiguration().contribInfo.find.addExtraSpaceOnTop){void 0===this._viewZone&&(this._viewZone=new Ke(0));var n=this._viewZone;this._codeEditor.changeViewZones(function(i){if(void 0!==t._viewZoneId){var r=t._getHeight();if(r===n.heightInPx)return;var o=r-n.heightInPx;return n.heightInPx=r,i.layoutZone(t._viewZoneId),void(e&&t._codeEditor.setScrollTop(t._codeEditor.getScrollTop()+o))}o=t._getHeight();n.heightInPx=o,t._viewZoneId=i.addZone(n),e&&t._codeEditor.setScrollTop(t._codeEditor.getScrollTop()+o)})}},t.prototype._removeViewZone=function(){var e=this;this._codeEditor.changeViewZones(function(t){void 0!==e._viewZoneId&&(t.removeZone(e._viewZoneId),e._viewZoneId=void 0,e._viewZone&&(e._codeEditor.setScrollTop(e._codeEditor.getScrollTop()-e._viewZone.heightInPx),e._viewZone=void 0))})},t.prototype._applyTheme=function(e){var t={inputActiveOptionBorder:e.getColor(m.V),inputActiveOptionBackground:e.getColor(m.U),inputBackground:e.getColor(m.W),inputForeground:e.getColor(m.Y),inputBorder:e.getColor(m.X),inputValidationInfoBackground:e.getColor(m._2),inputValidationInfoForeground:e.getColor(m._4),inputValidationInfoBorder:e.getColor(m._3),inputValidationWarningBackground:e.getColor(m._5),inputValidationWarningForeground:e.getColor(m._7),inputValidationWarningBorder:e.getColor(m._6),inputValidationErrorBackground:e.getColor(m.Z),inputValidationErrorForeground:e.getColor(m._1),inputValidationErrorBorder:e.getColor(m._0)};this._findInput.style(t),this._replaceInput.style(t)},t.prototype._tryUpdateWidgetWidth=function(){if(this._isVisible)if(this._codeEditor.getConfiguration().layoutInfo.contentWidth<=0)F.f(this._domNode,"hiddenEditor");else{F.C(this._domNode,"hiddenEditor")&&F.I(this._domNode,"hiddenEditor");var e=this._codeEditor.getConfiguration().layoutInfo.width,t=this._codeEditor.getConfiguration().layoutInfo.minimapWidth,n=!1,i=!1,r=!1;if(this._resized)if(F.B(this._domNode)>419)return this._domNode.style.maxWidth=e-28-t-15+"px",void(this._replaceInput.width=F.B(this._findInput.domNode));if(447+t>=e&&(i=!0),447+t-Be>=e&&(r=!0),447+t-Be>=e+50&&(n=!0),F.R(this._domNode,"collapsed-find-widget",n),F.R(this._domNode,"narrow-find-widget",r),F.R(this._domNode,"reduced-find-widget",i),r||n||(this._domNode.style.maxWidth=e-28-t-15+"px"),this._resized){this._findInput.inputBox.layout();var o=this._findInput.inputBox.width;o>0&&(this._replaceInput.width=o)}}},t.prototype._getHeight=function(){var e=0;return e+=4,e+=this._findInput.inputBox.height+2,this._isReplaceVisible&&(e+=4,e+=this._replaceInput.inputBox.height+2),e+=4},t.prototype._tryUpdateHeight=function(){var e=this._getHeight();return(null===this._cachedHeight||this._cachedHeight!==e)&&(this._cachedHeight=e,this._domNode.style.height=e+"px",!0)},t.prototype.focusFindInput=function(){this._findInput.select(),this._findInput.focus()},t.prototype.focusReplaceInput=function(){this._replaceInput.select(),this._replaceInput.focus()},t.prototype.highlightFindOptions=function(){this._findInput.highlightFindOptions()},t.prototype._updateSearchScope=function(){if(this._codeEditor.hasModel()&&this._toggleSelectionFind.checked){var e=this._codeEditor.getSelection();1===e.endColumn&&e.endLineNumber>e.startLineNumber&&(e=e.setEndPosition(e.endLineNumber-1,this._codeEditor.getModel().getLineMaxColumn(e.endLineNumber-1)));var t=this._state.currentMatch;e.startLineNumber!==e.endLineNumber&&(d.a.equalsRange(e,t)||this._state.change({searchScope:e},!0))}},t.prototype._onFindInputMouseDown=function(e){e.middleButton&&e.stopPropagation()},t.prototype._onFindInputKeyDown=function(e){if(e.equals(3|Ue)){var t=this._findInput.inputBox.inputElement,n=t.selectionStart,i=t.selectionEnd,r=t.value;if(null!==n&&null!==i){var o=r.substr(0,n)+"\n"+r.substr(i);return this._findInput.inputBox.value=o,t.setSelectionRange(n+1,n+1),this._findInput.inputBox.layout(),void e.preventDefault()}}return e.equals(2)?(this._isReplaceVisible?this._replaceInput.focus():this._findInput.focusOnCaseSensitive(),void e.preventDefault()):e.equals(2066)?(this._codeEditor.focus(),void e.preventDefault()):e.equals(16)?qe(e,this._findInput.getValue(),this._findInput.domNode.querySelector("textarea")):e.equals(18)?Ge(e,this._findInput.getValue(),this._findInput.domNode.querySelector("textarea")):void 0},t.prototype._onReplaceInputKeyDown=function(e){if(e.equals(3|Ue)){oe.g&&oe.e&&!this._ctrlEnterReplaceAllWarningPrompted&&(this._notificationService.info(i.a("ctrlEnter.keybindingChanged","Ctrl+Enter now inserts line break instead of replacing all. You can modify the keybinding for editor.action.replaceAll to override this behavior.")),this._ctrlEnterReplaceAllWarningPrompted=!0,this._storageService.store(ze,!0,0));var t=this._replaceInput.inputBox.inputElement,n=t.selectionStart,r=t.selectionEnd,o=t.value;if(null!==n&&null!==r){var s=o.substr(0,n)+"\n"+o.substr(r);return this._replaceInput.inputBox.value=s,t.setSelectionRange(n+1,n+1),this._replaceInput.inputBox.layout(),void e.preventDefault()}}return e.equals(2)?(this._findInput.focusOnCaseSensitive(),void e.preventDefault()):e.equals(1026)?(this._findInput.focus(),void e.preventDefault()):e.equals(2066)?(this._codeEditor.focus(),void e.preventDefault()):e.equals(16)?qe(e,this._replaceInput.inputBox.value,this._replaceInput.inputBox.element.querySelector("textarea")):e.equals(18)?Ge(e,this._replaceInput.inputBox.value,this._replaceInput.inputBox.element.querySelector("textarea")):void 0},t.prototype.getHorizontalSashTop=function(e){return 0},t.prototype.getHorizontalSashLeft=function(e){return 0},t.prototype.getHorizontalSashWidth=function(e){return 500},t.prototype._keybindingLabelFor=function(e){var t=this._keybindingService.lookupKeybinding(e);return t?" ("+t.getLabel()+")":""},t.prototype._buildDomNode=function(){var e=this;this._findInput=this._register(new Se(null,this._contextViewProvider,{width:221,label:Oe,placeholder:ke,appendCaseSensitiveLabel:this._keybindingLabelFor(A.ToggleCaseSensitiveCommand),appendWholeWordsLabel:this._keybindingLabelFor(A.ToggleWholeWordCommand),appendRegexLabel:this._keybindingLabelFor(A.ToggleRegexCommand),validation:function(t){if(0===t.length||!e._findInput.getRegex())return null;try{return new RegExp(t),null}catch(e){return{content:e.message}}},flexibleHeight:!0,flexibleWidth:!0,flexibleMaxHeight:118},this._contextKeyService,!0)),this._findInput.setRegex(!!this._state.isRegex),this._findInput.setCaseSensitive(!!this._state.matchCase),this._findInput.setWholeWords(!!this._state.wholeWord),this._register(this._findInput.onKeyDown(function(t){return e._onFindInputKeyDown(t)})),this._register(this._findInput.inputBox.onDidChange(function(){e._ignoreChangeEvent||e._state.change({searchString:e._findInput.getValue()},!0)})),this._register(this._findInput.onDidOptionChange(function(){e._state.change({isRegex:e._findInput.getRegex(),wholeWord:e._findInput.getWholeWords(),matchCase:e._findInput.getCaseSensitive()},!0)})),this._register(this._findInput.onCaseSensitiveKeyDown(function(t){t.equals(1026)&&e._isReplaceVisible&&(e._replaceInput.focus(),t.preventDefault())})),this._register(this._findInput.onRegexKeyDown(function(t){t.equals(2)&&e._isReplaceVisible&&(e._replaceInput.focusOnPreserve(),t.preventDefault())})),this._register(this._findInput.inputBox.onDidHeightChange(function(t){e._tryUpdateHeight()&&e._showViewZone()})),oe.c&&this._register(this._findInput.onMouseDown(function(t){return e._onFindInputMouseDown(t)})),this._matchesCount=document.createElement("div"),this._matchesCount.className="matchesCount",this._updateMatchesCount(),this._prevBtn=this._register(new Xe({label:Ne+this._keybindingLabelFor(A.PreviousMatchFindAction),className:"previous",onTrigger:function(){e._codeEditor.getAction(A.PreviousMatchFindAction).run().then(void 0,re.e)}})),this._nextBtn=this._register(new Xe({label:Ee+this._keybindingLabelFor(A.NextMatchFindAction),className:"next",onTrigger:function(){e._codeEditor.getAction(A.NextMatchFindAction).run().then(void 0,re.e)}}));var t=document.createElement("div");t.className="find-part",t.appendChild(this._findInput.domNode);var n=document.createElement("div");n.className="find-actions",t.appendChild(n),n.appendChild(this._matchesCount),n.appendChild(this._prevBtn.domNode),n.appendChild(this._nextBtn.domNode),this._toggleSelectionFind=this._register(new Ye({parent:n,title:Ie+this._keybindingLabelFor(A.ToggleSearchScopeCommand),onChange:function(){if(e._toggleSelectionFind.checked){if(e._codeEditor.hasModel()){var t=e._codeEditor.getSelection();1===t.endColumn&&t.endLineNumber>t.startLineNumber&&(t=t.setEndPosition(t.endLineNumber-1,e._codeEditor.getModel().getLineMaxColumn(t.endLineNumber-1))),t.isEmpty()||e._state.change({searchScope:t},!0)}}else e._state.change({searchScope:null},!0)}})),this._closeBtn=this._register(new Xe({label:De+this._keybindingLabelFor(A.CloseFindWidgetCommand),className:"close-fw",onTrigger:function(){e._state.change({isRevealed:!1,searchScope:null},!1)},onKeyDown:function(t){t.equals(2)&&e._isReplaceVisible&&(e._replaceBtn.isEnabled()?e._replaceBtn.focus():e._codeEditor.focus(),t.preventDefault())}})),n.appendChild(this._closeBtn.domNode),this._replaceInput=this._register(new xe(null,void 0,{label:Me,placeholder:Te,history:[],flexibleHeight:!0,flexibleWidth:!0,flexibleMaxHeight:118},this._contextKeyService,!0)),this._replaceInput.setPreserveCase(!!this._state.preserveCase),this._register(this._replaceInput.onKeyDown(function(t){return e._onReplaceInputKeyDown(t)})),this._register(this._replaceInput.inputBox.onDidChange(function(){e._state.change({replaceString:e._replaceInput.inputBox.value},!1)})),this._register(this._replaceInput.inputBox.onDidHeightChange(function(t){e._isReplaceVisible&&e._tryUpdateHeight()&&e._showViewZone()})),this._register(this._replaceInput.onDidOptionChange(function(){e._state.change({preserveCase:e._replaceInput.getPreserveCase()},!0)})),this._register(this._replaceInput.onPreserveCaseKeyDown(function(t){t.equals(2)&&(e._prevBtn.isEnabled()?e._prevBtn.focus():e._nextBtn.isEnabled()?e._nextBtn.focus():e._toggleSelectionFind.isEnabled()?e._toggleSelectionFind.focus():e._closeBtn.isEnabled()&&e._closeBtn.focus(),t.preventDefault())})),this._replaceBtn=this._register(new Xe({label:Pe+this._keybindingLabelFor(A.ReplaceOneAction),className:"replace",onTrigger:function(){e._controller.replace()},onKeyDown:function(t){t.equals(1026)&&(e._closeBtn.focus(),t.preventDefault())}})),this._replaceAllBtn=this._register(new Xe({label:Ae+this._keybindingLabelFor(A.ReplaceAllAction),className:"replace-all",onTrigger:function(){e._controller.replaceAll()}}));var i=document.createElement("div");i.className="replace-part",i.appendChild(this._replaceInput.domNode);var r=document.createElement("div");r.className="replace-actions",i.appendChild(r),r.appendChild(this._replaceBtn.domNode),r.appendChild(this._replaceAllBtn.domNode),this._toggleReplaceBtn=this._register(new Xe({label:Re,className:"toggle left",onTrigger:function(){e._state.change({isReplaceRevealed:!e._isReplaceVisible},!1),e._isReplaceVisible&&(e._replaceInput.width=F.B(e._findInput.domNode),e._replaceInput.inputBox.layout()),e._showViewZone()}})),this._toggleReplaceBtn.toggleClass("expand",this._isReplaceVisible),this._toggleReplaceBtn.toggleClass("collapse",!this._isReplaceVisible),this._toggleReplaceBtn.setExpanded(this._isReplaceVisible),this._domNode=document.createElement("div"),this._domNode.className="editor-widget find-widget",this._domNode.setAttribute("aria-hidden","true"),this._domNode.style.width="419px",this._domNode.appendChild(this._toggleReplaceBtn.domNode),this._domNode.appendChild(t),this._domNode.appendChild(i),this._resizeSash=new ie.a(this._domNode,this,{orientation:0}),this._resized=!1;var o=419;this._register(this._resizeSash.onDidStart(function(){o=F.B(e._domNode)})),this._register(this._resizeSash.onDidChange(function(t){e._resized=!0;var n=o+t.startX-t.currentX;if(!(n<419)){var i=n-Ve;n>(parseFloat(F.u(e._domNode).maxWidth)||0)||(e._domNode.style.width=n+"px",e._findInput.inputBox.width=i,e._isReplaceVisible&&(e._replaceInput.width=F.B(e._findInput.domNode)),e._findInput.inputBox.layout(),e._tryUpdateHeight())}})),this._register(this._resizeSash.onDidReset(function(){var t=F.B(e._domNode);if(!(t<419)){var n=419;e._resized&&419!==t||(n=e._codeEditor.getConfiguration().layoutInfo.width-28-e._codeEditor.getConfiguration().layoutInfo.minimapWidth-15,e._resized=!0);var i=n-Ve;e._domNode.style.width=n+"px",e._findInput.inputBox.width=i,e._isReplaceVisible&&(e._replaceInput.width=F.B(e._findInput.domNode)),e._findInput.inputBox.layout()}}))},t.prototype.updateAccessibilitySupport=function(){var e=this._codeEditor.getConfiguration().accessibilitySupport;this._findInput.setFocusInputOnOptionClick(2!==e)},t.ID="editor.contrib.findWidget",t}(j.a),Ye=function(e){function t(n){var i=e.call(this)||this;return i._opts=n,i._domNode=document.createElement("div"),i._domNode.className="monaco-checkbox",i._domNode.title=i._opts.title,i._domNode.tabIndex=0,i._checkbox=document.createElement("input"),i._checkbox.type="checkbox",i._checkbox.className="checkbox",i._checkbox.id="checkbox-"+t._COUNTER++,i._checkbox.tabIndex=-1,i._label=document.createElement("label"),i._label.className="label",i._label.htmlFor=i._checkbox.id,i._label.tabIndex=-1,i._domNode.appendChild(i._checkbox),i._domNode.appendChild(i._label),i._opts.parent.appendChild(i._domNode),i.onchange(i._checkbox,function(){i._opts.onChange()}),i}return Le(t,e),Object.defineProperty(t.prototype,"domNode",{get:function(){return this._domNode},enumerable:!0,configurable:!0}),t.prototype.isEnabled=function(){return this._domNode.tabIndex>=0},Object.defineProperty(t.prototype,"checked",{get:function(){return this._checkbox.checked},set:function(e){this._checkbox.checked=e},enumerable:!0,configurable:!0}),t.prototype.focus=function(){this._domNode.focus()},t.prototype.enable=function(){this._checkbox.removeAttribute("disabled")},t.prototype.disable=function(){this._checkbox.disabled=!0},t.prototype.setEnabled=function(e){e?(this.enable(),this.domNode.tabIndex=0):(this.disable(),this.domNode.tabIndex=-1)},t._COUNTER=0,t}(j.a),Xe=function(e){function t(t){var n=e.call(this)||this;return n._opts=t,n._domNode=document.createElement("div"),n._domNode.title=n._opts.label,n._domNode.tabIndex=0,n._domNode.className="button "+n._opts.className,n._domNode.setAttribute("role","button"),n._domNode.setAttribute("aria-label",n._opts.label),n.onclick(n._domNode,function(e){n._opts.onTrigger(),e.preventDefault()}),n.onkeydown(n._domNode,function(e){if(e.equals(10)||e.equals(3))return n._opts.onTrigger(),void e.preventDefault();n._opts.onKeyDown&&n._opts.onKeyDown(e)}),n}return Le(t,e),Object.defineProperty(t.prototype,"domNode",{get:function(){return this._domNode},enumerable:!0,configurable:!0}),t.prototype.isEnabled=function(){return this._domNode.tabIndex>=0},t.prototype.focus=function(){this._domNode.focus()},t.prototype.setEnabled=function(e){F.R(this._domNode,"disabled",!e),this._domNode.setAttribute("aria-disabled",String(!e)),this._domNode.tabIndex=e?0:-1},t.prototype.setExpanded=function(e){this._domNode.setAttribute("aria-expanded",String(!!e))},t.prototype.toggleClass=function(e,t){F.R(this._domNode,e,t)},t}(j.a);Object(v.f)(function(e,t){var n=function(e,n){n&&t.addRule(".monaco-editor "+e+" { background-color: "+n+"; }")};n(".findMatch",e.getColor(m.t)),n(".currentFindMatch",e.getColor(m.r)),n(".findScope",e.getColor(m.v)),n(".find-widget",e.getColor(m.N));var i=e.getColor(m._48);i&&t.addRule(".monaco-editor .find-widget { box-shadow: 0 2px 8px "+i+"; }");var r=e.getColor(m.u);r&&t.addRule(".monaco-editor .findMatch { border: 1px "+("hc"===e.type?"dotted":"solid")+" "+r+"; box-sizing: border-box; }");var o=e.getColor(m.s);o&&t.addRule(".monaco-editor .currentFindMatch { border: 2px solid "+o+"; padding: 1px; box-sizing: border-box; }");var s=e.getColor(m.w);s&&t.addRule(".monaco-editor .findScope { border: 1px "+("hc"===e.type?"dashed":"solid")+" "+s+"; }");var a=e.getColor(m.e);a&&t.addRule(".monaco-editor .find-widget { border: 2px solid "+a+"; }");var u=e.getColor(m.P);u&&t.addRule(".monaco-editor .find-widget { color: "+u+"; }");var c=e.getColor(m.R);c&&t.addRule(".monaco-editor .find-widget.no-results .matchesCount { color: "+c+"; }");var l=e.getColor(m.Q);if(l)t.addRule(".monaco-editor .find-widget .monaco-sash { background-color: "+l+"; width: 3px !important; margin-left: -4px;}");else{var d=e.getColor(m.O);d&&t.addRule(".monaco-editor .find-widget .monaco-sash { background-color: "+d+"; width: 3px !important; margin-left: -4px;}")}var h=e.getColor(m.V);h&&t.addRule(".monaco-editor .find-widget .monaco-checkbox .checkbox:checked + .label { border: 1px solid "+h.toString()+"; }");var f=e.getColor(m.U);f&&t.addRule(".monaco-editor .find-widget .monaco-checkbox .checkbox:checked + .label { background-color: "+f.toString()+"; }");var p=e.getColor(m.S);p&&t.addRule(".monaco-workbench .monaco-editor .find-widget .monaco-inputbox.synthetic-focus { outline-color: "+p+"; }")});var $e=n("44YW"),Je=n("yO/1"),Qe=n("JVO/"),et=n("NqM+"),tt=n("Cfmk"),nt=n("fAkY");t.getSelectionSearchString=at,n.d(t,"CommonFindController",function(){return ut}),n.d(t,"FindController",function(){return ct}),n.d(t,"StartFindAction",function(){return lt}),n.d(t,"StartFindWithSelectionAction",function(){return dt}),n.d(t,"MatchFindAction",function(){return ht}),n.d(t,"NextMatchFindAction",function(){return ft}),n.d(t,"NextMatchFindAction2",function(){return pt}),n.d(t,"PreviousMatchFindAction",function(){return gt}),n.d(t,"PreviousMatchFindAction2",function(){return mt}),n.d(t,"SelectionMatchFindAction",function(){return vt}),n.d(t,"NextSelectionMatchFindAction",function(){return _t}),n.d(t,"PreviousSelectionMatchFindAction",function(){return bt}),n.d(t,"StartFindReplaceAction",function(){return yt});var it=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),rt=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},ot=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},st=524288;function at(e){if(!e.hasModel())return null;var t=e.getSelection();if(t.startLineNumber===t.endLineNumber)if(t.isEmpty()){var n=e.getModel().getWordAtPosition(t.getStartPosition());if(n)return n.word}else if(e.getModel().getValueLengthInRange(t)e.startLineNumber&&(e=e.setEndPosition(e.endLineNumber-1,this._editor.getModel().getLineMaxColumn(e.endLineNumber-1))),e.isEmpty()||this._state.change({searchScope:e},!0)}},t.prototype.setSearchString=function(e){this._state.isRegex&&(e=s.p(e)),this._state.change({searchString:e},!1)},t.prototype.highlightFindOptions=function(){},t.prototype._start=function(e){if(this.disposeModel(),this._editor.hasModel()){var t,n={isRevealed:!0};if(e.seedSearchStringFromSelection)(t=at(this._editor))&&(this._state.isRegex?n.searchString=s.p(t):n.searchString=t);if(!n.searchString&&e.seedSearchStringFromGlobalClipboard)(t=this.getGlobalBufferTerm())&&(n.searchString=t);if(e.forceRevealReplace?n.isReplaceRevealed=!0:this._findWidgetVisible.get()||(n.isReplaceRevealed=!1),e.updateSearchScope){var i=this._editor.getSelection();i.isEmpty()||(n.searchScope=i)}this._state.change(n,!1),this._model||(this._model=new R(this._editor,this._state))}},t.prototype.start=function(e){this._start(e)},t.prototype.moveToNextMatch=function(){return!!this._model&&(this._model.moveToNextMatch(),!0)},t.prototype.moveToPrevMatch=function(){return!!this._model&&(this._model.moveToPrevMatch(),!0)},t.prototype.replace=function(){return!!this._model&&(this._model.replace(),!0)},t.prototype.replaceAll=function(){return!!this._model&&(this._model.replaceAll(),!0)},t.prototype.selectAllMatches=function(){return!!this._model&&(this._model.selectAllMatches(),this._editor.focus(),!0)},t.prototype.getGlobalBufferTerm=function(){return this._editor.getConfiguration().contribInfo.find.globalFindClipboard&&this._clipboardService&&this._editor.hasModel()&&!this._editor.getModel().isTooLargeForSyncing()?this._clipboardService.readFindText():""},t.prototype.setGlobalBufferTerm=function(e){this._editor.getConfiguration().contribInfo.find.globalFindClipboard&&this._clipboardService&&this._editor.hasModel()&&!this._editor.getModel().isTooLargeForSyncing()&&this._clipboardService.writeFindText(e)},t.ID="editor.contrib.findController",t=rt([ot(1,k.c),ot(2,tt.a),ot(3,$e.a)],t)}(o.a),ct=function(e){function t(t,n,i,r,o,s,a,u){var c=e.call(this,t,i,a,u)||this;return c._contextViewService=n,c._keybindingService=r,c._themeService=o,c._notificationService=s,c._widget=null,c._findOptionsWidget=null,c}return it(t,e),t.prototype._start=function(t){this._widget||this._createFindWidget(),!this._widget.getPosition()&&this._editor.getConfiguration().contribInfo.find.autoFindInSelection&&(t.updateSearchScope=!0),e.prototype._start.call(this,t),2===t.shouldFocus?this._widget.focusReplaceInput():1===t.shouldFocus&&this._widget.focusFindInput()},t.prototype.highlightFindOptions=function(){this._widget||this._createFindWidget(),this._state.isRevealed?this._widget.highlightFindOptions():this._findOptionsWidget.highlightFindOptions()},t.prototype._createFindWidget=function(){this._widget=this._register(new Ze(this._editor,this,this._state,this._contextViewService,this._keybindingService,this._contextKeyService,this._themeService,this._storageService,this._notificationService)),this._findOptionsWidget=this._register(new Q(this._editor,this._state,this._keybindingService,this._themeService))},t=rt([ot(1,Je.b),ot(2,k.c),ot(3,et.a),ot(4,v.c),ot(5,nt.a),ot(6,tt.a),ot(7,Object(Qe.d)($e.a))],t)}(ut),lt=function(e){function t(){return e.call(this,{id:A.StartFindAction,label:i.a("startFindAction","Find"),alias:"Find",precondition:void 0,kbOpts:{kbExpr:null,primary:2084,weight:100},menubarOpts:{menuId:14,group:"3_find",title:i.a({key:"miFind",comment:["&& denotes a mnemonic"]},"&&Find"),order:1}})||this}return it(t,e),t.prototype.run=function(e,t){var n=ut.get(t);n&&n.start({forceRevealReplace:!1,seedSearchStringFromSelection:t.getConfiguration().contribInfo.find.seedSearchStringFromSelection,seedSearchStringFromGlobalClipboard:t.getConfiguration().contribInfo.find.globalFindClipboard,shouldFocus:1,shouldAnimate:!0,updateSearchScope:!1})},t}(a.b),dt=function(e){function t(){return e.call(this,{id:A.StartFindWithSelection,label:i.a("startFindWithSelectionAction","Find With Selection"),alias:"Find With Selection",precondition:void 0,kbOpts:{kbExpr:null,primary:0,mac:{primary:2083},weight:100}})||this}return it(t,e),t.prototype.run=function(e,t){var n=ut.get(t);n&&(n.start({forceRevealReplace:!1,seedSearchStringFromSelection:!0,seedSearchStringFromGlobalClipboard:!1,shouldFocus:1,shouldAnimate:!0,updateSearchScope:!1}),n.setGlobalBufferTerm(n.getState().searchString))},t}(a.b),ht=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return it(t,e),t.prototype.run=function(e,t){var n=ut.get(t);n&&!this._run(n)&&(n.start({forceRevealReplace:!1,seedSearchStringFromSelection:0===n.getState().searchString.length&&t.getConfiguration().contribInfo.find.seedSearchStringFromSelection,seedSearchStringFromGlobalClipboard:!0,shouldFocus:0,shouldAnimate:!0,updateSearchScope:!1}),this._run(n))},t}(a.b),ft=function(e){function t(){return e.call(this,{id:A.NextMatchFindAction,label:i.a("findNextMatchAction","Find Next"),alias:"Find Next",precondition:void 0,kbOpts:{kbExpr:u.a.focus,primary:61,mac:{primary:2085,secondary:[61]},weight:100}})||this}return it(t,e),t.prototype._run=function(e){return e.moveToNextMatch()},t}(ht),pt=function(e){function t(){return e.call(this,{id:A.NextMatchFindAction,label:i.a("findNextMatchAction","Find Next"),alias:"Find Next",precondition:void 0,kbOpts:{kbExpr:k.a.and(u.a.focus,E),primary:3,weight:100}})||this}return it(t,e),t.prototype._run=function(e){return e.moveToNextMatch()},t}(ht),gt=function(e){function t(){return e.call(this,{id:A.PreviousMatchFindAction,label:i.a("findPreviousMatchAction","Find Previous"),alias:"Find Previous",precondition:void 0,kbOpts:{kbExpr:u.a.focus,primary:1085,mac:{primary:3109,secondary:[1085]},weight:100}})||this}return it(t,e),t.prototype._run=function(e){return e.moveToPrevMatch()},t}(ht),mt=function(e){function t(){return e.call(this,{id:A.PreviousMatchFindAction,label:i.a("findPreviousMatchAction","Find Previous"),alias:"Find Previous",precondition:void 0,kbOpts:{kbExpr:k.a.and(u.a.focus,E),primary:1027,weight:100}})||this}return it(t,e),t.prototype._run=function(e){return e.moveToPrevMatch()},t}(ht),vt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return it(t,e),t.prototype.run=function(e,t){var n=ut.get(t);if(n){var i=at(t);i&&n.setSearchString(i),this._run(n)||(n.start({forceRevealReplace:!1,seedSearchStringFromSelection:t.getConfiguration().contribInfo.find.seedSearchStringFromSelection,seedSearchStringFromGlobalClipboard:!1,shouldFocus:0,shouldAnimate:!0,updateSearchScope:!1}),this._run(n))}},t}(a.b),_t=function(e){function t(){return e.call(this,{id:A.NextSelectionMatchFindAction,label:i.a("nextSelectionMatchFindAction","Find Next Selection"),alias:"Find Next Selection",precondition:void 0,kbOpts:{kbExpr:u.a.focus,primary:2109,weight:100}})||this}return it(t,e),t.prototype._run=function(e){return e.moveToNextMatch()},t}(vt),bt=function(e){function t(){return e.call(this,{id:A.PreviousSelectionMatchFindAction,label:i.a("previousSelectionMatchFindAction","Find Previous Selection"),alias:"Find Previous Selection",precondition:void 0,kbOpts:{kbExpr:u.a.focus,primary:3133,weight:100}})||this}return it(t,e),t.prototype._run=function(e){return e.moveToPrevMatch()},t}(vt),yt=function(e){function t(){return e.call(this,{id:A.StartFindReplaceAction,label:i.a("startReplace","Replace"),alias:"Replace",precondition:void 0,kbOpts:{kbExpr:null,primary:2086,mac:{primary:2596},weight:100},menubarOpts:{menuId:14,group:"3_find",title:i.a({key:"miReplace",comment:["&& denotes a mnemonic"]},"&&Replace"),order:2}})||this}return it(t,e),t.prototype.run=function(e,t){if(t.hasModel()&&!t.getConfiguration().readOnly){var n=ut.get(t),i=t.getSelection(),r=n.isFindInputFocused(),o=!i.isEmpty()&&i.startLineNumber===i.endLineNumber&&t.getConfiguration().contribInfo.find.seedSearchStringFromSelection&&!r,s=r||o?2:1;n&&n.start({forceRevealReplace:!0,seedSearchStringFromSelection:o,seedSearchStringFromGlobalClipboard:t.getConfiguration().contribInfo.find.seedSearchStringFromSelection,shouldFocus:s,shouldAnimate:!0,updateSearchScope:!1})}},t}(a.b);Object(a.h)(ct),Object(a.f)(lt),Object(a.f)(dt),Object(a.f)(ft),Object(a.f)(pt),Object(a.f)(gt),Object(a.f)(mt),Object(a.f)(_t),Object(a.f)(bt),Object(a.f)(yt);var wt=a.c.bindToContribution(ut.get);Object(a.g)(new wt({id:A.CloseFindWidgetCommand,precondition:N,handler:function(e){return e.closeFindWidget()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:9,secondary:[1033]}})),Object(a.g)(new wt({id:A.ToggleCaseSensitiveCommand,precondition:void 0,handler:function(e){return e.toggleCaseSensitive()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:D.primary,mac:D.mac,win:D.win,linux:D.linux}})),Object(a.g)(new wt({id:A.ToggleWholeWordCommand,precondition:void 0,handler:function(e){return e.toggleWholeWords()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:M.primary,mac:M.mac,win:M.win,linux:M.linux}})),Object(a.g)(new wt({id:A.ToggleRegexCommand,precondition:void 0,handler:function(e){return e.toggleRegex()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:T.primary,mac:T.mac,win:T.win,linux:T.linux}})),Object(a.g)(new wt({id:A.ToggleSearchScopeCommand,precondition:void 0,handler:function(e){return e.toggleSearchScope()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:P.primary,mac:P.mac,win:P.win,linux:P.linux}})),Object(a.g)(new wt({id:A.ReplaceOneAction,precondition:N,handler:function(e){return e.replace()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:3094}})),Object(a.g)(new wt({id:A.ReplaceOneAction,precondition:N,handler:function(e){return e.replace()},kbOpts:{weight:105,kbExpr:k.a.and(u.a.focus,I),primary:3}})),Object(a.g)(new wt({id:A.ReplaceAllAction,precondition:N,handler:function(e){return e.replaceAll()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:2563}})),Object(a.g)(new wt({id:A.ReplaceAllAction,precondition:N,handler:function(e){return e.replaceAll()},kbOpts:{weight:105,kbExpr:k.a.and(u.a.focus,I),primary:void 0,mac:{primary:2051}}})),Object(a.g)(new wt({id:A.SelectAllMatchesAction,precondition:N,handler:function(e){return e.selectAllMatches()},kbOpts:{weight:105,kbExpr:u.a.focus,primary:515}}))},T1Vy:function(e,t){var n="[object Number]",i=Object.prototype.toString;e.exports=function(e){return"number"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},TNPA:function(e,t,n){"use strict";function i(e,t){var n=Math.pow(10,t);return Math.round(e*n)/n}n.d(t,"c",function(){return r}),n.d(t,"b",function(){return s}),n.d(t,"a",function(){return a});var r=function(){function e(e,t,n,r){void 0===r&&(r=1),this.r=0|Math.min(255,Math.max(0,e)),this.g=0|Math.min(255,Math.max(0,t)),this.b=0|Math.min(255,Math.max(0,n)),this.a=i(Math.max(Math.min(1,r),0),3)}return e.equals=function(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a},e}(),o=function(){function e(e,t,n,r){this.h=0|Math.max(Math.min(360,e),0),this.s=i(Math.max(Math.min(1,t),0),3),this.l=i(Math.max(Math.min(1,n),0),3),this.a=i(Math.max(Math.min(1,r),0),3)}return e.equals=function(e,t){return e.h===t.h&&e.s===t.s&&e.l===t.l&&e.a===t.a},e.fromRGBA=function(t){var n=t.r/255,i=t.g/255,r=t.b/255,o=t.a,s=Math.max(n,i,r),a=Math.min(n,i,r),u=0,c=0,l=(a+s)/2,d=s-a;if(d>0){switch(c=Math.min(l<=.5?d/(2*l):d/(2-2*l),1),s){case n:u=(i-r)/d+(i1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e},e.toRGBA=function(t){var n,i,o,s=t.h/360,a=t.s,u=t.l,c=t.a;if(0===a)n=i=o=u;else{var l=u<.5?u*(1+a):u+a-u*a,d=2*u-l;n=e._hue2rgb(d,l,s+1/3),i=e._hue2rgb(d,l,s),o=e._hue2rgb(d,l,s-1/3)}return new r(Math.round(255*n),Math.round(255*i),Math.round(255*o),c)},e}(),s=function(){function e(e,t,n,r){this.h=0|Math.max(Math.min(360,e),0),this.s=i(Math.max(Math.min(1,t),0),3),this.v=i(Math.max(Math.min(1,n),0),3),this.a=i(Math.max(Math.min(1,r),0),3)}return e.equals=function(e,t){return e.h===t.h&&e.s===t.s&&e.v===t.v&&e.a===t.a},e.fromRGBA=function(t){var n,i=t.r/255,r=t.g/255,o=t.b/255,s=Math.max(i,r,o),a=s-Math.min(i,r,o),u=0===s?0:a/s;return n=0===a?0:s===i?((r-o)/a%6+6)%6:s===r?(o-i)/a+2:(i-r)/a+4,new e(Math.round(60*n),u,s,t.a)},e.toRGBA=function(e){var t=e.h,n=e.s,i=e.v,o=e.a,s=i*n,a=s*(1-Math.abs(t/60%2-1)),u=i-s,c=[0,0,0],l=c[0],d=c[1],h=c[2];return t<60?(l=s,d=a):t<120?(l=a,d=s):t<180?(d=s,h=a):t<240?(d=a,h=s):t<300?(l=a,h=s):t<360&&(l=s,h=a),l=Math.round(255*(l+u)),d=Math.round(255*(d+u)),h=Math.round(255*(h+u)),new r(l,d,h,o)},e}(),a=function(){function e(e){if(!e)throw new Error("Color needs a value");if(e instanceof r)this.rgba=e;else if(e instanceof o)this._hsla=e,this.rgba=o.toRGBA(e);else{if(!(e instanceof s))throw new Error("Invalid color ctor argument");this._hsva=e,this.rgba=s.toRGBA(e)}}return e.fromHex=function(t){return e.Format.CSS.parseHex(t)||e.red},Object.defineProperty(e.prototype,"hsla",{get:function(){return this._hsla?this._hsla:o.fromRGBA(this.rgba)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hsva",{get:function(){return this._hsva?this._hsva:s.fromRGBA(this.rgba)},enumerable:!0,configurable:!0}),e.prototype.equals=function(e){return!!e&&r.equals(this.rgba,e.rgba)&&o.equals(this.hsla,e.hsla)&&s.equals(this.hsva,e.hsva)},e.prototype.getRelativeLuminance=function(){return i(.2126*e._relativeLuminanceForComponent(this.rgba.r)+.7152*e._relativeLuminanceForComponent(this.rgba.g)+.0722*e._relativeLuminanceForComponent(this.rgba.b),4)},e._relativeLuminanceForComponent=function(e){var t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)},e.prototype.isLighter=function(){return(299*this.rgba.r+587*this.rgba.g+114*this.rgba.b)/1e3>=128},e.prototype.isLighterThan=function(e){return this.getRelativeLuminance()>e.getRelativeLuminance()},e.prototype.isDarkerThan=function(e){return this.getRelativeLuminance()-1&&e%1==0&&e-1&&e%1==0&&e<=i}(e.length)&&!function(e){var t=M(e)?S.call(e):"";return t==a||t==u}(e)}function M(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function T(e){return!!e&&"object"==typeof e}e.exports=function(e,t,i,s){var a;e=D(e)?e:(a=e)?_(a,function(e){return D(e)?k(e):N(e)}(a)):[],i=i&&!s?function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||T(e)&&S.call(e)==l}(e))return o;if(M(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=M(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(d,"");var n=f.test(e);return n||p.test(e)?m(e.slice(2),n?2:8):h.test(e)?o:+e}(e))===n||e===-n){var t=e<0?-1:1;return t*r}return e==e?e:0}(e),i=t%1;return t==t?i?t-i:t:0}(i):0;var u=e.length;return i<0&&(i=O(u+i,0)),function(e){return"string"==typeof e||!I(e)&&T(e)&&S.call(e)==c}(e)?i<=u&&e.indexOf(t,i)>-1:!!u&&function(e,t,n){if(t!=t)return function(e,t,n,i){for(var r=e.length,o=n+(i?1:-1);i?o--:++o-1}},TU7t:function(e,t,n){"use strict";t.c=function e(t){if(!t||"object"!=typeof t)return t;if(t instanceof RegExp)return t;var n=Array.isArray(t)?[]:{};Object.keys(t).forEach(function(i){t[i]&&"object"==typeof t[i]?n[i]=e(t[i]):n[i]=t[i]});return n},t.d=function(e){if(!e||"object"!=typeof e)return e;var t=[e];for(;t.length>0;){var n=t.shift();for(var i in Object.freeze(n),n)if(r.call(n,i)){var o=n[i];"object"!=typeof o||Object.isFrozen(o)||t.push(o)}}return e},t.b=function(e,t){return function e(t,n,o){if(Object(i.k)(t))return t;var s=n(t);if(void 0!==s)return s;if(Object(i.c)(t)){for(var a=[],u=0,c=t;u console.log` because `log` has been completed recently."),r.a("suggestSelection.recentlyUsedByPrefix","Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`.")],default:"recentlyUsed",description:r.a("suggestSelection","Controls how suggestions are pre-selected when showing the suggest list.")},"editor.suggestFontSize":{type:"integer",default:0,minimum:0,markdownDescription:r.a("suggestFontSize","Font size for the suggest widget. When set to `0`, the value of `#editor.fontSize#` is used.")},"editor.suggestLineHeight":{type:"integer",default:0,minimum:0,markdownDescription:r.a("suggestLineHeight","Line height for the suggest widget. When set to `0`, the value of `#editor.lineHeight#` is used.")},"editor.tabCompletion":{type:"string",default:"off",enum:["on","off","onlySnippets"],enumDescriptions:[r.a("tabCompletion.on","Tab complete will insert the best matching suggestion when pressing tab."),r.a("tabCompletion.off","Disable tab completions."),r.a("tabCompletion.onlySnippets","Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.")],description:r.a("tabCompletion","Enables tab completions.")},"editor.suggest.filterGraceful":{type:"boolean",default:!0,description:r.a("suggest.filterGraceful","Controls whether filtering and sorting suggestions accounts for small typos.")},"editor.suggest.localityBonus":{type:"boolean",default:!1,description:r.a("suggest.localityBonus","Controls whether sorting favours words that appear close to the cursor.")},"editor.suggest.shareSuggestSelections":{type:"boolean",default:!1,markdownDescription:r.a("suggest.shareSuggestSelections","Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).")},"editor.suggest.snippetsPreventQuickSuggestions":{type:"boolean",default:!0,description:r.a("suggest.snippetsPreventQuickSuggestions","Control whether an active snippet prevents quick suggestions.")},"editor.suggest.showIcons":{type:"boolean",default:g.contribInfo.suggest.showIcons,description:r.a("suggest.showIcons","Controls whether to show or hide icons in suggestions.")},"editor.suggest.maxVisibleSuggestions":{type:"number",default:g.contribInfo.suggest.maxVisibleSuggestions,minimum:1,maximum:15,description:r.a("suggest.maxVisibleSuggestions","Controls how many suggestions IntelliSense will show before showing a scrollbar (maximum 15).")},"editor.suggest.filteredTypes":{type:"object",default:{keyword:!0,snippet:!0},markdownDescription:r.a("suggest.filtered","Controls whether some suggestion types should be filtered from IntelliSense. A list of suggestion types can be found here: https://code.visualstudio.com/docs/editor/intellisense#_types-of-completions."),properties:{method:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.method","When set to `false` IntelliSense never shows `method` suggestions.")},function:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.function","When set to `false` IntelliSense never shows `function` suggestions.")},constructor:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.constructor","When set to `false` IntelliSense never shows `constructor` suggestions.")},field:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.field","When set to `false` IntelliSense never shows `field` suggestions.")},variable:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.variable","When set to `false` IntelliSense never shows `variable` suggestions.")},class:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.class","When set to `false` IntelliSense never shows `class` suggestions.")},struct:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.struct","When set to `false` IntelliSense never shows `struct` suggestions.")},interface:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.interface","When set to `false` IntelliSense never shows `interface` suggestions.")},module:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.module","When set to `false` IntelliSense never shows `module` suggestions.")},property:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.property","When set to `false` IntelliSense never shows `property` suggestions.")},event:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.event","When set to `false` IntelliSense never shows `event` suggestions.")},operator:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.operator","When set to `false` IntelliSense never shows `operator` suggestions.")},unit:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.unit","When set to `false` IntelliSense never shows `unit` suggestions.")},value:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.value","When set to `false` IntelliSense never shows `value` suggestions.")},constant:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.constant","When set to `false` IntelliSense never shows `constant` suggestions.")},enum:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.enum","When set to `false` IntelliSense never shows `enum` suggestions.")},enumMember:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.enumMember","When set to `false` IntelliSense never shows `enumMember` suggestions.")},keyword:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.keyword","When set to `false` IntelliSense never shows `keyword` suggestions.")},text:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.text","When set to `false` IntelliSense never shows `text` suggestions.")},color:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.color","When set to `false` IntelliSense never shows `color` suggestions.")},file:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.file","When set to `false` IntelliSense never shows `file` suggestions.")},reference:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.reference","When set to `false` IntelliSense never shows `reference` suggestions.")},customcolor:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.customcolor","When set to `false` IntelliSense never shows `customcolor` suggestions.")},folder:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.folder","When set to `false` IntelliSense never shows `folder` suggestions.")},typeParameter:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.typeParameter","When set to `false` IntelliSense never shows `typeParameter` suggestions.")},snippet:{type:"boolean",default:!0,markdownDescription:r.a("suggest.filtered.snippet","When set to `false` IntelliSense never shows `snippet` suggestions.")}}},"editor.gotoLocation.multiple":{description:r.a("editor.gotoLocation.multiple","Controls the behavior of 'Go To' commands, like Go To Definition, when multiple target locations exist."),type:"string",enum:["peek","gotoAndPeek","goto"],default:g.contribInfo.gotoLocation.multiple,enumDescriptions:[r.a("editor.gotoLocation.multiple.peek","Show peek view of the results (default)"),r.a("editor.gotoLocation.multiple.gotoAndPeek","Go to the primary result and show a peek view"),r.a("editor.gotoLocation.multiple.goto","Go to the primary result and enable peek-less navigation to others")]},"editor.selectionHighlight":{type:"boolean",default:g.contribInfo.selectionHighlight,description:r.a("selectionHighlight","Controls whether the editor should highlight matches similar to the selection.")},"editor.occurrencesHighlight":{type:"boolean",default:g.contribInfo.occurrencesHighlight,description:r.a("occurrencesHighlight","Controls whether the editor should highlight semantic symbol occurrences.")},"editor.overviewRulerLanes":{type:"integer",default:3,description:r.a("overviewRulerLanes","Controls the number of decorations that can show up at the same position in the overview ruler.")},"editor.overviewRulerBorder":{type:"boolean",default:g.viewInfo.overviewRulerBorder,description:r.a("overviewRulerBorder","Controls whether a border should be drawn around the overview ruler.")},"editor.cursorBlinking":{type:"string",enum:["blink","smooth","phase","expand","solid"],default:c.h(g.viewInfo.cursorBlinking),description:r.a("cursorBlinking","Control the cursor animation style.")},"editor.mouseWheelZoom":{type:"boolean",default:g.viewInfo.mouseWheelZoom,markdownDescription:r.a("mouseWheelZoom","Zoom the font of the editor when using mouse wheel and holding `Ctrl`.")},"editor.cursorSmoothCaretAnimation":{type:"boolean",default:g.viewInfo.cursorSmoothCaretAnimation,description:r.a("cursorSmoothCaretAnimation","Controls whether the smooth caret animation should be enabled.")},"editor.cursorStyle":{type:"string",enum:["block","block-outline","line","line-thin","underline","underline-thin"],default:c.i(g.viewInfo.cursorStyle),description:r.a("cursorStyle","Controls the cursor style.")},"editor.cursorWidth":{type:"integer",default:g.viewInfo.cursorWidth,markdownDescription:r.a("cursorWidth","Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.")},"editor.fontLigatures":{type:"boolean",default:g.viewInfo.fontLigatures,description:r.a("fontLigatures","Enables/Disables font ligatures.")},"editor.hideCursorInOverviewRuler":{type:"boolean",default:g.viewInfo.hideCursorInOverviewRuler,description:r.a("hideCursorInOverviewRuler","Controls whether the cursor should be hidden in the overview ruler.")},"editor.renderWhitespace":{type:"string",enum:["none","boundary","selection","all"],enumDescriptions:["",r.a("renderWhitespace.boundary","Render whitespace characters except for single spaces between words."),r.a("renderWhitespace.selection","Render whitespace characters only on selected text."),""],default:g.viewInfo.renderWhitespace,description:r.a("renderWhitespace","Controls how the editor should render whitespace characters.")},"editor.renderControlCharacters":{type:"boolean",default:g.viewInfo.renderControlCharacters,description:r.a("renderControlCharacters","Controls whether the editor should render control characters.")},"editor.renderIndentGuides":{type:"boolean",default:g.viewInfo.renderIndentGuides,description:r.a("renderIndentGuides","Controls whether the editor should render indent guides.")},"editor.highlightActiveIndentGuide":{type:"boolean",default:g.viewInfo.highlightActiveIndentGuide,description:r.a("highlightActiveIndentGuide","Controls whether the editor should highlight the active indent guide.")},"editor.renderLineHighlight":{type:"string",enum:["none","gutter","line","all"],enumDescriptions:["","","",r.a("renderLineHighlight.all","Highlights both the gutter and the current line.")],default:g.viewInfo.renderLineHighlight,description:r.a("renderLineHighlight","Controls how the editor should render the current line highlight.")},"editor.codeLens":{type:"boolean",default:g.contribInfo.codeLens,description:r.a("codeLens","Controls whether the editor shows CodeLens.")},"editor.folding":{type:"boolean",default:g.contribInfo.folding,description:r.a("folding","Controls whether the editor has code folding enabled.")},"editor.foldingStrategy":{type:"string",enum:["auto","indentation"],default:g.contribInfo.foldingStrategy,markdownDescription:r.a("foldingStrategy","Controls the strategy for computing folding ranges. `auto` uses a language specific folding strategy, if available. `indentation` uses the indentation based folding strategy.")},"editor.showFoldingControls":{type:"string",enum:["always","mouseover"],default:g.contribInfo.showFoldingControls,description:r.a("showFoldingControls","Controls whether the fold controls on the gutter are automatically hidden.")},"editor.matchBrackets":{type:"boolean",default:g.contribInfo.matchBrackets,description:r.a("matchBrackets","Highlight matching brackets when one of them is selected.")},"editor.glyphMargin":{type:"boolean",default:g.viewInfo.glyphMargin,description:r.a("glyphMargin","Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.")},"editor.useTabStops":{type:"boolean",default:g.useTabStops,description:r.a("useTabStops","Inserting and deleting whitespace follows tab stops.")},"editor.trimAutoWhitespace":{type:"boolean",default:v.trimAutoWhitespace,description:r.a("trimAutoWhitespace","Remove trailing auto inserted whitespace.")},"editor.stablePeek":{type:"boolean",default:!1,markdownDescription:r.a("stablePeek","Keep peek editors open even when double clicking their content or when hitting `Escape`.")},"editor.dragAndDrop":{type:"boolean",default:g.dragAndDrop,description:r.a("dragAndDrop","Controls whether the editor should allow moving selections via drag and drop.")},"editor.accessibilitySupport":{type:"string",enum:["auto","on","off"],enumDescriptions:[r.a("accessibilitySupport.auto","The editor will use platform APIs to detect when a Screen Reader is attached."),r.a("accessibilitySupport.on","The editor will be permanently optimized for usage with a Screen Reader."),r.a("accessibilitySupport.off","The editor will never be optimized for usage with a Screen Reader.")],default:g.accessibilitySupport,description:r.a("accessibilitySupport","Controls whether the editor should run in a mode where it is optimized for screen readers.")},"editor.showUnused":{type:"boolean",default:g.showUnused,description:r.a("showUnused","Controls fading out of unused code.")},"editor.links":{type:"boolean",default:g.contribInfo.links,description:r.a("links","Controls whether the editor should detect links and make them clickable.")},"editor.colorDecorators":{type:"boolean",default:g.contribInfo.colorDecorators,description:r.a("colorDecorators","Controls whether the editor should render the inline color decorators and color picker.")},"editor.lightbulb.enabled":{type:"boolean",default:g.contribInfo.lightbulbEnabled,description:r.a("codeActions","Enables the code action lightbulb in the editor.")},"editor.maxTokenizationLineLength":{type:"integer",default:2e4,description:r.a("maxTokenizationLineLength","Lines above this length will not be tokenized for performance reasons")},"editor.codeActionsOnSave":{type:"object",properties:{"source.organizeImports":{type:"boolean",description:r.a("codeActionsOnSave.organizeImports","Controls whether organize imports action should be run on file save.")},"source.fixAll":{type:"boolean",description:r.a("codeActionsOnSave.fixAll","Controls whether auto fix action should be run on file save.")}},additionalProperties:{type:"boolean"},default:g.contribInfo.codeActionsOnSave,description:r.a("codeActionsOnSave","Code action kinds to be run on save.")},"editor.codeActionsOnSaveTimeout":{type:"number",default:g.contribInfo.codeActionsOnSaveTimeout,description:r.a("codeActionsOnSaveTimeout","Timeout in milliseconds after which the code actions that are run on save are cancelled.")},"editor.selectionClipboard":{type:"boolean",default:g.contribInfo.selectionClipboard,description:r.a("selectionClipboard","Controls whether the Linux primary clipboard should be supported."),included:u.c},"diffEditor.renderSideBySide":{type:"boolean",default:!0,description:r.a("sideBySide","Controls whether the diff editor shows the diff side by side or inline.")},"diffEditor.ignoreTrimWhitespace":{type:"boolean",default:!0,description:r.a("ignoreTrimWhitespace","Controls whether the diff editor shows changes in leading or trailing whitespace as diffs.")},"editor.largeFileOptimizations":{type:"boolean",default:v.largeFileOptimizations,description:r.a("largeFileOptimizations","Special handling for large files to disable certain memory intensive features.")},"diffEditor.renderIndicators":{type:"boolean",default:!0,description:r.a("renderIndicators","Controls whether the diff editor shows +/- indicators for added/removed changes.")}}},S=null;function x(){return null===S&&(S=Object.create(null),Object.keys(C.properties).forEach(function(e){S[e]=!0})),S}w.registerConfiguration(C)},TkWM:function(e,t,n){"use strict";var i=t,r=n("geuY"),o=n("08Lv"),s=n("tpuU");i.assert=o,i.toArray=s.toArray,i.zero2=s.zero2,i.toHex=s.toHex,i.encode=s.encode,i.getNAF=function(e,t){for(var n=[],i=1<=0;){var o;if(r.isOdd()){var s=r.andln(i-1);o=s>(i>>1)-1?(i>>1)-s:s,r.isubn(o)}else o=0;n.push(o);for(var a=0!==r.cmpn(0)&&0===r.andln(i-1)?t+1:1,u=1;u0||t.cmpn(-r)>0;){var o,s,a,u=e.andln(3)+i&3,c=t.andln(3)+r&3;3===u&&(u=-1),3===c&&(c=-1),o=0==(1&u)?0:3!=(a=e.andln(7)+i&7)&&5!==a||2!==c?u:-u,n[0].push(o),s=0==(1&c)?0:3!=(a=t.andln(7)+r&7)&&5!==a||2!==u?c:-c,n[1].push(s),2*i===o+1&&(i=1-i),2*r===s+1&&(r=1-r),e.iushrn(1),t.iushrn(1)}return n},i.cachedProperty=function(e,t,n){var i="_"+t;e.prototype[t]=function(){return void 0!==this[i]?this[i]:this[i]=n.call(this)}},i.parseBytes=function(e){return"string"==typeof e?i.toArray(e,"hex"):e},i.intFromLE=function(e){return new r(e,"hex","le")}},TlQ3:function(e,t,n){var i=n("EarI");e.exports=function(e,t){var n=t||Math.floor(Date.now()/1e3);if("string"==typeof e){var r=i(e);if(void 0===r)return;return Math.floor(n+r/1e3)}return"number"==typeof e?n+e:void 0}},TnCn:function(e,t,n){var i=t;i._reverse=function(e){var t={};return Object.keys(e).forEach(function(n){(0|n)==n&&(n|=0);var i=e[n];t[i]=n}),t},i.der=n("C1C2")},U6yG:function(e,t){t.encrypt=function(e,t){return e._cipher.encryptBlock(t)},t.decrypt=function(e,t){return e._cipher.decryptBlock(t)}},UBa7:function(e,t){t["des-ecb"]={key:8,iv:0},t["des-cbc"]=t.des={key:8,iv:8},t["des-ede3-cbc"]=t.des3={key:24,iv:8},t["des-ede3"]={key:24,iv:0},t["des-ede-cbc"]={key:16,iv:8},t["des-ede"]={key:16,iv:0}},UHZ4:function(e,t,n){"use strict";var i=n("lAcG"),r=n("Kp7x"),o=n("tqet"),s=n("ZfGv"),a=function(){function e(e,t){this.chr=e,this.type=t,this.width=0}return e.prototype.fulfill=function(e){this.width=e},e}(),u=function(){function e(e,t){this._bareFontInfo=e,this._requests=t,this._container=null,this._testElements=null}return e.prototype.read=function(){this._createDomElements(),document.body.appendChild(this._container),this._readFromDomElements(),document.body.removeChild(this._container),this._container=null,this._testElements=null},e.prototype._createDomElements=function(){var t=document.createElement("div");t.style.position="absolute",t.style.top="-50000px",t.style.width="50000px";var n=document.createElement("div");n.style.fontFamily=this._bareFontInfo.getMassagedFontFamily(),n.style.fontWeight=this._bareFontInfo.fontWeight,n.style.fontSize=this._bareFontInfo.fontSize+"px",n.style.lineHeight=this._bareFontInfo.lineHeight+"px",n.style.letterSpacing=this._bareFontInfo.letterSpacing+"px",t.appendChild(n);var i=document.createElement("div");i.style.fontFamily=this._bareFontInfo.getMassagedFontFamily(),i.style.fontWeight="bold",i.style.fontSize=this._bareFontInfo.fontSize+"px",i.style.lineHeight=this._bareFontInfo.lineHeight+"px",i.style.letterSpacing=this._bareFontInfo.letterSpacing+"px",t.appendChild(i);var r=document.createElement("div");r.style.fontFamily=this._bareFontInfo.getMassagedFontFamily(),r.style.fontWeight=this._bareFontInfo.fontWeight,r.style.fontSize=this._bareFontInfo.fontSize+"px",r.style.lineHeight=this._bareFontInfo.lineHeight+"px",r.style.letterSpacing=this._bareFontInfo.letterSpacing+"px",r.style.fontStyle="italic",t.appendChild(r);for(var o=[],s=0,a=this._requests.length;s.001){C=!1;break}}var k=!0;C&&y.width!==S&&(k=!1),y.width>b.width&&(k=!1);var N=i.b()>2e3;return new f.b({zoomLevel:i.c(),fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontSize:e.fontSize,lineHeight:e.lineHeight,letterSpacing:e.letterSpacing,isMonospace:C,typicalHalfwidthCharacterWidth:r.width,typicalFullwidthCharacterWidth:o.width,canUseHalfwidthRightwardsArrow:k,spaceWidth:s.width,maxDigitWidth:w},N)},t.INSTANCE=new t,t}(o.a),v=function(e){function t(t,n,r,o){void 0===r&&(r=null);var s=e.call(this,t,n)||this;return s.accessibilityService=o,s._elementSizeObserver=s._register(new d(r,function(){return s._onReferenceDomElementSizeChanged()})),s._register(m.INSTANCE.onDidChange(function(){return s._onCSSBasedConfigurationChanged()})),s._validatedOptions.automaticLayout&&s._elementSizeObserver.startObserving(),s._register(i.o(function(e){return s._recomputeOptions()})),s._register(s.accessibilityService.onDidChangeAccessibilitySupport(function(){return s._recomputeOptions()})),s._recomputeOptions(),s}return p(t,e),t.applyFontInfoSlow=function(e,t){e.style.fontFamily=t.getMassagedFontFamily(),e.style.fontWeight=t.fontWeight,e.style.fontSize=t.fontSize+"px",e.style.lineHeight=t.lineHeight+"px",e.style.letterSpacing=t.letterSpacing+"px"},t.applyFontInfo=function(e,t){e.setFontFamily(t.getMassagedFontFamily()),e.setFontWeight(t.fontWeight),e.setFontSize(t.fontSize),e.setLineHeight(t.lineHeight),e.setLetterSpacing(t.letterSpacing)},t.prototype._onReferenceDomElementSizeChanged=function(){this._recomputeOptions()},t.prototype._onCSSBasedConfigurationChanged=function(){this._recomputeOptions()},t.prototype.observeReferenceElement=function(e){this._elementSizeObserver.observe(e)},t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype._getExtraEditorClassName=function(){var e="";return i.l||i.n||(e+="no-user-select "),s.d&&(e+="mac "),e},t.prototype._getEnvConfiguration=function(){return{extraEditorClassName:this._getExtraEditorClassName(),outerWidth:this._elementSizeObserver.getWidth(),outerHeight:this._elementSizeObserver.getHeight(),emptySelectionClipboard:i.m||i.i,pixelRatio:i.a(),zoomLevel:i.c(),accessibilitySupport:this.accessibilityService.getAccessibilitySupport()}},t.prototype.readConfiguration=function(e){return m.INSTANCE.readConfiguration(e)},t}(h.a)},UMuV:function(e,t,n){"use strict";t.b=function(e,t){var n=new o.b(t);return n.preventDefault(),{leftButton:n.leftButton,posx:n.posx,posy:n.posy}},n.d(t,"a",function(){return a});var i=n("7/Cv"),r=n("Crnc"),o=n("b1X/"),s=n("tqet");var a=function(){function e(){this.hooks=new s.b,this.mouseMoveEventMerger=null,this.mouseMoveCallback=null,this.onStopCallback=null}return e.prototype.dispose=function(){this.stopMonitoring(!1),this.hooks.dispose()},e.prototype.stopMonitoring=function(e){if(this.isMonitoring()){this.hooks.clear(),this.mouseMoveEventMerger=null,this.mouseMoveCallback=null;var t=this.onStopCallback;this.onStopCallback=null,e&&t&&t()}},e.prototype.isMonitoring=function(){return!!this.mouseMoveEventMerger},e.prototype.startMonitoring=function(e,t,n){var s=this;if(!this.isMonitoring()){this.mouseMoveEventMerger=e,this.mouseMoveCallback=t,this.onStopCallback=n;for(var a=r.a.getSameOriginWindowChain(),u=0,c=a;u>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function s(e){this.h=e,this.state=i.alloc(16,0),this.cache=i.allocUnsafe(0)}s.prototype.ghash=function(e){for(var t=-1;++t0;t--)i[t]=i[t]>>>1|(1&i[t-1])<<31;i[0]=i[0]>>>1,n&&(i[0]=i[0]^225<<24)}this.state=o(r)},s.prototype.update=function(e){var t;for(this.cache=i.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},s.prototype.final=function(e,t){return this.cache.length&&this.ghash(i.concat([this.cache,r],16)),this.ghash(o([0,e,0,t])),this.state},e.exports=s},UcPO:function(e,t,n){e.exports=n("vzCy").EventEmitter},Uf3U:function(e,t,n){"use strict";n.d(t,"a",function(){return c});var i,r=n("7/Cv"),o=n("gzF+"),s=n("b1X/"),a=n("tqet"),u=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),c=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return u(t,e),t.prototype.onclick=function(e,t){this._register(r.h(e,r.d.CLICK,function(e){return t(new s.b(e))}))},t.prototype.onmousedown=function(e,t){this._register(r.h(e,r.d.MOUSE_DOWN,function(e){return t(new s.b(e))}))},t.prototype.onmouseover=function(e,t){this._register(r.h(e,r.d.MOUSE_OVER,function(e){return t(new s.b(e))}))},t.prototype.onnonbubblingmouseout=function(e,t){this._register(r.i(e,function(e){return t(new s.b(e))}))},t.prototype.onkeydown=function(e,t){this._register(r.h(e,r.d.KEY_DOWN,function(e){return t(new o.a(e))}))},t.prototype.onkeyup=function(e,t){this._register(r.h(e,r.d.KEY_UP,function(e){return t(new o.a(e))}))},t.prototype.oninput=function(e,t){this._register(r.h(e,r.d.INPUT,t))},t.prototype.onblur=function(e,t){this._register(r.h(e,r.d.BLUR,t))},t.prototype.onfocus=function(e,t){this._register(r.h(e,r.d.FOCUS,t))},t.prototype.onchange=function(e,t){this._register(r.h(e,r.d.CHANGE,t))},t}(a.a)},Uj3s:function(e,t,n){(function(t){var i=n("6S2P");e.exports=i.satisfies(t.version,"^6.12.0 || >=8.0.0")}).call(t,n("W2nU"))},UqCF:function(e,t,n){"use strict";t.b=function(e){(i=document.createElement("div")).className="monaco-aria-container",(r=document.createElement("div")).className="monaco-alert",r.setAttribute("role","alert"),r.setAttribute("aria-atomic","true"),i.appendChild(r),(o=document.createElement("div")).className="monaco-status",o.setAttribute("role","status"),o.setAttribute("aria-atomic","true"),i.appendChild(o),e.appendChild(i)},t.a=l,t.c=function(e,t){u.d?l(e,t):f(o,e,t)};var i,r,o,s=n("KL86"),a=(n.n(s),n("hK2W")),u=n("ZfGv"),c=n("7/Cv");function l(e,t){f(r,e,t)}var d=0,h=void 0;function f(e,t,n){if(i){if(!n)switch(h===t?d++:(h=t,d=0),d){case 0:break;case 1:t=a.a("repeated","{0} (occurred again)",t);break;default:t=a.a("repeatedNtimes","{0} (occurred {1} times)",t,d)}c.p(e),e.textContent=t,e.style.visibility="hidden",e.style.visibility="visible"}}},UuCV:function(e,t,n){"use strict";var i=n("zxiH"),r=n("aL7J"),o=n("Ao9X"),s=n("ll3Y"),a=n("vTy2"),u=n("iHM7"),c=function(){function e(e,t,n){this._range=e,this._charBeforeSelection=t,this._charAfterSelection=n}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(new a.a(this._range.startLineNumber,this._range.startColumn,this._range.startLineNumber,this._range.startColumn),this._charBeforeSelection),t.addTrackedEditOperation(new a.a(this._range.endLineNumber,this._range.endColumn,this._range.endLineNumber,this._range.endColumn),this._charAfterSelection)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations(),i=n[0].range,r=n[1].range;return new u.a(i.endLineNumber,i.endColumn,r.endLineNumber,r.endColumn-this._charAfterSelection.length)},e}(),l=n("6boo"),d=n("BwcV"),h=n("+oh4"),f=n("Fllr");n.d(t,"a",function(){return m}),n.d(t,"b",function(){return v});var p,g=this&&this.__extends||(p=function(e,t){return(p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}p(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),m=function(){function e(){}return e.indent=function(e,t,n){if(null===t||null===n)return[];for(var i=[],r=0,o=n.length;r1){var c=void 0;for(c=i-1;c>=1;c--){var l=n.getLineContent(c);if(r.A(l)>=0)break}if(c<1)return null;var d=n.getLineMaxColumn(c),p=f.a.getEnterAction(n,new a.a(c,d,c,d));p&&(s=p.indentation,(o=p.enterAction)&&(s+=o.appendText))}return o&&(o===h.a.Indent&&(s=e.shiftIndent(t,s)),o===h.a.Outdent&&(s=e.unshiftIndent(t,s)),s=t.normalizeIndentation(s)),s||null},e._replaceJumpToNextIndent=function(e,t,n,i){var r="",s=n.getStartPosition();if(e.insertSpaces)for(var a=l.a.visibleColumnFromColumn2(e,t,s),u=e.indentSize,c=u-a%u,d=0;d=0?s.setEndPosition(s.endLineNumber,Math.max(s.endColumn,E+1)):s.setEndPosition(s.endLineNumber,n.getLineMaxColumn(s.endLineNumber)),i)return new o.d(s,k+t.normalizeIndentation(C.afterEnter),!0);var I=0;return O<=E+1&&(t.insertSpaces||(L=Math.ceil(L/t.indentSize)),I=Math.min(L+1-t.normalizeIndentation(C.afterEnter).length-1,0)),new o.c(s,k+t.normalizeIndentation(C.afterEnter),0,I,!0)}return e._typeCommand(s,"\n"+t.normalizeIndentation(x),i)},e._isAutoIndentType=function(e,t,n){if(!e.autoIndent)return!1;for(var i=0,r=n.length;io.open.length){for(var l=!0,d=0,h=n;dv.column-1){var b=_.charAt(v.column-1);if(!e._isBeforeClosingBrace(t,c,b)&&!h(b))return null}if(!n.isCheapToTokenize(v.lineNumber))return null;if(1===c.open.length&&a&&"always"!==u){var y=Object(d.a)(t.wordSeparators);if(s&&v.column>1&&0===y.get(_.charCodeAt(v.column-2)))return null;if(!s&&v.column>2&&0===y.get(_.charCodeAt(v.column-3)))return null}n.forceTokenization(v.lineNumber);var w=n.getLineTokens(v.lineNumber),C=!1;try{C=f.a.shouldAutoClosePair(c,w,s?v.column:v.column-1)}catch(e){Object(i.e)(e)}if(!C)return null}return c},e._runAutoClosingOpenCharType=function(e,t,n,i,r,o,s){for(var a=[],u=0,c=i.length;u ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|\\n*|\\n*|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,table:m,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,text:/^[^\n]+/};function n(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||w.defaults,this.rules=t.normal,this.options.pedantic?this.rules=t.pedantic:this.options.gfm&&(this.options.tables?this.rules=t.tables:this.rules=t.gfm)}t._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,t._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,t.def=h(t.def).replace("label",t._label).replace("title",t._title).getRegex(),t.bullet=/(?:[*+-]|\d{1,9}\.)/,t.item=/^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/,t.item=h(t.item,"gm").replace(/bull/g,t.bullet).getRegex(),t.list=h(t.list).replace(/bull/g,t.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+t.def.source+")").getRegex(),t._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",t._comment=//,t.html=h(t.html,"i").replace("comment",t._comment).replace("tag",t._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),t.paragraph=h(t.paragraph).replace("hr",t.hr).replace("heading",t.heading).replace("lheading",t.lheading).replace("tag",t._tag).getRegex(),t.blockquote=h(t.blockquote).replace("paragraph",t.paragraph).getRegex(),t.normal=v({},t),t.gfm=v({},t.normal,{fences:/^ {0,3}(`{3,}|~{3,})([^`\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),t.gfm.paragraph=h(t.paragraph).replace("(?!","(?!"+t.gfm.fences.source.replace("\\1","\\2")+"|"+t.list.source.replace("\\1","\\3")+"|").getRegex(),t.tables=v({},t.gfm,{nptable:/^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,table:/^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/}),t.pedantic=v({},t.normal,{html:h("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",t._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/}),n.rules=t,n.lex=function(e,t){return new n(t).lex(e)},n.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},n.prototype.token=function(e,n){var i,r,o,s,a,u,c,l,d,h,f,p,g,m,v,y;for(e=e.replace(/^ +$/gm,"");e;)if((o=this.rules.newline.exec(e))&&(e=e.substring(o[0].length),o[0].length>1&&this.tokens.push({type:"space"})),o=this.rules.code.exec(e))e=e.substring(o[0].length),o=o[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?o:b(o,"\n")});else if(o=this.rules.fences.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"code",lang:o[2]?o[2].trim():o[2],text:o[3]||""});else if(o=this.rules.heading.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"heading",depth:o[1].length,text:o[2]});else if((o=this.rules.nptable.exec(e))&&(u={type:"table",header:_(o[1].replace(/^ *| *\| *$/g,"")),align:o[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:o[3]?o[3].replace(/\n$/,"").split("\n"):[]}).header.length===u.align.length){for(e=e.substring(o[0].length),f=0;f ?/gm,""),this.token(o,n),this.tokens.push({type:"blockquote_end"});else if(o=this.rules.list.exec(e)){for(e=e.substring(o[0].length),c={type:"list_start",ordered:m=(s=o[2]).length>1,start:m?+s:"",loose:!1},this.tokens.push(c),l=[],i=!1,g=(o=o[0].match(this.rules.item)).length,f=0;f1?1===a.length:a.length>1||this.options.smartLists&&a!==s)&&(e=o.slice(f+1).join("\n")+e,f=g-1)),r=i||/\n\n(?!\s*$)/.test(u),f!==g-1&&(i="\n"===u.charAt(u.length-1),r||(r=i)),r&&(c.loose=!0),y=void 0,(v=/^\[[ xX]\] /.test(u))&&(y=" "!==u[1],u=u.replace(/^\[[ xX]\] +/,"")),d={type:"list_item_start",task:v,checked:y,loose:r},l.push(d),this.tokens.push(d),this.token(u,!1),this.tokens.push({type:"list_item_end"});if(c.loose)for(g=l.length,f=0;f?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:m,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,em:/^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:m,text:/^(`+|[^`])(?:[\s\S]*?(?:(?=[\\?@\\[^_{|}~",r.em=h(r.em).replace(/punctuation/g,r._punctuation).getRegex(),r._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,r._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,r._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,r.autolink=h(r.autolink).replace("scheme",r._scheme).replace("email",r._email).getRegex(),r._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,r.tag=h(r.tag).replace("comment",t._comment).replace("attribute",r._attribute).getRegex(),r._label=/(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|`(?!`)|[^\[\]\\`])*?/,r._href=/\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)/,r._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,r.link=h(r.link).replace("label",r._label).replace("href",r._href).replace("title",r._title).getRegex(),r.reflink=h(r.reflink).replace("label",r._label).getRegex(),r.normal=v({},r),r.pedantic=v({},r.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",r._label).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",r._label).getRegex()}),r.gfm=v({},r.normal,{escape:h(r.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~+(?=\S)([\s\S]*?\S)~+/,text:/^(`+|[^`])(?:[\s\S]*?(?:(?=[\\/i.test(s[0])&&(this.inLink=!1),!this.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(s[0])?this.inRawBlock=!0:this.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(s[0])&&(this.inRawBlock=!1),e=e.substring(s[0].length),u+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(s[0]):l(s[0]):s[0];else if(s=this.rules.link.exec(e)){var c=y(s[2],"()");if(c>-1){var d=s[0].length-(s[2].length-c)-(s[3]||"").length;s[2]=s[2].substring(0,c),s[0]=s[0].substring(0,d).trim(),s[3]=""}e=e.substring(s[0].length),this.inLink=!0,i=s[2],this.options.pedantic?(t=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(i))?(i=t[1],r=t[3]):r="":r=s[3]?s[3].slice(1,-1):"",i=i.trim().replace(/^<([\s\S]*)>$/,"$1"),u+=this.outputLink(s,{href:o.escapes(i),title:o.escapes(r)}),this.inLink=!1}else if((s=this.rules.reflink.exec(e))||(s=this.rules.nolink.exec(e))){if(e=e.substring(s[0].length),t=(s[2]||s[1]).replace(/\s+/g," "),!(t=this.links[t.toLowerCase()])||!t.href){u+=s[0].charAt(0),e=s[0].substring(1)+e;continue}this.inLink=!0,u+=this.outputLink(s,t),this.inLink=!1}else if(s=this.rules.strong.exec(e))e=e.substring(s[0].length),u+=this.renderer.strong(this.output(s[4]||s[3]||s[2]||s[1]));else if(s=this.rules.em.exec(e))e=e.substring(s[0].length),u+=this.renderer.em(this.output(s[6]||s[5]||s[4]||s[3]||s[2]||s[1]));else if(s=this.rules.code.exec(e))e=e.substring(s[0].length),u+=this.renderer.codespan(l(s[2].trim(),!0));else if(s=this.rules.br.exec(e))e=e.substring(s[0].length),u+=this.renderer.br();else if(s=this.rules.del.exec(e))e=e.substring(s[0].length),u+=this.renderer.del(this.output(s[1]));else if(s=this.rules.autolink.exec(e))e=e.substring(s[0].length),i="@"===s[2]?"mailto:"+(n=l(this.mangle(s[1]))):n=l(s[1]),u+=this.renderer.link(i,null,n);else if(this.inLink||!(s=this.rules.url.exec(e))){if(s=this.rules.text.exec(e))e=e.substring(s[0].length),this.inRawBlock?u+=this.renderer.text(s[0]):u+=this.renderer.text(l(this.smartypants(s[0])));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else{if("@"===s[2])i="mailto:"+(n=l(s[0]));else{do{a=s[0],s[0]=this.rules._backpedal.exec(s[0])[0]}while(a!==s[0]);n=l(s[0]),i="www."===s[1]?"http://"+n:n}e=e.substring(s[0].length),u+=this.renderer.link(i,null,n)}return u},o.escapes=function(e){return e?e.replace(o.rules._escapes,"$1"):e},o.prototype.outputLink=function(e,t){var n=t.href,i=t.title?l(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,i,this.output(e[1])):this.renderer.image(n,i,l(e[1]))},o.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},o.prototype.mangle=function(e){if(!this.options.mangle)return e;for(var t,n="",i=e.length,r=0;r.5&&(t="x"+t.toString(16)),n+="&#"+t+";";return n},s.prototype.code=function(e,t,n){var i=(t||"").match(/\S*/)[0];if(this.options.highlight){var r=this.options.highlight(e,i);null!=r&&r!==e&&(n=!0,e=r)}return i?'
      '+(n?e:l(e,!0))+"
      \n":"
      "+(n?e:l(e,!0))+"
      "},s.prototype.blockquote=function(e){return"
      \n"+e+"
      \n"},s.prototype.html=function(e){return e},s.prototype.heading=function(e,t,n,i){return this.options.headerIds?"'+e+"\n":""+e+"\n"},s.prototype.hr=function(){return this.options.xhtml?"
      \n":"
      \n"},s.prototype.list=function(e,t,n){var i=t?"ol":"ul";return"<"+i+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"},s.prototype.listitem=function(e){return"
    • "+e+"
    • \n"},s.prototype.checkbox=function(e){return" "},s.prototype.paragraph=function(e){return"

      "+e+"

      \n"},s.prototype.table=function(e,t){return t&&(t=""+t+""),"\n\n"+e+"\n"+t+"
      \n"},s.prototype.tablerow=function(e){return"\n"+e+"\n"},s.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"\n"},s.prototype.strong=function(e){return""+e+""},s.prototype.em=function(e){return""+e+""},s.prototype.codespan=function(e){return""+e+""},s.prototype.br=function(){return this.options.xhtml?"
      ":"
      "},s.prototype.del=function(e){return""+e+""},s.prototype.link=function(e,t,n){if(null===(e=f(this.options.sanitize,this.options.baseUrl,e)))return n;var i='"},s.prototype.image=function(e,t,n){if(null===(e=f(this.options.sanitize,this.options.baseUrl,e)))return n;var i=''+n+'":">"},s.prototype.text=function(e){return e},a.prototype.strong=a.prototype.em=a.prototype.codespan=a.prototype.del=a.prototype.text=function(e){return e},a.prototype.link=a.prototype.image=function(e,t,n){return""+n},a.prototype.br=function(){return""},u.parse=function(e,t){return new u(t).parse(e)},u.prototype.parse=function(e){this.inline=new o(e.links,this.options),this.inlineText=new o(e.links,v({},this.options,{renderer:new a})),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},u.prototype.next=function(){return this.token=this.tokens.pop()},u.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},u.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},u.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,d(this.inlineText.output(this.token.text)),this.slugger);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,i,r="",o="";for(n="",e=0;e?@[\]^`{|}~]/g,"").replace(/\s/g,"-");if(this.seen.hasOwnProperty(t)){var n=t;do{this.seen[n]++,t=n+"-"+this.seen[n]}while(this.seen.hasOwnProperty(t))}return this.seen[t]=0,t},l.escapeTest=/[&<>"']/,l.escapeReplace=/[&<>"']/g,l.replacements={"&":"&","<":"<",">":">",'"':""","'":"'"},l.escapeTestNoEncode=/[<>"']|&(?!#?\w+;)/,l.escapeReplaceNoEncode=/[<>"']|&(?!#?\w+;)/g;var p={},g=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function m(){}function v(e){for(var t,n,i=1;i=0&&"\\"===n[r];)i=!i;return i?"|":" |"}).split(/ \|/),i=0;if(n.length>t)n.splice(t);else for(;n.lengthAn error occurred:

      "+l(e.message+"",!0)+"
      ";throw e}}m.exec=m,w.options=w.setOptions=function(e){return v(w.defaults,e),w},w.getDefaults=function(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:new s,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tables:!0,xhtml:!1}},w.defaults=w.getDefaults(),w.Parser=u,w.parser=u.parse,w.Renderer=s,w.TextRenderer=a,w.Lexer=n,w.lexer=n.lex,w.InlineLexer=o,w.inlineLexer=o.output,w.Slugger=c,w.parse=w,i=w}).call(this);i.Parser,i.parser;var c,l=i.Renderer,d=(i.TextRenderer,i.Lexer,i.lexer,i.InlineLexer,i.inlineLexer,i.parse);let h;!function(){return function e(t,n,i){function r(s,a){if(!n[s]){if(!t[s]){if(!a&&"function"==typeof c&&c)return c(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var l=n[s]={exports:{}};t[s][0].call(l.exports,function(e){return r(t[s][1][e]||e)},l,l.exports,e,t,n,i)}return n[s].exports}for(var o="function"==typeof c&&c,s=0;s\s]+))?)*)\s*(\/?)\s*>/,a=/^<\s*\/\s*([\w:-]+)[^>]*>/,u=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,c=/^=0&&(t.comment&&t.comment(e.substring(4,i)),e=e.substring(i+3),n=!1):l.test(e)?p(a,m):c.test(e)&&p(s,g),function(){if(n){var i,r=e.indexOf("<");r>=0?(i=e.substring(0,r),e=e.substring(r)):(i=e,e=""),t.chars&&t.chars(i)}}();var r=e===h;h=e,r&&(e="")}function p(t,i){var r=e.match(t);r&&(e=e.substring(r[0].length),r[0].replace(t,i),n=!1)}function g(e,n,s,a){var c={},l=r(n),h=o.voids[l]||!!a;s.replace(u,function(e,t,n,r,o){c[t]=void 0===n&&void 0===r&&void 0===o?void 0:i.decode(n||r||o||"")}),h||d.push(l),t.start&&t.start(l,c,h)}function m(e,n){var i,o=0,s=r(n);if(s)for(o=d.length-1;o>=0&&d[o]!==s;o--);if(o>=0){for(i=d.length-1;i>=o;i--)t.end&&t.end(d[i]);d.length=o}}m()}},{"./attributes":1,"./elements":3,"./lowercase":5,he:9}],8:[function(e,t,n){var i=e("he"),r=e("./lowercase"),o=e("./attributes"),s=e("./elements");t.exports=function(e,t){var n,a=t||{};return d(),{start:function(e,t,s){var l=r(e);n.ignoring?c(l):-1!==(a.allowedTags||[]).indexOf(l)&&(!a.filter||a.filter({tag:l,attrs:t}))?(u("<"),u(l),Object.keys(t).forEach(function(e){var n,s=t[e],c=(a.allowedClasses||{})[l]||[],d=(a.allowedAttributes||{})[l]||[];d=d.concat((a.allowedAttributes||{})["*"]||[]);var h=r(e);"class"===h&&-1===d.indexOf(h)?(s=s.split(" ").filter(function(e){return c&&-1!==c.indexOf(e)}).join(" ").trim(),n=s.length):n=-1!==d.indexOf(h)&&(!0!==o.uris[h]||function(e){var t=e[0];if("#"===t||"/"===t)return!0;var n=e.indexOf(":");if(-1===n)return!0;var i=e.indexOf("?");if(-1!==i&&n>i)return!0;var r=e.indexOf("#");return-1!==r&&n>r||a.allowedSchemes.some(function(t){return 0===e.indexOf(t+":")})}(s)),n&&(u(" "),u(e),"string"==typeof s&&(u('="'),u(i.encode(s)),u('"')))}),u(s?"/>":">")):c(l)},end:function(e){var t=r(e);-1!==(a.allowedTags||[]).indexOf(t)&&!1===n.ignoring?(u("")):l(t)},chars:function(e){!1===n.ignoring&&u(a.transformText?a.transformText(e):e)}};function u(t){e.push(t)}function c(e){s.voids[e]||(!1===n.ignoring?n={ignoring:e,depth:1}:n.ignoring===e&&n.depth++)}function l(e){n.ignoring===e&&--n.depth<=0&&d()}function d(){n={ignoring:!1,depth:0}}}},{"./attributes":1,"./elements":3,"./lowercase":5,he:9}],9:[function(e,t,n){var i={"&":"&","<":"<",">":">",'"':""","'":"'"},r={"&":"&","<":"<",">":">",""":'"',"'":"'"},o=/(&|<|>|"|')/g,s=/[&<>"']/g;function a(e){return i[e]}function u(e){return r[e]}function c(e){return null==e?"":String(e).replace(s,a)}function l(e){return null==e?"":String(e).replace(o,u)}c.options=l.options={},t.exports={encode:c,escape:c,decode:l,unescape:l,version:"1.0.0-browser"}},{}],10:[function(e,t,n){function i(e,t){return e[t]=!0,e}t.exports=function(e){return e.reduce(i,{})}},{}]},{},[4]);var f=h,p=n("+vUW"),g=n("TU7t"),m=n("aL7J"),v=n("mrx5");function _(e,t){void 0===t&&(t={});var n,i=Object(o.a)(t),c=function(t,n){var i=e.uris&&e.uris[t];if(!i)return t;var o=v.a.revive(i);return n&&(o=r.o(o)),o.query&&(o=o.with({query:function(t){var n;try{n=Object(p.a)(decodeURIComponent(t))}catch(e){}return n?(n=Object(g.b)(n,function(t){return e.uris&&e.uris[t]?v.a.revive(e.uris[t]):void 0}),encodeURIComponent(JSON.stringify(n))):t}(o.query)})),i&&(t=o.toString(!0)),t},h=new Promise(function(e){return n=e}),_=new l;_.image=function(e,t,n){var i,r=[],o=[];return e&&(e=(i=Object(a.d)(e)).href,r=i.dimensions,e=c(e,!0),o.push('src="'+e+'"')),n&&o.push('alt="'+n+'"'),t&&o.push('title="'+t+'"'),r.length&&(o=o.concat(r)),""},_.link=function(t,n,i){return t===i&&(i=Object(a.e)(i)),t=c(t,!1),n=Object(a.e)(n),!(t=Object(a.e)(t))||t.match(/^data:|javascript:/i)||t.match(/^command:/i)&&!e.isTrusted||t.match(/^command:(\/\/\/)?_workbench\.downloadResource/i)?i:'
      /g,">").replace(/"/g,""").replace(/'/g,"'"))+'" title="'+(n||t)+'">'+i+""},_.paragraph=function(e){return"

      "+e+"

      "},t.codeBlockRenderer&&(_.code=function(e,n){var r=t.codeBlockRenderer(n,e),o=u.b.nextId(),s=Promise.all([r,h]).then(function(e){var t=e[0],n=i.querySelector('div[data-code="'+o+'"]');n&&(n.innerHTML=t)}).catch(function(e){});return t.codeBlockRenderCallback&&s.then(t.codeBlockRenderCallback),'
      '+Object(m.o)(e)+"
      "});var b=t.actionHandler;b&&b.disposeables.add(r.k(i,"click",function(e){var t=e.target;if("A"===t.tagName||(t=t.parentElement)&&"A"===t.tagName)try{var n=t.dataset.href;n&&b.callback(n,e)}catch(e){Object(s.e)(e)}finally{e.preventDefault()}}));var y={sanitize:!0,renderer:_},w=["http","https","mailto","data"];e.isTrusted&&w.push("command");var C=d(e.value,y);return i.innerHTML=f(C,{allowedSchemes:w,allowedAttributes:{a:["href","name","target","data-href"],iframe:["allowfullscreen","frameborder","src"],img:["src","title","alt","width","height"],div:["class","data-code"]}}),n(),i}var b=n("GsV8"),y=n("6TMp"),w=n("Skdw"),C=n("JVO/"),S=n("Kp7x"),x=n("tqet"),L=n("PCC9");n.d(t,"a",function(){return I});var O,k=this&&this.__extends||(O=function(e,t){return(O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}O(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),N=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},E=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},I=function(e){function t(t,n,i){void 0===i&&(i=b.b);var r=e.call(this)||this;return r._editor=t,r._modeService=n,r._openerService=i,r._onDidRenderCodeBlock=r._register(new S.a),r.onDidRenderCodeBlock=r._onDidRenderCodeBlock.event,r}return k(t,e),t.prototype.getOptions=function(e){var t=this;return{codeBlockRenderer:function(e,n){var i=null;if(e)i=t._modeService.getModeIdForLanguageName(e);else{var r=t._editor.getModel();r&&(i=r.getLanguageIdentifier().language)}return t._modeService.triggerMode(i||""),Promise.resolve(!0).then(function(e){var t=L.y.getPromise(i||"");return t?t.then(function(e){return Object(w.b)(n,e)}):Object(w.b)(n,void 0)}).then(function(e){return''+e+""})},codeBlockRenderCallback:function(){return t._onDidRenderCodeBlock.fire()},actionHandler:{callback:function(e){var n;try{n=v.a.parse(e)}catch(e){}n&&t._openerService&&t._openerService.open(n).catch(s.e)},disposeables:e}}},t.prototype.render=function(e){var t=new x.b;return{element:e?_(e,this.getOptions(t)):document.createElement("span"),dispose:function(){return t.dispose()}}},t=N([E(1,y.a),E(2,Object(C.d)(b.a))],t)}(x.a)},"VI/i":function(e,t,n){"use strict";t.randomBytes=t.rng=t.pseudoRandomBytes=t.prng=n("rOku"),t.createHash=t.Hash=n("BVsN"),t.createHmac=t.Hmac=n("ARY+");var i=n("O+gO"),r=Object.keys(i),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(r);t.getHashes=function(){return o};var s=n("/vd3");t.pbkdf2=s.pbkdf2,t.pbkdf2Sync=s.pbkdf2Sync;var a=n("VKDQ");t.Cipher=a.Cipher,t.createCipher=a.createCipher,t.Cipheriv=a.Cipheriv,t.createCipheriv=a.createCipheriv,t.Decipher=a.Decipher,t.createDecipher=a.createDecipher,t.Decipheriv=a.Decipheriv,t.createDecipheriv=a.createDecipheriv,t.getCiphers=a.getCiphers,t.listCiphers=a.listCiphers;var u=n("PBsE");t.DiffieHellmanGroup=u.DiffieHellmanGroup,t.createDiffieHellmanGroup=u.createDiffieHellmanGroup,t.getDiffieHellman=u.getDiffieHellman,t.createDiffieHellman=u.createDiffieHellman,t.DiffieHellman=u.DiffieHellman;var c=n("KeN/");t.createSign=c.createSign,t.Sign=c.Sign,t.createVerify=c.createVerify,t.Verify=c.Verify,t.createECDH=n("gw8B");var l=n("9P96");t.publicEncrypt=l.publicEncrypt,t.privateEncrypt=l.privateEncrypt,t.publicDecrypt=l.publicDecrypt,t.privateDecrypt=l.privateDecrypt;var d=n("4R/o");t.randomFill=d.randomFill,t.randomFillSync=d.randomFillSync,t.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},t.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}},VKDQ:function(e,t,n){var i=n("IRek"),r=n("tXf9"),o=n("BCiZ"),s=n("UBa7"),a=n("Cgw8");function u(e,t,n){if(e=e.toLowerCase(),o[e])return r.createCipheriv(e,t,n);if(s[e])return new i({key:t,iv:n,mode:e});throw new TypeError("invalid suite type")}function c(e,t,n){if(e=e.toLowerCase(),o[e])return r.createDecipheriv(e,t,n);if(s[e])return new i({key:t,iv:n,mode:e,decrypt:!0});throw new TypeError("invalid suite type")}t.createCipher=t.Cipher=function(e,t){var n,i;if(e=e.toLowerCase(),o[e])n=o[e].key,i=o[e].iv;else{if(!s[e])throw new TypeError("invalid suite type");n=8*s[e].key,i=s[e].iv}var r=a(t,!1,n,i);return u(e,r.key,r.iv)},t.createCipheriv=t.Cipheriv=u,t.createDecipher=t.Decipher=function(e,t){var n,i;if(e=e.toLowerCase(),o[e])n=o[e].key,i=o[e].iv;else{if(!s[e])throw new TypeError("invalid suite type");n=8*s[e].key,i=s[e].iv}var r=a(t,!1,n,i);return c(e,r.key,r.iv)},t.createDecipheriv=t.Decipheriv=c,t.listCiphers=t.getCiphers=function(){return Object.keys(s).concat(r.getCiphers())}},"Vcj/":function(e,t){},VqvS:function(e,t,n){var i=n("LC74"),r=n("ps4E");function o(e){r.call(this,e),this.enc="pem"}i(o,r),e.exports=o,o.prototype.encode=function(e,t){for(var n=r.prototype.encode.call(this,e).toString("base64"),i=["-----BEGIN "+t.label+"-----"],o=0;o0)n.left||(n.left=new a,n.left.segment=i.value()),n=n.left;else if(r<0)n.right||(n.right=new a,n.right.segment=i.value()),n=n.right;else{if(!i.hasNext())break;i.next(),n.mid||(n.mid=new a,n.mid.segment=i.value()),n=n.mid}}var o=n.value;return n.value=t,n.key=e,o},e.prototype.get=function(e){for(var t=this._iter.reset(e),n=this._root;n;){var i=t.cmp(n.segment);if(i>0)n=n.left;else if(i<0)n=n.right;else{if(!t.hasNext())break;t.next(),n=n.mid}}return n?n.value:void 0},e.prototype.findSubstr=function(e){for(var t=this._iter.reset(e),n=this._root,i=void 0;n;){var r=t.cmp(n.segment);if(r>0)n=n.left;else if(r<0)n=n.right;else{if(!t.hasNext())break;t.next(),i=n.value||i,n=n.mid}}return n&&n.value||i},e.prototype.forEach=function(e){this._forEach(this._root,e)},e.prototype._forEach=function(e,t){e&&(this._forEach(e.left,t),e.value&&t(e.value,e.key),this._forEach(e.mid,t),this._forEach(e.right,t))},e}(),c=function(){function e(){this.map=new Map,this.ignoreCase=!1}return e.prototype.set=function(e,t){this.map.set(this.toKey(e),t)},e.prototype.get=function(e){return this.map.get(this.toKey(e))},e.prototype.toKey=function(e){var t=e.toString();return this.ignoreCase&&(t=t.toLowerCase()),t},e}(),l=function(e){function t(t,n){void 0===n&&(n=1);var i=e.call(this)||this;return i._limit=t,i._ratio=Math.min(Math.max(0,n),1),i}return r(t,e),t.prototype.get=function(t){return e.prototype.get.call(this,t,2)},t.prototype.peek=function(t){return e.prototype.get.call(this,t,0)},t.prototype.set=function(t,n){e.prototype.set.call(this,t,n,2),this.checkTrim()},t.prototype.checkTrim=function(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))},t}(function(){function e(){this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0}return e.prototype.clear=function(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0},Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),e.prototype.get=function(e,t){void 0===t&&(t=0);var n=this._map.get(e);if(n)return 0!==t&&this.touch(n,t),n.value},e.prototype.set=function(e,t,n){void 0===n&&(n=0);var i=this._map.get(e);if(i)i.value=t,0!==n&&this.touch(i,n);else{switch(i={key:e,value:t,next:void 0,previous:void 0},n){case 0:this.addItemLast(i);break;case 1:this.addItemFirst(i);break;case 2:default:this.addItemLast(i)}this._map.set(e,i),this._size++}},e.prototype.delete=function(e){return!!this.remove(e)},e.prototype.remove=function(e){var t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value},e.prototype.forEach=function(e,t){for(var n=this._head;n;)t?e.bind(t)(n.value,n.key,this):e(n.value,n.key,this),n=n.next},e.prototype.trimOld=function(e){if(!(e>=this.size))if(0!==e){for(var t=this._head,n=this.size;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0)}else this.clear()},e.prototype.addItemFirst=function(e){if(this._head||this._tail){if(!this._head)throw new Error("Invalid list");e.next=this._head,this._head.previous=e}else this._tail=e;this._head=e},e.prototype.addItemLast=function(e){if(this._head||this._tail){if(!this._tail)throw new Error("Invalid list");e.previous=this._tail,this._tail.next=e}else this._head=e;this._tail=e},e.prototype.removeItem=function(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{var t=e.next,n=e.previous;if(!t||!n)throw new Error("Invalid list");t.previous=n,n.next=t}e.next=void 0,e.previous=void 0},e.prototype.touch=function(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(1===t||2===t)if(1===t){if(e===this._head)return;var n=e.next,i=e.previous;e===this._tail?(i.next=void 0,this._tail=i):(n.previous=i,i.next=n),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e}else if(2===t){if(e===this._tail)return;n=e.next,i=e.previous;e===this._head?(n.previous=void 0,this._head=n):(n.previous=i,i.next=n),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e}},e.prototype.toJSON=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),e},e}())},WUwp:function(e,t){},WZeM:function(e,t,n){"use strict";n.d(t,"a",function(){return r}),t.b=function(e){return new r(e)};var i=n("7/Cv"),r=function(){function e(e){this.domNode=e,this._maxWidth=-1,this._width=-1,this._height=-1,this._top=-1,this._left=-1,this._bottom=-1,this._right=-1,this._fontFamily="",this._fontWeight="",this._fontSize=-1,this._lineHeight=-1,this._letterSpacing=-100,this._className="",this._display="",this._position="",this._visibility="",this._layerHint=!1}return e.prototype.setMaxWidth=function(e){this._maxWidth!==e&&(this._maxWidth=e,this.domNode.style.maxWidth=this._maxWidth+"px")},e.prototype.setWidth=function(e){this._width!==e&&(this._width=e,this.domNode.style.width=this._width+"px")},e.prototype.setHeight=function(e){this._height!==e&&(this._height=e,this.domNode.style.height=this._height+"px")},e.prototype.setTop=function(e){this._top!==e&&(this._top=e,this.domNode.style.top=this._top+"px")},e.prototype.unsetTop=function(){-1!==this._top&&(this._top=-1,this.domNode.style.top="")},e.prototype.setLeft=function(e){this._left!==e&&(this._left=e,this.domNode.style.left=this._left+"px")},e.prototype.setBottom=function(e){this._bottom!==e&&(this._bottom=e,this.domNode.style.bottom=this._bottom+"px")},e.prototype.setRight=function(e){this._right!==e&&(this._right=e,this.domNode.style.right=this._right+"px")},e.prototype.setFontFamily=function(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)},e.prototype.setFontWeight=function(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)},e.prototype.setFontSize=function(e){this._fontSize!==e&&(this._fontSize=e,this.domNode.style.fontSize=this._fontSize+"px")},e.prototype.setLineHeight=function(e){this._lineHeight!==e&&(this._lineHeight=e,this.domNode.style.lineHeight=this._lineHeight+"px")},e.prototype.setLetterSpacing=function(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.domNode.style.letterSpacing=this._letterSpacing+"px")},e.prototype.setClassName=function(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)},e.prototype.toggleClassName=function(e,t){i.R(this.domNode,e,t),this._className=this.domNode.className},e.prototype.setDisplay=function(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)},e.prototype.setPosition=function(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)},e.prototype.setVisibility=function(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)},e.prototype.setLayerHinting=function(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.willChange=this._layerHint?"transform":"auto")},e.prototype.setAttribute=function(e,t){this.domNode.setAttribute(e,t)},e.prototype.removeAttribute=function(e){this.domNode.removeAttribute(e)},e.prototype.appendChild=function(e){this.domNode.appendChild(e.domNode)},e.prototype.removeChild=function(e){this.domNode.removeChild(e.domNode)},e}()},X3l8:function(e,t,n){var i=n("EuP9"),r=i.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=i:(o(i,t),t.Buffer=s),s.prototype=Object.create(r.prototype),o(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i.SlowBuffer(e)}},X4X3:function(e,t,n){"use strict";var i=n("oYso").Buffer,r=i.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(i.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=d,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=i.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var i=n.charCodeAt(n.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function l(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return r>0&&(e.lastNeed=r-1),r;if(--i=0)return r>0&&(e.lastNeed=r-2),r;if(--i=0)return r>0&&(2===r?r=0:e.lastNeed=r-3),r;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var i=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},X6iQ:function(e,t,n){"use strict";function i(e,t){return function e(t,n,i,r,o){if(r<=i)return;var s=i+(r-i)/2|0;e(t,n,i,s,o);e(t,n,s+1,r,o);if(n(t[s],t[s+1])<=0)return;!function(e,t,n,i,r,o){for(var s=n,a=i+1,u=n;u<=r;u++)o[u]=e[u];for(var u=n;u<=r;u++)s>i?e[u]=o[a++]:a>r?e[u]=o[s++]:t(o[a],o[s])<0?e[u]=o[a++]:e[u]=o[s++]}(t,n,i,s,r,o)}(e,t,0,e.length-1,[]),e}function r(e,t){for(var n=0;n0))return o;r=o-1}}return-(i+1)},t.h=function(e,t){var n=0,i=e.length;if(0===i)return 0;for(;n0},t.e=function(e,t){if(!t)return e.filter(function(t,n){return e.indexOf(t)===n});var n=Object.create(null);return e.filter(function(e){var i=t(e);return!n[i]&&(n[i]=!0,!0)})},t.f=function(e){var t=new Set;return e.filter(function(e){return!t.has(e)&&(t.add(e),!0)})},t.j=r,t.i=function(e,t,n){void 0===n&&(n=void 0);var i=r(e,t);return i<0?n:e[i]},t.k=function(e){var t;return(t=[]).concat.apply(t,e)},t.r=function(e,t){var n="number"==typeof t?e:0;"number"==typeof t?n=e:(n=0,t=e);var i=[];if(n<=t)for(var r=n;rt;r--)i.push(r);return i},t.a=function(e,t,n){var i=e.slice(0,t),r=e.slice(t);return i.concat(n,r)},t.q=function(e,t){var n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))},t.p=function(e,t){var n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))},t.b=function(e){return Array.isArray(e)?e:[e]}},XTA7:function(e,t){},Y6WZ:function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"b",function(){return s});var i=n("CQAd"),r=function(){return function(e,t){this.index=e,this.remainder=t}}(),o=function(){function e(e){this.values=e,this.prefixSum=new Uint32Array(e.length),this.prefixSumValidIndex=new Int32Array(1),this.prefixSumValidIndex[0]=-1}return e.prototype.getCount=function(){return this.values.length},e.prototype.insertValues=function(e,t){e=Object(i.b)(e);var n=this.values,r=this.prefixSum,o=t.length;return 0!==o&&(this.values=new Uint32Array(n.length+o),this.values.set(n.subarray(0,e),0),this.values.set(n.subarray(e),e+o),this.values.set(t,e),e-1=0&&this.prefixSum.set(r.subarray(0,this.prefixSumValidIndex[0]+1)),!0)},e.prototype.changeValue=function(e,t){return e=Object(i.b)(e),t=Object(i.b)(t),this.values[e]!==t&&(this.values[e]=t,e-1=n.length)return!1;var o=n.length-e;return t>=o&&(t=o),0!==t&&(this.values=new Uint32Array(n.length-t),this.values.set(n.subarray(0,e),0),this.values.set(n.subarray(e+t),e),this.prefixSum=new Uint32Array(this.values.length),e-1=0&&this.prefixSum.set(r.subarray(0,this.prefixSumValidIndex[0]+1)),!0)},e.prototype.getTotalValue=function(){return 0===this.values.length?0:this._getAccumulatedValue(this.values.length-1)},e.prototype.getAccumulatedValue=function(e){return e<0?0:(e=Object(i.b)(e),this._getAccumulatedValue(e))},e.prototype._getAccumulatedValue=function(e){if(e<=this.prefixSumValidIndex[0])return this.prefixSum[e];var t=this.prefixSumValidIndex[0]+1;0===t&&(this.prefixSum[0]=this.values[0],t++),e>=this.values.length&&(e=this.values.length-1);for(var n=t;n<=e;n++)this.prefixSum[n]=this.prefixSum[n-1]+this.values[n];return this.prefixSumValidIndex[0]=Math.max(this.prefixSumValidIndex[0],e),this.prefixSum[e]},e.prototype.getIndexOf=function(e){e=Math.floor(e),this.getTotalValue();for(var t=0,n=this.values.length-1,i=0,o=0,s=0;t<=n;)if(i=t+(n-t)/2|0,e<(s=(o=this.prefixSum[i])-this.values[i]))n=i-1;else{if(!(e>=o))break;t=i+1}return new r(i,e-s)},e}(),s=function(){function e(e){this._cacheAccumulatedValueStart=0,this._cache=null,this._actual=new o(e),this._bustCache()}return e.prototype._bustCache=function(){this._cacheAccumulatedValueStart=0,this._cache=null},e.prototype.insertValues=function(e,t){this._actual.insertValues(e,t)&&this._bustCache()},e.prototype.changeValue=function(e,t){this._actual.changeValue(e,t)&&this._bustCache()},e.prototype.removeValues=function(e,t){this._actual.removeValues(e,t)&&this._bustCache()},e.prototype.getTotalValue=function(){return this._actual.getTotalValue()},e.prototype.getAccumulatedValue=function(e){return this._actual.getAccumulatedValue(e)},e.prototype.getIndexOf=function(e){if(e=Math.floor(e),null!==this._cache){var t=e-this._cacheAccumulatedValueStart;if(t>=0&&ta?t=e(t):t.length=this._delta8){var n=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-n,e.length),0===this.pending.length&&(this.pending=null),e=i.join32(e,0,e.length-n,this.endian);for(var r=0;r>>24&255,i[r++]=e>>>16&255,i[r++]=e>>>8&255,i[r++]=255&e}else for(i[r++]=255&e,i[r++]=e>>>8&255,i[r++]=e>>>16&255,i[r++]=e>>>24&255,i[r++]=0,i[r++]=0,i[r++]=0,i[r++]=0,o=8;o0||this.m_modifiedCount>0)&&this.m_changes.push(new i(this.m_originalStart,this.m_originalCount,this.m_modifiedStart,this.m_modifiedCount)),this.m_originalCount=0,this.m_modifiedCount=0,this.m_originalStart=Number.MAX_VALUE,this.m_modifiedStart=Number.MAX_VALUE},e.prototype.AddOriginalElement=function(e,t){this.m_originalStart=Math.min(this.m_originalStart,e),this.m_modifiedStart=Math.min(this.m_modifiedStart,t),this.m_originalCount++},e.prototype.AddModifiedElement=function(e,t){this.m_originalStart=Math.min(this.m_originalStart,e),this.m_modifiedStart=Math.min(this.m_modifiedStart,t),this.m_modifiedCount++},e.prototype.getChanges=function(){return(this.m_originalCount>0||this.m_modifiedCount>0)&&this.MarkNextChange(),this.m_changes},e.prototype.getReverseChanges=function(){return(this.m_originalCount>0||this.m_modifiedCount>0)&&this.MarkNextChange(),this.m_changes.reverse(),this.m_changes},e}(),u=function(){function e(e,t,n){void 0===n&&(n=null),this.OriginalSequence=e,this.ModifiedSequence=t,this.ContinueProcessingPredicate=n,this.m_forwardHistory=[],this.m_reverseHistory=[]}return e.prototype.ElementsAreEqual=function(e,t){return this.OriginalSequence.getElementAtIndex(e)===this.ModifiedSequence.getElementAtIndex(t)},e.prototype.OriginalElementsAreEqual=function(e,t){return this.OriginalSequence.getElementAtIndex(e)===this.OriginalSequence.getElementAtIndex(t)},e.prototype.ModifiedElementsAreEqual=function(e,t){return this.ModifiedSequence.getElementAtIndex(e)===this.ModifiedSequence.getElementAtIndex(t)},e.prototype.ComputeDiff=function(e){return this._ComputeDiff(0,this.OriginalSequence.getLength()-1,0,this.ModifiedSequence.getLength()-1,e)},e.prototype._ComputeDiff=function(e,t,n,i,r){var o=this.ComputeDiffRecursive(e,t,n,i,[!1]);return r?this.PrettifyChanges(o):o},e.prototype.ComputeDiffRecursive=function(e,t,n,r,s){for(s[0]=!1;e<=t&&n<=r&&this.ElementsAreEqual(e,n);)e++,n++;for(;t>=e&&r>=n&&this.ElementsAreEqual(t,r);)t--,r--;if(e>t||n>r){var a=void 0;return n<=r?(o.Assert(e===t+1,"originalStart should only be one more than originalEnd"),a=[new i(e,0,n,r-n+1)]):e<=t?(o.Assert(n===r+1,"modifiedStart should only be one more than modifiedEnd"),a=[new i(e,t-e+1,n,0)]):(o.Assert(e===t+1,"originalStart should only be one more than originalEnd"),o.Assert(n===r+1,"modifiedStart should only be one more than modifiedEnd"),a=[]),a}var u=[0],c=[0],l=this.ComputeRecursionPoint(e,t,n,r,u,c,s),d=u[0],h=c[0];if(null!==l)return l;if(!s[0]){var f=this.ComputeDiffRecursive(e,d,n,h,s),p=[];return p=s[0]?[new i(d+1,t-(d+1)+1,h+1,r-(h+1)+1)]:this.ComputeDiffRecursive(d+1,t,h+1,r,s),this.ConcatenateChanges(f,p)}return[new i(e,t-e+1,n,r-n+1)]},e.prototype.WALKTRACE=function(e,t,n,r,o,s,u,c,l,d,h,f,p,g,m,v,_,b){var y,w,C=null,S=new a,x=t,L=n,O=p[0]-v[0]-r,k=Number.MIN_VALUE,N=this.m_forwardHistory.length-1;do{(w=O+e)===x||w=0&&(e=(l=this.m_forwardHistory[N])[0],x=1,L=l.length-1)}while(--N>=-1);if(y=S.getReverseChanges(),b[0]){var E=p[0]+1,I=v[0]+1;if(null!==y&&y.length>0){var D=y[y.length-1];E=Math.max(E,D.getOriginalEnd()),I=Math.max(I,D.getModifiedEnd())}C=[new i(E,f-E+1,I,m-I+1)]}else{S=new a,x=s,L=u,O=p[0]-v[0]-c,k=Number.MAX_VALUE,N=_?this.m_reverseHistory.length-1:this.m_reverseHistory.length-2;do{(w=O+o)===x||w=d[w+1]?(g=(h=d[w+1]-1)-O-c,h>k&&S.MarkNextChange(),k=h+1,S.AddOriginalElement(h+1,g+1),O=w+1-o):(g=(h=d[w-1])-O-c,h>k&&S.MarkNextChange(),k=h,S.AddModifiedElement(h+1,g+1),O=w-1-o),N>=0&&(o=(d=this.m_reverseHistory[N])[0],x=1,L=d.length-1)}while(--N>=-1);C=S.getChanges()}return this.ConcatenateChanges(y,C)},e.prototype.ComputeRecursionPoint=function(e,t,n,r,o,a,u){var c,l=0,d=0,h=0,f=0,p=0,g=0;e--,n--,o[0]=0,a[0]=0,this.m_forwardHistory=[],this.m_reverseHistory=[];var m,v,_=t-e+(r-n),b=_+1,y=new Array(b),w=new Array(b),C=r-n,S=t-e,x=e-n,L=t-r,O=(S-C)%2==0;for(y[C]=e,w[S]=t,u[0]=!1,c=1;c<=_/2+1;c++){var k=0,N=0;for(h=this.ClipDiagonalBound(C-c,c,C,b),f=this.ClipDiagonalBound(C+c,c,C,b),m=h;m<=f;m+=2){for(d=(l=m===h||mk+N&&(k=l,N=d),!O&&Math.abs(m-S)<=c-1&&l>=w[m])return o[0]=l,a[0]=d,v<=w[m]&&c<=1448?this.WALKTRACE(C,h,f,x,S,p,g,L,y,w,l,t,o,d,r,a,O,u):null}var E=(k-e+(N-n)-c)/2;if(null!==this.ContinueProcessingPredicate&&!this.ContinueProcessingPredicate(k,this.OriginalSequence,E))return u[0]=!0,o[0]=k,a[0]=N,E>0&&c<=1448?this.WALKTRACE(C,h,f,x,S,p,g,L,y,w,l,t,o,d,r,a,O,u):[new i(++e,t-e+1,++n,r-n+1)];for(p=this.ClipDiagonalBound(S-c,c,S,b),g=this.ClipDiagonalBound(S+c,c,S,b),m=p;m<=g;m+=2){for(d=(l=m===p||m=w[m+1]?w[m+1]-1:w[m-1])-(m-S)-L,v=l;l>e&&d>n&&this.ElementsAreEqual(l,d);)l--,d--;if(w[m]=l,O&&Math.abs(m-C)<=c&&l<=y[m])return o[0]=l,a[0]=d,v>=y[m]&&c<=1448?this.WALKTRACE(C,h,f,x,S,p,g,L,y,w,l,t,o,d,r,a,O,u):null}if(c<=1447){var I=new Array(f-h+2);I[0]=C-h+1,s.Copy(y,h,I,1,f-h+1),this.m_forwardHistory.push(I),(I=new Array(g-p+2))[0]=S-p+1,s.Copy(w,p,I,1,g-p+1),this.m_reverseHistory.push(I)}}return this.WALKTRACE(C,h,f,x,S,p,g,L,y,w,l,t,o,d,r,a,O,u)},e.prototype.PrettifyChanges=function(e){for(var t=0;t0,s=n.modifiedLength>0;n.originalStart+n.originalLength=0;t--){n=e[t],i=0,r=0;if(t>0){var u=e[t-1];u.originalLength>0&&(i=u.originalStart+u.originalLength),u.modifiedLength>0&&(r=u.modifiedStart+u.modifiedLength)}o=n.originalLength>0,s=n.modifiedLength>0;for(var c=0,l=this._boundaryScore(n.originalStart,n.originalLength,n.modifiedStart,n.modifiedLength),d=1;;d++){var h=n.originalStart-d,f=n.modifiedStart-d;if(hl&&(l=p,c=d)}n.originalStart-=c,n.modifiedStart-=c}return e},e.prototype._OriginalIsBoundary=function(e){if(e<=0||e>=this.OriginalSequence.getLength()-1)return!0;var t=this.OriginalSequence.getElementAtIndex(e);return"string"==typeof t&&/^\s*$/.test(t)},e.prototype._OriginalRegionIsBoundary=function(e,t){if(this._OriginalIsBoundary(e)||this._OriginalIsBoundary(e-1))return!0;if(t>0){var n=e+t;if(this._OriginalIsBoundary(n-1)||this._OriginalIsBoundary(n))return!0}return!1},e.prototype._ModifiedIsBoundary=function(e){if(e<=0||e>=this.ModifiedSequence.getLength()-1)return!0;var t=this.ModifiedSequence.getElementAtIndex(e);return"string"==typeof t&&/^\s*$/.test(t)},e.prototype._ModifiedRegionIsBoundary=function(e,t){if(this._ModifiedIsBoundary(e)||this._ModifiedIsBoundary(e-1))return!0;if(t>0){var n=e+t;if(this._ModifiedIsBoundary(n-1)||this._ModifiedIsBoundary(n))return!0}return!1},e.prototype._boundaryScore=function(e,t,n,i){return(this._OriginalRegionIsBoundary(e,t)?1:0)+(this._ModifiedRegionIsBoundary(n,i)?1:0)},e.prototype.ConcatenateChanges=function(e,t){var n=[];if(0===e.length||0===t.length)return t.length>0?t:e;if(this.ChangesOverlap(e[e.length-1],t[0],n)){var i=new Array(e.length+t.length-1);return s.Copy(e,0,i,0,e.length-1),i[e.length-1]=n[0],s.Copy(t,1,i,e.length,t.length-1),i}i=new Array(e.length+t.length);return s.Copy(e,0,i,0,e.length),s.Copy(t,0,i,e.length,t.length),i},e.prototype.ChangesOverlap=function(e,t,n){if(o.Assert(e.originalStart<=t.originalStart,"Left change is not less than or equal to right change"),o.Assert(e.modifiedStart<=t.modifiedStart,"Left change is not less than or equal to right change"),e.originalStart+e.originalLength>=t.originalStart||e.modifiedStart+e.modifiedLength>=t.modifiedStart){var r=e.originalStart,s=e.originalLength,a=e.modifiedStart,u=e.modifiedLength;return e.originalStart+e.originalLength>=t.originalStart&&(s=t.originalStart+t.originalLength-e.originalStart),e.modifiedStart+e.modifiedLength>=t.modifiedStart&&(u=t.modifiedStart+t.modifiedLength-e.modifiedStart),n[0]=new i(r,s,a,u),!0}return n[0]=null,!1},e.prototype.ClipDiagonalBound=function(e,t,n,i){if(e>=0&&et.getLineMinColumn(n)?i.a.isLowSurrogate(t,n,r-2)?r-=2:r-=1:n>1&&(n-=1,r=t.getLineMaxColumn(n)),new s(n,r,0)},e.moveLeft=function(t,n,i,r,o){var s,a;if(i.hasSelection()&&!r)s=i.selection.startLineNumber,a=i.selection.startColumn;else{var u=e.left(t,n,i.position.lineNumber,i.position.column-(o-1));s=u.lineNumber,a=u.column}return i.move(r,s,a,0)},e.right=function(e,t,n,r){return rl?(n=l,u?r=t.getLineMaxColumn(n):(r=Math.min(t.getLineMaxColumn(n),r),i.a.isInsideSurrogatePair(t,n,r)&&(r-=1))):(r=i.a.columnFromVisibleColumn2(e,t,n,c),i.a.isInsideSurrogatePair(t,n,r)&&(r-=1)),o=c-i.a.visibleColumnFromColumn(t.getLineContent(n),r,e.tabSize),new s(n,r,o)},e.moveDown=function(t,n,i,r,o){var s,a;i.hasSelection()&&!r?(s=i.selection.endLineNumber,a=i.selection.endColumn):(s=i.position.lineNumber,a=i.position.column);var u=e.down(t,n,s,a,i.leftoverVisibleColumns,o,!0);return i.move(r,u.lineNumber,u.column,u.leftoverVisibleColumns)},e.translateDown=function(t,n,s){var a=s.selection,u=e.down(t,n,a.selectionStartLineNumber,a.selectionStartColumn,s.selectionStartLeftoverVisibleColumns,1,!1),c=e.down(t,n,a.positionLineNumber,a.positionColumn,s.leftoverVisibleColumns,1,!1);return new i.f(new o.a(u.lineNumber,u.column,u.lineNumber,u.column),u.leftoverVisibleColumns,new r.a(c.lineNumber,c.column),c.leftoverVisibleColumns)},e.up=function(e,t,n,r,o,a,u){var c=i.a.visibleColumnFromColumn(t.getLineContent(n),r,e.tabSize)+o;return(n-=a)<1?(n=1,u?r=t.getLineMinColumn(n):(r=Math.min(t.getLineMaxColumn(n),r),i.a.isInsideSurrogatePair(t,n,r)&&(r-=1))):(r=i.a.columnFromVisibleColumn2(e,t,n,c),i.a.isInsideSurrogatePair(t,n,r)&&(r-=1)),o=c-i.a.visibleColumnFromColumn(t.getLineContent(n),r,e.tabSize),new s(n,r,o)},e.moveUp=function(t,n,i,r,o){var s,a;i.hasSelection()&&!r?(s=i.selection.startLineNumber,a=i.selection.startColumn):(s=i.position.lineNumber,a=i.position.column);var u=e.up(t,n,s,a,i.leftoverVisibleColumns,o,!0);return i.move(r,u.lineNumber,u.column,u.leftoverVisibleColumns)},e.translateUp=function(t,n,s){var a=s.selection,u=e.up(t,n,a.selectionStartLineNumber,a.selectionStartColumn,s.selectionStartLeftoverVisibleColumns,1,!1),c=e.up(t,n,a.positionLineNumber,a.positionColumn,s.leftoverVisibleColumns,1,!1);return new i.f(new o.a(u.lineNumber,u.column,u.lineNumber,u.column),u.leftoverVisibleColumns,new r.a(c.lineNumber,c.column),c.leftoverVisibleColumns)},e.moveToBeginningOfLine=function(e,t,n,i){var r,o=n.position.lineNumber,s=t.getLineMinColumn(o),a=t.getLineFirstNonWhitespaceColumn(o)||s;return r=n.position.column===a?s:a,n.move(i,o,r,0)},e.moveToEndOfLine=function(e,t,n,i){var r=n.position.lineNumber,o=t.getLineMaxColumn(r);return n.move(i,r,o,0)},e.moveToBeginningOfBuffer=function(e,t,n,i){return n.move(i,1,1,0)},e.moveToEndOfBuffer=function(e,t,n,i){var r=t.getLineCount(),o=t.getLineMaxColumn(r);return n.move(i,r,o,0)},e}()},ZWAj:function(e,t,n){"use strict";n.d(t,"b",function(){return s}),n.d(t,"a",function(){return a});var i=n("aL7J"),r=n("artP"),o=n("vTy2"),s=function(){function e(e,t,n,i,r){this.value=e,this.selectionStart=t,this.selectionEnd=n,this.selectionStartPosition=i,this.selectionEndPosition=r}return e.prototype.toString=function(){return"[ <"+this.value+">, selectionStart: "+this.selectionStart+", selectionEnd: "+this.selectionEnd+"]"},e.readFromTextArea=function(t){return new e(t.getValue(),t.getSelectionStart(),t.getSelectionEnd(),null,null)},e.prototype.collapseSelection=function(){return new e(this.value,this.value.length,this.value.length,null,null)},e.prototype.writeToTextArea=function(e,t,n){t.setValue(e,this.value),n&&t.setSelectionRange(e,this.selectionStart,this.selectionEnd)},e.prototype.deduceEditorPosition=function(e){if(e<=this.selectionStart){var t=this.value.substring(e,this.selectionStart);return this._finishDeduceEditorPosition(this.selectionStartPosition,t,-1)}if(e>=this.selectionEnd){t=this.value.substring(this.selectionEnd,e);return this._finishDeduceEditorPosition(this.selectionEndPosition,t,1)}var n=this.value.substring(this.selectionStart,e);if(-1===n.indexOf(String.fromCharCode(8230)))return this._finishDeduceEditorPosition(this.selectionStartPosition,n,1);var i=this.value.substring(e,this.selectionEnd);return this._finishDeduceEditorPosition(this.selectionEndPosition,i,-1)},e.prototype._finishDeduceEditorPosition=function(e,t,n){for(var i=0,r=-1;-1!==(r=t.indexOf("\n",r+1));)i++;return[e,n*t.length,i]},e.selectedText=function(t){return new e(t,0,t.length,null,null)},e.deduceInput=function(e,t,n,r){if(!e)return{text:"",replaceCharCnt:0};var o=e.value,s=e.selectionStart,a=e.selectionEnd,u=t.value,c=t.selectionStart,l=t.selectionEnd;r&&o.length>0&&s===a&&c===l&&!i.J(u,o)&&i.m(u,o)&&(s=0,a=0);var d=o.substring(a),h=u.substring(l),f=i.c(d,h);u=u.substring(0,u.length-f);var p=(o=o.substring(0,o.length-f)).substring(0,s),g=u.substring(0,c),m=i.b(p,g);if(u=u.substring(m),o=o.substring(m),c-=m,s-=m,l-=m,a-=m,n&&c===l&&o.length>0){var v=null;if(c===u.length?i.J(u,o)&&(v=u.substring(o.length)):i.m(u,o)&&(v=u.substring(0,u.length-o.length)),null!==v&&v.length>0&&(/\uFE0F/.test(v)||i.f(v)))return{text:v,replaceCharCnt:0}}return c===l?o===u&&0===s&&a===o.length&&c===u.length&&-1===u.indexOf("\n")&&i.g(u)?{text:"",replaceCharCnt:0}:{text:u,replaceCharCnt:p.length-m}:{text:u,replaceCharCnt:a-s}},e.EMPTY=new e("",0,0,null,null),e}(),a=function(){function e(){}return e._getPageOfLine=function(t){return Math.floor((t-1)/e._LINES_PER_PAGE)},e._getRangeForPage=function(t){var n=t*e._LINES_PER_PAGE,i=n+1,r=n+e._LINES_PER_PAGE;return new o.a(i,1,r+1,1)},e.fromEditorSelection=function(t,n,i,a){var u,c=e._getPageOfLine(i.startLineNumber),l=e._getRangeForPage(c),d=e._getPageOfLine(i.endLineNumber),h=e._getRangeForPage(d),f=l.intersectRanges(new o.a(1,1,i.startLineNumber,i.startColumn)),p=n.getValueInRange(f,1),g=n.getLineCount(),m=n.getLineMaxColumn(g),v=h.intersectRanges(new o.a(i.endLineNumber,i.endColumn,g,m)),_=n.getValueInRange(v,1);if(c===d||c+1===d)u=n.getValueInRange(i,1);else{var b=l.intersectRanges(i),y=h.intersectRanges(i);u=n.getValueInRange(b,1)+String.fromCharCode(8230)+n.getValueInRange(y,1)}if(a){p.length>500&&(p=p.substring(p.length-500,p.length)),_.length>500&&(_=_.substring(0,500)),u.length>1e3&&(u=u.substring(0,500)+String.fromCharCode(8230)+u.substring(u.length-500,u.length))}return new s(p+u+_,p.length,p.length+u.length,new r.a(i.startLineNumber,i.startColumn),new r.a(i.endLineNumber,i.endColumn))},e._LINES_PER_PAGE=10,e}()},ZYUE:function(e,t,n){"use strict";t.c=function(e){return h(e)||e.authority},t.e=function(e,t,n){void 0===n&&(n=l(e));if(e===t)return!0;if(!e||!t)return!1;if(e.scheme!==t.scheme||!d(e.authority,t.authority))return!1;var i=e.path||"/",r=t.path||"/";return i===r||n&&Object(a.n)(i||"/",r||"/")},t.b=h,t.d=function(e){if(0===e.path.length)return e;if(e.scheme===u.b.file)return s.a.file(o.dirname(f(e)));var t=o.posix.dirname(e.path);e.authority&&t.length&&47!==t.charCodeAt(0)&&(console.error('dirname("'+e.toString+")) resulted in a relative path"),t="/");return e.with({path:t})},t.f=function(e){for(var t,n,i=[],r=1;r1&&e.scheme===u.b.file?"//"+e.authority+n:c.g&&47===n.charCodeAt(0)&&r.b(n.charCodeAt(1))&&58===n.charCodeAt(2)?n.substr(1):n,c.g&&(t=t.replace(/\//g,"\\")),t}!function(e){e.META_DATA_LABEL="label",e.META_DATA_DESCRIPTION="description",e.META_DATA_SIZE="size",e.META_DATA_MIME="mime",e.parseMetaData=function(t){var n=new Map;t.path.substring(t.path.indexOf(";")+1,t.path.lastIndexOf(";")).split(";").forEach(function(e){var t=e.split(":"),i=t[0],r=t[1];i&&r&&n.set(i,r)});var i=t.path.substring(0,t.path.indexOf(";"));return i&&n.set(e.META_DATA_MIME,i),n}}(i||(i={}))},ZfGv:function(e,t,n){"use strict";(function(e,i){n.d(t,"g",function(){return p}),n.d(t,"d",function(){return g}),n.d(t,"c",function(){return m}),n.d(t,"e",function(){return v}),n.d(t,"f",function(){return _}),n.d(t,"b",function(){return b}),t.h=function(t){null===y&&(y=b.setImmediate?b.setImmediate.bind(b):void 0!==e&&"function"==typeof e.nextTick?e.nextTick.bind(e):b.setTimeout.bind(b));return y(t)},n.d(t,"a",function(){return w});var r=!1,o=!1,s=!1,a=!1,u=!1,c=void 0,l=void 0!==e&&void 0!==e.versions&&void 0!==e.versions.electron&&"renderer"===e.type;if("object"!=typeof navigator||l){if("object"==typeof e){r="win32"===e.platform,o="darwin"===e.platform,s="linux"===e.platform,"en","en";var d=Object({NODE_ENV:"production"}).VSCODE_NLS_CONFIG;if(d)try{var h=JSON.parse(d),f=h.availableLanguages["*"];h.locale,f||"en",h._translationsConfigFile}catch(e){}a=!0}}else r=(c=navigator.userAgent).indexOf("Windows")>=0,o=c.indexOf("Macintosh")>=0,s=c.indexOf("Linux")>=0,u=!0,navigator.language;var p=r,g=o,m=s,v=a,_=u,b="object"==typeof self?self:"object"==typeof i?i:{},y=null;var w=o?2:r?1:3}).call(t,n("W2nU"),n("DuR2"))},Zq1s:function(e,t,n){var i=n("EXeW"),r=n("LYGd"),o=n("JaR3"),s=n("2JY6"),a=n("35aj"),u=n("X3l8").Buffer,c=u.alloc(128),l={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function d(e,t,n){var s=function(e){return"rmd160"===e||"ripemd160"===e?function(e){return(new r).update(e).digest()}:"md5"===e?i:function(t){return o(e).update(t).digest()}}(e),a="sha512"===e||"sha384"===e?128:64;t.length>a?t=s(t):t.lengththis._limit&&this._initialize(e.slice(e.length-this._limit))},e.prototype._initialize=function(e){this._history=new Set;for(var t=0,n=e;t=0);return r},o.prototype._randrange=function(e,t){var n=t.sub(e);return e.add(this._randbelow(n))},o.prototype.test=function(e,t,n){var r=e.bitLength(),o=i.mont(e),s=new i(1).toRed(o);t||(t=Math.max(1,r/48|0));for(var a=e.subn(1),u=0;!a.testn(u);u++);for(var c=e.shrn(u),l=a.toRed(o);t>0;t--){var d=this._randrange(new i(2),a);n&&n(d);var h=d.toRed(o).redPow(c);if(0!==h.cmp(s)&&0!==h.cmp(l)){for(var f=1;f0;t--){var l=this._randrange(new i(2),s),d=e.gcd(l);if(0!==d.cmpn(1))return d;var h=l.toRed(r).redPow(u);if(0!==h.cmp(o)&&0!==h.cmp(c)){for(var f=1;f=t.length?e:t[i]})},t.o=function(e){return e.replace(/[<>&]/g,function(e){switch(e){case"<":return"<";case">":return">";case"&":return"&";default:return e}})},t.p=o,t.M=function(e,t){void 0===t&&(t=" ");return a(s(e,t),t)},t.B=s,t.G=a,t.j=function(e){return e.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&").replace(/[\*]/g,".*")},t.J=function(e,t){if(e.length0?e.indexOf(t,n)===n:0===n&&e===t},t.k=function(e,t,n){void 0===n&&(n={});if(!e)throw new Error("Cannot create regex from empty string");t||(e=o(e));n.wholeWord&&(/\B/.test(e.charAt(0))||(e="\\b"+e),/\B/.test(e.charAt(e.length-1))||(e+="\\b"));var i="";n.global&&(i+="g");n.matchCase||(i+="i");n.multiline&&(i+="m");n.unicode&&(i+="u");return new RegExp(e,i)},t.E=function(e){if("^"===e.source||"^$"===e.source||"$"===e.source||"^\\s*$"===e.source)return!1;return!(!e.exec("")||0!==e.lastIndex)},t.D=function(e){return(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")},t.q=function(e){for(var t=0,n=e.length;t=0;n--){var i=e.charCodeAt(n);if(32!==i&&9!==i)return n}return-1},t.d=u,t.e=function(e,t){for(var n=Math.min(e.length,t.length),i=0;it.length?1:0},t.y=c,t.z=l,t.n=function(e,t){var n=e?e.length:0,i=t?t.length:0;if(n!==i)return!1;return h(e,t)},t.K=function(e,t){var n=t.length;if(t.length>e.length)return!1;return h(e,t,n)},t.b=function(e,t){var n,i=Math.min(e.length,t.length);for(n=0;n0&&65279===e.charCodeAt(0))},t.H=function(e){return btoa(encodeURIComponent(e))},t.F=function(e,t){for(var n="",i=0;it?1:0}function c(e){return e>=97&&e<=122}function l(e){return e>=65&&e<=90}function d(e){return c(e)||l(e)}function h(e,t,n){if(void 0===n&&(n=e.length),"string"!=typeof e||"string"!=typeof t)return!1;for(var i=0;i=11904&&e<=55215||e>=63744&&e<=64255||e>=65281&&e<=65374}var v=String.fromCharCode(65279)},aQx8:function(e,t,n){"use strict";t.c=function(e){return e.replace(/[\\/]/g,r.posix.sep)},t.a=function(e,t,n,o){void 0===o&&(o=r.sep);if(e===t)return!0;if(!e||!t)return!1;if(t.length>e.length)return!1;if(n){var s=Object(i.K)(e,t);if(!s)return!1;if(t.length===e.length)return!0;var a=t.length;return t.charAt(t.length-1)===o&&a--,e.charAt(a)===o}t.charAt(t.length-1)!==o&&(t+=o);return 0===e.indexOf(t)},t.b=function(e){return e>=65&&e<=90||e>=97&&e<=122};var i=n("aL7J"),r=n("/uRs")},aY2F:function(e,t,n){var i=n("LC74"),r=n("C015"),o=n("CzQx"),s=n("X3l8").Buffer,a=new Array(160);function u(){this.init(),this._w=a,o.call(this,128,112)}i(u,r),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=s.allocUnsafe(48);function t(t,n,i){e.writeInt32BE(t,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},e.exports=u},abWm:function(e,t,n){e.exports={decode:n("bkDy"),verify:n("mVLy"),sign:n("uXJe"),JsonWebTokenError:n("bxaG"),NotBeforeError:n("mIf9"),TokenExpiredError:n("Gz1/")}},am7U:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("hK2W"),o=n("vTy2"),s=n("iHM7"),a=n("/9db"),u=n("03Zz"),c=n("606G"),l=function(){function e(e,t,n){this._editRange=e,this._originalSelection=t,this._text=n}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._editRange,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return this._originalSelection.isEmpty()?new s.a(n.endLineNumber,Math.min(this._originalSelection.positionColumn,n.endColumn),n.endLineNumber,Math.min(this._originalSelection.positionColumn,n.endColumn)):new s.a(n.endLineNumber,n.endColumn-this._text.length,n.endLineNumber,n.endColumn)},e}(),d=n("4tuZ"),h=n("eoic"),f=n("Rfe2"),p=n("0ly5"),g=n("odeJ"),m=n("zxiH"),v=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),_=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},b=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},y=function(){function e(e,t){this.decorationIds=[],this.editor=e,this.editorWorkerService=t}return e.get=function(t){return t.getContribution(e.ID)},e.prototype.dispose=function(){},e.prototype.getId=function(){return e.ID},e.prototype.run=function(t,n){var i=this;this.currentRequest&&this.currentRequest.cancel();var r=this.editor.getSelection(),a=this.editor.getModel();if(a&&r){var u=r;if(u.startLineNumber===u.endLineNumber){var c=new d.a(this.editor,5),h=a.uri;return this.editorWorkerService.canNavigateValueSet(h)?(this.currentRequest=Object(g.f)(function(e){return i.editorWorkerService.navigateValueSet(h,u,n)}),this.currentRequest.then(function(n){if(n&&n.range&&n.value&&c.validate(i.editor)){var r=o.a.lift(n.range),a=n.range,d=n.value.length-(u.endColumn-u.startColumn);a={startLineNumber:a.startLineNumber,startColumn:a.startColumn,endLineNumber:a.endLineNumber,endColumn:a.startColumn+n.value.length},d>1&&(u=new s.a(u.startLineNumber,u.startColumn,u.endLineNumber,u.endColumn+d-1));var h=new l(r,u,n.value);i.editor.pushUndoStop(),i.editor.executeCommand(t,h),i.editor.pushUndoStop(),i.decorationIds=i.editor.deltaDecorations(i.decorationIds,[{range:a,options:e.DECORATION}]),i.decorationRemover&&i.decorationRemover.cancel(),i.decorationRemover=Object(g.l)(350),i.decorationRemover.then(function(){return i.decorationIds=i.editor.deltaDecorations(i.decorationIds,[])}).catch(m.e)}}).catch(m.e)):Promise.resolve(void 0)}}},e.ID="editor.contrib.inPlaceReplaceController",e.DECORATION=p.a.register({className:"valueSetReplacement"}),e=_([b(1,c.a)],e)}(),w=function(e){function t(){return e.call(this,{id:"editor.action.inPlaceReplace.up",label:r.a("InPlaceReplaceAction.previous.label","Replace with Previous Value"),alias:"Replace with Previous Value",precondition:a.a.writable,kbOpts:{kbExpr:a.a.editorTextFocus,primary:3154,weight:100}})||this}return v(t,e),t.prototype.run=function(e,t){var n=y.get(t);return n?n.run(this.id,!0):Promise.resolve(void 0)},t}(u.b),C=function(e){function t(){return e.call(this,{id:"editor.action.inPlaceReplace.down",label:r.a("InPlaceReplaceAction.next.label","Replace with Next Value"),alias:"Replace with Next Value",precondition:a.a.writable,kbOpts:{kbExpr:a.a.editorTextFocus,primary:3156,weight:100}})||this}return v(t,e),t.prototype.run=function(e,t){var n=y.get(t);return n?n.run(this.id,!1):Promise.resolve(void 0)},t}(u.b);Object(u.h)(y),Object(u.f)(w),Object(u.f)(C),Object(h.f)(function(e,t){var n=e.getColor(f.d);n&&t.addRule(".monaco-editor.vs .valueSetReplacement { outline: solid 2px "+n+"; }")})},annC:function(e,t,n){"use strict";var i=n("X3l8").Buffer,r=n("yNY4"),o=128,s=48,a=2;function u(e){if(i.isBuffer(e))return e;if("string"==typeof e)return i.from(e,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function c(e,t,n){for(var i=0;t+i=o&&--i,i}e.exports={derToJose:function(e,t){e=u(e);var n=r(t),c=n+1,l=e.length,d=0;if(e[d++]!==s)throw new Error('Could not find expected "seq"');var h=e[d++];if(h===(1|o)&&(h=e[d++]),l-d15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},h.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),n=-1;++n=0&&m0&&r){var N=function(e){r(e),e.children.forEach(N)};y.forEach(N)}var E=C.d.map(C.d.fromArray(y),L);return this._onDidSplice.fire({insertedNodes:v,deletedNodes:y}),E},e.prototype.rerender=function(e){if(0===e.length)throw new Error("Invalid tree location");var t=this.getTreeNodeWithListIndex(e),n=t.node,i=t.listIndex;t.revealed&&this.list.splice(i,1,[n])},e.prototype.getListIndex=function(e){var t=this.getTreeNodeWithListIndex(e),n=t.listIndex,i=t.visible,r=t.revealed;return i&&r?n:-1},e.prototype.getListRenderCount=function(e){return this.getTreeNode(e).renderNodeCount},e.prototype.isCollapsed=function(e){return this.getTreeNode(e).collapsed},e.prototype.setCollapsed=function(e,t,n){var i=this,r=this.getTreeNode(e);return void 0===t&&(t=!r.collapsed),this.eventBufferer.bufferEvents(function(){return i._setCollapsed(e,t,n)})},e.prototype._setCollapsed=function(e,t,n){var i=this.getTreeNodeWithListIndex(e),r=i.node,o=i.listIndex,s=i.revealed,a=this._setListNodeCollapsed(r,o,s,t,n||!1);if(r!==this.root&&this.autoExpandSingleChildren&&!t&&!n){for(var u=-1,c=0;c-1){u=-1;break}u=c}}u>-1&&this._setCollapsed(e.concat([u]),!1,!1)}return a},e.prototype._setListNodeCollapsed=function(e,t,n,i,r){var o=this._setNodeCollapsed(e,i,r,!1);if(!n||!e.visible)return o;var s=e.renderNodeCount,a=this.updateNodeAfterCollapseChange(e),u=s-(-1===t?0:1);return this.list.splice(t+1,u,a.slice(1)),o},e.prototype._setNodeCollapsed=function(e,t,n,i){var r=e.collapsible&&e.collapsed!==t;if(e.collapsible&&(e.collapsed=t,r&&this._onDidChangeCollapseState.fire({node:e,deep:i})),n)for(var o=0,s=e.children;o0,a.visibleChildrenCount=h,a.visible=2===u?h>0:1===u,a.visible?a.collapsed||(a.renderNodeCount=f):(a.renderNodeCount=0,i&&r.pop()),o&&o(a),a},e.prototype.updateNodeAfterCollapseChange=function(e){var t=e.renderNodeCount,n=[];return this._updateNodeAfterCollapseChange(e,n),this._updateAncestorsRenderNodeCount(e.parent,n.length-t),n},e.prototype._updateNodeAfterCollapseChange=function(e,t){if(!1===e.visible)return 0;if(t.push(e),e.renderNodeCount=1,!e.collapsed)for(var n=0,i=e.children;nt.children.length)throw new Error("Invalid tree location");return this.getTreeNode(i,t.children[n])},e.prototype.getTreeNodeWithListIndex=function(e){if(0===e.length)return{node:this.root,listIndex:-1,revealed:!0,visible:!1};var t=this.getParentNodeWithListIndex(e),n=t.parentNode,i=t.listIndex,r=t.revealed,o=t.visible,s=e[e.length-1];if(s<0||s>n.children.length)throw new Error("Invalid tree location");var a=n.children[s];return{node:a,listIndex:i,revealed:r,visible:o&&a.visible}},e.prototype.getParentNodeWithListIndex=function(e,t,n,i,r){void 0===t&&(t=this.root),void 0===n&&(n=0),void 0===i&&(i=!0),void 0===r&&(r=!0);var o=e[0],s=e.slice(1);if(o<0||o>t.children.length)throw new Error("Invalid tree location");for(var a=0;a0&&!e.collapsed?n.add(e):e.parent&&n.add(e.parent)}),this.activeIndentNodes.forEach(function(e){n.has(e)||t.renderedIndentGuides.forEach(e,function(e){return Object(i.I)(e,"active")})}),n.forEach(function(e){t.activeIndentNodes.has(e)||t.renderedIndentGuides.forEach(e,function(e){return Object(i.f)(e,"active")})}),this.activeIndentNodes=n}},e.prototype.dispose=function(){this.renderedNodes.clear(),this.renderedElements.clear(),this.indentGuidesDisposable.dispose(),this.disposables=Object(o.f)(this.disposables)},e.DefaultIndent=8,e}(),V=function(){function e(e,t,n){this.tree=e,this.keyboardNavigationLabelProvider=t,this._filter=n,this._totalCount=0,this._matchCount=0,this._pattern="",this._lowercasePattern="",this.disposables=[],e.onWillRefilter(this.reset,this,this.disposables)}return Object.defineProperty(e.prototype,"totalCount",{get:function(){return this._totalCount},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"matchCount",{get:function(){return this._matchCount},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pattern",{set:function(e){this._pattern=e,this._lowercasePattern=e.toLowerCase()},enumerable:!0,configurable:!0}),e.prototype.filter=function(e,t){if(this._filter){var n=this._filter.filter(e,t);if(this.tree.options.simpleKeyboardNavigation)return n;if(0===("boolean"==typeof n?n?1:0:S(n)?x(n.visibility):n))return!1}if(this._totalCount++,this.tree.options.simpleKeyboardNavigation||!this._pattern)return this._matchCount++,{data:w.a.Default,visibility:!0};var i=this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e),r=i&&i.toString();if(void 0===r)return{data:w.a.Default,visibility:!0};var o=Object(w.d)(this._pattern,this._lowercasePattern,0,r,r.toLowerCase(),0,!0);return o?(this._matchCount++,{data:o,visibility:!0}):this.tree.options.filterOnType?2:{data:w.a.Default,visibility:!0}},e.prototype.reset=function(){this._totalCount=0,this._matchCount=0},e.prototype.dispose=function(){this.disposables=Object(o.f)(this.disposables)},e}(),H=function(){function e(e,t,n,r,o){this.tree=e,this.view=n,this.filter=r,this.keyboardNavigationLabelProvider=o,this._enabled=!1,this._pattern="",this._empty=!1,this._onDidChangeEmptyState=new g.a,this.positionClassName="ne",this.automaticKeyboardNavigation=!0,this.triggered=!1,this._onDidChangePattern=new g.a,this.enabledDisposables=[],this.disposables=[],this.domNode=Object(i.a)(".monaco-list-type-filter."+this.positionClassName),this.domNode.draggable=!0,Object(y.a)(this.domNode,"dragstart")(this.onDragStart,this,this.disposables),this.messageDomNode=Object(i.m)(n.getHTMLElement(),Object(i.a)(".monaco-list-type-filter-message")),this.labelDomNode=Object(i.m)(this.domNode,Object(i.a)("span.label"));var a=Object(i.m)(this.domNode,Object(i.a)(".controls"));this._filterOnType=!!e.options.filterOnType,this.filterOnTypeDomNode=Object(i.m)(a,Object(i.a)("input.filter")),this.filterOnTypeDomNode.type="checkbox",this.filterOnTypeDomNode.checked=this._filterOnType,this.filterOnTypeDomNode.tabIndex=-1,this.updateFilterOnTypeTitle(),Object(y.a)(this.filterOnTypeDomNode,"input")(this.onDidChangeFilterOnType,this,this.disposables),this.clearDomNode=Object(i.m)(a,Object(i.a)("button.clear")),this.clearDomNode.tabIndex=-1,this.clearDomNode.title=Object(s.a)("clear","Clear"),this.keyboardNavigationEventFilter=e.options.keyboardNavigationEventFilter,t.onDidSplice(this.onDidSpliceModel,this,this.disposables),this.updateOptions(e.options)}return Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pattern",{get:function(){return this._pattern},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filterOnType",{get:function(){return this._filterOnType},enumerable:!0,configurable:!0}),e.prototype.updateOptions=function(e){e.simpleKeyboardNavigation?this.disable():this.enable(),void 0!==e.filterOnType&&(this._filterOnType=!!e.filterOnType,this.filterOnTypeDomNode.checked=this._filterOnType),void 0!==e.automaticKeyboardNavigation&&(this.automaticKeyboardNavigation=e.automaticKeyboardNavigation),this.tree.refilter(),this.render(),this.automaticKeyboardNavigation||this.onEventOrInput("")},e.prototype.enable=function(){var e=this;if(!this._enabled){var t=this.keyboardNavigationLabelProvider.mightProducePrintableCharacter?function(t){return e.keyboardNavigationLabelProvider.mightProducePrintableCharacter(t)}:function(e){return Object(r.f)(e)},n=g.b.chain(Object(y.a)(this.view.getHTMLElement(),"keydown")).filter(function(t){return!z(t.target)||t.target===e.filterOnTypeDomNode}).map(function(e){return new m.a(e)}).filter(this.keyboardNavigationEventFilter||function(){return!0}).filter(function(){return e.automaticKeyboardNavigation||e.triggered}).filter(function(n){return t(n)||(e.pattern.length>0||e.triggered)&&(9===n.keyCode||1===n.keyCode)&&!n.altKey&&!n.ctrlKey&&!n.metaKey||1===n.keyCode&&(E.d?n.altKey&&!n.metaKey:n.ctrlKey)&&!n.shiftKey}).forEach(function(e){e.stopPropagation(),e.preventDefault()}).event,i=Object(y.a)(this.clearDomNode,"click");g.b.chain(g.b.any(n,i)).event(this.onEventOrInput,this,this.enabledDisposables),this.filter.pattern="",this.tree.refilter(),this.render(),this._enabled=!0,this.triggered=!1}},e.prototype.disable=function(){this._enabled&&(this.domNode.remove(),this.enabledDisposables=Object(o.f)(this.enabledDisposables),this.tree.refilter(),this.render(),this._enabled=!1,this.triggered=!1)},e.prototype.onEventOrInput=function(e){"string"==typeof e?this.onInput(e):e instanceof MouseEvent||9===e.keyCode||1===e.keyCode&&(E.d?e.altKey:e.ctrlKey)?this.onInput(""):1===e.keyCode?this.onInput(0===this.pattern.length?"":this.pattern.substr(0,this.pattern.length-1)):this.onInput(this.pattern+e.browserEvent.key)},e.prototype.onInput=function(e){var t=this.view.getHTMLElement();e&&!this.domNode.parentElement?t.append(this.domNode):!e&&this.domNode.parentElement&&(this.domNode.remove(),this.tree.domFocus()),this._pattern=e,this._onDidChangePattern.fire(e),this.filter.pattern=e,this.tree.refilter(),e&&this.tree.focusNext(0,!0,void 0,function(e){return!w.a.isDefault(e.filterData)});var n=this.tree.getFocus();if(n.length>0){var i=n[0];null===this.tree.getRelativeTop(i)&&this.tree.reveal(i,.5)}this.render(),e||(this.triggered=!1)},e.prototype.onDragStart=function(){var e=this,t=this.view.getHTMLElement(),n=Object(i.x)(t).left,r=t.clientWidth,s=r/2,a=this.domNode.clientWidth,u=[],c=this.positionClassName,l=function(){switch(c){case"nw":e.domNode.style.top="4px",e.domNode.style.left="4px";break;case"ne":e.domNode.style.top="4px",e.domNode.style.left=r-a-6+"px"}};l(),Object(i.I)(this.domNode,c),Object(i.f)(this.domNode,"dragging"),u.push(Object(o.h)(function(){return Object(i.I)(e.domNode,"dragging")})),Object(y.a)(document,"dragover")(function(e){e.preventDefault();var t=e.screenX-n;e.dataTransfer&&(e.dataTransfer.dropEffect="none"),c=t0&&0===this.filter.matchCount;this.pattern&&this.tree.options.filterOnType&&e?(this.messageDomNode.textContent=Object(s.a)("empty","No elements found"),this._empty=!0):(this.messageDomNode.innerHTML="",this._empty=!1),Object(i.R)(this.domNode,"no-matches",e),this.domNode.title=Object(s.a)("found","Matched {0} out of {1} elements",this.filter.matchCount,this.filter.totalCount),this.labelDomNode.textContent=this.pattern.length>16?"…"+this.pattern.substr(this.pattern.length-16):this.pattern,this._onDidChangeEmptyState.fire(this._empty)},e.prototype.shouldAllowFocus=function(e){return!(this.enabled&&this.pattern&&!this.filterOnType)||(this.filter.totalCount>0&&this.filter.matchCount<=1||!w.a.isDefault(e.filterData))},e.prototype.dispose=function(){this.disable(),this._onDidChangePattern.dispose(),this.disposables=Object(o.f)(this.disposables)},e}();function z(e){return"INPUT"===e.tagName||"TEXTAREA"===e.tagName}function U(e){return{elements:e.elements.map(function(e){return e.element}),browserEvent:e.browserEvent}}function K(e,t){t(e),e.children.forEach(function(e){return K(e,t)})}var q=function(){function e(e){this.identityProvider=e,this.nodes=[],this._onDidChange=new g.a,this.onDidChange=this._onDidChange.event}return Object.defineProperty(e.prototype,"nodeSet",{get:function(){return this._nodeSet||(this._nodeSet=this.createNodeSet()),this._nodeSet},enumerable:!0,configurable:!0}),e.prototype.set=function(e,t){Object(_.g)(this.nodes,e)||this._set(e,!1,t)},e.prototype._set=function(e,t,n){if(this.nodes=e.slice(),this.elements=void 0,this._nodeSet=void 0,!t){var i=this;this._onDidChange.fire({get elements(){return i.get()},browserEvent:n})}},e.prototype.get=function(){return this.elements||(this.elements=this.nodes.map(function(e){return e.element})),this.elements.slice()},e.prototype.getNodes=function(){return this.nodes},e.prototype.has=function(e){return this.nodeSet.has(e)},e.prototype.onDidModelSplice=function(e){var t=this,n=e.insertedNodes,i=e.deletedNodes;if(!this.identityProvider){var r=this.createNodeSet(),o=function(e){return r.delete(e)};return i.forEach(function(e){return K(e,o)}),void this.set(Object(I.e)(r))}var s=new Set,a=function(e){return s.add(t.identityProvider.getId(e.element).toString())};i.forEach(function(e){return K(e,a)});var u=new Map,c=function(e){return u.set(t.identityProvider.getId(e.element).toString(),e)};n.forEach(function(e){return K(e,c)});for(var l=[],d=!0,h=0,f=this.nodes;h0&&e.prototype.setFocus.call(this,Object(_.f)(e.prototype.getFocus.call(this).concat(o))),s.length>0&&e.prototype.setSelection.call(this,Object(_.f)(e.prototype.getSelection.call(this).concat(s)))}},t.prototype.setFocus=function(t,n,i){var r=this;void 0===i&&(i=!1),e.prototype.setFocus.call(this,t,n),i||this.focusTrait.set(t.map(function(e){return r.element(e)}),n)},t.prototype.setSelection=function(t,n,i){var r=this;void 0===i&&(i=!1),e.prototype.setSelection.call(this,t,n),i||this.selectionTrait.set(t.map(function(e){return r.element(e)}),n)},t}(r.b),Y=function(){function e(e,t,n,r){var o,s=this;void 0===r&&(r={}),this._options=r,this.eventBufferer=new g.c,this.disposables=[],this._onWillRefilter=new g.a,this.onWillRefilter=this._onWillRefilter.event,this._onDidUpdateOptions=new g.a;var a,u,c,l=new j(t),d=new g.f,h=new g.f,f=new W(h.event);if(this.disposables.push(f),this.renderers=n.map(function(e){return new B(e,d.event,f,r)}),(o=this.disposables).push.apply(o,this.renderers),r.keyboardNavigationLabelProvider&&(a=new V(this,r.keyboardNavigationLabelProvider,r.filter),r=P({},r,{filter:a}),this.disposables.push(a)),this.focus=new q(r.identityProvider),this.selection=new q(r.identityProvider),this.view=new Z(e,l,this.renderers,this.focus,this.selection,P({},(u=function(){return s.model},(c=r)&&P({},c,{identityProvider:c.identityProvider&&{getId:function(e){return c.identityProvider.getId(e.element)}},dnd:c.dnd&&new R(u,c.dnd),multipleSelectionController:c.multipleSelectionController&&{isSelectionSingleChangeEvent:function(e){return c.multipleSelectionController.isSelectionSingleChangeEvent(P({},e,{element:e.element}))},isSelectionRangeChangeEvent:function(e){return c.multipleSelectionController.isSelectionRangeChangeEvent(P({},e,{element:e.element}))}},accessibilityProvider:c.accessibilityProvider&&{getAriaLabel:function(e){return c.accessibilityProvider.getAriaLabel(e.element)},getAriaLevel:function(e){return e.depth}},keyboardNavigationLabelProvider:c.keyboardNavigationLabelProvider&&P({},c.keyboardNavigationLabelProvider,{getKeyboardNavigationLabel:function(e){return c.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element)}}),enableKeyboardNavigation:c.simpleKeyboardNavigation,ariaProvider:{getSetSize:function(e){return e.parent.visibleChildrenCount},getPosInSet:function(e){return e.visibleChildIndex+1}}})),{tree:this})),this.model=this.createModel(this.view,r),d.input=this.model.onDidChangeCollapseState,this.model.onDidSplice(function(e){s.focus.onDidModelSplice(e),s.selection.onDidModelSplice(e)},null,this.disposables),h.input=g.b.map(g.b.any(this.focus.onDidChange,this.selection.onDidChange,this.model.onDidSplice),function(){return s.focus.getNodes().concat(s.selection.getNodes())}),!1!==r.keyboardSupport){var p=g.b.chain(this.view.onKeyDown).filter(function(e){return!z(e.target)}).map(function(e){return new m.a(e)});p.filter(function(e){return 15===e.keyCode}).on(this.onLeftArrow,this,this.disposables),p.filter(function(e){return 17===e.keyCode}).on(this.onRightArrow,this,this.disposables),p.filter(function(e){return 10===e.keyCode}).on(this.onSpace,this,this.disposables)}r.keyboardNavigationLabelProvider&&(this.typeFilterController=new H(this,this.model,this.view,a,r.keyboardNavigationLabelProvider),this.focusNavigationFilter=function(e){return s.typeFilterController.shouldAllowFocus(e)},this.disposables.push(this.typeFilterController)),this.styleElement=Object(i.s)(this.view.getHTMLElement()),Object(i.R)(this.getHTMLElement(),"always",this._options.renderIndentGuides===F.Always)}return Object.defineProperty(e.prototype,"onDidChangeFocus",{get:function(){return this.eventBufferer.wrapEvent(this.focus.onDidChange)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidChangeSelection",{get:function(){return this.eventBufferer.wrapEvent(this.selection.onDidChange)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidOpen",{get:function(){return g.b.map(this.view.onDidOpen,U)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidFocus",{get:function(){return this.view.onDidFocus},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidChangeCollapseState",{get:function(){return this.model.onDidChangeCollapseState},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"openOnSingleClick",{get:function(){return void 0===this._options.openOnSingleClick||this._options.openOnSingleClick},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"expandOnlyOnTwistieClick",{get:function(){return void 0!==this._options.expandOnlyOnTwistieClick&&this._options.expandOnlyOnTwistieClick},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onDidDispose",{get:function(){return this.view.onDidDispose},enumerable:!0,configurable:!0}),e.prototype.updateOptions=function(e){void 0===e&&(e={}),this._options=P({},this._options,e);for(var t=0,n=this.renderers;t .indent-guide, .monaco-list"+t+".always .monaco-tl-indent > .indent-guide { border-color: "+e.treeIndentGuidesStroke.transparent(.4)+"; }"),n.push(".monaco-list"+t+" .monaco-tl-indent > .indent-guide.active { border-color: "+e.treeIndentGuidesStroke+"; }"));var i=n.join("\n");i!==this.styleElement.innerHTML&&(this.styleElement.innerHTML=i),this.view.style(e)},e.prototype.getNode=function(e){return this.model.getNode(e)},e.prototype.collapse=function(e,t){return void 0===t&&(t=!1),this.model.setCollapsed(e,!0,t)},e.prototype.expand=function(e,t){return void 0===t&&(t=!1),this.model.setCollapsed(e,!1,t)},e.prototype.isCollapsed=function(e){return this.model.isCollapsed(e)},e.prototype.refilter=function(){this._onWillRefilter.fire(void 0),this.model.refilter()},e.prototype.setSelection=function(e,t){var n=this,i=e.map(function(e){return n.model.getNode(e)});this.selection.set(i,t);var r=e.map(function(e){return n.model.getListIndex(e)}).filter(function(e){return e>-1});this.view.setSelection(r,t,!0)},e.prototype.getSelection=function(){return this.selection.get()},e.prototype.setFocus=function(e,t){var n=this,i=e.map(function(e){return n.model.getNode(e)});this.focus.set(i,t);var r=e.map(function(e){return n.model.getListIndex(e)}).filter(function(e){return e>-1});this.view.setFocus(r,t,!0)},e.prototype.focusNext=function(e,t,n,i){void 0===e&&(e=1),void 0===t&&(t=!1),void 0===i&&(i=this.focusNavigationFilter),this.view.focusNext(e,t,n,i)},e.prototype.getFocus=function(){return this.focus.get()},e.prototype.reveal=function(e,t){this.model.expandTo(e);var n=this.model.getListIndex(e);-1!==n&&this.view.reveal(n,t)},e.prototype.getRelativeTop=function(e){var t=this.model.getListIndex(e);return-1===t?null:this.view.getRelativeTop(t)},e.prototype.onLeftArrow=function(e){e.preventDefault(),e.stopPropagation();var t=this.view.getFocusedElements();if(0!==t.length){var n=t[0],i=this.model.getNodeLocation(n);if(!this.model.setCollapsed(i,!0)){var r=this.model.getParentNodeLocation(i);if(null===r)return;var o=this.model.getListIndex(r);this.view.reveal(o),this.view.setFocus([o])}}},e.prototype.onRightArrow=function(e){e.preventDefault(),e.stopPropagation();var t=this.view.getFocusedElements();if(0!==t.length){var n=t[0],i=this.model.getNodeLocation(n);if(!this.model.setCollapsed(i,!1)){if(!n.children.some(function(e){return e.visible}))return;var r=this.view.getFocus()[0]+1;this.view.reveal(r),this.view.setFocus([r])}}},e.prototype.onSpace=function(e){e.preventDefault(),e.stopPropagation();var t=this.view.getFocusedElements();if(0!==t.length){var n=t[0],i=this.model.getNodeLocation(n),r=e.browserEvent.altKey;this.model.setCollapsed(i,void 0,r)}},e.prototype.dispose=function(){this.disposables=Object(o.f)(this.disposables),this.view.dispose()},e}(),X=this&&this.__assign||function(){return(X=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]-1&&i.focus.push(h),i&&i.viewState.selection&&i.viewState.selection.indexOf(c)>-1&&i.selection.push(h),i&&i.viewState.expanded&&i.viewState.expanded.indexOf(c)>-1?d.push(h):r&&o.collapseByDefault&&!o.collapseByDefault(t)&&(h.collapsedByDefault=!1,d.push(h)),h}),f=0,p=Object(I.e)(s);f-1)&&t.collapsedByDefault,t.collapsedByDefault=void 0,{element:t,children:t.hasChildren?C.d.map(C.d.fromArray(t.children),function(t){return e(t,n)}):[],collapsible:t.hasChildren,collapsed:i}}(e,t)});this.tree.setChildren(e===this.root?null:e,n),this._onDidRender.fire()},e.prototype.dispose=function(){Object(o.f)(this.disposables)},e}(),pe=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),ge=function(e){function t(t,n,i,r,o){void 0===o&&(o={});var s=e.call(this,t,n,i,o)||this;return s.dataSource=r,s.identityProvider=o.identityProvider,s}return pe(t,e),t.prototype.createModel=function(e,t){return new $(e,t)},t}(Y),me=n("xJaW");n.d(t,"a",function(){return Ce}),n.d(t,"b",function(){return Se}),n.d(t,"c",function(){return Ke});var ve,_e=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),be=this&&this.__assign||function(){return(be=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},we=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Ce=Object(l.c)("listService"),Se=function(){function e(e){this.lists=[],this._lastFocusedWidget=void 0}return Object.defineProperty(e.prototype,"lastFocusedList",{get:function(){return this._lastFocusedWidget},enumerable:!0,configurable:!0}),e.prototype.register=function(e,t){var n=this;if(this.lists.some(function(t){return t.widget===e}))throw new Error("Cannot register the same widget multiple times");var i={widget:e,extraContextKeys:t};return this.lists.push(i),e.getHTMLElement()===document.activeElement&&(this._lastFocusedWidget=e),Object(o.e)(e.onDidFocus(function(){return n._lastFocusedWidget=e}),Object(o.h)(function(){return n.lists.splice(n.lists.indexOf(i),1)}),e.onDidDispose(function(){n.lists=n.lists.filter(function(e){return e!==i}),n._lastFocusedWidget===e&&(n._lastFocusedWidget=void 0)}))},e=ye([we(0,c.c)],e)}(),xe=new c.d("listFocus",!0),Le=new c.d("listSupportsMultiselect",!0),Oe=new c.d("listHasSelectionOrFocus",!1),ke=new c.d("listDoubleSelection",!1),Ne=new c.d("listMultiSelection",!1),Ee=new c.d("listSupportsKeyboardNavigation",!0),Ie="listAutomaticKeyboardNavigation",De=new c.d(Ie,!0),Me=!1;var Te="workbench.list.multiSelectModifier",Pe="workbench.list.openMode",Ae="workbench.list.horizontalScrolling",Re="workbench.list.keyboardNavigation",Fe="workbench.list.automaticKeyboardNavigation",je="workbench.tree.indent",We="workbench.tree.renderIndentGuides";function Be(e){return"alt"===e.getValue(Te)}function Ve(e){return"doubleClick"!==e.getValue(Pe)}var He,ze=function(e){function t(t){var n=e.call(this)||this;return n.configurationService=t,n.useAltAsMultipleSelectionModifier=Be(t),n.registerListeners(),n}return _e(t,e),t.prototype.registerListeners=function(){var e=this;this._register(this.configurationService.onDidChangeConfiguration(function(t){t.affectsConfiguration(Te)&&(e.useAltAsMultipleSelectionModifier=Be(e.configurationService))}))},t.prototype.isSelectionSingleChangeEvent=function(e){return this.useAltAsMultipleSelectionModifier?e.browserEvent.altKey:Object(r.e)(e)},t.prototype.isSelectionRangeChangeEvent=function(e){return Object(r.d)(e)},t}(o.a),Ue=function(e){function t(t,n){var i=e.call(this)||this;return i.configurationService=t,i.existingOpenController=n,i.openOnSingleClick=Ve(t),i.registerListeners(),i}return _e(t,e),t.prototype.registerListeners=function(){var e=this;this._register(this.configurationService.onDidChangeConfiguration(function(t){t.affectsConfiguration(Pe)&&(e.openOnSingleClick=Ve(e.configurationService))}))},t.prototype.shouldOpen=function(e){if(e instanceof MouseEvent){var t=0===e.button,n=2===e.detail;return!(t&&!this.openOnSingleClick&&!n)&&(!(!t&&1!==e.button)&&(!this.existingOpenController||this.existingOpenController.shouldOpen(e)))}return!this.existingOpenController||this.existingOpenController.shouldOpen(e)},t}(o.a);(function(e){function t(t,n,i,r,o,s,a,u,c,l){var d=this,h=qe(t,r,o,a,u,c,l),f=h.options,p=h.getAutomaticKeyboardNavigation,g=h.disposable;return(d=e.call(this,t,n,i,f)||this).disposables.push(g),d.internals=new Ge(d,f,p,o,s,a,u,l),d.disposables.push(d.internals),d}_e(t,e),t=ye([we(4,c.c),we(5,Ce),we(6,p.c),we(7,a.a),we(8,d.a),we(9,me.b)],t)})(Q),function(e){function t(t,n,i,r,o,s,a,u,c,l,d){var h=this,f=qe(t,o,s,u,c,l,d),p=f.options,g=f.getAutomaticKeyboardNavigation,m=f.disposable;return(h=e.call(this,t,n,i,r,p)||this).disposables.push(m),h.internals=new Ge(h,p,g,s,a,u,c,d),h.disposables.push(h.internals),h}_e(t,e),t=ye([we(5,c.c),we(6,Ce),we(7,p.c),we(8,a.a),we(9,d.a),we(10,me.b)],t)}(ge);var Ke=function(e){function t(t,n,i,r,o,s,a,u,c,l,d){var h=this,f=qe(t,o,s,u,c,l,d),p=f.options,g=f.getAutomaticKeyboardNavigation,m=f.disposable;return(h=e.call(this,t,n,i,r,p)||this).disposables.push(m),h.internals=new Ge(h,p,g,s,a,u,c,d),h.disposables.push(h.internals),h}return _e(t,e),Object.defineProperty(t.prototype,"contextKeyService",{get:function(){return this.internals.contextKeyService},enumerable:!0,configurable:!0}),t=ye([we(5,c.c),we(6,Ce),we(7,p.c),we(8,a.a),we(9,d.a),we(10,me.b)],t)}(fe);function qe(e,t,n,s,u,c,l){Ee.bindTo(n),Me||(De.bindTo(n),Me=!0);var d=function(){var e=n.getContextKeyValue(Ie);return e&&(e=u.getValue(Fe)),e},h=2===l.getAccessibilitySupport()?"simple":u.getValue(Re),p=void 0!==t.horizontalScrolling?t.horizontalScrolling:function(e){return Object(a.f)(e,Ae,"workbench.tree.horizontalScrolling")}(u),g=Ve(u),m=function(e,t,n){var i=new o.b,r=be({},e);if(!1!==e.multipleSelectionSupport&&!e.multipleSelectionController){var s=new ze(t);r.multipleSelectionController=s,i.add(s)}var a=new Ue(t,e.openController);if(r.openController=a,i.add(a),e.keyboardNavigationLabelProvider){var u=e.keyboardNavigationLabelProvider;r.keyboardNavigationLabelProvider={getKeyboardNavigationLabel:function(e){return u.getKeyboardNavigationLabel(e)},mightProducePrintableCharacter:function(e){return n.mightProducePrintableCharacter(e)}}}return[r,i]}(t,u,c),v=m[0],_=m[1],b=t.additionalScrollHeight;return{getAutomaticKeyboardNavigation:d,disposable:_,options:be({keyboardSupport:!1,styleController:new r.a((He||(He=Object(i.s)()),He))},Object(f.e)(s.getTheme(),f.f),v,{indent:u.getValue(je),renderIndentGuides:u.getValue(We),automaticKeyboardNavigation:d(),simpleKeyboardNavigation:"simple"===h,filterOnType:"filter"===h,horizontalScrolling:p,openOnSingleClick:g,keyboardNavigationEventFilter:function(e,t){var n=!1;return function(i){if(n)return n=!1,!1;var r=t.softDispatch(i,e);return r&&r.enterChord?(n=!0,!1):(n=!1,!0)}}(e,c),additionalScrollHeight:b})}}var Ge=function(){function e(e,t,n,i,r,o,s,a){var u=this;this.disposables=[],this.contextKeyService=function(e,t){var n=e.createScoped(t.getHTMLElement());return xe.bindTo(n),n}(i,e),Le.bindTo(this.contextKeyService).set(!(!1===t.multipleSelectionSupport)),this.hasSelectionOrFocus=Oe.bindTo(this.contextKeyService),this.hasDoubleSelection=ke.bindTo(this.contextKeyService),this.hasMultiSelection=Ne.bindTo(this.contextKeyService),this._useAltAsMultipleSelectionModifier=Be(s);var c=new Set;c.add(Ie);var l=function(){var t=2===a.getAccessibilitySupport()?"simple":s.getValue(Re);e.updateOptions({simpleKeyboardNavigation:"simple"===t,filterOnType:"filter"===t})};this.disposables.push(this.contextKeyService,r.register(e),Object(f.b)(e,o),e.onDidChangeSelection(function(){var t=e.getSelection(),n=e.getFocus();u.hasSelectionOrFocus.set(t.length>0||n.length>0),u.hasMultiSelection.set(t.length>1),u.hasDoubleSelection.set(2===t.length)}),e.onDidChangeFocus(function(){var t=e.getSelection(),n=e.getFocus();u.hasSelectionOrFocus.set(t.length>0||n.length>0)}),s.onDidChangeConfiguration(function(t){if(t.affectsConfiguration(Pe)&&e.updateOptions({openOnSingleClick:Ve(s)}),t.affectsConfiguration(Te)&&(u._useAltAsMultipleSelectionModifier=Be(s)),t.affectsConfiguration(je)){var i=s.getValue(je);e.updateOptions({indent:i})}if(t.affectsConfiguration(We)){var r=s.getValue(We);e.updateOptions({renderIndentGuides:r})}t.affectsConfiguration(Re)&&l(),t.affectsConfiguration(Fe)&&e.updateOptions({automaticKeyboardNavigation:n()})}),this.contextKeyService.onDidChangeContext(function(t){t.affectsSome(c)&&e.updateOptions({automaticKeyboardNavigation:n()})}),a.onDidChangeAccessibilitySupport(function(){return l()}))}return e.prototype.dispose=function(){this.disposables=Object(o.f)(this.disposables)},e=ye([we(3,c.c),we(4,Ce),we(5,p.c),we(6,a.a),we(7,me.b)],e)}();h.a.as(u.a.Configuration).registerConfiguration({id:"workbench",order:7,title:Object(s.a)("workbenchConfigurationTitle","Workbench"),type:"object",properties:(ve={},ve[Te]={type:"string",enum:["ctrlCmd","alt"],enumDescriptions:[Object(s.a)("multiSelectModifier.ctrlCmd","Maps to `Control` on Windows and Linux and to `Command` on macOS."),Object(s.a)("multiSelectModifier.alt","Maps to `Alt` on Windows and Linux and to `Option` on macOS.")],default:"ctrlCmd",description:Object(s.a)({key:"multiSelectModifier",comment:["- `ctrlCmd` refers to a value the setting can take and should not be localized.","- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized."]},"The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")},ve[Pe]={type:"string",enum:["singleClick","doubleClick"],default:"singleClick",description:Object(s.a)({key:"openModeModifier",comment:["`singleClick` and `doubleClick` refers to a value the setting can take and should not be localized."]},"Controls how to open items in trees and lists using the mouse (if supported). For parents with children in trees, this setting will control if a single click expands the parent or a double click. Note that some trees and lists might choose to ignore this setting if it is not applicable. ")},ve[Ae]={type:"boolean",default:!1,description:Object(s.a)("horizontalScrolling setting","Controls whether lists and trees support horizontal scrolling in the workbench.")},ve["workbench.tree.horizontalScrolling"]={type:"boolean",default:!1,description:Object(s.a)("tree horizontalScrolling setting","Controls whether trees support horizontal scrolling in the workbench."),deprecationMessage:Object(s.a)("deprecated","This setting is deprecated, please use '{0}' instead.",Ae)},ve[je]={type:"number",default:8,minimum:0,maximum:40,description:Object(s.a)("tree indent setting","Controls tree indentation in pixels.")},ve[We]={type:"string",enum:["none","onHover","always"],default:"onHover",description:Object(s.a)("render tree indent guides","Controls whether the tree should render indent guides.")},ve[Re]={type:"string",enum:["simple","highlight","filter"],enumDescriptions:[Object(s.a)("keyboardNavigationSettingKey.simple","Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),Object(s.a)("keyboardNavigationSettingKey.highlight","Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),Object(s.a)("keyboardNavigationSettingKey.filter","Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")],default:"highlight",description:Object(s.a)("keyboardNavigationSettingKey","Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter.")},ve[Fe]={type:"boolean",default:!0,markdownDescription:Object(s.a)("automatic keyboard navigation setting","Controls whether keyboard navigation in lists and trees is automatically triggered simply by typing. If set to `false`, keyboard navigation is only triggered when executing the `list.toggleKeyboardNavigation` command, for which you can assign a keyboard shortcut.")},ve)})},bkDy:function(e,t,n){var i=n("dTr8");e.exports=function(e,t){t=t||{};var n=i.decode(e,t);if(!n)return null;var r=n.payload;if("string"==typeof r)try{var o=JSON.parse(r);null!==o&&"object"==typeof o&&(r=o)}catch(e){}return!0===t.complete?{header:n.header,payload:r,signature:n.signature}:r}},bxaG:function(e,t){var n=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=e,t&&(this.inner=t)};(n.prototype=Object.create(Error.prototype)).constructor=n,e.exports=n},"c/Tr":function(e,t,n){e.exports={default:n("5zde"),__esModule:!0}},"c/Wp":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("hK2W"),o=n("aL7J"),s=n("03Zz"),a=n("Ao9X"),u=n("artP"),c=n("vTy2"),l=n("/9db"),d=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),h=function(e){function t(){return e.call(this,{id:"editor.action.transposeLetters",label:r.a("transposeLetters.label","Transpose Letters"),alias:"Transpose Letters",precondition:l.a.writable,kbOpts:{kbExpr:l.a.textInputFocus,primary:0,mac:{primary:306},weight:100}})||this}return d(t,e),t.prototype.positionLeftOf=function(e,t){var n=e.column,i=e.lineNumber;return n>t.getLineMinColumn(i)?Object(o.x)(t.getLineContent(i).charCodeAt(n-2))?n-=2:n-=1:i>1&&(i-=1,n=t.getLineMaxColumn(i)),new u.a(i,n)},t.prototype.positionRightOf=function(e,t){var n=e.column,i=e.lineNumber;return n0&&(t.pushUndoStop(),t.executeCommands(this.id,i),t.pushUndoStop())}},t}(s.b);Object(s.f)(h)},c6Qy:function(e,t,n){"use strict";n.d(t,"a",function(){return i}),n.d(t,"b",function(){return r}),n.d(t,"c",function(){return o});var i=function(){function e(e,t,n){this.offset=0|e,this.type=t,this.language=n}return e.prototype.toString=function(){return"("+this.offset+", "+this.type+")"},e}(),r=function(){return function(e,t){this.tokens=e,this.endState=t}}(),o=function(){return function(e,t){this.tokens=e,this.endState=t}}()},c7fK:function(e,t,n){self.MonacoEnvironment=function(e){return{getWorkerUrl:function(t,n){var i="string"==typeof window.__webpack_public_path__?window.__webpack_public_path__:"/";return(i?i.replace(/\/$/,"")+"/":"")+e[n]}}}({editorWorkerService:"static/editor.worker.js",json:"static/json.worker.js"}),n("kQWG"),n("8VcP"),n("mcra"),n("4JIo"),n("G7Ib"),n("6jTg"),n("MfmB"),n("LA/v"),n("xteI"),n("HZsc"),n("d3wY"),n("NjkW"),n("T1Qz"),n("gpb6"),n("y3Fb"),n("ygb1"),n("QfwU"),n("oqRo"),n("MOjS"),n("GV5w"),n("l6RD"),n("am7U"),n("O8j7"),n("pvVJ"),n("QgSF"),n("ia1G"),n("2LSJ"),n("qqhx"),n("+u1c"),n("QM8g"),n("nY9q"),n("RzWM"),n("qBq4"),n("6Hge"),n("Bzq0"),n("7YfR"),n("qEZG"),n("0bce"),n("c/Wp"),n("2jYl"),n("I8T6"),n("EfRI"),e.exports=n("Ny4g"),n("Ye2W"),n("tTCp")},cLaT:function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("PCC9"),r=function(){function e(e,t){this._tokens=e,this._tokensCount=this._tokens.length>>>1,this._text=t}return e.prototype.equals=function(t){return t instanceof e&&this.slicedEquals(t,0,this._tokensCount)},e.prototype.slicedEquals=function(e,t,n){if(this._text!==e._text)return!1;if(this._tokensCount!==e._tokensCount)return!1;for(var i=t<<1,r=i+(n<<1),o=i;o0?this._tokens[e-1<<1]:0},e.prototype.getLanguageId=function(e){var t=this._tokens[1+(e<<1)];return i.x.getLanguageId(t)},e.prototype.getStandardTokenType=function(e){var t=this._tokens[1+(e<<1)];return i.x.getTokenType(t)},e.prototype.getForeground=function(e){var t=this._tokens[1+(e<<1)];return i.x.getForeground(t)},e.prototype.getClassName=function(e){var t=this._tokens[1+(e<<1)];return i.x.getClassNameFromMetadata(t)},e.prototype.getInlineStyle=function(e,t){var n=this._tokens[1+(e<<1)];return i.x.getInlineStyleFromMetadata(n,t)},e.prototype.getEndOffset=function(e){return this._tokens[e<<1]},e.prototype.findTokenIndexAtOffset=function(t){return e.findIndexInTokensArray(this._tokens,t)},e.prototype.inflate=function(){return this},e.prototype.sliceAndInflate=function(e,t,n){return new o(this,e,t,n)},e.convertToEndOffset=function(e,t){for(var n=(e.length>>>1)-1,i=0;i>>1)-1;nt&&(i=r)}return n},e}(),o=function(){function e(e,t,n,i){this._source=e,this._startOffset=t,this._endOffset=n,this._deltaOffset=i,this._firstTokenIndex=e.findTokenIndexAtOffset(t),this._tokensCount=0;for(var r=this._firstTokenIndex,o=e.getCount();r=n)break;this._tokensCount++}}return e.prototype.equals=function(t){return t instanceof e&&(this._startOffset===t._startOffset&&this._endOffset===t._endOffset&&this._deltaOffset===t._deltaOffset&&this._source.slicedEquals(t._source,this._firstTokenIndex,this._tokensCount))},e.prototype.getCount=function(){return this._tokensCount},e.prototype.getForeground=function(e){return this._source.getForeground(this._firstTokenIndex+e)},e.prototype.getEndOffset=function(e){var t=this._source.getEndOffset(this._firstTokenIndex+e);return Math.min(this._endOffset,t)-this._startOffset+this._deltaOffset},e.prototype.getClassName=function(e){return this._source.getClassName(this._firstTokenIndex+e)},e.prototype.getInlineStyle=function(e,t){return this._source.getInlineStyle(this._firstTokenIndex+e,t)},e.prototype.findTokenIndexAtOffset=function(e){return this._source.findTokenIndexAtOffset(e+this._startOffset-this._deltaOffset)-this._firstTokenIndex},e}()},cSWu:function(e,t,n){(t=e.exports=n("Rt1F")).Stream=t,t.Readable=t,t.Writable=n("7dSG"),t.Duplex=n("DsFX"),t.Transform=n("D1Va"),t.PassThrough=n("f48b")},czDl:function(e,t){},d3wY:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"CursorUndoController",function(){return l}),n.d(t,"CursorUndo",function(){return d});var i,r=n("hK2W"),o=n("tqet"),s=n("03Zz"),a=n("/9db"),u=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),c=function(){function e(e){this.selections=e}return e.prototype.equals=function(e){var t=this.selections.length;if(t!==e.selections.length)return!1;for(var n=0;n50&&n._undoStack.shift()),n._prevState=n._readState()})),n}return u(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype._readState=function(){return this._editor.hasModel()?new c(this._editor.getSelections()):null},t.prototype.getId=function(){return t.ID},t.prototype.cursorUndo=function(){if(this._editor.hasModel())for(var e=new c(this._editor.getSelections());this._undoStack.length>0;){var t=this._undoStack.pop();if(!t.equals(e))return this._isCursorUndo=!0,this._editor.setSelections(t.selections),this._editor.revealRangeInCenterIfOutsideViewport(t.selections[0],0),void(this._isCursorUndo=!1)}},t.ID="editor.contrib.cursorUndoController",t}(o.a),d=function(e){function t(){return e.call(this,{id:"cursorUndo",label:r.a("cursor.undo","Soft Undo"),alias:"Soft Undo",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:2099,weight:100}})||this}return u(t,e),t.prototype.run=function(e,t,n){l.get(t).cursorUndo()},t}(s.b);Object(s.h)(l),Object(s.f)(d)},dTr8:function(e,t,n){var i=n("h+nx"),r=n("9Io0");t.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],t.sign=i.sign,t.verify=r.verify,t.decode=r.decode,t.isValid=r.isValid,t.createSign=function(e){return new i(e)},t.createVerify=function(e){return new r(e)}},dwjm:function(e,t,n){"use strict";t.a=function(e){var t,n=this,i=!1;return function(){return i?t:(i=!0,t=e.apply(n,arguments))}}},e15g:function(e,t,n){"use strict";n.d(t,"b",function(){return v}),n.d(t,"a",function(){return b}),t.c=function(){return i},t.e=y,t.d=S,t.f=function(e,t){setTimeout(function(){var n;(n=x.onlyOnceSuggestions).push.apply(n,t),e.getContribution("editor.contrib.suggestController").triggerSuggest((new Set).add(x))},0)};var i,r=n("odeJ"),o=n("TU7t"),s=n("zxiH"),a=n("03Zz"),u=n("PCC9"),c=n("7g0X"),l=n("80kS"),d=n("vTy2"),h=n("GYOr"),f=n("tqet"),p=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},g=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0)||n.providerFilter.has(r))return Promise.resolve(r.provideCompletionItems(e,t,o,a)).then(function(o){var s=g.length;if(o){for(var a=0,u=o.suggestions||[];at.sortTextLow)return 1}return e.completion.labelt.completion.label?1:e.completion.kind-t.completion.kind}var C=new Map;function S(e){return C.get(e)}C.set(0,function(e,t){if(e.completion.kind!==t.completion.kind){if(25===e.completion.kind)return-1;if(25===t.completion.kind)return 1}return w(e,t)}),C.set(2,function(e,t){if(e.completion.kind!==t.completion.kind){if(25===e.completion.kind)return 1;if(25===t.completion.kind)return-1}return w(e,t)}),C.set(1,w),Object(a.e)("_executeCompletionItemProvider",function(e,t,n){return p(m,void 0,void 0,function(){var i,r,o,s,a,u,c,d;return g(this,function(h){switch(h.label){case 0:return i={incomplete:!1,suggestions:[]},r=new f.b,o=[],s=n.maxItemsToResolve||0,[4,y(e,t)];case 1:for(a=h.sent(),u=0,c=a;u>>32-t}function c(e,t,n,i,r,o,s){return u(e+(t&n|~t&i)+r+o|0,s)+t|0}function l(e,t,n,i,r,o,s){return u(e+(t&i|n&~i)+r+o|0,s)+t|0}function d(e,t,n,i,r,o,s){return u(e+(t^n^i)+r+o|0,s)+t|0}function h(e,t,n,i,r,o,s){return u(e+(n^(t|~i))+r+o|0,s)+t|0}i(a,r),a.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var n=this._a,i=this._b,r=this._c,o=this._d;i=h(i=h(i=h(i=h(i=d(i=d(i=d(i=d(i=l(i=l(i=l(i=l(i=c(i=c(i=c(i=c(i,r=c(r,o=c(o,n=c(n,i,r,o,e[0],3614090360,7),i,r,e[1],3905402710,12),n,i,e[2],606105819,17),o,n,e[3],3250441966,22),r=c(r,o=c(o,n=c(n,i,r,o,e[4],4118548399,7),i,r,e[5],1200080426,12),n,i,e[6],2821735955,17),o,n,e[7],4249261313,22),r=c(r,o=c(o,n=c(n,i,r,o,e[8],1770035416,7),i,r,e[9],2336552879,12),n,i,e[10],4294925233,17),o,n,e[11],2304563134,22),r=c(r,o=c(o,n=c(n,i,r,o,e[12],1804603682,7),i,r,e[13],4254626195,12),n,i,e[14],2792965006,17),o,n,e[15],1236535329,22),r=l(r,o=l(o,n=l(n,i,r,o,e[1],4129170786,5),i,r,e[6],3225465664,9),n,i,e[11],643717713,14),o,n,e[0],3921069994,20),r=l(r,o=l(o,n=l(n,i,r,o,e[5],3593408605,5),i,r,e[10],38016083,9),n,i,e[15],3634488961,14),o,n,e[4],3889429448,20),r=l(r,o=l(o,n=l(n,i,r,o,e[9],568446438,5),i,r,e[14],3275163606,9),n,i,e[3],4107603335,14),o,n,e[8],1163531501,20),r=l(r,o=l(o,n=l(n,i,r,o,e[13],2850285829,5),i,r,e[2],4243563512,9),n,i,e[7],1735328473,14),o,n,e[12],2368359562,20),r=d(r,o=d(o,n=d(n,i,r,o,e[5],4294588738,4),i,r,e[8],2272392833,11),n,i,e[11],1839030562,16),o,n,e[14],4259657740,23),r=d(r,o=d(o,n=d(n,i,r,o,e[1],2763975236,4),i,r,e[4],1272893353,11),n,i,e[7],4139469664,16),o,n,e[10],3200236656,23),r=d(r,o=d(o,n=d(n,i,r,o,e[13],681279174,4),i,r,e[0],3936430074,11),n,i,e[3],3572445317,16),o,n,e[6],76029189,23),r=d(r,o=d(o,n=d(n,i,r,o,e[9],3654602809,4),i,r,e[12],3873151461,11),n,i,e[15],530742520,16),o,n,e[2],3299628645,23),r=h(r,o=h(o,n=h(n,i,r,o,e[0],4096336452,6),i,r,e[7],1126891415,10),n,i,e[14],2878612391,15),o,n,e[5],4237533241,21),r=h(r,o=h(o,n=h(n,i,r,o,e[12],1700485571,6),i,r,e[3],2399980690,10),n,i,e[10],4293915773,15),o,n,e[1],2240044497,21),r=h(r,o=h(o,n=h(n,i,r,o,e[8],1873313359,6),i,r,e[15],4264355552,10),n,i,e[6],2734768916,15),o,n,e[13],1309151649,21),r=h(r,o=h(o,n=h(n,i,r,o,e[4],4149444226,6),i,r,e[11],3174756917,10),n,i,e[2],718787259,15),o,n,e[9],3951481745,21),this._a=this._a+n|0,this._b=this._b+i|0,this._c=this._c+r|0,this._d=this._d+o|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},e.exports=a},ejIc:function(e,t){e.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},eoic:function(e,t,n){"use strict";n.d(t,"c",function(){return a}),t.g=function(e){return{id:e}},n.d(t,"d",function(){return c}),n.d(t,"b",function(){return l}),t.e=function(e){switch(e){case u:return"vs-dark";case l:return"hc-black";default:return"vs"}},n.d(t,"a",function(){return d}),t.f=function(e){return h.onThemeChange(e)};var i=n("JVO/"),r=n("tqet"),o=n("RWr8"),s=n("Kp7x"),a=Object(i.c)("themeService");var u="dark",c="light",l="hc";var d={ThemingContribution:"base.contributions.theming"},h=new(function(){function e(){this.themingParticipants=[],this.themingParticipants=[],this.onThemingParticipantAddedEmitter=new s.a}return e.prototype.onThemeChange=function(e){var t=this;return this.themingParticipants.push(e),this.onThemingParticipantAddedEmitter.fire(e),Object(r.h)(function(){var n=t.themingParticipants.indexOf(e);t.themingParticipants.splice(n,1)})},e.prototype.getThemingParticipants=function(){return this.themingParticipants},e}());o.a.add(d.ThemingContribution,h)},f48b:function(e,t,n){"use strict";e.exports=o;var i=n("D1Va"),r=n("jOgh");function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}r.inherits=n("LC74"),r.inherits(o,i),o.prototype._transform=function(e,t,n){n(null,e)}},fAkY:function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"b",function(){return s});var i=n("Nr0y"),r=n("JVO/"),o=(i.a,Object(r.c)("notificationService")),s=function(){return function(){}}()},fBQ2:function(e,t,n){"use strict";var i=n("evD5"),r=n("X8DO");e.exports=function(e,t,n){t in e?i.f(e,t,r(0,n)):e[t]=n}},fC4T:function(e,t){e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},fWB8:function(e,t,n){"use strict";var i=n("1lLf"),r=n("Q48P");function o(){if(!(this instanceof o))return new o;r.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}i.inherits(o,r),e.exports=o,o.blockSize=512,o.outSize=224,o.hmacStrength=192,o.padLength=64,o.prototype._digest=function(e){return"hex"===e?i.toHex32(this.h.slice(0,7),"big"):i.split32(this.h.slice(0,7),"big")}},ftXN:function(e,t,n){"use strict";n.d(t,"a",function(){return i});var i,r=n("aL7J");i="undefined"!=typeof TextDecoder?function(e){return new o(e)}:function(e){return new s};var o=function(){function e(e){this._decoder=new TextDecoder("UTF-16LE"),this._capacity=0|e,this._buffer=new Uint16Array(this._capacity),this._completedStrings=null,this._bufferLength=0}return e.prototype.reset=function(){this._completedStrings=null,this._bufferLength=0},e.prototype.build=function(){return null!==this._completedStrings?(this._flushBuffer(),this._completedStrings.join("")):this._buildBuffer()},e.prototype._buildBuffer=function(){if(0===this._bufferLength)return"";var e=new Uint16Array(this._buffer.buffer,0,this._bufferLength);return this._decoder.decode(e)},e.prototype._flushBuffer=function(){var e=this._buildBuffer();this._bufferLength=0,null===this._completedStrings?this._completedStrings=[e]:this._completedStrings[this._completedStrings.length]=e},e.prototype.write1=function(e){var t=this._capacity-this._bufferLength;t<=1&&(0===t||r.w(e))&&this._flushBuffer(),this._buffer[this._bufferLength++]=e},e.prototype.appendASCII=function(e){this._bufferLength===this._capacity&&this._flushBuffer(),this._buffer[this._bufferLength++]=e},e.prototype.appendASCIIString=function(e){var t=e.length;if(this._bufferLength+t>=this._capacity)return this._flushBuffer(),void(this._completedStrings[this._completedStrings.length]=e);for(var n=0;n0&&0===e.minimapLeft?e.minimapWidth:0},e.prototype._onViewZoneTop=function(e){this.domNode.style.top=e+"px"},e.prototype._onViewZoneHeight=function(e){if(this.domNode.style.height=e+"px",this.container){var t=e-this._decoratingElementsHeight();this.container.style.height=t+"px";var n=this.editor.getLayoutInfo();this._doLayout(t,this._getWidth(n))}this._resizeSash&&this._resizeSash.layout()},Object.defineProperty(e.prototype,"position",{get:function(){var e=this._positionMarkerId[0];if(e){var t=this.editor.getModel();if(t){var n=t.getDecorationRange(e);if(n)return n.getStartPosition()}}},enumerable:!0,configurable:!0}),e.prototype.show=function(e,t){var n=g.a.isIRange(e)?e:new g.a(e.lineNumber,e.column,e.lineNumber,e.column);this._isShowing=!0,this._showImpl(n,t),this._isShowing=!1,this._positionMarkerId=this.editor.deltaDecorations(this._positionMarkerId,[{range:n,options:m.a.EMPTY}])},e.prototype.hide=function(){var e=this;this._viewZone&&(this.editor.changeViewZones(function(t){e._viewZone&&t.removeZone(e._viewZone.id)}),this._viewZone=null),this._overlayWidget&&(this.editor.removeOverlayWidget(this._overlayWidget),this._overlayWidget=null),this._arrow&&this._arrow.hide()},e.prototype._decoratingElementsHeight=function(){var e=this.editor.getConfiguration().lineHeight,t=0;this.options.showArrow&&(t+=2*Math.round(e/3));this.options.showFrame&&(t+=2*Math.round(e/9));return t},e.prototype._showImpl=function(e,t){var n=this,i={lineNumber:e.startLineNumber,column:e.startColumn},r=this.editor.getLayoutInfo(),o=this._getWidth(r);this.domNode.style.width=o+"px",this.domNode.style.left=this._getLeft(r)+"px";var s=document.createElement("div");s.style.overflow="hidden";var a=this.editor.getConfiguration().lineHeight,u=this.editor.getLayoutInfo().height/a*.8;t>=u&&(t=u);var c=0,l=0;if(this._arrow&&this.options.showArrow&&(c=Math.round(a/3),this._arrow.height=c,this._arrow.show(i)),this.options.showFrame&&(l=Math.round(a/9)),this.editor.changeViewZones(function(e){n._viewZone&&e.removeZone(n._viewZone.id),n._overlayWidget&&(n.editor.removeOverlayWidget(n._overlayWidget),n._overlayWidget=null),n.domNode.style.top="-1000px",n._viewZone=new b(s,i.lineNumber,i.column,t,function(e){return n._onViewZoneTop(e)},function(e){return n._onViewZoneHeight(e)}),n._viewZone.id=e.addZone(n._viewZone),n._overlayWidget=new y("vs.editor.contrib.zoneWidget"+n._viewZone.id,n.domNode),n.editor.addOverlayWidget(n._overlayWidget)}),this.container&&this.options.showFrame){var d=this.options.frameWidth?this.options.frameWidth:l;this.container.style.borderTopWidth=d+"px",this.container.style.borderBottomWidth=d+"px"}var h=t*a-this._decoratingElementsHeight();this.container&&(this.container.style.top=c+"px",this.container.style.height=h+"px",this.container.style.overflow="hidden"),this._doLayout(h,o),this.options.keepEditorSelection||this.editor.setSelection(e);var f=this.editor.getModel();if(f){var p=Math.min(f.getLineCount(),Math.max(1,e.endLineNumber+1));this.revealLine(p)}},e.prototype.revealLine=function(e){this.editor.revealLine(e,0)},e.prototype.setCssClass=function(e,t){this.container&&(t&&this.container.classList.remove(t),i.f(this.container,e))},e.prototype._onWidth=function(e){},e.prototype._doLayout=function(e,t){},e.prototype._relayout=function(e){var t=this;this._viewZone&&this._viewZone.heightInLines!==e&&this.editor.changeViewZones(function(n){t._viewZone&&(t._viewZone.heightInLines=e,n.layoutZone(t._viewZone.id))})},e.prototype._initSash=function(){var e,t=this;this._resizeSash||(this._resizeSash=this._disposables.add(new h.a(this.domNode,this,{orientation:1})),this.options.isResizeable||(this._resizeSash.hide(),this._resizeSash.state=0),this._disposables.add(this._resizeSash.onDidStart(function(n){t._viewZone&&(e={startY:n.startY,heightInLines:t._viewZone.heightInLines})})),this._disposables.add(this._resizeSash.onDidEnd(function(){e=void 0})),this._disposables.add(this._resizeSash.onDidChange(function(n){if(e){var i=(n.currentY-e.startY)/t.editor.getConfiguration().lineHeight,r=i<0?Math.ceil(i):Math.floor(i),o=e.heightInLines+r;o>5&&o<35&&t._relayout(o)}})))},e.prototype.getHorizontalSashLeft=function(){return 0},e.prototype.getHorizontalSashTop=function(){return(null===this.domNode.style.height?0:parseInt(this.domNode.style.height))-this._decoratingElementsHeight()/2},e.prototype.getHorizontalSashWidth=function(){var e=this.editor.getLayoutInfo();return e.width-e.minimapWidth},e}(),S=n("hK2W"),x=n("7g0X"),L=n("JVO/"),O=n("8xpx");n.d(t,"a",function(){return D}),n.d(t,"b",function(){return N}),t.d=function(e){var t=e.get(l.a).getFocusedCodeEditor();if(t instanceof d.a)return t.getParentEditor();return t},n.d(t,"c",function(){return T});var k,N,E,I=this&&this.__extends||(k=function(e,t){return(k=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}k(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),D=Object(L.c)("IPeekViewService");Object(O.b)(D,function(){function e(){this._widgets=new Map}return e.prototype.addExclusiveWidget=function(e,t){var n=this,i=this._widgets.get(e);i&&(i.listener.dispose(),i.widget.dispose());this._widgets.set(e,{widget:t,listener:t.onDidClose(function(){var i=n._widgets.get(e);i&&i.widget===t&&(i.listener.dispose(),n._widgets.delete(e))})})},e}()),(E=N||(N={})).inPeekEditor=new x.d("inReferenceSearchEditor",!0),E.notInPeekEditor=E.inPeekEditor.toNegated();var M={headerBackgroundColor:s.a.white,primaryHeadingColor:s.a.fromHex("#333333"),secondaryHeadingColor:s.a.fromHex("#6c6c6cb3")},T=function(e){function t(t,n){void 0===n&&(n={});var i=e.call(this,t,n)||this;return i._onDidClose=new a.a,u.g(i.options,M,!1),i}return I(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._onDidClose.fire(this)},Object.defineProperty(t.prototype,"onDidClose",{get:function(){return this._onDidClose.event},enumerable:!0,configurable:!0}),t.prototype.style=function(t){var n=this.options;t.headerBackgroundColor&&(n.headerBackgroundColor=t.headerBackgroundColor),t.primaryHeadingColor&&(n.primaryHeadingColor=t.primaryHeadingColor),t.secondaryHeadingColor&&(n.secondaryHeadingColor=t.secondaryHeadingColor),e.prototype.style.call(this,t)},t.prototype._applyStyles=function(){e.prototype._applyStyles.call(this);var t=this.options;this._headElement&&t.headerBackgroundColor&&(this._headElement.style.backgroundColor=t.headerBackgroundColor.toString()),this._primaryHeading&&t.primaryHeadingColor&&(this._primaryHeading.style.color=t.primaryHeadingColor.toString()),this._secondaryHeading&&t.secondaryHeadingColor&&(this._secondaryHeading.style.color=t.secondaryHeadingColor.toString()),this._bodyElement&&t.frameColor&&(this._bodyElement.style.borderColor=t.frameColor.toString())},t.prototype._fillContainer=function(e){this.setCssClass("peekview-widget"),this._headElement=i.a(".head"),this._bodyElement=i.a(".body"),this._fillHead(this._headElement),this._fillBody(this._bodyElement),e.appendChild(this._headElement),e.appendChild(this._bodyElement)},t.prototype._fillHead=function(e){var t=this,n=i.a(".peekview-title");i.m(this._headElement,n),i.k(n,"click",function(e){return t._onTitleClick(e)}),this._fillTitleIcon(n),this._primaryHeading=i.a("span.filename"),this._secondaryHeading=i.a("span.dirname"),this._metaHeading=i.a("span.meta"),i.m(n,this._primaryHeading,this._secondaryHeading,this._metaHeading);var s=i.a(".peekview-actions");i.m(this._headElement,s);var a=this._getActionBarOptions();this._actionbarWidget=new r.a(s,a),this._disposables.add(this._actionbarWidget),this._actionbarWidget.push(new o.a("peekview.close",S.a("label.close","Close"),"close-peekview-action",!0,function(){return t.dispose(),Promise.resolve()}),{label:!1,icon:!0})},t.prototype._fillTitleIcon=function(e){},t.prototype._getActionBarOptions=function(){return{}},t.prototype._onTitleClick=function(e){},t.prototype.setTitle=function(e,t){this._primaryHeading&&this._secondaryHeading&&(this._primaryHeading.innerHTML=c.o(e),this._primaryHeading.setAttribute("aria-label",e),t?this._secondaryHeading.innerHTML=c.o(t):i.p(this._secondaryHeading))},t.prototype.setMetaTitle=function(e){this._metaHeading&&(e?this._metaHeading.innerHTML=c.o(e):i.p(this._metaHeading))},t.prototype._doLayout=function(e,t){if(!this._isShowing&&e<0)this.dispose();else{var n=Math.ceil(1.2*this.editor.getConfiguration().lineHeight),i=e-(n+2);this._doLayoutHead(n,t),this._doLayoutBody(i,t)}},t.prototype._doLayoutHead=function(e,t){this._headElement&&(this._headElement.style.height=e+"px",this._headElement.style.lineHeight=this._headElement.style.height)},t.prototype._doLayoutBody=function(e,t){this._bodyElement&&(this._bodyElement.style.height=e+"px")},t}(C)},fxuI:function(e,t,n){var i=n("jkjm"),r=n("Cua8"),o=n("zOO0"),s=n("geuY"),a=n("jSRM"),u=n("BVsN"),c=n("5QAX"),l=n("X3l8").Buffer;e.exports=function(e,t,n){var d;d=e.padding?e.padding:n?1:4;var h,f=i(e),p=f.modulus.byteLength();if(t.length>p||new s(t).cmp(f.modulus)>=0)throw new Error("decryption error");h=n?c(new s(t),f):a(t,f);var g=l.alloc(p-h.length);if(h=l.concat([g,h],p),4===d)return function(e,t){var n=e.modulus.byteLength(),i=u("sha1").update(l.alloc(0)).digest(),s=i.length;if(0!==t[0])throw new Error("decryption error");var a=t.slice(1,s+1),c=t.slice(s+1),d=o(a,r(c,s)),h=o(c,r(d,n-s-1));if(function(e,t){e=l.from(e),t=l.from(t);var n=0,i=e.length;e.length!==t.length&&(n++,i=Math.min(e.length,t.length));var r=-1;for(;++r=t.length){o++;break}var s=t.slice(2,r-1);("0002"!==i.toString("hex")&&!n||"0001"!==i.toString("hex")&&n)&&o++;s.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(r)}(0,h,n);if(3===d)return h;throw new Error("unknown padding")}},fyvs:function(e,t,n){"use strict";n.d(t,"a",function(){return u});var i,r=n("Kp7x"),o=n("tqet"),s=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),a=function(){function e(e,t,n,i,r,o){t|=0,n|=0,i|=0,r|=0,o|=0,(e|=0)<0&&(e=0),n+e>t&&(n=t-e),n<0&&(n=0),i<0&&(i=0),o+i>r&&(o=r-i),o<0&&(o=0),this.width=e,this.scrollWidth=t,this.scrollLeft=n,this.height=i,this.scrollHeight=r,this.scrollTop=o}return e.prototype.equals=function(e){return this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop},e.prototype.withScrollDimensions=function(t){return new e(void 0!==t.width?t.width:this.width,void 0!==t.scrollWidth?t.scrollWidth:this.scrollWidth,this.scrollLeft,void 0!==t.height?t.height:this.height,void 0!==t.scrollHeight?t.scrollHeight:this.scrollHeight,this.scrollTop)},e.prototype.withScrollPosition=function(t){return new e(this.width,this.scrollWidth,void 0!==t.scrollLeft?t.scrollLeft:this.scrollLeft,this.height,this.scrollHeight,void 0!==t.scrollTop?t.scrollTop:this.scrollTop)},e.prototype.createScrollEvent=function(e){var t=this.width!==e.width,n=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,r=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:t,scrollWidthChanged:n,scrollLeftChanged:i,heightChanged:r,scrollHeightChanged:o,scrollTopChanged:s}},e}(),u=function(e){function t(t,n){var i=e.call(this)||this;return i._onScroll=i._register(new r.a),i.onScroll=i._onScroll.event,i._smoothScrollDuration=t,i._scheduleAtNextAnimationFrame=n,i._state=new a(0,0,0,0,0,0),i._smoothScrolling=null,i}return s(t,e),t.prototype.dispose=function(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),e.prototype.dispose.call(this)},t.prototype.setSmoothScrollDuration=function(e){this._smoothScrollDuration=e},t.prototype.validateScrollPosition=function(e){return this._state.withScrollPosition(e)},t.prototype.getScrollDimensions=function(){return this._state},t.prototype.setScrollDimensions=function(e){var t=this._state.withScrollDimensions(e);this._setState(t),this._smoothScrolling&&this._smoothScrolling.acceptScrollDimensions(this._state)},t.prototype.getFutureScrollPosition=function(){return this._smoothScrolling?this._smoothScrolling.to:this._state},t.prototype.getCurrentScrollPosition=function(){return this._state},t.prototype.setScrollPositionNow=function(e){var t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t)},t.prototype.setScrollPositionSmooth=function(e){var t=this;if(0===this._smoothScrollDuration)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:void 0===e.scrollLeft?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:void 0===e.scrollTop?this._smoothScrolling.to.scrollTop:e.scrollTop};var n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;var i=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration);this._smoothScrolling.dispose(),this._smoothScrolling=i}else{n=this._state.withScrollPosition(e);this._smoothScrolling=d.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(function(){t._smoothScrolling&&(t._smoothScrolling.animationFrameDisposable=null,t._performSmoothScrolling())})},t.prototype._performSmoothScrolling=function(){var e=this;if(this._smoothScrolling){var t=this._smoothScrolling.tick(),n=this._state.withScrollPosition(t);if(this._setState(n),t.isDone)return this._smoothScrolling.dispose(),void(this._smoothScrolling=null);this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(function(){e._smoothScrolling&&(e._smoothScrolling.animationFrameDisposable=null,e._performSmoothScrolling())})}},t.prototype._setState=function(e){var t=this._state;t.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(t)))},t}(o.a),c=function(){return function(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}}();function l(e,t){var n=t-e;return function(t){return e+n*(1-function(e){return Math.pow(e,3)}(1-t))}}var d=function(){function e(e,t,n,i){this.from=e,this.to=t,this.duration=i,this._startTime=n,this.animationFrameDisposable=null,this._initAnimations()}return e.prototype._initAnimations=function(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)},e.prototype._initAnimation=function(e,t,n){var i,r,o;if(Math.abs(e-t)>2.5*n){var s=void 0,a=void 0;return e=49&&s<=54?s-49+10:s>=17&&s<=22?s-17+10:15&s}return i}function u(e,t,n,i){for(var r=0,o=Math.min(e.length,n),s=t;s=49?a-49+10:a>=17?a-17+10:a}return r}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),i(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&r++,16===t?this._parseHex(e,r):this._parseBase(e,t,r),"-"===e[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(i(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},o.prototype._initArray=function(e,t,n){if(i("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var r=0;r=0;r-=3)s=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[o]|=s<>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===n)for(r=0,o=0;r>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=6)r=a(e,n,n+6),this.words[i]|=r<>>26-o&4194303,(o+=24)>=26&&(o-=26,i++);n+6!==t&&(r=a(e,t,n+6),this.words[i]|=r<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var i=0,r=1;r<=67108863;r*=t)i++;i--,r=r/t|0;for(var o=e.length-n,s=o%i,a=Math.min(o,o-s)+n,c=0,l=n;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],l=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],d=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(e,t,n){n.negative=t.negative^e.negative;var i=e.length+t.length|0;n.length=i,i=i-1|0;var r=0|e.words[0],o=0|t.words[0],s=r*o,a=67108863&s,u=s/67108864|0;n.words[0]=a;for(var c=1;c>>26,d=67108863&u,h=Math.min(c,t.length-1),f=Math.max(0,c-e.length+1);f<=h;f++){var p=c-f|0;l+=(s=(r=0|e.words[p])*(o=0|t.words[f])+d)/67108864|0,d=67108863&s}n.words[c]=0|d,u=0|l}return 0!==u?n.words[c]=0|u:n.length--,n.strip()}o.prototype.toString=function(e,t){var n;if(e=e||10,t=0|t||1,16===e||"hex"===e){n="";for(var r=0,o=0,s=0;s>>24-r&16777215)||s!==this.length-1?c[6-u.length]+u+n:u+n,(r+=2)>=26&&(r-=26,s--)}for(0!==o&&(n=o.toString(16)+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var h=l[e],f=d[e];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(f).toString(e);n=(p=p.idivn(f)).isZero()?g+n:c[h-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%t!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}i(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return i(void 0!==s),this.toArrayLike(s,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,n){var r=this.byteLength(),o=n||Math.max(1,r);i(r<=o,"byte array longer than desired length"),i(o>0,"Requested array length <= 0"),this.strip();var s,a,u="le"===t,c=new e(o),l=this.clone();if(u){for(a=0;!l.isZero();a++)s=l.andln(255),l.iushrn(8),c[a]=s;for(;a=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 0==(8191&t)&&(n+=13,t>>>=13),0==(127&t)&&(n+=7,t>>>=7),0==(15&t)&&(n+=4,t>>>=4),0==(3&t)&&(n+=2,t>>>=2),0==(1&t)&&n++,n},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;ne.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var i=0;ie.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){i("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-n),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){i("number"==typeof e&&e>=0);var n=e/26|0,r=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<e.length?(n=this,i=e):(n=e,i=this);for(var r=0,o=0;o>>26;for(;0!==r&&o>>26;if(this.length=n.length,0!==r)this.words[this.length]=r,this.length++;else if(n!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,i,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(n=this,i=e):(n=e,i=this);for(var o=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==o&&s>26,this.words[s]=67108863&t;if(0===o&&s>>13,f=0|s[1],p=8191&f,g=f>>>13,m=0|s[2],v=8191&m,_=m>>>13,b=0|s[3],y=8191&b,w=b>>>13,C=0|s[4],S=8191&C,x=C>>>13,L=0|s[5],O=8191&L,k=L>>>13,N=0|s[6],E=8191&N,I=N>>>13,D=0|s[7],M=8191&D,T=D>>>13,P=0|s[8],A=8191&P,R=P>>>13,F=0|s[9],j=8191&F,W=F>>>13,B=0|a[0],V=8191&B,H=B>>>13,z=0|a[1],U=8191&z,K=z>>>13,q=0|a[2],G=8191&q,Z=q>>>13,Y=0|a[3],X=8191&Y,$=Y>>>13,J=0|a[4],Q=8191&J,ee=J>>>13,te=0|a[5],ne=8191&te,ie=te>>>13,re=0|a[6],oe=8191&re,se=re>>>13,ae=0|a[7],ue=8191&ae,ce=ae>>>13,le=0|a[8],de=8191&le,he=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(c+(i=Math.imul(d,V))|0)+((8191&(r=(r=Math.imul(d,H))+Math.imul(h,V)|0))<<13)|0;c=((o=Math.imul(h,H))+(r>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(p,V),r=(r=Math.imul(p,H))+Math.imul(g,V)|0,o=Math.imul(g,H);var ve=(c+(i=i+Math.imul(d,U)|0)|0)+((8191&(r=(r=r+Math.imul(d,K)|0)+Math.imul(h,U)|0))<<13)|0;c=((o=o+Math.imul(h,K)|0)+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(v,V),r=(r=Math.imul(v,H))+Math.imul(_,V)|0,o=Math.imul(_,H),i=i+Math.imul(p,U)|0,r=(r=r+Math.imul(p,K)|0)+Math.imul(g,U)|0,o=o+Math.imul(g,K)|0;var _e=(c+(i=i+Math.imul(d,G)|0)|0)+((8191&(r=(r=r+Math.imul(d,Z)|0)+Math.imul(h,G)|0))<<13)|0;c=((o=o+Math.imul(h,Z)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(y,V),r=(r=Math.imul(y,H))+Math.imul(w,V)|0,o=Math.imul(w,H),i=i+Math.imul(v,U)|0,r=(r=r+Math.imul(v,K)|0)+Math.imul(_,U)|0,o=o+Math.imul(_,K)|0,i=i+Math.imul(p,G)|0,r=(r=r+Math.imul(p,Z)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,Z)|0;var be=(c+(i=i+Math.imul(d,X)|0)|0)+((8191&(r=(r=r+Math.imul(d,$)|0)+Math.imul(h,X)|0))<<13)|0;c=((o=o+Math.imul(h,$)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(S,V),r=(r=Math.imul(S,H))+Math.imul(x,V)|0,o=Math.imul(x,H),i=i+Math.imul(y,U)|0,r=(r=r+Math.imul(y,K)|0)+Math.imul(w,U)|0,o=o+Math.imul(w,K)|0,i=i+Math.imul(v,G)|0,r=(r=r+Math.imul(v,Z)|0)+Math.imul(_,G)|0,o=o+Math.imul(_,Z)|0,i=i+Math.imul(p,X)|0,r=(r=r+Math.imul(p,$)|0)+Math.imul(g,X)|0,o=o+Math.imul(g,$)|0;var ye=(c+(i=i+Math.imul(d,Q)|0)|0)+((8191&(r=(r=r+Math.imul(d,ee)|0)+Math.imul(h,Q)|0))<<13)|0;c=((o=o+Math.imul(h,ee)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,i=Math.imul(O,V),r=(r=Math.imul(O,H))+Math.imul(k,V)|0,o=Math.imul(k,H),i=i+Math.imul(S,U)|0,r=(r=r+Math.imul(S,K)|0)+Math.imul(x,U)|0,o=o+Math.imul(x,K)|0,i=i+Math.imul(y,G)|0,r=(r=r+Math.imul(y,Z)|0)+Math.imul(w,G)|0,o=o+Math.imul(w,Z)|0,i=i+Math.imul(v,X)|0,r=(r=r+Math.imul(v,$)|0)+Math.imul(_,X)|0,o=o+Math.imul(_,$)|0,i=i+Math.imul(p,Q)|0,r=(r=r+Math.imul(p,ee)|0)+Math.imul(g,Q)|0,o=o+Math.imul(g,ee)|0;var we=(c+(i=i+Math.imul(d,ne)|0)|0)+((8191&(r=(r=r+Math.imul(d,ie)|0)+Math.imul(h,ne)|0))<<13)|0;c=((o=o+Math.imul(h,ie)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(E,V),r=(r=Math.imul(E,H))+Math.imul(I,V)|0,o=Math.imul(I,H),i=i+Math.imul(O,U)|0,r=(r=r+Math.imul(O,K)|0)+Math.imul(k,U)|0,o=o+Math.imul(k,K)|0,i=i+Math.imul(S,G)|0,r=(r=r+Math.imul(S,Z)|0)+Math.imul(x,G)|0,o=o+Math.imul(x,Z)|0,i=i+Math.imul(y,X)|0,r=(r=r+Math.imul(y,$)|0)+Math.imul(w,X)|0,o=o+Math.imul(w,$)|0,i=i+Math.imul(v,Q)|0,r=(r=r+Math.imul(v,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,i=i+Math.imul(p,ne)|0,r=(r=r+Math.imul(p,ie)|0)+Math.imul(g,ne)|0,o=o+Math.imul(g,ie)|0;var Ce=(c+(i=i+Math.imul(d,oe)|0)|0)+((8191&(r=(r=r+Math.imul(d,se)|0)+Math.imul(h,oe)|0))<<13)|0;c=((o=o+Math.imul(h,se)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,i=Math.imul(M,V),r=(r=Math.imul(M,H))+Math.imul(T,V)|0,o=Math.imul(T,H),i=i+Math.imul(E,U)|0,r=(r=r+Math.imul(E,K)|0)+Math.imul(I,U)|0,o=o+Math.imul(I,K)|0,i=i+Math.imul(O,G)|0,r=(r=r+Math.imul(O,Z)|0)+Math.imul(k,G)|0,o=o+Math.imul(k,Z)|0,i=i+Math.imul(S,X)|0,r=(r=r+Math.imul(S,$)|0)+Math.imul(x,X)|0,o=o+Math.imul(x,$)|0,i=i+Math.imul(y,Q)|0,r=(r=r+Math.imul(y,ee)|0)+Math.imul(w,Q)|0,o=o+Math.imul(w,ee)|0,i=i+Math.imul(v,ne)|0,r=(r=r+Math.imul(v,ie)|0)+Math.imul(_,ne)|0,o=o+Math.imul(_,ie)|0,i=i+Math.imul(p,oe)|0,r=(r=r+Math.imul(p,se)|0)+Math.imul(g,oe)|0,o=o+Math.imul(g,se)|0;var Se=(c+(i=i+Math.imul(d,ue)|0)|0)+((8191&(r=(r=r+Math.imul(d,ce)|0)+Math.imul(h,ue)|0))<<13)|0;c=((o=o+Math.imul(h,ce)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(A,V),r=(r=Math.imul(A,H))+Math.imul(R,V)|0,o=Math.imul(R,H),i=i+Math.imul(M,U)|0,r=(r=r+Math.imul(M,K)|0)+Math.imul(T,U)|0,o=o+Math.imul(T,K)|0,i=i+Math.imul(E,G)|0,r=(r=r+Math.imul(E,Z)|0)+Math.imul(I,G)|0,o=o+Math.imul(I,Z)|0,i=i+Math.imul(O,X)|0,r=(r=r+Math.imul(O,$)|0)+Math.imul(k,X)|0,o=o+Math.imul(k,$)|0,i=i+Math.imul(S,Q)|0,r=(r=r+Math.imul(S,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,i=i+Math.imul(y,ne)|0,r=(r=r+Math.imul(y,ie)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,ie)|0,i=i+Math.imul(v,oe)|0,r=(r=r+Math.imul(v,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,i=i+Math.imul(p,ue)|0,r=(r=r+Math.imul(p,ce)|0)+Math.imul(g,ue)|0,o=o+Math.imul(g,ce)|0;var xe=(c+(i=i+Math.imul(d,de)|0)|0)+((8191&(r=(r=r+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;c=((o=o+Math.imul(h,he)|0)+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(j,V),r=(r=Math.imul(j,H))+Math.imul(W,V)|0,o=Math.imul(W,H),i=i+Math.imul(A,U)|0,r=(r=r+Math.imul(A,K)|0)+Math.imul(R,U)|0,o=o+Math.imul(R,K)|0,i=i+Math.imul(M,G)|0,r=(r=r+Math.imul(M,Z)|0)+Math.imul(T,G)|0,o=o+Math.imul(T,Z)|0,i=i+Math.imul(E,X)|0,r=(r=r+Math.imul(E,$)|0)+Math.imul(I,X)|0,o=o+Math.imul(I,$)|0,i=i+Math.imul(O,Q)|0,r=(r=r+Math.imul(O,ee)|0)+Math.imul(k,Q)|0,o=o+Math.imul(k,ee)|0,i=i+Math.imul(S,ne)|0,r=(r=r+Math.imul(S,ie)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,ie)|0,i=i+Math.imul(y,oe)|0,r=(r=r+Math.imul(y,se)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,se)|0,i=i+Math.imul(v,ue)|0,r=(r=r+Math.imul(v,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,i=i+Math.imul(p,de)|0,r=(r=r+Math.imul(p,he)|0)+Math.imul(g,de)|0,o=o+Math.imul(g,he)|0;var Le=(c+(i=i+Math.imul(d,pe)|0)|0)+((8191&(r=(r=r+Math.imul(d,ge)|0)+Math.imul(h,pe)|0))<<13)|0;c=((o=o+Math.imul(h,ge)|0)+(r>>>13)|0)+(Le>>>26)|0,Le&=67108863,i=Math.imul(j,U),r=(r=Math.imul(j,K))+Math.imul(W,U)|0,o=Math.imul(W,K),i=i+Math.imul(A,G)|0,r=(r=r+Math.imul(A,Z)|0)+Math.imul(R,G)|0,o=o+Math.imul(R,Z)|0,i=i+Math.imul(M,X)|0,r=(r=r+Math.imul(M,$)|0)+Math.imul(T,X)|0,o=o+Math.imul(T,$)|0,i=i+Math.imul(E,Q)|0,r=(r=r+Math.imul(E,ee)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,ee)|0,i=i+Math.imul(O,ne)|0,r=(r=r+Math.imul(O,ie)|0)+Math.imul(k,ne)|0,o=o+Math.imul(k,ie)|0,i=i+Math.imul(S,oe)|0,r=(r=r+Math.imul(S,se)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,se)|0,i=i+Math.imul(y,ue)|0,r=(r=r+Math.imul(y,ce)|0)+Math.imul(w,ue)|0,o=o+Math.imul(w,ce)|0,i=i+Math.imul(v,de)|0,r=(r=r+Math.imul(v,he)|0)+Math.imul(_,de)|0,o=o+Math.imul(_,he)|0;var Oe=(c+(i=i+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;c=((o=o+Math.imul(g,ge)|0)+(r>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,i=Math.imul(j,G),r=(r=Math.imul(j,Z))+Math.imul(W,G)|0,o=Math.imul(W,Z),i=i+Math.imul(A,X)|0,r=(r=r+Math.imul(A,$)|0)+Math.imul(R,X)|0,o=o+Math.imul(R,$)|0,i=i+Math.imul(M,Q)|0,r=(r=r+Math.imul(M,ee)|0)+Math.imul(T,Q)|0,o=o+Math.imul(T,ee)|0,i=i+Math.imul(E,ne)|0,r=(r=r+Math.imul(E,ie)|0)+Math.imul(I,ne)|0,o=o+Math.imul(I,ie)|0,i=i+Math.imul(O,oe)|0,r=(r=r+Math.imul(O,se)|0)+Math.imul(k,oe)|0,o=o+Math.imul(k,se)|0,i=i+Math.imul(S,ue)|0,r=(r=r+Math.imul(S,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,i=i+Math.imul(y,de)|0,r=(r=r+Math.imul(y,he)|0)+Math.imul(w,de)|0,o=o+Math.imul(w,he)|0;var ke=(c+(i=i+Math.imul(v,pe)|0)|0)+((8191&(r=(r=r+Math.imul(v,ge)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,ge)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,i=Math.imul(j,X),r=(r=Math.imul(j,$))+Math.imul(W,X)|0,o=Math.imul(W,$),i=i+Math.imul(A,Q)|0,r=(r=r+Math.imul(A,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,i=i+Math.imul(M,ne)|0,r=(r=r+Math.imul(M,ie)|0)+Math.imul(T,ne)|0,o=o+Math.imul(T,ie)|0,i=i+Math.imul(E,oe)|0,r=(r=r+Math.imul(E,se)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,se)|0,i=i+Math.imul(O,ue)|0,r=(r=r+Math.imul(O,ce)|0)+Math.imul(k,ue)|0,o=o+Math.imul(k,ce)|0,i=i+Math.imul(S,de)|0,r=(r=r+Math.imul(S,he)|0)+Math.imul(x,de)|0,o=o+Math.imul(x,he)|0;var Ne=(c+(i=i+Math.imul(y,pe)|0)|0)+((8191&(r=(r=r+Math.imul(y,ge)|0)+Math.imul(w,pe)|0))<<13)|0;c=((o=o+Math.imul(w,ge)|0)+(r>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,i=Math.imul(j,Q),r=(r=Math.imul(j,ee))+Math.imul(W,Q)|0,o=Math.imul(W,ee),i=i+Math.imul(A,ne)|0,r=(r=r+Math.imul(A,ie)|0)+Math.imul(R,ne)|0,o=o+Math.imul(R,ie)|0,i=i+Math.imul(M,oe)|0,r=(r=r+Math.imul(M,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,i=i+Math.imul(E,ue)|0,r=(r=r+Math.imul(E,ce)|0)+Math.imul(I,ue)|0,o=o+Math.imul(I,ce)|0,i=i+Math.imul(O,de)|0,r=(r=r+Math.imul(O,he)|0)+Math.imul(k,de)|0,o=o+Math.imul(k,he)|0;var Ee=(c+(i=i+Math.imul(S,pe)|0)|0)+((8191&(r=(r=r+Math.imul(S,ge)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,ge)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(j,ne),r=(r=Math.imul(j,ie))+Math.imul(W,ne)|0,o=Math.imul(W,ie),i=i+Math.imul(A,oe)|0,r=(r=r+Math.imul(A,se)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,se)|0,i=i+Math.imul(M,ue)|0,r=(r=r+Math.imul(M,ce)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,ce)|0,i=i+Math.imul(E,de)|0,r=(r=r+Math.imul(E,he)|0)+Math.imul(I,de)|0,o=o+Math.imul(I,he)|0;var Ie=(c+(i=i+Math.imul(O,pe)|0)|0)+((8191&(r=(r=r+Math.imul(O,ge)|0)+Math.imul(k,pe)|0))<<13)|0;c=((o=o+Math.imul(k,ge)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,i=Math.imul(j,oe),r=(r=Math.imul(j,se))+Math.imul(W,oe)|0,o=Math.imul(W,se),i=i+Math.imul(A,ue)|0,r=(r=r+Math.imul(A,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,i=i+Math.imul(M,de)|0,r=(r=r+Math.imul(M,he)|0)+Math.imul(T,de)|0,o=o+Math.imul(T,he)|0;var De=(c+(i=i+Math.imul(E,pe)|0)|0)+((8191&(r=(r=r+Math.imul(E,ge)|0)+Math.imul(I,pe)|0))<<13)|0;c=((o=o+Math.imul(I,ge)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863,i=Math.imul(j,ue),r=(r=Math.imul(j,ce))+Math.imul(W,ue)|0,o=Math.imul(W,ce),i=i+Math.imul(A,de)|0,r=(r=r+Math.imul(A,he)|0)+Math.imul(R,de)|0,o=o+Math.imul(R,he)|0;var Me=(c+(i=i+Math.imul(M,pe)|0)|0)+((8191&(r=(r=r+Math.imul(M,ge)|0)+Math.imul(T,pe)|0))<<13)|0;c=((o=o+Math.imul(T,ge)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,i=Math.imul(j,de),r=(r=Math.imul(j,he))+Math.imul(W,de)|0,o=Math.imul(W,he);var Te=(c+(i=i+Math.imul(A,pe)|0)|0)+((8191&(r=(r=r+Math.imul(A,ge)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,ge)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863;var Pe=(c+(i=Math.imul(j,pe))|0)+((8191&(r=(r=Math.imul(j,ge))+Math.imul(W,pe)|0))<<13)|0;return c=((o=Math.imul(W,ge))+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,u[0]=me,u[1]=ve,u[2]=_e,u[3]=be,u[4]=ye,u[5]=we,u[6]=Ce,u[7]=Se,u[8]=xe,u[9]=Le,u[10]=Oe,u[11]=ke,u[12]=Ne,u[13]=Ee,u[14]=Ie,u[15]=De,u[16]=Me,u[17]=Te,u[18]=Pe,0!==c&&(u[19]=c,n.length++),n};function p(e,t,n){return(new g).mulp(e,t,n)}function g(e,t){this.x=e,this.y=t}Math.imul||(f=h),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?f(this,e,t):n<63?h(this,e,t):n<1024?function(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var i=0,r=0,o=0;o>>26)|0)>>>26,s&=67108863}n.words[o]=a,i=s,s=r}return 0!==i?n.words[o]=i:n.length--,n.strip()}(this,e,t):p(this,e,t)},g.prototype.makeRBT=function(e){for(var t=new Array(e),n=o.prototype._countBits(e)-1,i=0;i>=1;return i},g.prototype.permute=function(e,t,n,i,r,o){for(var s=0;s>>=1)r++;return 1<>>=13,n[2*s+1]=8191&o,o>>>=13;for(s=2*t;s>=26,t+=r/67108864|0,t+=o>>>26,this.words[n]=67108863&o}return 0!==t&&(this.words[n]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n>>r}return t}(e);if(0===t.length)return new o(1);for(var n=this,i=0;i=0);var t,n=e%26,r=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(t=0;t>>26-n}s&&(this.words[t]=s,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<s)for(this.length-=s,c=0;c=0&&(0!==l||c>=r);c--){var d=0|this.words[c];this.words[c]=l<<26-o|d>>>o,l=d&a}return u&&0!==l&&(u.words[u.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,n){return i(0===this.negative),this.iushrn(e,t,n)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){i("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,r=1<=0);var t=e%26,n=(e-t)/26;if(i(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(i("number"==typeof e),i(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[r+n]=67108863&o}for(;r>26,this.words[r+n]=67108863&o;if(0===a)return this.strip();for(i(-1===a),a=0,r=0;r>26,this.words[r]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var n=(this.length,e.length),i=this.clone(),r=e,s=0|r.words[r.length-1];0!==(n=26-this._countBits(s))&&(r=r.ushln(n),i.iushln(n),s=0|r.words[r.length-1]);var a,u=i.length-r.length;if("mod"!==t){(a=new o(null)).length=u+1,a.words=new Array(a.length);for(var c=0;c=0;d--){var h=67108864*(0|i.words[r.length+d])+(0|i.words[r.length+d-1]);for(h=Math.min(h/s|0,67108863),i._ishlnsubmul(r,h,d);0!==i.negative;)h--,i.negative=0,i._ishlnsubmul(r,1,d),i.isZero()||(i.negative^=1);a&&(a.words[d]=h)}return a&&a.strip(),i.strip(),"div"!==t&&0!==n&&i.iushrn(n),{div:a||null,mod:i}},o.prototype.divmod=function(e,t,n){return i(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(r=a.div.neg()),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.iadd(e)),{div:r,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(r=a.div.neg()),{div:r,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var r,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,i=e.ushrn(1),r=e.andln(1),o=n.cmp(i);return o<0||1===r&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){i(e<=67108863);for(var t=(1<<26)%e,n=0,r=this.length-1;r>=0;r--)n=(t*n+(0|this.words[r]))%e;return n},o.prototype.idivn=function(e){i(e<=67108863);for(var t=0,n=this.length-1;n>=0;n--){var r=(0|this.words[n])+67108864*t;this.words[n]=r/e|0,t=r%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){i(0===e.negative),i(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new o(1),s=new o(0),a=new o(0),u=new o(1),c=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++c;for(var l=n.clone(),d=t.clone();!t.isZero();){for(var h=0,f=1;0==(t.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(r.isOdd()||s.isOdd())&&(r.iadd(l),s.isub(d)),r.iushrn(1),s.iushrn(1);for(var p=0,g=1;0==(n.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(a.isOdd()||u.isOdd())&&(a.iadd(l),u.isub(d)),a.iushrn(1),u.iushrn(1);t.cmp(n)>=0?(t.isub(n),r.isub(a),s.isub(u)):(n.isub(t),a.isub(r),u.isub(s))}return{a:a,b:u,gcd:n.iushln(c)}},o.prototype._invmp=function(e){i(0===e.negative),i(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,s=new o(1),a=new o(0),u=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var c=0,l=1;0==(t.words[0]&l)&&c<26;++c,l<<=1);if(c>0)for(t.iushrn(c);c-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);for(var d=0,h=1;0==(n.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(n.iushrn(d);d-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);t.cmp(n)>=0?(t.isub(n),s.isub(a)):(n.isub(t),a.isub(s))}return(r=0===t.cmpn(1)?s:a).cmpn(0)<0&&r.iadd(e),r},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var i=0;t.isEven()&&n.isEven();i++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var r=t.cmp(n);if(r<0){var o=t;t=n,n=o}else if(0===r||0===n.cmpn(1))break;t.isub(n)}return n.iushln(i)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){i("number"==typeof e);var t=e%26,n=(e-t)/26,r=1<>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)t=1;else{n&&(e=-e),i(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;n--){var i=0|this.words[n],r=0|e.words[n];if(i!==r){ir&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new C(e)},o.prototype.toRed=function(e){return i(!this.red,"Already a number in reduction context"),i(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return i(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return i(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var m={k256:null,p224:null,p192:null,p25519:null};function v(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function _(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function b(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function y(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function w(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function C(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else i(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function S(e){C.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}v.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},v.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t0?n.isub(this.p):n.strip(),n},v.prototype.split=function(e,t){e.iushrn(this.n,0,t)},v.prototype.imulK=function(e){return e.imul(this.k)},r(_,v),_.prototype.split=function(e,t){for(var n=Math.min(e.length,9),i=0;i>>22,r=o}r>>>=22,e.words[i-10]=r,0===r&&e.length>10?e.length-=10:e.length-=9},_.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n>>=26,e.words[n]=r,t=i}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(m[e])return m[e];var t;if("k256"===e)t=new _;else if("p224"===e)t=new b;else if("p192"===e)t=new y;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new w}return m[e]=t,t},C.prototype._verify1=function(e){i(0===e.negative,"red works only with positives"),i(e.red,"red works only with red numbers")},C.prototype._verify2=function(e,t){i(0==(e.negative|t.negative),"red works only with positives"),i(e.red&&e.red===t.red,"red works only with red numbers")},C.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},C.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},C.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},C.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},C.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},C.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},C.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},C.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},C.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},C.prototype.isqr=function(e){return this.imul(e,e.clone())},C.prototype.sqr=function(e){return this.mul(e,e)},C.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(i(t%2==1),3===t){var n=this.m.add(new o(1)).iushrn(2);return this.pow(e,n)}for(var r=this.m.subn(1),s=0;!r.isZero()&&0===r.andln(1);)s++,r.iushrn(1);i(!r.isZero());var a=new o(1).toRed(this),u=a.redNeg(),c=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,c).cmp(u);)l.redIAdd(u);for(var d=this.pow(l,r),h=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),p=s;0!==f.cmp(a);){for(var g=f,m=0;0!==g.cmp(a);m++)g=g.redSqr();i(m=0;i--){for(var c=t.words[i],l=u-1;l>=0;l--){var d=c>>l&1;r!==n[0]&&(r=this.sqr(r)),0!==d||0!==s?(s<<=1,s|=d,(4===++a||0===i&&0===l)&&(r=this.mul(r,n[s]),a=0,s=0)):a=0}u=26}return r},C.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},C.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new S(e)},r(S,C),S.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},S.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},S.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),i=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=n.isub(i).iushrn(this.shift),o=r;return r.cmp(this.m)>=0?o=r.isub(this.m):r.cmpn(0)<0&&(o=r.iadd(this.m)),o._forceRed(this)},S.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var n=e.mul(t),i=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=n.isub(i).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},S.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===e||e,this)}).call(t,n("3IRH")(e))},gpb6:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});n("Vcj/");var i=n("hK2W"),r=n("KIxu"),o=n("aL7J"),s=n("odeJ"),a=n("uNfg"),u=n("tqet"),c=n("03Zz"),l=n("Kp7x"),d=65535,h=function(){function e(e,t,n){if(e.length!==t.length||e.length>d)throw new Error("invalid startIndexes or endIndexes size");this._startIndexes=e,this._endIndexes=t,this._collapseStates=new Uint32Array(Math.ceil(e.length/32)),this._types=n,this._parentsComputed=!1}return e.prototype.ensureParentIndices=function(){var e=this;if(!this._parentsComputed){this._parentsComputed=!0;for(var t=[],n=function(n,i){var r=t[t.length-1];return e.getStartLineNumber(r)<=n&&e.getEndLineNumber(r)>=i},i=0,r=this._startIndexes.length;i16777215||s>16777215)throw new Error("startLineNumber or endLineNumber must not exceed 16777215");for(;t.length>0&&!n(o,s);)t.pop();var a=t.length>0?t[t.length-1]:-1;t.push(i),this._startIndexes[i]=o+((255&a)<<24),this._endIndexes[i]=s+((65280&a)<<16)}}},Object.defineProperty(e.prototype,"length",{get:function(){return this._startIndexes.length},enumerable:!0,configurable:!0}),e.prototype.getStartLineNumber=function(e){return 16777215&this._startIndexes[e]},e.prototype.getEndLineNumber=function(e){return 16777215&this._endIndexes[e]},e.prototype.getType=function(e){return this._types?this._types[e]:void 0},e.prototype.hasTypes=function(){return!!this._types},e.prototype.isCollapsed=function(e){var t=e/32|0,n=e%32;return 0!=(this._collapseStates[t]&1<>>24)+((4278190080&this._endIndexes[e])>>>16);return t===d?-1:t},e.prototype.contains=function(e,t){return this.getStartLineNumber(e)<=t&&this.getEndLineNumber(e)>=t},e.prototype.findIndex=function(e){var t=0,n=this._startIndexes.length;if(0===n)return-1;for(;t=0){if(this.getEndLineNumber(t)>=e)return t;for(t=this.getParentIndex(t);-1!==t;){if(this.contains(t,e))return t;t=this.getParentIndex(t)}}return-1},e.prototype.toString=function(){for(var e=[],t=0;t=this.endLineNumber},e.prototype.containsLine=function(e){return this.startLineNumber<=e&&e<=this.endLineNumber},e}(),p=function(){function e(e,t){this._updateEventEmitter=new l.a,this.onDidChange=this._updateEventEmitter.event,this._textModel=e,this._decorationProvider=t,this._regions=new h(new Uint32Array(0),new Uint32Array(0)),this._editorDecorationIds=[],this._isInitialized=!1}return Object.defineProperty(e.prototype,"regions",{get:function(){return this._regions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textModel",{get:function(){return this._textModel},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isInitialized",{get:function(){return this._isInitialized},enumerable:!0,configurable:!0}),e.prototype.toggleCollapseState=function(e){var t=this;if(e.length){var n={};this._decorationProvider.changeDecorations(function(i){for(var r=0,o=e;r=d))break;r(a,l===d),a++}}u=s()}for(;a0)return e},e.prototype.applyMemento=function(e){if(Array.isArray(e)){for(var t=[],n=0,i=e;n=0;){var o=this._regions.toRegion(i);t&&!t(o,r)||n.push(o),r++,i=o.parentIndex}return n},e.prototype.getRegionAtLine=function(e){if(this._regions){var t=this._regions.findRange(e);if(t>=0)return this._regions.toRegion(t)}return null},e.prototype.getRegionsInside=function(e,t){var n=[],i=e?e.regionIndex+1:0,r=e?e.endLineNumber:Number.MAX_VALUE;if(t&&2===t.length)for(var o=[],s=i,a=this._regions.length;s0&&!u.containedBy(o[o.length-1]);)o.pop();o.push(u),t(u,o.length)&&n.push(u)}else for(s=i,a=this._regions.length;s0)for(var o=0,s=i;o1)){var c=e.getRegionsInside(u,function(e,i){return e.isCollapsed!==t&&i=0;s--)if(n!==r.isCollapsed(s)){var a=r.getStartLineNumber(s);t.test(i.getLineContent(a))&&o.push(r.toRegion(s))}e.toggleCollapseState(o)}function _(e,t,n){for(var i=e.regions,r=[],o=i.length-1;o>=0;o--)n!==i.isCollapsed(o)&&t===i.getType(o)&&r.push(i.toRegion(o));e.toggleCollapseState(r)}var b=n("0ly5"),y=function(){function e(e){this.editor=e,this.autoHideFoldingControls=!0}return e.prototype.getDecorationOption=function(t){return t?e.COLLAPSED_VISUAL_DECORATION:this.autoHideFoldingControls?e.EXPANDED_AUTO_HIDE_VISUAL_DECORATION:e.EXPANDED_VISUAL_DECORATION},e.prototype.deltaDecorations=function(e,t){return this.editor.deltaDecorations(e,t)},e.prototype.changeDecorations=function(e){return this.editor.changeDecorations(e)},e.COLLAPSED_VISUAL_DECORATION=b.a.register({stickiness:1,afterContentClassName:"inline-folded",linesDecorationsClassName:"folding collapsed"}),e.EXPANDED_AUTO_HIDE_VISUAL_DECORATION=b.a.register({stickiness:1,linesDecorationsClassName:"folding"}),e.EXPANDED_VISUAL_DECORATION=b.a.register({stickiness:1,linesDecorationsClassName:"folding alwaysShowFoldIcons"}),e}(),w=n("/9db"),C=n("vTy2"),S=n("X6iQ"),x=function(){function e(e){var t=this;this._updateEventEmitter=new l.a,this._foldingModel=e,this._foldingModelListener=e.onDidChange(function(e){return t.updateHiddenRanges()}),this._hiddenRanges=[],e.regions.length&&this.updateHiddenRanges()}return Object.defineProperty(e.prototype,"onDidChange",{get:function(){return this._updateEventEmitter.event},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hiddenRanges",{get:function(){return this._hiddenRanges},enumerable:!0,configurable:!0}),e.prototype.updateHiddenRanges=function(){for(var e=!1,t=[],n=0,i=0,r=Number.MAX_VALUE,o=-1,s=this._foldingModel.regions;n0},e.prototype.isHidden=function(e){return null!==L(this._hiddenRanges,e)},e.prototype.adjustSelections=function(e){for(var t=this,n=!1,i=this._foldingModel.textModel,r=null,o=function(e){return r&&function(e,t){return e>=t.startLineNumber&&e<=t.endLineNumber}(e,r)||(r=L(t._hiddenRanges,e)),r?r.startLineNumber-1:null},s=0,a=e.length;s0&&(this._hiddenRanges=[],this._updateEventEmitter.fire(this._hiddenRanges)),this._foldingModelListener&&(this._foldingModelListener.dispose(),this._foldingModelListener=null)},e}();function L(e,t){var n=Object(S.h)(e,function(e){return t=0&&e[n].endLineNumber>=t?e[n]:null}var O=n("Fllr"),k=5e3,N="indent",E=function(){function e(e){this.editorModel=e,this.id=N}return e.prototype.dispose=function(){},e.prototype.compute=function(e){var t=O.a.getFoldingRules(this.editorModel.getLanguageIdentifier().id),n=t&&!!t.offSide,i=t&&t.markers;return Promise.resolve(function(e,t,n,i){void 0===i&&(i=k);var r=e.getOptions().tabSize,o=new I(i),s=void 0;n&&(s=new RegExp("("+n.start.source+")|(?:"+n.end.source+")"));var a=[],u=e.getLineCount()+1;a.push({indent:-1,endAbove:u,line:u});for(var c=e.getLineCount();c>0;c--){var l=e.getLineContent(c),d=b.b.computeIndentLevel(l,r),h=a[a.length-1];if(-1!==d){var f=void 0;if(s&&(f=l.match(s))){if(!f[1]){a.push({indent:-2,endAbove:c,line:c});continue}for(var p=a.length-1;p>0&&-2!==a[p].indent;)p--;if(p>0){a.length=p+1,h=a[p],o.insertFirst(c,h.line,d),h.line=c,h.indent=d,h.endAbove=c;continue}}if(h.indent>d){do{a.pop(),h=a[a.length-1]}while(h.indent>d);var g=h.endAbove-1;g-c>=1&&o.insertFirst(c,g,d)}h.indent===d?h.endAbove=c:a.push({indent:d,endAbove:c,line:c})}else t&&(h.endAbove=c)}return o.toIndentRanges(e)}(this.editorModel,n,i))},e}(),I=function(){function e(e){this._startIndexes=[],this._endIndexes=[],this._indentOccurrences=[],this._length=0,this._foldingRangesLimit=e}return e.prototype.insertFirst=function(e,t,n){if(!(e>16777215||t>16777215)){var i=this._length;this._startIndexes[i]=e,this._endIndexes[i]=t,this._length++,n<1e3&&(this._indentOccurrences[n]=(this._indentOccurrences[n]||0)+1)}},e.prototype.toIndentRanges=function(e){if(this._length<=this._foldingRangesLimit){for(var t=new Uint32Array(this._length),n=new Uint32Array(this._length),i=this._length-1,r=0;i>=0;i--,r++)t[r]=this._startIndexes[i],n[r]=this._endIndexes[i];return new h(t,n)}var o=0,s=this._indentOccurrences.length;for(i=0;ithis._foldingRangesLimit){s=i;break}o+=a}}var u=e.getOptions().tabSize;for(t=new Uint32Array(this._foldingRangesLimit),n=new Uint32Array(this._foldingRangesLimit),i=this._length-1,r=0;i>=0;i--){var c=this._startIndexes[i],l=e.getLineContent(c),d=b.b.computeIndentLevel(l,u);(d0&&u.end>u.start&&u.end<=o&&i.push({start:u.start,end:u.end,rank:r,kind:u.kind})}}},M.f)});return Promise.all(r).then(function(e){return i})}(this.providers,this.editorModel,e).then(function(e){return e?j(e,t.limit):null})},e.prototype.dispose=function(){},e}();var F=function(){function e(e){this._startIndexes=[],this._endIndexes=[],this._nestingLevels=[],this._nestingLevelCounts=[],this._types=[],this._length=0,this._foldingRangesLimit=e}return e.prototype.add=function(e,t,n,i){if(!(e>16777215||t>16777215)){var r=this._length;this._startIndexes[r]=e,this._endIndexes[r]=t,this._nestingLevels[r]=i,this._types[r]=n,this._length++,i<30&&(this._nestingLevelCounts[i]=(this._nestingLevelCounts[i]||0)+1)}},e.prototype.toIndentRanges=function(){if(this._length<=this._foldingRangesLimit){for(var e=new Uint32Array(this._length),t=new Uint32Array(this._length),n=0;nthis._foldingRangesLimit){r=n;break}i+=o}}e=new Uint32Array(this._foldingRangesLimit),t=new Uint32Array(this._foldingRangesLimit);for(var s=[],a=(n=0,0);nr.start)if(u.end<=r.end)o.push(r),r=u,i.add(u.start,u.end,u.kind&&u.kind.value,o.length);else{if(u.start>r.end){do{r=o.pop()}while(r&&u.start>r.end);r&&o.push(r),r=u}i.add(u.start,u.end,u.kind&&u.kind.value,o.length)}}else r=u,i.add(u.start,u.end,u.kind&&u.kind.value,o.length)}return i.toIndentRanges()}var W="init",B=function(){function e(e,t,n,i){if(this.editorModel=e,this.id=W,t.length){this.decorationIds=e.deltaDecorations([],t.map(function(t){return{range:{startLineNumber:t.startLineNumber,startColumn:0,endLineNumber:t.endLineNumber,endColumn:e.getLineLength(t.endLineNumber)},options:{stickiness:1}}})),this.timeout=setTimeout(n,i)}}return e.prototype.dispose=function(){this.decorationIds&&(this.editorModel.deltaDecorations(this.decorationIds,[]),this.decorationIds=void 0),"number"==typeof this.timeout&&(clearTimeout(this.timeout),this.timeout=void 0)},e.prototype.compute=function(e){var t=[];if(this.decorationIds)for(var n=0,i=this.decorationIds;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},K=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},q=new V.d("foldingEnabled",!1),G="editor.contrib.folding",Z=function(e){function t(t,n){var i=e.call(this)||this;return i.contextKeyService=n,i.localToDispose=i._register(new u.b),i.editor=t,i._isEnabled=i.editor.getConfiguration().contribInfo.folding,i._autoHideFoldingControls="mouseover"===i.editor.getConfiguration().contribInfo.showFoldingControls,i._useFoldingProviders="indentation"!==i.editor.getConfiguration().contribInfo.foldingStrategy,i.foldingModel=null,i.hiddenRangeModel=null,i.rangeProvider=null,i.foldingRegionPromise=null,i.foldingStateMemento=null,i.foldingModelPromise=null,i.updateScheduler=null,i.cursorChangedScheduler=null,i.mouseDownInfo=null,i.foldingDecorationProvider=new y(t),i.foldingDecorationProvider.autoHideFoldingControls=i._autoHideFoldingControls,i.foldingEnabled=q.bindTo(i.contextKeyService),i.foldingEnabled.set(i._isEnabled),i._register(i.editor.onDidChangeModel(function(){return i.onModelChanged()})),i._register(i.editor.onDidChangeConfiguration(function(e){if(e.contribInfo){var t=i._isEnabled;i._isEnabled=i.editor.getConfiguration().contribInfo.folding,i.foldingEnabled.set(i._isEnabled),t!==i._isEnabled&&i.onModelChanged();var n=i._autoHideFoldingControls;i._autoHideFoldingControls="mouseover"===i.editor.getConfiguration().contribInfo.showFoldingControls,n!==i._autoHideFoldingControls&&(i.foldingDecorationProvider.autoHideFoldingControls=i._autoHideFoldingControls,i.onModelContentChanged());var r=i._useFoldingProviders;i._useFoldingProviders="indentation"!==i.editor.getConfiguration().contribInfo.foldingStrategy,r!==i._useFoldingProviders&&i.onFoldingStrategyChanged()}})),i.onModelChanged(),i}return z(t,e),t.get=function(e){return e.getContribution(G)},t.prototype.getId=function(){return G},t.prototype.saveViewState=function(){var e=this.editor.getModel();if(!e||!this._isEnabled||e.isTooLargeForTokenization())return{};if(this.foldingModel){var t=this.foldingModel.isInitialized?this.foldingModel.getMemento():this.hiddenRangeModel.getMemento(),n=this.rangeProvider?this.rangeProvider.id:void 0;return{collapsedRegions:t,lineCount:e.getLineCount(),provider:n}}},t.prototype.restoreViewState=function(e){var t=this.editor.getModel();if(t&&this._isEnabled&&!t.isTooLargeForTokenization()&&this.hiddenRangeModel&&e&&e.collapsedRegions&&e.lineCount===t.getLineCount()){e.provider!==A&&e.provider!==W||(this.foldingStateMemento=e);var n=e.collapsedRegions;if(this.hiddenRangeModel.applyMemento(n)){var i=this.getFoldingModel();i&&i.then(function(e){e&&e.applyMemento(n)}).then(void 0,M.e)}}},t.prototype.onModelChanged=function(){var e=this;this.localToDispose.clear();var t=this.editor.getModel();this._isEnabled&&t&&!t.isTooLargeForTokenization()&&(this.foldingModel=new p(t,this.foldingDecorationProvider),this.localToDispose.add(this.foldingModel),this.hiddenRangeModel=new x(this.foldingModel),this.localToDispose.add(this.hiddenRangeModel),this.localToDispose.add(this.hiddenRangeModel.onDidChange(function(t){return e.onHiddenRangesChanges(t)})),this.updateScheduler=new s.a(200),this.cursorChangedScheduler=new s.d(function(){return e.revealCursor()},200),this.localToDispose.add(this.cursorChangedScheduler),this.localToDispose.add(D.m.onDidChange(function(){return e.onFoldingStrategyChanged()})),this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(function(){return e.onFoldingStrategyChanged()})),this.localToDispose.add(this.editor.onDidChangeModelContent(function(){return e.onModelContentChanged()})),this.localToDispose.add(this.editor.onDidChangeCursorPosition(function(){return e.onCursorPositionChanged()})),this.localToDispose.add(this.editor.onMouseDown(function(t){return e.onEditorMouseDown(t)})),this.localToDispose.add(this.editor.onMouseUp(function(t){return e.onEditorMouseUp(t)})),this.localToDispose.add({dispose:function(){e.foldingRegionPromise&&(e.foldingRegionPromise.cancel(),e.foldingRegionPromise=null),e.updateScheduler&&e.updateScheduler.cancel(),e.updateScheduler=null,e.foldingModel=null,e.foldingModelPromise=null,e.hiddenRangeModel=null,e.cursorChangedScheduler=null,e.foldingStateMemento=null,e.rangeProvider&&e.rangeProvider.dispose(),e.rangeProvider=null}}),this.onModelContentChanged())},t.prototype.onFoldingStrategyChanged=function(){this.rangeProvider&&this.rangeProvider.dispose(),this.rangeProvider=null,this.onModelContentChanged()},t.prototype.getRangeProvider=function(e){var t=this;if(this.rangeProvider)return this.rangeProvider;if(this.rangeProvider=new E(e),this._useFoldingProviders&&this.foldingModel){var n=D.m.ordered(this.foldingModel.textModel);if(0===n.length&&this.foldingStateMemento&&this.foldingStateMemento.collapsedRegions)return this.rangeProvider=new B(e,this.foldingStateMemento.collapsedRegions,function(){t.foldingStateMemento=null,t.onFoldingStrategyChanged()},3e4);n.length>0&&(this.rangeProvider=new R(e,n))}return this.foldingStateMemento=null,this.rangeProvider},t.prototype.getFoldingModel=function(){return this.foldingModelPromise},t.prototype.onModelContentChanged=function(){var e=this;this.updateScheduler&&(this.foldingRegionPromise&&(this.foldingRegionPromise.cancel(),this.foldingRegionPromise=null),this.foldingModelPromise=this.updateScheduler.trigger(function(){var t=e.foldingModel;if(!t)return null;var n=e.foldingRegionPromise=Object(s.f)(function(n){return e.getRangeProvider(t.textModel).compute(n)});return n.then(function(i){if(i&&n===e.foldingRegionPromise){var r=e.editor.getSelections(),o=r?r.map(function(e){return e.startLineNumber}):[];t.update(i,o)}return t})}).then(void 0,function(e){return Object(M.e)(e),null}))},t.prototype.onHiddenRangesChanges=function(e){if(this.hiddenRangeModel&&e.length){var t=this.editor.getSelections();t&&this.hiddenRangeModel.adjustSelections(t)&&this.editor.setSelections(t)}this.editor.setHiddenAreas(e)},t.prototype.onCursorPositionChanged=function(){this.hiddenRangeModel&&this.hiddenRangeModel.hasRanges()&&this.cursorChangedScheduler.schedule()},t.prototype.revealCursor=function(){var e=this,t=this.getFoldingModel();t&&t.then(function(t){if(t){var n=e.editor.getSelections();if(n&&n.length>0){for(var i=[],r=function(n){var r=n.selectionStartLineNumber;e.hiddenRangeModel&&e.hiddenRangeModel.isHidden(r)&&i.push.apply(i,t.getAllRegionsAtLine(r,function(e){return e.isCollapsed&&r>e.startLineNumber}))},o=0,s=n;o "+this.positionLineNumber+","+this.positionColumn+"]"},t.prototype.equalsSelection=function(e){return t.selectionsEqual(this,e)},t.selectionsEqual=function(e,t){return e.selectionStartLineNumber===t.selectionStartLineNumber&&e.selectionStartColumn===t.selectionStartColumn&&e.positionLineNumber===t.positionLineNumber&&e.positionColumn===t.positionColumn},t.prototype.getDirection=function(){return this.selectionStartLineNumber===this.startLineNumber&&this.selectionStartColumn===this.startColumn?0:1},t.prototype.setEndPosition=function(e,n){return 0===this.getDirection()?new t(this.startLineNumber,this.startColumn,e,n):new t(e,n,this.startLineNumber,this.startColumn)},t.prototype.getPosition=function(){return new r.a(this.positionLineNumber,this.positionColumn)},t.prototype.setStartPosition=function(e,n){return 0===this.getDirection()?new t(e,n,this.endLineNumber,this.endColumn):new t(this.endLineNumber,this.endColumn,e,n)},t.fromPositions=function(e,n){return void 0===n&&(n=e),new t(e.lineNumber,e.column,n.lineNumber,n.column)},t.liftSelection=function(e){return new t(e.selectionStartLineNumber,e.selectionStartColumn,e.positionLineNumber,e.positionColumn)},t.selectionsArrEqual=function(e,t){if(e&&!t||!e&&t)return!1;if(!e&&!t)return!0;if(e.length!==t.length)return!1;for(var n=0,i=e.length;n>>0},t.writeUInt32BE=function(e,t,n){e[0+n]=t>>>24,e[1+n]=t>>>16&255,e[2+n]=t>>>8&255,e[3+n]=255&t},t.ip=function(e,t,n,i){for(var r=0,o=0,s=6;s>=0;s-=2){for(var a=0;a<=24;a+=8)r<<=1,r|=t>>>a+s&1;for(a=0;a<=24;a+=8)r<<=1,r|=e>>>a+s&1}for(s=6;s>=0;s-=2){for(a=1;a<=25;a+=8)o<<=1,o|=t>>>a+s&1;for(a=1;a<=25;a+=8)o<<=1,o|=e>>>a+s&1}n[i+0]=r>>>0,n[i+1]=o>>>0},t.rip=function(e,t,n,i){for(var r=0,o=0,s=0;s<4;s++)for(var a=24;a>=0;a-=8)r<<=1,r|=t>>>a+s&1,r<<=1,r|=e>>>a+s&1;for(s=4;s<8;s++)for(a=24;a>=0;a-=8)o<<=1,o|=t>>>a+s&1,o<<=1,o|=e>>>a+s&1;n[i+0]=r>>>0,n[i+1]=o>>>0},t.pc1=function(e,t,n,i){for(var r=0,o=0,s=7;s>=5;s--){for(var a=0;a<=24;a+=8)r<<=1,r|=t>>a+s&1;for(a=0;a<=24;a+=8)r<<=1,r|=e>>a+s&1}for(a=0;a<=24;a+=8)r<<=1,r|=t>>a+s&1;for(s=1;s<=3;s++){for(a=0;a<=24;a+=8)o<<=1,o|=t>>a+s&1;for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1}for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1;n[i+0]=r>>>0,n[i+1]=o>>>0},t.r28shl=function(e,t){return e<>>28-t};var i=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];t.pc2=function(e,t,n,r){for(var o=0,s=0,a=i.length>>>1,u=0;u>>i[u]&1;for(u=a;u>>i[u]&1;n[r+0]=o>>>0,n[r+1]=s>>>0},t.expand=function(e,t,n){var i=0,r=0;i=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)i<<=6,i|=e>>>o&63;for(o=11;o>=3;o-=4)r|=e>>>o&63,r<<=6;r|=(31&e)<<1|e>>>31,t[n+0]=i>>>0,t[n+1]=r>>>0};var r=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];t.substitute=function(e,t){for(var n=0,i=0;i<4;i++){n<<=4,n|=r[64*i+(e>>>18-6*i&63)]}for(i=0;i<4;i++){n<<=4,n|=r[256+64*i+(t>>>18-6*i&63)]}return n>>>0};var o=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];t.permute=function(e){for(var t=0,n=0;n>>o[n]&1;return t>>>0},t.padSplit=function(e,t,n){for(var i=e.toString(2);i.length=0;n--)t+=e.charAt(n);return t}(e=n)),t}}(),g=function(){function e(){}return e._findPrevBracketInText=function(e,t,n,i){var o=n.match(e);if(!o)return null;var s=n.length-(o.index||0),a=o[0].length,u=i+s;return new r.a(t,u-a+1,t,u+1)},e.findPrevBracketInToken=function(e,t,n,i,r){var o=p(n).substring(n.length-r,n.length-i);return this._findPrevBracketInText(e,t,o,i)},e.findNextBracketInText=function(e,t,n,i){var o=n.match(e);if(!o)return null;var s=o.index||0,a=o[0].length;if(0===a)return null;var u=i+s;return new r.a(t,u+1,t,u+1+a)},e.findNextBracketInToken=function(e,t,n,i,r){var o=n.substring(i,r);return this.findNextBracketInText(e,t,o,i)},e}()},iP15:function(e,t,n){(function(t){function n(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&"true"===String(n).toLowerCase()}e.exports=function(e,t){if(n("noDeprecation"))return e;var i=!1;return function(){if(!i){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}}}).call(t,n("DuR2"))},iTY7:function(e,t,n){var i=n("LC74"),r=n("3UtB").Reporter,o=n("EuP9").Buffer;function s(e,t){r.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function a(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return e instanceof a||(e=new a(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}i(s,r),t.DecoderBuffer=s,s.prototype.save=function(){return{offset:this.offset,reporter:r.prototype.save.call(this)}},s.prototype.restore=function(e){var t=new s(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,r.prototype.restore.call(this,e.reporter),t},s.prototype.isEmpty=function(){return this.offset===this.length},s.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},s.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");var n=new s(this.base);return n._reporterState=this._reporterState,n.offset=this.offset,n.length=this.offset+e,this.offset+=e,n},s.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},t.EncoderBuffer=a,a.prototype.join=function(e,t){return e||(e=new o(this.length)),t||(t=0),0===this.length?e:(Array.isArray(this.value)?this.value.forEach(function(n){n.join(e,t),t+=n.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length),e)}},iXRW:function(e,t,n){"use strict";t.h=function(e){if(1===e)return"blink";if(4===e)return"expand";if(3===e)return"phase";if(2===e)return"smooth";if(5===e)return"solid";throw new Error("blinkingStyleToString: Unknown blinkingStyle")},n.d(t,"g",function(){return i}),t.i=function(e){if(e===i.Line)return"line";if(e===i.Block)return"block";if(e===i.Underline)return"underline";if(e===i.LineThin)return"line-thin";if(e===i.BlockOutline)return"block-outline";if(e===i.UnderlineThin)return"underline-thin";throw new Error("cursorStyleToString: Unknown cursorStyle")},n.d(t,"e",function(){return d}),n.d(t,"d",function(){return _}),n.d(t,"f",function(){return b}),n.d(t,"b",function(){return w}),n.d(t,"c",function(){return C}),n.d(t,"a",function(){return S});var i,r=n("hK2W"),o=n("X6iQ"),s=n("TU7t"),a=n("ZfGv"),u=n("+jct"),c=n("KIxu"),l=this&&this.__assign||function(){return(l=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=2?(S=v?2:4,M=2/b):(S=v?1:3,M=1/b),(L=Math.max(0,Math.floor((D-d-2)*M/(c+M))))/M>_&&(L=Math.floor(_*M)),O=D-L,"left"===m?(x=0,k+=L,N+=L,E+=L,I+=L):x=t-L-d}else x=0,L=0,S=0,O=D;var T=Math.max(1,Math.floor((O-d-2)/c)),P=h?f:0;return{width:t,height:n,glyphMarginLeft:k,glyphMarginWidth:C,glyphMarginHeight:n,lineNumbersLeft:N,lineNumbersWidth:y,lineNumbersHeight:n,decorationsLeft:E,decorationsWidth:u,decorationsHeight:n,contentLeft:I,contentWidth:O,contentHeight:n,renderMinimap:S,minimapLeft:x,minimapWidth:L,viewportColumn:T,verticalScrollbarWidth:d,horizontalScrollbarHeight:p,overviewRuler:{top:P,width:d,height:n-2*P,right:0}}},e}(),w={fontFamily:a.d?"Menlo, Monaco, 'Courier New', monospace":a.c?"'Droid Sans Mono', 'monospace', monospace, 'Droid Sans Fallback'":"Consolas, 'Courier New', monospace",fontWeight:"normal",fontSize:a.d?12:14,lineHeight:0,letterSpacing:0},C={tabSize:4,indentSize:4,insertSpaces:!0,detectIndentation:!0,trimAutoWhitespace:!0,largeFileOptimizations:!0},S={inDiffEditor:!1,wordSeparators:u.b,lineNumbersMinChars:5,lineDecorationsWidth:10,readOnly:!1,mouseStyle:"text",disableLayerHinting:!1,automaticLayout:!1,wordWrap:"off",wordWrapColumn:80,wordWrapMinified:!0,wrappingIndent:1,wordWrapBreakBeforeCharacters:"([{‘“〈《「『【〔([{「£¥$£¥++",wordWrapBreakAfterCharacters:" \t})]?|/&,;¢°′″‰℃、。。、¢,.:;?!%・・ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ァィゥェォャュョッー”〉》」』】〕)]}」",wordWrapBreakObtrusiveCharacters:".",autoClosingBrackets:"languageDefined",autoClosingQuotes:"languageDefined",autoClosingOvertype:"auto",autoSurround:"languageDefined",autoIndent:!0,dragAndDrop:!0,emptySelectionClipboard:!0,copyWithSyntaxHighlighting:!0,useTabStops:!0,multiCursorModifier:"altKey",multiCursorMergeOverlapping:!0,accessibilitySupport:"auto",showUnused:!0,viewInfo:{extraEditorClassName:"",disableMonospaceOptimizations:!1,rulers:[],ariaLabel:r.a("editorViewAccessibleLabel","Editor content"),renderLineNumbers:1,renderCustomLineNumbers:null,cursorSurroundingLines:0,renderFinalNewline:!0,selectOnLineNumbers:!0,glyphMargin:!0,revealHorizontalRightPadding:30,roundedSelection:!0,overviewRulerLanes:2,overviewRulerBorder:!0,cursorBlinking:1,mouseWheelZoom:!1,cursorSmoothCaretAnimation:!1,cursorStyle:i.Line,cursorWidth:0,hideCursorInOverviewRuler:!1,scrollBeyondLastLine:!0,scrollBeyondLastColumn:5,smoothScrolling:!1,stopRenderingLineAfter:1e4,renderWhitespace:"none",renderControlCharacters:!1,fontLigatures:!1,renderIndentGuides:!0,highlightActiveIndentGuide:!0,renderLineHighlight:"line",scrollbar:{vertical:1,horizontal:1,arrowSize:11,useShadows:!0,verticalHasArrows:!1,horizontalHasArrows:!1,horizontalScrollbarSize:10,horizontalSliderSize:10,verticalScrollbarSize:14,verticalSliderSize:14,handleMouseWheel:!0,mouseWheelScrollSensitivity:1,fastScrollSensitivity:5},minimap:{enabled:!0,side:"right",showSlider:"mouseover",renderCharacters:!0,maxColumn:120},fixedOverflowWidgets:!1},contribInfo:{selectionClipboard:!0,hover:{enabled:!0,delay:300,sticky:!0},links:!0,contextmenu:!0,quickSuggestions:{other:!0,comments:!1,strings:!1},quickSuggestionsDelay:10,parameterHints:{enabled:!0,cycle:!1},formatOnType:!1,formatOnPaste:!1,suggestOnTriggerCharacters:!0,acceptSuggestionOnEnter:"on",acceptSuggestionOnCommitCharacter:!0,wordBasedSuggestions:!0,suggestSelection:"recentlyUsed",suggestFontSize:0,suggestLineHeight:0,tabCompletion:"off",suggest:{filterGraceful:!0,snippets:"inline",snippetsPreventQuickSuggestions:!0,localityBonus:!1,shareSuggestSelections:!1,showIcons:!0,maxVisibleSuggestions:12,filteredTypes:Object.create(null)},gotoLocation:{multiple:"peek"},selectionHighlight:!0,occurrencesHighlight:!0,codeLens:!0,folding:!0,foldingStrategy:"auto",showFoldingControls:"mouseover",matchBrackets:!0,find:{seedSearchStringFromSelection:!0,autoFindInSelection:!1,globalFindClipboard:!1,addExtraSpaceOnTop:!0},colorDecorators:!0,lightbulbEnabled:!0,codeActionsOnSave:{},codeActionsOnSaveTimeout:750}}},ia1G:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});n("Q+ux");var i,r=n("hK2W"),o=n("odeJ"),s=n("80kS"),a=n("zxiH"),u=n("3uSZ"),c=n("tqet"),l=n("ZfGv"),d=n("03Zz"),h=n("0ly5"),f=n("PCC9"),p=n("qzX+"),g=n("mrx5"),m=n("vTy2"),v=n("jIdl"),_=n("ItKl"),b=n("X6iQ"),y=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),w=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},C=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},P=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},A=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},R=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0||!n.umod(e.prime1)||!n.umod(e.prime2);)n=new i(r(t));return n}e.exports=o,o.getr=s}).call(t,n("EuP9").Buffer)},jUH2:function(e,t,n){"use strict";n.d(t,"c",function(){return o}),n.d(t,"b",function(){return s}),n.d(t,"a",function(){return a}),t.d=function(e,t,n,r){return new i.b([new i.a(r,"",e)],n)},t.e=function(e,t,n,r){var s=new Uint32Array(2);return s[0]=r,s[1]=(16384|e<<0|2<<23)>>>0,new i.c(s,null===n?o:n)};var i=n("c6Qy"),r=n("PCC9"),o=new(function(){function e(){}return e.prototype.clone=function(){return this},e.prototype.equals=function(e){return this===e},e}()),s="vs.editor.nullMode",a=new r.p(s,0)},jkjm:function(e,t,n){var i=n("19bf"),r=n("8YCc"),o=n("7VT+"),s=n("tXf9"),a=n("/vd3"),u=n("X3l8").Buffer;function c(e){var t;"object"!=typeof e||u.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=u.from(e));var n,c,l=o(e,t),d=l.tag,h=l.data;switch(d){case"CERTIFICATE":c=i.certificate.decode(h,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(c||(c=i.PublicKey.decode(h,"der")),n=c.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return i.RSAPublicKey.decode(c.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return c.subjectPrivateKey=c.subjectPublicKey,{type:"ec",data:c};case"1.2.840.10040.4.1":return c.algorithm.params.pub_key=i.DSAparam.decode(c.subjectPublicKey.data,"der"),{type:"dsa",data:c.algorithm.params};default:throw new Error("unknown key id "+n)}throw new Error("unknown key type "+d);case"ENCRYPTED PRIVATE KEY":h=function(e,t){var n=e.algorithm.decrypt.kde.kdeparams.salt,i=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),o=r[e.algorithm.decrypt.cipher.algo.join(".")],c=e.algorithm.decrypt.cipher.iv,l=e.subjectPrivateKey,d=parseInt(o.split("-")[1],10)/8,h=a.pbkdf2Sync(t,n,i,d,"sha1"),f=s.createDecipheriv(o,h,c),p=[];return p.push(f.update(l)),p.push(f.final()),u.concat(p)}(h=i.EncryptedPrivateKey.decode(h,"der"),t);case"PRIVATE KEY":switch(n=(c=i.PrivateKey.decode(h,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return i.RSAPrivateKey.decode(c.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:c.algorithm.curve,privateKey:i.ECPrivateKey.decode(c.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return c.algorithm.params.priv_key=i.DSAparam.decode(c.subjectPrivateKey,"der"),{type:"dsa",params:c.algorithm.params};default:throw new Error("unknown key id "+n)}throw new Error("unknown key type "+d);case"RSA PUBLIC KEY":return i.RSAPublicKey.decode(h,"der");case"RSA PRIVATE KEY":return i.RSAPrivateKey.decode(h,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:i.DSAPrivateKey.decode(h,"der")};case"EC PRIVATE KEY":return{curve:(h=i.ECPrivateKey.decode(h,"der")).parameters.value,privateKey:h.privateKey};default:throw new Error("unknown key type "+d)}}e.exports=c,c.signature=i.signature},k2Sm:function(e,t,n){var i=n("X3l8").Buffer;function r(e,t,n){for(var i,r,s,a=-1,u=0;++a<8;)i=e._cipher.encryptBlock(e._prev),r=t&1<<7-a?128:0,u+=(128&(s=i[0]^r))>>a%8,e._prev=o(e._prev,n?r:s);return u}function o(e,t){var n=e.length,r=-1,o=i.allocUnsafe(e.length);for(e=i.concat([e,i.from([t])]);++r>7;return o}t.encrypt=function(e,t,n){for(var o=t.length,s=i.allocUnsafe(o),a=-1;++a=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},k=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},N=new _.d("accessibilityHelpWidgetVisible",!1),E=function(e){function t(t,n){var i=e.call(this)||this;return i._editor=t,i._widget=i._register(n.createInstance(I,i._editor)),i}return L(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype.getId=function(){return t.ID},t.prototype.show=function(){this._widget.show()},t.prototype.hide=function(){this._widget.hide()},t.ID="editor.contrib.accessibilityHelpController",t=O([k(1,b.a)],t)}(d.a);var I=function(e){function t(t,n,i,r){var o=e.call(this)||this;return o._contextKeyService=n,o._keybindingService=i,o._openerService=r,o._editor=t,o._isVisibleKey=N.bindTo(o._contextKeyService),o._domNode=Object(a.b)(document.createElement("div")),o._domNode.setClassName("accessibilityHelpWidget"),o._domNode.setDisplay("none"),o._domNode.setAttribute("role","dialog"),o._domNode.setAttribute("aria-hidden","true"),o._contentDomNode=Object(a.b)(document.createElement("div")),o._contentDomNode.setAttribute("role","document"),o._domNode.appendChild(o._contentDomNode),o._isVisible=!1,o._register(o._editor.onDidLayoutChange(function(){o._isVisible&&o._layout()})),o._register(s.k(o._contentDomNode.domNode,"keydown",function(e){if(o._isVisible&&(e.equals(2083)&&(Object(c.a)(x.a.emergencyConfOn),o._editor.updateOptions({accessibilitySupport:"on"}),s.p(o._contentDomNode.domNode),o._buildContent(),o._contentDomNode.domNode.focus(),e.preventDefault(),e.stopPropagation()),e.equals(2086))){Object(c.a)(x.a.openingDocs);var t=o._editor.getRawConfiguration().accessibilityHelpUrl;void 0===t&&(t="https://go.microsoft.com/fwlink/?linkid=852450"),o._openerService.open(p.a.parse(t)),e.preventDefault(),e.stopPropagation()}})),o.onblur(o._contentDomNode.domNode,function(){o.hide()}),o._editor.addOverlayWidget(o),o}return L(t,e),t.prototype.dispose=function(){this._editor.removeOverlayWidget(this),e.prototype.dispose.call(this)},t.prototype.getId=function(){return t.ID},t.prototype.getDomNode=function(){return this._domNode.domNode},t.prototype.getPosition=function(){return{preference:null}},t.prototype.show=function(){this._isVisible||(this._isVisible=!0,this._isVisibleKey.set(!0),this._layout(),this._domNode.setDisplay("block"),this._domNode.setAttribute("aria-hidden","false"),this._contentDomNode.domNode.tabIndex=0,this._buildContent(),this._contentDomNode.domNode.focus())},t.prototype._descriptionForCommand=function(e,t,n){var i=this._keybindingService.lookupKeybinding(e);return i?f.r(t,i.getAriaLabel()):f.r(n,e)},t.prototype._buildContent=function(){var e=this._editor.getConfiguration(),t=this._editor.getSelections(),n=0;if(t){var i=this._editor.getModel();i&&t.forEach(function(e){n+=i.getValueLengthInRange(e)})}var r=function(e,t){return e&&0!==e.length?1===e.length?t?f.r(x.a.singleSelectionRange,e[0].positionLineNumber,e[0].positionColumn,t):f.r(x.a.singleSelection,e[0].positionLineNumber,e[0].positionColumn):t?f.r(x.a.multiSelectionRange,e.length,t):e.length>0?f.r(x.a.multiSelection,e.length):"":x.a.noSelection}(t,n);e.wrappingInfo.inDiffEditor?e.readOnly?r+=x.a.readonlyDiffEditor:r+=x.a.editableDiffEditor:e.readOnly?r+=x.a.readonlyEditor:r+=x.a.editableEditor;var o=h.d?x.a.changeConfigToOnMac:x.a.changeConfigToOnWinLinux;switch(e.accessibilitySupport){case 0:r+="\n\n - "+o;break;case 2:r+="\n\n - "+x.a.auto_on;break;case 1:r+="\n\n - "+x.a.auto_off,r+=" "+o}e.tabFocusMode?r+="\n\n - "+this._descriptionForCommand(v.ToggleTabFocusModeAction.ID,x.a.tabFocusModeOnMsg,x.a.tabFocusModeOnMsgNoKb):r+="\n\n - "+this._descriptionForCommand(v.ToggleTabFocusModeAction.ID,x.a.tabFocusModeOffMsg,x.a.tabFocusModeOffMsgNoKb),r+="\n\n - "+(h.d?x.a.openDocMac:x.a.openDocWinLinux),r+="\n\n"+x.a.outroMsg,this._contentDomNode.domNode.appendChild(Object(u.b)(r)),this._contentDomNode.domNode.setAttribute("aria-label",r)},t.prototype.hide=function(){this._isVisible&&(this._isVisible=!1,this._isVisibleKey.reset(),this._domNode.setDisplay("none"),this._domNode.setAttribute("aria-hidden","true"),this._contentDomNode.domNode.tabIndex=-1,s.p(this._contentDomNode.domNode),this._editor.focus())},t.prototype._layout=function(){var e=this._editor.getLayoutInfo(),n=Math.max(5,Math.min(t.WIDTH,e.width-40)),i=Math.max(5,Math.min(t.HEIGHT,e.height-40));this._domNode.setWidth(n),this._domNode.setHeight(i);var r=Math.round((e.height-i)/2);this._domNode.setTop(r);var o=Math.round((e.width-n)/2);this._domNode.setLeft(o)},t.ID="editor.contrib.accessibilityHelpWidget",t.WIDTH=500,t.HEIGHT=300,t=O([k(1,_.c),k(2,y.a),k(3,w.a)],t)}(l.a),D=function(e){function t(){return e.call(this,{id:"editor.action.showAccessibilityHelp",label:x.a.showAccessibilityHelpAction,alias:"Show Accessibility Help",precondition:void 0,kbOpts:{kbExpr:m.a.focus,primary:o.j?2107:571,weight:100}})||this}return L(t,e),t.prototype.run=function(e,t){var n=E.get(t);n&&n.show()},t}(g.b);Object(g.h)(E),Object(g.f)(D);var M=g.c.bindToContribution(E.get);Object(g.g)(new M({id:"closeAccessibilityHelp",precondition:N,handler:function(e){return e.hide()},kbOpts:{weight:200,kbExpr:m.a.focus,primary:9,secondary:[1033]}})),Object(S.f)(function(e,t){var n=e.getColor(C.N);n&&t.addRule(".monaco-editor .accessibilityHelpWidget { background-color: "+n+"; }");var i=e.getColor(C.P);i&&t.addRule(".monaco-editor .accessibilityHelpWidget { color: "+i+"; }");var r=e.getColor(C._48);r&&t.addRule(".monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px "+r+"; }");var o=e.getColor(C.e);o&&t.addRule(".monaco-editor .accessibilityHelpWidget { border: 2px solid "+o+"; }")})},kkc6:function(e,t,n){var i=n("EuP9"),r=i.Buffer;function o(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=i:(o(i,t),t.Buffer=s),o(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i.SlowBuffer(e)}},l6RD:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});n("o37+");var i,r=n("hK2W"),o=n("uNfg"),s=n("tqet"),a=n("03Zz"),u=n("vTy2"),c=n("/9db"),l=n("6TMp"),d=n("7/Cv"),h=n("80kS"),f=n("TNPA"),p=n("3uSZ"),g=n("artP"),m=n("0ly5"),v=n("PCC9"),_=n("pWM+"),b=n("MfmB"),y=n("Kp7x"),w=function(){function e(e,t,n){this.presentationIndex=n,this._onColorFlushed=new y.a,this.onColorFlushed=this._onColorFlushed.event,this._onDidChangeColor=new y.a,this.onDidChangeColor=this._onDidChangeColor.event,this._onDidChangePresentation=new y.a,this.onDidChangePresentation=this._onDidChangePresentation.event,this.originalColor=e,this._color=e,this._colorPresentations=t}return Object.defineProperty(e.prototype,"color",{get:function(){return this._color},set:function(e){this._color.equals(e)||(this._color=e,this._onDidChangeColor.fire(e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"presentation",{get:function(){return this.colorPresentations[this.presentationIndex]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorPresentations",{get:function(){return this._colorPresentations},set:function(e){this._colorPresentations=e,this.presentationIndex>e.length-1&&(this.presentationIndex=0),this._onDidChangePresentation.fire(this.presentation)},enumerable:!0,configurable:!0}),e.prototype.selectNextColorPresentation=function(){this.presentationIndex=(this.presentationIndex+1)%this.colorPresentations.length,this.flushColor(),this._onDidChangePresentation.fire(this.presentation)},e.prototype.guessColorPresentation=function(e,t){for(var n=0;n0,n&&i)?e:void 0;var t,n,i},function(e){Object(F.f)(e)})});return Promise.all(i).then(R.d)}Object(a.e)("_executeHoverProvider",function(e,t){return j(e,t,h.a.None)});var W=n("odeJ"),B=function(){function e(e,t,n,i,r){var o=this;this._computer=e,this._state=0,this._hoverTime=r,this._firstWaitScheduler=new W.d(function(){return o._triggerAsyncComputation()},0),this._secondWaitScheduler=new W.d(function(){return o._triggerSyncComputation()},0),this._loadingMessageScheduler=new W.d(function(){return o._showLoadingMessage()},0),this._asyncComputationPromise=null,this._asyncComputationPromiseDone=!1,this._completeCallback=t,this._errorCallback=n,this._progressCallback=i}return e.prototype.setHoverTime=function(e){this._hoverTime=e},e.prototype._firstWaitTime=function(){return this._hoverTime/2},e.prototype._secondWaitTime=function(){return this._hoverTime/2},e.prototype._loadingMessageTime=function(){return 3*this._hoverTime},e.prototype._triggerAsyncComputation=function(){var e=this;this._state=2,this._secondWaitScheduler.schedule(this._secondWaitTime()),this._computer.computeAsync?(this._asyncComputationPromiseDone=!1,this._asyncComputationPromise=Object(W.f)(function(t){return e._computer.computeAsync(t)}),this._asyncComputationPromise.then(function(t){e._asyncComputationPromiseDone=!0,e._withAsyncResult(t)},function(t){return e._onError(t)})):this._asyncComputationPromiseDone=!0},e.prototype._triggerSyncComputation=function(){this._computer.computeSync&&this._computer.onResult(this._computer.computeSync(),!0),this._asyncComputationPromiseDone?(this._state=0,this._onComplete(this._computer.getResult())):(this._state=3,this._onProgress(this._computer.getResult()))},e.prototype._showLoadingMessage=function(){3===this._state&&this._onProgress(this._computer.getResultWithLoadingMessage())},e.prototype._withAsyncResult=function(e){e&&this._computer.onResult(e,!1),3===this._state&&(this._state=0,this._onComplete(this._computer.getResult()))},e.prototype._onComplete=function(e){this._completeCallback&&this._completeCallback(e)},e.prototype._onError=function(e){this._errorCallback?this._errorCallback(e):Object(F.e)(e)},e.prototype._onProgress=function(e){this._progressCallback&&this._progressCallback(e)},e.prototype.start=function(e){if(0===e)0===this._state&&(this._state=1,this._firstWaitScheduler.schedule(this._firstWaitTime()),this._loadingMessageScheduler.schedule(this._loadingMessageTime()));else switch(this._state){case 0:this._triggerAsyncComputation(),this._secondWaitScheduler.cancel(),this._triggerSyncComputation();break;case 2:this._secondWaitScheduler.cancel(),this._triggerSyncComputation()}},e.prototype.cancel=function(){this._loadingMessageScheduler.cancel(),1===this._state&&this._firstWaitScheduler.cancel(),2===this._state&&(this._secondWaitScheduler.cancel(),this._asyncComputationPromise&&(this._asyncComputationPromise.cancel(),this._asyncComputationPromise=null)),3===this._state&&this._asyncComputationPromise&&(this._asyncComputationPromise.cancel(),this._asyncComputationPromise=null),this._state=0},e}(),V=n("qecS"),H=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),z=function(e){function t(t,n){var i=e.call(this)||this;return i.allowEditorOverflow=!0,i._id=t,i._editor=n,i._isVisible=!1,i._stoleFocus=!1,i._containerDomNode=document.createElement("div"),i._containerDomNode.className="monaco-editor-hover hidden",i._containerDomNode.tabIndex=0,i._domNode=document.createElement("div"),i._domNode.className="monaco-editor-hover-content",i.scrollbar=new V.a(i._domNode,{}),i._register(i.scrollbar),i._containerDomNode.appendChild(i.scrollbar.getDomNode()),i.onkeydown(i._containerDomNode,function(e){e.equals(9)&&i.hide()}),i._register(i._editor.onDidChangeConfiguration(function(e){e.fontInfo&&i.updateFont()})),i._editor.onDidLayoutChange(function(e){return i.layout()}),i.layout(),i._editor.addContentWidget(i),i._showAtPosition=null,i._showAtRange=null,i._stoleFocus=!1,i}return H(t,e),Object.defineProperty(t.prototype,"isVisible",{get:function(){return this._isVisible},set:function(e){this._isVisible=e,Object(d.R)(this._containerDomNode,"hidden",!this._isVisible)},enumerable:!0,configurable:!0}),t.prototype.getId=function(){return this._id},t.prototype.getDomNode=function(){return this._containerDomNode},t.prototype.showAt=function(e,t,n){this._showAtPosition=e,this._showAtRange=t,this.isVisible=!0,this._editor.layoutContentWidget(this),this._editor.render(),this._stoleFocus=n,n&&this._containerDomNode.focus()},t.prototype.hide=function(){this.isVisible&&(this.isVisible=!1,this._editor.layoutContentWidget(this),this._stoleFocus&&this._editor.focus())},t.prototype.getPosition=function(){return this.isVisible?{position:this._showAtPosition,range:this._showAtRange,preference:[1,2]}:null},t.prototype.dispose=function(){this._editor.removeContentWidget(this),e.prototype.dispose.call(this)},t.prototype.updateFont=function(){var e=this;Array.prototype.slice.call(this._domNode.getElementsByClassName("code")).forEach(function(t){return e._editor.applyFontInfo(t)})},t.prototype.updateContents=function(e){this._domNode.textContent="",this._domNode.appendChild(e),this.updateFont(),this._editor.layoutContentWidget(this),this.onContentsChange()},t.prototype.onContentsChange=function(){this.scrollbar.scanDomNode()},t.prototype.layout=function(){var e=Math.max(this._editor.getLayoutInfo().height/4,250),t=this._editor.getConfiguration().fontInfo,n=t.fontSize,i=t.lineHeight;this._domNode.style.fontSize=n+"px",this._domNode.style.lineHeight=i+"px",this._domNode.style.maxHeight=e+"px",this._domNode.style.maxWidth=Math.max(.66*this._editor.getLayoutInfo().width,500)+"px"},t}(x.a),U=function(e){function t(t,n){var i=e.call(this)||this;return i._id=t,i._editor=n,i._isVisible=!1,i._domNode=document.createElement("div"),i._domNode.className="monaco-editor-hover hidden",i._domNode.setAttribute("aria-hidden","true"),i._domNode.setAttribute("role","presentation"),i._showAtLineNumber=-1,i._register(i._editor.onDidChangeConfiguration(function(e){e.fontInfo&&i.updateFont()})),i._editor.addOverlayWidget(i),i}return H(t,e),Object.defineProperty(t.prototype,"isVisible",{get:function(){return this._isVisible},set:function(e){this._isVisible=e,Object(d.R)(this._domNode,"hidden",!this._isVisible)},enumerable:!0,configurable:!0}),t.prototype.getId=function(){return this._id},t.prototype.getDomNode=function(){return this._domNode},t.prototype.showAt=function(e){this._showAtLineNumber=e,this.isVisible||(this.isVisible=!0);var t=this._editor.getLayoutInfo(),n=this._editor.getTopForLineNumber(this._showAtLineNumber),i=this._editor.getScrollTop(),r=this._editor.getConfiguration().lineHeight,o=n-i-(this._domNode.clientHeight-r)/2;this._domNode.style.left=t.glyphMarginLeft+t.glyphMarginWidth+"px",this._domNode.style.top=Math.max(Math.round(o),0)+"px"},t.prototype.hide=function(){this.isVisible&&(this.isVisible=!1)},t.prototype.getPosition=function(){return null},t.prototype.dispose=function(){this._editor.removeOverlayWidget(this),e.prototype.dispose.call(this)},t.prototype.updateFont=function(){var e=this,t=Array.prototype.slice.call(this._domNode.getElementsByTagName("code")),n=Array.prototype.slice.call(this._domNode.getElementsByClassName("code"));t.concat(n).forEach(function(t){return e._editor.applyFontInfo(t)})},t.prototype.updateContents=function(e){this._domNode.textContent="",this._domNode.appendChild(e),this.updateFont()},t}(x.a),K=n("VBCr"),q=n("OHx0"),G=n("ZYUE"),Z=n("GsV8"),Y=n("MOjS"),X=n("OBuU"),$=n("0Td8"),J=n("mhQ0"),Q=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),ee=d.a,te=function(){return function(e,t,n){this.range=e,this.color=t,this.provider=n}}(),ne=function(){return function(e,t){this.range=e,this.marker=t}}(),ie=function(){function e(e,t){this._markerDecorationsService=t,this._editor=e,this._result=[]}return e.prototype.setRange=function(e){this._range=e,this._result=[]},e.prototype.clearResult=function(){this._result=[]},e.prototype.computeAsync=function(e){if(!this._editor.hasModel()||!this._range)return Promise.resolve([]);var t=this._editor.getModel();return v.n.has(t)?j(t,new g.a(this._range.startLineNumber,this._range.startColumn),e):Promise.resolve([])},e.prototype.computeSync=function(){var e=this;if(!this._editor.hasModel()||!this._range)return[];var t=this._editor.getModel(),n=this._range.startLineNumber;if(n>this._editor.getModel().getLineCount())return[];var i=b.ColorDetector.get(this._editor),r=t.getLineMaxColumn(n),o=this._editor.getLineDecorations(n),s=!1,a=this._range,c=o.map(function(o){var c=o.range.startLineNumber===n?o.range.startColumn:1,l=o.range.endLineNumber===n?o.range.endColumn:r;if(c>a.startColumn||a.endColumn>l)return null;var d=new u.a(a.startLineNumber,c,a.startLineNumber,l),h=e._markerDecorationsService.getMarker(t,o);if(h)return new ne(d,h);var f=i.getColorData(o.range.getStartPosition());if(!s&&f){s=!0;var g=f.colorInfo,m=g.color,v=g.range;return new te(v,m,f.provider)}return Object(p.b)(o.options.hoverMessage)?null:{contents:o.options.hoverMessage?Object(R.b)(o.options.hoverMessage):[],range:d}});return Object(R.d)(c)},e.prototype.onResult=function(e,t){this._result=t?e.concat(this._result.sort(function(e,t){return e instanceof te?-1:t instanceof te?1:0})):this._result.concat(e)},e.prototype.getResult=function(){return this._result.slice(0)},e.prototype.getResultWithLoadingMessage=function(){return this._result.slice(0).concat([this._getLoadingMessage()])},e.prototype._getLoadingMessage=function(){return{range:this._range,contents:[(new p.a).appendText(r.a("modesContentHover.loading","Loading..."))]}},e}(),re=function(e){function t(n,i,r,o,a,u){void 0===u&&(u=Z.b);var c=e.call(this,t.ID,n)||this;return c._themeService=r,c._keybindingService=o,c._modeService=a,c._openerService=u,c.renderDisposable=c._register(new s.d),c._messages=[],c._lastRange=null,c._computer=new ie(c._editor,i),c._highlightDecorations=[],c._isChangingDecorations=!1,c._shouldFocus=!1,c._colorPicker=null,c._hoverOperation=new B(c._computer,function(e){return c._withResult(e,!0)},null,function(e){return c._withResult(e,!1)},c._editor.getConfiguration().contribInfo.hover.delay),c._register(d.k(c.getDomNode(),d.d.FOCUS,function(){c._colorPicker&&d.f(c.getDomNode(),"colorpicker-hover")})),c._register(d.k(c.getDomNode(),d.d.BLUR,function(){d.I(c.getDomNode(),"colorpicker-hover")})),c._register(n.onDidChangeConfiguration(function(e){c._hoverOperation.setHoverTime(c._editor.getConfiguration().contribInfo.hover.delay)})),c}return Q(t,e),t.prototype.dispose=function(){this._hoverOperation.cancel(),e.prototype.dispose.call(this)},t.prototype.onModelDecorationsChanged=function(){this._isChangingDecorations||this.isVisible&&(this._hoverOperation.cancel(),this._computer.clearResult(),this._colorPicker||this._hoverOperation.start(0))},t.prototype.startShowingAt=function(e,t,n){if(!this._lastRange||!this._lastRange.equalsRange(e)){if(this._hoverOperation.cancel(),this.isVisible)if(this._showAtPosition&&this._showAtPosition.lineNumber===e.startLineNumber){for(var i=[],r=0,o=this._messages.length;r=e.endColumn&&i.push(s)}if(i.length>0){if(function(e,t){if(!e&&t||e&&!t||e.length!==t.length)return!1;for(var n=0;n0?this._renderMessages(this._lastRange,this._messages):t&&this.hide()},t.prototype._renderMessages=function(e,n){var i=this;this.renderDisposable.dispose(),this._colorPicker=null;var r=Number.MAX_VALUE,o=n[0].range?u.a.lift(n[0].range):null,a=document.createDocumentFragment(),c=!0,l=!1,m=new s.b,v=[];if(n.forEach(function(e){if(e.range)if(r=Math.min(r,e.range.startColumn),o=o?u.a.plusRange(o,e.range):u.a.lift(e.range),e instanceof te){l=!0;var t=e.color,n=t.red,g=t.green,b=t.blue,y=t.alpha,C=new f.c(255*n,255*g,255*b,y),S=new f.a(C);if(!i._editor.hasModel())return;var x=i._editor.getModel(),L=new u.a(e.range.startLineNumber,e.range.startColumn,e.range.endLineNumber,e.range.endColumn),O={range:e.range,color:e.color},k=new w(S,[],0),N=new A(a,k,i._editor.getConfiguration().pixelRatio,i._themeService);Object(_.a)(x,O,e.provider,h.a.None).then(function(t){if(k.colorPresentations=t||[],i._editor.hasModel()){var n=i._editor.getModel().getValueInRange(e.range);k.guessColorPresentation(S,n);var r=function(){var e,t;k.presentation.textEdit?(e=[k.presentation.textEdit],t=(t=new u.a(k.presentation.textEdit.range.startLineNumber,k.presentation.textEdit.range.startColumn,k.presentation.textEdit.range.endLineNumber,k.presentation.textEdit.range.endColumn)).setEndPosition(t.endLineNumber,t.startColumn+k.presentation.textEdit.text.length)):(e=[{identifier:null,range:L,text:k.presentation.label,forceMoveMarkers:!1}],t=L.setEndPosition(L.endLineNumber,L.startColumn+k.presentation.label.length)),i._editor.pushUndoStop(),i._editor.executeEdits("colorpicker",e),k.presentation.additionalTextEdits&&(e=k.presentation.additionalTextEdits.slice(),i._editor.executeEdits("colorpicker",e),i.hide()),i._editor.pushUndoStop(),L=t},o=function(t){return Object(_.a)(x,{range:L,color:{red:t.rgba.r/255,green:t.rgba.g/255,blue:t.rgba.b/255,alpha:t.rgba.a}},e.provider,h.a.None).then(function(e){k.colorPresentations=e||[]})},c=k.onColorFlushed(function(e){o(e).then(r)}),l=k.onDidChangeColor(o);i._colorPicker=N,i.showAt(L.getStartPosition(),L,i._shouldFocus),i.updateContents(a),i._colorPicker.layout(),i.renderDisposable.value=Object(s.e)(c,l,N,m)}})}else e instanceof ne?(v.push(e),c=!1):e.contents.filter(function(e){return!Object(p.b)(e)}).forEach(function(e){var t=ee("div.hover-row.markdown-hover"),n=d.m(t,ee("div.hover-contents")),r=m.add(new K.a(i._editor,i._modeService,i._openerService));m.add(r.onDidRenderCodeBlock(function(){n.className="hover-contents code-hover-contents",i.onContentsChange()}));var o=m.add(r.render(e));n.appendChild(o.element),a.appendChild(t),c=!1})}),v.length){v.forEach(function(e){return a.appendChild(i.renderMarkerHover(e))});var b=1===v.length?v[0]:v.sort(function(e,t){return q.c.compare(e.marker.severity,t.marker.severity)})[0];a.appendChild(this.renderMarkerStatusbar(b))}l||c||(this.showAt(new g.a(e.startLineNumber,r),o,this._shouldFocus),this.updateContents(a)),this._isChangingDecorations=!0,this._highlightDecorations=this._editor.deltaDecorations(this._highlightDecorations,o?[{range:o,options:t._DECORATION_OPTIONS}]:[]),this._isChangingDecorations=!1},t.prototype.renderMarkerHover=function(e){var t=this,n=ee("div.hover-row"),i=d.m(n,ee("div.marker.hover-contents")),r=e.marker,o=r.source,s=r.message,a=r.code,u=r.relatedInformation;this._editor.applyFontInfo(i);var c=d.m(i,ee("span"));if(c.style.whiteSpace="pre-wrap",c.innerText=s,o||a){var l=d.m(i,ee("span"));l.style.opacity="0.6",l.style.paddingLeft="6px",l.innerText=o&&a?o+"("+a+")":o||"("+a+")"}if(Object(R.n)(u))for(var h=function(e,n,r,o){var s=d.m(i,ee("div"));s.style.marginTop="8px";var a=d.m(s,ee("a"));a.innerText=Object(G.b)(n)+"("+r+", "+o+"): ",a.style.cursor="pointer",a.onclick=function(e){e.stopPropagation(),e.preventDefault(),t._openerService&&t._openerService.open(n.with({fragment:r+","+o})).catch(F.e)};var u=d.m(s,ee("span"));u.innerText=e,f._editor.applyFontInfo(u)},f=this,p=0,g=u;p0?this._renderMessages(this._lastLineNumber,this._messages):this.hide()},t.prototype._renderMessages=function(e,t){this._renderDisposeables.clear();for(var n=document.createDocumentFragment(),i=0,r=t;i=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},he=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},fe=function(){function e(e,t,n,i,r,o){var a=this;this._editor=e,this._openerService=t,this._modeService=n,this._markerDecorationsService=i,this._keybindingService=r,this._themeService=o,this._toUnhook=new s.b,this._isMouseDown=!1,this._hoverClicked=!1,this._contentWidget=null,this._glyphWidget=null,this._hookEvents(),this._didChangeConfigurationHandler=this._editor.onDidChangeConfiguration(function(e){e.contribInfo&&(a._hideWidgets(),a._unhookEvents(),a._hookEvents())})}return Object.defineProperty(e.prototype,"contentWidget",{get:function(){return this._contentWidget||this._createHoverWidgets(),this._contentWidget},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"glyphWidget",{get:function(){return this._glyphWidget||this._createHoverWidgets(),this._glyphWidget},enumerable:!0,configurable:!0}),e.get=function(t){return t.getContribution(e.ID)},e.prototype._hookEvents=function(){var e=this,t=function(){return e._hideWidgets()},n=this._editor.getConfiguration().contribInfo.hover;this._isHoverEnabled=n.enabled,this._isHoverSticky=n.sticky,this._isHoverEnabled?(this._toUnhook.add(this._editor.onMouseDown(function(t){return e._onEditorMouseDown(t)})),this._toUnhook.add(this._editor.onMouseUp(function(t){return e._onEditorMouseUp(t)})),this._toUnhook.add(this._editor.onMouseMove(function(t){return e._onEditorMouseMove(t)})),this._toUnhook.add(this._editor.onKeyDown(function(t){return e._onKeyDown(t)})),this._toUnhook.add(this._editor.onDidChangeModelDecorations(function(){return e._onModelDecorationsChanged()}))):this._toUnhook.add(this._editor.onMouseMove(t)),this._toUnhook.add(this._editor.onMouseLeave(t)),this._toUnhook.add(this._editor.onDidChangeModel(t)),this._toUnhook.add(this._editor.onDidScrollChange(function(t){return e._onEditorScrollChanged(t)}))},e.prototype._unhookEvents=function(){this._toUnhook.clear()},e.prototype._onModelDecorationsChanged=function(){this.contentWidget.onModelDecorationsChanged(),this.glyphWidget.onModelDecorationsChanged()},e.prototype._onEditorScrollChanged=function(e){(e.scrollTopChanged||e.scrollLeftChanged)&&this._hideWidgets()},e.prototype._onEditorMouseDown=function(e){this._isMouseDown=!0;var t=e.target.type;9!==t||e.target.detail!==re.ID?12===t&&e.target.detail===ae.ID||(12!==t&&e.target.detail!==ae.ID&&(this._hoverClicked=!1),this._hideWidgets()):this._hoverClicked=!0},e.prototype._onEditorMouseUp=function(e){this._isMouseDown=!1},e.prototype._onEditorMouseMove=function(e){var t=e.target.type;if(!(this._isMouseDown&&this._hoverClicked&&this.contentWidget.isColorPickerVisible()||this._isHoverSticky&&9===t&&e.target.detail===re.ID||this._isHoverSticky&&12===t&&e.target.detail===ae.ID)){if(7===t){var n=this._editor.getConfiguration().fontInfo.typicalHalfwidthCharacterWidth/2,i=e.target.detail;i&&!i.isAfterLines&&"number"==typeof i.horizontalDistanceToText&&i.horizontalDistanceToText=12&&t<=16)return!1}return!0};var i=n("Kp7x"),r=function(){function e(){this._zoomLevel=0,this._lastZoomLevelChangeTime=0,this._onDidChangeZoomLevel=new i.a,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event}return e.prototype.getZoomLevel=function(){return this._zoomLevel},e.prototype.getTimeSinceLastZoomLevelChanged=function(){return Date.now()-this._lastZoomLevelChangeTime},e.prototype.getPixelRatio=function(){var e=document.createElement("canvas").getContext("2d");return(window.devicePixelRatio||1)/(e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1)},e.INSTANCE=new e,e}();var o=navigator.userAgent,s=o.indexOf("Trident")>=0,a=o.indexOf("Edge/")>=0,u=s||a,c=o.indexOf("Firefox")>=0,l=o.indexOf("AppleWebKit")>=0,d=o.indexOf("Chrome")>=0,h=!d&&o.indexOf("Safari")>=0,f=!d&&!h&&l,p=o.indexOf("iPad")>=0,g=a&&o.indexOf("WebView/")>=0},lQBd:function(e,t,n){"use strict";var i=n("KDHK"),r=i.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),o=i.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),s=i.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())}),a=i.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())}),u=i.define("RelativeDistinguishedName",function(){this.setof(o)}),c=i.define("RDNSequence",function(){this.seqof(u)}),l=i.define("Name",function(){this.choice({rdnSequence:this.use(c)})}),d=i.define("Validity",function(){this.seq().obj(this.key("notBefore").use(r),this.key("notAfter").use(r))}),h=i.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),f=i.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(s),this.key("issuer").use(l),this.key("validity").use(d),this.key("subject").use(l),this.key("subjectPublicKeyInfo").use(a),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(h).optional())}),p=i.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(f),this.key("signatureAlgorithm").use(s),this.key("signatureValue").bitstr())});e.exports=p},lUSU:function(e,t,n){var i=n("H2Pp");t.encrypt=function(e,t){var n=i(t,e._prev);return e._prev=e._cipher.encryptBlock(n),e._prev},t.decrypt=function(e,t){var n=e._prev;e._prev=t;var r=e._cipher.decryptBlock(t);return i(r,n)}},lWLP:function(e,t,n){"use strict";n.d(t,"b",function(){return o}),n.d(t,"a",function(){return s});var i=n("hK2W"),r=function(){function e(e,t,n){void 0===n&&(n=t),this.modifierLabels=[null],this.modifierLabels[2]=e,this.modifierLabels[1]=t,this.modifierLabels[3]=n}return e.prototype.toLabel=function(e,t,n){if(0===t.length)return null;for(var i=[],r=0,o=t.length;r1)if(r.a.visibleColumnFromColumn(_,b+1,d)%h!=0&&t.isCheapToTokenize(v-1)){var y=a.a.getRawEnterActionAtPosition(t,v-1,t.getLineMaxColumn(v-1));if(y){if(m=g,y.appendText)for(var w=0,C=y.appendText.length;wp+(n.clockTolerance||0))return f(new r("jwt not active",new Date(1e3*b.nbf)))}if(void 0!==b.exp&&!n.ignoreExpiration){if("number"!=typeof b.exp)return f(new i("invalid exp value"));if(p>=b.exp+(n.clockTolerance||0))return f(new o("jwt expired",new Date(1e3*b.exp)))}if(n.audience){var y=Array.isArray(n.audience)?n.audience:[n.audience];if(!(Array.isArray(b.aud)?b.aud:[b.aud]).some(function(e){return y.some(function(t){return t instanceof RegExp?t.test(e):t===e})}))return f(new i("jwt audience invalid. expected: "+y.join(" or ")))}if(n.issuer&&("string"==typeof n.issuer&&b.iss!==n.issuer||Array.isArray(n.issuer)&&-1===n.issuer.indexOf(b.iss)))return f(new i("jwt issuer invalid. expected: "+n.issuer));if(n.subject&&b.sub!==n.subject)return f(new i("jwt subject invalid. expected: "+n.subject));if(n.jwtid&&b.jti!==n.jwtid)return f(new i("jwt jwtid invalid. expected: "+n.jwtid));if(n.nonce&&b.nonce!==n.nonce)return f(new i("jwt nonce invalid. expected: "+n.nonce));if(n.maxAge){if("number"!=typeof b.iat)return f(new i("iat required when maxAge is specified"));var w=a(n.maxAge,b.iat);if(void 0===w)return f(new i('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(p>=w+(n.clockTolerance||0))return f(new o("maxAge exceeded",new Date(1e3*w)))}if(!0===n.complete){var C=g.signature;return f(null,{header:_,payload:b,signature:C})}return f(null,b)})}},mcra:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("hK2W"),o=n("03Zz"),s=n("/9db"),a=n("vTy2"),u=function(){function e(e,t){this._selection=e,this._isMovingLeft=t,this._cutStartIndex=-1,this._cutEndIndex=-1,this._moved=!1,this._selectionId=null}return e.prototype.getEditOperations=function(e,t){var n=this._selection;if(this._selectionId=t.trackSelection(n),n.startLineNumber===n.endLineNumber&&(!this._isMovingLeft||0!==n.startColumn)&&(this._isMovingLeft||n.endColumn!==e.getLineMaxColumn(n.startLineNumber))){var i,r,o,s=n.selectionStartLineNumber,u=e.getLineContent(s);this._isMovingLeft?(i=u.substring(0,n.startColumn-2),r=u.substring(n.startColumn-1,n.endColumn-1),o=u.substring(n.startColumn-2,n.startColumn-1)+u.substring(n.endColumn-1)):(i=u.substring(0,n.startColumn-1)+u.substring(n.endColumn-1,n.endColumn),r=u.substring(n.startColumn-1,n.endColumn-1),o=u.substring(n.endColumn));var c=i+r+o;t.addEditOperation(new a.a(s,1,s,e.getLineMaxColumn(s)),null),t.addEditOperation(new a.a(s,1,s,1),c),this._cutStartIndex=n.startColumn+(this._isMovingLeft?-1:1),this._cutEndIndex=this._cutStartIndex+n.endColumn-n.startColumn,this._moved=!0}},e.prototype.computeCursorState=function(e,t){var n=t.getTrackedSelection(this._selectionId);return this._moved&&(n=(n=n.setStartPosition(n.startLineNumber,this._cutStartIndex)).setEndPosition(n.startLineNumber,this._cutEndIndex)),n},e}(),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),l=function(e){function t(t,n){var i=e.call(this,n)||this;return i.left=t,i}return c(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=[],i=0,r=t.getSelections();i=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||45===o||46===o||95===o||126===o||t&&47===o)-1!==i&&(n+=encodeURIComponent(e.substring(i,r)),i=-1),void 0!==n&&(n+=e.charAt(r));else{void 0===n&&(n=e.substr(0,r));var s=v[o];void 0!==s?(-1!==i&&(n+=encodeURIComponent(e.substring(i,r)),i=-1),n+=s):-1===i&&(i=r)}}return-1!==i&&(n+=encodeURIComponent(e.substring(i))),void 0!==n?n:e}function b(e){for(var t=void 0,n=0;n1&&"file"===e.scheme?"//"+e.authority+e.path:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?e.path[1].toLowerCase()+e.path.substr(2):e.path,o.g&&(t=t.replace(/\//g,"\\")),t}function w(e,t){var n=t?b:_,i="",r=e.scheme,o=e.authority,s=e.path,a=e.query,u=e.fragment;if(r&&(i+=r,i+=":"),(o||"file"===r)&&(i+=h,i+=h),o){var c=o.indexOf("@");if(-1!==c){var l=o.substr(0,c);o=o.substr(c+1),-1===(c=l.indexOf(":"))?i+=n(l,!1):(i+=n(l.substr(0,c),!1),i+=":",i+=n(l.substr(c+1),!1)),i+="@"}-1===(c=(o=o.toLowerCase()).indexOf(":"))?i+=n(o,!1):(i+=n(o.substr(0,c),!1),i+=o.substr(c))}if(s){if(s.length>=3&&47===s.charCodeAt(0)&&58===s.charCodeAt(2))(d=s.charCodeAt(1))>=65&&d<=90&&(s="/"+String.fromCharCode(d+32)+":"+s.substr(3));else if(s.length>=2&&58===s.charCodeAt(1)){var d;(d=s.charCodeAt(0))>=65&&d<=90&&(s=String.fromCharCode(d+32)+":"+s.substr(2))}i+=n(s,!0)}return a&&(i+="?",i+=n(a,!1)),u&&(i+="#",i+=t?u:_(u,!1)),i}},mtgd:function(e,t,n){"use strict";var i=n("TU7t"),r=n("aL7J");function o(e){return Object(r.o)(e)}n.d(t,"a",function(){return s});var s=function(){function e(e,t){this.supportOcticons=t,this.domNode=document.createElement("span"),this.domNode.className="monaco-highlighted-label",this.didEverRender=!1,e.appendChild(this.domNode)}return Object.defineProperty(e.prototype,"element",{get:function(){return this.domNode},enumerable:!0,configurable:!0}),e.prototype.set=function(t,n,r,o){void 0===n&&(n=[]),void 0===r&&(r=""),t||(t=""),o&&(t=e.escapeNewLines(t,n)),this.didEverRender&&this.text===t&&this.title===r&&i.e(this.highlights,n)||(Array.isArray(n)||(n=[]),this.text=t,this.title=r,this.highlights=n,this.render())},e.prototype.render=function(){for(var e="",t=0,n=0,i=this.highlights;n";var a=this.text.substring(t,s.start);e+=this.supportOcticons?o(a):Object(r.o)(a),e+="",t=s.end}e+='';var u=this.text.substring(s.start,s.end);e+=this.supportOcticons?o(u):Object(r.o)(u),e+="",t=s.end}}if(t";u=this.text.substring(t);e+=this.supportOcticons?o(u):Object(r.o)(u),e+=""}this.domNode.innerHTML=e,this.domNode.title=this.title,this.didEverRender=!0},e.escapeNewLines=function(e,t){var n=0,i=0;return e.replace(/\r\n|\r|\n/g,function(e,r){i="\r\n"===e?-1:0,r+=n;for(var o=0,s=t;o=r&&(a.start+=i),a.end>=r&&(a.end+=i))}return n+=i,"⏎"})},e}()},nLHh:function(e,t){},nOGB:function(e,t,n){var i=n("EuP9").Buffer;e.exports=function(e){return"string"==typeof e?e:"number"==typeof e||i.isBuffer(e)?e.toString():JSON.stringify(e)}},nY9q:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"defaultReferenceSearchOptions",function(){return E}),n.d(t,"ReferenceController",function(){return I}),n.d(t,"ReferenceAction",function(){return D}),t.provideReferences=P;var i,r=n("hK2W"),o=n("7g0X"),s=n("Kx4b"),a=n("artP"),u=n("03Zz"),c=n("PCC9"),l=n("vTy2"),d=n("fw2Z"),h=n("Pb27"),f=n("9uVW"),p=n("odeJ"),g=n("zxiH"),m=n("/9db"),v=n("IrTV"),_=n("P1SM"),b=n("bhIx"),y=n("ni2T"),w=n("ItKl"),C=n("mrx5"),S=n("vORD"),x=n("80kS"),L=n("X6iQ"),O=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),k=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},N=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},E={getMetaTitle:function(e){return e.references.length>1?r.a("meta.titleReference"," – {0} references",e.references.length):""}},I=function(){function e(e,t){e instanceof v.a&&d.b.inPeekEditor.bindTo(t)}return e.prototype.dispose=function(){},e.prototype.getId=function(){return e.ID},e.ID="editor.contrib.referenceController",e=k([N(1,o.c)],e)}(),D=function(e){function t(){return e.call(this,{id:"editor.action.referenceSearch.trigger",label:r.a("references.action.label","Peek References"),alias:"Peek References",precondition:o.a.and(m.a.hasReferenceProvider,d.b.notInPeekEditor,m.a.isInEmbeddedEditor.toNegated()),kbOpts:{kbExpr:m.a.editorTextFocus,primary:1094,weight:100},menuOpts:{group:"navigation",order:1.5}})||this}return O(t,e),t.prototype.run=function(e,t){var n=h.a.get(t);if(n&&t.hasModel()){var i=t.getSelection(),r=t.getModel(),o=Object(p.f)(function(e){return P(r,i.getStartPosition(),e).then(function(e){return new f.c(e)})});n.toggleWidget(i,o,E)}},t}(u.b);Object(u.h)(I),Object(u.f)(D);function M(e,t){T(e,function(e){return e.closeWidget()})}function T(e,t){var n=Object(d.d)(e);if(n){var i=h.a.get(n);i&&t(i)}}function P(e,t,n){var i=c.s.ordered(e).map(function(i){return Promise.resolve(i.provideReferences(e,t,{includeDeclaration:!0},n)).then(function(e){if(Array.isArray(e))return e},function(e){Object(g.f)(e)})});return Promise.all(i).then(function(e){return Object(L.k)(Object(L.d)(e))})}w.a.registerCommand({id:"editor.action.findReferences",handler:function(e,t,n){if(!(t instanceof C.a))throw new Error("illegal argument, uri");if(!n)throw new Error("illegal argument, position");var i=e.get(S.a);return i.openCodeEditor({resource:t},i.getFocusedCodeEditor()).then(function(e){if(Object(_.a)(e)&&e.hasModel()){var t=h.a.get(e);if(t){var i=Object(p.f)(function(t){return P(e.getModel(),a.a.lift(n),t).then(function(e){return new f.c(e)})}),r=new l.a(n.lineNumber,n.column,n.lineNumber,n.column);return Promise.resolve(t.toggleWidget(r,i,E))}}})}}),w.a.registerCommand({id:"editor.action.showReferences",handler:function(e,t,n,i){if(!(t instanceof C.a))throw new Error("illegal argument, uri expected");if(!i)throw new Error("missing references");var r=e.get(S.a);return r.openCodeEditor({resource:t},r.getFocusedCodeEditor()).then(function(e){if(Object(_.a)(e)){var t=h.a.get(e);if(t)return t.toggleWidget(new l.a(n.lineNumber,n.column,n.lineNumber,n.column),Object(p.f)(function(e){return Promise.resolve(new f.c(i))}),E)}})},description:{description:"Show references at a position in a file",args:[{name:"uri",description:"The text document in which to show references",constraint:C.a},{name:"position",description:"The position at which to show",constraint:a.a.isIPosition},{name:"locations",description:"An array of locations.",constraint:Array}]}}),s.a.registerCommandAndKeybindingRule({id:"goToNextReference",weight:250,primary:62,when:h.b,handler:function(e){T(e,function(e){e.goToNextOrPreviousReference(!0)})}}),s.a.registerCommandAndKeybindingRule({id:"goToNextReferenceFromEmbeddedEditor",weight:150,primary:62,when:d.b.inPeekEditor,handler:function(e){T(e,function(e){e.goToNextOrPreviousReference(!0)})}}),s.a.registerCommandAndKeybindingRule({id:"goToPreviousReference",weight:250,primary:1086,when:h.b,handler:function(e){T(e,function(e){e.goToNextOrPreviousReference(!1)})}}),s.a.registerCommandAndKeybindingRule({id:"goToPreviousReferenceFromEmbeddedEditor",weight:150,primary:1086,when:d.b.inPeekEditor,handler:function(e){T(e,function(e){e.goToNextOrPreviousReference(!1)})}}),s.a.registerCommandAndKeybindingRule({id:"closeReferenceSearch",weight:250,primary:9,secondary:[1033],when:o.a.and(h.b,o.a.not("config.editor.stablePeek")),handler:M}),s.a.registerCommandAndKeybindingRule({id:"closeReferenceSearchEditor",weight:-1,primary:9,secondary:[1033],when:o.a.and(d.b.inPeekEditor,o.a.not("config.editor.stablePeek")),handler:M}),s.a.registerCommandAndKeybindingRule({id:"openReferenceToSide",weight:100,primary:2051,mac:{primary:259},when:o.a.and(h.b,y.c),handler:function(e,t){var n=e.get(b.a),i=n.lastFocusedList&&n.lastFocusedList.getFocus();i instanceof f.b&&T(e,function(e){return e.openReference(i,!0)})}}),Object(u.e)("_executeReferenceProvider",function(e,t){return P(e,t,x.a.None)})},ni2T:function(e,t,n){"use strict";var i,r,o,s=n("7/Cv"),a=n("TNPA"),u=n("Kp7x"),c=n("tqet"),l=n("lapT"),d=n("ZYUE"),h=(n("Bv73"),n("IrTV")),f=n("vTy2"),p=n("0ly5"),g=n("B/Xy"),m=n("9uVW"),v=n("tpa8"),_=(n("0u1n"),n("aL7J")),b=n("TU7t"),y={badgeBackground:a.a.fromHex("#4D4D4D"),badgeForeground:a.a.fromHex("#FFFFFF")},w=function(){function e(e,t){this.count=0,this.options=t||Object.create(null),Object(b.g)(this.options,y,!1),this.badgeBackground=this.options.badgeBackground,this.badgeForeground=this.options.badgeForeground,this.badgeBorder=this.options.badgeBorder,this.element=Object(s.m)(e,Object(s.a)(".monaco-count-badge")),this.countFormat=this.options.countFormat||"{0}",this.titleFormat=this.options.titleFormat||"",this.setCount(this.options.count||0)}return e.prototype.setCount=function(e){this.count=e,this.render()},e.prototype.setTitleFormat=function(e){this.titleFormat=e,this.render()},e.prototype.render=function(){this.element.textContent=Object(_.r)(this.countFormat,this.count),this.element.title=Object(_.r)(this.titleFormat,this.count),this.applyStyles()},e.prototype.style=function(e){this.badgeBackground=e.badgeBackground,this.badgeForeground=e.badgeForeground,this.badgeBorder=e.badgeBorder,this.applyStyles()},e.prototype.applyStyles=function(){if(this.element){var e=this.badgeBackground?this.badgeBackground.toString():null,t=this.badgeForeground?this.badgeForeground.toString():null,n=this.badgeBorder?this.badgeBorder.toString():null;this.element.style.backgroundColor=e,this.element.style.color=t,this.element.style.borderWidth=n?"1px":null,this.element.style.borderStyle=n?"solid":null,this.element.style.borderColor=n}},e}(),C=n("g1W0"),S=n("eoic"),x=n("Yqb6"),L=n("hK2W"),O=n("1sup"),k=n("JVO/"),N=n("NqM+"),E=n("GYOr"),I=n("mtgd"),D=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),M=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},T=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},P=function(){function e(e){this._resolverService=e}return e.prototype.hasChildren=function(e){return e instanceof m.c||e instanceof m.a&&!e.failure},e.prototype.getChildren=function(e){if(e instanceof m.c)return e.groups;if(e instanceof m.a)return e.resolve(this._resolverService).then(function(e){return e.children});throw new Error("bad tree")},e=M([T(0,g.a)],e)}(),A=function(){function e(){}return e.prototype.getHeight=function(){return 23},e.prototype.getTemplateId=function(e){return e instanceof m.a?W.id:V.id},e}(),R=function(){function e(e){this._keybindingService=e}return e.prototype.getKeyboardNavigationLabel=function(e){if(e instanceof m.b){var t=e.parent.preview,n=t&&t.preview(e.range);if(n)return n.value}return Object(d.b)(e.uri)},e.prototype.mightProducePrintableCharacter=function(e){return this._keybindingService.mightProducePrintableCharacter(e)},e=M([T(0,N.a)],e)}(),F=function(){function e(){}return e.prototype.getId=function(e){return e.id},e}(),j=function(e){function t(t,n,i){var r=e.call(this)||this;r._uriLabel=n;var o=document.createElement("div");return s.f(o,"reference-file"),r.file=r._register(new v.a(o,{supportHighlights:!0})),r.badge=new w(s.m(o,s.a(".count"))),r._register(Object(x.a)(r.badge,i)),t.appendChild(o),r}return D(t,e),t.prototype.set=function(e,t){var n=Object(d.d)(e.uri);this.file.setLabel(Object(O.a)(e.uri),this._uriLabel.getUriLabel(n,{relative:!0}),{title:this._uriLabel.getUriLabel(e.uri),matches:t});var i=e.children.length;this.badge.setCount(i),e.failure?this.badge.setTitleFormat(Object(L.a)("referencesFailre","Failed to resolve file.")):i>1?this.badge.setTitleFormat(Object(L.a)("referencesCount","{0} references",i)):this.badge.setTitleFormat(Object(L.a)("referenceCount","{0} reference",i))},t=M([T(1,C.a),T(2,S.c)],t)}(c.a),W=function(){function e(t){this._instantiationService=t,this.templateId=e.id}return e.prototype.renderTemplate=function(e){return this._instantiationService.createInstance(j,e)},e.prototype.renderElement=function(e,t,n){n.set(e.element,Object(E.c)(e.filterData))},e.prototype.disposeTemplate=function(e){e.dispose()},e.id="FileReferencesRenderer",e=M([T(0,k.a)],e)}(),B=function(){function e(e){this.label=new I.a(e,!1)}return e.prototype.set=function(e,t){var n=e.parent.preview,i=n&&n.preview(e.range);if(i){var r=i.value,o=i.highlight;t&&!E.a.isDefault(t)?(s.R(this.label.element,"referenceMatch",!1),this.label.set(r,Object(E.c)(t))):(s.R(this.label.element,"referenceMatch",!0),this.label.set(r,[o]))}else this.label.set(Object(d.b)(e.uri)+":"+(e.range.startLineNumber+1)+":"+(e.range.startColumn+1))},e}(),V=function(){function e(){this.templateId=e.id}return e.prototype.renderTemplate=function(e){return new B(e)},e.prototype.renderElement=function(e,t,n){n.set(e.element,e.filterData)},e.prototype.disposeTemplate=function(){},e.id="OneReferenceRenderer",e}(),H=function(){function e(){}return e.prototype.getAriaLabel=function(e){return e instanceof m.a?e.getAriaMessage():e instanceof m.b?e.getAriaMessage():null},e}(),z=n("7g0X"),U=n("bhIx"),K=n("L5KM"),q=n("fw2Z"),G=(n("C9H4"),n("KIxu")),Z=n("ot3f"),Y=n("X6iQ"),X=n("5tK6"),$=n("Gxst"),J=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Q={separatorBorder:a.a.transparent},ee=function(){function e(e,t,n,i){this.container=e,this.view=t,this.disposable=i,this._cachedVisibleSize=void 0,"number"==typeof n?(this._size=n,this._cachedVisibleSize=void 0,s.f(e,"visible")):(this._size=0,this._cachedVisibleSize=n.cachedVisibleSize)}return Object.defineProperty(e.prototype,"size",{get:function(){return this._size},set:function(e){this._size=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"visible",{get:function(){return void 0===this._cachedVisibleSize},enumerable:!0,configurable:!0}),e.prototype.setVisible=function(e,t){e!==this.visible&&(e?(this.size=Object(Z.a)(this._cachedVisibleSize,this.viewMinimumSize,this.viewMaximumSize),this._cachedVisibleSize=void 0):(this._cachedVisibleSize="number"==typeof t?t:this.size,this.size=0),s.R(this.container,"visible",e),this.view.setVisible&&this.view.setVisible(e))},Object.defineProperty(e.prototype,"minimumSize",{get:function(){return this.visible?this.view.minimumSize:0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"viewMinimumSize",{get:function(){return this.view.minimumSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximumSize",{get:function(){return this.visible?this.view.maximumSize:0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"viewMaximumSize",{get:function(){return this.view.maximumSize},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"priority",{get:function(){return this.view.priority},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"snap",{get:function(){return!!this.view.snap},enumerable:!0,configurable:!0}),e.prototype.layout=function(e){this.view.layout(this.size,e)},e.prototype.dispose=function(){return this.disposable.dispose(),this.view},e}(),te=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return J(t,e),t.prototype.layout=function(t){e.prototype.layout.call(this,t),this.container.style.height=this.size+"px"},t}(ee),ne=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return J(t,e),t.prototype.layout=function(t){e.prototype.layout.call(this,t),this.container.style.width=this.size+"px"},t}(ee);!function(e){e[e.Idle=0]="Idle",e[e.Busy=1]="Busy"}(r||(r={})),function(e){e.Distribute={type:"distribute"},e.Split=function(e){return{type:"split",index:e}},e.Invisible=function(e){return{type:"invisible",cachedVisibleSize:e}}}(o||(o={}));var ie=function(e){function t(t,n){void 0===n&&(n={});var i=e.call(this)||this;return i.size=0,i.contentSize=0,i.proportions=void 0,i.viewItems=[],i.sashItems=[],i.state=r.Idle,i._onDidSashChange=i._register(new u.a),i.onDidSashChange=i._onDidSashChange.event,i._onDidSashReset=i._register(new u.a),i.orientation=G.j(n.orientation)?0:n.orientation,i.inverseAltBehavior=!!n.inverseAltBehavior,i.proportionalLayout=!!G.j(n.proportionalLayout)||!!n.proportionalLayout,i.el=document.createElement("div"),s.f(i.el,"monaco-split-view2"),s.f(i.el,0===i.orientation?"vertical":"horizontal"),t.appendChild(i.el),i.sashContainer=s.m(i.el,s.a(".sash-container")),i.viewContainer=s.m(i.el,s.a(".split-view-container")),i.style(n.styles||Q),n.descriptor&&(i.size=n.descriptor.size,n.descriptor.views.forEach(function(e,t){var n=G.j(e.visible)||e.visible?e.size:{type:"invisible",cachedVisibleSize:e.size},r=e.view;i.doAddView(r,n,t,!0)}),i.contentSize=i.viewItems.reduce(function(e,t){return e+t.size},0),i.saveProportions()),i}return J(t,e),Object.defineProperty(t.prototype,"orthogonalStartSash",{get:function(){return this._orthogonalStartSash},set:function(e){for(var t=0,n=this.sashItems;t0&&(this.proportions=this.viewItems.map(function(t){return t.size/e.contentSize}))},t.prototype.onSashStart=function(e){var t=this,n=e.sash,i=e.start,r=e.alt,o=Object(Y.j)(this.sashItems,function(e){return e.sash===n}),s=Object(c.e)(Object($.a)(document.body,"keydown")(function(e){return a(t.sashDragState.current,e.altKey)}),Object($.a)(document.body,"keyup")(function(){return a(t.sashDragState.current,!1)})),a=function(e,n){var i,r,a=t.viewItems.map(function(e){return e.size}),u=Number.NEGATIVE_INFINITY,c=Number.POSITIVE_INFINITY;(t.inverseAltBehavior&&(n=!n),n)&&(o===t.sashItems.length-1?(u=((y=t.viewItems[o]).minimumSize-y.size)/2,c=(y.maximumSize-y.size)/2):(u=((y=t.viewItems[o+1]).size-y.maximumSize)/2,c=(y.size-y.minimumSize)/2));if(!n){var l=Object(Y.r)(o,-1),d=Object(Y.r)(o+1,t.viewItems.length),h=l.reduce(function(e,n){return e+(t.viewItems[n].minimumSize-a[n])},0),f=l.reduce(function(e,n){return e+(t.viewItems[n].viewMaximumSize-a[n])},0),p=0===d.length?Number.POSITIVE_INFINITY:d.reduce(function(e,n){return e+(a[n]-t.viewItems[n].minimumSize)},0),g=0===d.length?Number.NEGATIVE_INFINITY:d.reduce(function(e,n){return e+(a[n]-t.viewItems[n].viewMaximumSize)},0),m=Math.max(h,g),v=Math.min(p,f),_=t.findFirstSnapIndex(l),b=t.findFirstSnapIndex(d);if("number"==typeof _){var y=t.viewItems[_],w=Math.floor(y.viewMinimumSize/2);i={index:_,limitDelta:y.visible?m-w:m+w,size:y.size}}if("number"==typeof b){y=t.viewItems[b],w=Math.floor(y.viewMinimumSize/2);r={index:b,limitDelta:y.visible?v+w:v-w,size:y.size}}}t.sashDragState={start:e,current:e,index:o,sizes:a,minDelta:u,maxDelta:c,alt:n,snapBefore:i,snapAfter:r,disposable:s}};a(i,r)},t.prototype.onSashChange=function(e){var t=e.current,n=this.sashDragState,i=n.index,r=n.start,o=n.sizes,s=n.alt,a=n.minDelta,u=n.maxDelta,c=n.snapBefore,l=n.snapAfter;this.sashDragState.current=t;var d=t-r,h=this.resize(i,d,o,void 0,void 0,a,u,c,l);if(s){var f=i===this.sashItems.length-1,p=this.viewItems.map(function(e){return e.size}),g=f?i:i+1,m=this.viewItems[g],v=m.size-m.maximumSize,_=m.size-m.minimumSize,b=f?i-1:i+1;this.resize(b,-h,p,void 0,void 0,v,_)}this.distributeEmptySpace(),this.layoutViews()},t.prototype.onSashEnd=function(e){this._onDidSashChange.fire(e),this.sashDragState.disposable.dispose(),this.saveProportions()},t.prototype.onViewChange=function(e,t){var n=this.viewItems.indexOf(e);n<0||n>=this.viewItems.length||(t="number"==typeof t?t:e.size,t=Object(Z.a)(t,e.minimumSize,e.maximumSize),this.inverseAltBehavior&&n>0?(this.resize(n-1,Math.floor((e.size-t)/2)),this.distributeEmptySpace(),this.layoutViews()):(e.size=t,this.relayout([n],void 0)))},t.prototype.resizeView=function(e,t){var n=this;if(this.state!==r.Idle)throw new Error("Cant modify splitview");if(this.state=r.Busy,!(e<0||e>=this.viewItems.length)){var i=Object(Y.r)(this.viewItems.length).filter(function(t){return t!==e}),o=i.filter(function(e){return 1===n.viewItems[e].priority}).concat([e]),s=i.filter(function(e){return 2===n.viewItems[e].priority}),a=this.viewItems[e];t=Math.round(t),t=Object(Z.a)(t,a.minimumSize,Math.min(a.maximumSize,this.size)),a.size=t,this.relayout(o,s),this.state=r.Idle}},t.prototype.distributeViewSizes=function(){for(var e=this,t=[],n=0,i=0,r=this.viewItems;i0&&(t.push(u),n+=u.size)}for(var o=Math.floor(n/t.length),s=0,a=t;s=this.viewItems.length?-1:this.viewItems[e].size},t.prototype.doAddView=function(e,t,n,i){var o=this;if(void 0===n&&(n=this.viewItems.length),this.state!==r.Idle)throw new Error("Cant modify splitview");this.state=r.Busy;var a=s.a(".split-view-view");n===this.viewItems.length?this.viewContainer.appendChild(a):this.viewContainer.insertBefore(a,this.viewContainer.children.item(n));var l,d=e.onDidChange(function(e){return o.onViewChange(g,e)}),h=Object(c.h)(function(){return o.viewContainer.removeChild(a)}),f=Object(c.e)(d,h);l="number"==typeof t?t:"split"===t.type?this.getViewSize(t.index)/2:"invisible"===t.type?{cachedVisibleSize:t.cachedVisibleSize}:e.minimumSize;var p,g=0===this.orientation?new te(a,e,l,f):new ne(a,e,l,f);if(this.viewItems.splice(n,0,g),this.viewItems.length>1){var m=0===this.orientation?1:0,v=0===this.orientation?{getHorizontalSashTop:function(e){return o.getSashPosition(e)}}:{getVerticalSashLeft:function(e){return o.getSashPosition(e)}},_=new X.a(this.sashContainer,v,{orientation:m,orthogonalStartSash:this.orthogonalStartSash,orthogonalEndSash:this.orthogonalEndSash}),b=0===this.orientation?function(e){return{sash:_,start:e.startY,current:e.currentY,alt:e.altKey}}:function(e){return{sash:_,start:e.startX,current:e.currentX,alt:e.altKey}},y=u.b.map(_.onDidStart,b)(this.onSashStart,this),w=u.b.map(_.onDidChange,b)(this.onSashChange,this),C=u.b.map(_.onDidEnd,function(){return Object(Y.j)(o.sashItems,function(e){return e.sash===_})})(this.onSashEnd,this),S=_.onDidReset(function(){var e=Object(Y.j)(o.sashItems,function(e){return e.sash===_}),t=Object(Y.r)(e,-1),n=Object(Y.r)(e+1,o.viewItems.length),i=o.findFirstSnapIndex(t),r=o.findFirstSnapIndex(n);("number"!=typeof i||o.viewItems[i].visible)&&("number"!=typeof r||o.viewItems[r].visible)&&o._onDidSashReset.fire(e)}),x=Object(c.e)(y,w,C,S,_),L={sash:_,disposable:x};this.sashItems.splice(n-1,0,L)}a.appendChild(e.element),"number"!=typeof t&&"split"===t.type&&(p=[t.index]),i||this.relayout([n],p),this.state=r.Idle,i||"number"==typeof t||"distribute"!==t.type||this.distributeViewSizes()},t.prototype.relayout=function(e,t){var n=this.viewItems.reduce(function(e,t){return e+t.size},0);this.resize(this.viewItems.length-1,this.size-n,void 0,e,t),this.distributeEmptySpace(),this.layoutViews(),this.saveProportions()},t.prototype.resize=function(e,t,n,i,r,o,s,a,u){var c=this;if(void 0===n&&(n=this.viewItems.map(function(e){return e.size})),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===s&&(s=Number.POSITIVE_INFINITY),e<0||e>=this.viewItems.length)return 0;var l=Object(Y.r)(e,-1),d=Object(Y.r)(e+1,this.viewItems.length);if(r)for(var h=0,f=r;h=a.limitDelta)!==E.visible,E.setVisible(I,a.size)}if(!N&&u){var I;E=this.viewItems[u.index];N=(I=t0||t});t=!1;var i=this.viewItems.map(function(e){return t=e.maximumSize-e.size>0||t}),r=this.viewItems.slice().reverse();t=!1;var o=r.map(function(e){return t=e.size-e.minimumSize>0||t}).reverse();t=!1;var s=r.map(function(e){return t=e.maximumSize-e.size>0||t}).reverse();this.sashItems.forEach(function(t,r){var a=t.sash,u=!(n[r]&&s[r+1]),c=!(i[r]&&o[r+1]);if(u&&c){var l=Object(Y.r)(r,-1),d=Object(Y.r)(r+1,e.viewItems.length),h=e.findFirstSnapIndex(l),f=e.findFirstSnapIndex(d),p="number"==typeof h&&!e.viewItems[h].visible,g="number"==typeof f&&!e.viewItems[f].visible;p&&o[r]?a.state=1:g&&n[r]?a.state=2:a.state=0}else a.state=u&&!c?1:!u&&c?2:3})},t.prototype.getSashPosition=function(e){for(var t=0,n=0;n0)return;if(!s.visible&&s.snap)return i}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.viewItems.forEach(function(e){return e.dispose()}),this.viewItems=[],this.sashItems.forEach(function(e){return e.disposable.dispose()}),this.sashItems=[]},t}(c.a);n.d(t,"a",function(){return le}),n.d(t,"c",function(){return de}),n.d(t,"b",function(){return he}),n.d(t,"d",function(){return pe}),n.d(t,"e",function(){return ge});var re=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),oe=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},se=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ae=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},ue=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0?e.children[0]:void 0},t.prototype._revealReference=function(e,t){return ae(this,void 0,void 0,function(){var n,i,r,o,s;return ue(this,function(a){switch(a.label){case 0:return this._revealedReference===e?[2]:(this._revealedReference=e,e.uri.scheme!==l.b.inMemory?this.setTitle(Object(d.c)(e.uri),this._uriLabel.getUriLabel(Object(d.d)(e.uri))):this.setTitle(L.a("peekView.alternateTitle","References")),n=this._textModelResolverService.createModelReference(e.uri),this._tree.getInput()!==e.parent?[3,1]:(this._tree.reveal(e),[3,3]));case 1:return t&&this._tree.reveal(e.parent),[4,this._tree.expand(e.parent)];case 2:a.sent(),this._tree.reveal(e),a.label=3;case 3:return[4,n];case 4:return i=a.sent(),this._model?(Object(c.f)(this._previewModelReference),(r=i.object)?(o=this._preview.getModel()===r.textEditorModel?0:1,s=f.a.lift(e.range).collapseToStart(),this._previewModelReference=i,this._preview.setModel(r.textEditorModel),this._preview.setSelection(s),this._preview.revealRangeInCenter(s,o)):(this._preview.setModel(this._previewNotAvailableMessage),i.dispose()),[2]):(i.dispose(),[2])}})})},t=oe([se(3,S.c),se(4,g.a),se(5,k.a),se(6,q.a),se(7,C.a)],t)}(q.c),fe=Object(K._36)("peekViewTitle.background",{dark:"#1E1E1E",light:"#FFFFFF",hc:"#0C141F"},L.a("peekViewTitleBackground","Background color of the peek view title area.")),pe=Object(K._36)("peekViewTitleLabel.foreground",{dark:"#FFFFFF",light:"#333333",hc:"#FFFFFF"},L.a("peekViewTitleForeground","Color of the peek view title.")),ge=Object(K._36)("peekViewTitleDescription.foreground",{dark:"#ccccccb3",light:"#6c6c6cb3",hc:"#FFFFFF99"},L.a("peekViewTitleInfoForeground","Color of the peek view title info.")),me=Object(K._36)("peekView.border",{dark:"#007acc",light:"#007acc",hc:K.e},L.a("peekViewBorder","Color of the peek view borders and arrow.")),ve=Object(K._36)("peekViewResult.background",{dark:"#252526",light:"#F3F3F3",hc:a.a.black},L.a("peekViewResultsBackground","Background color of the peek view result list.")),_e=Object(K._36)("peekViewResult.lineForeground",{dark:"#bbbbbb",light:"#646465",hc:a.a.white},L.a("peekViewResultsMatchForeground","Foreground color for line nodes in the peek view result list.")),be=Object(K._36)("peekViewResult.fileForeground",{dark:a.a.white,light:"#1E1E1E",hc:a.a.white},L.a("peekViewResultsFileForeground","Foreground color for file nodes in the peek view result list.")),ye=Object(K._36)("peekViewResult.selectionBackground",{dark:"#3399ff33",light:"#3399ff33",hc:null},L.a("peekViewResultsSelectionBackground","Background color of the selected entry in the peek view result list.")),we=Object(K._36)("peekViewResult.selectionForeground",{dark:a.a.white,light:"#6C6C6C",hc:a.a.white},L.a("peekViewResultsSelectionForeground","Foreground color of the selected entry in the peek view result list.")),Ce=Object(K._36)("peekViewEditor.background",{dark:"#001F33",light:"#F2F8FC",hc:a.a.black},L.a("peekViewEditorBackground","Background color of the peek view editor.")),Se=Object(K._36)("peekViewEditorGutter.background",{dark:Ce,light:Ce,hc:Ce},L.a("peekViewEditorGutterBackground","Background color of the gutter in the peek view editor.")),xe=Object(K._36)("peekViewResult.matchHighlightBackground",{dark:"#ea5c004d",light:"#ea5c004d",hc:null},L.a("peekViewResultsMatchHighlight","Match highlight color in the peek view result list.")),Le=Object(K._36)("peekViewEditor.matchHighlightBackground",{dark:"#ff8f0099",light:"#f5d802de",hc:null},L.a("peekViewEditorMatchHighlight","Match highlight color in the peek view editor.")),Oe=Object(K._36)("peekViewEditor.matchHighlightBorder",{dark:null,light:null,hc:K.b},L.a("peekViewEditorMatchHighlightBorder","Match highlight border in the peek view editor."));Object(S.f)(function(e,t){var n=e.getColor(xe);n&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { background-color: "+n+"; }");var i=e.getColor(Le);i&&t.addRule(".monaco-editor .reference-zone-widget .preview .reference-decoration { background-color: "+i+"; }");var r=e.getColor(Oe);r&&t.addRule(".monaco-editor .reference-zone-widget .preview .reference-decoration { border: 2px solid "+r+"; box-sizing: border-box; }");var o=e.getColor(K.b);o&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { border: 1px dotted "+o+"; box-sizing: border-box; }");var s=e.getColor(ve);s&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree { background-color: "+s+"; }");var a=e.getColor(_e);a&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree { color: "+a+"; }");var u=e.getColor(be);u&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree .reference-file { color: "+u+"; }");var c=e.getColor(ye);c&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { background-color: "+c+"; }");var l=e.getColor(we);l&&t.addRule(".monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { color: "+l+" !important; }");var d=e.getColor(Ce);d&&t.addRule(".monaco-editor .reference-zone-widget .preview .monaco-editor .monaco-editor-background,.monaco-editor .reference-zone-widget .preview .monaco-editor .inputarea.ime-input {\tbackground-color: "+d+";}");var h=e.getColor(Se);h&&t.addRule(".monaco-editor .reference-zone-widget .preview .monaco-editor .margin {\tbackground-color: "+h+";}")})},nyV4:function(e,t,n){"use strict";var i=n("08Lv"),r=n("LC74"),o={};t.instantiate=function(e){function t(t){e.call(this,t),this._cbcInit()}r(t,e);for(var n=Object.keys(o),i=0;i=r)return Promise.resolve(n);var s=e[i++],a=Promise.resolve(s());return a.then(function(e){return t(e)?Promise.resolve(e):o()})};return o()},n.d(t,"e",function(){return c}),n.d(t,"c",function(){return l}),n.d(t,"d",function(){return d}),n.d(t,"k",function(){return u}),n.d(t,"b",function(){return h});var i=n("80kS"),r=n("zxiH"),o=n("tqet");function s(e){var t=new i.b,n=e(t.token),o=new Promise(function(e,i){t.token.onCancellationRequested(function(){i(r.a())}),Promise.resolve(n).then(function(n){t.dispose(),e(n)},function(e){t.dispose(),i(e)})});return new(function(){function e(){}return e.prototype.cancel=function(){t.cancel()},e.prototype.then=function(e,t){return o.then(e,t)},e.prototype.catch=function(e){return this.then(void 0,e)},e.prototype.finally=function(e){return o.finally(e)},e}())}var a=function(){function e(e){this.defaultDelay=e,this.timeout=null,this.completionPromise=null,this.doResolve=null,this.task=null}return e.prototype.trigger=function(e,t){var n=this;return void 0===t&&(t=this.defaultDelay),this.task=e,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise(function(e,t){n.doResolve=e,n.doReject=t}).then(function(){n.completionPromise=null,n.doResolve=null;var e=n.task;return n.task=null,e()})),this.timeout=setTimeout(function(){n.timeout=null,n.doResolve(null)},t),this.completionPromise},e.prototype.isTriggered=function(){return null!==this.timeout},e.prototype.cancel=function(){this.cancelTimeout(),this.completionPromise&&(this.doReject(r.a()),this.completionPromise=null)},e.prototype.cancelTimeout=function(){null!==this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},e.prototype.dispose=function(){this.cancelTimeout()},e}();var u,c=function(){function e(e,t){this._token=-1,"function"==typeof e&&"number"==typeof t&&this.setIfNotSet(e,t)}return e.prototype.dispose=function(){this.cancel()},e.prototype.cancel=function(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)},e.prototype.cancelAndSet=function(e,t){var n=this;this.cancel(),this._token=setTimeout(function(){n._token=-1,e()},t)},e.prototype.setIfNotSet=function(e,t){var n=this;-1===this._token&&(this._token=setTimeout(function(){n._token=-1,e()},t))},e}(),l=function(){function e(){this._token=-1}return e.prototype.dispose=function(){this.cancel()},e.prototype.cancel=function(){-1!==this._token&&(clearInterval(this._token),this._token=-1)},e.prototype.cancelAndSet=function(e,t){this.cancel(),this._token=setInterval(function(){e()},t)},e}(),d=function(){function e(e,t){this.timeoutToken=-1,this.runner=e,this.timeout=t,this.timeoutHandler=this.onTimeout.bind(this)}return e.prototype.dispose=function(){this.cancel(),this.runner=null},e.prototype.cancel=function(){this.isScheduled()&&(clearTimeout(this.timeoutToken),this.timeoutToken=-1)},e.prototype.schedule=function(e){void 0===e&&(e=this.timeout),this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,e)},e.prototype.isScheduled=function(){return-1!==this.timeoutToken},e.prototype.onTimeout=function(){this.timeoutToken=-1,this.runner&&this.doRun()},e.prototype.doRun=function(){this.runner&&this.runner()},e}();!function(){if("function"!=typeof requestIdleCallback||"function"!=typeof cancelIdleCallback){var e=Object.freeze({didTimeout:!0,timeRemaining:function(){return 15}});u=function(t){var n=setTimeout(function(){return t(e)}),i=!1;return{dispose:function(){i||(i=!0,clearTimeout(n))}}}}else u=function(e,t){var n=requestIdleCallback(e,"number"==typeof t?{timeout:t}:void 0),i=!1;return{dispose:function(){i||(i=!0,cancelIdleCallback(n))}}}}();var h=function(){function e(e){var t=this;this._didRun=!1,this._executor=function(){try{t._value=e()}catch(e){t._error=e}finally{t._didRun=!0}},this._handle=u(function(){return t._executor()})}return e.prototype.dispose=function(){this._handle.dispose()},e.prototype.getValue=function(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value},e}()},oqRo:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("xF6g"),r=(n.n(i),n("hK2W")),o=n("odeJ"),s=n("zxiH"),a=n("3uSZ"),u=n("6TMp"),c=n("vTy2"),l=n("PCC9"),d=n("03Zz"),h=n("iLE3"),f=n("tqet"),p=n("B/Xy"),g=n("eoic"),m=n("L5KM"),v=n("4tuZ"),_=n("QfwU"),b=n("qzX+"),y=n("artP"),w=n("KIxu"),C=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},S=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},x=function(){function e(e,t,n){var i=this;this.textModelResolverService=t,this.modeService=n,this.toUnhook=new f.b,this.decorations=[],this.currentWordUnderMouse=null,this.previousPromise=null,this.editor=e;var r=new b.a(e);this.toUnhook.add(r),this.toUnhook.add(r.onMouseMoveOrRelevantKeyDown(function(e){var t=e[0],n=e[1];i.startFindDefinition(t,Object(w.m)(n))})),this.toUnhook.add(r.onExecute(function(e){i.isEnabled(e)&&i.gotoDefinition(e.target,e.hasSideBySideModifier).then(function(){i.removeDecorations()},function(e){i.removeDecorations(),Object(s.e)(e)})})),this.toUnhook.add(r.onCancel(function(){i.removeDecorations(),i.currentWordUnderMouse=null}))}return e.prototype.startFindDefinition=function(e,t){var n=this;if(!(9===e.target.type&&this.decorations.length>0)){if(!this.editor.hasModel()||!this.isEnabled(e,t))return this.currentWordUnderMouse=null,void this.removeDecorations();var i=e.target.position?this.editor.getModel().getWordAtPosition(e.target.position):null;if(!i)return this.currentWordUnderMouse=null,void this.removeDecorations();var u=e.target.position;if(!this.currentWordUnderMouse||this.currentWordUnderMouse.startColumn!==i.startColumn||this.currentWordUnderMouse.endColumn!==i.endColumn||this.currentWordUnderMouse.word!==i.word){this.currentWordUnderMouse=i;var l=new v.a(this.editor,15);this.previousPromise&&(this.previousPromise.cancel(),this.previousPromise=null),this.previousPromise=Object(o.f)(function(t){return n.findDefinition(e.target,t)}),this.previousPromise.then(function(e){if(e&&e.length&&l.validate(n.editor))if(e.length>1)n.addDecoration(new c.a(u.lineNumber,i.startColumn,u.lineNumber,i.endColumn),(new a.a).appendText(r.a("multipleResults","Click to show {0} definitions.",e.length)));else{var t=e[0];if(!t.uri)return;n.textModelResolverService.createModelReference(t.uri).then(function(e){if(e.object&&e.object.textEditorModel){var r=e.object.textEditorModel,o=t.range.startLineNumber;if(o<1||o>r.getLineCount())e.dispose();else{var s,l=n.getPreviewValue(r,o,t);s=t.originSelectionRange?c.a.lift(t.originSelectionRange):new c.a(u.lineNumber,i.startColumn,u.lineNumber,i.endColumn);var d=n.modeService.getModeIdByFilepathOrFirstLine(r.uri);n.addDecoration(s,(new a.a).appendCodeblock(d||"",l)),e.dispose()}}else e.dispose()})}else n.removeDecorations()}).then(void 0,s.e)}}},e.prototype.getPreviewValue=function(t,n,i){var r=i.targetSelectionRange?i.range:this.getPreviewRangeBasedOnBrackets(t,n);return r.endLineNumber-r.startLineNumber>=e.MAX_SOURCE_PREVIEW_LINES&&(r=this.getPreviewRangeBasedOnIndentation(t,n)),this.stripIndentationFromPreviewRange(t,n,r)},e.prototype.stripIndentationFromPreviewRange=function(e,t,n){for(var i=e.getLineFirstNonWhitespaceColumn(t),r=t+1;ri)return new c.a(n,1,i+1,1);s=t.findNextBracket(new y.a(l,d))}return new c.a(n,1,i+1,1)},e.prototype.addDecoration=function(e,t){var n={range:e,options:{inlineClassName:"goto-definition-link",hoverMessage:t}};this.decorations=this.editor.deltaDecorations(this.decorations,[n])},e.prototype.removeDecorations=function(){this.decorations.length>0&&(this.decorations=this.editor.deltaDecorations(this.decorations,[]))},e.prototype.isEnabled=function(e,t){return this.editor.hasModel()&&e.isNoneOrSingleMouseDown&&6===e.target.type&&(e.hasTriggerModifier||!!t&&t.keyCodeIsTriggerKey)&&l.f.has(this.editor.getModel())},e.prototype.findDefinition=function(e,t){var n=this.editor.getModel();return n?Object(h.b)(n,e.position,t):Promise.resolve(null)},e.prototype.gotoDefinition=function(e,t){var n=this;this.editor.setPosition(e.position);var i=new _.DefinitionAction(new _.DefinitionActionConfig(t,!1,!0,!1),{alias:"",label:"",id:"",precondition:void 0});return this.editor.invokeWithinContext(function(e){return i.run(e,n.editor)})},e.prototype.getId=function(){return e.ID},e.prototype.dispose=function(){this.toUnhook.dispose()},e.ID="editor.contrib.gotodefinitionwithmouse",e.MAX_SOURCE_PREVIEW_LINES=8,e=C([S(1,p.a),S(2,u.a)],e)}();Object(d.h)(x),Object(g.f)(function(e,t){var n=e.getColor(m.n);n&&t.addRule(".monaco-editor .goto-definition-link { color: "+n+" !important; }")})},ot3f:function(e,t,n){"use strict";t.a=function(e,t,n){return Math.min(Math.max(e,t),n)}},pJVg:function(e,t){},"pS+P":function(e,t,n){"use strict";var i=n("tRuz"),r=n("geuY"),o=n("LC74"),s=i.base,a=n("lZ6o").utils;function u(e){s.call(this,"mont",e),this.a=new r(e.a,16).toRed(this.red),this.b=new r(e.b,16).toRed(this.red),this.i4=new r(4).toRed(this.red).redInvm(),this.two=new r(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,n){s.BasePoint.call(this,e,"projective"),null===t&&null===n?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new r(t,16),this.z=new r(n,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}o(u,s),e.exports=u,u.prototype.validate=function(e){var t=e.normalize().x,n=t.redSqr(),i=n.redMul(t).redAdd(n.redMul(this.a)).redAdd(t);return 0===i.redSqrt().redSqr().cmp(i)},o(c,s.BasePoint),u.prototype.decodePoint=function(e,t){return this.point(a.toArray(e,t),1)},u.prototype.point=function(e,t){return new c(this,e,t)},u.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),n=e.redSub(t),i=e.redMul(t),r=n.redMul(t.redAdd(this.curve.a24.redMul(n)));return this.curve.point(i,r)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var n=this.x.redAdd(this.z),i=this.x.redSub(this.z),r=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(n),s=r.redMul(i),a=t.z.redMul(o.redAdd(s).redSqr()),u=t.x.redMul(o.redISub(s).redSqr());return this.curve.point(a,u)},c.prototype.mul=function(e){for(var t=e.clone(),n=this,i=this.curve.point(null,null),r=[];0!==t.cmpn(0);t.iushrn(1))r.push(t.andln(1));for(var o=r.length-1;o>=0;o--)0===r[o]?(n=n.diffAdd(i,this),i=i.dbl()):(i=n.diffAdd(i,this),n=n.dbl());return i},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},"pWM+":function(e,t,n){"use strict";t.b=function(e,t){var n=[],i=u.c.ordered(e).reverse().map(function(i){return Promise.resolve(i.provideDocumentColors(e,t)).then(function(e){if(Array.isArray(e))for(var t=0,r=e;t0&&n.ishrn(i),n}function d(e,n,r){var o,s;do{for(o=new t(0);8*o.length=31)return i.error("Multi-octet tag encoding unsupported");t||(r|=32);return r|=a.tagClassByName[n||"universal"]<<6}(e,t,n,this.reporter);if(i.length<128)return(o=new r(2))[0]=s,o[1]=i.length,this._createEncoderBuffer([o,i]);for(var u=1,c=i.length;c>=256;c>>=8)u++;(o=new r(2+u))[0]=s,o[1]=128|u;c=1+u;for(var l=i.length;l>0;c--,l>>=8)o[c]=255&l;return this._createEncoderBuffer([o,i])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){for(var n=new r(2*e.length),i=0;i=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}var o=0;for(i=0;i=128;s>>=7)o++}var a=new r(o),u=a.length-1;for(i=e.length-1;i>=0;i--){s=e[i];for(a[u--]=127&s;(s>>=7)>0;)a[u--]=128|127&s}return this._createEncoderBuffer(a)},c.prototype._encodeTime=function(e,t){var n,i=new Date(e);return"gentime"===t?n=[l(i.getFullYear()),l(i.getUTCMonth()+1),l(i.getUTCDate()),l(i.getUTCHours()),l(i.getUTCMinutes()),l(i.getUTCSeconds()),"Z"].join(""):"utctime"===t?n=[l(i.getFullYear()%100),l(i.getUTCMonth()+1),l(i.getUTCDate()),l(i.getUTCHours()),l(i.getUTCMinutes()),l(i.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(n,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!r.isBuffer(e)){var n=e.toArray();!e.sign&&128&n[0]&&n.unshift(0),e=new r(n)}if(r.isBuffer(e)){var i=e.length;0===e.length&&i++;var o=new r(i);return e.copy(o),0===e.length&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);i=1;for(var s=e;s>=256;s>>=8)i++;for(s=(o=new Array(i)).length-1;s>=0;s--)o[s]=255&e,e>>=8;return 128&o[0]&&o.unshift(0),this._createEncoderBuffer(new r(o))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,n){var i,r=this._baseState;if(null===r.default)return!1;var o=e.join();if(void 0===r.defaultBuffer&&(r.defaultBuffer=this._encodeValue(r.default,t,n).join()),o.length!==r.defaultBuffer.length)return!1;for(i=0;i=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},E=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},I=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},D=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0},e.prototype.resolveRenameLocation=function(e){return I(this,void 0,void 0,function(){var t,n,i;return D(this,function(r){switch(r.label){case 0:return(t=this._providers[0])?t.resolveRenameLocation?[4,t.resolveRenameLocation(this.model,this.position,e)]:[3,2]:[2,void 0];case 1:n=r.sent(),r.label=2;case 2:return!n&&(i=this.model.getWordAtPosition(this.position))?[2,{range:new d.a(this.position.lineNumber,i.startColumn,this.position.lineNumber,i.endColumn),text:i.word}]:[2,n]}})})},e.prototype.provideRenameEdits=function(e,t,n,r){return I(this,void 0,void 0,function(){var o,s;return D(this,function(a){switch(a.label){case 0:return(o=this._providers[t])?[4,o.provideRenameEdits(this.model,this.position,e,r)]:[2,{edits:[],rejectReason:n.join("\n")}];case 1:return(s=a.sent())?s.rejectReason?[2,this.provideRenameEdits(e,t+1,n.concat(s.rejectReason),r)]:[2,s]:[2,this.provideRenameEdits(e,t+1,n.concat(i.a("no result","No result.")),r)]}})})},e}();function T(e,t,n){return I(this,void 0,void 0,function(){return D(this,function(i){return[2,new M(e,t).provideRenameEdits(n,0,[],x.a.None)]})})}var P=function(e){function t(t,n,i,r,o,s){var a=e.call(this)||this;return a.editor=t,a._notificationService=n,a._bulkEditService=i,a._progressService=r,a._contextKeyService=o,a._themeService=s,a._renameOperationIdPool=1,a._register(a.editor.onDidChangeModel(function(){return a.onModelChanged()})),a._register(a.editor.onDidChangeModelLanguage(function(){return a.onModelChanged()})),a._register(a.editor.onDidChangeCursorSelection(function(){return a.onModelChanged()})),a}return k(t,e),t.get=function(e){return e.getContribution(t.ID)},Object.defineProperty(t.prototype,"renameInputField",{get:function(){return this._renameInputField||(this._renameInputField=this._register(new p(this.editor,this._themeService,this._contextKeyService))),this._renameInputField},enumerable:!0,configurable:!0}),t.prototype.getId=function(){return t.ID},t.prototype.run=function(){return I(this,void 0,void 0,function(){var e,t=this;return D(this,function(n){return this._activeRename&&this._activeRename.operation.cancel(),e=this._renameOperationIdPool++,this._activeRename={id:e,operation:Object(L.f)(function(n){return t.doRename(n,e)})},[2,this._activeRename.operation]})})},t.prototype.doRename=function(e,t){return I(this,void 0,void 0,function(){var n,r,o,s,a,u,c,l,h=this;return D(this,function(f){switch(f.label){case 0:if(!this.editor.hasModel())return[2,void 0];if(n=this.editor.getPosition(),!(r=new M(this.editor.getModel(),n)).hasProvider())return[2,void 0];f.label=1;case 1:return f.trys.push([1,3,,4]),s=r.resolveRenameLocation(e),this._progressService.showWhile(s,250),[4,s];case 2:return o=f.sent(),[3,4];case 3:return a=f.sent(),_.a.get(this.editor).showMessage(a||i.a("resolveRenameLocationFailed","An unknown error occurred while resolving rename location"),n),[2,void 0];case 4:return o?o.rejectReason?(_.a.get(this.editor).showMessage(o.rejectReason,n),[2,void 0]):this._activeRename&&this._activeRename.id===t?(u=this.editor.getSelection(),c=0,l=o.text.length,d.a.isEmpty(u)||d.a.spansMultipleLines(u)||!d.a.containsRange(o.range,u)||(c=Math.max(0,u.startColumn-o.range.startColumn),l=Math.min(o.range.endColumn,u.endColumn)-o.range.startColumn),[2,this.renameInputField.getInput(o.range,o.text,c,l).then(function(t){if("boolean"!=typeof t){h.editor.focus();var n=new b.a(h.editor,15),s=Promise.resolve(r.provideRenameEdits(t,0,[],e).then(function(e){if(h.editor.hasModel()){if(!e.rejectReason)return h._bulkEditService.apply(e,{editor:h.editor}).then(function(e){e.ariaSummary&&Object(v.a)(i.a("aria","Successfully renamed '{0}' to '{1}'. Summary: {2}",o.text,t,e.ariaSummary))});n.validate(h.editor)?_.a.get(h.editor).showMessage(e.rejectReason,h.editor.getPosition()):h._notificationService.info(e.rejectReason)}},function(e){return h._notificationService.error(i.a("rename.failed","Rename failed to execute.")),Promise.reject(e)}));return h._progressService.showWhile(s,250),s}t&&h.editor.focus()})]):[2,void 0]:[2,void 0]}})})},t.prototype.acceptRenameInput=function(){this._renameInputField&&this._renameInputField.acceptInput()},t.prototype.cancelRenameInput=function(){this._renameInputField&&this._renameInputField.cancelInput(!0)},t.prototype.onModelChanged=function(){this._activeRename&&(this._activeRename.operation.cancel(),this._activeRename=void 0)},t.ID="editor.contrib.renameController",t=N([E(1,y.a),E(2,w.a),E(3,s.a),E(4,o.c),E(5,g.c)],t)}(c.a),A=function(e){function t(){return e.call(this,{id:"editor.action.rename",label:i.a("rename.label","Rename Symbol"),alias:"Rename Symbol",precondition:o.a.and(u.a.writable,u.a.hasRenameProvider),kbOpts:{kbExpr:u.a.editorTextFocus,primary:60,weight:100},menuOpts:{group:"1_modification",order:1.1}})||this}return k(t,e),t.prototype.runCommand=function(t,n){var i=this,o=t.get(S.a),s=Array.isArray(n)&&n||[void 0,void 0],a=s[0],u=s[1];return C.a.isUri(a)&&l.a.isIPosition(u)?o.openCodeEditor({resource:a},o.getActiveCodeEditor()).then(function(e){e&&(e.setPosition(u),e.invokeWithinContext(function(t){return i.reportTelemetry(t,e),i.run(t,e)}))},r.e):e.prototype.runCommand.call(this,t,n)},t.prototype.run=function(e,t){var n=P.get(t);return n?n.run():Promise.resolve()},t}(a.b);Object(a.h)(P),Object(a.f)(A);var R=a.c.bindToContribution(P.get);Object(a.g)(new R({id:"acceptRenameInput",precondition:f,handler:function(e){return e.acceptRenameInput()},kbOpts:{weight:199,kbExpr:u.a.focus,primary:3}})),Object(a.g)(new R({id:"cancelRenameInput",precondition:f,handler:function(e){return e.cancelRenameInput()},kbOpts:{weight:199,kbExpr:u.a.focus,primary:9,secondary:[1033]}})),Object(a.e)("_executeDocumentRenameProvider",function(e,t,n){var i=n.newName;if("string"!=typeof i)throw Object(r.b)("newName");return T(e,t,i)})},qEZG:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("03Zz"),o=n("sKqm"),s=n("EfIu"),a=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),u=function(e){function t(){var t=e.call(this,{id:"editor.action.toggleHighContrast",label:s.h.toggleHighContrast,alias:"Toggle High Contrast Theme",precondition:void 0})||this;return t._originalThemeName=null,t}return a(t,e),t.prototype.run=function(e,t){var n=e.get(o.a);this._originalThemeName?(n.setTheme(this._originalThemeName),this._originalThemeName=null):(this._originalThemeName=n.getTheme().themeName,n.setTheme("hc-black"))},t}(r.b);Object(r.f)(u)},qecS:function(e,t,n){"use strict";n("XTA7");var i,r=n("lAcG"),o=n("7/Cv"),s=n("WZeM"),a=n("b1X/"),u=n("UMuV"),c=n("Uf3U"),l=n("odeJ"),d=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),h=11,f=function(e){function t(t){var n=e.call(this)||this;return n._onActivate=t.onActivate,n.bgDomNode=document.createElement("div"),n.bgDomNode.className="arrow-background",n.bgDomNode.style.position="absolute",n.bgDomNode.style.width=t.bgWidth+"px",n.bgDomNode.style.height=t.bgHeight+"px",void 0!==t.top&&(n.bgDomNode.style.top="0px"),void 0!==t.left&&(n.bgDomNode.style.left="0px"),void 0!==t.bottom&&(n.bgDomNode.style.bottom="0px"),void 0!==t.right&&(n.bgDomNode.style.right="0px"),n.domNode=document.createElement("div"),n.domNode.className=t.className,n.domNode.style.position="absolute",n.domNode.style.width=h+"px",n.domNode.style.height=h+"px",void 0!==t.top&&(n.domNode.style.top=t.top+"px"),void 0!==t.left&&(n.domNode.style.left=t.left+"px"),void 0!==t.bottom&&(n.domNode.style.bottom=t.bottom+"px"),void 0!==t.right&&(n.domNode.style.right=t.right+"px"),n._mouseMoveMonitor=n._register(new u.a),n.onmousedown(n.bgDomNode,function(e){return n._arrowMouseDown(e)}),n.onmousedown(n.domNode,function(e){return n._arrowMouseDown(e)}),n._mousedownRepeatTimer=n._register(new l.c),n._mousedownScheduleRepeatTimer=n._register(new l.e),n}return d(t,e),t.prototype._arrowMouseDown=function(e){var t=this;this._onActivate(),this._mousedownRepeatTimer.cancel(),this._mousedownScheduleRepeatTimer.cancelAndSet(function(){t._mousedownRepeatTimer.cancelAndSet(function(){return t._onActivate()},1e3/24)},200),this._mouseMoveMonitor.startMonitoring(u.b,function(e){},function(){t._mousedownRepeatTimer.cancel(),t._mousedownScheduleRepeatTimer.cancel()}),e.preventDefault()},t}(c.a),p=n("tqet"),g=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),m=function(e){function t(t,n,i){var r=e.call(this)||this;return r._visibility=t,r._visibleClassName=n,r._invisibleClassName=i,r._domNode=null,r._isVisible=!1,r._isNeeded=!1,r._shouldBeVisible=!1,r._revealTimer=r._register(new l.e),r}return g(t,e),t.prototype.applyVisibilitySetting=function(e){return 2!==this._visibility&&(3===this._visibility||e)},t.prototype.setShouldBeVisible=function(e){var t=this.applyVisibilitySetting(e);this._shouldBeVisible!==t&&(this._shouldBeVisible=t,this.ensureVisibility())},t.prototype.setIsNeeded=function(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())},t.prototype.setDomNode=function(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)},t.prototype.ensureVisibility=function(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)},t.prototype._reveal=function(){var e=this;this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(function(){e._domNode&&e._domNode.setClassName(e._visibleClassName)},0))},t.prototype._hide=function(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode&&this._domNode.setClassName(this._invisibleClassName+(e?" fade":"")))},t}(p.a),v=n("ZfGv"),_=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),b=function(e){function t(t){var n=e.call(this)||this;return n._lazyRender=t.lazyRender,n._host=t.host,n._scrollable=t.scrollable,n._scrollbarState=t.scrollbarState,n._visibilityController=n._register(new m(t.visibility,"visible scrollbar "+t.extraScrollbarClassName,"invisible scrollbar "+t.extraScrollbarClassName)),n._mouseMoveMonitor=n._register(new u.a),n._shouldRender=!0,n.domNode=Object(s.b)(document.createElement("div")),n.domNode.setAttribute("role","presentation"),n.domNode.setAttribute("aria-hidden","true"),n._visibilityController.setDomNode(n.domNode),n.domNode.setPosition("absolute"),n.onmousedown(n.domNode.domNode,function(e){return n._domNodeMouseDown(e)}),n}return _(t,e),t.prototype._createArrow=function(e){var t=this._register(new f(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)},t.prototype._createSlider=function(e,t,n,i){var r=this;this.slider=Object(s.b)(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),"number"==typeof n&&this.slider.setWidth(n),"number"==typeof i&&this.slider.setHeight(i),this.slider.setLayerHinting(!0),this.domNode.domNode.appendChild(this.slider.domNode),this.onmousedown(this.slider.domNode,function(e){e.leftButton&&(e.preventDefault(),r._sliderMouseDown(e,function(){}))}),this.onclick(this.slider.domNode,function(e){e.leftButton&&e.stopPropagation()})},t.prototype._onElementSize=function(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender},t.prototype._onElementScrollSize=function(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender},t.prototype._onElementScrollPosition=function(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender},t.prototype.beginReveal=function(){this._visibilityController.setShouldBeVisible(!0)},t.prototype.beginHide=function(){this._visibilityController.setShouldBeVisible(!1)},t.prototype.render=function(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))},t.prototype._domNodeMouseDown=function(e){e.target===this.domNode.domNode&&this._onMouseDown(e)},t.prototype.delegateMouseDown=function(e){var t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),i=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderMousePosition(e);n<=r&&r<=i?e.leftButton&&(e.preventDefault(),this._sliderMouseDown(e,function(){})):this._onMouseDown(e)},t.prototype._onMouseDown=function(e){var t,n;if(e.target===this.domNode.domNode&&"number"==typeof e.browserEvent.offsetX&&"number"==typeof e.browserEvent.offsetY)t=e.browserEvent.offsetX,n=e.browserEvent.offsetY;else{var i=o.x(this.domNode.domNode);t=e.posx-i.left,n=e.posy-i.top}this._setDesiredScrollPositionNow(this._scrollbarState.getDesiredScrollPositionFromOffset(this._mouseDownRelativePosition(t,n))),e.leftButton&&(e.preventDefault(),this._sliderMouseDown(e,function(){}))},t.prototype._sliderMouseDown=function(e,t){var n=this,i=this._sliderMousePosition(e),r=this._sliderOrthogonalMousePosition(e),o=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._mouseMoveMonitor.startMonitoring(u.b,function(e){var t=n._sliderOrthogonalMousePosition(e),s=Math.abs(t-r);if(v.g&&s>140)n._setDesiredScrollPositionNow(o.getScrollPosition());else{var a=n._sliderMousePosition(e)-i;n._setDesiredScrollPositionNow(o.getDesiredScrollPositionFromDelta(a))}},function(){n.slider.toggleClassName("active",!1),n._host.onDragEnd(),t()}),this._host.onDragStart()},t.prototype._setDesiredScrollPositionNow=function(e){var t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)},t}(c.a),y=function(){function e(e,t,n){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=0,this._scrollSize=0,this._scrollPosition=0,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}return e.prototype.clone=function(){var t=new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize);return t.setVisibleSize(this._visibleSize),t.setScrollSize(this._scrollSize),t.setScrollPosition(this._scrollPosition),t},e.prototype.setVisibleSize=function(e){var t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)},e.prototype.setScrollSize=function(e){var t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)},e.prototype.setScrollPosition=function(e){var t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)},e._computeValues=function(e,t,n,i,r){var o=Math.max(0,n-e),s=Math.max(0,o-2*t),a=i>0&&i>n;if(!a)return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(s),computedSliderRatio:0,computedSliderPosition:0};var u=Math.round(Math.max(20,Math.floor(n*s/i))),c=(s-u)/(i-n),l=r*c;return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(u),computedSliderRatio:c,computedSliderPosition:Math.round(l)}},e.prototype._refreshComputedValues=function(){var t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition},e.prototype.getArrowSize=function(){return this._arrowSize},e.prototype.getScrollPosition=function(){return this._scrollPosition},e.prototype.getRectangleLargeSize=function(){return this._computedAvailableSize},e.prototype.getRectangleSmallSize=function(){return this._scrollbarSize},e.prototype.isNeeded=function(){return this._computedIsNeeded},e.prototype.getSliderSize=function(){return this._computedSliderSize},e.prototype.getSliderPosition=function(){return this._computedSliderPosition},e.prototype.getDesiredScrollPositionFromOffset=function(e){if(!this._computedIsNeeded)return 0;var t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)},e.prototype.getDesiredScrollPositionFromDelta=function(e){if(!this._computedIsNeeded)return 0;var t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)},e}(),w=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),C=function(e){function t(t,n,i){var r=e.call(this,{lazyRender:n.lazyRender,host:i,scrollbarState:new y(n.horizontalHasArrows?n.arrowSize:0,2===n.horizontal?0:n.horizontalScrollbarSize,2===n.vertical?0:n.verticalScrollbarSize),visibility:n.horizontal,extraScrollbarClassName:"horizontal",scrollable:t})||this;if(n.horizontalHasArrows){var o=(n.arrowSize-h)/2,s=(n.horizontalScrollbarSize-h)/2;r._createArrow({className:"left-arrow",top:s,left:o,bottom:void 0,right:void 0,bgWidth:n.arrowSize,bgHeight:n.horizontalScrollbarSize,onActivate:function(){return r._host.onMouseWheel(new a.c(null,1,0))}}),r._createArrow({className:"right-arrow",top:s,left:void 0,bottom:void 0,right:o,bgWidth:n.arrowSize,bgHeight:n.horizontalScrollbarSize,onActivate:function(){return r._host.onMouseWheel(new a.c(null,-1,0))}})}return r._createSlider(Math.floor((n.horizontalScrollbarSize-n.horizontalSliderSize)/2),0,void 0,n.horizontalSliderSize),r}return w(t,e),t.prototype._updateSlider=function(e,t){this.slider.setWidth(e),this.slider.setLeft(t)},t.prototype._renderDomNode=function(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)},t.prototype.onDidScroll=function(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender},t.prototype._mouseDownRelativePosition=function(e,t){return e},t.prototype._sliderMousePosition=function(e){return e.posx},t.prototype._sliderOrthogonalMousePosition=function(e){return e.posy},t.prototype.writeScrollPosition=function(e,t){e.scrollLeft=t},t}(b),S=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),x=function(e){function t(t,n,i){var r=e.call(this,{lazyRender:n.lazyRender,host:i,scrollbarState:new y(n.verticalHasArrows?n.arrowSize:0,2===n.vertical?0:n.verticalScrollbarSize,0),visibility:n.vertical,extraScrollbarClassName:"vertical",scrollable:t})||this;if(n.verticalHasArrows){var o=(n.arrowSize-h)/2,s=(n.verticalScrollbarSize-h)/2;r._createArrow({className:"up-arrow",top:o,left:s,bottom:void 0,right:void 0,bgWidth:n.verticalScrollbarSize,bgHeight:n.arrowSize,onActivate:function(){return r._host.onMouseWheel(new a.c(null,0,1))}}),r._createArrow({className:"down-arrow",top:void 0,left:s,bottom:o,right:void 0,bgWidth:n.verticalScrollbarSize,bgHeight:n.arrowSize,onActivate:function(){return r._host.onMouseWheel(new a.c(null,0,-1))}})}return r._createSlider(0,Math.floor((n.verticalScrollbarSize-n.verticalSliderSize)/2),n.verticalSliderSize,void 0),r}return S(t,e),t.prototype._updateSlider=function(e,t){this.slider.setHeight(e),this.slider.setTop(t)},t.prototype._renderDomNode=function(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)},t.prototype.onDidScroll=function(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender},t.prototype._mouseDownRelativePosition=function(e,t){return t},t.prototype._sliderMousePosition=function(e){return e.posy},t.prototype._sliderOrthogonalMousePosition=function(e){return e.posx},t.prototype.writeScrollPosition=function(e,t){e.scrollTop=t},t}(b),L=n("Kp7x"),O=n("fyvs");n.d(t,"b",function(){return D}),n.d(t,"c",function(){return M}),n.d(t,"a",function(){return T});var k=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),N=function(){return function(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}}(),E=function(){function e(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}return e.prototype.isPhysicalMouseWheel=function(){if(-1===this._front&&-1===this._rear)return!1;for(var e=1,t=0,n=1,i=this._rear;;){var r=i===this._front?e:Math.pow(2,-n);if(e-=r,t+=this._memory[i].score*r,i===this._front)break;i=(this._capacity+i-1)%this._capacity,n++}return t<=.5},e.prototype.accept=function(e,t,n){var i=new N(e,t,n);i.score=this._computeScore(i),-1===this._front&&-1===this._rear?(this._memory[0]=i,this._front=0,this._rear=0):(this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i)},e.prototype._computeScore=function(e){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;var t=.5;-1===this._front&&-1===this._rear||this._memory[this._rear];return(Math.abs(e.deltaX-Math.round(e.deltaX))>0||Math.abs(e.deltaY-Math.round(e.deltaY))>0)&&(t+=.25),Math.min(Math.max(t,0),1)},e.INSTANCE=new e,e}(),I=function(e){function t(t,n,i){var r=e.call(this)||this;r._onScroll=r._register(new L.a),r.onScroll=r._onScroll.event,t.style.overflow="hidden",r._options=P(n),r._scrollable=i,r._register(r._scrollable.onScroll(function(e){r._onDidScroll(e),r._onScroll.fire(e)}));var o={onMouseWheel:function(e){return r._onMouseWheel(e)},onDragStart:function(){return r._onDragStart()},onDragEnd:function(){return r._onDragEnd()}};return r._verticalScrollbar=r._register(new x(r._scrollable,r._options,o)),r._horizontalScrollbar=r._register(new C(r._scrollable,r._options,o)),r._domNode=document.createElement("div"),r._domNode.className="monaco-scrollable-element "+r._options.className,r._domNode.setAttribute("role","presentation"),r._domNode.style.position="relative",r._domNode.style.overflow="hidden",r._domNode.appendChild(t),r._domNode.appendChild(r._horizontalScrollbar.domNode.domNode),r._domNode.appendChild(r._verticalScrollbar.domNode.domNode),r._options.useShadows?(r._leftShadowDomNode=Object(s.b)(document.createElement("div")),r._leftShadowDomNode.setClassName("shadow"),r._domNode.appendChild(r._leftShadowDomNode.domNode),r._topShadowDomNode=Object(s.b)(document.createElement("div")),r._topShadowDomNode.setClassName("shadow"),r._domNode.appendChild(r._topShadowDomNode.domNode),r._topLeftShadowDomNode=Object(s.b)(document.createElement("div")),r._topLeftShadowDomNode.setClassName("shadow top-left-corner"),r._domNode.appendChild(r._topLeftShadowDomNode.domNode)):(r._leftShadowDomNode=null,r._topShadowDomNode=null,r._topLeftShadowDomNode=null),r._listenOnDomNode=r._options.listenOnDomNode||r._domNode,r._mouseWheelToDispose=[],r._setListeningToMouseWheel(r._options.handleMouseWheel),r.onmouseover(r._listenOnDomNode,function(e){return r._onMouseOver(e)}),r.onnonbubblingmouseout(r._listenOnDomNode,function(e){return r._onMouseOut(e)}),r._hideTimeout=r._register(new l.e),r._isDragging=!1,r._mouseIsOver=!1,r._shouldRender=!0,r._revealOnScroll=!0,r}return k(t,e),t.prototype.dispose=function(){this._mouseWheelToDispose=Object(p.f)(this._mouseWheelToDispose),e.prototype.dispose.call(this)},t.prototype.getDomNode=function(){return this._domNode},t.prototype.getOverviewRulerLayoutInfo=function(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}},t.prototype.delegateVerticalScrollbarMouseDown=function(e){this._verticalScrollbar.delegateMouseDown(e)},t.prototype.getScrollDimensions=function(){return this._scrollable.getScrollDimensions()},t.prototype.setScrollDimensions=function(e){this._scrollable.setScrollDimensions(e)},t.prototype.updateClassName=function(e){this._options.className=e,v.d&&(this._options.className+=" mac"),this._domNode.className="monaco-scrollable-element "+this._options.className},t.prototype.updateOptions=function(e){var t=P(e);this._options.handleMouseWheel=t.handleMouseWheel,this._options.mouseWheelScrollSensitivity=t.mouseWheelScrollSensitivity,this._options.fastScrollSensitivity=t.fastScrollSensitivity,this._setListeningToMouseWheel(this._options.handleMouseWheel),this._options.lazyRender||this._render()},t.prototype._setListeningToMouseWheel=function(e){var t=this;if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Object(p.f)(this._mouseWheelToDispose),e)){this._mouseWheelToDispose.push(o.h(this._listenOnDomNode,r.g?"mousewheel":"wheel",function(e){t._onMouseWheel(new a.c(e))}))}},t.prototype._onMouseWheel=function(e){var t,n=E.INSTANCE;if(n.accept(Date.now(),e.deltaX,e.deltaY),e.deltaY||e.deltaX){var i=e.deltaY*this._options.mouseWheelScrollSensitivity,r=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.flipAxes&&(i=(t=[r,i])[0],r=t[1]);var o=!v.d&&e.browserEvent&&e.browserEvent.shiftKey;!this._options.scrollYToX&&!o||r||(r=i,i=0),e.browserEvent&&e.browserEvent.altKey&&(r*=this._options.fastScrollSensitivity,i*=this._options.fastScrollSensitivity);var s=this._scrollable.getFutureScrollPosition(),a={};if(i){var u=s.scrollTop-50*i;this._verticalScrollbar.writeScrollPosition(a,u)}if(r){var c=s.scrollLeft-50*r;this._horizontalScrollbar.writeScrollPosition(a,c)}if(a=this._scrollable.validateScrollPosition(a),s.scrollLeft!==a.scrollLeft||s.scrollTop!==a.scrollTop)this._options.mouseWheelSmoothScroll&&n.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(a):this._scrollable.setScrollPositionNow(a),this._shouldRender=!0}(this._options.alwaysConsumeMouseWheel||this._shouldRender)&&(e.preventDefault(),e.stopPropagation())},t.prototype._onDidScroll=function(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()},t.prototype.renderNow=function(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()},t.prototype._render=function(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){var e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0;this._leftShadowDomNode.setClassName("shadow"+(n?" left":"")),this._topShadowDomNode.setClassName("shadow"+(t?" top":"")),this._topLeftShadowDomNode.setClassName("shadow top-left-corner"+(t?" top":"")+(n?" left":""))}},t.prototype._onDragStart=function(){this._isDragging=!0,this._reveal()},t.prototype._onDragEnd=function(){this._isDragging=!1,this._hide()},t.prototype._onMouseOut=function(e){this._mouseIsOver=!1,this._hide()},t.prototype._onMouseOver=function(e){this._mouseIsOver=!0,this._reveal()},t.prototype._reveal=function(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()},t.prototype._hide=function(){this._mouseIsOver||this._isDragging||(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())},t.prototype._scheduleHide=function(){var e=this;this._mouseIsOver||this._isDragging||this._hideTimeout.cancelAndSet(function(){return e._hide()},500)},t}(c.a),D=function(e){function t(t,n){var i=this;(n=n||{}).mouseWheelSmoothScroll=!1;var r=new O.a(0,function(e){return o.P(e)});return(i=e.call(this,t,n,r)||this)._register(r),i}return k(t,e),t.prototype.setScrollPosition=function(e){this._scrollable.setScrollPositionNow(e)},t.prototype.getScrollPosition=function(){return this._scrollable.getCurrentScrollPosition()},t}(I),M=function(e){function t(t,n,i){return e.call(this,t,n,i)||this}return k(t,e),t}(I),T=function(e){function t(t,n){var i=e.call(this,t,n)||this;return i._element=t,i.onScroll(function(e){e.scrollTopChanged&&(i._element.scrollTop=e.scrollTop),e.scrollLeftChanged&&(i._element.scrollLeft=e.scrollLeft)}),i.scanDomNode(),i}return k(t,e),t.prototype.scanDomNode=function(){this.setScrollDimensions({width:this._element.clientWidth,scrollWidth:this._element.scrollWidth,height:this._element.clientHeight,scrollHeight:this._element.scrollHeight}),this.setScrollPosition({scrollLeft:this._element.scrollLeft,scrollTop:this._element.scrollTop})},t}(D);function P(e){var t={lazyRender:void 0!==e.lazyRender&&e.lazyRender,className:void 0!==e.className?e.className:"",useShadows:void 0===e.useShadows||e.useShadows,handleMouseWheel:void 0===e.handleMouseWheel||e.handleMouseWheel,flipAxes:void 0!==e.flipAxes&&e.flipAxes,alwaysConsumeMouseWheel:void 0!==e.alwaysConsumeMouseWheel&&e.alwaysConsumeMouseWheel,scrollYToX:void 0!==e.scrollYToX&&e.scrollYToX,mouseWheelScrollSensitivity:void 0!==e.mouseWheelScrollSensitivity?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:void 0!==e.fastScrollSensitivity?e.fastScrollSensitivity:5,mouseWheelSmoothScroll:void 0===e.mouseWheelSmoothScroll||e.mouseWheelSmoothScroll,arrowSize:void 0!==e.arrowSize?e.arrowSize:11,listenOnDomNode:void 0!==e.listenOnDomNode?e.listenOnDomNode:null,horizontal:void 0!==e.horizontal?e.horizontal:1,horizontalScrollbarSize:void 0!==e.horizontalScrollbarSize?e.horizontalScrollbarSize:10,horizontalSliderSize:void 0!==e.horizontalSliderSize?e.horizontalSliderSize:0,horizontalHasArrows:void 0!==e.horizontalHasArrows&&e.horizontalHasArrows,vertical:void 0!==e.vertical?e.vertical:1,verticalScrollbarSize:void 0!==e.verticalScrollbarSize?e.verticalScrollbarSize:10,verticalHasArrows:void 0!==e.verticalHasArrows&&e.verticalHasArrows,verticalSliderSize:void 0!==e.verticalSliderSize?e.verticalSliderSize:0};return t.horizontalSliderSize=void 0!==e.horizontalSliderSize?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=void 0!==e.verticalSliderSize?e.verticalSliderSize:t.verticalScrollbarSize,v.d&&(t.className+=" mac"),t}},qqhx:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("hK2W"),r=n("tqet"),o=n("JVO/"),s=n("/9db"),a=n("7g0X"),u=n("03Zz"),c=n("7/Cv"),l=n("Gxst"),d=n("UqCF"),h=n("qecS"),f=n("Kp7x"),p=(n("s/JM"),n("6TMp")),g=n("VBCr"),m=n("odeJ"),v=n("zxiH"),_=n("PCC9"),b=n("80kS"),y=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},w=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},R=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},F=c.a,j=function(e){function t(t,n,i,o){var s=e.call(this)||this;return s.editor=t,s.renderDisposeables=s._register(new r.b),s.model=s._register(new r.d),s.allowEditorOverflow=!0,s.markdownRenderer=s._register(new g.a(t,o,i)),s.model.value=new T(t),s.keyVisible=S.Visible.bindTo(n),s.keyMultipleSignatures=S.MultipleSignatures.bindTo(n),s.visible=!1,s._register(s.model.value.onChangedHints(function(e){e?(s.show(),s.render(e)):s.hide()})),s}return P(t,e),t.prototype.createParamaterHintDOMNodes=function(){var e=this;this.element=F(".editor-widget.parameter-hints-widget");var t=c.m(this.element,F(".wrapper"));t.tabIndex=-1;var n=c.m(t,F(".buttons")),i=c.m(n,F(".button.previous")),r=c.m(n,F(".button.next")),o=Object(l.b)(Object(l.a)(i,"click"));this._register(o(this.previous,this));var s=Object(l.b)(Object(l.a)(r,"click"));this._register(s(this.next,this)),this.overloads=c.m(t,F(".overloads"));var a=F(".body");this.scrollbar=new h.a(a,{}),this._register(this.scrollbar),t.appendChild(this.scrollbar.getDomNode()),this.signature=c.m(a,F(".signature")),this.docs=c.m(a,F(".docs")),this.editor.addContentWidget(this),this.hide(),this.element.style.userSelect="text",this._register(this.editor.onDidChangeCursorSelection(function(t){e.visible&&e.editor.layoutContentWidget(e)}));var u=function(){var t=e.editor.getConfiguration().fontInfo;e.element.style.fontSize=t.fontSize+"px"};u(),this._register(f.b.chain(this.editor.onDidChangeConfiguration.bind(this.editor)).filter(function(e){return e.fontInfo}).on(u,null)),this._register(this.editor.onDidLayoutChange(function(t){return e.updateMaxHeight()})),this.updateMaxHeight()},t.prototype.show=function(){var e=this;this.model&&!this.visible&&(this.element||this.createParamaterHintDOMNodes(),this.keyVisible.set(!0),this.visible=!0,setTimeout(function(){return c.f(e.element,"visible")},100),this.editor.layoutContentWidget(this))},t.prototype.hide=function(){this.model&&this.visible&&(this.element||this.createParamaterHintDOMNodes(),this.keyVisible.reset(),this.visible=!1,this.announcedLabel=null,c.I(this.element,"visible"),this.editor.layoutContentWidget(this))},t.prototype.getPosition=function(){return this.visible?{position:this.editor.getPosition(),preference:[1,2]}:null},t.prototype.render=function(e){var t=e.signatures.length>1;c.R(this.element,"multiple",t),this.keyMultipleSignatures.set(t),this.signature.innerHTML="",this.docs.innerHTML="";var n=e.signatures[e.activeSignature];if(n){var r=c.m(this.signature,F(".code")),o=n.parameters.length>0,s=this.editor.getConfiguration().fontInfo;if(r.style.fontSize=s.fontSize+"px",r.style.fontFamily=s.fontFamily,o)this.renderParameters(r,n,e.activeParameter);else c.m(r,F("span")).textContent=n.label;this.renderDisposeables.clear();var a=n.parameters[e.activeParameter];if(a&&a.documentation){var u=F("span.documentation");if("string"==typeof a.documentation)u.textContent=a.documentation;else{var l=this.markdownRenderer.render(a.documentation);c.f(l.element,"markdown-docs"),this.renderDisposeables.add(l),u.appendChild(l.element)}c.m(this.docs,F("p",{},u))}if(void 0===n.documentation);else if("string"==typeof n.documentation)c.m(this.docs,F("p",{},n.documentation));else{l=this.markdownRenderer.render(n.documentation);c.f(l.element,"markdown-docs"),this.renderDisposeables.add(l),c.m(this.docs,l.element)}var h=!1;a&&"string"==typeof a.documentation&&a.documentation.length>0&&(h=!0),a&&"object"==typeof a.documentation&&a.documentation.value.length>0&&(h=!0),"string"==typeof n.documentation&&n.documentation.length>0&&(h=!0),"object"==typeof n.documentation&&n.documentation.value.length>0&&(h=!0),c.R(this.signature,"has-docs",h),c.R(this.docs,"empty",!h);var f=String(e.activeSignature+1);if(e.signatures.length<10&&(f+="/"+e.signatures.length),this.overloads.textContent=f,a){var p=this.getParameterLabel(n,e.activeParameter);this.announcedLabel!==p&&(d.a(i.a("hint","{0}, hint",p)),this.announcedLabel=p)}this.editor.layoutContentWidget(this),this.scrollbar.scanDomNode()}},t.prototype.renderParameters=function(e,t,n){var i=this.getParameterLabelOffsets(t,n),r=i[0],o=i[1],s=document.createElement("span");s.textContent=t.label.substring(0,r);var a=document.createElement("span");a.textContent=t.label.substring(r,o),a.className="parameter active";var u=document.createElement("span");u.textContent=t.label.substring(o),c.m(e,s,a,u)},t.prototype.getParameterLabel=function(e,t){var n=e.parameters[t];return"string"==typeof n.label?n.label:e.label.substring(n.label[0],n.label[1])},t.prototype.getParameterLabelOffsets=function(e,t){var n=e.parameters[t];if(n){if(Array.isArray(n.label))return n.label;var i=e.label.lastIndexOf(n.label);return i>=0?[i,i+n.label.length]:[0,0]}return[0,0]},t.prototype.next=function(){this.model.value&&(this.editor.focus(),this.model.value.next())},t.prototype.previous=function(){this.model.value&&(this.editor.focus(),this.model.value.previous())},t.prototype.cancel=function(){this.model.value&&this.model.value.cancel()},t.prototype.getDomNode=function(){return this.element},t.prototype.getId=function(){return t.ID},t.prototype.trigger=function(e){this.model.value&&this.model.value.trigger(e,0)},t.prototype.updateMaxHeight=function(){var e=Math.max(this.editor.getLayoutInfo().height/4,250);this.element.style.maxHeight=e+"px"},t.ID="editor.widget.parameterHintsWidget",t=A([R(1,a.c),R(2,k.a),R(3,p.a)],t)}(r.a);Object(E.f)(function(e,t){var n=e.getColor(N.B);if(n){var i=e.type===E.b?2:1;t.addRule(".monaco-editor .parameter-hints-widget { border: "+i+"px solid "+n+"; }"),t.addRule(".monaco-editor .parameter-hints-widget.multiple .body { border-left: 1px solid "+n.transparent(.5)+"; }"),t.addRule(".monaco-editor .parameter-hints-widget .signature.has-docs { border-bottom: 1px solid "+n.transparent(.5)+"; }")}var r=e.getColor(N.A);r&&t.addRule(".monaco-editor .parameter-hints-widget { background-color: "+r+"; }");var o=e.getColor(N._46);o&&t.addRule(".monaco-editor .parameter-hints-widget a { color: "+o+"; }");var s=e.getColor(N._45);s&&t.addRule(".monaco-editor .parameter-hints-widget code { background-color: "+s+"; }")}),n.d(t,"TriggerParameterHintsAction",function(){return z});var W=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),B=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},V=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},H=function(e){function t(t,n){var i=e.call(this)||this;return i.editor=t,i.widget=i._register(n.createInstance(j,i.editor)),i}return W(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype.getId=function(){return t.ID},t.prototype.cancel=function(){this.widget.cancel()},t.prototype.previous=function(){this.widget.previous()},t.prototype.next=function(){this.widget.next()},t.prototype.trigger=function(e){this.widget.trigger(e)},t.ID="editor.controller.parameterHints",t=B([V(1,o.a)],t)}(r.a),z=function(e){function t(){return e.call(this,{id:"editor.action.triggerParameterHints",label:i.a("parameterHints.trigger.label","Trigger Parameter Hints"),alias:"Trigger Parameter Hints",precondition:s.a.hasSignatureHelpProvider,kbOpts:{kbExpr:s.a.editorTextFocus,primary:3082,weight:100}})||this}return W(t,e),t.prototype.run=function(e,t){var n=H.get(t);n&&n.trigger({triggerKind:_.w.Invoke})},t}(u.b);Object(u.h)(H),Object(u.f)(z);var U=u.c.bindToContribution(H.get);Object(u.g)(new U({id:"closeParameterHints",precondition:S.Visible,handler:function(e){return e.cancel()},kbOpts:{weight:175,kbExpr:s.a.focus,primary:9,secondary:[1033]}})),Object(u.g)(new U({id:"showPrevParameterHint",precondition:a.a.and(S.Visible,S.MultipleSignatures),handler:function(e){return e.previous()},kbOpts:{weight:175,kbExpr:s.a.focus,primary:16,secondary:[528],mac:{primary:16,secondary:[528,302]}}})),Object(u.g)(new U({id:"showNextParameterHint",precondition:a.a.and(S.Visible,S.MultipleSignatures),handler:function(e){return e.next()},kbOpts:{weight:175,kbExpr:s.a.focus,primary:18,secondary:[530],mac:{primary:18,secondary:[530,300]}}}))},qyJz:function(e,t,n){"use strict";var i=n("+ZMJ"),r=n("kM2E"),o=n("sB3e"),s=n("msXi"),a=n("Mhyx"),u=n("QRG4"),c=n("fBQ2"),l=n("3fs2");r(r.S+r.F*!n("dY0y")(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,r,d,h=o(e),f="function"==typeof this?this:Array,p=arguments.length,g=p>1?arguments[1]:void 0,m=void 0!==g,v=0,_=l(h);if(m&&(g=i(g,p>2?arguments[2]:void 0,2)),void 0==_||f==Array&&a(_))for(n=new f(t=u(h.length));t>v;v++)c(n,v,m?g(h[v],v):h[v]);else for(d=_.call(h),n=new f;!(r=d.next()).done;v++)c(n,v,m?s(d,g,[r.value,v],!0):r.value);return n.length=v,n}})},"qzX+":function(e,t,n){"use strict";n.d(t,"a",function(){return g});var i,r=n("xF6g"),o=(n.n(r),n("lAcG")),s=n("tqet"),a=n("Kp7x"),u=n("ZfGv"),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});function l(e,t){return!!e[t]}var d=function(){return function(e,t){this.target=e.target,this.hasTriggerModifier=l(e.event,t.triggerModifier),this.hasSideBySideModifier=l(e.event,t.triggerSideBySideModifier),this.isNoneOrSingleMouseDown=o.j||e.event.detail<=1}}(),h=function(){return function(e,t){this.keyCodeIsTriggerKey=e.keyCode===t.triggerKey,this.keyCodeIsSideBySideKey=e.keyCode===t.triggerSideBySideKey,this.hasTriggerModifier=l(e,t.triggerModifier)}}(),f=function(){function e(e,t,n,i){this.triggerKey=e,this.triggerModifier=t,this.triggerSideBySideKey=n,this.triggerSideBySideModifier=i}return e.prototype.equals=function(e){return this.triggerKey===e.triggerKey&&this.triggerModifier===e.triggerModifier&&this.triggerSideBySideKey===e.triggerSideBySideKey&&this.triggerSideBySideModifier===e.triggerSideBySideModifier},e}();function p(e){return"altKey"===e?u.d?new f(57,"metaKey",6,"altKey"):new f(5,"ctrlKey",6,"altKey"):u.d?new f(6,"altKey",57,"metaKey"):new f(6,"altKey",5,"ctrlKey")}var g=function(e){function t(t){var n=e.call(this)||this;return n._onMouseMoveOrRelevantKeyDown=n._register(new a.a),n.onMouseMoveOrRelevantKeyDown=n._onMouseMoveOrRelevantKeyDown.event,n._onExecute=n._register(new a.a),n.onExecute=n._onExecute.event,n._onCancel=n._register(new a.a),n.onCancel=n._onCancel.event,n._editor=t,n._opts=p(n._editor.getConfiguration().multiCursorModifier),n.lastMouseMoveEvent=null,n.hasTriggerKeyOnMouseDown=!1,n._register(n._editor.onDidChangeConfiguration(function(e){if(e.multiCursorModifier){var t=p(n._editor.getConfiguration().multiCursorModifier);if(n._opts.equals(t))return;n._opts=t,n.lastMouseMoveEvent=null,n.hasTriggerKeyOnMouseDown=!1,n._onCancel.fire()}})),n._register(n._editor.onMouseMove(function(e){return n.onEditorMouseMove(new d(e,n._opts))})),n._register(n._editor.onMouseDown(function(e){return n.onEditorMouseDown(new d(e,n._opts))})),n._register(n._editor.onMouseUp(function(e){return n.onEditorMouseUp(new d(e,n._opts))})),n._register(n._editor.onKeyDown(function(e){return n.onEditorKeyDown(new h(e,n._opts))})),n._register(n._editor.onKeyUp(function(e){return n.onEditorKeyUp(new h(e,n._opts))})),n._register(n._editor.onMouseDrag(function(){return n.resetHandler()})),n._register(n._editor.onDidChangeCursorSelection(function(e){return n.onDidChangeCursorSelection(e)})),n._register(n._editor.onDidChangeModel(function(e){return n.resetHandler()})),n._register(n._editor.onDidChangeModelContent(function(){return n.resetHandler()})),n._register(n._editor.onDidScrollChange(function(e){(e.scrollTopChanged||e.scrollLeftChanged)&&n.resetHandler()})),n}return c(t,e),t.prototype.onDidChangeCursorSelection=function(e){e.selection&&e.selection.startColumn!==e.selection.endColumn&&this.resetHandler()},t.prototype.onEditorMouseMove=function(e){this.lastMouseMoveEvent=e,this._onMouseMoveOrRelevantKeyDown.fire([e,null])},t.prototype.onEditorMouseDown=function(e){this.hasTriggerKeyOnMouseDown=e.hasTriggerModifier},t.prototype.onEditorMouseUp=function(e){this.hasTriggerKeyOnMouseDown&&this._onExecute.fire(e)},t.prototype.onEditorKeyDown=function(e){this.lastMouseMoveEvent&&(e.keyCodeIsTriggerKey||e.keyCodeIsSideBySideKey&&e.hasTriggerModifier)?this._onMouseMoveOrRelevantKeyDown.fire([this.lastMouseMoveEvent,e]):e.hasTriggerModifier&&this._onCancel.fire()},t.prototype.onEditorKeyUp=function(e){e.keyCodeIsTriggerKey&&this._onCancel.fire()},t.prototype.resetHandler=function(){this.lastMouseMoveEvent=null,this.hasTriggerKeyOnMouseDown=!1,this._onCancel.fire()},t}(s.a)},rHGw:function(e,t,n){"use strict";n.d(t,"a",function(){return c}),n.d(t,"b",function(){return C});var i=n("hK2W"),r=n("Kp7x"),o=n("RWr8"),s=n("KIxu"),a=n("aL7J"),u=n("LQgD"),c={Configuration:"base.contributions.configuration"},l={properties:{},patternProperties:{}},d={properties:{},patternProperties:{}},h={properties:{},patternProperties:{}},f={properties:{},patternProperties:{}},p={properties:{},patternProperties:{}},g={properties:{},patternProperties:{}},m="vscode://schemas/settings/editor",v=o.a.as(u.a.JSONContribution),_=function(){function e(){this.overrideIdentifiers=[],this._onDidSchemaChange=new r.a,this._onDidUpdateConfiguration=new r.a,this.defaultOverridesConfigurationNode={id:"defaultOverrides",title:i.a("defaultConfigurations.title","Default Configuration Overrides"),properties:{}},this.configurationContributors=[this.defaultOverridesConfigurationNode],this.editorConfigurationSchema={properties:{},patternProperties:{},additionalProperties:!1,errorMessage:"Unknown editor configuration setting",allowsTrailingCommas:!0,allowComments:!0},this.configurationProperties={},this.excludedConfigurationProperties={},this.computeOverridePropertyPattern(),v.registerSchema(m,this.editorConfigurationSchema)}return e.prototype.registerConfiguration=function(e,t){void 0===t&&(t=!0),this.registerConfigurations([e],t)},e.prototype.registerConfigurations=function(e,t){var n=this;void 0===t&&(t=!0);var i=[];e.forEach(function(e){i.push.apply(i,n.validateAndRegisterProperties(e,t)),n.configurationContributors.push(e),n.registerJSONConfiguration(e),n.updateSchemaForOverrideSettingsConfiguration(e)}),this._onDidSchemaChange.fire(),this._onDidUpdateConfiguration.fire(i)},e.prototype.registerOverrideIdentifiers=function(e){var t;(t=this.overrideIdentifiers).push.apply(t,e),this.updateOverridePropertyPatternKey()},e.prototype.validateAndRegisterProperties=function(e,t,n,i){void 0===t&&(t=!0),void 0===n&&(n=3),void 0===i&&(i=!1),n=s.k(e.scope)?n:e.scope,i=e.overridable||i;var r=[],o=e.properties;if(o)for(var a in o){var u=void 0;if(t&&(u=L(a)))console.warn(u),delete o[a];else{var c=o[a],l=c.default;s.j(l)&&(c.default=S(c.type)),i&&(c.overridable=!0),C.test(a)?c.scope=void 0:c.scope=s.k(c.scope)?n:c.scope,!o[a].hasOwnProperty("included")||o[a].included?(this.configurationProperties[a]=o[a],r.push(a)):(this.excludedConfigurationProperties[a]=o[a],delete o[a])}}var d=e.allOf;if(d)for(var h=0,f=d;ho)throw new RangeError("requested too many random bytes");var n=s.allocUnsafe(e);if(e>0)if(e>r)for(var u=0;u>6],r=0==(32&n);if(31==(31&n)){var o=n;for(n=0;128==(128&o);){if(o=e.readUInt8(t),e.isError(o))return o;n<<=7,n|=127&o}}else n&=31;return{cls:i,primitive:r,tag:n,tagStr:a.tag[n]}}function d(e,t,n){var i=e.readUInt8(n);if(e.isError(i))return i;if(!t&&128===i)return null;if(0==(128&i))return i;var r=127&i;if(r>4)return e.error("length octect is too long");i=0;for(var o=0;on)&&(!l.isEmpty()||0!==c.type&&3!==c.type)){var d=l.startLineNumber===n?l.startColumn:i,h=l.endLineNumber===n?l.endColumn:r;o[s++]=new e(d,h,c.inlineClassName,c.type)}}return o},e.compare=function(e,t){return e.startColumn===t.startColumn?e.endColumn===t.endColumn?e.classNamet.className?1:0:e.endColumn-t.endColumn:e.startColumn-t.startColumn},e}(),o=function(){return function(e,t,n){this.startOffset=e,this.endOffset=t,this.className=n}}(),s=function(){function e(){this.stopOffsets=[],this.classNames=[],this.count=0}return e.prototype.consumeLowerThan=function(e,t,n){for(;this.count>0&&this.stopOffsets[0]0&&t=e){this.stopOffsets.splice(n,0,e),this.classNames.splice(n,0,t);break}this.count++},e}(),a=function(){function e(){}return e.normalize=function(e,t){if(0===t.length)return[];for(var n=[],r=new s,o=0,a=0,u=t.length;a1){var f=e.charCodeAt(l-2);i.w(f)&&l--}if(d>1){f=e.charCodeAt(d-2);i.w(f)&&d--}var p=l-1,g=d-2;o=r.consumeLowerThan(p,o,n),0===r.count&&(o=p),r.insert(g,h)}return r.consumeLowerThan(1073741824,o,n),n},e}()},tGak:function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return o});var i=function(){function e(e,t,n){this.from=0|e,this.to=0|t,this.colorId=0|n}return e.compare=function(e,t){return e.colorId===t.colorId?e.from===t.from?e.to-t.to:e.from-t.from:e.colorId-t.colorId},e}(),r=function(){function e(e,t,n){this.startLineNumber=e,this.endLineNumber=t,this.color=n,this._colorZone=null}return e.compare=function(e,t){return e.color===t.color?e.startLineNumber===t.startLineNumber?e.endLineNumber-t.endLineNumber:e.startLineNumber-t.startLineNumber:e.colorn&&(f=n-p);var g=c.color,m=this._color2Id[g];m||(m=++this._lastAssignedId,this._color2Id[g]=m,this._id2Color[m]=g);var v=new i(f-p,f+p,m);c.setColorZone(v),s.push(v)}return this._colorZonesInvalid=!1,s.sort(i.compare),s},e}()},tRuz:function(e,t,n){"use strict";var i=t;i.base=n("B6Bn"),i.short=n("wrMp"),i.mont=n("pS+P"),i.edwards=n("24Y6")},tTCp:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i="undefined"==typeof monaco?self.monaco:monaco,r={};var o,s,a={};function u(e){return a[e]||(a[e]=function(e){return(0,r[e].loader)().then(function(t){i.languages.setMonarchTokensProvider(e,t.language),i.languages.setLanguageConfiguration(e,t.conf)})}(e)),a[e]}s=(o={id:"sql",extensions:[".sql"],aliases:["SQL"],loader:function(){return n.e(25).then(n.bind(null,"77T5"))}}).id,r[s]=o,i.languages.register(o),i.languages.onLanguage(s,function(){u(s)})},tVlf:function(e,t){},tXf9:function(e,t,n){var i=n("bSQl"),r=n("+jDU"),o=n("6ZSt");t.createCipher=t.Cipher=i.createCipher,t.createCipheriv=t.Cipheriv=i.createCipheriv,t.createDecipher=t.Decipher=r.createDecipher,t.createDecipheriv=t.Decipheriv=r.createDecipheriv,t.listCiphers=t.getCiphers=function(){return Object.keys(o)}},tZcU:function(e,t,n){(function(e){(function(){"use strict";function t(e){var t=this.constructor;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){return t.reject(n)})})}var n=setTimeout;function i(){}function r(e){if(!(this instanceof r))throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],c(e,this)}function o(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,r._immediateFn(function(){var n=1===e._state?t.onFulfilled:t.onRejected;if(null!==n){var i;try{i=n(e._value)}catch(e){return void a(t.promise,e)}s(t.promise,i)}else(1===e._state?s:a)(t.promise,e._value)})):e._deferreds.push(t)}function s(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var n=t.then;if(t instanceof r)return e._state=3,e._value=t,void u(e);if("function"==typeof n)return void c((i=n,o=t,function(){i.apply(o,arguments)}),e)}e._state=1,e._value=t,u(e)}catch(t){a(e,t)}var i,o}function a(e,t){e._state=2,e._value=t,u(e)}function u(e){2===e._state&&0===e._deferreds.length&&r._immediateFn(function(){e._handled||r._unhandledRejectionFn(e._value)});for(var t=0,n=e._deferreds.length;t>8,s=255&r;o?n.push(o,s):n.push(s)}return n},i.zero2=r,i.toHex=o,i.encode=function(e,t){return"hex"===t?o(e):e}},tqet:function(e,t,n){"use strict";t.g=function(e){return"function"==typeof e.dispose&&0===e.dispose.length},t.f=a,t.e=function(){for(var e=[],t=0;t>>0)>>>0},t.f=function(e,t){if(0===e)return null;var n=(65535&e)>>>0,i=(4294901760&e)>>>16;if(0!==i)return new d([c(n,t),c(i,t)]);return new d([c(n,t)])},n.d(t,"e",function(){return l}),n.d(t,"d",function(){return h}),n.d(t,"c",function(){return f});var i,r=n("zxiH"),o=function(){function e(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}return e.prototype.define=function(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e},e.prototype.keyCodeToStr=function(e){return this._keyCodeToStr[e]},e.prototype.strToKeyCode=function(e){return this._strToKeyCode[e.toLowerCase()]||0},e}(),s=new o,a=new o,u=new o;function c(e,t){var n=!!(2048&e),i=!!(256&e);return new l(2===t?i:n,!!(1024&e),!!(512&e),2===t?n:i,255&e)}!function(){function e(e,t,n,i){void 0===n&&(n=t),void 0===i&&(i=n),s.define(e,t),a.define(e,n),u.define(e,i)}e(0,"unknown"),e(1,"Backspace"),e(2,"Tab"),e(3,"Enter"),e(4,"Shift"),e(5,"Ctrl"),e(6,"Alt"),e(7,"PauseBreak"),e(8,"CapsLock"),e(9,"Escape"),e(10,"Space"),e(11,"PageUp"),e(12,"PageDown"),e(13,"End"),e(14,"Home"),e(15,"LeftArrow","Left"),e(16,"UpArrow","Up"),e(17,"RightArrow","Right"),e(18,"DownArrow","Down"),e(19,"Insert"),e(20,"Delete"),e(21,"0"),e(22,"1"),e(23,"2"),e(24,"3"),e(25,"4"),e(26,"5"),e(27,"6"),e(28,"7"),e(29,"8"),e(30,"9"),e(31,"A"),e(32,"B"),e(33,"C"),e(34,"D"),e(35,"E"),e(36,"F"),e(37,"G"),e(38,"H"),e(39,"I"),e(40,"J"),e(41,"K"),e(42,"L"),e(43,"M"),e(44,"N"),e(45,"O"),e(46,"P"),e(47,"Q"),e(48,"R"),e(49,"S"),e(50,"T"),e(51,"U"),e(52,"V"),e(53,"W"),e(54,"X"),e(55,"Y"),e(56,"Z"),e(57,"Meta"),e(58,"ContextMenu"),e(59,"F1"),e(60,"F2"),e(61,"F3"),e(62,"F4"),e(63,"F5"),e(64,"F6"),e(65,"F7"),e(66,"F8"),e(67,"F9"),e(68,"F10"),e(69,"F11"),e(70,"F12"),e(71,"F13"),e(72,"F14"),e(73,"F15"),e(74,"F16"),e(75,"F17"),e(76,"F18"),e(77,"F19"),e(78,"NumLock"),e(79,"ScrollLock"),e(80,";",";","OEM_1"),e(81,"=","=","OEM_PLUS"),e(82,",",",","OEM_COMMA"),e(83,"-","-","OEM_MINUS"),e(84,".",".","OEM_PERIOD"),e(85,"/","/","OEM_2"),e(86,"`","`","OEM_3"),e(110,"ABNT_C1"),e(111,"ABNT_C2"),e(87,"[","[","OEM_4"),e(88,"\\","\\","OEM_5"),e(89,"]","]","OEM_6"),e(90,"'","'","OEM_7"),e(91,"OEM_8"),e(92,"OEM_102"),e(93,"NumPad0"),e(94,"NumPad1"),e(95,"NumPad2"),e(96,"NumPad3"),e(97,"NumPad4"),e(98,"NumPad5"),e(99,"NumPad6"),e(100,"NumPad7"),e(101,"NumPad8"),e(102,"NumPad9"),e(103,"NumPad_Multiply"),e(104,"NumPad_Add"),e(105,"NumPad_Separator"),e(106,"NumPad_Subtract"),e(107,"NumPad_Decimal"),e(108,"NumPad_Divide")}(),function(e){e.toString=function(e){return s.keyCodeToStr(e)},e.fromString=function(e){return s.strToKeyCode(e)},e.toUserSettingsUS=function(e){return a.keyCodeToStr(e)},e.toUserSettingsGeneral=function(e){return u.keyCodeToStr(e)},e.fromUserSettings=function(e){return a.strToKeyCode(e)||u.strToKeyCode(e)}}(i||(i={}));var l=function(){function e(e,t,n,i,r){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=i,this.keyCode=r}return e.prototype.equals=function(e){return this.ctrlKey===e.ctrlKey&&this.shiftKey===e.shiftKey&&this.altKey===e.altKey&&this.metaKey===e.metaKey&&this.keyCode===e.keyCode},e.prototype.isModifierKey=function(){return 0===this.keyCode||5===this.keyCode||57===this.keyCode||6===this.keyCode||4===this.keyCode},e.prototype.toChord=function(){return new d([this])},e.prototype.isDuplicateModifierCase=function(){return this.ctrlKey&&5===this.keyCode||this.shiftKey&&4===this.keyCode||this.altKey&&6===this.keyCode||this.metaKey&&57===this.keyCode},e}(),d=function(){function e(e){if(0===e.length)throw Object(r.b)("parts");this.parts=e}return e.prototype.equals=function(e){if(null===e)return!1;if(this.parts.length!==e.parts.length)return!1;for(var t=0;t0)return c(new Error("invalid "+l.join(",")+" option for "+typeof e+" payload"))}if(void 0!==e.exp&&void 0!==r.expiresIn)return c(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void 0!==e.nbf&&void 0!==r.notBefore)return c(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){m(p,!1,e,"options")}(r)}catch(e){return c(e)}var d=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:a&&(e.iat=d),void 0!==r.notBefore){try{e.nbf=i(r.notBefore,d)}catch(e){return c(e)}if(void 0===e.nbf)return c(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void 0!==r.expiresIn&&"object"==typeof e){try{e.exp=i(r.expiresIn,d)}catch(e){return c(e)}if(void 0===e.exp)return c(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(v).forEach(function(t){var n=v[t];if(void 0!==r[t]){if(void 0!==e[n])return c(new Error('Bad "options.'+t+'" option. The payload already has an "'+n+'" property.'));e[n]=r[t]}});var f=r.encoding||"utf8";if("function"!=typeof s)return o.sign({header:u,payload:e,secret:n,encoding:f});s=s&&h(s),o.createSign({header:u,privateKey:n,payload:e,encoding:f}).once("error",s).once("done",function(e){s(null,e)})}}).call(t,n("EuP9").Buffer)},ujcs:function(e,t){t.read=function(e,t,n,i,r){var o,s,a=8*r-i-1,u=(1<>1,l=-7,d=n?r-1:0,h=n?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-l)-1,f>>=-l,l+=a;l>0;o=256*o+e[t+d],d+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=i;l>0;s=256*s+e[t+d],d+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,i),o-=c}return(f?-1:1)*s*Math.pow(2,o-i)},t.write=function(e,t,n,i,r,o){var s,a,u,c=8*o-r-1,l=(1<>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:o-1,p=i?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+d>=1?h/u:h*Math.pow(2,1-d))*u>=2&&(s++,u/=2),s+d>=l?(a=0,s=l):s+d>=1?(a=(t*u-1)*Math.pow(2,r),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,r),s=0));r>=8;e[n+f]=255&a,f+=p,a/=256,r-=8);for(s=s<0;e[n+f]=255&s,f+=p,s/=256,c-=8);e[n+f-p]|=128*g}},vMHI:function(e,t){var n="[object Boolean]",i=Object.prototype.toString;e.exports=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},vORD:function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("JVO/"),r=Object(i.c)("codeEditorService")},vTy2:function(e,t,n){"use strict";n.d(t,"a",function(){return r});var i=n("artP"),r=function(){function e(e,t,n,i){e>n||e===n&&t>i?(this.startLineNumber=n,this.startColumn=i,this.endLineNumber=e,this.endColumn=t):(this.startLineNumber=e,this.startColumn=t,this.endLineNumber=n,this.endColumn=i)}return e.prototype.isEmpty=function(){return e.isEmpty(this)},e.isEmpty=function(e){return e.startLineNumber===e.endLineNumber&&e.startColumn===e.endColumn},e.prototype.containsPosition=function(t){return e.containsPosition(this,t)},e.containsPosition=function(e,t){return!(t.lineNumbere.endLineNumber)&&(!(t.lineNumber===e.startLineNumber&&t.columne.endColumn))},e.prototype.containsRange=function(t){return e.containsRange(this,t)},e.containsRange=function(e,t){return!(t.startLineNumbere.endLineNumber||t.endLineNumber>e.endLineNumber)&&(!(t.startLineNumber===e.startLineNumber&&t.startColumne.endColumn)))},e.prototype.strictContainsRange=function(t){return e.strictContainsRange(this,t)},e.strictContainsRange=function(e,t){return!(t.startLineNumbere.endLineNumber||t.endLineNumber>e.endLineNumber)&&(!(t.startLineNumber===e.startLineNumber&&t.startColumn<=e.startColumn)&&!(t.endLineNumber===e.endLineNumber&&t.endColumn>=e.endColumn)))},e.prototype.plusRange=function(t){return e.plusRange(this,t)},e.plusRange=function(t,n){var i,r,o,s;return n.startLineNumbert.endLineNumber?(o=n.endLineNumber,s=n.endColumn):n.endLineNumber===t.endLineNumber?(o=n.endLineNumber,s=Math.max(n.endColumn,t.endColumn)):(o=t.endLineNumber,s=t.endColumn),new e(i,r,o,s)},e.prototype.intersectRanges=function(t){return e.intersectRanges(this,t)},e.intersectRanges=function(t,n){var i=t.startLineNumber,r=t.startColumn,o=t.endLineNumber,s=t.endColumn,a=n.startLineNumber,u=n.startColumn,c=n.endLineNumber,l=n.endColumn;return ic?(o=c,s=l):o===c&&(s=Math.min(s,l)),i>o?null:i===o&&r>s?null:new e(i,r,o,s)},e.prototype.equalsRange=function(t){return e.equalsRange(this,t)},e.equalsRange=function(e,t){return!!e&&!!t&&e.startLineNumber===t.startLineNumber&&e.startColumn===t.startColumn&&e.endLineNumber===t.endLineNumber&&e.endColumn===t.endColumn},e.prototype.getEndPosition=function(){return new i.a(this.endLineNumber,this.endColumn)},e.prototype.getStartPosition=function(){return new i.a(this.startLineNumber,this.startColumn)},e.prototype.toString=function(){return"["+this.startLineNumber+","+this.startColumn+" -> "+this.endLineNumber+","+this.endColumn+"]"},e.prototype.setEndPosition=function(t,n){return new e(this.startLineNumber,this.startColumn,t,n)},e.prototype.setStartPosition=function(t,n){return new e(t,n,this.endLineNumber,this.endColumn)},e.prototype.collapseToStart=function(){return e.collapseToStart(this)},e.collapseToStart=function(t){return new e(t.startLineNumber,t.startColumn,t.startLineNumber,t.startColumn)},e.fromPositions=function(t,n){return void 0===n&&(n=t),new e(t.lineNumber,t.column,n.lineNumber,n.column)},e.lift=function(t){return t?new e(t.startLineNumber,t.startColumn,t.endLineNumber,t.endColumn):null},e.isIRange=function(e){return e&&"number"==typeof e.startLineNumber&&"number"==typeof e.startColumn&&"number"==typeof e.endLineNumber&&"number"==typeof e.endColumn},e.areIntersectingOrTouching=function(e,t){return!(e.endLineNumbere.startLineNumber},e}()},vWx2:function(e,t,n){var i=n("LC74"),r=n("EuP9").Buffer,o=n("reGU");function s(e){o.call(this,e),this.enc="pem"}i(s,o),e.exports=s,s.prototype.decode=function(e,t){for(var n=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,a=-1,u=-1,c=0;c=u?r=Math.max(r,u+c-i):(t[n++]=new R(i,r),i=u,r=c)}return t[n++]=new R(i,r),t},e._createHorizontalRangesFromClientRects=function(e,t){if(!e||0===e.length)return null;for(var n=[],i=0,r=e.length;ia)return null;(t=Math.min(a,Math.max(0,t)))!==(i=Math.min(a,Math.max(0,i)))&&i>0&&0===r&&(i--,r=1073741824);var u=e.children[t].firstChild,c=e.children[i].firstChild;if(u&&c||(!u&&0===n&&t>0&&(u=e.children[t-1].firstChild,n=1073741824),!c&&0===r&&i>0&&(c=e.children[i-1].firstChild,r=1073741824)),!u||!c)return null;n=Math.min(u.textContent.length,Math.max(0,n)),r=Math.min(c.textContent.length,Math.max(0,r));var l=this._readClientRects(u,n,c,r,s);return this._createHorizontalRangesFromClientRects(l,o)},e}(),W=n("t7eM"),B=n("Qxje"),V=n("eoic"),H=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),z=!!_.e||!(_.c||g.i||g.l),U=g.g,K=function(){function e(e,t){this._domNode=e,this._clientRectDeltaLeft=0,this._clientRectDeltaLeftRead=!1,this.endNode=t}return Object.defineProperty(e.prototype,"clientRectDeltaLeft",{get:function(){return this._clientRectDeltaLeftRead||(this._clientRectDeltaLeftRead=!0,this._clientRectDeltaLeft=this._domNode.getBoundingClientRect().left),this._clientRectDeltaLeft},enumerable:!0,configurable:!0}),e}(),q=function(){function e(e,t){this.themeType=t,this.renderWhitespace=e.editor.viewInfo.renderWhitespace,this.renderControlCharacters=e.editor.viewInfo.renderControlCharacters,this.spaceWidth=e.editor.fontInfo.spaceWidth,this.useMonospaceOptimizations=e.editor.fontInfo.isMonospace&&!e.editor.viewInfo.disableMonospaceOptimizations,this.canUseHalfwidthRightwardsArrow=e.editor.fontInfo.canUseHalfwidthRightwardsArrow,this.lineHeight=e.editor.lineHeight,this.stopRenderingLineAfter=e.editor.viewInfo.stopRenderingLineAfter,this.fontLigatures=e.editor.viewInfo.fontLigatures}return e.prototype.equals=function(e){return this.themeType===e.themeType&&this.renderWhitespace===e.renderWhitespace&&this.renderControlCharacters===e.renderControlCharacters&&this.spaceWidth===e.spaceWidth&&this.useMonospaceOptimizations===e.useMonospaceOptimizations&&this.canUseHalfwidthRightwardsArrow===e.canUseHalfwidthRightwardsArrow&&this.lineHeight===e.lineHeight&&this.stopRenderingLineAfter===e.stopRenderingLineAfter&&this.fontLigatures===e.fontLigatures},e}(),G=function(){function e(e){this._options=e,this._isMaybeInvalid=!0,this._renderedViewLine=null}return e.prototype.getDomNode=function(){return this._renderedViewLine&&this._renderedViewLine.domNode?this._renderedViewLine.domNode.domNode:null},e.prototype.setDomNode=function(e){if(!this._renderedViewLine)throw new Error("I have no rendered view line to set the dom node to...");this._renderedViewLine.domNode=Object(f.b)(e)},e.prototype.onContentChanged=function(){this._isMaybeInvalid=!0},e.prototype.onTokensChanged=function(){this._isMaybeInvalid=!0},e.prototype.onDecorationsChanged=function(){this._isMaybeInvalid=!0},e.prototype.onOptionsChanged=function(e){this._isMaybeInvalid=!0,this._options=e},e.prototype.onSelectionChanged=function(){return!(!U&&this._options.themeType!==V.b&&"selection"!==this._options.renderWhitespace)&&(this._isMaybeInvalid=!0,!0)},e.prototype.renderLine=function(t,n,i,r){if(!1===this._isMaybeInvalid)return!1;this._isMaybeInvalid=!1;var o=i.getViewLineRenderingData(t),s=this._options,a=W.a.filter(o.inlineDecorations,t,o.minColumn,o.maxColumn),u=null;if(U||s.themeType===V.b||"selection"===this._options.renderWhitespace)for(var c=0,l=i.selections;ct)){var h=d.startLineNumber===t?d.startColumn:o.minColumn,f=d.endLineNumber===t?d.endColumn:o.maxColumn;h');var g=Object(B.d)(p,r);r.appendASCIIString("

    ");var m=null;return z&&o.isBasicASCII&&s.useMonospaceOptimizations&&0===g.containsForeignElements&&o.content.length<300&&p.lineTokens.getCount()<100&&(m=new Z(this._renderedViewLine?this._renderedViewLine.domNode:null,p,g.characterMapping)),m||(m=$(this._renderedViewLine?this._renderedViewLine.domNode:null,p,g.characterMapping,g.containsRTL,g.containsForeignElements)),this._renderedViewLine=m,!0},e.prototype.layoutLine=function(e,t){this._renderedViewLine&&this._renderedViewLine.domNode&&(this._renderedViewLine.domNode.setTop(t),this._renderedViewLine.domNode.setHeight(this._options.lineHeight))},e.prototype.getWidth=function(){return this._renderedViewLine?this._renderedViewLine.getWidth():0},e.prototype.getWidthIsFast=function(){return!this._renderedViewLine||this._renderedViewLine.getWidthIsFast()},e.prototype.getVisibleRangesForRange=function(e,t,n){if(!this._renderedViewLine)return null;e|=0,t|=0,e=Math.min(this._renderedViewLine.input.lineContent.length+1,Math.max(1,e)),t=Math.min(this._renderedViewLine.input.lineContent.length+1,Math.max(1,t));var i=0|this._renderedViewLine.input.stopRenderingLineAfter;return-1!==i&&e>i&&t>i?null:(-1!==i&&e>i&&(e=i),-1!==i&&t>i&&(t=i),this._renderedViewLine.getVisibleRangesForRange(e,t,n))},e.prototype.getColumnOfNodeOffset=function(e,t,n){return this._renderedViewLine?this._renderedViewLine.getColumnOfNodeOffset(e,t,n):1},e.CLASS_NAME="view-line",e}(),Z=function(){function e(e,t,n){this.domNode=e,this.input=t,this._characterMapping=n,this._charWidth=t.spaceWidth}return e.prototype.getWidth=function(){return this._getCharPosition(this._characterMapping.length)},e.prototype.getWidthIsFast=function(){return!0},e.prototype.getVisibleRangesForRange=function(e,t,n){var i=this._getCharPosition(e),r=this._getCharPosition(t);return[new R(i,r-i)]},e.prototype._getCharPosition=function(e){var t=this._characterMapping.getAbsoluteOffsets();return 0===t.length?0:Math.round(this._charWidth*t[e-1])},e.prototype.getColumnOfNodeOffset=function(e,t,n){for(var i=t.textContent.length,r=-1;t;)t=t.previousSibling,r++;return this._characterMapping.partDataToCharOffset(r,i,n)+1},e}(),Y=function(){function e(e,t,n,i,r){if(this.domNode=e,this.input=t,this._characterMapping=n,this._isWhitespaceOnly=/^\s*$/.test(t.lineContent),this._containsForeignElements=r,this._cachedWidth=-1,this._pixelOffsetCache=null,!i||0===this._characterMapping.length){this._pixelOffsetCache=new Int32Array(Math.max(2,this._characterMapping.length+1));for(var o=0,s=this._characterMapping.length;o<=s;o++)this._pixelOffsetCache[o]=-1}}return e.prototype._getReadingTarget=function(){return this.domNode.domNode.firstChild},e.prototype.getWidth=function(){return-1===this._cachedWidth&&(this._cachedWidth=this._getReadingTarget().offsetWidth),this._cachedWidth},e.prototype.getWidthIsFast=function(){return-1!==this._cachedWidth},e.prototype.getVisibleRangesForRange=function(e,t,n){if(null!==this._pixelOffsetCache){var i=this._readPixelOffset(e,n);if(-1===i)return null;var r=this._readPixelOffset(t,n);return-1===r?null:[new R(i,r-i)]}return this._readVisibleRangesForRange(e,t,n)},e.prototype._readVisibleRangesForRange=function(e,t,n){if(e===t){var i=this._readPixelOffset(e,n);return-1===i?null:[new R(i,0)]}return this._readRawVisibleRangesForRange(e,t,n)},e.prototype._readPixelOffset=function(e,t){if(0===this._characterMapping.length){if(0===this._containsForeignElements)return 0;if(2===this._containsForeignElements)return 0;if(1===this._containsForeignElements)return this.getWidth()}if(null!==this._pixelOffsetCache){var n=this._pixelOffsetCache[e];if(-1!==n)return n;var i=this._actualReadPixelOffset(e,t);return this._pixelOffsetCache[e]=i,i}return this._actualReadPixelOffset(e,t)},e.prototype._actualReadPixelOffset=function(e,t){if(0===this._characterMapping.length){var n=j.readHorizontalRanges(this._getReadingTarget(),0,0,0,0,t.clientRectDeltaLeft,t.endNode);return n&&0!==n.length?n[0].left:-1}if(e===this._characterMapping.length&&this._isWhitespaceOnly&&0===this._containsForeignElements)return this.getWidth();var i=this._characterMapping.charOffsetToPartData(e-1),r=B.a.getPartIndex(i),o=B.a.getCharIndex(i),s=j.readHorizontalRanges(this._getReadingTarget(),r,o,r,o,t.clientRectDeltaLeft,t.endNode);return s&&0!==s.length?s[0].left:-1},e.prototype._readRawVisibleRangesForRange=function(e,t,n){if(1===e&&t===this._characterMapping.length)return[new R(0,this.getWidth())];var i=this._characterMapping.charOffsetToPartData(e-1),r=B.a.getPartIndex(i),o=B.a.getCharIndex(i),s=this._characterMapping.charOffsetToPartData(t-1),a=B.a.getPartIndex(s),u=B.a.getCharIndex(s);return j.readHorizontalRanges(this._getReadingTarget(),r,o,a,u,n.clientRectDeltaLeft,n.endNode)},e.prototype.getColumnOfNodeOffset=function(e,t,n){for(var i=t.textContent.length,r=-1;t;)t=t.previousSibling,r++;return this._characterMapping.partDataToCharOffset(r,i,n)+1},e}(),X=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return H(t,e),t.prototype._readVisibleRangesForRange=function(t,n,i){var r=e.prototype._readVisibleRangesForRange.call(this,t,n,i);if(!r||0===r.length||t===n||1===t&&n===this._characterMapping.length)return r;if(!this.input.containsRTL){var o=this._readPixelOffset(n,i);if(-1!==o){var s=r[r.length-1];s.left=4&&3===e[0]&&7===e[3]},e.isStrictChildOfViewLines=function(e){return e.length>4&&3===e[0]&&7===e[3]},e.isChildOfScrollableElement=function(e){return e.length>=2&&3===e[0]&&5===e[1]},e.isChildOfMinimap=function(e){return e.length>=2&&3===e[0]&&8===e[1]},e.isChildOfContentWidgets=function(e){return e.length>=4&&3===e[0]&&1===e[3]},e.isChildOfOverflowingContentWidgets=function(e){return e.length>=1&&2===e[0]},e.isChildOfOverlayWidgets=function(e){return e.length>=2&&3===e[0]&&4===e[1]},e}(),se=function(){function e(e,t,n){this.model=e.model,this.layoutInfo=e.configuration.editor.layoutInfo,this.viewDomNode=t.viewDomNode,this.lineHeight=e.configuration.editor.lineHeight,this.typicalHalfwidthCharacterWidth=e.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,this.lastViewCursorsRenderData=n,this._context=e,this._viewHelper=t}return e.prototype.getZoneAtCoord=function(t){return e.getZoneAtCoord(this._context,t)},e.getZoneAtCoord=function(e,t){var n=e.viewLayout.getWhitespaceAtVerticalOffset(t);if(n){var i=n.verticalOffset+n.height/2,r=e.model.getLineCount(),o=null,s=void 0,a=null;return n.afterLineNumber!==r&&(a=new ee.a(n.afterLineNumber+1,1)),n.afterLineNumber>0&&(o=new ee.a(n.afterLineNumber,e.model.getLineMaxColumn(n.afterLineNumber))),s=null===a?o:null===o?a:t=e.layoutInfo.glyphMarginLeft,this.isInContentArea=!this.isInMarginArea,this.mouseColumn=Math.max(0,le._getMouseColumn(this.mouseContentHorizontalOffset,e.typicalHalfwidthCharacterWidth))}}()),ue={isAfterLines:!0};function ce(e){return{isAfterLines:!1,horizontalDistanceToText:e}}var le=function(){function e(e,t){this._context=e,this._viewHelper=t}return e.prototype.mouseTargetIsWidget=function(e){var t=e.target,n=M.collect(t,this._viewHelper.viewDomNode);return!(!oe.isChildOfContentWidgets(n)&&!oe.isChildOfOverflowingContentWidgets(n))||!!oe.isChildOfOverlayWidgets(n)},e.prototype.createMouseTarget=function(t,n,i,r){var o=new se(this._context,this._viewHelper,t),s=new ae(o,n,i,r);try{return e._createMouseTarget(o,s,!1)}catch(e){return s.fulfill(0)}},e._createMouseTarget=function(t,n,i){if(null===n.target){if(i)return n.fulfill(0);var r=e._doHitTest(t,n);return r.position?e.createMouseTargetFromHitTestPosition(t,n,r.position.lineNumber,r.position.column):this._createMouseTarget(t,n.withTarget(r.hitTarget),!0)}var o=n,s=null;return(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=s||e._hitTestContentWidget(t,o))||e._hitTestOverlayWidget(t,o))||e._hitTestMinimap(t,o))||e._hitTestScrollbarSlider(t,o))||e._hitTestViewZone(t,o))||e._hitTestMargin(t,o))||e._hitTestViewCursor(t,o))||e._hitTestTextArea(t,o))||e._hitTestViewLines(t,o,i))||e._hitTestScrollbar(t,o))||n.fulfill(0)},e._hitTestContentWidget=function(e,t){if(oe.isChildOfContentWidgets(t.targetPath)||oe.isChildOfOverflowingContentWidgets(t.targetPath)){var n=e.findAttribute(t.target,"widgetId");return n?t.fulfill(9,null,null,n):t.fulfill(0)}return null},e._hitTestOverlayWidget=function(e,t){if(oe.isChildOfOverlayWidgets(t.targetPath)){var n=e.findAttribute(t.target,"widgetId");return n?t.fulfill(12,null,null,n):t.fulfill(0)}return null},e._hitTestViewCursor=function(e,t){if(t.target)for(var n=0,i=o=e.lastViewCursorsRenderData;nr.contentLeft+r.width)){var l=e.getVerticalOffsetForLineNumber(r.position.lineNumber);if(l<=a&&a<=l+r.height)return t.fulfill(6,r.position)}}return null},e._hitTestViewZone=function(e,t){var n=e.getZoneAtCoord(t.mouseVerticalOffset);if(n){var i=t.isInContentArea?8:5;return t.fulfill(i,n.position,null,n)}return null},e._hitTestTextArea=function(e,t){return oe.isTextArea(t.targetPath)?t.fulfill(1):null},e._hitTestMargin=function(e,t){if(t.isInMarginArea){var n=e.getFullLineRangeAtCoord(t.mouseVerticalOffset),i=n.range.getStartPosition(),r=Math.abs(t.pos.x-t.editorPos.x),o={isAfterLines:n.isAfterLines,glyphMarginLeft:e.layoutInfo.glyphMarginLeft,glyphMarginWidth:e.layoutInfo.glyphMarginWidth,lineNumbersWidth:e.layoutInfo.lineNumbersWidth,offsetX:r};return(r-=e.layoutInfo.glyphMarginLeft)<=e.layoutInfo.glyphMarginWidth?t.fulfill(2,i,n.range,o):(r-=e.layoutInfo.glyphMarginWidth)<=e.layoutInfo.lineNumbersWidth?t.fulfill(3,i,n.range,o):(r-=e.layoutInfo.lineNumbersWidth,t.fulfill(4,i,n.range,o))}return null},e._hitTestViewLines=function(t,n,i){if(!oe.isChildOfViewLines(n.targetPath))return null;if(t.isAfterLines(n.mouseVerticalOffset)){var r=t.model.getLineCount(),o=t.model.getLineMaxColumn(r);return n.fulfill(7,new ee.a(r,o),void 0,ue)}if(i){if(oe.isStrictChildOfViewLines(n.targetPath)){var s=t.getLineNumberAtVerticalOffset(n.mouseVerticalOffset);if(0===t.model.getLineLength(s)){var a=t.getLineWidth(s),u=ce(n.mouseContentHorizontalOffset-a);return n.fulfill(7,new ee.a(s,1),void 0,u)}}return n.fulfill(0)}var c=e._doHitTest(t,n);return c.position?e.createMouseTargetFromHitTestPosition(t,n,c.position.lineNumber,c.position.column):this._createMouseTarget(t,n.withTarget(c.hitTarget),!0)},e._hitTestMinimap=function(e,t){if(oe.isChildOfMinimap(t.targetPath)){var n=e.getLineNumberAtVerticalOffset(t.mouseVerticalOffset),i=e.model.getLineMaxColumn(n);return t.fulfill(11,new ee.a(n,i))}return null},e._hitTestScrollbarSlider=function(e,t){if(oe.isChildOfScrollableElement(t.targetPath)&&t.target&&1===t.target.nodeType){var n=t.target.className;if(n&&/\b(slider|scrollbar)\b/.test(n)){var i=e.getLineNumberAtVerticalOffset(t.mouseVerticalOffset),r=e.model.getLineMaxColumn(i);return t.fulfill(11,new ee.a(i,r))}}return null},e._hitTestScrollbar=function(e,t){if(oe.isChildOfScrollableElement(t.targetPath)){var n=e.getLineNumberAtVerticalOffset(t.mouseVerticalOffset),i=e.model.getLineMaxColumn(n);return t.fulfill(11,new ee.a(n,i))}return null},e.prototype.getMouseColumn=function(t,n){var i=this._context.configuration.editor.layoutInfo,r=this._context.viewLayout.getCurrentScrollLeft()+n.x-t.x-i.contentLeft;return e._getMouseColumn(r,this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth)},e._getMouseColumn=function(e,t){return e<0?1:Math.round(e/t)+1},e.createMouseTargetFromHitTestPosition=function(e,t,n,i){var r=new ee.a(n,i),o=e.getLineWidth(n);if(t.mouseContentHorizontalOffset>o){if(g.f&&1===r.column){var s=ce(t.mouseContentHorizontalOffset-o);return t.fulfill(7,new ee.a(n,e.model.getLineMaxColumn(n)),void 0,s)}var a=ce(t.mouseContentHorizontalOffset-o);return t.fulfill(7,r,void 0,a)}var u=e.visibleRangeForPosition2(n,i);if(!u)return t.fulfill(0,r);var c=u.left;if(t.mouseContentHorizontalOffset===c)return t.fulfill(6,r);var l=[];if(l.push({offset:u.left,column:i}),i>1){var d=e.visibleRangeForPosition2(n,i-1);d&&l.push({offset:d.left,column:i-1})}if(i=t.editorPos.y+e.layoutInfo.height&&(r=t.editorPos.y+e.layoutInfo.height-1);var o=new w(t.pos.x,r),s=this._actualDoHitTestWithCaretRangeFromPoint(e,o.toClientCoordinates());return s.position?s:this._actualDoHitTestWithCaretRangeFromPoint(e,t.pos.toClientCoordinates())},e._actualDoHitTestWithCaretRangeFromPoint=function(e,t){var n=document.caretRangeFromPoint(t.clientX,t.clientY);if(!n||!n.startContainer)return{position:null,hitTarget:null};var i=n.startContainer,r=null;if(i.nodeType===i.TEXT_NODE){var o=(a=(s=i.parentNode)?s.parentNode:null)?a.parentNode:null;if((o&&o.nodeType===o.ELEMENT_NODE?o.className:null)===G.CLASS_NAME)return{position:e.getPositionFromDOMInfo(s,n.startOffset),hitTarget:null};r=i.parentNode}else if(i.nodeType===i.ELEMENT_NODE){var s,a;if(((a=(s=i.parentNode)?s.parentNode:null)&&a.nodeType===a.ELEMENT_NODE?a.className:null)===G.CLASS_NAME)return{position:e.getPositionFromDOMInfo(i,i.textContent.length),hitTarget:null};r=i}return{position:null,hitTarget:r}},e._doHitTestWithCaretPositionFromPoint=function(e,t){var n=document.caretPositionFromPoint(t.clientX,t.clientY);if(n.offsetNode.nodeType===n.offsetNode.TEXT_NODE){var i=n.offsetNode.parentNode,r=i?i.parentNode:null,o=r?r.parentNode:null;return(o&&o.nodeType===o.ELEMENT_NODE?o.className:null)===G.CLASS_NAME?{position:e.getPositionFromDOMInfo(n.offsetNode.parentNode,n.offset),hitTarget:null}:{position:null,hitTarget:n.offsetNode.parentNode}}return{position:null,hitTarget:n.offsetNode}},e._doHitTestWithMoveToPoint=function(e,t){var n=null,i=null,r=document.body.createTextRange();try{r.moveToPoint(t.clientX,t.clientY)}catch(e){return{position:null,hitTarget:null}}r.collapse(!0);var o=r?r.parentElement():null,s=o?o.parentNode:null,a=s?s.parentNode:null;if((a&&a.nodeType===a.ELEMENT_NODE?a.className:"")===G.CLASS_NAME){var u=r.duplicate();u.moveToElementText(o),u.setEndPoint("EndToStart",r),n=e.getPositionFromDOMInfo(o,u.text.length),u.moveToElementText(e.viewDomNode)}else i=o;return r.moveToElementText(e.viewDomNode),{position:n,hitTarget:i}},e._doHitTest=function(e,t){return document.caretRangeFromPoint?this._doHitTestWithCaretRangeFromPoint(e,t):document.caretPositionFromPoint?this._doHitTestWithCaretPositionFromPoint(e,t.pos.toClientCoordinates()):document.body.createTextRange?this._doHitTestWithMoveToPoint(e,t.pos.toClientCoordinates()):{position:null,hitTarget:null}},e}(),de=n("G8r4"),he=n("iHM7"),fe=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();function pe(e){return function(t,n){var i=!1;return e&&(i=e.mouseTargetIsWidget(n)),i||n.preventDefault(),n}}var ge=function(e){function t(n,i,r){var s=e.call(this)||this;s._isFocused=!1,s._context=n,s.viewController=i,s.viewHelper=r,s.mouseTargetFactory=new le(s._context,r),s._mouseDownOperation=s._register(new me(s._context,s.viewController,s.viewHelper,function(e,t){return s._createMouseTarget(e,t)},function(e){return s._getMouseColumn(e)})),s._asyncFocus=s._register(new v.d(function(){return s.viewHelper.focusTextArea()},0)),s.lastMouseLeaveTime=-1;var a=new O(s.viewHelper.viewDomNode);s._register(a.onContextMenu(s.viewHelper.viewDomNode,function(e){return s._onContextMenu(e,!0)})),s._register(a.onMouseMoveThrottled(s.viewHelper.viewDomNode,function(e){return s._onMouseMove(e)},pe(s.mouseTargetFactory),t.MOUSE_MOVE_MINIMUM_TIME)),s._register(a.onMouseUp(s.viewHelper.viewDomNode,function(e){return s._onMouseUp(e)})),s._register(a.onMouseLeave(s.viewHelper.viewDomNode,function(e){return s._onMouseLeave(e)})),s._register(a.onMouseDown(s.viewHelper.viewDomNode,function(e){return s._onMouseDown(e)}));return s._register(o.h(s.viewHelper.viewDomNode,g.g?"mousewheel":"wheel",function(e){if(s.viewController.emitMouseWheel(e),s._context.configuration.editor.viewInfo.mouseWheelZoom){var t=new m.c(e);if(t.browserEvent.ctrlKey||t.browserEvent.metaKey){var n=de.a.getZoomLevel(),i=t.deltaY>0?1:-1;de.a.setZoomLevel(n+i),t.preventDefault(),t.stopPropagation()}}},!0)),s._context.addEventHandler(s),s}return fe(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),e.prototype.dispose.call(this)},t.prototype.onCursorStateChanged=function(e){return this._mouseDownOperation.onCursorStateChanged(e),!1},t.prototype.onFocusChanged=function(e){return this._isFocused=e.isFocused,!1},t.prototype.onScrollChanged=function(e){return this._mouseDownOperation.onScrollChanged(),!1},t.prototype.getTargetAtClientPoint=function(e,t){var n=new C(e,t).toPageCoordinates(),i=x(this.viewHelper.viewDomNode);if(n.yi.y+i.height||n.xi.x+i.width)return null;var r=this.viewHelper.getLastViewCursorsRenderData();return this.mouseTargetFactory.createMouseTarget(r,i,n,null)},t.prototype._createMouseTarget=function(e,t){var n=this.viewHelper.getLastViewCursorsRenderData();return this.mouseTargetFactory.createMouseTarget(n,e.editorPos,e.pos,t?e.target:null)},t.prototype._getMouseColumn=function(e){return this.mouseTargetFactory.getMouseColumn(e.editorPos,e.pos)},t.prototype._onContextMenu=function(e,t){this.viewController.emitContextMenu({event:e,target:this._createMouseTarget(e,t)})},t.prototype._onMouseMove=function(e){this._mouseDownOperation.isActive()||(e.timestampt.y+t.height){var a,u;o=i.getCurrentScrollTop()+(e.posy-t.y);if(a=se.getZoneAtCoord(this._context,o))if(u=this._helpPositionJumpOverViewZone(a))return new re(null,13,r,u);var c=i.getLineNumberAtVerticalOffset(o);return new re(null,13,r,new ee.a(c,n.getLineMaxColumn(c)))}var l=i.getLineNumberAtVerticalOffset(i.getCurrentScrollTop()+(e.posy-t.y));return e.posxt.x+t.width?new re(null,13,r,new ee.a(l,n.getLineMaxColumn(l))):null},t.prototype._findMousePosition=function(e,t){var n=this._getPositionOutsideEditor(e);if(n)return n;var i=this._createMouseTarget(e,t);if(!i.position)return null;if(8===i.type||5===i.type){var r=this._helpPositionJumpOverViewZone(i.detail);if(r)return new re(i.element,i.type,i.mouseColumn,r,null,i.detail)}return i},t.prototype._helpPositionJumpOverViewZone=function(e){var t=new ee.a(this._currentSelection.selectionStartLineNumber,this._currentSelection.selectionStartColumn),n=e.positionBefore,i=e.positionAfter;return n&&i?n.isBefore(t)?n:i:null},t.prototype._dispatchMouse=function(e,t){e.position&&this._viewController.dispatchMouse({position:e.position,mouseColumn:e.mouseColumn,startedOnLineNumbers:this._mouseState.startedOnLineNumbers,inSelectionMode:t,mouseDownCount:this._mouseState.count,altKey:this._mouseState.altKey,ctrlKey:this._mouseState.ctrlKey,metaKey:this._mouseState.metaKey,shiftKey:this._mouseState.shiftKey,leftButton:this._mouseState.leftButton,middleButton:this._mouseState.middleButton})},t}(u.a),ve=function(){function e(){this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._leftButton=!1,this._middleButton=!1,this._startedOnLineNumbers=!1,this._lastMouseDownPosition=null,this._lastMouseDownPositionEqualCount=0,this._lastMouseDownCount=0,this._lastSetMouseDownCountTime=0,this.isDragAndDrop=!1}return Object.defineProperty(e.prototype,"altKey",{get:function(){return this._altKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ctrlKey",{get:function(){return this._ctrlKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"metaKey",{get:function(){return this._metaKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shiftKey",{get:function(){return this._shiftKey},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftButton",{get:function(){return this._leftButton},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"middleButton",{get:function(){return this._middleButton},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"startedOnLineNumbers",{get:function(){return this._startedOnLineNumbers},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._lastMouseDownCount},enumerable:!0,configurable:!0}),e.prototype.setModifiers=function(e){this._altKey=e.altKey,this._ctrlKey=e.ctrlKey,this._metaKey=e.metaKey,this._shiftKey=e.shiftKey},e.prototype.setStartButtons=function(e){this._leftButton=e.leftButton,this._middleButton=e.middleButton},e.prototype.setStartedOnLineNumbers=function(e){this._startedOnLineNumbers=e},e.prototype.trySetCount=function(t,n){var i=(new Date).getTime();i-this._lastSetMouseDownCountTime>e.CLEAR_MOUSE_DOWN_COUNT_TIME&&(t=1),this._lastSetMouseDownCountTime=i,t>this._lastMouseDownCount+1&&(t=this._lastMouseDownCount+1),this._lastMouseDownPosition&&this._lastMouseDownPosition.equals(n)?this._lastMouseDownPositionEqualCount++:this._lastMouseDownPositionEqualCount=1,this._lastMouseDownPosition=n,this._lastMouseDownCount=Math.min(t,this._lastMouseDownPositionEqualCount)},e.CLEAR_MOUSE_DOWN_COUNT_TIME=400,e}(),_e=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();function be(e,t){var n={translationY:t.translationY,translationX:t.translationX};return e&&(n.translationY+=e.translationY,n.translationX+=e.translationX),n}var ye=function(e){function t(t,n,i){var r=e.call(this,t,n,i)||this;return r.viewHelper.linesContentDomNode.style.msTouchAction="none",r.viewHelper.linesContentDomNode.style.msContentZooming="none",r._installGestureHandlerTimeout=window.setTimeout(function(){if(r._installGestureHandlerTimeout=-1,window.MSGesture){var e=new MSGesture,t=new MSGesture;e.target=r.viewHelper.linesContentDomNode,t.target=r.viewHelper.linesContentDomNode,r.viewHelper.linesContentDomNode.addEventListener("MSPointerDown",function(n){var i=n.pointerType;i!==(n.MSPOINTER_TYPE_MOUSE||"mouse")?i===(n.MSPOINTER_TYPE_TOUCH||"touch")?(r._lastPointerType="touch",e.addPointer(n.pointerId)):(r._lastPointerType="pen",t.addPointer(n.pointerId)):r._lastPointerType="mouse"}),r._register(o.j(r.viewHelper.linesContentDomNode,"MSGestureChange",function(e){return r._onGestureChange(e)},be)),r._register(o.h(r.viewHelper.linesContentDomNode,"MSGestureTap",function(e){return r._onCaptureGestureTap(e)},!0))}},100),r._lastPointerType="mouse",r}return _e(t,e),t.prototype._onMouseDown=function(t){"mouse"===this._lastPointerType&&e.prototype._onMouseDown.call(this,t)},t.prototype._onCaptureGestureTap=function(e){var t=this,n=new L(e,this.viewHelper.viewDomNode),i=this._createMouseTarget(n,!1);i.position&&this.viewController.moveTo(i.position),n.browserEvent.fromElement?(n.preventDefault(),this.viewHelper.focusTextArea()):setTimeout(function(){t.viewHelper.focusTextArea()})},t.prototype._onGestureChange=function(e){this._context.viewLayout.deltaScrollNow(-e.translationX,-e.translationY)},t.prototype.dispose=function(){window.clearTimeout(this._installGestureHandlerTimeout),e.prototype.dispose.call(this)},t}(ge),we=function(e){function t(t,n,i){var r=e.call(this,t,n,i)||this;return r.viewHelper.linesContentDomNode.style.touchAction="none",r._installGestureHandlerTimeout=window.setTimeout(function(){if(r._installGestureHandlerTimeout=-1,window.MSGesture){var e=new MSGesture,t=new MSGesture;e.target=r.viewHelper.linesContentDomNode,t.target=r.viewHelper.linesContentDomNode,r.viewHelper.linesContentDomNode.addEventListener("pointerdown",function(n){var i=n.pointerType;"mouse"!==i?"touch"===i?(r._lastPointerType="touch",e.addPointer(n.pointerId)):(r._lastPointerType="pen",t.addPointer(n.pointerId)):r._lastPointerType="mouse"}),r._register(o.j(r.viewHelper.linesContentDomNode,"MSGestureChange",function(e){return r._onGestureChange(e)},be)),r._register(o.h(r.viewHelper.linesContentDomNode,"MSGestureTap",function(e){return r._onCaptureGestureTap(e)},!0))}},100),r._lastPointerType="mouse",r}return _e(t,e),t.prototype._onMouseDown=function(t){"mouse"===this._lastPointerType&&e.prototype._onMouseDown.call(this,t)},t.prototype._onCaptureGestureTap=function(e){var t=this,n=new L(e,this.viewHelper.viewDomNode),i=this._createMouseTarget(n,!1);i.position&&this.viewController.moveTo(i.position),n.browserEvent.fromElement?(n.preventDefault(),this.viewHelper.focusTextArea()):setTimeout(function(){t.viewHelper.focusTextArea()})},t.prototype._onGestureChange=function(e){this._context.viewLayout.deltaScrollNow(-e.translationX,-e.translationY)},t.prototype.dispose=function(){window.clearTimeout(this._installGestureHandlerTimeout),e.prototype.dispose.call(this)},t}(ge),Ce=function(e){function t(t,n,i){var r=e.call(this,t,n,i)||this;return p.b.addTarget(r.viewHelper.linesContentDomNode),r._register(o.h(r.viewHelper.linesContentDomNode,p.a.Tap,function(e){return r.onTap(e)})),r._register(o.h(r.viewHelper.linesContentDomNode,p.a.Change,function(e){return r.onChange(e)})),r._register(o.h(r.viewHelper.linesContentDomNode,p.a.Contextmenu,function(e){return r._onContextMenu(new L(e,r.viewHelper.viewDomNode),!1)})),r}return _e(t,e),t.prototype.onTap=function(e){e.preventDefault(),this.viewHelper.focusTextArea();var t=this._createMouseTarget(new L(e,this.viewHelper.viewDomNode),!1);t.position&&this.viewController.moveTo(t.position)},t.prototype.onChange=function(e){this._context.viewLayout.deltaScrollNow(-e.translationX,-e.translationY)},t}(ge),Se=function(e){function t(t,n,i){var r=e.call(this)||this;return window.navigator.msPointerEnabled?r.handler=r._register(new ye(t,n,i)):window.TouchEvent?r.handler=r._register(new Ce(t,n,i)):window.navigator.pointerEnabled||window.PointerEvent?r.handler=r._register(new we(t,n,i)):r.handler=r._register(new ge(t,n,i)),r}return _e(t,e),t.prototype.getTargetAtClientPoint=function(e,t){return this.handler.getTargetAtClientPoint(e,t)},t}(u.a),xe=(n("9vcT"),n("aL7J")),Le=n("4QaN"),Oe=n("ZWAj"),ke=(n("7Do+"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),Ne=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ke(t,e),t}(E),Ee=n("Rfe2"),Ie=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),De=function(e){function t(t){var n=e.call(this)||this;return n._context=t,n._readConfig(),n._lastCursorModelPosition=new ee.a(1,1),n._renderResult=null,n._context.addEventHandler(n),n}return Ie(t,e),t.prototype._readConfig=function(){var e=this._context.configuration.editor;this._lineHeight=e.lineHeight,this._renderLineNumbers=e.viewInfo.renderLineNumbers,this._renderCustomLineNumbers=e.viewInfo.renderCustomLineNumbers,this._renderFinalNewline=e.viewInfo.renderFinalNewline,this._lineNumbersLeft=e.layoutInfo.lineNumbersLeft,this._lineNumbersWidth=e.layoutInfo.lineNumbersWidth},t.prototype.dispose=function(){this._context.removeEventHandler(this),this._renderResult=null,e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return this._readConfig(),!0},t.prototype.onCursorStateChanged=function(e){var t=e.selections[0].getPosition();return this._lastCursorModelPosition=this._context.model.coordinatesConverter.convertViewPositionToModelPosition(t),2===this._renderLineNumbers||3===this._renderLineNumbers},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesChanged=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return e.scrollTopChanged},t.prototype.onZonesChanged=function(e){return!0},t.prototype._getLineRenderLineNumber=function(e){var t=this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new ee.a(e,1));if(1!==t.column)return"";var n=t.lineNumber;if(!this._renderFinalNewline){var i=this._context.model.getLineCount(),r=this._context.model.getLineContent(n);if(n===i&&""===r)return""}if(this._renderCustomLineNumbers)return this._renderCustomLineNumbers(n);if(2===this._renderLineNumbers){var o=Math.abs(this._lastCursorModelPosition.lineNumber-n);return 0===o?''+n+"":String(o)}return 3===this._renderLineNumbers?this._lastCursorModelPosition.lineNumber===n?String(n):n%10==0?String(n):"":String(n)},t.prototype.prepareRender=function(e){if(0!==this._renderLineNumbers){for(var n=_.c?this._lineHeight%2==0?" lh-even":" lh-odd":"",i=e.visibleRange.startLineNumber,r=e.visibleRange.endLineNumber,o='
    ',s=[],a=i;a<=r;a++){var u=a-i,c=this._getLineRenderLineNumber(a);s[u]=c?o+c+"
    ":""}this._renderResult=s}else this._renderResult=null},t.prototype.render=function(e,t){if(!this._renderResult)return"";var n=t-e;return n<0||n>=this._renderResult.length?"":this._renderResult[n]},t.CLASS_NAME="line-numbers",t}(Ne);Object(V.f)(function(e,t){var n=e.getColor(Ee.k);n&&t.addRule(".monaco-editor .line-numbers { color: "+n+"; }");var i=e.getColor(Ee.b);i&&t.addRule(".monaco-editor .current-line ~ .line-numbers { color: "+i+"; }")});var Me=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Te=function(e){function t(n){var i=e.call(this,n)||this;return i._canUseLayerHinting=i._context.configuration.editor.canUseLayerHinting,i._contentLeft=i._context.configuration.editor.layoutInfo.contentLeft,i._glyphMarginLeft=i._context.configuration.editor.layoutInfo.glyphMarginLeft,i._glyphMarginWidth=i._context.configuration.editor.layoutInfo.glyphMarginWidth,i._domNode=Object(f.b)(document.createElement("div")),i._domNode.setClassName(t.OUTER_CLASS_NAME),i._domNode.setPosition("absolute"),i._domNode.setAttribute("role","presentation"),i._domNode.setAttribute("aria-hidden","true"),i._glyphMarginBackgroundDomNode=Object(f.b)(document.createElement("div")),i._glyphMarginBackgroundDomNode.setClassName(t.CLASS_NAME),i._domNode.appendChild(i._glyphMarginBackgroundDomNode),i}return Me(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.getDomNode=function(){return this._domNode},t.prototype.onConfigurationChanged=function(e){return e.canUseLayerHinting&&(this._canUseLayerHinting=this._context.configuration.editor.canUseLayerHinting),e.layoutInfo&&(this._contentLeft=this._context.configuration.editor.layoutInfo.contentLeft,this._glyphMarginLeft=this._context.configuration.editor.layoutInfo.glyphMarginLeft,this._glyphMarginWidth=this._context.configuration.editor.layoutInfo.glyphMarginWidth),!0},t.prototype.onScrollChanged=function(t){return e.prototype.onScrollChanged.call(this,t)||t.scrollTopChanged},t.prototype.prepareRender=function(e){},t.prototype.render=function(e){this._domNode.setLayerHinting(this._canUseLayerHinting);var t=e.scrollTop-e.bigNumbersDelta;this._domNode.setTop(-t);var n=Math.min(e.scrollHeight,1e6);this._domNode.setHeight(n),this._domNode.setWidth(this._contentLeft),this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft),this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth),this._glyphMarginBackgroundDomNode.setHeight(n)},t.CLASS_NAME="glyph-margin",t.OUTER_CLASS_NAME="margin",t}(D),Pe=n("BwcV"),Ae=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Re=function(){return function(e){this.type=1,this.canUseLayerHinting=e.canUseLayerHinting,this.pixelRatio=e.pixelRatio,this.editorClassName=e.editorClassName,this.lineHeight=e.lineHeight,this.readOnly=e.readOnly,this.accessibilitySupport=e.accessibilitySupport,this.emptySelectionClipboard=e.emptySelectionClipboard,this.copyWithSyntaxHighlighting=e.copyWithSyntaxHighlighting,this.layoutInfo=e.layoutInfo,this.fontInfo=e.fontInfo,this.viewInfo=e.viewInfo,this.wrappingInfo=e.wrappingInfo}}(),Fe=function(){return function(e){this.type=2,this.selections=e}}(),je=function(){return function(){this.type=3}}(),We=function(){return function(){this.type=4}}(),Be=function(){return function(e){this.type=5,this.isFocused=e}}(),Ve=function(){return function(){this.type=6}}(),He=function(){return function(e,t){this.type=7,this.fromLineNumber=e,this.toLineNumber=t}}(),ze=function(){return function(e,t){this.type=8,this.fromLineNumber=e,this.toLineNumber=t}}(),Ue=function(){return function(e,t){this.type=9,this.fromLineNumber=e,this.toLineNumber=t}}(),Ke=function(){return function(e,t,n,i){this.type=10,this.range=e,this.verticalType=t,this.revealHorizontal=n,this.scrollType=i}}(),qe=function(){return function(e){this.type=11,this.scrollWidth=e.scrollWidth,this.scrollLeft=e.scrollLeft,this.scrollHeight=e.scrollHeight,this.scrollTop=e.scrollTop,this.scrollWidthChanged=e.scrollWidthChanged,this.scrollLeftChanged=e.scrollLeftChanged,this.scrollHeightChanged=e.scrollHeightChanged,this.scrollTopChanged=e.scrollTopChanged}}(),Ge=function(){return function(e){this.type=12,this.ranges=e}}(),Ze=function(){return function(){this.type=15}}(),Ye=function(){return function(){this.type=13}}(),Xe=function(){return function(){this.type=14}}(),$e=function(){return function(){this.type=16}}(),Je=function(e){function t(){var t=e.call(this)||this;return t._listeners=[],t._collector=null,t._collectorCnt=0,t}return Ae(t,e),t.prototype.dispose=function(){this._listeners=[],e.prototype.dispose.call(this)},t.prototype._beginEmit=function(){return this._collectorCnt++,1===this._collectorCnt&&(this._collector=new Qe),this._collector},t.prototype._endEmit=function(){if(this._collectorCnt--,0===this._collectorCnt){var e=this._collector.finalize();this._collector=null,e.length>0&&this._emit(e)}},t.prototype._emit=function(e){for(var t=this._listeners.slice(0),n=0,i=t.length;n0)return new Oe.b(i,i.length,i.length,n,n)}}return Oe.b.EMPTY}return Oe.a.fromEditorSelection(e,s,r._selections[0],0===r._accessibilitySupport)},deduceModelPosition:function(e,t,n){return r._context.model.deduceModelPositionRelativeToViewPosition(e,t,n)}};return r._textAreaInput=r._register(new Le.b(a,r.textArea)),r._register(r._textAreaInput.onKeyDown(function(e){r._viewController.emitKeyDown(e)})),r._register(r._textAreaInput.onKeyUp(function(e){r._viewController.emitKeyUp(e)})),r._register(r._textAreaInput.onPaste(function(e){var t=rt.INSTANCE.get(e.text),n=!1,i=null;t&&(n=r._emptySelectionClipboard&&t.isFromEmptySelection,i=t.multicursorText),r._viewController.paste("keyboard",e.text,n,i)})),r._register(r._textAreaInput.onCut(function(){r._viewController.cut("keyboard")})),r._register(r._textAreaInput.onType(function(e){e.replaceCharCnt?r._viewController.replacePreviousChar("keyboard",e.text,e.replaceCharCnt):r._viewController.type("keyboard",e.text)})),r._register(r._textAreaInput.onSelectionChangeRequest(function(e){r._viewController.setSelection("keyboard",e)})),r._register(r._textAreaInput.onCompositionStart(function(){var e=r._selections[0].startLineNumber,t=r._selections[0].startColumn;r._context.privateViewEventBus.emit(new Ke(new te.a(e,t,e,t),0,!0,1));var n=r._viewHelper.visibleRangeForPositionRelativeToEditor(e,t);n&&(r._visibleTextArea=new nt(r._context.viewLayout.getVerticalOffsetForLineNumber(e),n.left,it?0:1),r._render()),r.textArea.setClassName("inputarea ime-input"),r._viewController.compositionStart("keyboard")})),r._register(r._textAreaInput.onCompositionUpdate(function(e){g.g?r._visibleTextArea=r._visibleTextArea.setWidth(0):r._visibleTextArea=r._visibleTextArea.setWidth(function(e,t){var n=document.createElement("canvas").getContext("2d");n.font=(i=t,r="normal",o=i.fontWeight,s=i.fontSize,a=i.lineHeight,u=i.fontFamily,r+" normal "+o+" "+s+"px / "+a+"px "+u);var i,r,o,s,a,u;var c=n.measureText(e);return g.i?c.width+2:c.width}(e.data,r._fontInfo)),r._render()})),r._register(r._textAreaInput.onCompositionEnd(function(){r._visibleTextArea=null,r._render(),r.textArea.setClassName("inputarea"),r._viewController.compositionEnd("keyboard")})),r._register(r._textAreaInput.onFocus(function(){r._context.privateViewEventBus.emit(new Be(!0))})),r._register(r._textAreaInput.onBlur(function(){r._context.privateViewEventBus.emit(new Be(!1))})),r}return tt(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype._getWordBeforePosition=function(e){for(var t=this._context.model.getLineContent(e.lineNumber),n=Object(Pe.a)(this._context.configuration.editor.wordSeparators),i=e.column,r=0;i>1;){var o=t.charCodeAt(i-2);if(0!==n.get(o)||r>50)return t.substring(i-1,e.column-1);r++,i--}return t.substring(0,e.column-1)},t.prototype._getCharacterBeforePosition=function(e){if(e.column>1){var t=this._context.model.getLineContent(e.lineNumber).charAt(e.column-2);if(!xe.w(t.charCodeAt(0)))return t}return""},t.prototype.onConfigurationChanged=function(e){var t=this._context.configuration.editor;return e.fontInfo&&(this._fontInfo=t.fontInfo),e.viewInfo&&this.textArea.setAttribute("aria-label",t.viewInfo.ariaLabel),e.layoutInfo&&(this._contentLeft=t.layoutInfo.contentLeft,this._contentWidth=t.layoutInfo.contentWidth,this._contentHeight=t.layoutInfo.contentHeight),e.lineHeight&&(this._lineHeight=t.lineHeight),e.accessibilitySupport&&(this._accessibilitySupport=t.accessibilitySupport,this._textAreaInput.writeScreenReaderContent("strategy changed")),e.emptySelectionClipboard&&(this._emptySelectionClipboard=t.emptySelectionClipboard),e.copyWithSyntaxHighlighting&&(this._copyWithSyntaxHighlighting=t.copyWithSyntaxHighlighting),!0},t.prototype.onCursorStateChanged=function(e){return this._selections=e.selections.slice(0),this._textAreaInput.writeScreenReaderContent("selection changed"),!0},t.prototype.onDecorationsChanged=function(e){return!0},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesChanged=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return this._scrollLeft=e.scrollLeft,this._scrollTop=e.scrollTop,!0},t.prototype.onZonesChanged=function(e){return!0},t.prototype.isFocused=function(){return this._textAreaInput.isFocused()},t.prototype.focusTextArea=function(){this._textAreaInput.focusTextArea()},t.prototype.prepareRender=function(e){var t=new ee.a(this._selections[0].positionLineNumber,this._selections[0].positionColumn);this._primaryCursorVisibleRange=e.visibleRangeForPosition(t)},t.prototype.render=function(e){this._textAreaInput.writeScreenReaderContent("render"),this._render()},t.prototype._render=function(){if(this._visibleTextArea)this._renderInsideEditor(this._visibleTextArea.top-this._scrollTop,this._contentLeft+this._visibleTextArea.left-this._scrollLeft,this._visibleTextArea.width,this._lineHeight,!0);else if(this._primaryCursorVisibleRange){var e=this._contentLeft+this._primaryCursorVisibleRange.left-this._scrollLeft;if(ethis._contentLeft+this._contentWidth)this._renderAtTopLeft();else{var t=this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber)-this._scrollTop;t<0||t>this._contentHeight?this._renderAtTopLeft():this._renderInsideEditor(t,e,it?0:1,it?0:1,!1)}}else this._renderAtTopLeft()},t.prototype._renderInsideEditor=function(e,t,n,i,r){var o=this.textArea,s=this.textAreaCover;r?l.a.applyFontInfo(o,this._fontInfo):(o.setFontSize(1),o.setLineHeight(this._fontInfo.lineHeight)),o.setTop(e),o.setLeft(t),o.setWidth(n),o.setHeight(i),s.setTop(0),s.setLeft(0),s.setWidth(0),s.setHeight(0)},t.prototype._renderAtTopLeft=function(){var e=this.textArea,t=this.textAreaCover;if(l.a.applyFontInfo(e,this._fontInfo),e.setTop(0),e.setLeft(0),t.setTop(0),t.setLeft(0),it)return e.setWidth(0),e.setHeight(0),t.setWidth(0),void t.setHeight(0);e.setWidth(1),e.setHeight(1),t.setWidth(1),t.setHeight(1),this._context.configuration.editor.viewInfo.glyphMargin?t.setClassName("monaco-editor-background textAreaCover "+Te.OUTER_CLASS_NAME):0!==this._context.configuration.editor.viewInfo.renderLineNumbers?t.setClassName("monaco-editor-background textAreaCover "+De.CLASS_NAME):t.setClassName("monaco-editor-background textAreaCover")},t}(D);var st=n("HZsc"),at=function(){function e(e,t,n,i){this.configuration=e,this.viewModel=t,this.outgoingEvents=n,this.commandDelegate=i}return e.prototype._execMouseCommand=function(e,t){t.source="mouse",this.commandDelegate.executeEditorCommand(e,t)},e.prototype.paste=function(e,t,n,i){this.commandDelegate.paste(e,t,n,i)},e.prototype.type=function(e,t){this.commandDelegate.type(e,t)},e.prototype.replacePreviousChar=function(e,t,n){this.commandDelegate.replacePreviousChar(e,t,n)},e.prototype.compositionStart=function(e){this.commandDelegate.compositionStart(e)},e.prototype.compositionEnd=function(e){this.commandDelegate.compositionEnd(e)},e.prototype.cut=function(e){this.commandDelegate.cut(e)},e.prototype.setSelection=function(e,t){this.commandDelegate.executeEditorCommand(st.CoreNavigationCommands.SetSelection,{source:e,selection:t})},e.prototype._validateViewColumn=function(e){var t=this.viewModel.getLineMinColumn(e.lineNumber);return e.column=4?this._selectAll():3===e.mouseDownCount?this._hasMulticursorModifier(e)?e.inSelectionMode?this._lastCursorLineSelectDrag(e.position):this._lastCursorLineSelect(e.position):e.inSelectionMode?this._lineSelectDrag(e.position):this._lineSelect(e.position):2===e.mouseDownCount?this._hasMulticursorModifier(e)?this._lastCursorWordSelect(e.position):e.inSelectionMode?this._wordSelectDrag(e.position):this._wordSelect(e.position):this._hasMulticursorModifier(e)?this._hasNonMulticursorModifier(e)||(e.shiftKey?this._columnSelect(e.position,e.mouseColumn,!1):e.inSelectionMode?this._lastCursorMoveToSelect(e.position):this._createCursor(e.position,!1)):e.inSelectionMode?e.altKey?this._columnSelect(e.position,e.mouseColumn,!0):this._moveToSelect(e.position):this.moveTo(e.position)},e.prototype._usualArgs=function(e){return e=this._validateViewColumn(e),{position:this._convertViewToModelPosition(e),viewPosition:e}},e.prototype.moveTo=function(e){this._execMouseCommand(st.CoreNavigationCommands.MoveTo,this._usualArgs(e))},e.prototype._moveToSelect=function(e){this._execMouseCommand(st.CoreNavigationCommands.MoveToSelect,this._usualArgs(e))},e.prototype._columnSelect=function(e,t,n){e=this._validateViewColumn(e),this._execMouseCommand(st.CoreNavigationCommands.ColumnSelect,{position:this._convertViewToModelPosition(e),viewPosition:e,mouseColumn:t,setAnchorIfNotSet:n})},e.prototype._createCursor=function(e,t){e=this._validateViewColumn(e),this._execMouseCommand(st.CoreNavigationCommands.CreateCursor,{position:this._convertViewToModelPosition(e),viewPosition:e,wholeLine:t})},e.prototype._lastCursorMoveToSelect=function(e){this._execMouseCommand(st.CoreNavigationCommands.LastCursorMoveToSelect,this._usualArgs(e))},e.prototype._wordSelect=function(e){this._execMouseCommand(st.CoreNavigationCommands.WordSelect,this._usualArgs(e))},e.prototype._wordSelectDrag=function(e){this._execMouseCommand(st.CoreNavigationCommands.WordSelectDrag,this._usualArgs(e))},e.prototype._lastCursorWordSelect=function(e){this._execMouseCommand(st.CoreNavigationCommands.LastCursorWordSelect,this._usualArgs(e))},e.prototype._lineSelect=function(e){this._execMouseCommand(st.CoreNavigationCommands.LineSelect,this._usualArgs(e))},e.prototype._lineSelectDrag=function(e){this._execMouseCommand(st.CoreNavigationCommands.LineSelectDrag,this._usualArgs(e))},e.prototype._lastCursorLineSelect=function(e){this._execMouseCommand(st.CoreNavigationCommands.LastCursorLineSelect,this._usualArgs(e))},e.prototype._lastCursorLineSelectDrag=function(e){this._execMouseCommand(st.CoreNavigationCommands.LastCursorLineSelectDrag,this._usualArgs(e))},e.prototype._selectAll=function(){this._execMouseCommand(st.CoreNavigationCommands.SelectAll,{})},e.prototype._convertViewToModelPosition=function(e){return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(e)},e.prototype.emitKeyDown=function(e){this.outgoingEvents.emitKeyDown(e)},e.prototype.emitKeyUp=function(e){this.outgoingEvents.emitKeyUp(e)},e.prototype.emitContextMenu=function(e){this.outgoingEvents.emitContextMenu(e)},e.prototype.emitMouseMove=function(e){this.outgoingEvents.emitMouseMove(e)},e.prototype.emitMouseLeave=function(e){this.outgoingEvents.emitMouseLeave(e)},e.prototype.emitMouseUp=function(e){this.outgoingEvents.emitMouseUp(e)},e.prototype.emitMouseDown=function(e){this.outgoingEvents.emitMouseDown(e)},e.prototype.emitMouseDrag=function(e){this.outgoingEvents.emitMouseDrag(e)},e.prototype.emitMouseDrop=function(e){this.outgoingEvents.emitMouseDrop(e)},e.prototype.emitMouseWheel=function(e){this.outgoingEvents.emitMouseWheel(e)},e}(),ut=n("ftXN"),ct=function(){function e(e){this._createLine=e,this._set(1,[])}return e.prototype.flush=function(){this._set(1,[])},e.prototype._set=function(e,t){this._lines=t,this._rendLineNumberStart=e},e.prototype._get=function(){return{rendLineNumberStart:this._rendLineNumberStart,lines:this._lines}},e.prototype.getStartLineNumber=function(){return this._rendLineNumberStart},e.prototype.getEndLineNumber=function(){return this._rendLineNumberStart+this._lines.length-1},e.prototype.getCount=function(){return this._lines.length},e.prototype.getLine=function(e){var t=e-this._rendLineNumberStart;if(t<0||t>=this._lines.length)throw new Error("Illegal value for lineNumber");return this._lines[t]},e.prototype.onLinesDeleted=function(e,t){if(0===this.getCount())return null;var n=this.getStartLineNumber(),i=this.getEndLineNumber();if(ti)return null;for(var o=0,s=0,a=n;a<=i;a++){var u=a-this._rendLineNumberStart;e<=a&&a<=t&&(0===s?(o=u,s=1):s++)}if(e=n&&o<=i&&(this._lines[o-this._rendLineNumberStart].onContentChanged(),r=!0);return r},e.prototype.onLinesInserted=function(e,t){if(0===this.getCount())return null;var n=t-e+1,i=this.getStartLineNumber(),r=this.getEndLineNumber();if(e<=i)return this._rendLineNumberStart+=n,null;if(e>r)return null;if(n+e>r)return this._lines.splice(e-this._rendLineNumberStart,r-e+1);for(var o=[],s=0;sn))for(var a=Math.max(t,s.fromLineNumber),u=Math.min(n,s.toLineNumber),c=a;c<=u;c++){var l=c-this._rendLineNumberStart;this._lines[l].onTokensChanged(),i=!0}}return i},e}(),lt=function(){function e(e){var t=this;this._host=e,this.domNode=this._createDomNode(),this._linesCollection=new ct(function(){return t._host.createVisibleLine()})}return e.prototype._createDomNode=function(){var e=Object(f.b)(document.createElement("div"));return e.setClassName("view-layer"),e.setPosition("absolute"),e.domNode.setAttribute("role","presentation"),e.domNode.setAttribute("aria-hidden","true"),e},e.prototype.onConfigurationChanged=function(e){return e.layoutInfo},e.prototype.onFlushed=function(e){return this._linesCollection.flush(),!0},e.prototype.onLinesChanged=function(e){return this._linesCollection.onLinesChanged(e.fromLineNumber,e.toLineNumber)},e.prototype.onLinesDeleted=function(e){var t=this._linesCollection.onLinesDeleted(e.fromLineNumber,e.toLineNumber);if(t)for(var n=0,i=t.length;nt)(u=t)<=(s=Math.min(n,r.rendLineNumberStart-1))&&(this._insertLinesBefore(r,u,s,i,t),r.linesLength+=s-u+1);else if(r.rendLineNumberStart0&&(this._removeLinesBefore(r,a),r.linesLength-=a)}if(r.rendLineNumberStart=t,r.rendLineNumberStart+r.linesLength-1n){var s,a,u=Math.max(0,n-r.rendLineNumberStart+1);(a=(s=r.linesLength-1)-u+1)>0&&(this._removeLinesAfter(r,a),r.linesLength-=a)}return this._finishRendering(r,!1,i),r},e.prototype._renderUntouchedLines=function(e,t,n,i,r){for(var o=e.rendLineNumberStart,s=e.lines,a=t;a<=n;a++){var u=o+a;s[a].layoutLine(u,i[u-r])}},e.prototype._insertLinesBefore=function(e,t,n,i,r){for(var o=[],s=0,a=t;a<=n;a++)o[s++]=this.host.createVisibleLine();e.lines=o.concat(e.lines)},e.prototype._removeLinesBefore=function(e,t){for(var n=0;n=0;s--){var a=e.lines[s];i[s]&&(a.setDomNode(o),o=o.previousSibling)}},e.prototype._finishRenderingInvalidLines=function(e,t,n){var i=document.createElement("div");i.innerHTML=t;for(var r=0;r'),i.appendASCIIString(r),i.appendASCIIString(""),!0)},e.prototype.layoutLine=function(e,t){this._domNode&&(this._domNode.setTop(t),this._domNode.setHeight(this._lineHeight))},e}(),gt=function(e){function t(t){var n=e.call(this,t)||this;return n._contentWidth=n._context.configuration.editor.layoutInfo.contentWidth,n.domNode.setHeight(0),n}return ht(t,e),t.prototype.onConfigurationChanged=function(t){return t.layoutInfo&&(this._contentWidth=this._context.configuration.editor.layoutInfo.contentWidth),e.prototype.onConfigurationChanged.call(this,t)},t.prototype.onScrollChanged=function(t){return e.prototype.onScrollChanged.call(this,t)||t.scrollWidthChanged},t.prototype._viewOverlaysRender=function(t){e.prototype._viewOverlaysRender.call(this,t),this.domNode.setWidth(Math.max(t.scrollWidth,this._contentWidth))},t}(ft),mt=function(e){function t(t){var n=e.call(this,t)||this;return n._contentLeft=n._context.configuration.editor.layoutInfo.contentLeft,n.domNode.setClassName("margin-view-overlays"),n.domNode.setWidth(1),l.a.applyFontInfo(n.domNode,n._context.configuration.editor.fontInfo),n}return ht(t,e),t.prototype.onConfigurationChanged=function(t){var n=!1;return t.fontInfo&&(l.a.applyFontInfo(this.domNode,this._context.configuration.editor.fontInfo),n=!0),t.layoutInfo&&(this._contentLeft=this._context.configuration.editor.layoutInfo.contentLeft,n=!0),e.prototype.onConfigurationChanged.call(this,t)||n},t.prototype.onScrollChanged=function(t){return e.prototype.onScrollChanged.call(this,t)||t.scrollHeightChanged},t.prototype._viewOverlaysRender=function(t){e.prototype._viewOverlaysRender.call(this,t);var n=Math.min(t.scrollHeight,1e6);this.domNode.setHeight(n),this.domNode.setWidth(this._contentLeft)},t}(ft),vt=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),_t=function(){return function(e,t){this.top=e,this.left=t}}(),bt=function(e){function t(t,n){var i=e.call(this,t)||this;return i._viewDomNode=n,i._widgets={},i.domNode=Object(f.b)(document.createElement("div")),M.write(i.domNode,1),i.domNode.setClassName("contentWidgets"),i.domNode.setPosition("absolute"),i.domNode.setTop(0),i.overflowingContentWidgetsDomNode=Object(f.b)(document.createElement("div")),M.write(i.overflowingContentWidgetsDomNode,2),i.overflowingContentWidgetsDomNode.setClassName("overflowingContentWidgets"),i}return vt(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._widgets={}},t.prototype.onConfigurationChanged=function(e){for(var t=0,n=Object.keys(this._widgets);t=i,l=a,d=r.viewportHeight-a>=i,h=e.left,f=t.left;return h+n>r.scrollLeft+r.viewportWidth&&(h=r.scrollLeft+r.viewportWidth-n),f+n>r.scrollLeft+r.viewportWidth&&(f=r.scrollLeft+r.viewportWidth-n),h=22,y=g+i<=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-22;m+n+20>_&&(m-=s=m-(_-n-20),d-=s);v+n+20>_&&(v-=s=v-(_-n-20),h-=s);m<0&&(m-=s=m,d-=s);v<0&&(v-=s=v,h-=s);return this._fixedOverflowWidgets&&(c=p,l=g,d=m,h=v),{fitsAbove:b,aboveTop:c,aboveLeft:d,fitsBelow:y,belowTop:l,belowLeft:h}},e.prototype._prepareRenderWidgetAtExactPositionOverflowing=function(e){return new _t(e.top,e.left+this._contentLeft)},e.prototype._getTopAndBottomLeft=function(e){if(!this._viewPosition)return[null,null];var t=e.visibleRangeForPosition(this._viewPosition);if(!t)return[null,null];var n=e.getVerticalOffsetForLineNumber(this._viewPosition.lineNumber)-e.scrollTop,i=new _t(n,t.left),r=this._viewPosition.lineNumber,o=t.left;if(this._viewRange){var s=e.linesVisibleRangesForRange(this._viewRange,!1);if(s&&s.length>0)for(var a=s.length-1;a>=0;a--){var u=s[a];if(u.lineNumber>=r){u.lineNumber>r&&(r=u.lineNumber,o=1073741824);for(var c=0,l=u.ranges.length;ce.endLineNumber||this.domNode.setMaxWidth(this._maxWidth))},e.prototype.prepareRender=function(e){this._renderData=this._prepareRenderWidget(e)},e.prototype.render=function(e){this._renderData?(this.allowEditorOverflow?(this.domNode.setTop(this._renderData.top),this.domNode.setLeft(this._renderData.left)):(this.domNode.setTop(this._renderData.top+e.scrollTop-e.bigNumbersDelta),this.domNode.setLeft(this._renderData.left)),this._isVisible||(this.domNode.setVisibility("inherit"),this.domNode.setAttribute("monaco-visible-content-widget","true"),this._isVisible=!0)):this._isVisible&&(this.domNode.removeAttribute("monaco-visible-content-widget"),this._isVisible=!1,this.domNode.setVisibility("hidden"))},e}(),wt=(n("Eawl"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),Ct=function(e){function t(t){var n=e.call(this)||this;return n._context=t,n._lineHeight=n._context.configuration.editor.lineHeight,n._renderLineHighlight=n._context.configuration.editor.viewInfo.renderLineHighlight,n._selectionIsEmpty=!0,n._primaryCursorLineNumber=1,n._scrollWidth=0,n._contentWidth=n._context.configuration.editor.layoutInfo.contentWidth,n._context.addEventHandler(n),n}return wt(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return e.lineHeight&&(this._lineHeight=this._context.configuration.editor.lineHeight),e.viewInfo&&(this._renderLineHighlight=this._context.configuration.editor.viewInfo.renderLineHighlight),e.layoutInfo&&(this._contentWidth=this._context.configuration.editor.layoutInfo.contentWidth),!0},t.prototype.onCursorStateChanged=function(e){var t=!1,n=e.selections[0].positionLineNumber;this._primaryCursorLineNumber!==n&&(this._primaryCursorLineNumber=n,t=!0);var i=e.selections[0].isEmpty();return this._selectionIsEmpty!==i?(this._selectionIsEmpty=i,!0):t},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return e.scrollWidthChanged},t.prototype.onZonesChanged=function(e){return!0},t.prototype.prepareRender=function(e){this._scrollWidth=e.scrollWidth},t.prototype.render=function(e,t){return t===this._primaryCursorLineNumber&&this._shouldShowCurrentLine()?'
    ':""},t.prototype._shouldShowCurrentLine=function(){return("line"===this._renderLineHighlight||"all"===this._renderLineHighlight)&&this._selectionIsEmpty},t.prototype._willRenderMarginCurrentLine=function(){return"gutter"===this._renderLineHighlight||"all"===this._renderLineHighlight},t}(Ne);Object(V.f)(function(e,t){var n=e.getColor(Ee.i);if(n&&t.addRule(".monaco-editor .view-overlays .current-line { background-color: "+n+"; }"),!n||n.isTransparent()||e.defines(Ee.j)){var i=e.getColor(Ee.j);i&&(t.addRule(".monaco-editor .view-overlays .current-line { border: 2px solid "+i+"; }"),"hc"===e.type&&t.addRule(".monaco-editor .view-overlays .current-line { border-width: 1px; }"))}});n("3ZDw");var St=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),xt=function(e){function t(t){var n=e.call(this)||this;return n._context=t,n._lineHeight=n._context.configuration.editor.lineHeight,n._renderLineHighlight=n._context.configuration.editor.viewInfo.renderLineHighlight,n._selectionIsEmpty=!0,n._primaryCursorLineNumber=1,n._contentLeft=n._context.configuration.editor.layoutInfo.contentLeft,n._context.addEventHandler(n),n}return St(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return e.lineHeight&&(this._lineHeight=this._context.configuration.editor.lineHeight),e.viewInfo&&(this._renderLineHighlight=this._context.configuration.editor.viewInfo.renderLineHighlight),e.layoutInfo&&(this._contentLeft=this._context.configuration.editor.layoutInfo.contentLeft),!0},t.prototype.onCursorStateChanged=function(e){var t=!1,n=e.selections[0].positionLineNumber;this._primaryCursorLineNumber!==n&&(this._primaryCursorLineNumber=n,t=!0);var i=e.selections[0].isEmpty();return this._selectionIsEmpty!==i?(this._selectionIsEmpty=i,!0):t},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onZonesChanged=function(e){return!0},t.prototype.prepareRender=function(e){},t.prototype.render=function(e,t){if(t===this._primaryCursorLineNumber){var n="current-line";if(this._shouldShowCurrentLine())n="current-line current-line-margin"+(this._willRenderContentCurrentLine()?" current-line-margin-both":"");return'
    '}return""},t.prototype._shouldShowCurrentLine=function(){return"gutter"===this._renderLineHighlight||"all"===this._renderLineHighlight},t.prototype._willRenderContentCurrentLine=function(){return("line"===this._renderLineHighlight||"all"===this._renderLineHighlight)&&this._selectionIsEmpty},t}(Ne);Object(V.f)(function(e,t){var n=e.getColor(Ee.i);if(n)t.addRule(".monaco-editor .margin-view-overlays .current-line-margin { background-color: "+n+"; border: none; }");else{var i=e.getColor(Ee.j);i&&t.addRule(".monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid "+i+"; }"),"hc"===e.type&&t.addRule(".monaco-editor .margin-view-overlays .current-line-margin { border-width: 1px; }")}});n("84z/");var Lt=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Ot=function(e){function t(t){var n=e.call(this)||this;return n._context=t,n._lineHeight=n._context.configuration.editor.lineHeight,n._typicalHalfwidthCharacterWidth=n._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,n._renderResult=null,n._context.addEventHandler(n),n}return Lt(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),this._renderResult=null,e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return e.lineHeight&&(this._lineHeight=this._context.configuration.editor.lineHeight),e.fontInfo&&(this._typicalHalfwidthCharacterWidth=this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth),!0},t.prototype.onDecorationsChanged=function(e){return!0},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesChanged=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return e.scrollTopChanged||e.scrollWidthChanged},t.prototype.onZonesChanged=function(e){return!0},t.prototype.prepareRender=function(e){for(var t=e.getDecorationsInViewport(),n=[],i=0,r=0,o=t.length;rt.options.zIndex)return 1;var n=e.options.className,i=t.options.className;return ni?1:te.a.compareRangesUsingStarts(e.range,t.range)});for(var a=e.visibleRange.startLineNumber,u=e.visibleRange.endLineNumber,c=[],l=a;l<=u;l++){c[l-a]=""}this._renderWholeLineDecorations(e,n,c),this._renderNormalDecorations(e,n,c),this._renderResult=c},t.prototype._renderWholeLineDecorations=function(e,t,n){for(var i=String(this._lineHeight),r=e.visibleRange.startLineNumber,o=e.visibleRange.endLineNumber,s=0,a=t.length;s',l=Math.max(u.range.startLineNumber,r),d=Math.min(u.range.endLineNumber,o),h=l;h<=d;h++){n[h-r]+=c}}},t.prototype._renderNormalDecorations=function(e,t,n){for(var i=String(this._lineHeight),r=e.visibleRange.startLineNumber,o=null,s=!1,a=null,u=0,c=t.length;u';s[d]+=m}}},t.prototype.render=function(e,t){if(!this._renderResult)return"";var n=t-e;return n<0||n>=this._renderResult.length?"":this._renderResult[n]},t}(Ne),kt=n("qecS"),Nt=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Et=function(e){function t(t,n,i,r){var s=e.call(this,t)||this,a=s._context.configuration.editor.viewInfo.scrollbar,u={listenOnDomNode:i.domNode,className:"editor-scrollable "+Object(V.e)(t.theme.type),useShadows:!1,lazyRender:!0,vertical:a.vertical,horizontal:a.horizontal,verticalHasArrows:a.verticalHasArrows,horizontalHasArrows:a.horizontalHasArrows,verticalScrollbarSize:a.verticalScrollbarSize,verticalSliderSize:a.verticalSliderSize,horizontalScrollbarSize:a.horizontalScrollbarSize,horizontalSliderSize:a.horizontalSliderSize,handleMouseWheel:a.handleMouseWheel,arrowSize:a.arrowSize,mouseWheelScrollSensitivity:a.mouseWheelScrollSensitivity,fastScrollSensitivity:a.fastScrollSensitivity};s.scrollbar=s._register(new kt.c(n.domNode,u,s._context.viewLayout.scrollable)),M.write(s.scrollbar.getDomNode(),5),s.scrollbarDomNode=Object(f.b)(s.scrollbar.getDomNode()),s.scrollbarDomNode.setPosition("absolute"),s._setLayout();var c=function(e,t,n){var i={};if(t){var r=e.scrollTop;r&&(i.scrollTop=s._context.viewLayout.getCurrentScrollTop()+r,e.scrollTop=0)}if(n){var o=e.scrollLeft;o&&(i.scrollLeft=s._context.viewLayout.getCurrentScrollLeft()+o,e.scrollLeft=0)}s._context.viewLayout.setScrollPositionNow(i)};return s._register(o.h(i.domNode,"scroll",function(e){return c(i.domNode,!0,!0)})),s._register(o.h(n.domNode,"scroll",function(e){return c(n.domNode,!0,!1)})),s._register(o.h(r.domNode,"scroll",function(e){return c(r.domNode,!0,!1)})),s._register(o.h(s.scrollbarDomNode.domNode,"scroll",function(e){return c(s.scrollbarDomNode.domNode,!0,!1)})),s}return Nt(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype._setLayout=function(){var e=this._context.configuration.editor.layoutInfo;this.scrollbarDomNode.setLeft(e.contentLeft),"right"===this._context.configuration.editor.viewInfo.minimap.side?this.scrollbarDomNode.setWidth(e.contentWidth+e.minimapWidth):this.scrollbarDomNode.setWidth(e.contentWidth),this.scrollbarDomNode.setHeight(e.contentHeight)},t.prototype.getOverviewRulerLayoutInfo=function(){return this.scrollbar.getOverviewRulerLayoutInfo()},t.prototype.getDomNode=function(){return this.scrollbarDomNode},t.prototype.delegateVerticalScrollbarMouseDown=function(e){this.scrollbar.delegateVerticalScrollbarMouseDown(e)},t.prototype.onConfigurationChanged=function(e){if(e.viewInfo){var t=this._context.configuration.editor,n={handleMouseWheel:t.viewInfo.scrollbar.handleMouseWheel,mouseWheelScrollSensitivity:t.viewInfo.scrollbar.mouseWheelScrollSensitivity,fastScrollSensitivity:t.viewInfo.scrollbar.fastScrollSensitivity};this.scrollbar.updateOptions(n)}return e.layoutInfo&&this._setLayout(),!0},t.prototype.onScrollChanged=function(e){return!0},t.prototype.onThemeChanged=function(e){return this.scrollbar.updateClassName("editor-scrollable "+Object(V.e)(this._context.theme.type)),!0},t.prototype.prepareRender=function(e){},t.prototype.render=function(e){this.scrollbar.renderNow()},t}(D),It=(n("uHSv"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),Dt=function(){return function(e,t,n){this.startLineNumber=+e,this.endLineNumber=+t,this.className=String(n)}}(),Mt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return It(t,e),t.prototype._render=function(e,t,n){for(var i=[],r=e;r<=t;r++){i[r-e]=[]}if(0===n.length)return i;n.sort(function(e,t){return e.className===t.className?e.startLineNumber===t.startLineNumber?e.endLineNumber-t.endLineNumber:e.startLineNumber-t.startLineNumber:e.className',s=[],a=t;a<=n;a++){var u=a-t,c=i[u];0===c.length?s[u]="":s[u]='
    =this._renderResult.length?"":this._renderResult[n]},t}(Mt),Pt=(n("gCdB"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),At=function(e){function t(t){var n=e.call(this)||this;n._context=t,n._primaryLineNumber=0,n._lineHeight=n._context.configuration.editor.lineHeight,n._spaceWidth=n._context.configuration.editor.fontInfo.spaceWidth,n._enabled=n._context.configuration.editor.viewInfo.renderIndentGuides,n._activeIndentEnabled=n._context.configuration.editor.viewInfo.highlightActiveIndentGuide;var i=n._context.configuration.editor.wrappingInfo.wrappingColumn;return n._maxIndentLeft=-1===i?-1:i*n._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,n._renderResult=null,n._context.addEventHandler(n),n}return Pt(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),this._renderResult=null,e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){if(e.lineHeight&&(this._lineHeight=this._context.configuration.editor.lineHeight),e.fontInfo&&(this._spaceWidth=this._context.configuration.editor.fontInfo.spaceWidth),e.viewInfo&&(this._enabled=this._context.configuration.editor.viewInfo.renderIndentGuides,this._activeIndentEnabled=this._context.configuration.editor.viewInfo.highlightActiveIndentGuide),e.wrappingInfo||e.fontInfo){var t=this._context.configuration.editor.wrappingInfo.wrappingColumn;this._maxIndentLeft=-1===t?-1:t*this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth}return!0},t.prototype.onCursorStateChanged=function(e){var t=e.selections[0],n=t.isEmpty()?t.positionLineNumber:0;return this._primaryLineNumber!==n&&(this._primaryLineNumber=n,!0)},t.prototype.onDecorationsChanged=function(e){return!0},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesChanged=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return e.scrollTopChanged},t.prototype.onZonesChanged=function(e){return!0},t.prototype.onLanguageConfigurationChanged=function(e){return!0},t.prototype.prepareRender=function(e){if(this._enabled){var t=e.visibleRange.startLineNumber,n=e.visibleRange.endLineNumber,i=this._context.model.getOptions().indentSize*this._spaceWidth,r=e.scrollWidth,o=this._lineHeight,s=this._context.model.getLinesIndentGuides(t,n),a=0,u=0,c=0;if(this._activeIndentEnabled&&this._primaryLineNumber){var l=this._context.model.getActiveIndentGuide(this._primaryLineNumber,t,n);a=l.startLineNumber,u=l.endLineNumber,c=l.indent}for(var d=[],h=t;h<=n;h++){for(var f=a<=h&&h<=u,p=h-t,g=s[p],m="",v=e.visibleRangeForPosition(new ee.a(h,1)),_=v?v.left:0,b=1;b<=g;b++){if(m+='
    ',(_+=i)>r||this._maxIndentLeft>0&&_>this._maxIndentLeft)break}d[p]=m}this._renderResult=d}else this._renderResult=null},t.prototype.render=function(e,t){if(!this._renderResult)return"";var n=t-e;return n<0||n>=this._renderResult.length?"":this._renderResult[n]},t}(Ne);Object(V.f)(function(e,t){var n=e.getColor(Ee.h);n&&t.addRule(".monaco-editor .lines-content .cigr { box-shadow: 1px 0 0 0 "+n+" inset; }");var i=e.getColor(Ee.a)||n;i&&t.addRule(".monaco-editor .lines-content .cigra { box-shadow: 1px 0 0 0 "+i+" inset; }")});n("+0Qw");var Rt=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Ft=function(){function e(){this._currentVisibleRange=new te.a(1,1,1,1)}return e.prototype.getCurrentVisibleRange=function(){return this._currentVisibleRange},e.prototype.setCurrentVisibleRange=function(e){this._currentVisibleRange=e},e}(),jt=function(){return function(e,t,n,i,r,o){this.lineNumber=e,this.startColumn=t,this.endColumn=n,this.startScrollTop=i,this.stopScrollTop=r,this.scrollType=o}}(),Wt=function(e){function t(t,n){var i=e.call(this,t)||this;i._linesContent=n,i._textRangeRestingSpot=document.createElement("div"),i._visibleLines=new lt(i),i.domNode=i._visibleLines.domNode;var r=i._context.configuration;return i._lineHeight=r.editor.lineHeight,i._typicalHalfwidthCharacterWidth=r.editor.fontInfo.typicalHalfwidthCharacterWidth,i._isViewportWrapping=r.editor.wrappingInfo.isViewportWrapping,i._revealHorizontalRightPadding=r.editor.viewInfo.revealHorizontalRightPadding,i._scrollOff=r.editor.viewInfo.cursorSurroundingLines,i._canUseLayerHinting=r.editor.canUseLayerHinting,i._viewLineOptions=new q(r,i._context.theme.type),M.write(i.domNode,7),i.domNode.setClassName("view-lines"),l.a.applyFontInfo(i.domNode,r.editor.fontInfo),i._maxLineWidth=0,i._asyncUpdateLineWidths=new v.d(function(){i._updateLineWidthsSlow()},200),i._lastRenderedData=new Ft,i._horizontalRevealRequest=null,i}return Rt(t,e),t.prototype.dispose=function(){this._asyncUpdateLineWidths.dispose(),e.prototype.dispose.call(this)},t.prototype.getDomNode=function(){return this.domNode},t.prototype.createVisibleLine=function(){return new G(this._viewLineOptions)},t.prototype.onConfigurationChanged=function(e){this._visibleLines.onConfigurationChanged(e),e.wrappingInfo&&(this._maxLineWidth=0);var t=this._context.configuration;return e.lineHeight&&(this._lineHeight=t.editor.lineHeight),e.fontInfo&&(this._typicalHalfwidthCharacterWidth=t.editor.fontInfo.typicalHalfwidthCharacterWidth),e.wrappingInfo&&(this._isViewportWrapping=t.editor.wrappingInfo.isViewportWrapping),e.viewInfo&&(this._revealHorizontalRightPadding=t.editor.viewInfo.revealHorizontalRightPadding,this._scrollOff=t.editor.viewInfo.cursorSurroundingLines),e.canUseLayerHinting&&(this._canUseLayerHinting=t.editor.canUseLayerHinting),e.fontInfo&&l.a.applyFontInfo(this.domNode,t.editor.fontInfo),this._onOptionsMaybeChanged(),e.layoutInfo&&(this._maxLineWidth=0),!0},t.prototype._onOptionsMaybeChanged=function(){var e=this._context.configuration,t=new q(e,this._context.theme.type);if(!this._viewLineOptions.equals(t)){this._viewLineOptions=t;for(var n=this._visibleLines.getStartLineNumber(),i=this._visibleLines.getEndLineNumber(),r=n;r<=i;r++){this._visibleLines.getVisibleLine(r).onOptionsChanged(this._viewLineOptions)}return!0}return!1},t.prototype.onCursorStateChanged=function(e){for(var t=this._visibleLines.getStartLineNumber(),n=this._visibleLines.getEndLineNumber(),i=!1,r=t;r<=n;r++)i=this._visibleLines.getVisibleLine(r).onSelectionChanged()||i;return i},t.prototype.onDecorationsChanged=function(e){for(var t=this._visibleLines.getStartLineNumber(),n=this._visibleLines.getEndLineNumber(),i=t;i<=n;i++)this._visibleLines.getVisibleLine(i).onDecorationsChanged();return!0},t.prototype.onFlushed=function(e){var t=this._visibleLines.onFlushed(e);return this._maxLineWidth=0,t},t.prototype.onLinesChanged=function(e){return this._visibleLines.onLinesChanged(e)},t.prototype.onLinesDeleted=function(e){return this._visibleLines.onLinesDeleted(e)},t.prototype.onLinesInserted=function(e){return this._visibleLines.onLinesInserted(e)},t.prototype.onRevealRangeRequest=function(e){var t=this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(),e.range,e.verticalType),n=this._context.viewLayout.validateScrollPosition({scrollTop:t});e.revealHorizontal?e.range.startLineNumber!==e.range.endLineNumber?n={scrollTop:n.scrollTop,scrollLeft:0}:this._horizontalRevealRequest=new jt(e.range.startLineNumber,e.range.startColumn,e.range.endColumn,this._context.viewLayout.getCurrentScrollTop(),n.scrollTop,e.scrollType):this._horizontalRevealRequest=null;var i=Math.abs(this._context.viewLayout.getCurrentScrollTop()-n.scrollTop);return 0===e.scrollType&&i>this._lineHeight?this._context.viewLayout.setScrollPositionSmooth(n):this._context.viewLayout.setScrollPositionNow(n),!0},t.prototype.onScrollChanged=function(e){if(this._horizontalRevealRequest&&e.scrollLeftChanged&&(this._horizontalRevealRequest=null),this._horizontalRevealRequest&&e.scrollTopChanged){var t=Math.min(this._horizontalRevealRequest.startScrollTop,this._horizontalRevealRequest.stopScrollTop),n=Math.max(this._horizontalRevealRequest.startScrollTop,this._horizontalRevealRequest.stopScrollTop);(e.scrollTopn)&&(this._horizontalRevealRequest=null)}return this.domNode.setWidth(e.scrollWidth),this._visibleLines.onScrollChanged(e)||!0},t.prototype.onTokensChanged=function(e){return this._visibleLines.onTokensChanged(e)},t.prototype.onZonesChanged=function(e){return this._context.viewLayout.onMaxLineWidthChanged(this._maxLineWidth),this._visibleLines.onZonesChanged(e)},t.prototype.onThemeChanged=function(e){return this._onOptionsMaybeChanged()},t.prototype.getPositionFromDOMInfo=function(e,t){var n=this._getViewLineDomNode(e);if(null===n)return null;var i=this._getLineNumberFor(n);if(-1===i)return null;if(i<1||i>this._context.model.getLineCount())return null;if(1===this._context.model.getLineMaxColumn(i))return new ee.a(i,1);var r=this._visibleLines.getStartLineNumber(),o=this._visibleLines.getEndLineNumber();if(io)return null;var s=this._visibleLines.getVisibleLine(i).getColumnOfNodeOffset(i,e,t),a=this._context.model.getLineMinColumn(i);return sn?-1:this._visibleLines.getVisibleLine(e).getWidth()},t.prototype.linesVisibleRangesForRange=function(e,t){if(this.shouldRender())return null;var n=e.endLineNumber,i=te.a.intersectRanges(e,this._lastRenderedData.getCurrentVisibleRange());if(!i)return null;var r=[],o=0,s=new K(this.domNode.domNode,this._textRangeRestingSpot),a=0;t&&(a=this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new ee.a(i.startLineNumber,1)).lineNumber);for(var u=this._visibleLines.getStartLineNumber(),c=this._visibleLines.getEndLineNumber(),l=i.startLineNumber;l<=i.endLineNumber;l++)if(!(lc)){var d=l===i.startLineNumber?i.startColumn:1,h=l===i.endLineNumber?i.endColumn:this._context.model.getLineMaxColumn(l),f=this._visibleLines.getVisibleLine(l).getVisibleRangesForRange(d,h,s);if(f&&0!==f.length){if(t&&lo)){var a=s===t.startLineNumber?t.startColumn:1,u=s===t.endLineNumber?t.endColumn:this._context.model.getLineMaxColumn(s),c=this._visibleLines.getVisibleLine(s).getVisibleRangesForRange(a,u,i);c&&0!==c.length&&(n=n.concat(c))}return 0===n.length?null:n},t.prototype.visibleRangeForPosition=function(e){var t=this.visibleRangesForRange2(new te.a(e.lineNumber,e.column,e.lineNumber,e.column));return t?t[0]:null},t.prototype.updateLineWidths=function(){this._updateLineWidths(!1)},t.prototype._updateLineWidthsFast=function(){return this._updateLineWidths(!0)},t.prototype._updateLineWidthsSlow=function(){this._updateLineWidths(!1)},t.prototype._updateLineWidths=function(e){for(var t=this._visibleLines.getStartLineNumber(),n=this._visibleLines.getEndLineNumber(),i=1,r=!0,o=t;o<=n;o++){var s=this._visibleLines.getVisibleLine(o);!e||s.getWidthIsFast()?i=Math.max(i,s.getWidth()):r=!1}return r&&1===t&&n===this._context.model.getLineCount()&&(this._maxLineWidth=0),this._ensureMaxLineWidth(i),r},t.prototype.prepareRender=function(){throw new Error("Not supported")},t.prototype.render=function(){throw new Error("Not supported")},t.prototype.renderText=function(e){if(this._visibleLines.renderLines(e),this._lastRenderedData.setCurrentVisibleRange(e.visibleRange),this.domNode.setWidth(this._context.viewLayout.getScrollWidth()),this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(),1e6)),this._horizontalRevealRequest){var t=this._horizontalRevealRequest.lineNumber,n=this._horizontalRevealRequest.startColumn,i=this._horizontalRevealRequest.endColumn,r=this._horizontalRevealRequest.scrollType;if(e.startLineNumber<=t&&t<=e.endLineNumber){this._horizontalRevealRequest=null,this.onDidRender();var o=this._computeScrollLeftToRevealRange(t,n,i);this._isViewportWrapping||this._ensureMaxLineWidth(o.maxHorizontalOffset),0===r?this._context.viewLayout.setScrollPositionSmooth({scrollLeft:o.scrollLeft}):this._context.viewLayout.setScrollPositionNow({scrollLeft:o.scrollLeft})}}this._updateLineWidthsFast()||this._asyncUpdateLineWidths.schedule(),this._linesContent.setLayerHinting(this._canUseLayerHinting);var s=this._context.viewLayout.getCurrentScrollTop()-e.bigNumbersDelta;this._linesContent.setTop(-s),this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft())},t.prototype._ensureMaxLineWidth=function(e){var t=Math.ceil(e);this._maxLineWidthl&&(l=f.left+f.width)}return r=l,c=Math.max(0,c-t.HORIZONTAL_EXTRA_PX),l+=this._revealHorizontalRightPadding,{scrollLeft:this._computeMinimumScrolling(s,a,c,l),maxHorizontalOffset:r}},t.prototype._computeMinimumScrolling=function(e,t,n,i,r,o){r=!!r,o=!!o;var s=(t|=0)-(e|=0);return(i|=0)-(n|=0)t?Math.max(0,i-s):e:n},t.HORIZONTAL_EXTRA_PX=30,t}(D),Bt=(n("MlKm"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),Vt=function(e){function t(t){var n=e.call(this)||this;return n._context=t,n._decorationsLeft=n._context.configuration.editor.layoutInfo.decorationsLeft,n._decorationsWidth=n._context.configuration.editor.layoutInfo.decorationsWidth,n._renderResult=null,n._context.addEventHandler(n),n}return Bt(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),this._renderResult=null,e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return e.layoutInfo&&(this._decorationsLeft=this._context.configuration.editor.layoutInfo.decorationsLeft,this._decorationsWidth=this._context.configuration.editor.layoutInfo.decorationsWidth),!0},t.prototype.onDecorationsChanged=function(e){return!0},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesChanged=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return e.scrollTopChanged},t.prototype.onZonesChanged=function(e){return!0},t.prototype._getDecorations=function(e){for(var t=e.getDecorationsInViewport(),n=[],i=0,r=0,o=t.length;r
    ',o=[],s=t;s<=n;s++){for(var a=s-t,u=i[a],c="",l=0,d=u.length;l';r[s]=u}this._renderResult=r},t.prototype.render=function(e,t){return this._renderResult?this._renderResult[t-e]:""},t}(Mt),Ut=(n("OkZj"),function(){function e(t,n,i,r){this.r=e._clamp(t),this.g=e._clamp(n),this.b=e._clamp(i),this.a=e._clamp(r)}return e._clamp=function(e){return e<0?0:e>255?255:0|e},e.Empty=new e(0,0,0,0),e}()),Kt=n("PCC9"),qt=function(){function e(){var e=this;this._onDidChange=new a.a,this.onDidChange=this._onDidChange.event,this._updateColorMap(),Kt.y.onDidChange(function(t){t.changedColorMap&&e._updateColorMap()})}return e.getInstance=function(){return this._INSTANCE||(this._INSTANCE=new e),this._INSTANCE},e.prototype._updateColorMap=function(){var e=Kt.y.getColorMap();if(!e)return this._colors=[Ut.Empty],void(this._backgroundIsLight=!0);this._colors=[Ut.Empty];for(var t=1;t=.5,this._onDidChange.fire(void 0)},e.prototype.getColor=function(e){return(e<1||e>=this._colors.length)&&(e=2),this._colors[e]},e.prototype.backgroundIsLight=function(){return this._backgroundIsLight},e._INSTANCE=null,e}(),Gt=function(){function e(t,n){if(760!==t.length)throw new Error("Invalid x2CharData");if(190!==n.length)throw new Error("Invalid x1CharData");this.x2charData=t,this.x1charData=n,this.x2charDataLight=e.soften(t,.8),this.x1charDataLight=e.soften(n,50/60)}return e.soften=function(e,t){for(var n=new Uint8ClampedArray(e.length),i=0,r=e.length;it.width||i+4>t.height)console.warn("bad render request outside image data");else{var u=a?this.x2charDataLight:this.x2charData,c=e._getChIndex(r),l=4*t.width,d=s.r,h=s.g,f=s.b,p=o.r-d,g=o.g-h,m=o.b-f,v=t.data,_=4*c*2,b=i*l+4*n,y=u[_]/255;v[b+0]=d+p*y,v[b+1]=h+g*y,v[b+2]=f+m*y;y=u[_+1]/255;v[b+4]=d+p*y,v[b+5]=h+g*y,v[b+6]=f+m*y,b+=l;y=u[_+2]/255;v[b+0]=d+p*y,v[b+1]=h+g*y,v[b+2]=f+m*y;y=u[_+3]/255;v[b+4]=d+p*y,v[b+5]=h+g*y,v[b+6]=f+m*y,b+=l;y=u[_+4]/255;v[b+0]=d+p*y,v[b+1]=h+g*y,v[b+2]=f+m*y;y=u[_+5]/255;v[b+4]=d+p*y,v[b+5]=h+g*y,v[b+6]=f+m*y,b+=l;y=u[_+6]/255;v[b+0]=d+p*y,v[b+1]=h+g*y,v[b+2]=f+m*y;y=u[_+7]/255;v[b+4]=d+p*y,v[b+5]=h+g*y,v[b+6]=f+m*y}},e.prototype.x1RenderChar=function(t,n,i,r,o,s,a){if(n+1>t.width||i+2>t.height)console.warn("bad render request outside image data");else{var u=a?this.x1charDataLight:this.x1charData,c=e._getChIndex(r),l=4*t.width,d=s.r,h=s.g,f=s.b,p=o.r-d,g=o.g-h,m=o.b-f,v=t.data,_=2*c*1,b=i*l+4*n,y=u[_]/255;v[b+0]=d+p*y,v[b+1]=h+g*y,v[b+2]=f+m*y,b+=l;y=u[_+1]/255;v[b+0]=d+p*y,v[b+1]=h+g*y,v[b+2]=f+m*y}},e.prototype.x2BlockRenderChar=function(e,t,n,i,r,o){if(t+2>e.width||n+4>e.height)console.warn("bad render request outside image data");else{var s=4*e.width,a=r.r,u=r.g,c=r.b,l=a+.5*(i.r-a),d=u+.5*(i.g-u),h=c+.5*(i.b-c),f=e.data,p=n*s+4*t;f[p+0]=l,f[p+1]=d,f[p+2]=h,f[p+4]=l,f[p+5]=d,f[p+6]=h,f[(p+=s)+0]=l,f[p+1]=d,f[p+2]=h,f[p+4]=l,f[p+5]=d,f[p+6]=h,f[(p+=s)+0]=l,f[p+1]=d,f[p+2]=h,f[p+4]=l,f[p+5]=d,f[p+6]=h,f[(p+=s)+0]=l,f[p+1]=d,f[p+2]=h,f[p+4]=l,f[p+5]=d,f[p+6]=h}},e.prototype.x1BlockRenderChar=function(e,t,n,i,r,o){if(t+1>e.width||n+2>e.height)console.warn("bad render request outside image data");else{var s=4*e.width,a=r.r,u=r.g,c=r.b,l=a+.5*(i.r-a),d=u+.5*(i.g-u),h=c+.5*(i.b-c),f=e.data,p=n*s+4*t;f[p+0]=l,f[p+1]=d,f[p+2]=h,f[(p+=s)+0]=l,f[p+1]=d,f[p+2]=h}},e}();function Zt(e){for(var t=new Uint8ClampedArray(e.length),n=0,i=e.length;n=s+y)return new e(a,u,_,b,l,w=1,s);var w=Math.max(1,Math.floor(n-b*h/f));return c&&c.scrollHeight===u&&(c.scrollTop>a&&(w=Math.min(w,c.startLineNumber)),c.scrollToprn)n._context.viewLayout.setScrollPositionNow({scrollTop:r.scrollTop});else{var s=e.posy-t;n._context.viewLayout.setScrollPositionNow({scrollTop:r.getDesiredScrollTopFromDelta(s)})}},function(){n._slider.toggleClassName("active",!1)})}}),n}return en(t,e),t.prototype.dispose=function(){this._mouseDownListener.dispose(),this._sliderMouseMoveMonitor.dispose(),this._sliderMouseDownListener.dispose(),e.prototype.dispose.call(this)},t.prototype._getMinimapDomNodeClassName=function(){return"always"===this._options.showSlider?"minimap slider-always":"minimap slider-mouseover"},t.prototype.getDomNode=function(){return this._domNode},t.prototype._applyLayout=function(){this._domNode.setLeft(this._options.minimapLeft),this._domNode.setWidth(this._options.minimapWidth),this._domNode.setHeight(this._options.minimapHeight),this._shadow.setHeight(this._options.minimapHeight),this._canvas.setWidth(this._options.canvasOuterWidth),this._canvas.setHeight(this._options.canvasOuterHeight),this._canvas.domNode.width=this._options.canvasInnerWidth,this._canvas.domNode.height=this._options.canvasInnerHeight,this._decorationsCanvas.setWidth(this._options.canvasOuterWidth),this._decorationsCanvas.setHeight(this._options.canvasOuterHeight),this._decorationsCanvas.domNode.width=this._options.canvasInnerWidth,this._decorationsCanvas.domNode.height=this._options.canvasInnerHeight,this._slider.setWidth(this._options.minimapWidth)},t.prototype._getBuffer=function(){return this._buffers||(this._buffers=new cn(this._canvas.domNode.getContext("2d"),this._options.canvasInnerWidth,this._options.canvasInnerHeight,this._tokensColorTracker.getColor(2))),this._buffers.getBuffer()},t.prototype._onOptionsMaybeChanged=function(){var e=new on(this._context.configuration);return!this._options.equals(e)&&(this._options=e,this._lastRenderData=null,this._buffers=null,this._applyLayout(),this._domNode.setClassName(this._getMinimapDomNodeClassName()),!0)},t.prototype.onConfigurationChanged=function(e){return this._onOptionsMaybeChanged()},t.prototype.onFlushed=function(e){return this._lastRenderData=null,!0},t.prototype.onLinesChanged=function(e){return!!this._lastRenderData&&this._lastRenderData.onLinesChanged(e)},t.prototype.onLinesDeleted=function(e){return this._lastRenderData&&this._lastRenderData.onLinesDeleted(e),!0},t.prototype.onLinesInserted=function(e){return this._lastRenderData&&this._lastRenderData.onLinesInserted(e),!0},t.prototype.onScrollChanged=function(e){return this._renderDecorations=!0,!0},t.prototype.onTokensChanged=function(e){return!!this._lastRenderData&&this._lastRenderData.onTokensChanged(e)},t.prototype.onTokensColorsChanged=function(e){return this._lastRenderData=null,this._buffers=null,!0},t.prototype.onZonesChanged=function(e){return this._lastRenderData=null,!0},t.prototype.onDecorationsChanged=function(e){return this._renderDecorations=!0,!0},t.prototype.onThemeChanged=function(e){return this._context.model.invalidateMinimapColorCache(),this._renderDecorations=!!this._lastDecorations,!!this._lastDecorations},t.prototype.prepareRender=function(e){},t.prototype.render=function(e){if(0===this._options.renderMinimap)return this._shadow.setClassName("minimap-shadow-hidden"),this._sliderHorizontal.setWidth(0),void this._sliderHorizontal.setHeight(0);e.scrollLeft+e.viewportWidth>=e.scrollWidth?this._shadow.setClassName("minimap-shadow-hidden"):this._shadow.setClassName("minimap-shadow-visible");var t=sn.create(this._options,e.visibleRange.startLineNumber,e.visibleRange.endLineNumber,e.viewportHeight,e.viewportData.whitespaceViewportData.length>0,this._context.model.getLineCount(),e.scrollTop,e.scrollHeight,this._lastRenderData?this._lastRenderData.renderedLayout:null);this._slider.setTop(t.sliderTop),this._slider.setHeight(t.sliderHeight);var n=e.scrollLeft/this._options.typicalHalfwidthCharacterWidth,i=Math.min(this._options.minimapWidth,Math.round(n*nn(this._options.renderMinimap)/this._options.pixelRatio));this._sliderHorizontal.setLeft(i),this._sliderHorizontal.setWidth(this._options.minimapWidth-i),this._sliderHorizontal.setTop(0),this._sliderHorizontal.setHeight(t.sliderHeight),this.renderDecorations(t),this._lastRenderData=this.renderLines(t)},t.prototype.renderDecorations=function(e){if(this._renderDecorations){this._renderDecorations=!1;var t=this._context.model.getDecorationsInViewport(new te.a(e.startLineNumber,1,e.endLineNumber,this._context.model.getLineMaxColumn(e.endLineNumber))),n=this._options,i=n.renderMinimap,r=n.canvasInnerWidth,o=n.canvasInnerHeight,s=tn(i),a=nn(i),u=this._context.model.getOptions().tabSize,c=this._decorationsCanvas.domNode.getContext("2d");c.clearRect(0,0,r,o);for(var l=new Map,d=0;dr?l.length-1:_-1;if(C>0){var S=l[C]-w||2;this.renderDecoration(e,n.options.minimap,w,c,S,o)}d&&this.renderLineHighlight(e,n.options.minimap,c,o)},t.prototype.renderLineHighlight=function(e,t,n,i){var r=t.getColor(this._context.theme);e.fillStyle=r&&r.transparent(.5).toString()||"",e.fillRect(0,n,e.canvas.width,i)},t.prototype.renderDecoration=function(e,t,n,i,r,o){var s=t.getColor(this._context.theme);e.fillStyle=s&&s.toString()||"",e.fillRect(n,i,r,o)},t.prototype.renderLines=function(e){var n=this._options.renderMinimap,i=e.startLineNumber,r=e.endLineNumber,o=tn(n);if(this._lastRenderData&&this._lastRenderData.linesEquals(e)){var s=this._lastRenderData._get();return new un(e,s.imageData,s.lines)}for(var a=this._getBuffer(),u=t._renderUntouchedLines(a,i,r,o,this._lastRenderData),c=u[0],l=u[1],d=u[2],h=this._context.model.getMinimapLinesRenderingData(i,r,d),f=h.tabSize,p=this._tokensColorTracker.getColor(2),g=this._tokensColorTracker.backgroundIsLight(),m=0,v=[],_=0,b=r-i+1;_=0&&Lh)return;var w=c.charCodeAt(p);if(9===w){var C=a-(p+g)%a;g+=C-1,f+=C*d}else if(32===w)f+=d;else for(var S=xe.v(w)?2:1,x=0;xh)return}},t}(D);Object(V.f)(function(e,t){var n=e.getColor(Qt._39);if(n){var i=n.transparent(.5);t.addRule(".monaco-editor .minimap-slider, .monaco-editor .minimap-slider .minimap-slider-horizontal { background: "+i+"; }")}var r=e.getColor(Qt._40);if(r){var o=r.transparent(.5);t.addRule(".monaco-editor .minimap-slider:hover, .monaco-editor .minimap-slider:hover .minimap-slider-horizontal { background: "+o+"; }")}var s=e.getColor(Qt._38);if(s){var a=s.transparent(.5);t.addRule(".monaco-editor .minimap-slider.active, .monaco-editor .minimap-slider.active .minimap-slider-horizontal { background: "+a+"; }")}var u=e.getColor(Qt._37);u&&t.addRule(".monaco-editor .minimap-shadow-visible { box-shadow: "+u+" -6px 0 6px -6px inset; }")});n("EG+O");var dn=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),hn=function(e){function t(t){var n=e.call(this,t)||this;return n._widgets={},n._verticalScrollbarWidth=n._context.configuration.editor.layoutInfo.verticalScrollbarWidth,n._minimapWidth=n._context.configuration.editor.layoutInfo.minimapWidth,n._horizontalScrollbarHeight=n._context.configuration.editor.layoutInfo.horizontalScrollbarHeight,n._editorHeight=n._context.configuration.editor.layoutInfo.height,n._editorWidth=n._context.configuration.editor.layoutInfo.width,n._domNode=Object(f.b)(document.createElement("div")),M.write(n._domNode,4),n._domNode.setClassName("overlayWidgets"),n}return dn(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._widgets={}},t.prototype.getDomNode=function(){return this._domNode},t.prototype.onConfigurationChanged=function(e){return!!e.layoutInfo&&(this._verticalScrollbarWidth=this._context.configuration.editor.layoutInfo.verticalScrollbarWidth,this._minimapWidth=this._context.configuration.editor.layoutInfo.minimapWidth,this._horizontalScrollbarHeight=this._context.configuration.editor.layoutInfo.horizontalScrollbarHeight,this._editorHeight=this._context.configuration.editor.layoutInfo.height,this._editorWidth=this._context.configuration.editor.layoutInfo.width,!0)},t.prototype.addWidget=function(e){var t=Object(f.b)(e.getDomNode());this._widgets[e.getId()]={widget:e,preference:null,domNode:t},t.setPosition("absolute"),t.setAttribute("widgetId",e.getId()),this._domNode.appendChild(t),this.setShouldRender()},t.prototype.setWidgetPosition=function(e,t){var n=this._widgets[e.getId()];return n.preference!==t&&(n.preference=t,this.setShouldRender(),!0)},t.prototype.removeWidget=function(e){var t=e.getId();if(this._widgets.hasOwnProperty(t)){var n=this._widgets[t].domNode.domNode;delete this._widgets[t],n.parentNode.removeChild(n),this.setShouldRender()}},t.prototype._renderWidget=function(e){var t=e.domNode;if(null!==e.preference)if(0===e.preference)t.setTop(0),t.setRight(2*this._verticalScrollbarWidth+this._minimapWidth);else if(1===e.preference){var n=t.domNode.clientHeight;t.setTop(this._editorHeight-n-2*this._horizontalScrollbarHeight),t.setRight(2*this._verticalScrollbarWidth+this._minimapWidth)}else 2===e.preference&&(t.setTop(0),t.domNode.style.right="50%");else t.unsetTop()},t.prototype.prepareRender=function(e){},t.prototype.render=function(e){this._domNode.setWidth(this._editorWidth);for(var t=Object.keys(this._widgets),n=0,i=t.length;n=3){var r,o,s,a=i-(r=Math.floor(i/3))-(o=Math.floor(i/3)),u=(s=e)+r;return[[0,s,u,s,s+r+a,s,u,s],[0,r,a,r+a,o,r+a+o,a+o,r+a+o]]}if(2===n)return[[0,s=e,s,s,s+(r=Math.floor(i/2)),s,s,s],[0,r,r,r,o=i-r,r+o,r+o,r+o]];return[[0,e,e,e,e,e,e,e],[0,i,i,i,i,i,i,i]]},e.prototype.equals=function(e){return this.lineHeight===e.lineHeight&&this.pixelRatio===e.pixelRatio&&this.overviewRulerLanes===e.overviewRulerLanes&&this.renderBorder===e.renderBorder&&this.borderColor===e.borderColor&&this.hideCursor===e.hideCursor&&this.cursorColor===e.cursorColor&&this.themeType===e.themeType&&this.backgroundColor===e.backgroundColor&&this.top===e.top&&this.right===e.right&&this.domWidth===e.domWidth&&this.domHeight===e.domHeight&&this.canvasWidth===e.canvasWidth&&this.canvasHeight===e.canvasHeight},e}(),mn=function(e){function t(t){var n=e.call(this,t)||this;return n._domNode=Object(f.b)(document.createElement("canvas")),n._domNode.setClassName("decorationsOverviewRuler"),n._domNode.setPosition("absolute"),n._domNode.setLayerHinting(!0),n._domNode.setAttribute("aria-hidden","true"),n._updateSettings(!1),n._tokensColorTrackerListener=Kt.y.onDidChange(function(e){e.changedColorMap&&n._updateSettings(!0)}),n._cursorPositions=[],n}return pn(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._tokensColorTrackerListener.dispose()},t.prototype._updateSettings=function(e){var t=new gn(this._context.configuration,this._context.theme);return(!this._settings||!this._settings.equals(t))&&(this._settings=t,this._domNode.setTop(this._settings.top),this._domNode.setRight(this._settings.right),this._domNode.setWidth(this._settings.domWidth),this._domNode.setHeight(this._settings.domHeight),this._domNode.domNode.width=this._settings.canvasWidth,this._domNode.domNode.height=this._settings.canvasHeight,e&&this._render(),!0)},t.prototype.onConfigurationChanged=function(e){return this._updateSettings(!1)},t.prototype.onCursorStateChanged=function(e){this._cursorPositions=[];for(var t=0,n=e.selections.length;tt&&(E=t-a),x=E-a,D=E+a;x>_+1||w!==m?(0!==b&&u.fillRect(c[m],v,l[m],_-v),m=w,v=x,_=D):D>_&&(_=D)}u.fillRect(c[m],v,l[m],_-v)}if(!this._settings.hideCursor&&this._settings.cursorColor){var L=2*this._settings.pixelRatio|0,O=L/2|0,k=this._settings.x[7],N=this._settings.w[7];u.fillStyle=this._settings.cursorColor;for(v=-100,_=-100,b=0,y=this._cursorPositions.length;bt&&(E=t-O);var D=(x=E-O)+L;x>_+1?(0!==b&&u.fillRect(k,v,N,_-v),v=x,_=D):D>_&&(_=D)}u.fillRect(k,v,N,_-v)}this._settings.renderBorder&&this._settings.borderColor&&this._settings.overviewRulerLanes>0&&(u.beginPath(),u.lineWidth=1,u.strokeStyle=this._settings.borderColor,u.moveTo(0,0),u.lineTo(0,t),u.stroke(),u.moveTo(0,0),u.lineTo(e,0),u.stroke())},t}(D),vn=n("tGak"),_n=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),bn=function(e){function t(t,n){var i=e.call(this)||this;return i._context=t,i._domNode=Object(f.b)(document.createElement("canvas")),i._domNode.setClassName(n),i._domNode.setPosition("absolute"),i._domNode.setLayerHinting(!0),i._zoneManager=new vn.b(function(e){return i._context.viewLayout.getVerticalOffsetForLineNumber(e)}),i._zoneManager.setDOMWidth(0),i._zoneManager.setDOMHeight(0),i._zoneManager.setOuterHeight(i._context.viewLayout.getScrollHeight()),i._zoneManager.setLineHeight(i._context.configuration.editor.lineHeight),i._zoneManager.setPixelRatio(i._context.configuration.editor.pixelRatio),i._context.addEventHandler(i),i}return _n(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return e.lineHeight&&(this._zoneManager.setLineHeight(this._context.configuration.editor.lineHeight),this._render()),e.pixelRatio&&(this._zoneManager.setPixelRatio(this._context.configuration.editor.pixelRatio),this._domNode.setWidth(this._zoneManager.getDOMWidth()),this._domNode.setHeight(this._zoneManager.getDOMHeight()),this._domNode.domNode.width=this._zoneManager.getCanvasWidth(),this._domNode.domNode.height=this._zoneManager.getCanvasHeight(),this._render()),!0},t.prototype.onFlushed=function(e){return this._render(),!0},t.prototype.onScrollChanged=function(e){return e.scrollHeightChanged&&(this._zoneManager.setOuterHeight(e.scrollHeight),this._render()),!0},t.prototype.onZonesChanged=function(e){return this._render(),!0},t.prototype.getDomNode=function(){return this._domNode.domNode},t.prototype.setLayout=function(e){this._domNode.setTop(e.top),this._domNode.setRight(e.right);var t=!1;t=this._zoneManager.setDOMWidth(e.width)||t,(t=this._zoneManager.setDOMHeight(e.height)||t)&&(this._domNode.setWidth(this._zoneManager.getDOMWidth()),this._domNode.setHeight(this._zoneManager.getDOMHeight()),this._domNode.domNode.width=this._zoneManager.getCanvasWidth(),this._domNode.domNode.height=this._zoneManager.getCanvasHeight(),this._render())},t.prototype.setZones=function(e){this._zoneManager.setZones(e),this._render()},t.prototype._render=function(){if(0===this._zoneManager.getOuterHeight())return!1;var e=this._zoneManager.getCanvasWidth(),t=this._zoneManager.getCanvasHeight(),n=this._zoneManager.resolveColorZones(),i=this._zoneManager.getId2Color(),r=this._domNode.domNode.getContext("2d");return r.clearRect(0,0,e,t),n.length>0&&this._renderOneLane(r,n,i,e),!0},t.prototype._renderOneLane=function(e,t,n,i){for(var r=0,o=0,s=0,a=0,u=t;a=d?s=Math.max(s,h):(e.fillRect(0,o,i,s-o),o=d,s=h)}e.fillRect(0,o,i,s-o)},t}(E),yn=(n("5RGO"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),wn=function(e){function t(t){var n=e.call(this,t)||this;return n.domNode=Object(f.b)(document.createElement("div")),n.domNode.setAttribute("role","presentation"),n.domNode.setAttribute("aria-hidden","true"),n.domNode.setClassName("view-rulers"),n._renderedRulers=[],n._rulers=n._context.configuration.editor.viewInfo.rulers,n._typicalHalfwidthCharacterWidth=n._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,n}return yn(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return!!(e.viewInfo||e.layoutInfo||e.fontInfo)&&(this._rulers=this._context.configuration.editor.viewInfo.rulers,this._typicalHalfwidthCharacterWidth=this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,!0)},t.prototype.onScrollChanged=function(e){return e.scrollHeightChanged},t.prototype.prepareRender=function(e){},t.prototype._ensureRulersCount=function(){var e=this._renderedRulers.length,t=this._rulers.length;if(e!==t)if(e0;){(o=Object(f.b)(document.createElement("div"))).setClassName("view-ruler"),o.setWidth(n),this.domNode.appendChild(o),this._renderedRulers.push(o),i--}else for(var r=e-t;r>0;){var o=this._renderedRulers.pop();this.domNode.removeChild(o),r--}},t.prototype.render=function(e){this._ensureRulersCount();for(var t=0,n=this._rulers.length;t0;return this._shouldShow!==e&&(this._shouldShow=e,!0)},t.prototype.getDomNode=function(){return this._domNode},t.prototype._updateWidth=function(){var e=this._context.configuration.editor.layoutInfo,t=0;return t=0===e.renderMinimap||e.minimapWidth>0&&0===e.minimapLeft?e.width:e.width-e.minimapWidth-e.verticalScrollbarWidth,this._width!==t&&(this._width=t,!0)},t.prototype.onConfigurationChanged=function(e){var t=!1;return e.viewInfo&&(this._useShadows=this._context.configuration.editor.viewInfo.scrollbar.useShadows),e.layoutInfo&&(t=this._updateWidth()),this._updateShouldShow()||t},t.prototype.onScrollChanged=function(e){return this._scrollTop=e.scrollTop,this._updateShouldShow()},t.prototype.prepareRender=function(e){},t.prototype.render=function(e){this._domNode.setWidth(this._width),this._domNode.setClassName(this._shouldShow?"scroll-decoration":"")},t}(D);Object(V.f)(function(e,t){var n=e.getColor(Qt._37);n&&t.addRule(".monaco-editor .scroll-decoration { box-shadow: "+n+" 0 6px 6px -6px inset; }")});n("MfYP");var xn=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Ln=function(){return function(e){this.left=e.left,this.width=e.width,this.startStyle=null,this.endStyle=null}}(),On=function(){return function(e,t){this.lineNumber=e,this.ranges=t}}();function kn(e){return new Ln(e)}function Nn(e){return new On(e.lineNumber,e.ranges.map(kn))}var En=g.g,In=function(e){function t(t){var n=e.call(this)||this;return n._previousFrameVisibleRangesWithStyle=[],n._context=t,n._lineHeight=n._context.configuration.editor.lineHeight,n._roundedSelection=n._context.configuration.editor.viewInfo.roundedSelection,n._typicalHalfwidthCharacterWidth=n._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,n._selections=[],n._renderResult=null,n._context.addEventHandler(n),n}return xn(t,e),t.prototype.dispose=function(){this._context.removeEventHandler(this),this._renderResult=null,e.prototype.dispose.call(this)},t.prototype.onConfigurationChanged=function(e){return e.lineHeight&&(this._lineHeight=this._context.configuration.editor.lineHeight),e.viewInfo&&(this._roundedSelection=this._context.configuration.editor.viewInfo.roundedSelection),e.fontInfo&&(this._typicalHalfwidthCharacterWidth=this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth),!0},t.prototype.onCursorStateChanged=function(e){return this._selections=e.selections.slice(0),!0},t.prototype.onDecorationsChanged=function(e){return!0},t.prototype.onFlushed=function(e){return!0},t.prototype.onLinesChanged=function(e){return!0},t.prototype.onLinesDeleted=function(e){return!0},t.prototype.onLinesInserted=function(e){return!0},t.prototype.onScrollChanged=function(e){return e.scrollTopChanged},t.prototype.onZonesChanged=function(e){return!0},t.prototype._visibleRangesHaveGaps=function(e){for(var t=0,n=e.length;t1)return!0}return!1},t.prototype._enrichVisibleRangesWithStyle=function(e,t,n){var i=this._typicalHalfwidthCharacterWidth/4,r=null,o=null;if(n&&n.length>0&&t.length>0){var s=t[0].lineNumber;if(s===e.startLineNumber)for(var a=0;!r&&a=0;a--)n[a].lineNumber===u&&(o=n[a].ranges[0]);r&&!r.startStyle&&(r=null),o&&!o.startStyle&&(o=null)}a=0;for(var c=t.length;a0){var g=t[a-1].ranges[0].left,m=t[a-1].ranges[0].left+t[a-1].ranges[0].width;Dn(d-g)g&&(f.top=1),Dn(h-m)'},t.prototype._actualRenderOneSelection=function(e,n,i,r){for(var o=r.length>0&&r[0].ranges[0].startStyle,s=this._lineHeight.toString(),a=(this._lineHeight-1).toString(),u=r.length>0?r[0].lineNumber:0,c=r.length>0?r[r.length-1].lineNumber:0,l=0,d=r.length;l1,c)}}this._previousFrameVisibleRangesWithStyle=o,this._renderResult=t},t.prototype.render=function(e,t){if(!this._renderResult)return"";var n=t-e;return n<0||n>=this._renderResult.length?"":this._renderResult[n]},t.SELECTION_CLASS_NAME="selected-text",t.SELECTION_TOP_LEFT="top-left-radius",t.SELECTION_BOTTOM_LEFT="bottom-left-radius",t.SELECTION_TOP_RIGHT="top-right-radius",t.SELECTION_BOTTOM_RIGHT="bottom-right-radius",t.EDITOR_BACKGROUND_CLASS_NAME="monaco-editor-background",t.ROUNDED_PIECE_WIDTH=10,t}(Ne);function Dn(e){return e<0?-e:e}Object(V.f)(function(e,t){var n=e.getColor(Qt.H);n&&t.addRule(".monaco-editor .focused .selected-text { background-color: "+n+"; }");var i=e.getColor(Qt.E);i&&t.addRule(".monaco-editor .selected-text { background-color: "+i+"; }");var r=e.getColor(Qt.I);r&&t.addRule(".monaco-editor .view-line span.inline-selected-text { color: "+r+"; }")});n("8EM9");var Mn=n("iXRW"),Tn=function(){return function(e,t,n,i,r,o){this.top=e,this.left=t,this.width=n,this.height=i,this.textContent=r,this.textContentClassName=o}}(),Pn=function(){function e(e){this._context=e,this._cursorStyle=this._context.configuration.editor.viewInfo.cursorStyle,this._lineHeight=this._context.configuration.editor.lineHeight,this._typicalHalfwidthCharacterWidth=this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,this._lineCursorWidth=Math.min(this._context.configuration.editor.viewInfo.cursorWidth,this._typicalHalfwidthCharacterWidth),this._isVisible=!0,this._domNode=Object(f.b)(document.createElement("div")),this._domNode.setClassName("cursor"),this._domNode.setHeight(this._lineHeight),this._domNode.setTop(0),this._domNode.setLeft(0),l.a.applyFontInfo(this._domNode,this._context.configuration.editor.fontInfo),this._domNode.setDisplay("none"),this._position=new ee.a(1,1),this._lastRenderedContent="",this._renderData=null}return e.prototype.getDomNode=function(){return this._domNode},e.prototype.getPosition=function(){return this._position},e.prototype.show=function(){this._isVisible||(this._domNode.setVisibility("inherit"),this._isVisible=!0)},e.prototype.hide=function(){this._isVisible&&(this._domNode.setVisibility("hidden"),this._isVisible=!1)},e.prototype.onConfigurationChanged=function(e){return e.lineHeight&&(this._lineHeight=this._context.configuration.editor.lineHeight),e.fontInfo&&(l.a.applyFontInfo(this._domNode,this._context.configuration.editor.fontInfo),this._typicalHalfwidthCharacterWidth=this._context.configuration.editor.fontInfo.typicalHalfwidthCharacterWidth),e.viewInfo&&(this._cursorStyle=this._context.configuration.editor.viewInfo.cursorStyle,this._lineCursorWidth=Math.min(this._context.configuration.editor.viewInfo.cursorWidth,this._typicalHalfwidthCharacterWidth)),!0},e.prototype.onCursorPositionChanged=function(e){return this._position=e,!0},e.prototype._prepareRender=function(e){var t="",n="";if(this._cursorStyle===Mn.g.Line||this._cursorStyle===Mn.g.LineThin){var i,r=e.visibleRangeForPosition(this._position);if(!r)return null;if(this._cursorStyle===Mn.g.Line){if((i=o.q(this._lineCursorWidth>0?this._lineCursorWidth:2))>2)t=this._context.model.getLineContent(this._position.lineNumber).charAt(this._position.column-1)}else i=o.q(1);var s=r.left;i>=2&&s>=1&&(s-=1);var a=e.getVerticalOffsetForLineNumber(this._position.lineNumber)-e.bigNumbersDelta;return new Tn(a,s,i,this._lineHeight,t,n)}var u=e.linesVisibleRangesForRange(new te.a(this._position.lineNumber,this._position.column,this._position.lineNumber,this._position.column+1),!1);if(!u||0===u.length||0===u[0].ranges.length)return null;var c=u[0].ranges[0],l=c.width<1?this._typicalHalfwidthCharacterWidth:c.width;if(this._cursorStyle===Mn.g.Block){var d=this._context.model.getViewLineData(this._position.lineNumber);t=d.content.charAt(this._position.column-1),xe.w(d.content.charCodeAt(this._position.column-1))&&(t+=d.content.charAt(this._position.column));var h=d.tokens.findTokenIndexAtOffset(this._position.column-1);n=d.tokens.getClassName(h)}var f=e.getVerticalOffsetForLineNumber(this._position.lineNumber)-e.bigNumbersDelta,p=this._lineHeight;return this._cursorStyle!==Mn.g.Underline&&this._cursorStyle!==Mn.g.UnderlineThin||(f+=this._lineHeight-2,p=2),new Tn(f,c.left,l,p,t,n)},e.prototype.prepareRender=function(e){this._renderData=this._prepareRender(e)},e.prototype.render=function(e){return this._renderData?(this._lastRenderedContent!==this._renderData.textContent&&(this._lastRenderedContent=this._renderData.textContent,this._domNode.domNode.textContent=this._lastRenderedContent),this._domNode.setClassName("cursor "+this._renderData.textContentClassName),this._domNode.setDisplay("block"),this._domNode.setTop(this._renderData.top),this._domNode.setLeft(this._renderData.left),this._domNode.setWidth(this._renderData.width),this._domNode.setLineHeight(this._renderData.height),this._domNode.setHeight(this._renderData.height),{domNode:this._domNode.domNode,position:this._position,contentLeft:this._renderData.left,height:this._renderData.height,width:2}):(this._domNode.setDisplay("none"),null)},e}(),An=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Rn=function(e){function t(t){var n=e.call(this,t)||this;return n._readOnly=n._context.configuration.editor.readOnly,n._cursorBlinking=n._context.configuration.editor.viewInfo.cursorBlinking,n._cursorStyle=n._context.configuration.editor.viewInfo.cursorStyle,n._cursorSmoothCaretAnimation=n._context.configuration.editor.viewInfo.cursorSmoothCaretAnimation,n._selectionIsEmpty=!0,n._isVisible=!1,n._primaryCursor=new Pn(n._context),n._secondaryCursors=[],n._renderData=[],n._domNode=Object(f.b)(document.createElement("div")),n._domNode.setAttribute("role","presentation"),n._domNode.setAttribute("aria-hidden","true"),n._updateDomClassName(),n._domNode.appendChild(n._primaryCursor.getDomNode()),n._startCursorBlinkAnimation=new v.e,n._cursorFlatBlinkInterval=new v.c,n._blinkingEnabled=!1,n._editorHasFocus=!1,n._updateBlinking(),n}return An(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._startCursorBlinkAnimation.dispose(),this._cursorFlatBlinkInterval.dispose()},t.prototype.getDomNode=function(){return this._domNode},t.prototype.onConfigurationChanged=function(e){e.readOnly&&(this._readOnly=this._context.configuration.editor.readOnly),e.viewInfo&&(this._cursorBlinking=this._context.configuration.editor.viewInfo.cursorBlinking,this._cursorStyle=this._context.configuration.editor.viewInfo.cursorStyle,this._cursorSmoothCaretAnimation=this._context.configuration.editor.viewInfo.cursorSmoothCaretAnimation),this._primaryCursor.onConfigurationChanged(e),this._updateBlinking(),e.viewInfo&&this._updateDomClassName();for(var t=0,n=this._secondaryCursors.length;tt.length){var o=this._secondaryCursors.length-t.length;for(i=0;in){var o=t-n;for(r=0;r=e+1&&this.lastAddedCursorIndex--,this.secondaryCursors[e].dispose(this.context),this.secondaryCursors.splice(e,1)},e.prototype._getAll=function(){var e=[];e[0]=this.primaryCursor;for(var t=0,n=this.secondaryCursors.length;td&&S.index--}e.splice(d,1),t.splice(l,1),this._removeSecondaryCursor(d-1),r--}}}}},e}(),$n=n("2Ayt"),Jn=n("UuCV"),Qn=n("33h2"),ei=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();var ti=function(){return function(e,t,n){this.selections=e,this.source=t,this.reason=n}}(),ni=function(){function e(e,t){this.modelVersionId=e.getVersionId(),this.cursorState=t.getAll()}return e.prototype.equals=function(e){if(!e)return!1;if(this.modelVersionId!==e.modelVersionId)return!1;if(this.cursorState.length!==e.cursorState.length)return!1;for(var t=0,n=this.cursorState.length;t=t.length)return!1;if(!t[n].strictContainsRange(e[n]))return!1}return!0},e}(),ri=function(e){function t(t,n,i){var r=e.call(this)||this;r._onDidReachMaxCursorCount=r._register(new a.a),r.onDidReachMaxCursorCount=r._onDidReachMaxCursorCount.event,r._onDidAttemptReadOnlyEdit=r._register(new a.a),r.onDidAttemptReadOnlyEdit=r._onDidAttemptReadOnlyEdit.event,r._onDidChange=r._register(new a.a),r.onDidChange=r._onDidChange.event,r._configuration=t,r._model=n,r._knownModelVersionId=r._model.getVersionId(),r._viewModel=i,r.context=new ne.c(r._configuration,r._model,r._viewModel),r._cursors=new Xn(r.context),r._isHandling=!1,r._isDoingComposition=!1,r._columnSelectData=null,r._autoClosedActions=[],r._prevEditOperationType=0,r._register(r._model.onDidChangeRawContent(function(e){if(r._knownModelVersionId=e.versionId,!r._isHandling){var t=e.containsEvent(1);r._onModelContentChanged(t)}})),r._register(i.addEventListener(function(e){(function(e){for(var t=0,n=e.length;t0)for(var e=this._cursors.getSelections(),t=0;tt.MAX_CURSOR_COUNT&&(i=i.slice(0,t.MAX_CURSOR_COUNT),this._onDidReachMaxCursorCount.fire(void 0));var r=new ni(this._model,this);this._cursors.setStates(i),this._cursors.normalize(),this._columnSelectData=null,this._validateAutoClosedActions(),this._emitStateChangedIfNecessary(e,n,r)},t.prototype.setColumnSelectData=function(e){this._columnSelectData=e},t.prototype.reveal=function(e,t,n){this._revealRange(t,0,e,n)},t.prototype.revealRange=function(e,t,n,i){this.emitCursorRevealRange(t,n,e,i)},t.prototype.scrollTo=function(e){this._viewModel.viewLayout.setScrollPositionSmooth({scrollTop:e})},t.prototype.saveState=function(){for(var e=[],t=this._cursors.getSelections(),n=0,i=t.length;n0&&this._pushAutoClosedAction(n,i),this._prevEditOperationType=e.type}e.shouldPushStackElementAfter&&this._model.pushStackElement()}},t.prototype._interpretCommandResult=function(e){e&&0!==e.length||(e=this._cursors.readSelectionFromMarkers()),this._columnSelectData=null,this._cursors.setSelections(e),this._cursors.normalize()},t.prototype._emitStateChangedIfNecessary=function(e,t,n){var i=new ni(this._model,this);if(i.equals(n))return!1;var r=this._cursors.getSelections(),o=this._cursors.getViewSelections();try{this._beginEmit().emit(new Fe(o))}finally{this._endEmit()}return n&&n.cursorState.length===i.cursorState.length&&!i.cursorState.some(function(e,t){return!e.modelState.equals(n.cursorState[t].modelState)})||this._onDidChange.fire(new ti(r,e||"keyboard",t)),!0},t.prototype._revealRange=function(e,t,n,i){var r=this._cursors.getViewPositions(),o=r[0];if(1===e)for(var s=1;s1)return;var a=new te.a(o.lineNumber,o.column,o.lineNumber,o.column);this.emitCursorRevealRange(a,t,n,i)},t.prototype.emitCursorRevealRange=function(e,t,n,i){try{this._beginEmit().emit(new Ke(e,t,n,i))}finally{this._endEmit()}},t.prototype._findAutoClosingPairs=function(e){if(!e.length)return null;for(var t=[],n=0,i=e.length;n=0)return null;var o=r.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);if(!o)return null;var s=o[1],a=this.context.config.autoClosingPairsClose2.get(s);if(!a||1!==a.length)return null;var u=a[0].open,c=r.text.length-o[2].length-1,l=r.text.lastIndexOf(u,c-1);if(-1===l)return null;t.push([l,c])}return t},t.prototype.executeEdits=function(e,t,n){var i=this,r=null;"snippet"===e&&(r=this._findAutoClosingPairs(t)),r&&(t[0]._isTracked=!0);var o=[],s=[],a=this._model.pushEditOperations(this.getSelections(),t,function(e){if(r)for(var t=0,a=r.length;t0&&this._pushAutoClosedAction(o,s)},t.prototype.trigger=function(e,t,n){var i=Qn.b;if(t!==i.CompositionStart)if(t===i.CompositionEnd&&(this._isDoingComposition=!1),this._configuration.editor.readOnly)this._onDidAttemptReadOnlyEdit.fire(void 0);else{var r=new ni(this._model,this),o=0;t!==i.Undo&&t!==i.Redo&&this._cursors.stopTrackingSelections(),this._cursors.ensureValidState(),this._isHandling=!0;try{switch(t){case i.Type:this._type(e,n.text);break;case i.ReplacePreviousChar:this._replacePreviousChar(n.text,n.replaceCharCnt);break;case i.Paste:o=4,this._paste(n.text,n.pasteOnNewLine,n.multicursorText);break;case i.Cut:this._cut();break;case i.Undo:o=5,this._interpretCommandResult(this._model.undo());break;case i.Redo:o=6,this._interpretCommandResult(this._model.redo());break;case i.ExecuteCommand:this._externalExecuteCommand(n);break;case i.ExecuteCommands:this._externalExecuteCommands(n);break;case i.CompositionEnd:this._interpretCompositionEnd(e)}}catch(e){Object(s.e)(e)}this._isHandling=!1,t!==i.Undo&&t!==i.Redo&&this._cursors.startTrackingSelections(),this._validateAutoClosedActions(),this._emitStateChangedIfNecessary(e,o,r)&&this._revealRange(0,0,!0,0)}else this._isDoingComposition=!0},t.prototype._interpretCompositionEnd=function(e){if(!this._isDoingComposition&&"keyboard"===e){var t=ii.getAllAutoClosedCharacters(this._autoClosedActions);this._executeEditOperation(Jn.a.compositionEndWithInterceptors(this._prevEditOperationType,this.context.config,this.context.model,this.getSelections(),t))}},t.prototype._type=function(e,t){if(this._isDoingComposition||"keyboard"!==e)this._executeEditOperation(Jn.a.typeWithoutInterceptors(this._prevEditOperationType,this.context.config,this.context.model,this.getSelections(),t));else for(var n=0,i=t.length;n0&&(o[0]._isTracked=!0);var u=e.model.pushEditOperations(e.selectionsBefore,o,function(n){for(var i=[],r=0;r0?(i[n].sort(u),c[n]=t[n].computeCursorState(e.model,{getInverseEditOperations:function(){return i[n]},getTrackedSelection:function(t){var n=parseInt(t,10),i=e.model._getTrackedRange(e.trackedRanges[n]);return 0===e.trackedRangesDirection[n]?new he.a(i.startLineNumber,i.startColumn,i.endLineNumber,i.endColumn):new he.a(i.endLineNumber,i.endColumn,i.startLineNumber,i.startColumn)}})):c[n]=e.selectionsBefore[n]};for(r=0;rr.identifier.major?i.identifier.major:r.identifier.major).toString()]=!0;for(var s=0;s0&&n--}}return t},e}(),si=n("lthF"),ai=n("/9db"),ui=n("Skdw"),ci=n("fyvs"),li=function(){function e(){this._instanceId=xe.I(++e.INSTANCE_COUNT),this._heights=[],this._minWidths=[],this._ids=[],this._afterLineNumbers=[],this._ordinals=[],this._prefixSum=[],this._prefixSumValidIndex=-1,this._whitespaceId2Index={},this._lastWhitespaceId=0,this._minWidth=-1}return e.findInsertionIndex=function(e,t,n,i){for(var r=0,o=e.length;r>>1;t===e[s]?i=t&&(this._whitespaceId2Index[c]=l+1)}this._whitespaceId2Index[e]=t,this._prefixSumValidIndex=Math.min(this._prefixSumValidIndex,t-1)},e.prototype.changeWhitespace=function(e,t,n){t|=0,n|=0;var i=!1;return i=this.changeWhitespaceHeight(e,n)||i,i=this.changeWhitespaceAfterLineNumber(e,t)||i},e.prototype.changeWhitespaceHeight=function(e,t){if(t|=0,this._whitespaceId2Index.hasOwnProperty(e)){var n=this._whitespaceId2Index[e];if(this._heights[n]!==t)return this._heights[n]=t,this._prefixSumValidIndex=Math.min(this._prefixSumValidIndex,n-1),!0}return!1},e.prototype.changeWhitespaceAfterLineNumber=function(t,n){if(n|=0,this._whitespaceId2Index.hasOwnProperty(t)){var i=this._whitespaceId2Index[t];if(this._afterLineNumbers[i]!==n){var r=this._ordinals[i],o=this._heights[i],s=this._minWidths[i];this.removeWhitespace(t);var a=e.findInsertionIndex(this._afterLineNumbers,n,this._ordinals,r);return this._insertWhitespaceAtIndex(t,a,n,r,o,s),!0}}return!1},e.prototype.removeWhitespace=function(e){if(this._whitespaceId2Index.hasOwnProperty(e)){var t=this._whitespaceId2Index[e];return delete this._whitespaceId2Index[e],this._removeWhitespaceAtIndex(t),this._minWidth=-1,!0}return!1},e.prototype._removeWhitespaceAtIndex=function(e){e|=0,this._heights.splice(e,1),this._minWidths.splice(e,1),this._ids.splice(e,1),this._afterLineNumbers.splice(e,1),this._ordinals.splice(e,1),this._prefixSum.splice(e,1),this._prefixSumValidIndex=Math.min(this._prefixSumValidIndex,e-1);for(var t=Object.keys(this._whitespaceId2Index),n=0,i=t.length;n=e&&(this._whitespaceId2Index[r]=o-1)}},e.prototype.onLinesDeleted=function(e,t){e|=0,t|=0;for(var n=0,i=this._afterLineNumbers.length;nt&&(this._afterLineNumbers[n]-=t-e+1)}},e.prototype.onLinesInserted=function(e,t){e|=0,t|=0;for(var n=0,i=this._afterLineNumbers.length;n=t.length||t[r+1]>=e)return r;n=r+1|0}else i=r-1|0}return-1},e.prototype._findFirstWhitespaceAfterLineNumber=function(e){e|=0;var t=this._findLastWhitespaceBeforeLineNumber(e)+1;return t1?this._lineHeight*(e-1):0)+this._whitespaces.getAccumulatedHeightBeforeLineNumber(e)},e.prototype.getWhitespaceAccumulatedHeightBeforeLineNumber=function(e){return this._whitespaces.getAccumulatedHeightBeforeLineNumber(e)},e.prototype.getWhitespaceMinWidth=function(){return this._whitespaces.getMinWidth()},e.prototype.isAfterLines=function(e){return e>this.getLinesTotalHeight()},e.prototype.getLineNumberAtOrAfterVerticalOffset=function(e){if((e|=0)<0)return 1;for(var t=0|this._lineCount,n=this._lineHeight,i=1,r=t;i=s+n)i=o+1;else{if(e>=s)return o;r=o}}return i>t?t:i},e.prototype.getLinesViewportData=function(e,t){e|=0,t|=0;var n,i,r=this._lineHeight,o=0|this.getLineNumberAtOrAfterVerticalOffset(e),s=0|this.getVerticalOffsetForLineNumber(o),a=0|this._lineCount,u=0|this._whitespaces.getFirstWhitespaceIndexAfterLineNumber(o),c=0|this._whitespaces.getCount();-1===u?(u=c,i=a+1,n=0):(i=0|this._whitespaces.getAfterLineNumberForWhitespaceIndex(u),n=0|this._whitespaces.getHeightForWhitespaceIndex(u));var l=s,d=l,h=0;s>=5e5&&(h=5e5*Math.floor(s/5e5),d-=h=Math.floor(h/r)*r);for(var f=[],p=e+(t-e)/2,g=-1,m=o;m<=a;m++){if(-1===g){(l<=p&&pp)&&(g=m)}for(l+=r,f[m-o]=d,d+=r;i===m;)d+=n,l+=n,++u>=c?i=a+1:(i=0|this._whitespaces.getAfterLineNumberForWhitespaceIndex(u),n=0|this._whitespaces.getHeightForWhitespaceIndex(u));if(l>=t){a=m;break}}-1===g&&(g=a);var v=0|this.getVerticalOffsetForLineNumber(a),_=o,b=a;return _t&&b--,{bigNumbersDelta:h,startLineNumber:o,endLineNumber:a,relativeVerticalOffset:f,centeredLineNumber:g,completelyVisibleStartLineNumber:_,completelyVisibleEndLineNumber:b}},e.prototype.getVerticalOffsetForWhitespaceIndex=function(e){e|=0;var t=this._whitespaces.getAfterLineNumberForWhitespaceIndex(e);return(t>=1?this._lineHeight*t:0)+(e>0?this._whitespaces.getAccumulatedHeight(e-1):0)},e.prototype.getWhitespaceIndexAtOrAfterVerticallOffset=function(e){e|=0;var t,n,i=0,r=this._whitespaces.getCount()-1;if(r<0)return-1;if(e>=this.getVerticalOffsetForWhitespaceIndex(r)+this._whitespaces.getHeightForWhitespaceIndex(r))return-1;for(;i=(n=this.getVerticalOffsetForWhitespaceIndex(t))+this._whitespaces.getHeightForWhitespaceIndex(t))i=t+1;else{if(e>=n)return t;r=t}return i},e.prototype.getWhitespaceAtVerticalOffset=function(e){e|=0;var t=this.getWhitespaceIndexAtOrAfterVerticallOffset(e);if(t<0)return null;if(t>=this._whitespaces.getCount())return null;var n=this.getVerticalOffsetForWhitespaceIndex(t);if(n>e)return null;var i=this._whitespaces.getHeightForWhitespaceIndex(t);return{id:this._whitespaces.getIdForWhitespaceIndex(t),afterLineNumber:this._whitespaces.getAfterLineNumberForWhitespaceIndex(t),verticalOffset:n,height:i}},e.prototype.getWhitespaceViewportData=function(e,t){e|=0,t|=0;var n=this.getWhitespaceIndexAtOrAfterVerticallOffset(e),i=this._whitespaces.getCount()-1;if(n<0)return[];for(var r=[],o=n;o<=i;o++){var s=this.getVerticalOffsetForWhitespaceIndex(o),a=this._whitespaces.getHeightForWhitespaceIndex(o);if(s>=t)break;r.push({id:this._whitespaces.getIdForWhitespaceIndex(o),afterLineNumber:this._whitespaces.getAfterLineNumberForWhitespaceIndex(o),verticalOffset:s,height:a})}return r},e.prototype.getWhitespaces=function(){return this._whitespaces.getWhitespaces(this._lineHeight)},e}(),hi=n("e1sR"),fi=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),pi=function(e){function t(t,n,i){var r=e.call(this)||this;return r._configuration=t,r._linesLayout=new di(n,r._configuration.editor.lineHeight),r.scrollable=r._register(new ci.a(0,i)),r._configureSmoothScrollDuration(),r.scrollable.setScrollDimensions({width:t.editor.layoutInfo.contentWidth,height:t.editor.layoutInfo.contentHeight}),r.onDidScroll=r.scrollable.onScroll,r._updateHeight(),r}return fi(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onHeightMaybeChanged=function(){this._updateHeight()},t.prototype._configureSmoothScrollDuration=function(){this.scrollable.setSmoothScrollDuration(this._configuration.editor.viewInfo.smoothScrolling?125:0)},t.prototype.onConfigurationChanged=function(e){e.lineHeight&&this._linesLayout.setLineHeight(this._configuration.editor.lineHeight),e.layoutInfo&&this.scrollable.setScrollDimensions({width:this._configuration.editor.layoutInfo.contentWidth,height:this._configuration.editor.layoutInfo.contentHeight}),e.viewInfo&&this._configureSmoothScrollDuration(),this._updateHeight()},t.prototype.onFlushed=function(e){this._linesLayout.onFlushed(e)},t.prototype.onLinesDeleted=function(e,t){this._linesLayout.onLinesDeleted(e,t)},t.prototype.onLinesInserted=function(e,t){this._linesLayout.onLinesInserted(e,t)},t.prototype._getHorizontalScrollbarHeight=function(e){return 2===this._configuration.editor.viewInfo.scrollbar.horizontal?0:e.width>=e.scrollWidth?0:this._configuration.editor.viewInfo.scrollbar.horizontalScrollbarSize},t.prototype._getTotalHeight=function(){var e=this.scrollable.getScrollDimensions(),t=this._linesLayout.getLinesTotalHeight();return this._configuration.editor.viewInfo.scrollBeyondLastLine?t+=e.height-this._configuration.editor.lineHeight:t+=this._getHorizontalScrollbarHeight(e),Math.max(e.height,t)},t.prototype._updateHeight=function(){this.scrollable.setScrollDimensions({scrollHeight:this._getTotalHeight()})},t.prototype.getCurrentViewport=function(){var e=this.scrollable.getScrollDimensions(),t=this.scrollable.getCurrentScrollPosition();return new hi.f(t.scrollTop,t.scrollLeft,e.width,e.height)},t.prototype.getFutureViewport=function(){var e=this.scrollable.getScrollDimensions(),t=this.scrollable.getFutureScrollPosition();return new hi.f(t.scrollTop,t.scrollLeft,e.width,e.height)},t.prototype._computeScrollWidth=function(e,t){if(!this._configuration.editor.wrappingInfo.isViewportWrapping){var n=this._configuration.editor.viewInfo.scrollBeyondLastColumn*this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,i=this._linesLayout.getWhitespaceMinWidth();return Math.max(e+n,t,i)}return Math.max(e,t)},t.prototype.onMaxLineWidthChanged=function(e){var t=this._computeScrollWidth(e,this.getCurrentViewport().width);this.scrollable.setScrollDimensions({scrollWidth:t}),this._updateHeight()},t.prototype.saveState=function(){var e=this.scrollable.getFutureScrollPosition(),t=e.scrollTop,n=this._linesLayout.getLineNumberAtOrAfterVerticalOffset(t);return{scrollTop:t,scrollTopWithoutViewZones:t-this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(n),scrollLeft:e.scrollLeft}},t.prototype.addWhitespace=function(e,t,n,i){return this._linesLayout.insertWhitespace(e,t,n,i)},t.prototype.changeWhitespace=function(e,t,n){return this._linesLayout.changeWhitespace(e,t,n)},t.prototype.removeWhitespace=function(e){return this._linesLayout.removeWhitespace(e)},t.prototype.getVerticalOffsetForLineNumber=function(e){return this._linesLayout.getVerticalOffsetForLineNumber(e)},t.prototype.isAfterLines=function(e){return this._linesLayout.isAfterLines(e)},t.prototype.getLineNumberAtVerticalOffset=function(e){return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(e)},t.prototype.getWhitespaceAtVerticalOffset=function(e){return this._linesLayout.getWhitespaceAtVerticalOffset(e)},t.prototype.getLinesViewportData=function(){var e=this.getCurrentViewport();return this._linesLayout.getLinesViewportData(e.top,e.top+e.height)},t.prototype.getLinesViewportDataAtScrollTop=function(e){var t=this.scrollable.getScrollDimensions();return e+t.height>t.scrollHeight&&(e=t.scrollHeight-t.height),e<0&&(e=0),this._linesLayout.getLinesViewportData(e,e+t.height)},t.prototype.getWhitespaceViewportData=function(){var e=this.getCurrentViewport();return this._linesLayout.getWhitespaceViewportData(e.top,e.top+e.height)},t.prototype.getWhitespaces=function(){return this._linesLayout.getWhitespaces()},t.prototype.getScrollWidth=function(){return this.scrollable.getScrollDimensions().scrollWidth},t.prototype.getScrollHeight=function(){return this.scrollable.getScrollDimensions().scrollHeight},t.prototype.getCurrentScrollLeft=function(){return this.scrollable.getCurrentScrollPosition().scrollLeft},t.prototype.getCurrentScrollTop=function(){return this.scrollable.getCurrentScrollPosition().scrollTop},t.prototype.validateScrollPosition=function(e){return this.scrollable.validateScrollPosition(e)},t.prototype.setScrollPositionNow=function(e){this.scrollable.setScrollPositionNow(e)},t.prototype.setScrollPositionSmooth=function(e){this.scrollable.setScrollPositionSmooth(e)},t.prototype.deltaScrollNow=function(e,t){var n=this.scrollable.getCurrentScrollPosition();this.scrollable.setScrollPositionNow({scrollLeft:n.scrollLeft+e,scrollTop:n.scrollTop+t})},t}(u.a),gi=n("GfE5"),mi=n("CQAd"),vi=n("Y6WZ"),_i=n("0ly5"),bi=function(){return function(e,t){this.outputLineIndex=e,this.outputOffset=t}}(),yi=function(){function e(e){this._lines=e}return e.prototype.convertViewPositionToModelPosition=function(e){return this._lines.convertViewPositionToModelPosition(e.lineNumber,e.column)},e.prototype.convertViewRangeToModelRange=function(e){var t=this._lines.convertViewPositionToModelPosition(e.startLineNumber,e.startColumn),n=this._lines.convertViewPositionToModelPosition(e.endLineNumber,e.endColumn);return new te.a(t.lineNumber,t.column,n.lineNumber,n.column)},e.prototype.validateViewPosition=function(e,t){return this._lines.validateViewPosition(e.lineNumber,e.column,t)},e.prototype.validateViewRange=function(e,t){var n=this._lines.validateViewPosition(e.startLineNumber,e.startColumn,t.getStartPosition()),i=this._lines.validateViewPosition(e.endLineNumber,e.endColumn,t.getEndPosition());return new te.a(n.lineNumber,n.column,i.lineNumber,i.column)},e.prototype.convertModelPositionToViewPosition=function(e){return this._lines.convertModelPositionToViewPosition(e.lineNumber,e.column)},e.prototype.convertModelRangeToViewRange=function(e){var t=this._lines.convertModelPositionToViewPosition(e.startLineNumber,e.startColumn),n=this._lines.convertModelPositionToViewPosition(e.endLineNumber,e.endColumn);return new te.a(t.lineNumber,t.column,n.lineNumber,n.column)},e.prototype.modelPositionIsVisible=function(e){return this._lines.modelPositionIsVisible(e.lineNumber,e.column)},e}(),wi=function(){function e(e,t,n,i,r,o){this.model=e,this._validModelVersionId=-1,this.tabSize=n,this.wrappingColumn=i,this.columnsForFullWidthChar=r,this.wrappingIndent=o,this.linePositionMapperFactory=t,this._constructLines(!0)}return e.prototype.dispose=function(){this.hiddenAreasIds=this.model.deltaDecorations(this.hiddenAreasIds,[])},e.prototype.createCoordinatesConverter=function(){return new yi(this)},e.prototype._ensureValidState=function(){if(this.model.getVersionId()!==this._validModelVersionId)throw new Error("ViewModel is out of sync with Model!");this.lines.length!==this.model.getLineCount()&&this._constructLines(!1)},e.prototype._constructLines=function(e){var t=this;this.lines=[],e&&(this.hiddenAreasIds=[]);for(var n=this.model.getLinesContent(),i=n.length,r=new Uint32Array(i),o=this.hiddenAreasIds.map(function(e){return t.model.getDecorationRange(e)}).sort(te.a.compareRangesUsingStarts),s=1,a=0,u=-1,c=u+1=s&&d<=a,f=Li(this.linePositionMapperFactory,n[l],this.tabSize,this.wrappingColumn,this.columnsForFullWidthChar,this.wrappingIndent,!h);r[l]=f.getViewLineCount(),this.lines[l]=f}this._validModelVersionId=this.model.getVersionId(),this.prefixSumComputer=new vi.b(r)},e.prototype.getHiddenAreas=function(){var e=this;return this.hiddenAreasIds.map(function(t){return e.model.getDecorationRange(t)})},e.prototype._reduceRanges=function(e){var t=this;if(0===e.length)return[];for(var n=e.map(function(e){return t.model.validateRange(e)}).sort(te.a.compareRangesUsingStarts),i=[],r=n[0].startLineNumber,o=n[0].endLineNumber,s=1,a=n.length;so+1?(i.push(new te.a(r,1,o,1)),r=u.startLineNumber,o=u.endLineNumber):u.endLineNumber>o&&(o=u.endLineNumber)}return i.push(new te.a(r,1,o,1)),i},e.prototype.setHiddenAreas=function(e){var t=this,n=this._reduceRanges(e),i=this.hiddenAreasIds.map(function(e){return t.model.getDecorationRange(e)}).sort(te.a.compareRangesUsingStarts);if(n.length===i.length){for(var r=!1,o=0;o=d&&m<=h?this.lines[o].isVisible()&&(this.lines[o]=this.lines[o].setVisible(!1),v=!0):(g=!0,this.lines[o].isVisible()||(this.lines[o]=this.lines[o].setVisible(!0),v=!0)),v){var _=this.lines[o].getViewLineCount();this.prefixSumComputer.changeValue(o,_)}}return g||this.setHiddenAreas([]),!0},e.prototype.modelPositionIsVisible=function(e,t){return!(e<1||e>this.lines.length)&&this.lines[e-1].isVisible()},e.prototype.setTabSize=function(e){return this.tabSize!==e&&(this.tabSize=e,this._constructLines(!1),!0)},e.prototype.setWrappingSettings=function(e,t,n){return(this.wrappingIndent!==e||this.wrappingColumn!==t||this.columnsForFullWidthChar!==n)&&(this.wrappingIndent=e,this.wrappingColumn=t,this.columnsForFullWidthChar=n,this._constructLines(!1),!0)},e.prototype.onModelFlushed=function(){this._constructLines(!0)},e.prototype.onModelLinesDeleted=function(e,t,n){if(e<=this._validModelVersionId)return null;var i=1===t?1:this.prefixSumComputer.getAccumulatedValue(t-2)+1,r=this.prefixSumComputer.getAccumulatedValue(n-1);return this.lines.splice(t-1,n-t+1),this.prefixSumComputer.removeValues(t-1,n-t+1),new ze(i,r)},e.prototype.onModelLinesInserted=function(e,t,n,i){if(e<=this._validModelVersionId)return null;for(var r=this.getHiddenAreas(),o=!1,s=new ee.a(t,1),a=0,u=r;aa?(p=(f=(l=(c=1===t?1:this.prefixSumComputer.getAccumulatedValue(t-2)+1)+a-1)+1)+(r-a)-1,u=!0):rt?t:e},e.prototype.warmUpLookupCache=function(e,t){this.prefixSumComputer.warmUpCache(e-1,t-1)},e.prototype.getActiveIndentGuide=function(e,t,n){this._ensureValidState(),e=this._toValidViewLineNumber(e),t=this._toValidViewLineNumber(t),n=this._toValidViewLineNumber(n);var i=this.convertViewPositionToModelPosition(e,this.getViewLineMinColumn(e)),r=this.convertViewPositionToModelPosition(t,this.getViewLineMinColumn(t)),o=this.convertViewPositionToModelPosition(n,this.getViewLineMinColumn(n)),s=this.model.getActiveIndentGuide(i.lineNumber,r.lineNumber,o.lineNumber),a=this.convertModelPositionToViewPosition(s.startLineNumber,1),u=this.convertModelPositionToViewPosition(s.endLineNumber,this.model.getLineMaxColumn(s.endLineNumber));return{startLineNumber:a.lineNumber,endLineNumber:u.lineNumber,indent:s.indent}},e.prototype.getViewLinesIndentGuides=function(e,t){this._ensureValidState(),e=this._toValidViewLineNumber(e),t=this._toValidViewLineNumber(t);for(var n=this.convertViewPositionToModelPosition(e,this.getViewLineMinColumn(e)),i=this.convertViewPositionToModelPosition(t,this.getViewLineMaxColumn(t)),r=[],o=[],s=[],a=n.lineNumber-1,u=i.lineNumber-1,c=null,l=a;l<=u;l++){var d=this.lines[l];if(d.isVisible()){var h=d.getViewLineNumberOfModelPosition(0,l===a?n.column:1),f=d.getViewLineNumberOfModelPosition(0,this.model.getLineMaxColumn(l+1)),p=0;(w=f-h+1)>1&&1===d.getViewLineMinColumn(this.model,l+1,f)&&(p=0===h?1:2),o.push(w),s.push(p),null===c&&(c=new ee.a(l+1,0))}else null!==c&&(r=r.concat(this.model.getLinesIndentGuides(c.lineNumber,l)),c=null)}null!==c&&(r=r.concat(this.model.getLinesIndentGuides(c.lineNumber,i.lineNumber)),c=null);for(var g=t-e+1,m=new Array(g),v=0,_=0,b=r.length;_t&&(f=!0,h=t-r+1);var p=d+h;if(l.getViewLinesData(this.model,u+1,d,p,r-e,n,a),r+=h,f)break}}return a},e.prototype.validateViewPosition=function(e,t,n){this._ensureValidState(),e=this._toValidViewLineNumber(e);var i=this.prefixSumComputer.getIndexOf(e-1),r=i.index,o=i.remainder,s=this.lines[r],a=s.getViewLineMinColumn(this.model,r+1,o),u=s.getViewLineMaxColumn(this.model,r+1,o);tu&&(t=u);var c=s.getModelColumnOfViewPosition(o,t);return this.model.validatePosition(new ee.a(r+1,c)).equals(n)?new ee.a(e,t):this.convertModelPositionToViewPosition(n.lineNumber,n.column)},e.prototype.convertViewPositionToModelPosition=function(e,t){this._ensureValidState(),e=this._toValidViewLineNumber(e);var n=this.prefixSumComputer.getIndexOf(e-1),i=n.index,r=n.remainder,o=this.lines[i].getModelColumnOfViewPosition(r,t);return this.model.validatePosition(new ee.a(i+1,o))},e.prototype.convertModelPositionToViewPosition=function(e,t){this._ensureValidState();for(var n=this.model.validatePosition(new ee.a(e,t)),i=n.lineNumber,r=n.column,o=i-1,s=!1;o>0&&!this.lines[o].isVisible();)o--,s=!0;if(0===o&&!this.lines[o].isVisible())return new ee.a(1,1);var a=1+(0===o?0:this.prefixSumComputer.getAccumulatedValue(o-1));return s?this.lines[o].getViewPositionOfModelPosition(a,this.model.getLineMaxColumn(o+1)):this.lines[i-1].getViewPositionOfModelPosition(a,r)},e.prototype._getViewLineNumberForModelPosition=function(e,t){var n=e-1;if(this.lines[n].isVisible()){var i=1+(0===n?0:this.prefixSumComputer.getAccumulatedValue(n-1));return this.lines[n].getViewLineNumberOfModelPosition(i,t)}for(;n>0&&!this.lines[n].isVisible();)n--;if(0===n&&!this.lines[n].isVisible())return 1;var r=1+(0===n?0:this.prefixSumComputer.getAccumulatedValue(n-1));return this.lines[n].getViewLineNumberOfModelPosition(r,this.model.getLineMaxColumn(n+1))},e.prototype.getAllOverviewRulerDecorations=function(e,t,n){for(var i=this.model.getOverviewRulerDecorations(e,t),r=new Ni,o=0,s=i;ot.id?1:0:n});for(var d=[],h=0,f=null,p=0,g=o;p0&&(o=this.wrappedIndent+o),o},e.prototype.getViewLineLength=function(e,t,n){if(!this._isVisible)throw new Error("Not supported");var i=this.getInputStartOffsetOfOutputLineIndex(n),r=this.getInputEndOffsetOfOutputLineIndex(e,t,n)-i;return n>0&&(r=this.wrappedIndent.length+r),r},e.prototype.getViewLineMinColumn=function(e,t,n){if(!this._isVisible)throw new Error("Not supported");return n>0?this.wrappedIndentLength+1:1},e.prototype.getViewLineMaxColumn=function(e,t,n){if(!this._isVisible)throw new Error("Not supported");return this.getViewLineContent(e,t,n).length+1},e.prototype.getViewLineData=function(e,t,n){if(!this._isVisible)throw new Error("Not supported");var i=this.getInputStartOffsetOfOutputLineIndex(n),r=this.getInputEndOffsetOfOutputLineIndex(e,t,n),o=e.getValueInRange({startLineNumber:t,startColumn:i+1,endLineNumber:t,endColumn:r+1});n>0&&(o=this.wrappedIndent+o);var s=n>0?this.wrappedIndentLength+1:1,a=o.length+1,u=n+10&&(c=this.wrappedIndentLength);var l=e.getLineTokens(t);return new hi.c(o,u,s,a,l.sliceAndInflate(i,r,c))},e.prototype.getViewLinesData=function(e,t,n,i,r,o,s){if(!this._isVisible)throw new Error("Not supported");for(var a=n;a0&&(n0&&(r+=this.wrappedIndentLength),new ee.a(e+i,r)},e.prototype.getViewLineNumberOfModelPosition=function(e,t){if(!this._isVisible)throw new Error("Not supported");return e+this.positionMapper.getOutputPositionOfInputOffset(t-1).outputLineIndex},e}();function Li(e,t,n,i,r,o,s){var a=e.createLineMapping(t,n,i,r,o);return null===a?s?Ci.INSTANCE:Si.INSTANCE:new xi(a,s)}var Oi=function(){function e(e){this._lines=e}return e.prototype._validPosition=function(e){return this._lines.model.validatePosition(e)},e.prototype._validRange=function(e){return this._lines.model.validateRange(e)},e.prototype.convertViewPositionToModelPosition=function(e){return this._validPosition(e)},e.prototype.convertViewRangeToModelRange=function(e){return this._validRange(e)},e.prototype.validateViewPosition=function(e,t){return this._validPosition(t)},e.prototype.validateViewRange=function(e,t){return this._validRange(t)},e.prototype.convertModelPositionToViewPosition=function(e){return this._validPosition(e)},e.prototype.convertModelRangeToViewRange=function(e){return this._validRange(e)},e.prototype.modelPositionIsVisible=function(e){var t=this._lines.model.getLineCount();return!(e.lineNumber<1||e.lineNumber>t)},e}(),ki=function(){function e(e){this.model=e}return e.prototype.dispose=function(){},e.prototype.createCoordinatesConverter=function(){return new Oi(this)},e.prototype.getHiddenAreas=function(){return[]},e.prototype.setHiddenAreas=function(e){return!1},e.prototype.setTabSize=function(e){return!1},e.prototype.setWrappingSettings=function(e,t,n){return!1},e.prototype.onModelFlushed=function(){},e.prototype.onModelLinesDeleted=function(e,t,n){return new ze(t,n)},e.prototype.onModelLinesInserted=function(e,t,n,i){return new Ue(t,n)},e.prototype.onModelLineChanged=function(e,t,n){return[!1,new He(t,t),null,null]},e.prototype.acceptVersionId=function(e){},e.prototype.getViewLineCount=function(){return this.model.getLineCount()},e.prototype.warmUpLookupCache=function(e,t){},e.prototype.getActiveIndentGuide=function(e,t,n){return{startLineNumber:e,endLineNumber:e,indent:0}},e.prototype.getViewLinesIndentGuides=function(e,t){for(var n=t-e+1,i=new Array(n),r=0;r=t)return void(n>s&&(r[r.length-1]=n));r.push(i,t,n)}else this.result[e]=[i,t,n]},e}(),Ei=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Ii=function(e){function t(t,n,i){for(var r=e.call(this,0)||this,o=0;o=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959?4:e.prototype.get.call(this,t)},t}(gi.a),Di=function(){function e(e,t,n){this.classifier=new Ii(e,t,n)}return e.nextVisibleColumn=function(e,t,n,i){return e=+e,t=+t,i=+i,n?e+(t-e%t):e+i},e.prototype.createLineMapping=function(t,n,i,r,o){if(-1===i)return null;n=+n,i=+i,r=+r;var s=0,a="",u=-1;if(0!==(o=+o)&&-1!==(u=xe.q(t))){a=t.substring(0,u);for(var c=0;ci&&(a="",s=0)}var d=this.classifier,h=0,f=[],p=0,g=0,m=-1,v=0,_=-1,b=0,y=t.length;for(c=0;c0){var x=t.charCodeAt(c-1);1!==d.get(x)&&(m=c,v=s)}var L=1;if(xe.v(w)&&(L=r),(g=e.nextVisibleColumn(g,n,C,L))>i&&0!==c){var O=void 0,k=void 0;-1!==m&&v<=i?(O=m,k=v):-1!==_&&b<=i?(O=_,k=b):(O=c,k=s),f[p++]=O-h,h=O,g=e.nextVisibleColumn(k,n,C,L),m=-1,v=0,_=-1,b=0}if(-1!==m&&(v=e.nextVisibleColumn(v,n,C,L)),-1!==_&&(b=e.nextVisibleColumn(b,n,C,L)),2===S&&(0===o||c>=u)&&(m=c+1,v=s),4===S&&c=2&&e.viewportStartLineTrackedRange){var g=e.model._getTrackedRange(e.viewportStartLineTrackedRange);if(g){var m=e.coordinatesConverter.convertModelPositionToViewPosition(g.getStartPosition()),v=e.viewLayout.getVerticalOffsetForLineNumber(m.lineNumber);e.viewLayout.setScrollPositionNow({scrollTop:v+e.viewportStartLineDelta})}}})),this._register(this.model.onDidChangeTokens(function(t){for(var n=[],i=0,r=t.ranges.length;ia||(o0&&s[u-1]===s[u]||(a+=this.model.getLineContent(s[u])+r);return a}for(var c=[],l=0,d=o;l'+this._getHTMLToCopy(n,o)+""},t.prototype._getHTMLToCopy=function(e,t){for(var n=e.startLineNumber,i=e.startColumn,r=e.endLineNumber,o=e.endColumn,s=this.getTabSize(),a="",u=n;u<=r;u++){var c=this.model.getLineTokens(u),l=c.getLineContent(),d=u===n?i-1:0,h=u===r?o-1:l.length;a+=""===l?"
    ":Object(ui.a)(l,c.inflate(),t,d,h,s)}return a},t.prototype._getColorMap=function(){var e=Kt.y.getColorMap(),t=["#000000"];if(e)for(var n=1,i=e.length;n=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},qi=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Gi=0,Zi="showUnused",Yi=function(){function e(e,t,n,i,r,o){this.model=e,this.viewModel=t,this.cursor=n,this.view=i,this.hasRealView=r,this.listenersToRemove=o}return e.prototype.dispose=function(){Object(u.f)(this.listenersToRemove),this.model.onBeforeDetached(),this.hasRealView&&this.view.dispose(),this.cursor.dispose(),this.viewModel.dispose()},e}(),Xi=function(e){function t(t,n,i,r,o,u,c,l,h,f){var p,g=e.call(this)||this;g._onDidDispose=g._register(new a.a),g.onDidDispose=g._onDidDispose.event,g._onDidChangeModelContent=g._register(new a.a),g.onDidChangeModelContent=g._onDidChangeModelContent.event,g._onDidChangeModelLanguage=g._register(new a.a),g.onDidChangeModelLanguage=g._onDidChangeModelLanguage.event,g._onDidChangeModelLanguageConfiguration=g._register(new a.a),g.onDidChangeModelLanguageConfiguration=g._onDidChangeModelLanguageConfiguration.event,g._onDidChangeModelOptions=g._register(new a.a),g.onDidChangeModelOptions=g._onDidChangeModelOptions.event,g._onDidChangeModelDecorations=g._register(new a.a),g.onDidChangeModelDecorations=g._onDidChangeModelDecorations.event,g._onDidChangeConfiguration=g._register(new a.a),g.onDidChangeConfiguration=g._onDidChangeConfiguration.event,g._onDidChangeModel=g._register(new a.a),g.onDidChangeModel=g._onDidChangeModel.event,g._onDidChangeCursorPosition=g._register(new a.a),g.onDidChangeCursorPosition=g._onDidChangeCursorPosition.event,g._onDidChangeCursorSelection=g._register(new a.a),g.onDidChangeCursorSelection=g._onDidChangeCursorSelection.event,g._onDidAttemptReadOnlyEdit=g._register(new a.a),g.onDidAttemptReadOnlyEdit=g._onDidAttemptReadOnlyEdit.event,g._onDidLayoutChange=g._register(new a.a),g.onDidLayoutChange=g._onDidLayoutChange.event,g._editorTextFocus=g._register(new $i),g.onDidFocusEditorText=g._editorTextFocus.onDidChangeToTrue,g.onDidBlurEditorText=g._editorTextFocus.onDidChangeToFalse,g._editorWidgetFocus=g._register(new $i),g.onDidFocusEditorWidget=g._editorWidgetFocus.onDidChangeToTrue,g.onDidBlurEditorWidget=g._editorWidgetFocus.onDidChangeToFalse,g._onWillType=g._register(new a.a),g.onWillType=g._onWillType.event,g._onDidType=g._register(new a.a),g.onDidType=g._onDidType.event,g._onCompositionStart=g._register(new a.a),g.onCompositionStart=g._onCompositionStart.event,g._onCompositionEnd=g._register(new a.a),g.onCompositionEnd=g._onCompositionEnd.event,g._onDidPaste=g._register(new a.a),g.onDidPaste=g._onDidPaste.event,g._onMouseUp=g._register(new a.a),g.onMouseUp=g._onMouseUp.event,g._onMouseDown=g._register(new a.a),g.onMouseDown=g._onMouseDown.event,g._onMouseDrag=g._register(new a.a),g.onMouseDrag=g._onMouseDrag.event,g._onMouseDrop=g._register(new a.a),g.onMouseDrop=g._onMouseDrop.event,g._onContextMenu=g._register(new a.a),g.onContextMenu=g._onContextMenu.event,g._onMouseMove=g._register(new a.a),g.onMouseMove=g._onMouseMove.event,g._onMouseLeave=g._register(new a.a),g.onMouseLeave=g._onMouseLeave.event,g._onMouseWheel=g._register(new a.a),g.onMouseWheel=g._onMouseWheel.event,g._onKeyUp=g._register(new a.a),g.onKeyUp=g._onKeyUp.event,g._onKeyDown=g._register(new a.a),g.onKeyDown=g._onKeyDown.event,g._onDidScrollChange=g._register(new a.a),g.onDidScrollChange=g._onDidScrollChange.event,g._onDidChangeViewZones=g._register(new a.a),g.onDidChangeViewZones=g._onDidChangeViewZones.event,g._domElement=t,g._id=++Gi,g._decorationTypeKeysToIds={},g._decorationTypeSubtypes={},g.isSimpleWidget=i.isSimpleWidget||!1,g._telemetryData=i.telemetryData,n=n||{},g._configuration=g._register(g._createConfiguration(n,f)),g._register(g._configuration.onDidChange(function(e){g._onDidChangeConfiguration.fire(e),e.layoutInfo&&g._onDidLayoutChange.fire(g._configuration.editor.layoutInfo),g._configuration.editor.showUnused?g._domElement.classList.add(Zi):g._domElement.classList.remove(Zi)})),g._contextKeyService=g._register(c.createScoped(g._domElement)),g._notificationService=h,g._codeEditorService=o,g._commandService=u,g._themeService=l,g._register(new Ji(g,g._contextKeyService)),g._register(new Qi(g,g._contextKeyService)),g._instantiationService=r.createChild(new Bi.a([ji.c,g._contextKeyService])),g._modelData=null,g._contributions={},g._actions={},g._focusTracker=new er(t),g._focusTracker.onChange(function(){g._editorWidgetFocus.setValue(g._focusTracker.hasFocus())}),g._contentWidgets={},g._overlayWidgets={};for(var m=0,v=(p=Array.isArray(i.contributions)?i.contributions:d.d.getEditorContributions()).length;m1),this._hasNonEmptySelection.set(e.some(function(e){return!e.isEmpty()}))):(this._hasMultipleSelections.reset(),this._hasNonEmptySelection.reset())},t.prototype._updateFromFocus=function(){this._editorFocus.set(this._editor.hasWidgetFocus()&&!this._editor.isSimpleWidget),this._editorTextFocus.set(this._editor.hasTextFocus()&&!this._editor.isSimpleWidget),this._textInputFocus.set(this._editor.hasTextFocus())},t.prototype._updateFromModel=function(){var e=this._editor.getModel();this._canUndo.set(Boolean(e&&e.canUndo())),this._canRedo.set(Boolean(e&&e.canRedo()))},t}(u.a),Qi=function(e){function t(t,n){var i=e.call(this)||this;i._editor=t,i._contextKeyService=n,i._langId=ai.a.languageId.bindTo(n),i._hasCompletionItemProvider=ai.a.hasCompletionItemProvider.bindTo(n),i._hasCodeActionsProvider=ai.a.hasCodeActionsProvider.bindTo(n),i._hasCodeLensProvider=ai.a.hasCodeLensProvider.bindTo(n),i._hasDefinitionProvider=ai.a.hasDefinitionProvider.bindTo(n),i._hasDeclarationProvider=ai.a.hasDeclarationProvider.bindTo(n),i._hasImplementationProvider=ai.a.hasImplementationProvider.bindTo(n),i._hasTypeDefinitionProvider=ai.a.hasTypeDefinitionProvider.bindTo(n),i._hasHoverProvider=ai.a.hasHoverProvider.bindTo(n),i._hasDocumentHighlightProvider=ai.a.hasDocumentHighlightProvider.bindTo(n),i._hasDocumentSymbolProvider=ai.a.hasDocumentSymbolProvider.bindTo(n),i._hasReferenceProvider=ai.a.hasReferenceProvider.bindTo(n),i._hasRenameProvider=ai.a.hasRenameProvider.bindTo(n),i._hasSignatureHelpProvider=ai.a.hasSignatureHelpProvider.bindTo(n),i._hasDocumentFormattingProvider=ai.a.hasDocumentFormattingProvider.bindTo(n),i._hasDocumentSelectionFormattingProvider=ai.a.hasDocumentSelectionFormattingProvider.bindTo(n),i._hasMultipleDocumentFormattingProvider=ai.a.hasMultipleDocumentFormattingProvider.bindTo(n),i._hasMultipleDocumentSelectionFormattingProvider=ai.a.hasMultipleDocumentSelectionFormattingProvider.bindTo(n),i._isInWalkThrough=ai.a.isInEmbeddedEditor.bindTo(n);var r=function(){return i._update()};return i._register(t.onDidChangeModel(r)),i._register(t.onDidChangeModelLanguage(r)),i._register(Kt.d.onDidChange(r)),i._register(Kt.a.onDidChange(r)),i._register(Kt.b.onDidChange(r)),i._register(Kt.f.onDidChange(r)),i._register(Kt.e.onDidChange(r)),i._register(Kt.o.onDidChange(r)),i._register(Kt.z.onDidChange(r)),i._register(Kt.n.onDidChange(r)),i._register(Kt.i.onDidChange(r)),i._register(Kt.k.onDidChange(r)),i._register(Kt.s.onDidChange(r)),i._register(Kt.t.onDidChange(r)),i._register(Kt.g.onDidChange(r)),i._register(Kt.j.onDidChange(r)),i._register(Kt.v.onDidChange(r)),r(),i}return Ui(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.reset=function(){var e=this;this._contextKeyService.bufferChangeEvents(function(){e._langId.reset(),e._hasCompletionItemProvider.reset(),e._hasCodeActionsProvider.reset(),e._hasCodeLensProvider.reset(),e._hasDefinitionProvider.reset(),e._hasDeclarationProvider.reset(),e._hasImplementationProvider.reset(),e._hasTypeDefinitionProvider.reset(),e._hasHoverProvider.reset(),e._hasDocumentHighlightProvider.reset(),e._hasDocumentSymbolProvider.reset(),e._hasReferenceProvider.reset(),e._hasRenameProvider.reset(),e._hasDocumentFormattingProvider.reset(),e._hasDocumentSelectionFormattingProvider.reset(),e._hasSignatureHelpProvider.reset(),e._isInWalkThrough.reset()})},t.prototype._update=function(){var e=this,t=this._editor.getModel();t?this._contextKeyService.bufferChangeEvents(function(){e._langId.set(t.getLanguageIdentifier().language),e._hasCompletionItemProvider.set(Kt.d.has(t)),e._hasCodeActionsProvider.set(Kt.a.has(t)),e._hasCodeLensProvider.set(Kt.b.has(t)),e._hasDefinitionProvider.set(Kt.f.has(t)),e._hasDeclarationProvider.set(Kt.e.has(t)),e._hasImplementationProvider.set(Kt.o.has(t)),e._hasTypeDefinitionProvider.set(Kt.z.has(t)),e._hasHoverProvider.set(Kt.n.has(t)),e._hasDocumentHighlightProvider.set(Kt.i.has(t)),e._hasDocumentSymbolProvider.set(Kt.k.has(t)),e._hasReferenceProvider.set(Kt.s.has(t)),e._hasRenameProvider.set(Kt.t.has(t)),e._hasSignatureHelpProvider.set(Kt.v.has(t)),e._hasDocumentFormattingProvider.set(Kt.g.has(t)||Kt.j.has(t)),e._hasDocumentSelectionFormattingProvider.set(Kt.j.has(t)),e._hasMultipleDocumentFormattingProvider.set(Kt.g.all(t).length+Kt.j.all(t).length>1),e._hasMultipleDocumentSelectionFormattingProvider.set(Kt.j.all(t).length>1),e._isInWalkThrough.set(t.uri.scheme===c.b.walkThroughSnippet)}):this.reset()},t}(u.a),er=function(e){function t(t){var n=e.call(this)||this;return n._onChange=n._register(new a.a),n.onChange=n._onChange.event,n._hasFocus=!1,n._domFocusTracker=n._register(o.S(t)),n._register(n._domFocusTracker.onDidFocus(function(){n._hasFocus=!0,n._onChange.fire(void 0)})),n._register(n._domFocusTracker.onDidBlur(function(){n._hasFocus=!1,n._onChange.fire(void 0)})),n}return Ui(t,e),t.prototype.hasFocus=function(){return this._hasFocus},t}(u.a),tr=encodeURIComponent("");function ir(e){return tr+encodeURIComponent(e.toString())+nr}var rr=encodeURIComponent('');Object(V.f)(function(e,t){var n=e.getColor(Qt.p);n&&t.addRule(".monaco-editor .squiggly-error { border-bottom: 4px double "+n+"; }");var i=e.getColor(Qt.q);i&&t.addRule('.monaco-editor .squiggly-error { background: url("data:image/svg+xml,'+ir(i)+'") repeat-x bottom left; }');var r=e.getColor(Qt.L);r&&t.addRule(".monaco-editor .squiggly-warning { border-bottom: 4px double "+r+"; }");var o=e.getColor(Qt.M);o&&t.addRule('.monaco-editor .squiggly-warning { background: url("data:image/svg+xml,'+ir(o)+'") repeat-x bottom left; }');var s=e.getColor(Qt.F);s&&t.addRule(".monaco-editor .squiggly-info { border-bottom: 4px double "+s+"; }");var a=e.getColor(Qt.G);a&&t.addRule('.monaco-editor .squiggly-info { background: url("data:image/svg+xml,'+ir(a)+'") repeat-x bottom left; }');var u=e.getColor(Qt.y);u&&t.addRule(".monaco-editor .squiggly-hint { border-bottom: 2px dotted "+u+"; }");var c=e.getColor(Qt.z);c&&t.addRule('.monaco-editor .squiggly-hint { background: url("data:image/svg+xml,'+(rr+encodeURIComponent(c.toString())+or)+'") no-repeat bottom left; }');var l=e.getColor(Ee.o);l&&t.addRule("."+Zi+" .monaco-editor .squiggly-inline-unnecessary { opacity: "+l.rgba.a+"; }");var d=e.getColor(Ee.n);d&&t.addRule("."+Zi+" .monaco-editor .squiggly-unnecessary { border-bottom: 2px dashed "+d+"; }");var h=e.getColor(Qt.x)||"inherit";t.addRule(".monaco-editor .squiggly-inline-deprecated { text-decoration: line-through; text-decoration-color: "+h+"}")})},vbff:function(e,t,n){"use strict";var i;n.d(t,"a",function(){return i}),function(e){function t(e,t){if(e.start>=t.end||t.start>=e.end)return{start:0,end:0};var n=Math.max(e.start,t.start),i=Math.min(e.end,t.end);return i-n<=0?{start:0,end:0}:{start:n,end:i}}function n(e){return e.end-e.start<=0}e.intersect=t,e.isEmpty=n,e.intersects=function(e,i){return!n(t(e,i))},e.relativeComplement=function(e,t){var i=[],r={start:e.start,end:Math.min(t.start,e.end)},o={start:Math.max(t.end,e.start),end:e.end};return n(r)||i.push(r),n(o)||i.push(o),i}}(i||(i={}))},vugd:function(e,t,n){var i=n("3UtB").Reporter,r=n("3UtB").EncoderBuffer,o=n("3UtB").DecoderBuffer,s=n("08Lv"),a=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(a);function c(e,t){var n={};this._baseState=n,n.enc=e,n.parent=t||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}e.exports=c;var l=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){var e=this._baseState,t={};l.forEach(function(n){t[n]=e[n]});var n=new this.constructor(t.parent);return n._baseState=t,n},c.prototype._wrap=function(){var e=this._baseState;u.forEach(function(t){this[t]=function(){var n=new this.constructor(this);return e.children.push(n),n[t].apply(n,arguments)}},this)},c.prototype._init=function(e){var t=this._baseState;s(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),s.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){var t=this._baseState,n=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==n.length&&(s(null===t.children),t.children=n,n.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(s(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;var t={};return Object.keys(e).forEach(function(n){n==(0|n)&&(n|=0);var i=e[n];t[i]=n}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){c.prototype[e]=function(){var t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}}),a.forEach(function(e){c.prototype[e]=function(){var t=this._baseState,n=Array.prototype.slice.call(arguments);return s(null===t.tag),t.tag=e,this._useArgs(n),this}}),c.prototype.use=function(e){s(e);var t=this._baseState;return s(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){var t=this._baseState;return s(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){var t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){var t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){var e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){var t=this._baseState;return s(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){var t=this._baseState;return s(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},c.prototype.contains=function(e){var t=this._baseState;return s(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){var n=this._baseState;if(null===n.parent)return e.wrapResult(n.children[0]._decode(e,t));var i,r=n.default,s=!0,a=null;if(null!==n.key&&(a=e.enterKey(n.key)),n.optional){var u=null;if(null!==n.explicit?u=n.explicit:null!==n.implicit?u=n.implicit:null!==n.tag&&(u=n.tag),null!==u||n.any){if(s=this._peekTag(e,u,n.any),e.isError(s))return s}else{var c=e.save();try{null===n.choice?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),s=!0}catch(e){s=!1}e.restore(c)}}if(n.obj&&s&&(i=e.enterObject()),s){if(null!==n.explicit){var l=this._decodeTag(e,n.explicit);if(e.isError(l))return l;e=l}var d=e.offset;if(null===n.use&&null===n.choice){if(n.any)c=e.save();var h=this._decodeTag(e,null!==n.implicit?n.implicit:n.tag,n.any);if(e.isError(h))return h;n.any?r=e.raw(c):e=h}if(t&&t.track&&null!==n.tag&&t.track(e.path(),d,e.length,"tagged"),t&&t.track&&null!==n.tag&&t.track(e.path(),e.offset,e.length,"content"),r=n.any?r:null===n.choice?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),e.isError(r))return r;if(n.any||null!==n.choice||null===n.children||n.children.forEach(function(n){n._decode(e,t)}),n.contains&&("octstr"===n.tag||"bitstr"===n.tag)){var f=new o(r);r=this._getUse(n.contains,e._reporterState.obj)._decode(f,t)}}return n.obj&&s&&(r=e.leaveObject(i)),null===n.key||null===r&&!0!==s?null!==a&&e.exitKey(a):e.leaveKey(a,n.key,r),r},c.prototype._decodeGeneric=function(e,t,n){var i=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,i.args[0],n):/str$/.test(e)?this._decodeStr(t,e,n):"objid"===e&&i.args?this._decodeObjid(t,i.args[0],i.args[1],n):"objid"===e?this._decodeObjid(t,null,null,n):"gentime"===e||"utctime"===e?this._decodeTime(t,e,n):"null_"===e?this._decodeNull(t,n):"bool"===e?this._decodeBool(t,n):"objDesc"===e?this._decodeStr(t,e,n):"int"===e||"enum"===e?this._decodeInt(t,i.args&&i.args[0],n):null!==i.use?this._getUse(i.use,t._reporterState.obj)._decode(t,n):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){var n=this._baseState;return n.useDecoder=this._use(e,t),s(null===n.useDecoder._baseState.parent),n.useDecoder=n.useDecoder._baseState.children[0],n.implicit!==n.useDecoder._baseState.implicit&&(n.useDecoder=n.useDecoder.clone(),n.useDecoder._baseState.implicit=n.implicit),n.useDecoder},c.prototype._decodeChoice=function(e,t){var n=this._baseState,i=null,r=!1;return Object.keys(n.choice).some(function(o){var s=e.save(),a=n.choice[o];try{var u=a._decode(e,t);if(e.isError(u))return!1;i={type:o,value:u},r=!0}catch(t){return e.restore(s),!1}return!0},this),r?i:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new r(e,this.reporter)},c.prototype._encode=function(e,t,n){var i=this._baseState;if(null===i.default||i.default!==e){var r=this._encodeValue(e,t,n);if(void 0!==r&&!this._skipDefault(r,t,n))return r}},c.prototype._encodeValue=function(e,t,n){var r=this._baseState;if(null===r.parent)return r.children[0]._encode(e,t||new i);var o=null;if(this.reporter=t,r.optional&&void 0===e){if(null===r.default)return;e=r.default}var s=null,a=!1;if(r.any)o=this._createEncoderBuffer(e);else if(r.choice)o=this._encodeChoice(e,t);else if(r.contains)s=this._getUse(r.contains,n)._encode(e,t),a=!0;else if(r.children)s=r.children.map(function(n){if("null_"===n._baseState.tag)return n._encode(null,t,e);if(null===n._baseState.key)return t.error("Child should have a key");var i=t.enterKey(n._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");var r=n._encode(e[n._baseState.key],t,e);return t.leaveKey(i),r},this).filter(function(e){return e}),s=this._createEncoderBuffer(s);else if("seqof"===r.tag||"setof"===r.tag){if(!r.args||1!==r.args.length)return t.error("Too many args for : "+r.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");var u=this.clone();u._baseState.implicit=null,s=this._createEncoderBuffer(e.map(function(n){var i=this._baseState;return this._getUse(i.args[0],e)._encode(n,t)},u))}else null!==r.use?o=this._getUse(r.use,n)._encode(e,t):(s=this._encodePrimitive(r.tag,e),a=!0);if(!r.any&&null===r.choice){var c=null!==r.implicit?r.implicit:r.tag,l=null===r.implicit?"universal":"context";null===c?null===r.use&&t.error("Tag could be omitted only for .use()"):null===r.use&&(o=this._encodeComposite(c,a,l,s))}return null!==r.explicit&&(o=this._encodeComposite(r.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){var n=this._baseState,i=n.choice[e.type];return i||s(!1,e.type+" not found in "+JSON.stringify(Object.keys(n.choice))),i._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){var n=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&n.args)return this._encodeObjid(t,n.reverseArgs[0],n.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,n.args&&n.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(e)}},vzCy:function(e,t,n){"use strict";var i,r="object"==typeof Reflect?Reflect:null,o=r&&"function"==typeof r.apply?r.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};i=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var u=10;function c(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function l(e,t,n,i){var r,o,s,a;if("function"!=typeof n)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n);if(void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),s=o[t]),void 0===s)s=o[t]=n,++e._eventsCount;else if("function"==typeof s?s=o[t]=i?[n,s]:[s,n]:i?s.unshift(n):s.push(n),(r=c(e))>0&&s.length>r&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,a=u,console&&console.warn&&console.warn(a)}return e}function d(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=function(){for(var e=[],t=0;t0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=r[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var c=u.length,l=p(u,c);for(n=0;n=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,r=o;break}if(r<0)return this;0===r?n.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},a.prototype.listeners=function(e){return h(this,e,!0)},a.prototype.rawListeners=function(e){return h(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},a.prototype.listenerCount=f,a.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},wV8Z:function(e,t,n){"use strict";t.d=function(e){var t=[];for(var n in e)i.call(e,n)&&t.push(e[n]);return t},t.b=function(e){for(var t in e)if(i.call(e,t))return e[t];return},t.c=function(e,t){var n=function(n){if(i.call(e,n)){var r=t({key:n,value:e[n]},function(){delete e[n]});if(!1===r)return{value:void 0}}};for(var r in e){var o=n(r);if("object"==typeof o)return o.value}},n.d(t,"a",function(){return r});var i=Object.prototype.hasOwnProperty;var r=function(){function e(){this.map=new Map}return e.prototype.add=function(e,t){var n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)},e.prototype.delete=function(e,t){var n=this.map.get(e);n&&(n.delete(t),0===n.size&&this.map.delete(e))},e.prototype.forEach=function(e,t){var n=this.map.get(e);n&&n.forEach(t)},e}()},wVzJ:function(e,t){},wrMp:function(e,t,n){"use strict";var i=n("tRuz"),r=n("lZ6o"),o=n("geuY"),s=n("LC74"),a=i.base,u=r.utils.assert;function c(e){a.call(this,"short",e),this.a=new o(e.a,16).toRed(this.red),this.b=new o(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function l(e,t,n,i){a.BasePoint.call(this,e,"affine"),null===t&&null===n?(this.x=null,this.y=null,this.inf=!0):(this.x=new o(t,16),this.y=new o(n,16),i&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function d(e,t,n,i){a.BasePoint.call(this,e,"jacobian"),null===t&&null===n&&null===i?(this.x=this.curve.one,this.y=this.curve.one,this.z=new o(0)):(this.x=new o(t,16),this.y=new o(n,16),this.z=new o(i,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}s(c,a),e.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,n;if(e.beta)t=new o(e.beta,16).toRed(this.red);else{var i=this._getEndoRoots(this.p);t=(t=i[0].cmp(i[1])<0?i[0]:i[1]).toRed(this.red)}if(e.lambda)n=new o(e.lambda,16);else{var r=this._getEndoRoots(this.n);0===this.g.mul(r[0]).x.cmp(this.g.x.redMul(t))?n=r[0]:(n=r[1],u(0===this.g.mul(n).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:n,basis:e.basis?e.basis.map(function(e){return{a:new o(e.a,16),b:new o(e.b,16)}}):this._getEndoBasis(n)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:o.mont(e),n=new o(2).toRed(t).redInvm(),i=n.redNeg(),r=new o(3).toRed(t).redNeg().redSqrt().redMul(n);return[i.redAdd(r).fromRed(),i.redSub(r).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,n,i,r,s,a,u,c,l,d=this.n.ushrn(Math.floor(this.n.bitLength()/2)),h=e,f=this.n.clone(),p=new o(1),g=new o(0),m=new o(0),v=new o(1),_=0;0!==h.cmpn(0);){var b=f.div(h);c=f.sub(b.mul(h)),l=m.sub(b.mul(p));var y=v.sub(b.mul(g));if(!i&&c.cmp(d)<0)t=u.neg(),n=p,i=c.neg(),r=l;else if(i&&2==++_)break;u=c,f=h,h=c,m=p,p=l,v=g,g=y}s=c.neg(),a=l;var w=i.sqr().add(r.sqr());return s.sqr().add(a.sqr()).cmp(w)>=0&&(s=t,a=n),i.negative&&(i=i.neg(),r=r.neg()),s.negative&&(s=s.neg(),a=a.neg()),[{a:i,b:r},{a:s,b:a}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,n=t[0],i=t[1],r=i.b.mul(e).divRound(this.n),o=n.b.neg().mul(e).divRound(this.n),s=r.mul(n.a),a=o.mul(i.a),u=r.mul(n.b),c=o.mul(i.b);return{k1:e.sub(s).sub(a),k2:u.add(c).neg()}},c.prototype.pointFromX=function(e,t){(e=new o(e,16)).red||(e=e.toRed(this.red));var n=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),i=n.redSqrt();if(0!==i.redSqr().redSub(n).cmp(this.zero))throw new Error("invalid point");var r=i.fromRed().isOdd();return(t&&!r||!t&&r)&&(i=i.redNeg()),this.point(e,i)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,n=e.y,i=this.a.redMul(t),r=t.redSqr().redMul(t).redIAdd(i).redIAdd(this.b);return 0===n.redSqr().redISub(r).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,n){for(var i=this._endoWnafT1,r=this._endoWnafT2,o=0;o":""},l.prototype.isInfinity=function(){return this.inf},l.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var n=t.redSqr().redISub(this.x).redISub(e.x),i=t.redMul(this.x.redSub(n)).redISub(this.y);return this.curve.point(n,i)},l.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,n=this.x.redSqr(),i=e.redInvm(),r=n.redAdd(n).redIAdd(n).redIAdd(t).redMul(i),o=r.redSqr().redISub(this.x.redAdd(this.x)),s=r.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},l.prototype.getX=function(){return this.x.fromRed()},l.prototype.getY=function(){return this.y.fromRed()},l.prototype.mul=function(e){return e=new o(e,16),this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},l.prototype.mulAdd=function(e,t,n){var i=[this,t],r=[e,n];return this.curve.endo?this.curve._endoWnafMulAdd(i,r):this.curve._wnafMulAdd(1,i,r,2)},l.prototype.jmulAdd=function(e,t,n){var i=[this,t],r=[e,n];return this.curve.endo?this.curve._endoWnafMulAdd(i,r,!0):this.curve._wnafMulAdd(1,i,r,2,!0)},l.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},l.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var n=this.precomputed,i=function(e){return e.neg()};t.precomputed={naf:n.naf&&{wnd:n.naf.wnd,points:n.naf.points.map(i)},doubles:n.doubles&&{step:n.doubles.step,points:n.doubles.points.map(i)}}}return t},l.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},s(d,a.BasePoint),c.prototype.jpoint=function(e,t,n){return new d(this,e,t,n)},d.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),n=this.x.redMul(t),i=this.y.redMul(t).redMul(e);return this.curve.point(n,i)},d.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},d.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),n=this.z.redSqr(),i=this.x.redMul(t),r=e.x.redMul(n),o=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(n.redMul(this.z)),a=i.redSub(r),u=o.redSub(s);if(0===a.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=a.redSqr(),l=c.redMul(a),d=i.redMul(c),h=u.redSqr().redIAdd(l).redISub(d).redISub(d),f=u.redMul(d.redISub(h)).redISub(o.redMul(l)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(h,f,p)},d.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),n=this.x,i=e.x.redMul(t),r=this.y,o=e.y.redMul(t).redMul(this.z),s=n.redSub(i),a=r.redSub(o);if(0===s.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=s.redSqr(),c=u.redMul(s),l=n.redMul(u),d=a.redSqr().redIAdd(c).redISub(l).redISub(l),h=a.redMul(l.redISub(d)).redISub(r.redMul(c)),f=this.z.redMul(s);return this.curve.jpoint(d,h,f)},d.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,n=0;n=0)return!1;if(n.redIAdd(r),0===this.x.cmp(n))return!0}},d.prototype.inspect=function(){return this.isInfinity()?"":""},d.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},wtJh:function(e,t){},x0Ha:function(e,t,n){"use strict";var i=n("ypnx");function r(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var n=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||i.nextTick(r,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(i.nextTick(r,n,e),n._writableState&&(n._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},x33M:function(e,t){},xF6g:function(e,t){},xJaW:function(e,t,n){"use strict";n.d(t,"b",function(){return o}),n.d(t,"a",function(){return s});var i=n("JVO/"),r=n("7g0X"),o=Object(i.c)("accessibilityService"),s=new r.d("accessibilityModeEnabled",!1)},xgy6:function(e,t,n){"use strict";(function(e){n.d(t,"a",function(){return o}),n.d(t,"b",function(){return s}),n.d(t,"c",function(){return a});var i=n("ZfGv"),r=void 0===e?{cwd:function(){return"/"},env:Object.create(null),get platform(){return i.g?"win32":i.d?"darwin":"linux"},nextTick:function(e){return Object(i.h)(e)}}:e,o=r.cwd,s=r.env,a=r.platform}).call(t,n("W2nU"))},xteI:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"ContextMenuController",function(){return v});var i,r=n("hK2W"),o=n("7/Cv"),s=n("IG52"),a=n("tqet"),u=n("03Zz"),c=n("/9db"),l=n("C3c5"),d=n("7g0X"),h=n("yO/1"),f=n("NqM+"),p=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=this&&this.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},m=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},v=function(){function e(e,t,n,i,r,o){var s=this;this._contextMenuService=t,this._contextViewService=n,this._contextKeyService=i,this._keybindingService=r,this._menuService=o,this._toDispose=new a.b,this._contextMenuIsBeingShownCount=0,this._editor=e,this._toDispose.add(this._editor.onContextMenu(function(e){return s._onContextMenu(e)})),this._toDispose.add(this._editor.onMouseWheel(function(e){s._contextMenuIsBeingShownCount>0&&s._contextViewService.hideContextView()})),this._toDispose.add(this._editor.onKeyDown(function(e){58===e.keyCode&&(e.preventDefault(),e.stopPropagation(),s.showContextMenu())}))}return e.get=function(t){return t.getContribution(e.ID)},e.prototype._onContextMenu=function(e){if(this._editor.hasModel()){if(!this._editor.getConfiguration().contribInfo.contextmenu)return this._editor.focus(),void(e.target.position&&!this._editor.getSelection().containsPosition(e.target.position)&&this._editor.setPosition(e.target.position));if(12!==e.target.type&&(e.event.preventDefault(),6===e.target.type||7===e.target.type||1===e.target.type)){this._editor.focus(),e.target.position&&!this._editor.getSelection().containsPosition(e.target.position)&&this._editor.setPosition(e.target.position);var t=null;1!==e.target.type&&(t={x:e.event.posx-1,width:2,y:e.event.posy-1,height:2}),this.showContextMenu(t)}}},e.prototype.showContextMenu=function(e){if(this._editor.getConfiguration().contribInfo.contextmenu&&this._editor.hasModel())if(this._contextMenuService){var t=this._getMenuActions(this._editor.getModel());t.length>0&&this._doShowContextMenu(t,e)}else this._editor.focus()},e.prototype._getMenuActions=function(e){var t=[],n=this._menuService.createMenu(7,this._contextKeyService),i=n.getActions({arg:e.uri});n.dispose();for(var r=0,o=i;r0&&this._contextViewService.hideContextView(),this._toDispose.dispose()},e.ID="editor.contrib.contextmenu",e=g([m(1,h.a),m(2,h.b),m(3,d.c),m(4,f.a),m(5,l.a)],e)}(),_=function(e){function t(){return e.call(this,{id:"editor.action.showContextMenu",label:r.a("action.showContextMenu.label","Show Editor Context Menu"),alias:"Show Editor Context Menu",precondition:void 0,kbOpts:{kbExpr:c.a.textInputFocus,primary:1092,weight:100}})||this}return p(t,e),t.prototype.run=function(e,t){v.get(t).showContextMenu()},t}(u.b);Object(u.h)(v),Object(u.f)(_)},y3Fb:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,r=n("hK2W"),o=n("03Zz"),s=n("G8r4"),a=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),u=function(e){function t(){return e.call(this,{id:"editor.action.fontZoomIn",label:r.a("EditorFontZoomIn.label","Editor Font Zoom In"),alias:"Editor Font Zoom In",precondition:void 0})||this}return a(t,e),t.prototype.run=function(e,t){s.a.setZoomLevel(s.a.getZoomLevel()+1)},t}(o.b),c=function(e){function t(){return e.call(this,{id:"editor.action.fontZoomOut",label:r.a("EditorFontZoomOut.label","Editor Font Zoom Out"),alias:"Editor Font Zoom Out",precondition:void 0})||this}return a(t,e),t.prototype.run=function(e,t){s.a.setZoomLevel(s.a.getZoomLevel()-1)},t}(o.b),l=function(e){function t(){return e.call(this,{id:"editor.action.fontZoomReset",label:r.a("EditorFontZoomReset.label","Editor Font Zoom Reset"),alias:"Editor Font Zoom Reset",precondition:void 0})||this}return a(t,e),t.prototype.run=function(e,t){s.a.setZoomLevel(0)},t}(o.b);Object(o.f)(u),Object(o.f)(c),Object(o.f)(l)},yDvu:function(e,t,n){"use strict";var i=n("X3l8").Buffer,r=n("9DG0").Transform;function o(e){r.call(this),this._block=i.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}n("LC74")(o,r),o.prototype._transform=function(e,t,n){var i=null;try{this.update(e,t)}catch(e){i=e}n(i)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!i.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");i.isBuffer(e)||(e=i.from(e,t));for(var n=this._block,r=0;this._blockOffset+e.length-r>=this._blockSize;){for(var o=this._blockOffset;o0;++s)this._length[s]+=a,(a=this._length[s]/4294967296|0)>0&&(this._length[s]-=4294967296*a);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var n=0;n<4;++n)this._length[n]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},e.exports=o},yMmo:function(e,t,n){"use strict";var i=n("geuY"),r=n("lZ6o").utils.assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}e.exports=o,o.fromPublic=function(e,t,n){return t instanceof o?t:new o(e,{pub:t,pubEnc:n})},o.fromPrivate=function(e,t,n){return t instanceof o?t:new o(e,{priv:t,privEnc:n})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new i(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?r(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||r(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.mul(this.priv).getX()},o.prototype.sign=function(e,t,n){return this.ec.sign(e,this,t,n)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},yNY4:function(e,t,n){"use strict";function i(e){return(e/8|0)+(e%8==0?0:1)}var r={ES256:i(256),ES384:i(384),ES512:i(521)};e.exports=function(e){var t=r[e];if(t)return t;throw new Error('Unknown algorithm "'+e+'"')}},"yO/1":function(e,t,n){"use strict";n.d(t,"b",function(){return r}),n.d(t,"a",function(){return o});var i=n("JVO/"),r=Object(i.c)("contextViewService"),o=Object(i.c)("contextMenuService")},ygb1:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("X6iQ"),r=n("80kS"),o=n("uNfg"),s=n("tqet"),a=n("03Zz"),u=n("vORD"),c=n("GfE5"),l=n("vTy2"),d=n("/9db"),h=n("PCC9"),f=n("606G"),p=n("UqCF"),g=n("zxiH"),m=n("mrx5"),v=n("4tuZ"),_=n("P1SM"),b=n("artP"),y=n("iHM7"),w=n("jIdl"),C=n("0WPX"),S=function(){function e(){}return e._handleEolEdits=function(e,t){for(var n=void 0,i=[],r=0,o=t;r0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},z=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},U=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function s(e){try{u(i.next(e))}catch(e){o(e)}}function a(e){try{u(i.throw(e))}catch(e){o(e)}}function u(e){e.done?r(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},K=this&&this.__generator||function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&o[0]?i.return:o[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,o[1])).done)return r;switch(i=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,i=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]1)){var n=this._editor.getModel(),r=this._editor.getPosition(),o=!1,s=this._editor.onDidChangeModelContent(function(e){if(e.isFlush)return o=!0,void s.dispose();for(var t=0,n=e.changes.length;t1||this._instantiationService.invokeFunction(T,this.editor,e,2,r.a.None).catch(g.e))},e.ID="editor.contrib.formatOnPaste",e=H([z(1,O.a)],e)}(),Y=function(e){function t(){return e.call(this,{id:"editor.action.formatDocument",label:x.a("formatDocument.label","Format Document"),alias:"Format Document",precondition:B.a.and(d.a.writable,d.a.hasDocumentFormattingProvider),kbOpts:{kbExpr:B.a.and(d.a.editorTextFocus,d.a.hasDocumentFormattingProvider),primary:1572,linux:{primary:3111},weight:100},menuOpts:{when:d.a.hasDocumentFormattingProvider,group:"1_modification",order:1.3}})||this}return V(t,e),t.prototype.run=function(e,t){return U(this,void 0,void 0,function(){return K(this,function(n){switch(n.label){case 0:return t.hasModel()?[4,e.get(O.a).invokeFunction(A,t,1,r.a.None)]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})})},t}(a.b),X=function(e){function t(){return e.call(this,{id:"editor.action.formatSelection",label:x.a("formatSelection.label","Format Selection"),alias:"Format Selection",precondition:B.a.and(d.a.writable,d.a.hasDocumentSelectionFormattingProvider),kbOpts:{kbExpr:B.a.and(d.a.editorTextFocus,d.a.hasDocumentSelectionFormattingProvider),primary:Object(o.a)(2089,2084),weight:100},menuOpts:{when:B.a.and(d.a.hasDocumentSelectionFormattingProvider,d.a.hasNonEmptySelection),group:"1_modification",order:1.31}})||this}return V(t,e),t.prototype.run=function(e,t){return U(this,void 0,void 0,function(){var n,i,o;return K(this,function(s){switch(s.label){case 0:return t.hasModel()?(n=e.get(O.a),i=t.getModel(),(o=t.getSelection()).isEmpty()&&(o=new l.a(o.startLineNumber,1,o.startLineNumber,i.getLineMaxColumn(o.startLineNumber))),[4,n.invokeFunction(T,t,o,1,r.a.None)]):[2];case 1:return s.sent(),[2]}})})},t}(a.b);Object(a.h)(G),Object(a.h)(Z),Object(a.f)(Y),Object(a.f)(X),W.a.registerCommand("editor.action.format",function(e){return U(q,void 0,void 0,function(){var t,n;return K(this,function(i){switch(i.label){case 0:return(t=e.get(u.a).getFocusedCodeEditor())&&t.hasModel()?(n=e.get(W.b),t.getSelection().isEmpty()?[4,n.executeCommand("editor.action.formatDocument")]:[3,2]):[2];case 1:return i.sent(),[3,4];case 2:return[4,n.executeCommand("editor.action.formatSelection")];case 3:i.sent(),i.label=4;case 4:return[2]}})})})},ypnx:function(e,t,n){"use strict";(function(t){void 0===t||!t.version||0===t.version.indexOf("v0.")||0===t.version.indexOf("v1.")&&0!==t.version.indexOf("v1.8.")?e.exports={nextTick:function(e,n,i,r){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var o,s,a=arguments.length;switch(a){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick(function(){e.call(null,n)});case 3:return t.nextTick(function(){e.call(null,n,i)});case 4:return t.nextTick(function(){e.call(null,n,i,r)});default:for(o=new Array(a-1),s=0;s>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function h(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function f(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}i(u,r),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,n=this._w,i=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,u=0|this._e,p=0|this._f,g=0|this._g,m=0|this._h,v=0;v<16;++v)n[v]=e.readInt32BE(4*v);for(;v<64;++v)n[v]=0|(((t=n[v-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+n[v-7]+f(n[v-15])+n[v-16];for(var _=0;_<64;++_){var b=m+h(u)+c(u,p,g)+s[_]+n[_]|0,y=d(i)+l(i,r,o)|0;m=g,g=p,p=u,u=a+b|0,a=o,o=r,r=i,i=b+y|0}this._a=i+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=u+this._e|0,this._f=p+this._f|0,this._g=g+this._g|0,this._h=m+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},e.exports=u},zwZj:function(e,t,n){"use strict";n("3Clc");var i,r=n("03Zz"),o=n("0ly5"),s=n("7/Cv"),a=(n("2ZBE"),n("hK2W")),u=n("ZfGv"),c=n("KIxu"),l=function(){function e(e){this.modelProvider=Object(c.f)(e.getModel)?e:{getModel:function(){return e}}}return e.prototype.getId=function(e,t){if(!t)return null;var n=this.modelProvider.getModel();return n===t?"__root__":n.dataSource.getId(t)},e.prototype.hasChildren=function(e,t){var n=this.modelProvider.getModel();return!!(n&&n===t&&n.entries.length>0)},e.prototype.getChildren=function(e,t){var n=this.modelProvider.getModel();return Promise.resolve(n===t?n.entries:[])},e.prototype.getParent=function(e,t){return Promise.resolve(null)},e}(),d=function(){function e(e){this.modelProvider=e}return e.prototype.getAriaLabel=function(e,t){var n=this.modelProvider.getModel();return n.accessibilityProvider?n.accessibilityProvider.getAriaLabel(t):null},e.prototype.getPosInSet=function(e,t){var n=this.modelProvider.getModel(),i=0;if(n.filter)for(var r=0,o=n.entries;r=0;t--){var n=this._arr[t];if(e.toChord().equals(n.keybinding))return n.callback}return null},e}(),_=function(){function e(e){var t=this;void 0===e&&(e={clickBehavior:0,keyboardSupport:!0,openMode:0}),this.options=e,this.downKeyBindingDispatcher=new v,this.upKeyBindingDispatcher=new v,("boolean"!=typeof e.keyboardSupport||e.keyboardSupport)&&(this.downKeyBindingDispatcher.set(16,function(e,n){return t.onUp(e,n)}),this.downKeyBindingDispatcher.set(18,function(e,n){return t.onDown(e,n)}),this.downKeyBindingDispatcher.set(15,function(e,n){return t.onLeft(e,n)}),this.downKeyBindingDispatcher.set(17,function(e,n){return t.onRight(e,n)}),u.d&&(this.downKeyBindingDispatcher.set(2064,function(e,n){return t.onLeft(e,n)}),this.downKeyBindingDispatcher.set(300,function(e,n){return t.onDown(e,n)}),this.downKeyBindingDispatcher.set(302,function(e,n){return t.onUp(e,n)})),this.downKeyBindingDispatcher.set(11,function(e,n){return t.onPageUp(e,n)}),this.downKeyBindingDispatcher.set(12,function(e,n){return t.onPageDown(e,n)}),this.downKeyBindingDispatcher.set(14,function(e,n){return t.onHome(e,n)}),this.downKeyBindingDispatcher.set(13,function(e,n){return t.onEnd(e,n)}),this.downKeyBindingDispatcher.set(10,function(e,n){return t.onSpace(e,n)}),this.downKeyBindingDispatcher.set(9,function(e,n){return t.onEscape(e,n)}),this.upKeyBindingDispatcher.set(3,this.onEnter.bind(this)),this.upKeyBindingDispatcher.set(2051,this.onEnter.bind(this)))}return e.prototype.onMouseDown=function(e,t,n,i){if(void 0===i&&(i="mouse"),0===this.options.clickBehavior&&(n.leftButton||n.middleButton)){if(n.target){if(n.target.tagName&&"input"===n.target.tagName.toLowerCase())return!1;if(s.t(n.target,"scrollbar","monaco-tree"))return!1;if(s.t(n.target,"monaco-action-bar","row"))return!1}return this.onLeftClick(e,t,n,i)}return!1},e.prototype.onClick=function(e,t,n){return u.d&&n.ctrlKey?(n.preventDefault(),n.stopPropagation(),!1):(!n.target||!n.target.tagName||"input"!==n.target.tagName.toLowerCase())&&((0!==this.options.clickBehavior||!n.leftButton&&!n.middleButton)&&this.onLeftClick(e,t,n))},e.prototype.onLeftClick=function(e,t,n,i){void 0===i&&(i="mouse");var r=n,o={origin:i,originalEvent:n,didClickOnTwistie:this.isClickOnTwistie(r)};e.getInput()===t?(e.clearFocus(o),e.clearSelection(o)):(n&&r.browserEvent&&"mousedown"===r.browserEvent.type&&1===r.browserEvent.detail||n.preventDefault(),n.stopPropagation(),e.domFocus(),e.setSelection([t],o),e.setFocus(t,o),this.shouldToggleExpansion(t,r,i)&&(e.isExpanded(t)?e.collapse(t).then(void 0,g.e):e.expand(t).then(void 0,g.e)));return!0},e.prototype.shouldToggleExpansion=function(e,t,n){var i="mouse"===n&&2===t.detail;return this.openOnSingleClick||i||this.isClickOnTwistie(t)},Object.defineProperty(e.prototype,"openOnSingleClick",{get:function(){return 0===this.options.openMode},enumerable:!0,configurable:!0}),e.prototype.isClickOnTwistie=function(e){var t=e.target;if(!s.C(t,"content"))return!1;var n=window.getComputedStyle(t,":before");if("none"===n.backgroundImage||"none"===n.display)return!1;var i=parseInt(n.width)+parseInt(n.paddingRight);return e.browserEvent.offsetX<=i},e.prototype.onContextMenu=function(e,t,n){return(!n.target||!n.target.tagName||"input"!==n.target.tagName.toLowerCase())&&(n&&(n.preventDefault(),n.stopPropagation()),!1)},e.prototype.onTap=function(e,t,n){var i=n.initialTarget;return(!i||!i.tagName||"input"!==i.tagName.toLowerCase())&&this.onLeftClick(e,t,n,"touch")},e.prototype.onKeyDown=function(e,t){return this.onKey(this.downKeyBindingDispatcher,e,t)},e.prototype.onKeyUp=function(e,t){return this.onKey(this.upKeyBindingDispatcher,e,t)},e.prototype.onKey=function(e,t,n){var i=e.dispatch(n.toKeybinding());return!(!i||!i(t,n))&&(n.preventDefault(),n.stopPropagation(),!0)},e.prototype.onUp=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?e.clearHighlight(n):(e.focusPrevious(1,n),e.reveal(e.getFocus()).then(void 0,g.e)),!0},e.prototype.onPageUp=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?e.clearHighlight(n):(e.focusPreviousPage(n),e.reveal(e.getFocus()).then(void 0,g.e)),!0},e.prototype.onDown=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?e.clearHighlight(n):(e.focusNext(1,n),e.reveal(e.getFocus()).then(void 0,g.e)),!0},e.prototype.onPageDown=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?e.clearHighlight(n):(e.focusNextPage(n),e.reveal(e.getFocus()).then(void 0,g.e)),!0},e.prototype.onHome=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?e.clearHighlight(n):(e.focusFirst(n),e.reveal(e.getFocus()).then(void 0,g.e)),!0},e.prototype.onEnd=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?e.clearHighlight(n):(e.focusLast(n),e.reveal(e.getFocus()).then(void 0,g.e)),!0},e.prototype.onLeft=function(e,t){var n={origin:"keyboard",originalEvent:t};if(e.getHighlight())e.clearHighlight(n);else{var i=e.getFocus();e.collapse(i).then(function(t){if(i&&!t)return e.focusParent(n),e.reveal(e.getFocus())}).then(void 0,g.e)}return!0},e.prototype.onRight=function(e,t){var n={origin:"keyboard",originalEvent:t};if(e.getHighlight())e.clearHighlight(n);else{var i=e.getFocus();e.expand(i).then(function(t){if(i&&!t)return e.focusFirstChild(n),e.reveal(e.getFocus())}).then(void 0,g.e)}return!0},e.prototype.onEnter=function(e,t){var n={origin:"keyboard",originalEvent:t};if(e.getHighlight())return!1;var i=e.getFocus();return i&&e.setSelection([i],n),!0},e.prototype.onSpace=function(e,t){if(e.getHighlight())return!1;var n=e.getFocus();return n&&e.toggleExpansion(n),!0},e.prototype.onEscape=function(e,t){var n={origin:"keyboard",originalEvent:t};return e.getHighlight()?(e.clearHighlight(n),!0):e.getSelection().length?(e.clearSelection(n),!0):!!e.getFocus()&&(e.clearFocus(n),!0)},e}(),b=function(){function e(){}return e.prototype.getDragURI=function(e,t){return null},e.prototype.onDragStart=function(e,t,n){},e.prototype.onDragOver=function(e,t,n,i){return null},e.prototype.drop=function(e,t,n,i){},e}(),y=function(){function e(){}return e.prototype.isVisible=function(e,t){return!0},e}(),w=function(){function e(){}return e.prototype.getAriaLabel=function(e,t){return null},e}(),C=function(){function e(e,t){this.styleElement=e,this.selectorSuffix=t}return e.prototype.style=function(e){var t=this.selectorSuffix?"."+this.selectorSuffix:"",n=[];e.listFocusBackground&&n.push(".monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { background-color: "+e.listFocusBackground+"; }"),e.listFocusForeground&&n.push(".monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { color: "+e.listFocusForeground+"; }"),e.listActiveSelectionBackground&&n.push(".monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: "+e.listActiveSelectionBackground+"; }"),e.listActiveSelectionForeground&&n.push(".monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: "+e.listActiveSelectionForeground+"; }"),e.listFocusAndSelectionBackground&&n.push("\n\t\t\t\t.monaco-tree-drag-image,\n\t\t\t\t.monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { background-color: "+e.listFocusAndSelectionBackground+"; }\n\t\t\t"),e.listFocusAndSelectionForeground&&n.push("\n\t\t\t\t.monaco-tree-drag-image,\n\t\t\t\t.monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { color: "+e.listFocusAndSelectionForeground+"; }\n\t\t\t"),e.listInactiveSelectionBackground&&n.push(".monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: "+e.listInactiveSelectionBackground+"; }"),e.listInactiveSelectionForeground&&n.push(".monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: "+e.listInactiveSelectionForeground+"; }"),e.listHoverBackground&&n.push(".monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { background-color: "+e.listHoverBackground+"; }"),e.listHoverForeground&&n.push(".monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { color: "+e.listHoverForeground+"; }"),e.listDropBackground&&n.push("\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row.drop-target { background-color: "+e.listDropBackground+" !important; color: inherit !important; }\n\t\t\t"),e.listFocusOutline&&n.push("\n\t\t\t\t.monaco-tree-drag-image\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px solid "+e.listFocusOutline+"; background: #000; }\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row \t\t\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px solid transparent; }\n\t\t\t\t.monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) \t\t\t\t\t\t{ border: 1px dotted "+e.listFocusOutline+"; }\n\t\t\t\t.monaco-tree"+t+".focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) \t\t\t\t\t\t{ border: 1px solid "+e.listFocusOutline+"; }\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) \t\t\t\t\t\t\t{ border: 1px solid "+e.listFocusOutline+"; }\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) \t{ border: 1px dashed "+e.listFocusOutline+"; }\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-wrapper.drop-target,\n\t\t\t\t.monaco-tree"+t+" .monaco-tree-rows > .monaco-tree-row.drop-target\t\t\t\t\t\t\t\t\t\t\t\t{ border: 1px dashed "+e.listFocusOutline+"; }\n\t\t\t");var i=n.join("\n");i!==this.styleElement.innerHTML&&(this.styleElement.innerHTML=i)},e}(),S=n("5TlO"),x=n("tqet"),L=n("Kp7x"),O=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),k=function(){function e(e){this._onDispose=new L.a,this.onDispose=this._onDispose.event,this._item=e}return Object.defineProperty(e.prototype,"item",{get:function(){return this._item},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._onDispose&&(this._onDispose.fire(),this._onDispose.dispose(),this._onDispose=void 0)},e}(),N=function(){function e(){this.locks=Object.create({})}return e.prototype.isLocked=function(e){return!!this.locks[e.id]},e.prototype.run=function(e,t){var n=this,i=this.getLock(e);return i?new Promise(function(r,o){L.b.once(i.onDispose)(function(){return n.run(e,t).then(r,o)})}):new Promise(function(i,r){if(e.isDisposed())return r(new Error("Item is disposed."));var o=n.locks[e.id]=new k(e);return t().then(function(t){return delete n.locks[e.id],o.dispose(),t}).then(i,r)})},e.prototype.getLock=function(e){var t;for(t in this.locks){var n=this.locks[t];if(e.intersects(n.item))return n}return null},e}(),E=function(){function e(){this._isDisposed=!1,this._onDidRevealItem=new L.d,this.onDidRevealItem=this._onDidRevealItem.event,this._onExpandItem=new L.d,this.onExpandItem=this._onExpandItem.event,this._onDidExpandItem=new L.d,this.onDidExpandItem=this._onDidExpandItem.event,this._onCollapseItem=new L.d,this.onCollapseItem=this._onCollapseItem.event,this._onDidCollapseItem=new L.d,this.onDidCollapseItem=this._onDidCollapseItem.event,this._onDidAddTraitItem=new L.d,this.onDidAddTraitItem=this._onDidAddTraitItem.event,this._onDidRemoveTraitItem=new L.d,this.onDidRemoveTraitItem=this._onDidRemoveTraitItem.event,this._onDidRefreshItem=new L.d,this.onDidRefreshItem=this._onDidRefreshItem.event,this._onRefreshItemChildren=new L.d,this.onRefreshItemChildren=this._onRefreshItemChildren.event,this._onDidRefreshItemChildren=new L.d,this.onDidRefreshItemChildren=this._onDidRefreshItemChildren.event,this._onDidDisposeItem=new L.d,this.onDidDisposeItem=this._onDidDisposeItem.event,this.items={}}return e.prototype.register=function(e){S.a(!this.isRegistered(e.id),"item already registered: "+e.id);var t=Object(x.e)(this._onDidRevealItem.add(e.onDidReveal),this._onExpandItem.add(e.onExpand),this._onDidExpandItem.add(e.onDidExpand),this._onCollapseItem.add(e.onCollapse),this._onDidCollapseItem.add(e.onDidCollapse),this._onDidAddTraitItem.add(e.onDidAddTrait),this._onDidRemoveTraitItem.add(e.onDidRemoveTrait),this._onDidRefreshItem.add(e.onDidRefresh),this._onRefreshItemChildren.add(e.onRefreshChildren),this._onDidRefreshItemChildren.add(e.onDidRefreshChildren),this._onDidDisposeItem.add(e.onDidDispose));this.items[e.id]={item:e,disposable:t}},e.prototype.deregister=function(e){S.a(this.isRegistered(e.id),"item not registered: "+e.id),this.items[e.id].disposable.dispose(),delete this.items[e.id]},e.prototype.isRegistered=function(e){return this.items.hasOwnProperty(e)},e.prototype.getItem=function(e){var t=this.items[e];return t?t.item:null},e.prototype.dispose=function(){this.items=null,this._onDidRevealItem.dispose(),this._onExpandItem.dispose(),this._onDidExpandItem.dispose(),this._onCollapseItem.dispose(),this._onDidCollapseItem.dispose(),this._onDidAddTraitItem.dispose(),this._onDidRemoveTraitItem.dispose(),this._onDidRefreshItem.dispose(),this._onRefreshItemChildren.dispose(),this._onDidRefreshItemChildren.dispose(),this._isDisposed=!0},e.prototype.isDisposed=function(){return this._isDisposed},e}(),I=function(){function e(e,t,n,i,r){this._onDidCreate=new L.a,this._onDidReveal=new L.a,this.onDidReveal=this._onDidReveal.event,this._onExpand=new L.a,this.onExpand=this._onExpand.event,this._onDidExpand=new L.a,this.onDidExpand=this._onDidExpand.event,this._onCollapse=new L.a,this.onCollapse=this._onCollapse.event,this._onDidCollapse=new L.a,this.onDidCollapse=this._onDidCollapse.event,this._onDidAddTrait=new L.a,this.onDidAddTrait=this._onDidAddTrait.event,this._onDidRemoveTrait=new L.a,this.onDidRemoveTrait=this._onDidRemoveTrait.event,this._onDidRefresh=new L.a,this.onDidRefresh=this._onDidRefresh.event,this._onRefreshChildren=new L.a,this.onRefreshChildren=this._onRefreshChildren.event,this._onDidRefreshChildren=new L.a,this.onDidRefreshChildren=this._onDidRefreshChildren.event,this._onDidDispose=new L.a,this.onDidDispose=this._onDidDispose.event,this.registry=t,this.context=n,this.lock=i,this.element=r,this.id=e,this.registry.register(this),this.doesHaveChildren=this.context.dataSource.hasChildren(this.context.tree,this.element),this.needsChildrenRefresh=!0,this.parent=null,this.previous=null,this.next=null,this.firstChild=null,this.lastChild=null,this.traits={},this.depth=0,this.expanded=!(!this.context.dataSource.shouldAutoexpand||!this.context.dataSource.shouldAutoexpand(this.context.tree,r)),this._onDidCreate.fire(this),this.visible=this._isVisible(),this.height=this._getHeight(),this._isDisposed=!1}return e.prototype.getElement=function(){return this.element},e.prototype.hasChildren=function(){return this.doesHaveChildren},e.prototype.getDepth=function(){return this.depth},e.prototype.isVisible=function(){return this.visible},e.prototype.setVisible=function(e){this.visible=e},e.prototype.isExpanded=function(){return this.expanded},e.prototype._setExpanded=function(e){this.expanded=e},e.prototype.reveal=function(e){void 0===e&&(e=null);var t={item:this,relativeTop:e};this._onDidReveal.fire(t)},e.prototype.expand=function(){var e=this;return this.isExpanded()||!this.doesHaveChildren||this.lock.isLocked(this)?Promise.resolve(!1):this.lock.run(this,function(){if(e.isExpanded()||!e.doesHaveChildren)return Promise.resolve(!1);var t={item:e};return e._onExpand.fire(t),(e.needsChildrenRefresh?e.refreshChildren(!1,!0,!0):Promise.resolve(null)).then(function(){return e._setExpanded(!0),e._onDidExpand.fire(t),!0})}).then(function(t){return!e.isDisposed()&&(e.context.options.autoExpandSingleChildren&&t&&null!==e.firstChild&&e.firstChild===e.lastChild&&e.firstChild.isVisible()?e.firstChild.expand().then(function(){return!0}):t)})},e.prototype.collapse=function(e){var t=this;if(void 0===e&&(e=!1),e){var n=Promise.resolve(null);return this.forEachChild(function(e){n=n.then(function(){return e.collapse(!0)})}),n.then(function(){return t.collapse(!1)})}return!this.isExpanded()||this.lock.isLocked(this)?Promise.resolve(!1):this.lock.run(this,function(){var e={item:t};return t._onCollapse.fire(e),t._setExpanded(!1),t._onDidCollapse.fire(e),Promise.resolve(!0)})},e.prototype.addTrait=function(e){var t={item:this,trait:e};this.traits[e]=!0,this._onDidAddTrait.fire(t)},e.prototype.removeTrait=function(e){var t={item:this,trait:e};delete this.traits[e],this._onDidRemoveTrait.fire(t)},e.prototype.hasTrait=function(e){return this.traits[e]||!1},e.prototype.getAllTraits=function(){var e,t=[];for(e in this.traits)this.traits.hasOwnProperty(e)&&this.traits[e]&&t.push(e);return t},e.prototype.getHeight=function(){return this.height},e.prototype.refreshChildren=function(t,n,i){var r=this;if(void 0===n&&(n=!1),void 0===i&&(i=!1),!i&&!this.isExpanded()){var o=function(e){e.needsChildrenRefresh=!0,e.forEachChild(o)};return o(this),Promise.resolve(this)}this.needsChildrenRefresh=!1;var s=function(){var i={item:r,isNested:n};return r._onRefreshChildren.fire(i),(r.doesHaveChildren?r.context.dataSource.getChildren(r.context.tree,r.element):Promise.resolve([])).then(function(n){if(r.isDisposed()||r.registry.isDisposed())return Promise.resolve(null);if(!Array.isArray(n))return Promise.reject(new Error("Please return an array of children."));n=n?n.slice(0):[],n=r.sort(n);for(var i={};null!==r.firstChild;)i[r.firstChild.id]=r.firstChild,r.removeChild(r.firstChild);for(var o=0,s=n.length;o=0;r--)this.onInsertItem(c[r]);for(r=this.heightMap.length-1;r>=i;r--)this.onRefreshItem(this.heightMap[r]);return a},e.prototype.onInsertItem=function(e){},e.prototype.onRemoveItems=function(e){for(var t,n=null,i=null,r=0,o=0;n=e.next();){if(r=this.indexes[n],!(t=this.heightMap[r]))return void console.error("view item doesnt exist");o-=t.height,delete this.indexes[n],this.onRemoveItem(t),null===i&&(i=r)}if(0!==o&&null!==i)for(this.heightMap.splice(i,r-i+1),r=i;r=n.top+n.height))return t;if(i===t)break;i=t}return this.heightMap.length},e.prototype.indexAfter=function(e){return Math.min(this.indexAt(e)+1,this.heightMap.length)},e.prototype.itemAtIndex=function(e){return this.heightMap[e]},e.prototype.itemAfter=function(e){return this.heightMap[this.indexes[e.model.id]+1]||null},e.prototype.createViewItem=function(e){throw new Error("not implemented")},e.prototype.dispose=function(){this.heightMap=[],this.indexes={}},e}(),q=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),G=function(){function e(e,t,n){this._posx=e,this._posy=t,this._target=n}return e.prototype.preventDefault=function(){},e.prototype.stopPropagation=function(){},Object.defineProperty(e.prototype,"target",{get:function(){return this._target},enumerable:!0,configurable:!0}),e}(),Z=function(e){function t(t){var n=e.call(this,t.posx,t.posy,t.target)||this;return n.originalEvent=t,n}return q(t,e),t.prototype.preventDefault=function(){this.originalEvent.preventDefault()},t.prototype.stopPropagation=function(){this.originalEvent.stopPropagation()},t}(G),Y=function(e){function t(t,n,i){var r=e.call(this,t,n,i.target)||this;return r.originalEvent=i,r}return q(t,e),t.prototype.preventDefault=function(){this.originalEvent.preventDefault()},t.prototype.stopPropagation=function(){this.originalEvent.stopPropagation()},t}(G),X=n("VvfH"),$=n("odeJ"),J=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();var Q=function(){function e(e){this.context=e,this._cache={"":[]}}return e.prototype.alloc=function(e){var t=this.cache(e).pop();if(!t){var n=document.createElement("div");n.className="content";var i=document.createElement("div");i.appendChild(n);var r=null;try{r=this.context.renderer.renderTemplate(this.context.tree,e,n)}catch(e){console.error("Tree usage error: exception while rendering template"),console.error(e)}t={element:i,templateId:e,templateData:r}}return t},e.prototype.release=function(e,t){!function(e){try{e.parentElement.removeChild(e)}catch(e){}}(t.element),this.cache(e).push(t)},e.prototype.cache=function(e){return this._cache[e]||(this._cache[e]=[])},e.prototype.garbageCollect=function(){var e=this;this._cache&&Object.keys(this._cache).forEach(function(t){e._cache[t].forEach(function(n){e.context.renderer.disposeTemplate(e.context.tree,t,n.templateData),n.element=null,n.templateData=null}),delete e._cache[t]})},e.prototype.dispose=function(){this.garbageCollect(),this._cache=null},e}(),ee=function(){function e(e,t){var n=this;this.width=0,this.needsRender=!1,this.uri=null,this.unbindDragStart=x.a.None,this._draggable=!1,this.context=e,this.model=t,this.id=this.model.id,this.row=null,this.top=0,this.height=t.getHeight(),this._styles={},t.getAllTraits().forEach(function(e){return n._styles[e]=!0}),t.isExpanded()&&this.addClass("expanded")}return Object.defineProperty(e.prototype,"expanded",{set:function(e){e?this.addClass("expanded"):this.removeClass("expanded")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"loading",{set:function(e){e?this.addClass("loading"):this.removeClass("loading")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"draggable",{get:function(){return this._draggable},set:function(e){this._draggable=e,this.render(!0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropTarget",{set:function(e){e?this.addClass("drop-target"):this.removeClass("drop-target")},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"element",{get:function(){return this.row&&this.row.element},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"templateId",{get:function(){return this._templateId||(this._templateId=this.context.renderer.getTemplateId&&this.context.renderer.getTemplateId(this.context.tree,this.model.getElement()))},enumerable:!0,configurable:!0}),e.prototype.addClass=function(e){this._styles[e]=!0,this.render(!0)},e.prototype.removeClass=function(e){delete this._styles[e],this.render(!0)},e.prototype.render=function(e){var t=this;if(void 0===e&&(e=!1),this.model&&this.element){var n=["monaco-tree-row"];n.push.apply(n,Object.keys(this._styles)),this.model.hasChildren()&&n.push("has-children"),this.element.className=n.join(" "),this.element.draggable=this.draggable,this.element.style.height=this.height+"px",this.element.setAttribute("role","treeitem");var i=this.context.accessibilityProvider,r=i.getAriaLabel(this.context.tree,this.model.getElement());if(r&&this.element.setAttribute("aria-label",r),i.getPosInSet&&i.getSetSize&&(this.element.setAttribute("aria-setsize",i.getSetSize()),this.element.setAttribute("aria-posinset",i.getPosInSet(this.context.tree,this.model.getElement()))),this.model.hasTrait("focused")){var o=F.H(this.model.id);this.element.setAttribute("aria-selected","true"),this.element.setAttribute("id",o)}else this.element.setAttribute("aria-selected","false"),this.element.removeAttribute("id");this.model.hasChildren()?this.element.setAttribute("aria-expanded",String(!!this._styles.expanded)):this.element.removeAttribute("aria-expanded"),this.element.setAttribute("aria-level",String(this.model.getDepth())),this.context.options.paddingOnRow?this.element.style.paddingLeft=this.context.options.twistiePixels+(this.model.getDepth()-1)*this.context.options.indentPixels+"px":(this.element.style.paddingLeft=(this.model.getDepth()-1)*this.context.options.indentPixels+"px",this.row.element.firstElementChild.style.paddingLeft=this.context.options.twistiePixels+"px");var a=this.context.dnd.getDragURI(this.context.tree,this.model.getElement());if(a!==this.uri&&(this.unbindDragStart&&this.unbindDragStart.dispose(),a?(this.uri=a,this.draggable=!0,this.unbindDragStart=s.h(this.element,"dragstart",function(e){t.onDragStart(e)})):this.uri=null),!e&&this.element){var u=0;if(this.context.horizontalScrolling){var c=window.getComputedStyle(this.element);u=parseFloat(c.paddingLeft)}this.context.horizontalScrolling&&(this.element.style.width="fit-content");try{this.context.renderer.renderElement(this.context.tree,this.model.getElement(),this.templateId,this.row.templateData)}catch(e){console.error("Tree usage error: exception while rendering element"),console.error(e)}this.context.horizontalScrolling&&(this.width=s.w(this.element)+u,this.element.style.width="")}}},e.prototype.insertInDOM=function(e,t){if(this.row||(this.row=this.context.cache.alloc(this.templateId),this.element[ne.BINDING]=this),!this.element.parentElement){if(null===t)e.appendChild(this.element);else try{e.insertBefore(this.element,t)}catch(t){console.warn("Failed to locate previous tree element"),e.appendChild(this.element)}this.render()}},e.prototype.removeFromDOM=function(){this.row&&(this.unbindDragStart.dispose(),this.uri=null,this.element[ne.BINDING]=null,this.context.cache.release(this.templateId,this.row),this.row=null)},e.prototype.dispose=function(){this.row=null},e}(),te=function(e){function t(t,n,i){var r=e.call(this,t,n)||this;return r.row={element:i,templateData:null,templateId:null},r}return J(t,e),t.prototype.render=function(){if(this.model&&this.element){var e=["monaco-tree-wrapper"];e.push.apply(e,Object.keys(this._styles)),this.model.hasChildren()&&e.push("has-children"),this.element.className=e.join(" ")}},t.prototype.insertInDOM=function(e,t){},t.prototype.removeFromDOM=function(){},t}(ee);var ne=function(e){function t(n,i){var r=e.call(this)||this;r.model=null,r.lastPointerType="",r.lastClickTimeStamp=0,r.contentWidthUpdateDelayer=new $.a(50),r.isRefreshing=!1,r.refreshingPreviousChildrenIds={},r.currentDragAndDropData=null,r.currentDropTarget=null,r.currentDropTargets=null,r.currentDropDisposable=x.a.None,r.dragAndDropScrollInterval=null,r.dragAndDropScrollTimeout=null,r.dragAndDropMouseY=null,r.highlightedItemWasDraggable=!1,r.onHiddenScrollTop=null,r._onDOMFocus=new L.a,r.onDOMFocus=r._onDOMFocus.event,r._onDOMBlur=new L.a,r._onDidScroll=new L.a,t.counter++,r.instance=t.counter;var o=void 0===n.options.horizontalScrollMode?2:n.options.horizontalScrollMode;r.horizontalScrolling=2!==o,r.context={dataSource:n.dataSource,renderer:n.renderer,controller:n.controller,dnd:n.dnd,filter:n.filter,sorter:n.sorter,tree:n.tree,accessibilityProvider:n.accessibilityProvider,options:n.options,cache:new Q(n),horizontalScrolling:r.horizontalScrolling},r.modelListeners=[],r.viewListeners=[],r.items={},r.domNode=document.createElement("div"),r.domNode.className="monaco-tree no-focused-item monaco-tree-instance-"+r.instance,r.domNode.tabIndex=n.options.preventRootFocus?-1:0,r.styleElement=s.s(r.domNode),r.treeStyler=n.styler||new C(r.styleElement,"monaco-tree-instance-"+r.instance),r.domNode.setAttribute("role","tree"),r.context.options.ariaLabel&&r.domNode.setAttribute("aria-label",r.context.options.ariaLabel),r.context.options.alwaysFocused&&s.f(r.domNode,"focused"),r.context.options.paddingOnRow||s.f(r.domNode,"no-row-padding"),r.wrapper=document.createElement("div"),r.wrapper.className="monaco-tree-wrapper",r.scrollableElement=new U.b(r.wrapper,{alwaysConsumeMouseWheel:!0,horizontal:o,vertical:void 0!==n.options.verticalScrollMode?n.options.verticalScrollMode:1,useShadows:n.options.useShadows}),r.scrollableElement.onScroll(function(e){r.render(e.scrollTop,e.height,e.scrollLeft,e.width,e.scrollWidth),r._onDidScroll.fire()}),P.j?(r.wrapper.style.msTouchAction="none",r.wrapper.style.msContentZooming="none"):R.b.addTarget(r.wrapper),r.rowsContainer=document.createElement("div"),r.rowsContainer.className="monaco-tree-rows",n.options.showTwistie&&(r.rowsContainer.className+=" show-twisties");var a=s.S(r.domNode);return r.viewListeners.push(a.onDidFocus(function(){return r.onFocus()})),r.viewListeners.push(a.onDidBlur(function(){return r.onBlur()})),r.viewListeners.push(a),r.viewListeners.push(s.h(r.domNode,"keydown",function(e){return r.onKeyDown(e)})),r.viewListeners.push(s.h(r.domNode,"keyup",function(e){return r.onKeyUp(e)})),r.viewListeners.push(s.h(r.domNode,"mousedown",function(e){return r.onMouseDown(e)})),r.viewListeners.push(s.h(r.domNode,"mouseup",function(e){return r.onMouseUp(e)})),r.viewListeners.push(s.h(r.wrapper,"auxclick",function(e){e&&1===e.button&&r.onMouseMiddleClick(e)})),r.viewListeners.push(s.h(r.wrapper,"click",function(e){return r.onClick(e)})),r.viewListeners.push(s.h(r.domNode,"contextmenu",function(e){return r.onContextMenu(e)})),r.viewListeners.push(s.h(r.wrapper,R.a.Tap,function(e){return r.onTap(e)})),r.viewListeners.push(s.h(r.wrapper,R.a.Change,function(e){return r.onTouchChange(e)})),P.j&&(r.viewListeners.push(s.h(r.wrapper,"MSPointerDown",function(e){return r.onMsPointerDown(e)})),r.viewListeners.push(s.h(r.wrapper,"MSGestureTap",function(e){return r.onMsGestureTap(e)})),r.viewListeners.push(s.j(r.wrapper,"MSGestureChange",function(e){return r.onThrottledMsGestureChange(e)},function(e,t){t.stopPropagation(),t.preventDefault();var n={translationY:t.translationY,translationX:t.translationX};return e&&(n.translationY+=e.translationY,n.translationX+=e.translationX),n}))),r.viewListeners.push(s.h(window,"dragover",function(e){return r.onDragOver(e)})),r.viewListeners.push(s.h(r.wrapper,"drop",function(e){return r.onDrop(e)})),r.viewListeners.push(s.h(window,"dragend",function(e){return r.onDragEnd(e)})),r.viewListeners.push(s.h(window,"dragleave",function(e){return r.onDragOver(e)})),r.wrapper.appendChild(r.rowsContainer),r.domNode.appendChild(r.scrollableElement.getDomNode()),i.appendChild(r.domNode),r.lastRenderTop=0,r.lastRenderHeight=0,r.didJustPressContextMenuKey=!1,r.currentDropTarget=null,r.currentDropTargets=[],r.shouldInvalidateDropReaction=!1,r.dragAndDropScrollInterval=null,r.dragAndDropScrollTimeout=null,r.onRowsChanged(),r.layout(),r.setupMSGesture(),r.applyStyles(n.options),r}return J(t,e),t.prototype.applyStyles=function(e){this.treeStyler.style(e)},t.prototype.createViewItem=function(e){return new ee(this.context,e)},t.prototype.getHTMLElement=function(){return this.domNode},t.prototype.focus=function(){this.domNode.focus()},t.prototype.isFocused=function(){return document.activeElement===this.domNode},t.prototype.blur=function(){this.domNode.blur()},t.prototype.setupMSGesture=function(){var e=this;window.MSGesture&&(this.msGesture=new MSGesture,setTimeout(function(){return e.msGesture.target=e.wrapper},100))},t.prototype.isTreeVisible=function(){return null===this.onHiddenScrollTop},t.prototype.layout=function(e,t){this.isTreeVisible()&&(this.viewHeight=e||s.v(this.wrapper),this.scrollHeight=this.getContentHeight(),this.horizontalScrolling&&(this.viewWidth=t||s.w(this.wrapper)))},t.prototype.render=function(e,t,n,i,r){var o,s,a=e,u=e+t,c=this.lastRenderTop+this.lastRenderHeight;for(o=this.indexAfter(u)-1,s=this.indexAt(Math.max(c,a));o>=s;o--)this.insertItemInDOM(this.itemAtIndex(o));for(o=Math.min(this.indexAt(this.lastRenderTop),this.indexAfter(u))-1,s=this.indexAt(a);o>=s;o--)this.insertItemInDOM(this.itemAtIndex(o));for(o=this.indexAt(this.lastRenderTop),s=Math.min(this.indexAt(a),this.indexAfter(c));o1e3,c=[],l=!1;if(!u)l=(c=new A.a({getLength:function(){return r.length},getElementAtIndex:function(e){return r[e]}},{getLength:function(){return o.length},getElementAtIndex:function(e){return o[e].id}},null).ComputeDiff(!1)).some(function(e){if(e.modifiedLength>0)for(var n=e.modifiedStart,i=e.modifiedStart+e.modifiedLength;n0&&this.onRemoveItems(new z.a(r,f.originalStart,f.originalStart+f.originalLength)),f.modifiedLength>0){var p=o[f.modifiedStart-1]||n;p=p.getDepth()>0?p:null,this.onInsertItems(new z.a(o,f.modifiedStart,f.modifiedStart+f.modifiedLength),p?p.id:null)}}else(u||c.length)&&(this.onRemoveItems(new z.a(r)),this.onInsertItems(new z.a(o),n.getDepth()>0?n.id:null));(u||c.length)&&this.onRowsChanged()}},t.prototype.onItemRefresh=function(e){this.onItemsRefresh([e])},t.prototype.onItemsRefresh=function(e){var t=this;this.onRefreshItemSet(e.filter(function(e){return t.items.hasOwnProperty(e.id)})),this.onRowsChanged()},t.prototype.onItemExpanding=function(e){var t=this.items[e.item.id];t&&(t.expanded=!0)},t.prototype.onItemExpanded=function(e){var t=e.item,n=this.items[t.id];if(n){n.expanded=!0;var i=this.onInsertItems(t.getNavigator(),t.id)||0,r=this.scrollTop;n.top+n.height<=this.scrollTop&&(r+=i),this.onRowsChanged(r)}},t.prototype.onItemCollapsing=function(e){var t=e.item,n=this.items[t.id];n&&(n.expanded=!1,this.onRemoveItems(new z.e(t.getNavigator(),function(e){return e&&e.id})),this.onRowsChanged())},t.prototype.onItemReveal=function(e){var t=e.item,n=e.relativeTop,i=this.items[t.id];if(i)if(null!==n){n=(n=n<0?0:n)>1?1:n;var r=i.height-this.viewHeight;this.scrollTop=r*n+i.top}else{var o=i.top+i.height,s=this.scrollTop+this.viewHeight;i.top=s&&(this.scrollTop=o-this.viewHeight)}},t.prototype.onItemAddTrait=function(e){var t=e.item,n=e.trait,i=this.items[t.id];i&&i.addClass(n),"highlighted"===n&&(s.f(this.domNode,n),i&&(this.highlightedItemWasDraggable=!!i.draggable,i.draggable&&(i.draggable=!1)))},t.prototype.onItemRemoveTrait=function(e){var t=e.item,n=e.trait,i=this.items[t.id];i&&i.removeClass(n),"highlighted"===n&&(s.I(this.domNode,n),this.highlightedItemWasDraggable&&(i.draggable=!0),this.highlightedItemWasDraggable=!1)},t.prototype.onModelFocusChange=function(){var e=this.model&&this.model.getFocus();s.R(this.domNode,"no-focused-item",!e),e?this.domNode.setAttribute("aria-activedescendant",F.H(this.context.dataSource.getId(this.context.tree,e))):this.domNode.removeAttribute("aria-activedescendant")},t.prototype.onInsertItem=function(e){var t=this;e.onDragStart=function(n){t.onDragStart(e,n)},e.needsRender=!0,this.refreshViewItem(e),this.items[e.id]=e},t.prototype.onRefreshItem=function(e,t){void 0===t&&(t=!1),e.needsRender=e.needsRender||t,this.refreshViewItem(e)},t.prototype.onRemoveItem=function(e){this.removeItemFromDOM(e),e.dispose(),delete this.items[e.id]},t.prototype.refreshViewItem=function(e){e.render(),this.shouldBeRendered(e)?this.insertItemInDOM(e):this.removeItemFromDOM(e)},t.prototype.onClick=function(e){if(!this.lastPointerType||"mouse"===this.lastPointerType){var t=new j.b(e),n=this.getItemAround(t.target);n&&(P.j&&Date.now()-this.lastClickTimeStamp<300&&(t.detail=2),this.lastClickTimeStamp=Date.now(),this.context.controller.onClick(this.context.tree,n.model.getElement(),t))}},t.prototype.onMouseMiddleClick=function(e){if(this.context.controller.onMouseMiddleClick){var t=new j.b(e),n=this.getItemAround(t.target);n&&this.context.controller.onMouseMiddleClick(this.context.tree,n.model.getElement(),t)}},t.prototype.onMouseDown=function(e){if(this.didJustPressContextMenuKey=!1,this.context.controller.onMouseDown&&(!this.lastPointerType||"mouse"===this.lastPointerType)){var t=new j.b(e);if(!(t.ctrlKey&&u.e&&u.d)){var n=this.getItemAround(t.target);n&&this.context.controller.onMouseDown(this.context.tree,n.model.getElement(),t)}}},t.prototype.onMouseUp=function(e){if(this.context.controller.onMouseUp&&(!this.lastPointerType||"mouse"===this.lastPointerType)){var t=new j.b(e);if(!(t.ctrlKey&&u.e&&u.d)){var n=this.getItemAround(t.target);n&&this.context.controller.onMouseUp(this.context.tree,n.model.getElement(),t)}}},t.prototype.onTap=function(e){var t=this.getItemAround(e.initialTarget);t&&this.context.controller.onTap(this.context.tree,t.model.getElement(),e)},t.prototype.onTouchChange=function(e){e.preventDefault(),e.stopPropagation(),this.scrollTop-=e.translationY},t.prototype.onContextMenu=function(e){var t,n;if(e instanceof KeyboardEvent||this.didJustPressContextMenuKey){this.didJustPressContextMenuKey=!1;var i=new W.a(e),r=void 0;if(n=this.model.getFocus()){var o=this.context.dataSource.getId(this.context.tree,n),a=this.items[o];r=s.x(a.element)}else n=this.model.getInput(),r=s.x(this.inputItem.element);t=new Y(r.left+r.width,r.top,i)}else{var u=new j.b(e),c=this.getItemAround(u.target);if(!c)return;n=c.model.getElement(),t=new Z(u)}this.context.controller.onContextMenu(this.context.tree,n,t)},t.prototype.onKeyDown=function(e){var t=new W.a(e);this.didJustPressContextMenuKey=58===t.keyCode||t.shiftKey&&68===t.keyCode,t.target&&t.target.tagName&&"input"===t.target.tagName.toLowerCase()||(this.didJustPressContextMenuKey&&(t.preventDefault(),t.stopPropagation()),this.context.controller.onKeyDown(this.context.tree,t))},t.prototype.onKeyUp=function(e){this.didJustPressContextMenuKey&&this.onContextMenu(e),this.didJustPressContextMenuKey=!1,this.context.controller.onKeyUp(this.context.tree,new W.a(e))},t.prototype.onDragStart=function(e,t){if(!this.model.getHighlight()){var n,i=e.model.getElement(),r=this.model.getSelection();if(n=r.indexOf(i)>-1?r:[i],t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setData(X.a.RESOURCES,JSON.stringify([e.uri])),t.dataTransfer.setDragImage){var o=void 0;o=this.context.dnd.getDragLabel?this.context.dnd.getDragLabel(this.context.tree,n):String(n.length);var s=document.createElement("div");s.className="monaco-tree-drag-image",s.textContent=o,document.body.appendChild(s),t.dataTransfer.setDragImage(s,-10,-10),setTimeout(function(){return document.body.removeChild(s)},0)}this.currentDragAndDropData=new B(n),X.c.CurrentDragAndDropData=new V(n),this.context.dnd.onDragStart(this.context.tree,this.currentDragAndDropData,new j.a(t))}},t.prototype.setupDragAndDropScrollInterval=function(){var e=this,t=s.z(this.wrapper).top;this.dragAndDropScrollInterval||(this.dragAndDropScrollInterval=window.setInterval(function(){if(null!==e.dragAndDropMouseY){var n=e.dragAndDropMouseY-t,i=0,r=e.viewHeight-35;n<35?i=Math.max(-14,.2*(n-35)):n>r&&(i=Math.min(14,.2*(n-r))),e.scrollTop+=i}},10),this.cancelDragAndDropScrollTimeout(),this.dragAndDropScrollTimeout=window.setTimeout(function(){e.cancelDragAndDropScrollInterval(),e.dragAndDropScrollTimeout=null},1e3))},t.prototype.cancelDragAndDropScrollInterval=function(){this.dragAndDropScrollInterval&&(window.clearInterval(this.dragAndDropScrollInterval),this.dragAndDropScrollInterval=null),this.cancelDragAndDropScrollTimeout()},t.prototype.cancelDragAndDropScrollTimeout=function(){this.dragAndDropScrollTimeout&&(window.clearTimeout(this.dragAndDropScrollTimeout),this.dragAndDropScrollTimeout=null)},t.prototype.onDragOver=function(e){var t=this;e.preventDefault();var n,i=new j.a(e),r=this.getItemAround(i.target);if(!r||0===i.posx&&0===i.posy&&i.browserEvent.type===s.d.DRAG_LEAVE)return this.currentDropTarget&&(this.currentDropTargets.forEach(function(e){return e.dropTarget=!1}),this.currentDropTargets=[],this.currentDropDisposable.dispose()),this.cancelDragAndDropScrollInterval(),this.currentDropTarget=null,this.currentDropElement=null,this.dragAndDropMouseY=null,!1;if(this.setupDragAndDropScrollInterval(),this.dragAndDropMouseY=i.posy,!this.currentDragAndDropData)if(X.c.CurrentDragAndDropData)this.currentDragAndDropData=X.c.CurrentDragAndDropData;else{if(!i.dataTransfer.types)return!1;this.currentDragAndDropData=new H}this.currentDragAndDropData.update(i.browserEvent.dataTransfer);var o,a=r.model;do{if(n=a?a.getElement():this.model.getInput(),!(o=this.context.dnd.onDragOver(this.context.tree,this.currentDragAndDropData,n,i))||1!==o.bubble)break;a=a&&a.parent}while(a);if(!a)return this.currentDropElement=null,!1;var u=o&&o.accept;u?(this.currentDropElement=a.getElement(),i.preventDefault(),i.dataTransfer.dropEffect=0===o.effect?"copy":"move"):this.currentDropElement=null;var c,l,d=a.id===this.inputItem.id?this.inputItem:this.items[a.id];if((this.shouldInvalidateDropReaction||this.currentDropTarget!==d||(c=this.currentDropElementReaction,l=o,!(!c&&!l||c&&l&&c.accept===l.accept&&c.bubble===l.bubble&&c.effect===l.effect)))&&(this.shouldInvalidateDropReaction=!1,this.currentDropTarget&&(this.currentDropTargets.forEach(function(e){return e.dropTarget=!1}),this.currentDropTargets=[],this.currentDropDisposable.dispose()),this.currentDropTarget=d,this.currentDropElementReaction=o,u)){if(this.currentDropTarget&&(this.currentDropTarget.dropTarget=!0,this.currentDropTargets.push(this.currentDropTarget)),0===o.bubble)for(var h=a.getNavigator(),f=void 0;f=h.next();)(r=this.items[f.id])&&(r.dropTarget=!0,this.currentDropTargets.push(r));if(o.autoExpand){var p=Object($.l)(500);this.currentDropDisposable=x.h(function(){return p.cancel()}),p.then(function(){return t.context.tree.expand(t.currentDropElement)}).then(function(){return t.shouldInvalidateDropReaction=!0})}}return!0},t.prototype.onDrop=function(e){if(this.currentDropElement){var t=new j.a(e);t.preventDefault(),this.currentDragAndDropData.update(t.browserEvent.dataTransfer),this.context.dnd.drop(this.context.tree,this.currentDragAndDropData,this.currentDropElement,t),this.onDragEnd(e)}this.cancelDragAndDropScrollInterval()},t.prototype.onDragEnd=function(e){this.currentDropTarget&&(this.currentDropTargets.forEach(function(e){return e.dropTarget=!1}),this.currentDropTargets=[]),this.currentDropDisposable.dispose(),this.cancelDragAndDropScrollInterval(),this.currentDragAndDropData=null,X.c.CurrentDragAndDropData=void 0,this.currentDropElement=null,this.currentDropTarget=null,this.dragAndDropMouseY=null},t.prototype.onFocus=function(){this.context.options.alwaysFocused||s.f(this.domNode,"focused"),this._onDOMFocus.fire()},t.prototype.onBlur=function(){this.context.options.alwaysFocused||s.I(this.domNode,"focused"),this.domNode.removeAttribute("aria-activedescendant"),this._onDOMBlur.fire()},t.prototype.onMsPointerDown=function(e){if(this.msGesture){var t=e.pointerType;t!==(e.MSPOINTER_TYPE_MOUSE||"mouse")?t===(e.MSPOINTER_TYPE_TOUCH||"touch")&&(this.lastPointerType="touch",e.stopPropagation(),e.preventDefault(),this.msGesture.addPointer(e.pointerId)):this.lastPointerType="mouse"}},t.prototype.onThrottledMsGestureChange=function(e){this.scrollTop-=e.translationY},t.prototype.onMsGestureTap=function(e){e.initialTarget=document.elementFromPoint(e.clientX,e.clientY),this.onTap(e)},t.prototype.insertItemInDOM=function(e){var t=null,n=this.itemAfter(e);n&&n.element&&(t=n.element),e.insertInDOM(this.rowsContainer,t)},t.prototype.removeItemFromDOM=function(e){e&&e.removeFromDOM()},t.prototype.shouldBeRendered=function(e){return e.topthis.lastRenderTop},t.prototype.getItemAround=function(e){var n=this.inputItem,i=e;do{if(i[t.BINDING]&&(n=i[t.BINDING]),i===this.wrapper||i===this.domNode)return n;if(i===this.scrollableElement.getDomNode()||i===document.body)return}while(i=i.parentElement)},t.prototype.releaseModel=function(){this.model&&(this.modelListeners=x.f(this.modelListeners),this.model=null)},t.prototype.dispose=function(){var t=this;this.scrollableElement.dispose(),this.releaseModel(),this.viewListeners=x.f(this.viewListeners),this._onDOMFocus.dispose(),this._onDOMBlur.dispose(),this.domNode.parentNode&&this.domNode.parentNode.removeChild(this.domNode),this.items&&Object.keys(this.items).forEach(function(e){return t.items[e].removeFromDOM()}),this.context.cache&&this.context.cache.dispose(),e.prototype.dispose.call(this)},t.BINDING="monaco-tree-row",t.LOADING_DECORATION_DELAY=800,t.counter=0,t}(K),ie=n("TNPA"),re=n("TU7t"),oe=function(){return function(e,t,n){if(void 0===n&&(n={}),this.tree=e,this.configuration=t,this.options=n,!t.dataSource)throw new Error("You must provide a Data Source to the tree.");this.dataSource=t.dataSource,this.renderer=t.renderer,this.controller=t.controller||new _({clickBehavior:1,keyboardSupport:"boolean"!=typeof n.keyboardSupport||n.keyboardSupport}),this.dnd=t.dnd||new b,this.filter=t.filter||new y,this.sorter=t.sorter,this.accessibilityProvider=t.accessibilityProvider||new w,this.styler=t.styler}}(),se={listFocusBackground:ie.a.fromHex("#073655"),listActiveSelectionBackground:ie.a.fromHex("#0E639C"),listActiveSelectionForeground:ie.a.fromHex("#FFFFFF"),listFocusAndSelectionBackground:ie.a.fromHex("#094771"),listFocusAndSelectionForeground:ie.a.fromHex("#FFFFFF"),listInactiveSelectionBackground:ie.a.fromHex("#3F3F46"),listHoverBackground:ie.a.fromHex("#2A2D2E"),listDropBackground:ie.a.fromHex("#383B3D")},ae=function(){function e(e,t,n){void 0===n&&(n={}),this._onDidChangeFocus=new L.f,this.onDidChangeFocus=this._onDidChangeFocus.event,this._onDidChangeSelection=new L.f,this.onDidChangeSelection=this._onDidChangeSelection.event,this._onHighlightChange=new L.f,this._onDidExpandItem=new L.f,this._onDidCollapseItem=new L.f,this._onDispose=new L.a,this.onDidDispose=this._onDispose.event,this.container=e,Object(re.g)(n,se,!1),n.twistiePixels="number"==typeof n.twistiePixels?n.twistiePixels:32,n.showTwistie=!1!==n.showTwistie,n.indentPixels="number"==typeof n.indentPixels?n.indentPixels:12,n.alwaysFocused=!0===n.alwaysFocused,n.useShadows=!1!==n.useShadows,n.paddingOnRow=!1!==n.paddingOnRow,n.showLoading=!1!==n.showLoading,this.context=new oe(this,t,n),this.model=new T(this.context),this.view=new ne(this.context,this.container),this.view.setModel(this.model),this._onDidChangeFocus.input=this.model.onDidFocus,this._onDidChangeSelection.input=this.model.onDidSelect,this._onHighlightChange.input=this.model.onDidHighlight,this._onDidExpandItem.input=this.model.onDidExpandItem,this._onDidCollapseItem.input=this.model.onDidCollapseItem}return e.prototype.style=function(e){this.view.applyStyles(e)},Object.defineProperty(e.prototype,"onDidFocus",{get:function(){return this.view&&this.view.onDOMFocus},enumerable:!0,configurable:!0}),e.prototype.getHTMLElement=function(){return this.view.getHTMLElement()},e.prototype.layout=function(e,t){this.view.layout(e,t)},e.prototype.domFocus=function(){this.view.focus()},e.prototype.isDOMFocused=function(){return this.view.isFocused()},e.prototype.domBlur=function(){this.view.blur()},e.prototype.setInput=function(e){return this.model.setInput(e)},e.prototype.getInput=function(){return this.model.getInput()},e.prototype.expand=function(e){return this.model.expand(e)},e.prototype.collapse=function(e,t){return void 0===t&&(t=!1),this.model.collapse(e,t)},e.prototype.toggleExpansion=function(e,t){return void 0===t&&(t=!1),this.model.toggleExpansion(e,t)},e.prototype.isExpanded=function(e){return this.model.isExpanded(e)},e.prototype.reveal=function(e,t){return void 0===t&&(t=null),this.model.reveal(e,t)},e.prototype.getHighlight=function(){return this.model.getHighlight()},e.prototype.clearHighlight=function(e){this.model.setHighlight(null,e)},e.prototype.setSelection=function(e,t){this.model.setSelection(e,t)},e.prototype.getSelection=function(){return this.model.getSelection()},e.prototype.clearSelection=function(e){this.model.setSelection([],e)},e.prototype.setFocus=function(e,t){this.model.setFocus(e,t)},e.prototype.getFocus=function(){return this.model.getFocus()},e.prototype.focusNext=function(e,t){this.model.focusNext(e,t)},e.prototype.focusPrevious=function(e,t){this.model.focusPrevious(e,t)},e.prototype.focusParent=function(e){this.model.focusParent(e)},e.prototype.focusFirstChild=function(e){this.model.focusFirstChild(e)},e.prototype.focusFirst=function(e,t){this.model.focusFirst(e,t)},e.prototype.focusNth=function(e,t){this.model.focusNth(e,t)},e.prototype.focusLast=function(e,t){this.model.focusLast(e,t)},e.prototype.focusNextPage=function(e){this.view.focusNextPage(e)},e.prototype.focusPreviousPage=function(e){this.view.focusPreviousPage(e)},e.prototype.clearFocus=function(e){this.model.setFocus(null,e)},e.prototype.dispose=function(){this._onDispose.fire(),null!==this.model&&(this.model.dispose(),this.model=null),null!==this.view&&(this.view.dispose(),this.view=null),this._onDidChangeFocus.dispose(),this._onDidChangeSelection.dispose(),this._onHighlightChange.dispose(),this._onDidExpandItem.dispose(),this._onDidCollapseItem.dispose(),this._onDispose.dispose()},e}(),ue=(n("1O6n"),this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}()),ce={progressBarBackground:ie.a.fromHex("#0E70C0")},le=function(e){function t(t,n){var i=e.call(this)||this;return i.options=n||Object.create(null),Object(re.g)(i.options,ce,!1),i.workedVal=0,i.progressBarBackground=i.options.progressBarBackground,i._register(i.showDelayedScheduler=new $.d(function(){return Object(s.Q)(i.element)},0)),i.create(t),i}return ue(t,e),t.prototype.create=function(e){this.element=document.createElement("div"),Object(s.f)(this.element,"monaco-progress-container"),e.appendChild(this.element),this.bit=document.createElement("div"),Object(s.f)(this.bit,"progress-bit"),this.element.appendChild(this.bit),this.applyStyles()},t.prototype.off=function(){this.bit.style.width="inherit",this.bit.style.opacity="1",Object(s.J)(this.element,"active","infinite","discrete"),this.workedVal=0,this.totalWork=void 0},t.prototype.stop=function(){return this.doDone(!1)},t.prototype.doDone=function(e){var t=this;return Object(s.f)(this.element,"done"),Object(s.C)(this.element,"infinite")?(this.bit.style.opacity="0",e?setTimeout(function(){return t.off()},200):this.off()):(this.bit.style.width="inherit",e?setTimeout(function(){return t.off()},200):this.off()),this},t.prototype.hide=function(){Object(s.D)(this.element),this.showDelayedScheduler.cancel()},t.prototype.style=function(e){this.progressBarBackground=e.progressBarBackground,this.applyStyles()},t.prototype.applyStyles=function(){if(this.bit){var e=this.progressBarBackground?this.progressBarBackground.toString():null;this.bit.style.backgroundColor=e}},t}(x.a),de=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),he=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return de(t,e),t.prototype.onContextMenu=function(t,n,i){return u.d?this.onLeftClick(t,n,i):e.prototype.onContextMenu.call(this,t,n,i)},t}(_),fe={background:ie.a.fromHex("#1E1E1E"),foreground:ie.a.fromHex("#CCCCCC"),pickerGroupForeground:ie.a.fromHex("#0097FB"),pickerGroupBorder:ie.a.fromHex("#3F3F46"),widgetShadow:ie.a.fromHex("#000000"),progressBarBackground:ie.a.fromHex("#0E70C0")},pe=a.a("quickOpenAriaLabel","Quick picker. Type to narrow down results."),ge=function(e){function t(t,n,i){var r=e.call(this)||this;return r.isDisposed=!1,r.container=t,r.callbacks=n,r.options=i,r.styles=i||Object.create(null),Object(re.g)(r.styles,fe,!1),r.model=null,r}return de(t,e),t.prototype.getModel=function(){return this.model},t.prototype.create=function(){var e=this;this.element=document.createElement("div"),s.f(this.element,"monaco-quick-open-widget"),this.container.appendChild(this.element),this._register(s.h(this.element,s.d.CONTEXT_MENU,function(e){return s.c.stop(e,!0)})),this._register(s.h(this.element,s.d.FOCUS,function(t){return e.gainingFocus()},!0)),this._register(s.h(this.element,s.d.BLUR,function(t){return e.loosingFocus(t)},!0)),this._register(s.h(this.element,s.d.KEY_DOWN,function(t){var n=new W.a(t);if(9===n.keyCode)s.c.stop(t,!0),e.hide(2);else if(2===n.keyCode&&!n.altKey&&!n.ctrlKey&&!n.metaKey){var i=t.currentTarget.querySelectorAll("input, .monaco-tree, .monaco-tree-row.focused .action-label.icon");n.shiftKey&&n.target===i[0]?(s.c.stop(t,!0),i[i.length-1].focus()):n.shiftKey||n.target!==i[i.length-1]||(s.c.stop(t,!0),i[0].focus())}})),this.progressBar=this._register(new le(this.element,{progressBarBackground:this.styles.progressBarBackground})),this.progressBar.hide(),this.inputContainer=document.createElement("div"),s.f(this.inputContainer,"quick-open-input"),this.element.appendChild(this.inputContainer),this.inputBox=this._register(new p.b(this.inputContainer,void 0,{placeholder:this.options.inputPlaceHolder||"",ariaLabel:pe,inputBackground:this.styles.inputBackground,inputForeground:this.styles.inputForeground,inputBorder:this.styles.inputBorder,inputValidationInfoBackground:this.styles.inputValidationInfoBackground,inputValidationInfoForeground:this.styles.inputValidationInfoForeground,inputValidationInfoBorder:this.styles.inputValidationInfoBorder,inputValidationWarningBackground:this.styles.inputValidationWarningBackground,inputValidationWarningForeground:this.styles.inputValidationWarningForeground,inputValidationWarningBorder:this.styles.inputValidationWarningBorder,inputValidationErrorBackground:this.styles.inputValidationErrorBackground,inputValidationErrorForeground:this.styles.inputValidationErrorForeground,inputValidationErrorBorder:this.styles.inputValidationErrorBorder})),this.inputElement=this.inputBox.inputElement,this.inputElement.setAttribute("role","combobox"),this.inputElement.setAttribute("aria-haspopup","false"),this.inputElement.setAttribute("aria-autocomplete","list"),this._register(s.h(this.inputBox.inputElement,s.d.INPUT,function(t){return e.onType()})),this._register(s.h(this.inputBox.inputElement,s.d.KEY_DOWN,function(t){var n=new W.a(t),i=e.shouldOpenInBackground(n);if(2!==n.keyCode)if(18===n.keyCode||16===n.keyCode||12===n.keyCode||11===n.keyCode)s.c.stop(t,!0),e.navigateInTree(n.keyCode,n.shiftKey),e.inputBox.inputElement.selectionStart===e.inputBox.inputElement.selectionEnd&&(e.inputBox.inputElement.selectionStart=e.inputBox.value.length);else if(3===n.keyCode||i){s.c.stop(t,!0);var r=e.tree.getFocus();r&&e.elementSelected(r,t,i?2:1)}})),this.resultCount=document.createElement("div"),s.f(this.resultCount,"quick-open-result-count"),this.resultCount.setAttribute("aria-live","polite"),this.resultCount.setAttribute("aria-atomic","true"),this.element.appendChild(this.resultCount),this.treeContainer=document.createElement("div"),s.f(this.treeContainer,"quick-open-tree"),this.element.appendChild(this.treeContainer);var t=this.options.treeCreator||function(e,t,n){return new ae(e,t,n)};return this.tree=this._register(t(this.treeContainer,{dataSource:new l(this),controller:new he({clickBehavior:1,keyboardSupport:this.options.keyboardSupport}),renderer:this.renderer=new f(this,this.styles),filter:new h(this),accessibilityProvider:new d(this)},{twistiePixels:11,indentPixels:0,alwaysFocused:!0,verticalScrollMode:3,horizontalScrollMode:2,ariaLabel:a.a("treeAriaLabel","Quick Picker"),keyboardSupport:this.options.keyboardSupport,preventRootFocus:!1})),this.treeElement=this.tree.getHTMLElement(),this._register(this.tree.onDidChangeFocus(function(t){e.elementFocused(t.focus,t)})),this._register(this.tree.onDidChangeSelection(function(t){if(t.selection&&t.selection.length>0){var n=t.payload&&t.payload.originalEvent instanceof j.b?t.payload.originalEvent:void 0,i=!!n&&e.shouldOpenInBackground(n);e.elementSelected(t.selection[0],t,i?2:1)}})),this._register(s.h(this.treeContainer,s.d.KEY_DOWN,function(t){var n=new W.a(t);e.quickNavigateConfiguration&&(18!==n.keyCode&&16!==n.keyCode&&12!==n.keyCode&&11!==n.keyCode||(s.c.stop(t,!0),e.navigateInTree(n.keyCode)))})),this._register(s.h(this.treeContainer,s.d.KEY_UP,function(t){var n=new W.a(t),i=n.keyCode;if(e.quickNavigateConfiguration){var r=e.quickNavigateConfiguration.keybindings;if(3===i||r.some(function(e){var t=e.getParts(),r=t[0];return!t[1]&&(r.shiftKey&&4===i?!(n.ctrlKey||n.altKey||n.metaKey):!(!r.altKey||6!==i)||(!(!r.ctrlKey||5!==i)||!(!r.metaKey||57!==i)))})){var o=e.tree.getFocus();o&&e.elementSelected(o,t)}}})),this.layoutDimensions&&this.layout(this.layoutDimensions),this.applyStyles(),this._register(s.h(this.treeContainer,s.d.KEY_DOWN,function(t){var n=new W.a(t);e.quickNavigateConfiguration||18!==n.keyCode&&16!==n.keyCode&&12!==n.keyCode&&11!==n.keyCode||(s.c.stop(t,!0),e.navigateInTree(n.keyCode,n.shiftKey),e.treeElement.focus())})),this.element},t.prototype.style=function(e){this.styles=e,this.applyStyles()},t.prototype.applyStyles=function(){if(this.element){var e=this.styles.foreground?this.styles.foreground.toString():null,t=this.styles.background?this.styles.background.toString():null,n=this.styles.borderColor?this.styles.borderColor.toString():null,i=this.styles.widgetShadow?this.styles.widgetShadow.toString():null;this.element.style.color=e,this.element.style.backgroundColor=t,this.element.style.borderColor=n,this.element.style.borderWidth=n?"1px":null,this.element.style.borderStyle=n?"solid":null,this.element.style.boxShadow=i?"0 5px 8px "+i:null}this.progressBar&&this.progressBar.style({progressBarBackground:this.styles.progressBarBackground}),this.inputBox&&this.inputBox.style({inputBackground:this.styles.inputBackground,inputForeground:this.styles.inputForeground,inputBorder:this.styles.inputBorder,inputValidationInfoBackground:this.styles.inputValidationInfoBackground,inputValidationInfoForeground:this.styles.inputValidationInfoForeground,inputValidationInfoBorder:this.styles.inputValidationInfoBorder,inputValidationWarningBackground:this.styles.inputValidationWarningBackground,inputValidationWarningForeground:this.styles.inputValidationWarningForeground,inputValidationWarningBorder:this.styles.inputValidationWarningBorder,inputValidationErrorBackground:this.styles.inputValidationErrorBackground,inputValidationErrorForeground:this.styles.inputValidationErrorForeground,inputValidationErrorBorder:this.styles.inputValidationErrorBorder}),this.tree&&!this.options.treeCreator&&this.tree.style(this.styles),this.renderer&&this.renderer.updateStyles(this.styles)},t.prototype.shouldOpenInBackground=function(e){if(e instanceof W.a){if(17!==e.keyCode)return!1;if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return!1;var t=this.inputBox.inputElement;return t.selectionEnd===this.inputBox.value.length&&t.selectionStart===t.selectionEnd}return e.middleButton},t.prototype.onType=function(){var e=this.inputBox.value;this.helpText&&(e?s.D(this.helpText):s.Q(this.helpText)),this.callbacks.onType(e)},t.prototype.navigateInTree=function(e,t){var n=this.tree.getInput(),i=n?n.entries:[],r=this.tree.getFocus();switch(e){case 18:this.tree.focusNext();break;case 16:this.tree.focusPrevious();break;case 12:this.tree.focusNextPage();break;case 11:this.tree.focusPreviousPage();break;case 2:t?this.tree.focusPrevious():this.tree.focusNext()}var o=this.tree.getFocus();i.length>1&&r===o&&(16===e||2===e&&t?this.tree.focusLast():(18===e||2===e&&!t)&&this.tree.focusFirst()),(o=this.tree.getFocus())&&this.tree.reveal(o)},t.prototype.elementFocused=function(e,t){if(e&&this.isVisible()){var n=this.treeElement.getAttribute("aria-activedescendant");n?this.inputElement.setAttribute("aria-activedescendant",n):this.inputElement.removeAttribute("aria-activedescendant");var i={event:t,keymods:this.extractKeyMods(t),quickNavigateConfiguration:this.quickNavigateConfiguration};this.model.runner.run(e,0,i)}},t.prototype.elementSelected=function(e,t,n){var i=!0;if(this.isVisible()){var r=n||1,o={event:t,keymods:this.extractKeyMods(t),quickNavigateConfiguration:this.quickNavigateConfiguration};i=this.model.runner.run(e,r,o)}i&&this.hide(0)},t.prototype.extractKeyMods=function(e){return{ctrlCmd:e&&(e.ctrlKey||e.metaKey||e.payload&&e.payload.originalEvent&&(e.payload.originalEvent.ctrlKey||e.payload.originalEvent.metaKey)),alt:e&&(e.altKey||e.payload&&e.payload.originalEvent&&e.payload.originalEvent.altKey)}},t.prototype.show=function(e,t){this.visible=!0,this.isLoosingFocus=!1,this.quickNavigateConfiguration=t?t.quickNavigateConfiguration:void 0,this.quickNavigateConfiguration?(s.D(this.inputContainer),s.Q(this.element),this.tree.domFocus()):(s.Q(this.inputContainer),s.Q(this.element),this.inputBox.focus()),this.helpText&&(this.quickNavigateConfiguration||c.i(e)?s.D(this.helpText):s.Q(this.helpText)),c.i(e)?this.doShowWithPrefix(e):(t&&t.value&&this.restoreLastInput(t.value),this.doShowWithInput(e,t&&t.autoFocus?t.autoFocus:{})),t&&t.inputSelection&&!this.quickNavigateConfiguration&&this.inputBox.select(t.inputSelection),this.callbacks.onShow&&this.callbacks.onShow()},t.prototype.restoreLastInput=function(e){this.inputBox.value=e,this.inputBox.select(),this.callbacks.onType(e)},t.prototype.doShowWithPrefix=function(e){this.inputBox.value=e,this.callbacks.onType(e)},t.prototype.doShowWithInput=function(e,t){this.setInput(e,t)},t.prototype.setInputAndLayout=function(e,t){var n=this;this.treeContainer.style.height=this.getHeight(e)+"px",this.tree.setInput(null).then(function(){return n.model=e,n.inputElement.setAttribute("aria-haspopup",String(e&&e.entries&&e.entries.length>0)),n.tree.setInput(e)}).then(function(){n.tree.layout();var i=e?e.entries.filter(function(t){return n.isElementVisible(e,t)}):[];n.updateResultCount(i.length),i.length&&n.autoFocus(e,i,t)})},t.prototype.isElementVisible=function(e,t){return!e.filter||e.filter.isVisible(t)},t.prototype.autoFocus=function(e,t,n){if(void 0===n&&(n={}),n.autoFocusPrefixMatch){for(var i=void 0,r=void 0,o=n.autoFocusPrefixMatch,s=o.toLowerCase(),a=0,u=t;an.autoFocusIndex&&(this.tree.focusNth(n.autoFocusIndex),this.tree.reveal(this.tree.getFocus())):n.autoFocusSecondEntry?t.length>1&&this.tree.focusNth(1):n.autoFocusLastEntry&&t.length>1&&this.tree.focusLast()},t.prototype.getHeight=function(e){var n=this,i=e.renderer;if(!e){var r=i.getHeight(null);return this.options.minItemsToShow?this.options.minItemsToShow*r:0}var o,s=0;this.layoutDimensions&&this.layoutDimensions.height&&(o=.4*(this.layoutDimensions.height-50)),(!o||o>t.MAX_ITEMS_HEIGHT)&&(o=t.MAX_ITEMS_HEIGHT);for(var a=e.entries.filter(function(t){return n.isElementVisible(e,t)}),u=this.options.maxItemsToShow||a.length,c=0;c=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},Ce=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Se=function(){function e(e,t){this.themeService=t,this.widget=null,this.rangeHighlightDecorationId=null,this.lastKnownEditorSelection=null,this.editor=e}return e.get=function(t){return t.getContribution(e.ID)},e.prototype.getId=function(){return e.ID},e.prototype.dispose=function(){this.widget&&(this.widget.destroy(),this.widget=null)},e.prototype.run=function(e){var t=this;this.widget&&(this.widget.destroy(),this.widget=null);var n=function(e){t.clearDecorations(),e&&t.lastKnownEditorSelection&&(t.editor.setSelection(t.lastKnownEditorSelection),t.editor.revealRangeInCenterIfOutsideViewport(t.lastKnownEditorSelection,0)),t.lastKnownEditorSelection=null,document.activeElement!==document.body&&e||t.editor.focus()};this.widget=new _e(this.editor,function(){return n(!1)},function(){return n(!0)},function(n){t.widget.setInput(e.getModel(n),e.getAutoFocus(n))},{inputAriaLabel:e.inputAriaLabel},this.themeService),this.lastKnownEditorSelection||(this.lastKnownEditorSelection=this.editor.getSelection()),this.widget.show("")},e.prototype.decorateLine=function(t,n){var i=[];this.rangeHighlightDecorationId&&(i.push(this.rangeHighlightDecorationId),this.rangeHighlightDecorationId=null);var r=[{range:t,options:e._RANGE_HIGHLIGHT_DECORATION}],o=n.deltaDecorations(i,r);this.rangeHighlightDecorationId=o[0]},e.prototype.clearDecorations=function(){this.rangeHighlightDecorationId&&(this.editor.deltaDecorations([this.rangeHighlightDecorationId],[]),this.rangeHighlightDecorationId=null)},e.ID="editor.controller.quickOpenController",e._RANGE_HIGHLIGHT_DECORATION=o.a.register({className:"rangeHighlight",isWholeLine:!0}),e=we([Ce(1,be.c)],e)}(),xe=function(e){function t(t,n){var i=e.call(this,n)||this;return i._inputAriaLabel=t,i}return ye(t,e),t.prototype.getController=function(e){return Se.get(e)},t.prototype._show=function(e,t){e.run({inputAriaLabel:this._inputAriaLabel,getModel:function(e){return t.getModel(e)},getAutoFocus:function(e){return t.getAutoFocus(e)}})},t}(r.b);Object(r.h)(Se)},zxiH:function(e,t,n){"use strict";t.e=function(e){o(e)||i.onUnexpectedError(e);return},t.f=function(e){o(e)||i.onUnexpectedExternalError(e);return},t.g=function(e){if(e instanceof Error){var t=e.name,n=e.message,i=e.stacktrace||e.stack;return{$isError:!0,name:t,message:n,stack:i}}return e},t.d=o,t.a=function(){var e=new Error(r);return e.name=e.message,e},t.b=function(e){return e?new Error("Illegal argument: "+e):new Error("Illegal argument")},t.c=function(e){return e?new Error("Illegal state: "+e):new Error("Illegal state")};var i=new(function(){function e(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(function(){if(e.stack)throw new Error(e.message+"\n\n"+e.stack);throw e},0)}}return e.prototype.emit=function(e){this.listeners.forEach(function(t){t(e)})},e.prototype.onUnexpectedError=function(e){this.unexpectedErrorHandler(e),this.emit(e)},e.prototype.onUnexpectedExternalError=function(e){this.unexpectedErrorHandler(e)},e}());var r="Canceled";function o(e){return e instanceof Error&&e.name===r&&e.message===r}}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/20.9b195e570cc0ef6c1bc5.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/20.9b195e570cc0ef6c1bc5.js deleted file mode 100644 index 90a54a5382..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/20.9b195e570cc0ef6c1bc5.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([20],{LbE0:function(t,e,s){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n={name:"help-view",components:{},data:function(){return{lang:window.localStorage.getItem("language")||"en"}},computed:{learnEnterprise:function(){return"en"===this.lang?"https://www.emqx.io/products/enterprise":"https://www.emqx.io/cn/products/enterprise"},freeTrial:function(){return"en"===this.lang?"https://www.emqx.io/downloads#enterprise":"https://www.emqx.io/cn/downloads#enterprise"},docsLink:function(){return"en"===this.lang?"https://docs.emqx.io/broker/v4/en":"https://docs.emqx.io/broker/v4/cn"},faqLink:function(){return"en"===this.lang?"https://docs.emqx.io/tutorial/v4/en/faq/faq.html":"https://docs.emqx.io/broker/latest/cn/faq/faq.html"}},methods:{}},a={render:function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"help-view"},[s("div",{staticClass:"page-title"},[t._v(t._s(t.$t("leftbar.help")))]),t._v(" "),s("div",{staticClass:"help-item"},[s("h3",[t._v(t._s(t.$t("help.quickStart")))]),t._v(" "),s("p",[t._v(t._s(t.$t("help.emqxDesc")))]),t._v(" "),s("a",{attrs:{target:"_blank",href:"https://github.com/emqx/emqx"}},[t._v("Github")])]),t._v(" "),s("el-divider"),t._v(" "),s("div",{staticClass:"help-item"},[s("h3",[t._v(t._s(t.$t("help.emqxEnterprise")))]),t._v(" "),s("p",{domProps:{innerHTML:t._s(t.$t("help.enterpriseDesc"))}}),t._v(" "),s("a",{attrs:{target:"_blank",href:t.learnEnterprise}},[t._v("\n "+t._s(t.$t("oper.learnMore"))+"\n ")]),t._v(" "),s("a",{attrs:{target:"_blank",href:t.freeTrial}},[t._v("\n "+t._s(t.$t("help.freeTrial"))+"\n ")])]),t._v(" "),s("el-divider"),t._v(" "),s("div",{staticClass:"help-item"},[s("h3",[t._v(t._s(t.$t("help.useDocs")))]),t._v(" "),s("p",[t._v(t._s(t.$t("help.docsDesc")))]),t._v(" "),s("a",{attrs:{target:"_blank",href:t.docsLink}},[t._v("\n "+t._s(t.$t("help.forwardView"))+"\n ")])]),t._v(" "),s("el-divider"),t._v(" "),s("div",{staticClass:"help-item"},[s("h3",[t._v("FAQ")]),t._v(" "),s("p",[t._v(t._s(t.$t("help.faqDesc")))]),t._v(" "),s("a",{attrs:{target:"_blank",href:t.faqLink}},[t._v("\n "+t._s(t.$t("help.forwardFaq"))+"\n ")])]),t._v(" "),s("el-divider"),t._v(" "),s("div",{staticClass:"help-item"},[s("h3",[t._v(t._s(t.$t("help.followUs")))]),t._v(" "),t._m(0),t._v(" "),t._m(1),t._v(" "),t._m(2),t._v(" "),t._m(3),t._v(" "),t._m(4),t._v(" "),t._m(5)])],1)},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"follow-link",attrs:{target:"_blank",href:"https://github.com/emqx/emqx"}},[e("i",{staticClass:"iconfont icon-git"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"follow-link",attrs:{target:"_blank",href:"https://twitter.com/emqtt"}},[e("i",{staticClass:"iconfont icon-tuite"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"follow-link",attrs:{target:"_blank",href:"https://emqx.slack.com/"}},[e("i",{staticClass:"iconfont icon-slack"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"follow-link",attrs:{target:"_blank",href:"https://stackoverflow.com/questions/tagged/emq"}},[e("i",{staticClass:"iconfont icon-stack-overflow"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"follow-link",attrs:{target:"_blank",href:"https://groups.google.com/forum/#!forum/emqtt"}},[e("i",{staticClass:"iconfont icon-icons-google_groups"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"follow-link",attrs:{target:"_blank",href:"https://www.youtube.com/channel/UCDU9GWFk8NTGiTvPx_2XskA"}},[e("i",{staticClass:"iconfont icon-youtube"})])}]};var i=s("VU/8")(n,a,!1,function(t){s("fYOn")},null,null);e.default=i.exports},fYOn:function(t,e){}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/21.bcb0d732684777bd59b3.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/21.bcb0d732684777bd59b3.js deleted file mode 100644 index 0c4cce33c2..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/21.bcb0d732684777bd59b3.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([21],{Tk0c:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=r("Dd8w"),s=r.n(a),o=r("zL8q"),i=r("CqLJ"),l=r.n(i),p={name:"applications-view",components:{"el-dialog":o.Dialog,"el-input":o.Input,"el-switch":o.Switch,"el-select":o.Select,"el-option":o.Option,"el-button":o.Button,"el-table":o.Table,"el-table-column":o.TableColumn,"el-date-picker":o.DatePicker,"el-popover":o.Popover,"el-tooltip":o.Tooltip,"el-form":o.Form,"el-form-item":o.FormItem,"el-row":o.Row,"el-col":o.Col},data:function(){return{tableData:[],displayDialog:!1,oper:"new",record:{app_id:"",name:"",desc:"",secret:"",expired:"",status:!0},rules:{app_id:[{required:!0,message:this.$t("app.errors")}],name:[{required:!0,message:this.$t("app.errors")}]},popoverVisible:!1,pickerDisable:{disabledDate:function(e){return e.getTime()0&&void 0!==arguments[0]&&arguments[0],r=arguments[1];if(t){var a=s()({},r);13===new Date(a.expired).getTime().toString().length?a.expired/=1e3:a.expired=void 0,this.$httpPut("/apps/"+a.app_id,a).then(function(){e.$message.success(e.$t("oper.editSuccess")),e.loadData()}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})}else this.$refs.record.validate(function(t){if(t){var r=s()({},e.record);13===new Date(r.expired).getTime().toString().length?r.expired/=1e3:r.expired=void 0,e.$httpPut("/apps/"+r.app_id,r).then(function(){e.displayDialog=!1,e.$message.success(e.$t("oper.editSuccess")),e.loadData()}).catch(function(t){e.$message.error(t||e.$t("error.networkError"))})}})},showApp:function(e){var t=this;this.oper="view",this.$httpGet("/apps/"+e.app_id).then(function(e){t.displayDialog=!0,t.record=e.data,10===t.record.expired.toString().length&&(t.record.expired=new Date(1e3*t.record.expired)),t.displayDialog=!0}).catch(function(e){t.$message.error(e||t.$t("error.networkError"))})},deleteApp:function(e){var t=this;this.$httpDelete("/apps/"+e.app_id).then(function(){t.loadData(),t.hidePopover()}).catch(function(e){t.$message.error(e||t.$t("error.networkError"))})},handleOperation:function(){var e=this,t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],r=arguments[1];this.displayDialog=!0,setTimeout(function(){t?(e.oper="new",e.record={app_id:Math.random().toString(16).slice(2),name:"",desc:"",secret:"",expired:"",status:!0}):(e.oper="edit",e.record=s()({},r),e.record.expired=e.record.expired&&10===e.record.expired.toString().length?new Date(1e3*e.record.expired):""),e.$refs.record.resetFields()},10)},hidePopover:function(){var e=this;this.popoverVisible=!0,setTimeout(function(){e.popoverVisible=!1},0)},dateFormat:function(e){try{return 10===e.toString().length?l()(1e3*e,"yyyy-mm-dd"):this.$t("app.expiredText")}catch(e){return this.$t("app.expiredText")}}},created:function(){this.loadData()}},n={render:function(){var e=this,t=e.$createElement,r=e._self._c||t;return r("div",{staticClass:"applications-view"},[r("div",{staticClass:"page-title"},[e._v("\n "+e._s(e.$t("leftbar.applications"))+"\n "),r("el-button",{staticClass:"confirm-btn",staticStyle:{float:"right"},attrs:{round:"",plain:"",type:"success",icon:"el-icon-plus",size:"medium",disable:e.$store.state.loading},on:{click:e.handleOperation}},[e._v("\n "+e._s(e.$t("app.newApp"))+"\n ")])],1),e._v(" "),r("el-table",{directives:[{name:"loading",rawName:"v-loading",value:e.$store.state.loading,expression:"$store.state.loading"}],attrs:{border:"",data:e.tableData}},[r("el-table-column",{attrs:{prop:"app_id","min-width":"90px",label:e.$t("app.appId")}}),e._v(" "),r("el-table-column",{attrs:{prop:"name","min-width":"100px",label:e.$t("app.name")}}),e._v(" "),r("el-table-column",{attrs:{prop:"expired","min-width":"120px",label:e.$t("app.expired")},scopedSlots:e._u([{key:"default",fn:function(t){return[e._v("\n "+e._s(e.dateFormat(t.row.expired))+"\n ")]}}])}),e._v(" "),r("el-table-column",{attrs:{prop:"desc","min-width":"90px",label:e.$t("app.desc")}}),e._v(" "),r("el-table-column",{attrs:{label:e.$t("app.status")},scopedSlots:e._u([{key:"default",fn:function(t){return[r("el-tooltip",{attrs:{content:t.row.status?e.$t("app.enableText"):e.$t("app.disableText"),placement:"left"}},[r("el-switch",{attrs:{"active-text":"","inactive-text":"","active-color":"#13ce66","inactive-color":"#ff4949"},on:{change:function(r){return e.updateApp(!0,t.row)}},model:{value:t.row.status,callback:function(r){e.$set(t.row,"status",r)},expression:"props.row.status"}})],1)]}}])}),e._v(" "),r("el-table-column",{attrs:{width:"180px",label:e.$t("oper.oper")},scopedSlots:e._u([{key:"default",fn:function(t){return[r("el-button",{attrs:{type:"success",size:"mini",plain:""},on:{click:function(r){return e.showApp(t.row)}}},[e._v("\n "+e._s(e.$t("oper.view"))+"\n ")]),e._v(" "),r("el-button",{attrs:{type:"success",size:"mini",plain:""},on:{click:function(r){return e.handleOperation(!1,t.row)}}},[e._v("\n "+e._s(e.$t("oper.edit"))+"\n ")]),e._v(" "),r("el-popover",{attrs:{placement:"right",trigger:"click",value:e.popoverVisible}},[r("p",[e._v(e._s(e.$t("oper.confirmDelete")))]),e._v(" "),r("div",{staticStyle:{"text-align":"right"}},[r("el-button",{staticClass:"cache-btn",attrs:{size:"mini",type:"text"},on:{click:e.hidePopover}},[e._v("\n "+e._s(e.$t("oper.cancel"))+"\n ")]),e._v(" "),r("el-button",{attrs:{size:"mini",type:"success"},on:{click:function(r){return e.deleteApp(t.row)}}},[e._v("\n "+e._s(e.$t("oper.confirm"))+"\n ")])],1),e._v(" "),r("el-button",{attrs:{slot:"reference",size:"mini",type:"danger",plain:""},slot:"reference"},[e._v("\n "+e._s(e.$t("oper.delete"))+"\n ")])],1)]}}])})],1),e._v(" "),r("el-dialog",{attrs:{width:"view"===e.oper?"660px":"500px",visible:e.displayDialog,title:e.$t("app."+e.oper+"App")},on:{"update:visible":function(t){e.displayDialog=t}},nativeOn:{keyup:function(t){return!t.type.indexOf("key")&&e._k(t.keyCode,"enter",13,t.key,"Enter")?null:e.createApp(t)}}},[r("el-form",{ref:"record",staticClass:"el-form--public app-info",attrs:{size:"medium",rules:"view"===e.oper?{}:e.rules,model:e.record}},[r("el-row",{attrs:{gutter:20}},["view"===e.oper?[r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"app_id",label:e.$t("app.appId")}},[r("el-input",{staticClass:"is-disabled",attrs:{readonly:!0},model:{value:e.record.app_id,callback:function(t){e.$set(e.record,"app_id",t)},expression:"record.app_id"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{label:e.$t("app.secret")}},[r("el-input",{staticClass:"is-disabled",attrs:{readonly:!0},model:{value:e.record.secret,callback:function(t){e.$set(e.record,"secret",t)},expression:"record.secret"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"name",label:e.$t("app.name")}},[r("el-input",{staticClass:"is-disabled",attrs:{readonly:!0},model:{value:e.record.name,callback:function(t){e.$set(e.record,"name",t)},expression:"record.name"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"status",label:e.$t("app.status")}},[r("el-select",{staticClass:"el-select--public",attrs:{"popper-class":"el-select--public",disabled:"view"===e.oper},model:{value:e.record.status,callback:function(t){e.$set(e.record,"status",t)},expression:"record.status"}},[r("el-option",{attrs:{label:e.$t("app.enable"),value:!0}}),e._v(" "),r("el-option",{attrs:{label:e.$t("app.disable"),value:!1}})],1)],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{label:e.$t("app.expired")}},[r("el-date-picker",{attrs:{"picker-options":e.pickerDisable,placeholder:e.$t("app.expiredText"),disabled:"view"===e.oper},model:{value:e.record.expired,callback:function(t){e.$set(e.record,"expired",t)},expression:"record.expired"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"desc",label:e.$t("app.desc")}},[r("el-input",{staticClass:"is-disabled",attrs:{readonly:!0},model:{value:e.record.desc,callback:function(t){e.$set(e.record,"desc",t)},expression:"record.desc"}})],1)],1)]:[r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"app_id",label:e.$t("app.appId")}},[r("el-input",{attrs:{disabled:["view","edit"].includes(e.oper)},model:{value:e.record.app_id,callback:function(t){e.$set(e.record,"app_id",t)},expression:"record.app_id"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},["view"===e.oper?r("el-form-item",{attrs:{label:e.$t("app.secret")}},[r("el-input",{attrs:{disabled:""},model:{value:e.record.secret,callback:function(t){e.$set(e.record,"secret",t)},expression:"record.secret"}})],1):e._e()],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"name",label:e.$t("app.name")}},[r("el-input",{attrs:{disabled:["view","edit"].includes(e.oper)},model:{value:e.record.name,callback:function(t){e.$set(e.record,"name",t)},expression:"record.name"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}}),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"status",label:e.$t("app.status")}},[r("el-select",{staticClass:"el-select--public",attrs:{"popper-class":"el-select--public",disabled:"view"===e.oper},model:{value:e.record.status,callback:function(t){e.$set(e.record,"status",t)},expression:"record.status"}},[r("el-option",{attrs:{label:e.$t("app.enable"),value:!0}}),e._v(" "),r("el-option",{attrs:{label:e.$t("app.disable"),value:!1}})],1)],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{label:e.$t("app.expired")}},[r("el-date-picker",{attrs:{"picker-options":e.pickerDisable,placeholder:e.$t("app.expiredText"),disabled:"view"===e.oper},model:{value:e.record.expired,callback:function(t){e.$set(e.record,"expired",t)},expression:"record.expired"}})],1)],1),e._v(" "),r("el-col",{attrs:{span:12}},[r("el-form-item",{attrs:{prop:"desc",label:e.$t("app.desc")}},[r("el-input",{attrs:{disabled:["view"].includes(e.oper)},model:{value:e.record.desc,callback:function(t){e.$set(e.record,"desc",t)},expression:"record.desc"}})],1)],1)]],2)],1),e._v(" "),"view"!==e.oper?r("div",{attrs:{slot:"footer"},slot:"footer"},[r("el-button",{staticClass:"cache-btn",attrs:{type:"text"},on:{click:function(t){e.displayDialog=!1}}},[e._v("\n "+e._s(e.$t("oper.cancel"))+"\n ")]),e._v(" "),"edit"===e.oper?r("el-button",{staticClass:"confirm-btn",attrs:{type:"success",loading:e.$store.state.loading,disabled:e.$store.state.loading},on:{click:function(t){return e.updateApp(!1)}}},[e._v("\n "+e._s(e.$t("oper.save"))+"\n ")]):e._e(),e._v(" "),"new"===e.oper?r("el-button",{staticClass:"confirm-btn",attrs:{type:"success",loading:e.$store.state.loading,disabled:e.$store.state.loading},on:{click:e.createApp}},[e._v("\n "+e._s(e.$t("oper.save"))+"\n ")]):e._e()],1):r("div",{attrs:{slot:"footer"},slot:"footer"},[r("div",{staticClass:"guide-doc"},[e._v("\n "+e._s(this.$t("app.guide"))+"\n "),r("a",{attrs:{href:"zh"===e.lang?"https://docs.emqx.io/broker/latest/cn/advanced/http-api.html":"https://docs.emqx.io/broker/latest/en/advanced/http-api.html",target:"_blank"}},[e._v("\n "+e._s(e.$t("app.docs"))+"\n ")])])])],1)],1)},staticRenderFns:[]};var c=r("VU/8")(p,n,!1,function(e){r("uPvA")},null,null);t.default=c.exports},uPvA:function(e,t){}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/24.de01258f230e5adebc01.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/24.de01258f230e5adebc01.js deleted file mode 100644 index ee9f0a5653..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/24.de01258f230e5adebc01.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([24],{"SG+P":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r,i,o,a,s,u,c,d,f,l,g,h,p,m,v,b,k,C,_,y=function(){function e(e){var t=this;this._defaults=e,this._worker=null,this._idleCheckInterval=setInterval(function(){return t._checkIfIdle()},3e4),this._lastUsedTime=0,this._configChangeListener=this._defaults.onDidChange(function(){return t._stopWorker()})}return e.prototype._stopWorker=function(){this._worker&&(this._worker.dispose(),this._worker=null),this._client=null},e.prototype.dispose=function(){clearInterval(this._idleCheckInterval),this._configChangeListener.dispose(),this._stopWorker()},e.prototype._checkIfIdle=function(){this._worker&&(Date.now()-this._lastUsedTime>12e4&&this._stopWorker())},e.prototype._getClient=function(){return this._lastUsedTime=Date.now(),this._client||(this._worker=monaco.editor.createWebWorker({moduleId:"vs/language/json/jsonWorker",label:this._defaults.languageId,createData:{languageSettings:this._defaults.diagnosticsOptions,languageId:this._defaults.languageId,enableSchemaRequest:this._defaults.diagnosticsOptions.enableSchemaRequest}}),this._client=this._worker.getProxy()),this._client},e.prototype.getLanguageServiceWorker=function(){for(var e,t=this,n=[],r=0;r0&&(i.arguments=n),i},e.is=function(e){var t=e;return Q.defined(t)&&Q.string(t.title)&&Q.string(t.command)}}(p||(p={})),function(e){e.replace=function(e,t){return{range:e,newText:t}},e.insert=function(e,t){return{range:{start:e,end:e},newText:t}},e.del=function(e){return{range:e,newText:""}},e.is=function(e){var t=e;return Q.objectLiteral(t)&&Q.string(t.newText)&&i.is(t.range)}}(m||(m={})),function(e){e.create=function(e,t){return{textDocument:e,edits:t}},e.is=function(e){var t=e;return Q.defined(t)&&E.is(t.textDocument)&&Array.isArray(t.edits)}}(v||(v={})),function(e){e.create=function(e,t){var n={kind:"create",uri:e};return void 0===t||void 0===t.overwrite&&void 0===t.ignoreIfExists||(n.options=t),n},e.is=function(e){var t=e;return t&&"create"===t.kind&&Q.string(t.uri)&&(void 0===t.options||(void 0===t.options.overwrite||Q.boolean(t.options.overwrite))&&(void 0===t.options.ignoreIfExists||Q.boolean(t.options.ignoreIfExists)))}}(b||(b={})),function(e){e.create=function(e,t,n){var r={kind:"rename",oldUri:e,newUri:t};return void 0===n||void 0===n.overwrite&&void 0===n.ignoreIfExists||(r.options=n),r},e.is=function(e){var t=e;return t&&"rename"===t.kind&&Q.string(t.oldUri)&&Q.string(t.newUri)&&(void 0===t.options||(void 0===t.options.overwrite||Q.boolean(t.options.overwrite))&&(void 0===t.options.ignoreIfExists||Q.boolean(t.options.ignoreIfExists)))}}(k||(k={})),function(e){e.create=function(e,t){var n={kind:"delete",uri:e};return void 0===t||void 0===t.recursive&&void 0===t.ignoreIfNotExists||(n.options=t),n},e.is=function(e){var t=e;return t&&"delete"===t.kind&&Q.string(t.uri)&&(void 0===t.options||(void 0===t.options.recursive||Q.boolean(t.options.recursive))&&(void 0===t.options.ignoreIfNotExists||Q.boolean(t.options.ignoreIfNotExists)))}}(C||(C={})),function(e){e.is=function(e){var t=e;return t&&(void 0!==t.changes||void 0!==t.documentChanges)&&(void 0===t.documentChanges||t.documentChanges.every(function(e){return Q.string(e.kind)?b.is(e)||k.is(e)||C.is(e):v.is(e)}))}}(_||(_={}));var w,E,x,S,I,A,T,M,P,R,F,j,D,L,O,W,N,U=function(){function e(e){this.edits=e}return e.prototype.insert=function(e,t){this.edits.push(m.insert(e,t))},e.prototype.replace=function(e,t){this.edits.push(m.replace(e,t))},e.prototype.delete=function(e){this.edits.push(m.del(e))},e.prototype.add=function(e){this.edits.push(e)},e.prototype.all=function(){return this.edits},e.prototype.clear=function(){this.edits.splice(0,this.edits.length)},e}();!function(){function e(e){var t=this;this._textEditChanges=Object.create(null),e&&(this._workspaceEdit=e,e.documentChanges?e.documentChanges.forEach(function(e){if(v.is(e)){var n=new U(e.edits);t._textEditChanges[e.textDocument.uri]=n}}):e.changes&&Object.keys(e.changes).forEach(function(n){var r=new U(e.changes[n]);t._textEditChanges[n]=r}))}Object.defineProperty(e.prototype,"edit",{get:function(){return this._workspaceEdit},enumerable:!0,configurable:!0}),e.prototype.getTextEditChange=function(e){if(E.is(e)){if(this._workspaceEdit||(this._workspaceEdit={documentChanges:[]}),!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.");var t=e;if(!(r=this._textEditChanges[t.uri])){var n={textDocument:t,edits:i=[]};this._workspaceEdit.documentChanges.push(n),r=new U(i),this._textEditChanges[t.uri]=r}return r}if(this._workspaceEdit||(this._workspaceEdit={changes:Object.create(null)}),!this._workspaceEdit.changes)throw new Error("Workspace edit is not configured for normal text edit changes.");var r;if(!(r=this._textEditChanges[e])){var i=[];this._workspaceEdit.changes[e]=i,r=new U(i),this._textEditChanges[e]=r}return r},e.prototype.createFile=function(e,t){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(b.create(e,t))},e.prototype.renameFile=function(e,t,n){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(k.create(e,t,n))},e.prototype.deleteFile=function(e,t){this.checkDocumentChanges(),this._workspaceEdit.documentChanges.push(C.create(e,t))},e.prototype.checkDocumentChanges=function(){if(!this._workspaceEdit||!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for document changes.")}}();!function(e){e.create=function(e){return{uri:e}},e.is=function(e){var t=e;return Q.defined(t)&&Q.string(t.uri)}}(w||(w={})),function(e){e.create=function(e,t){return{uri:e,version:t}},e.is=function(e){var t=e;return Q.defined(t)&&Q.string(t.uri)&&(null===t.version||Q.number(t.version))}}(E||(E={})),function(e){e.create=function(e,t,n,r){return{uri:e,languageId:t,version:n,text:r}},e.is=function(e){var t=e;return Q.defined(t)&&Q.string(t.uri)&&Q.string(t.languageId)&&Q.number(t.version)&&Q.string(t.text)}}(x||(x={})),function(e){e.PlainText="plaintext",e.Markdown="markdown"}(S||(S={})),function(e){e.is=function(t){var n=t;return n===e.PlainText||n===e.Markdown}}(S||(S={})),function(e){e.is=function(e){var t=e;return Q.objectLiteral(e)&&S.is(t.kind)&&Q.string(t.value)}}(I||(I={})),function(e){e.Text=1,e.Method=2,e.Function=3,e.Constructor=4,e.Field=5,e.Variable=6,e.Class=7,e.Interface=8,e.Module=9,e.Property=10,e.Unit=11,e.Value=12,e.Enum=13,e.Keyword=14,e.Snippet=15,e.Color=16,e.File=17,e.Reference=18,e.Folder=19,e.EnumMember=20,e.Constant=21,e.Struct=22,e.Event=23,e.Operator=24,e.TypeParameter=25}(A||(A={})),function(e){e.PlainText=1,e.Snippet=2}(T||(T={})),function(e){e.create=function(e){return{label:e}}}(M||(M={})),function(e){e.create=function(e,t){return{items:e||[],isIncomplete:!!t}}}(P||(P={})),function(e){e.fromPlainText=function(e){return e.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")},e.is=function(e){var t=e;return Q.string(t)||Q.objectLiteral(t)&&Q.string(t.language)&&Q.string(t.value)}}(R||(R={})),function(e){e.is=function(e){var t=e;return!!t&&Q.objectLiteral(t)&&(I.is(t.contents)||R.is(t.contents)||Q.typedArray(t.contents,R.is))&&(void 0===e.range||i.is(e.range))}}(F||(F={})),function(e){e.create=function(e,t){return t?{label:e,documentation:t}:{label:e}}}(j||(j={})),function(e){e.create=function(e,t){for(var n=[],r=2;r=0;o--){var a=r[o],s=e.offsetAt(a.range.start),u=e.offsetAt(a.range.end);if(!(u<=i))throw new Error("Overlapping edit");n=n.substring(0,s)+a.newText+n.substring(u,n.length),i=s}return n}}(G||(G={})),function(e){e.Manual=1,e.AfterDelay=2,e.FocusOut=3}(J||(J={}));var Q,X=function(){function e(e,t,n,r){this._uri=e,this._languageId=t,this._version=n,this._content=r,this._lineOffsets=null}return Object.defineProperty(e.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return this._version},enumerable:!0,configurable:!0}),e.prototype.getText=function(e){if(e){var t=this.offsetAt(e.start),n=this.offsetAt(e.end);return this._content.substring(t,n)}return this._content},e.prototype.update=function(e,t){this._content=e.text,this._version=t,this._lineOffsets=null},e.prototype.getLineOffsets=function(){if(null===this._lineOffsets){for(var e=[],t=this._content,n=!0,r=0;r0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets},e.prototype.positionAt=function(e){e=Math.max(Math.min(e,this._content.length),0);var t=this.getLineOffsets(),n=0,i=t.length;if(0===i)return r.create(0,e);for(;ne?i=o:n=o+1}var a=n-1;return r.create(a,e-t[a])},e.prototype.offsetAt=function(e){var t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;var n=t[e.line],r=e.line+1=48&&a<=57)o=16*o+a-48;else if(a>=65&&a<=70)o=16*o+a-65+10;else{if(!(a>=97&&a<=102))break;o=16*o+a-97+10}n++,i++}return i=r)return o=r,a=17;var t=e.charCodeAt(n);if(pe(t)){do{n++,i+=String.fromCharCode(t),t=e.charCodeAt(n)}while(pe(t));return a=15}if(me(t))return n++,i+=String.fromCharCode(t),13===t&&10===e.charCodeAt(n)&&(n++,i+="\n"),s++,c=n,a=14;switch(t){case 123:return n++,a=1;case 125:return n++,a=2;case 91:return n++,a=3;case 93:return n++,a=4;case 58:return n++,a=6;case 44:return n++,a=5;case 34:return n++,i=function(){for(var t="",i=n;;){if(n>=r){t+=e.substring(i,n),f=2;break}var o=e.charCodeAt(n);if(34===o){t+=e.substring(i,n),n++;break}if(92!==o){if(o>=0&&o<=31){if(me(o)){t+=e.substring(i,n),f=2;break}f=6}n++}else{if(t+=e.substring(i,n),++n>=r){f=2;break}switch(o=e.charCodeAt(n++)){case 34:t+='"';break;case 92:t+="\\";break;case 47:t+="/";break;case 98:t+="\b";break;case 102:t+="\f";break;case 110:t+="\n";break;case 114:t+="\r";break;case 116:t+="\t";break;case 117:var a=l(4,!0);a>=0?t+=String.fromCharCode(a):f=4;break;default:f=5}i=n}}return t}(),a=10;case 47:var g=n-1;if(47===e.charCodeAt(n+1)){for(n+=2;n=12&&e<=15);return e}:g,getToken:function(){return a},getTokenValue:function(){return i},getTokenOffset:function(){return o},getTokenLength:function(){return n-o},getTokenStartLine:function(){return u},getTokenStartCharacter:function(){return o-d},getTokenError:function(){return f}}}function pe(e){return 32===e||9===e||11===e||12===e||160===e||5760===e||e>=8192&&e<=8203||8239===e||8287===e||12288===e||65279===e}function me(e){return 10===e||13===e||8232===e||8233===e}function ve(e){return e>=48&&e<=57}!function(e){e.DEFAULT={allowTrailingComma:!1}}(ce||(ce={}));var be=he;function ke(e){return{getInitialState:function(){return new Pe(null,null,!1)},tokenize:function(t,n,r,i){return function(e,t,n,r,i){void 0===r&&(r=0);var o=0,a=!1;switch(n.scanError){case 2:t='"'+t,o=1;break;case 1:t="/*"+t,o=2}var s,u,c=be(t),d=n.lastWasColon;u={tokens:[],endState:n.clone()};for(;;){var f=r+c.getPosition(),l="";if(17===(s=c.scan()))break;if(f===r+c.getPosition())throw new Error("Scanner did not advance, next 3 characters are: "+t.substr(c.getPosition(),3));switch(a&&(f-=o),a=o>0,s){case 1:case 2:l=Ce,d=!1;break;case 3:case 4:l=_e,d=!1;break;case 6:l=ye,d=!0;break;case 5:l=we,d=!1;break;case 8:case 9:l=Ee,d=!1;break;case 7:l=xe,d=!1;break;case 10:l=d?Se:Ae,d=!1;break;case 11:l=Ie,d=!1}if(e)switch(s){case 12:l=Me;break;case 13:l=Te}u.endState=new Pe(n.getStateData(),c.getTokenError(),d),u.tokens.push({startIndex:f,scopes:l})}return u}(e,t,n,r)}}}var Ce="delimiter.bracket.json",_e="delimiter.array.json",ye="delimiter.colon.json",we="delimiter.comma.json",Ee="keyword.json",xe="keyword.json",Se="string.value.json",Ie="number.json",Ae="string.key.json",Te="comment.block.json",Me="comment.line.json",Pe=function(){function e(e,t,n){this._state=e,this.scanError=t,this.lastWasColon=n}return e.prototype.clone=function(){return new e(this._state,this.scanError,this.lastWasColon)},e.prototype.equals=function(t){return t===this||!!(t&&t instanceof e)&&(this.scanError===t.scanError&&this.lastWasColon===t.lastWasColon)},e.prototype.getStateData=function(){return this._state},e.prototype.setStateData=function(e){this._state=e},e}();function Re(e){return{dispose:function(){return Fe(e)}}}function Fe(e){for(;e.length;)e.pop().dispose()}t.setupMode=function(e){var t=[],n=[],r=new y(e);t.push(r);var i=function(){for(var e=[],t=0;t=!%&+\-*/|~^]/,"operator"]],whitespace:[[/\s+/,"white"]],comments:[[/--+.*/,"comment"],[/\/\*/,{token:"comment.quote",next:"@comment"}]],comment:[[/[^*/]+/,"comment"],[/\*\//,{token:"comment.quote",next:"@pop"}],[/./,"comment"]],pseudoColumns:[[/[$][A-Za-z_][\w@#$]*/,{cases:{"@pseudoColumns":"predefined","@default":"identifier"}}]],numbers:[[/0[xX][0-9a-fA-F]*/,"number"],[/[$][+-]*\d*(\.\d*)?/,"number"],[/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/,"number"]],strings:[[/N'/,{token:"string",next:"@string"}],[/'/,{token:"string",next:"@string"}]],string:[[/[^']+/,"string"],[/''/,"string"],[/'/,{token:"string",next:"@pop"}]],complexIdentifiers:[[/\[/,{token:"identifier.quote",next:"@bracketedIdentifier"}],[/"/,{token:"identifier.quote",next:"@quotedIdentifier"}]],bracketedIdentifier:[[/[^\]]+/,"identifier"],[/]]/,"identifier"],[/]/,{token:"identifier.quote",next:"@pop"}]],quotedIdentifier:[[/[^"]+/,"identifier"],[/""/,"identifier"],[/"/,{token:"identifier.quote",next:"@pop"}]],scopes:[[/BEGIN\s+(DISTRIBUTED\s+)?TRAN(SACTION)?\b/i,"keyword"],[/BEGIN\s+TRY\b/i,{token:"keyword.try"}],[/END\s+TRY\b/i,{token:"keyword.try"}],[/BEGIN\s+CATCH\b/i,{token:"keyword.catch"}],[/END\s+CATCH\b/i,{token:"keyword.catch"}],[/(BEGIN|CASE)\b/i,{token:"keyword.block"}],[/END\b/i,{token:"keyword.block"}],[/WHEN\b/i,{token:"keyword.choice"}],[/THEN\b/i,{token:"keyword.choice"}]]}}}}); \ No newline at end of file diff --git a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/3.aae2407112886de0df05.js b/_build/emqx/lib/emqx_dashboard/priv/www/static/js/3.aae2407112886de0df05.js deleted file mode 100644 index b8d0b7ae43..0000000000 --- a/_build/emqx/lib/emqx_dashboard/priv/www/static/js/3.aae2407112886de0df05.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([3],{"+0Qw":function(e,t){},"+66z":function(e,t){var n=Object.prototype.toString;e.exports=function(e){return n.call(e)}},"+Tn7":function(e,t){},"+gg+":function(e,t,n){var i=n("TQ3y")["__core-js_shared__"];e.exports=i},"+jct":function(e,t,n){"use strict";n.d(t,"b",function(){return i}),n.d(t,"a",function(){return o}),t.c=function(e){var t=o;if(e&&e instanceof RegExp)if(e.global)t=e;else{var n="g";e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.unicode&&(n+="u"),t=new RegExp(e.source,n)}return t.lastIndex=0,t},t.d=function(e,t,n,i){t.lastIndex=0;var o=t.exec(n);if(!o)return null;var r=o[0].indexOf(" ")>=0?function(e,t,n,i){var o,r=e-1-i;t.lastIndex=0;for(;o=t.exec(n);){var s=o.index||0;if(s>r)return null;if(t.lastIndex>=r)return{word:o[0],startColumn:i+1+s,endColumn:i+1+t.lastIndex}}return null}(e,t,n,i):function(e,t,n,i){var o,r=e-1-i,s=n.lastIndexOf(" ",r-1)+1;t.lastIndex=s;for(;o=t.exec(n);){var a=o.index||0;if(a<=r&&t.lastIndex>=r)return{word:o[0],startColumn:i+1+a,endColumn:i+1+t.lastIndex}}return null}(e,t,n,i);return t.lastIndex=0,r};var i="`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";var o=function(e){void 0===e&&(e="");for(var t="(-?\\d*\\.\\d\\w*)|([^",n=0,o=i;n=0||(t+="\\"+r)}return t+="\\s]+)",new RegExp(t,"g")}()},"+oh4":function(e,t,n){"use strict";var i;n.d(t,"a",function(){return i}),n.d(t,"b",function(){return o}),function(e){e[e.None=0]="None",e[e.Indent=1]="Indent",e[e.IndentOutdent=2]="IndentOutdent",e[e.Outdent=3]="Outdent"}(i||(i={}));var o=function(){function e(e){if(this.open=e.open,this.close=e.close,this._standardTokenMask=0,Array.isArray(e.notIn))for(var t=0,n=e.notIn.length;t200)return t;if("object"==typeof t){switch(t.$mid){case 1:return i.a.revive(t);case 2:return new RegExp(t.source,t.flags)}for(var o in t)Object.hasOwnProperty.call(t,o)&&(t[o]=e(t[o],n+1))}return t}(t,0)};var i=n("mrx5")},"/9db":function(e,t,n){"use strict";n.d(t,"a",function(){return i});var i,o=n("7g0X");!function(e){e.editorTextFocus=new o.d("editorTextFocus",!1),e.focus=new o.d("editorFocus",!1),e.textInputFocus=new o.d("textInputFocus",!1),e.readOnly=new o.d("editorReadonly",!1),e.writable=e.readOnly.toNegated(),e.hasNonEmptySelection=new o.d("editorHasSelection",!1),e.hasOnlyEmptySelection=e.hasNonEmptySelection.toNegated(),e.hasMultipleSelections=new o.d("editorHasMultipleSelections",!1),e.hasSingleSelection=e.hasMultipleSelections.toNegated(),e.tabMovesFocus=new o.d("editorTabMovesFocus",!1),e.tabDoesNotMoveFocus=e.tabMovesFocus.toNegated(),e.isInEmbeddedEditor=new o.d("isInEmbeddedEditor",!1),e.canUndo=new o.d("canUndo",!1),e.canRedo=new o.d("canRedo",!1),e.languageId=new o.d("editorLangId",""),e.hasCompletionItemProvider=new o.d("editorHasCompletionItemProvider",!1),e.hasCodeActionsProvider=new o.d("editorHasCodeActionsProvider",!1),e.hasCodeLensProvider=new o.d("editorHasCodeLensProvider",!1),e.hasDefinitionProvider=new o.d("editorHasDefinitionProvider",!1),e.hasDeclarationProvider=new o.d("editorHasDeclarationProvider",!1),e.hasImplementationProvider=new o.d("editorHasImplementationProvider",!1),e.hasTypeDefinitionProvider=new o.d("editorHasTypeDefinitionProvider",!1),e.hasHoverProvider=new o.d("editorHasHoverProvider",!1),e.hasDocumentHighlightProvider=new o.d("editorHasDocumentHighlightProvider",!1),e.hasDocumentSymbolProvider=new o.d("editorHasDocumentSymbolProvider",!1),e.hasReferenceProvider=new o.d("editorHasReferenceProvider",!1),e.hasRenameProvider=new o.d("editorHasRenameProvider",!1),e.hasSignatureHelpProvider=new o.d("editorHasSignatureHelpProvider",!1),e.hasDocumentFormattingProvider=new o.d("editorHasDocumentFormattingProvider",!1),e.hasDocumentSelectionFormattingProvider=new o.d("editorHasDocumentSelectionFormattingProvider",!1),e.hasMultipleDocumentFormattingProvider=new o.d("editorHasMultipleDocumentFormattingProvider",!1),e.hasMultipleDocumentSelectionFormattingProvider=new o.d("editorHasMultipleDocumentSelectionFormattingProvider",!1)}(i||(i={}))},"/GnY":function(e,t,n){var i=n("HT7L"),o=n("W529"),r=Object.prototype.hasOwnProperty;e.exports=function(e){if(!i(e))return o(e);var t=[];for(var n in Object(e))r.call(e,n)&&"constructor"!=n&&t.push(n);return t}},"/tAm":function(e,t,n){"use strict";t.__esModule=!0;var i=r(n("gdof")),o=r(n("7PNz"));function r(e){return e&&e.__esModule?e:{default:e}}var s=["ALL","ALTER","ANALYZE","AND","ANY","ARRAY","AS","ASC","BEGIN","BETWEEN","BINARY","BOOLEAN","BREAK","BUCKET","BUILD","BY","CALL","CASE","CAST","CLUSTER","COLLATE","COLLECTION","COMMIT","CONNECT","CONTINUE","CORRELATE","COVER","CREATE","DATABASE","DATASET","DATASTORE","DECLARE","DECREMENT","DELETE","DERIVED","DESC","DESCRIBE","DISTINCT","DO","DROP","EACH","ELEMENT","ELSE","END","EVERY","EXCEPT","EXCLUDE","EXECUTE","EXISTS","EXPLAIN","FALSE","FETCH","FIRST","FLATTEN","FOR","FORCE","FROM","FUNCTION","GRANT","GROUP","GSI","HAVING","IF","IGNORE","ILIKE","IN","INCLUDE","INCREMENT","INDEX","INFER","INLINE","INNER","INSERT","INTERSECT","INTO","IS","JOIN","KEY","KEYS","KEYSPACE","KNOWN","LAST","LEFT","LET","LETTING","LIKE","LIMIT","LSM","MAP","MAPPING","MATCHED","MATERIALIZED","MERGE","MINUS","MISSING","NAMESPACE","NEST","NOT","NULL","NUMBER","OBJECT","OFFSET","ON","OPTION","OR","ORDER","OUTER","OVER","PARSE","PARTITION","PASSWORD","PATH","POOL","PREPARE","PRIMARY","PRIVATE","PRIVILEGE","PROCEDURE","PUBLIC","RAW","REALM","REDUCE","RENAME","RETURN","RETURNING","REVOKE","RIGHT","ROLE","ROLLBACK","SATISFIES","SCHEMA","SELECT","SELF","SEMI","SET","SHOW","SOME","START","STATISTICS","STRING","SYSTEM","THEN","TO","TRANSACTION","TRIGGER","TRUE","TRUNCATE","UNDER","UNION","UNIQUE","UNKNOWN","UNNEST","UNSET","UPDATE","UPSERT","USE","USER","USING","VALIDATE","VALUE","VALUED","VALUES","VIA","VIEW","WHEN","WHERE","WHILE","WITH","WITHIN","WORK","XOR"],a=["DELETE FROM","EXCEPT ALL","EXCEPT","EXPLAIN DELETE FROM","EXPLAIN UPDATE","EXPLAIN UPSERT","FROM","GROUP BY","HAVING","INFER","INSERT INTO","INTERSECT ALL","INTERSECT","LET","LIMIT","MERGE","NEST","ORDER BY","PREPARE","SELECT","SET CURRENT SCHEMA","SET SCHEMA","SET","UNION ALL","UNION","UNNEST","UPDATE","UPSERT","USE KEYS","VALUES","WHERE"],u=["AND","INNER JOIN","JOIN","LEFT JOIN","LEFT OUTER JOIN","OR","OUTER JOIN","RIGHT JOIN","RIGHT OUTER JOIN","XOR"],l=void 0,c=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.cfg=t}return e.prototype.format=function(e){return l||(l=new o.default({reservedWords:s,reservedToplevelWords:a,reservedNewlineWords:u,stringTypes:['""',"''","``"],openParens:["(","[","{"],closeParens:[")","]","}"],namedPlaceholderTypes:["$"],lineCommentTypes:["#","--"]})),new i.default(this.cfg,l).format(e)},e}();t.default=c,e.exports=t.default},"/uRs":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"win32",function(){return b}),n.d(t,"posix",function(){return C}),n.d(t,"normalize",function(){return w}),n.d(t,"join",function(){return S}),n.d(t,"relative",function(){return L}),n.d(t,"dirname",function(){return O}),n.d(t,"basename",function(){return E}),n.d(t,"extname",function(){return N}),n.d(t,"sep",function(){return x});var i,o=n("xgy6"),r=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=65,a=97,u=90,l=122,c=46,d=47,h=92,p=function(e){function t(t,n,i){var o,r=this;"string"==typeof n&&0===n.indexOf("not ")?(o="must not be",n=n.replace(/^not /,"")):o="must be";var s='The "'+t+'" '+(-1!==t.indexOf(".")?"property":"argument")+" "+o+" of type "+n;return s+=". Received type "+typeof i,(r=e.call(this,s)||this).code="ERR_INVALID_ARG_TYPE",r}return r(t,e),t}(Error);function f(e,t){if("string"!=typeof e)throw new p(t,"string",e)}function g(e){return e===d||e===h}function m(e){return e===d}function _(e){return e>=s&&e<=u||e>=a&&e<=l}function v(e,t,n,i){for(var o,r="",s=0,a=-1,u=0,l=0;l<=e.length;++l){if(l2){var h=r.lastIndexOf(n);-1===h?(r="",s=0):s=(r=r.slice(0,h)).length-1-r.lastIndexOf(n),a=l,u=0;continue}if(2===r.length||1===r.length){r="",s=0,a=l,u=0;continue}}t&&(r.length>0?r+=n+"..":r="..",s=2)}else r.length>0?r+=n+e.slice(a+1,l):r=e.slice(a+1,l),s=l-a-1;a=l,u=0}else o===c&&-1!==u?++u:u=-1}return r}function y(e,t){var n=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+i:n+e+i:i}var b={resolve:function(){for(var e=[],t=0;t=-1;s--){var a=void 0;if(s>=0?a=e[s]:n?void 0!==(a=o.b["="+n]||o.a())&&a.slice(0,3).toLowerCase()===n.toLowerCase()+"\\"||(a=n+"\\"):a=o.a(),f(a,"path"),0!==a.length){var u=a.length,l=0,c="",d=!1,h=a.charCodeAt(0);if(u>1)if(g(h))if(d=!0,g(a.charCodeAt(1))){for(var p=2,m=p;p2&&g(a.charCodeAt(2))&&(d=!0,l=3));else g(h)&&(l=1,d=!0);if(!(c.length>0&&n.length>0&&c.toLowerCase()!==n.toLowerCase())&&(0===n.length&&c.length>0&&(n=c),r||(i=a.slice(l)+"\\"+i,r=d),n.length>0&&r))break}}return i=v(i,!r,"\\",g),n+(r?"\\":"")+i||"."},normalize:function(e){f(e,"path");var t=e.length;if(0===t)return".";var n,i,o=0,r=!1,s=e.charCodeAt(0);if(t>1)if(g(s))if(r=!0,g(e.charCodeAt(1))){for(var a=2,u=a;a2&&g(e.charCodeAt(2))&&(r=!0,o=3));else if(g(s))return"\\";return 0!==(i=o0&&g(e.charCodeAt(t-1))&&(i+="\\"),void 0===n?r?i.length>0?"\\"+i:"\\":i.length>0?i:"":r?i.length>0?n+"\\"+i:n+"\\":i.length>0?n+i:n},isAbsolute:function(e){f(e,"path");var t=e.length;if(0===t)return!1;var n=e.charCodeAt(0);return!!g(n)||!!(_(n)&&t>2&&58===e.charCodeAt(1)&&g(e.charCodeAt(2)))},join:function(){for(var e,t,n=[],i=0;i0&&(void 0===e?e=t=r:e+="\\"+r)}if(void 0===e)return".";var s=!0,a=0;if("string"==typeof t&&g(t.charCodeAt(0))){++a;var u=t.length;u>1&&g(t.charCodeAt(1))&&(++a,u>2&&(g(t.charCodeAt(2))?++a:s=!1))}if(s){for(;a=2&&(e="\\"+e.slice(a))}return b.normalize(e)},relative:function(e,t){if(f(e,"from"),f(t,"to"),e===t)return"";var n=b.resolve(e),i=b.resolve(t);if(n===i)return"";if((e=n.toLowerCase())===(t=i.toLowerCase()))return"";for(var o=0;oo&&e.charCodeAt(r-1)===h;--r);for(var s=r-o,a=0;aa&&t.charCodeAt(u-1)===h;--u);for(var l=u-a,c=sc){if(t.charCodeAt(a+p)===h)return i.slice(a+p+1);if(2===p)return i.slice(a+p)}s>c&&(e.charCodeAt(o+p)===h?d=p:2===p&&(d=3));break}var g=e.charCodeAt(o+p);if(g!==t.charCodeAt(a+p))break;g===h&&(d=p)}if(p!==c&&-1===d)return i;var m="";for(-1===d&&(d=0),p=o+d+1;p<=r;++p)p!==r&&e.charCodeAt(p)!==h||(0===m.length?m+="..":m+="\\..");return m.length>0?m+i.slice(a+d,u):(a+=d,i.charCodeAt(a)===h&&++a,i.slice(a,u))},toNamespacedPath:function(e){if("string"!=typeof e)return e;if(0===e.length)return"";var t=b.resolve(e);if(t.length>=3)if(t.charCodeAt(0)===h){if(t.charCodeAt(1)===h){var n=t.charCodeAt(2);if(63!==n&&n!==c)return"\\\\?\\UNC\\"+t.slice(2)}}else if(_(t.charCodeAt(0))&&58===t.charCodeAt(1)&&t.charCodeAt(2)===h)return"\\\\?\\"+t;return e},dirname:function(e){f(e,"path");var t=e.length;if(0===t)return".";var n=-1,i=-1,o=!0,r=0,s=e.charCodeAt(0);if(t>1)if(g(s)){if(n=r=1,g(e.charCodeAt(1))){for(var a=2,u=a;a2&&g(e.charCodeAt(2))&&(n=r=3));else if(g(s))return e;for(var l=t-1;l>=r;--l)if(g(e.charCodeAt(l))){if(!o){i=l;break}}else o=!1;if(-1===i){if(-1===n)return".";i=n}return e.slice(0,i)},basename:function(e,t){void 0!==t&&f(t,"ext"),f(e,"path");var n,i=0,o=-1,r=!0;e.length>=2&&(_(e.charCodeAt(0))&&58===e.charCodeAt(1)&&(i=2));if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var s=t.length-1,a=-1;for(n=e.length-1;n>=i;--n){var u=e.charCodeAt(n);if(g(u)){if(!r){i=n+1;break}}else-1===a&&(r=!1,a=n+1),s>=0&&(u===t.charCodeAt(s)?-1==--s&&(o=n):(s=-1,o=a))}return i===o?o=a:-1===o&&(o=e.length),e.slice(i,o)}for(n=e.length-1;n>=i;--n)if(g(e.charCodeAt(n))){if(!r){i=n+1;break}}else-1===o&&(r=!1,o=n+1);return-1===o?"":e.slice(i,o)},extname:function(e){f(e,"path");var t=0,n=-1,i=0,o=-1,r=!0,s=0;e.length>=2&&58===e.charCodeAt(1)&&_(e.charCodeAt(0))&&(t=i=2);for(var a=e.length-1;a>=t;--a){var u=e.charCodeAt(a);if(g(u)){if(!r){i=a+1;break}}else-1===o&&(r=!1,o=a+1),u===c?-1===n?n=a:1!==s&&(s=1):-1!==n&&(s=-1)}return-1===n||-1===o||0===s||1===s&&n===o-1&&n===i+1?"":e.slice(n,o)},format:function(e){if(null===e||"object"!=typeof e)throw new p("pathObject","Object",e);return y("\\",e)},parse:function(e){f(e,"path");var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var n=e.length,i=0,o=e.charCodeAt(0);if(n>1){if(g(o)){if(i=1,g(e.charCodeAt(1))){for(var r=2,s=r;r2))return t.root=t.dir=e,t;if(g(e.charCodeAt(2))){if(3===n)return t.root=t.dir=e,t;i=3}}}else if(g(o))return t.root=t.dir=e,t;i>0&&(t.root=e.slice(0,i));for(var a=-1,u=i,l=-1,d=!0,h=e.length-1,p=0;h>=i;--h)if(g(o=e.charCodeAt(h))){if(!d){u=h+1;break}}else-1===l&&(d=!1,l=h+1),o===c?-1===a?a=h:1!==p&&(p=1):-1!==a&&(p=-1);return-1===a||-1===l||0===p||1===p&&a===l-1&&a===u+1?-1!==l&&(t.base=t.name=e.slice(u,l)):(t.name=e.slice(u,a),t.base=e.slice(u,l),t.ext=e.slice(a,l)),t.dir=u>0&&u!==i?e.slice(0,u-1):t.root,t},sep:"\\",delimiter:";",win32:null,posix:null},C={resolve:function(){for(var e=[],t=0;t=-1&&!i;r--){var s=void 0;f(s=r>=0?e[r]:o.a(),"path"),0!==s.length&&(n=s+"/"+n,i=s.charCodeAt(0)===d)}return n=v(n,!i,"/",m),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(e){if(f(e,"path"),0===e.length)return".";var t=e.charCodeAt(0)===d,n=e.charCodeAt(e.length-1)===d;return 0!==(e=v(e,!t,"/",m)).length||t||(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return f(e,"path"),e.length>0&&e.charCodeAt(0)===d},join:function(){for(var e,t=[],n=0;n0&&(void 0===e?e=o:e+="/"+o)}return void 0===e?".":C.normalize(e)},relative:function(e,t){if(f(e,"from"),f(t,"to"),e===t)return"";if((e=C.resolve(e))===(t=C.resolve(t)))return"";for(var n=1;na){if(t.charCodeAt(r+l)===d)return t.slice(r+l+1);if(0===l)return t.slice(r+l)}else o>a&&(e.charCodeAt(n+l)===d?u=l:0===l&&(u=0));break}var c=e.charCodeAt(n+l);if(c!==t.charCodeAt(r+l))break;c===d&&(u=l)}var h="";for(l=n+u+1;l<=i;++l)l!==i&&e.charCodeAt(l)!==d||(0===h.length?h+="..":h+="/..");return h.length>0?h+t.slice(r+u):(r+=u,t.charCodeAt(r)===d&&++r,t.slice(r))},toNamespacedPath:function(e){return e},dirname:function(e){if(f(e,"path"),0===e.length)return".";for(var t=e.charCodeAt(0)===d,n=-1,i=!0,o=e.length-1;o>=1;--o)if(e.charCodeAt(o)===d){if(!i){n=o;break}}else i=!1;return-1===n?t?"/":".":t&&1===n?"//":e.slice(0,n)},basename:function(e,t){void 0!==t&&f(t,"ext"),f(e,"path");var n,i=0,o=-1,r=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var s=t.length-1,a=-1;for(n=e.length-1;n>=0;--n){var u=e.charCodeAt(n);if(u===d){if(!r){i=n+1;break}}else-1===a&&(r=!1,a=n+1),s>=0&&(u===t.charCodeAt(s)?-1==--s&&(o=n):(s=-1,o=a))}return i===o?o=a:-1===o&&(o=e.length),e.slice(i,o)}for(n=e.length-1;n>=0;--n)if(e.charCodeAt(n)===d){if(!r){i=n+1;break}}else-1===o&&(r=!1,o=n+1);return-1===o?"":e.slice(i,o)},extname:function(e){f(e,"path");for(var t=-1,n=0,i=-1,o=!0,r=0,s=e.length-1;s>=0;--s){var a=e.charCodeAt(s);if(a!==d)-1===i&&(o=!1,i=s+1),a===c?-1===t?t=s:1!==r&&(r=1):-1!==t&&(r=-1);else if(!o){n=s+1;break}}return-1===t||-1===i||0===r||1===r&&t===i-1&&t===n+1?"":e.slice(t,i)},format:function(e){if(null===e||"object"!=typeof e)throw new p("pathObject","Object",e);return y("/",e)},parse:function(e){f(e,"path");var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var n,i=e.charCodeAt(0)===d;i?(t.root="/",n=1):n=0;for(var o=-1,r=0,s=-1,a=!0,u=e.length-1,l=0;u>=n;--u){var h=e.charCodeAt(u);if(h!==d)-1===s&&(a=!1,s=u+1),h===c?-1===o?o=u:1!==l&&(l=1):-1!==o&&(l=-1);else if(!a){r=u+1;break}}return-1===o||-1===s||0===l||1===l&&o===s-1&&o===r+1?-1!==s&&(t.base=t.name=0===r&&i?e.slice(1,s):e.slice(r,s)):(0===r&&i?(t.name=e.slice(1,o),t.base=e.slice(1,s)):(t.name=e.slice(r,o),t.base=e.slice(r,s)),t.ext=e.slice(o,s)),r>0?t.dir=e.slice(0,r-1):i&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};C.win32=b.win32=b,C.posix=b.posix=C;var w="win32"===o.c?b.normalize:C.normalize,S="win32"===o.c?b.join:C.join,L="win32"===o.c?b.relative:C.relative,O="win32"===o.c?b.dirname:C.dirname,E="win32"===o.c?b.basename:C.basename,N="win32"===o.c?b.extname:C.extname,x="win32"===o.c?b.sep:C.sep},"03Zz":function(e,t,n){"use strict";n.d(t,"a",function(){return y}),n.d(t,"c",function(){return b}),n.d(t,"b",function(){return C}),t.j=w,t.e=function(e,t){w(e,function(e,n){var i=n.resource,o=n.position;if(!(i instanceof s.a))throw Object(r.b)("resource");if(!u.a.isIPosition(o))throw Object(r.b)("position");var a=e.get(l.a).getModel(i);if(a){var d=u.a.lift(o);return t(a,d,n)}return e.get(c.a).createModelReference(i).then(function(e){return new Promise(function(i,r){try{var s=t(e.object.textEditorModel,u.a.lift(o),n);i(s)}catch(e){r(e)}}).finally(function(){e.dispose()})})})},t.g=function(e){return S.INSTANCE.registerEditorCommand(e),e},t.f=function(e){S.INSTANCE.registerEditorAction(new e)},t.i=function(e){S.INSTANCE.registerEditorAction(e)},t.h=function(e){S.INSTANCE.registerEditorContribution(e)},n.d(t,"d",function(){return o});var i,o,r=n("zxiH"),s=n("mrx5"),a=n("vORD"),u=n("artP"),l=n("jIdl"),c=n("B/Xy"),d=n("C3c5"),h=n("ItKl"),p=n("7g0X"),f=n("Kx4b"),g=n("RWr8"),m=n("3ciN"),_=n("KIxu"),v=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),y=function(){function e(e){this.id=e.id,this.precondition=e.precondition,this._kbOpts=e.kbOpts,this._menubarOpts=e.menubarOpts,this._description=e.description}return e.prototype.register=function(){var e=this;if(this._menubarOpts&&d.c.appendMenuItem(this._menubarOpts.menuId,{group:this._menubarOpts.group,command:{id:this.id,title:this._menubarOpts.title},when:this._menubarOpts.when,order:this._menubarOpts.order}),this._kbOpts){var t=this._kbOpts.kbExpr;this.precondition&&(t=t?p.a.and(t,this.precondition):this.precondition),f.a.registerCommandAndKeybindingRule({id:this.id,handler:function(t,n){return e.runCommand(t,n)},weight:this._kbOpts.weight,when:t,primary:this._kbOpts.primary,secondary:this._kbOpts.secondary,win:this._kbOpts.win,linux:this._kbOpts.linux,mac:this._kbOpts.mac,description:this._description})}else h.a.registerCommand({id:this.id,handler:function(t,n){return e.runCommand(t,n)},description:this._description})},e}(),b=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return v(t,e),t.bindToContribution=function(e){return function(t){function n(e){var n=t.call(this,e)||this;return n._callback=e.handler,n}return v(n,t),n.prototype.runEditorCommand=function(t,n,i){e(n)&&this._callback(e(n),i)},n}(t)},t.prototype.runCommand=function(e,t){var n=this,i=e.get(a.a),o=i.getFocusedCodeEditor()||i.getActiveCodeEditor();if(o)return o.invokeWithinContext(function(e){if(e.get(p.c).contextMatchesRules(Object(_.m)(n.precondition)))return n.runEditorCommand(e,o,t)})},t}(y),C=function(e){function t(t){var n=e.call(this,t)||this;return n.label=t.label,n.alias=t.alias,n.menuOpts=t.menuOpts,n}return v(t,e),t.prototype.register=function(){this.menuOpts&&d.c.appendMenuItem(7,{command:{id:this.id,title:this.label},when:p.a.and(this.precondition,this.menuOpts.when),group:this.menuOpts.group,order:this.menuOpts.order}),e.prototype.register.call(this)},t.prototype.runEditorCommand=function(e,t,n){return this.reportTelemetry(e,t),this.run(e,t,n||{})},t.prototype.reportTelemetry=function(e,t){e.get(m.a).publicLog2("editorActionInvoked",{name:this.label,id:this.id})},t}(b);function w(e,t){h.a.registerCommand(e,function(e,n){return t(e,n||{})})}!function(e){e.getEditorCommand=function(e){return S.INSTANCE.getEditorCommand(e)},e.getEditorActions=function(){return S.INSTANCE.getEditorActions()},e.getEditorContributions=function(){return S.INSTANCE.getEditorContributions()}}(o||(o={}));var S=function(){function e(){this.editorContributions=[],this.editorActions=[],this.editorCommands=Object.create(null)}return e.prototype.registerEditorContribution=function(e){this.editorContributions.push(e)},e.prototype.registerEditorAction=function(e){e.register(),this.editorActions.push(e)},e.prototype.getEditorContributions=function(){return this.editorContributions.slice(0)},e.prototype.getEditorActions=function(){return this.editorActions.slice(0)},e.prototype.registerEditorCommand=function(e){e.register(),this.editorCommands[e.id]=e},e.prototype.getEditorCommand=function(e){return this.editorCommands[e]||null},e.INSTANCE=new e,e}();g.a.add("editor.contributions",S.INSTANCE)},"0Td8":function(e,t,n){"use strict";var i,o,r=n("tqet"),s=n("aL7J"),a=n("03Zz"),u=n("7VLx"),l=n("/9db"),c=n("zxiH"),d=n("Cv8t"),h=n("yO/1"),p=n("NqM+"),f=n("7/Cv"),g=n("AKCZ"),m=n("artP"),_=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),v=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},y=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},N=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}};!function(e){e.Hidden=new(function(){return function(){this.type=0}}());var t=function(){return function(e,t,n){this.actions=e,this.editorPosition=t,this.widgetPosition=n,this.type=1}}();e.Showing=t}(o||(o={}));var x,I=function(e){function t(t,n,i){var r=e.call(this)||this;return r._editor=t,r._quickFixActionId=n,r._keybindingService=i,r._onClick=r._register(new w.a),r.onClick=r._onClick.event,r._state=o.Hidden,r._domNode=document.createElement("div"),r._domNode.className="lightbulb-glyph",r._editor.addContentWidget(r),r._register(r._editor.onDidChangeModelContent(function(e){var t=r._editor.getModel();(1!==r._state.type||!t||r._state.editorPosition.lineNumber>=t.getLineCount())&&r.hide()})),r._register(f.k(r._domNode,"mousedown",function(e){if(1===r._state.type){r._editor.focus(),e.preventDefault();var t=f.x(r._domNode),n=t.top,i=t.height,o=r._editor.getConfiguration().lineHeight,s=Math.floor(o/3);null!==r._state.widgetPosition.position&&r._state.widgetPosition.position.lineNumber2&&i._editor.getTopForLineNumber(e)===i._editor.getTopForLineNumber(e-1)},p=s;if(!(r.fontInfo.spaceWidth*d>22))if(s>1&&!h(s-1))p-=1;else if(h(s+1)){if(a*r.fontInfo.spaceWidth<22)return this.hide()}else p+=1;this._state=new o.Showing(e,n,{position:{lineNumber:p,column:1},preference:t._posPref}),f.R(this._domNode,"autofixable",e.hasAutoFix),this._editor.layoutContentWidget(this)},Object.defineProperty(t.prototype,"title",{set:function(e){this._domNode.title=e},enumerable:!0,configurable:!0}),t.prototype.hide=function(){this._state=o.Hidden,this._editor.layoutContentWidget(this)},t.prototype._updateLightBulbTitle=function(){var e,t=this._keybindingService.lookupKeybinding(this._quickFixActionId);e=t?L.a("quickFixWithKb","Show Fixes ({0})",t.getLabel()):L.a("quickFix","Show Fixes"),this.title=e},t._posPref=[0],t=E([N(2,p.a)],t)}(r.a),D=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),k=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},T=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},M=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},R=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]0))return[3,9];if(1!==e.trigger.autoApply&&(0!==e.trigger.autoApply||1!==t.actions.length))return[3,9];i.label=5;case 5:return i.trys.push([5,,7,8]),[4,this.delegate.applyCodeAction(t.actions[0],!1)];case 6:return i.sent(),[3,8];case 7:return t.dispose(),[7];case 8:return[2];case 9:return this._activeCodeActions.value=t,this._codeActionWidget.show(t,e.position),[3,11];case 10:this._codeActionWidget.isVisible?t.dispose():this._activeCodeActions.value=t,i.label=11;case 11:return[2]}})})},t.prototype.showCodeActionList=function(e,t){return M(this,void 0,void 0,function(){return R(this,function(n){return this._codeActionWidget.show(e,t),[2]})})},t.prototype._handleLightBulbSelect=function(e){this._codeActionWidget.show(e.actions,e)},t=k([T(3,h.a),T(4,p.a)],t)}(r.a),P=n("ItKl"),F=n("7g0X"),W=n("OHx0"),j=n("DBt1"),V=n("odeJ"),B=n("vTy2"),H=n("PCC9"),z=n("OBuU"),U=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),K=new F.d("supportedCodeAction",""),q=function(e){function t(t,n,i,o){void 0===o&&(o=250);var r=e.call(this)||this;return r._editor=t,r._markerService=n,r._signalChange=i,r._delay=o,r._autoTriggerTimer=r._register(new V.e),r._register(r._markerService.onMarkerChanged(function(e){return r._onMarkerChanges(e)})),r._register(r._editor.onDidChangeCursorPosition(function(){return r._onCursorChange()})),r}return U(t,e),t.prototype.trigger=function(e){var t=this._getRangeOfSelectionUnlessWhitespaceEnclosed(e);return this._createEventAndSignalChange(e,t)},t.prototype._onMarkerChanges=function(e){var t=this,n=this._editor.getModel();n&&e.some(function(e){return e.toString()===n.uri.toString()})&&this._autoTriggerTimer.cancelAndSet(function(){t.trigger({type:"auto"})},this._delay)},t.prototype._onCursorChange=function(){var e=this;this._autoTriggerTimer.cancelAndSet(function(){e.trigger({type:"auto"})},this._delay)},t.prototype._getRangeOfMarker=function(e){var t=this._editor.getModel();if(t)for(var n=0,i=this._markerService.read({resource:t.uri});n=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},J=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Q=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},$=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=0;t--)this.editOperations[t]={operations:e.applyEdits(this.editOperations[t].operations)}},e.prototype.redo=function(e){for(var t=0;t0){var e=this.past.pop();try{e.undo(this.model)}catch(e){return Object(i.e)(e),this.clear(),null}return this.future.push(e),{selections:e.beforeCursorState,recordedVersionId:e.beforeVersionId}}return null},e.prototype.canUndo=function(){return this.past.length>0||null!==this.currentOpenStackElement},e.prototype.redo=function(){if(this.future.length>0){var e=this.future.pop();try{e.redo(this.model)}catch(e){return Object(i.e)(e),this.clear(),null}return this.past.push(e),{selections:e.afterCursorState,recordedVersionId:e.afterVersionId}}return null},e.prototype.canRedo=function(){return this.future.length>0},e}(),_=function(){return function(){this.spacesDiff=0,this.looksLikeAlignment=!1}}();function v(e,t,n,i,o){var r;for(o.spacesDiff=0,o.looksLikeAlignment=!1,r=0;r0&&a>0||l>0&&c>0)){var d=Math.abs(a-c),h=Math.abs(s-l);if(0===d)return o.spacesDiff=h,void(h>0&&0<=l-1&&l-10?o++:m>1&&r++,v(s,a,h,g,l),!l.looksLikeAlignment||n&&t===l.spacesDiff)){var S=l.spacesDiff;S<=8&&u[S]++,s=h,a=g}}var L=n;o!==r&&(L=oE&&(E=t,O=e)}),4===O&&u[4]>0&&u[2]>0&&u[2]>=u[4]/2&&(O=2)}return{insertSpaces:L,tabSize:O}}function b(e){return(1&e.metadata)>>>0}function C(e,t){e.metadata=254&e.metadata|t<<0}function w(e){return(2&e.metadata)>>>1==1}function S(e,t){e.metadata=253&e.metadata|(t?1:0)<<1}function L(e){return(4&e.metadata)>>>2==1}function O(e,t){e.metadata=251&e.metadata|(t?1:0)<<2}function E(e){return(8&e.metadata)>>>3==1}function N(e,t){e.metadata=247&e.metadata|(t?1:0)<<3}function x(e,t){e.metadata=207&e.metadata|t<<4}function I(e,t){e.metadata=191&e.metadata|(t?1:0)<<6}var D=function(){function e(e,t,n){this.metadata=0,this.parent=this,this.left=this,this.right=this,C(this,1),this.start=t,this.end=n,this.delta=0,this.maxEnd=n,this.id=e,this.ownerId=0,this.options=null,O(this,!1),x(this,1),N(this,!1),I(this,!1),this.cachedVersionId=0,this.cachedAbsoluteStart=t,this.cachedAbsoluteEnd=n,this.range=null,S(this,!1)}return e.prototype.reset=function(e,t,n,i){this.start=t,this.end=n,this.maxEnd=n,this.cachedVersionId=e,this.cachedAbsoluteStart=t,this.cachedAbsoluteEnd=n,this.range=i},e.prototype.setOptions=function(e){this.options=e;var t=this.options.className;O(this,"squiggly-error"===t||"squiggly-warning"===t||"squiggly-info"===t),x(this,this.options.stickiness),N(this,!(!this.options.overviewRuler||!this.options.overviewRuler.color)),I(this,this.options.collapseOnReplaceEdit)},e.prototype.setCachedOffsets=function(e,t,n){this.cachedVersionId!==n&&(this.range=null),this.cachedVersionId=n,this.cachedAbsoluteStart=e,this.cachedAbsoluteEnd=t},e.prototype.detach=function(){this.parent=null,this.left=null,this.right=null},e}(),k=new D(null,0,0);k.parent=k,k.left=k,k.right=k,C(k,0);var T=function(){function e(){this.root=k,this.requestNormalizeDelta=!1}return e.prototype.intervalSearch=function(e,t,n,i,o){return this.root===k?[]:function(e,t,n,i,o,r){var s=e.root,a=0,u=0,l=0,c=[],d=0;for(;s!==k;)if(w(s))S(s.left,!1),S(s.right,!1),s===s.parent.right&&(a-=s.parent.delta),s=s.parent;else{if(!w(s.left)){if(a+s.maxEndn)S(s,!0);else{if((l=a+s.end)>=t){s.setCachedOffsets(u,l,r);var h=!0;i&&s.ownerId&&s.ownerId!==i&&(h=!1),o&&L(s)&&(h=!1),h&&(c[d++]=s)}S(s,!0),s.right===k||w(s.right)||(a+=s.delta,s=s.right)}}return S(e.root,!1),c}(this,e,t,n,i,o)},e.prototype.search=function(e,t,n){return this.root===k?[]:function(e,t,n,i){var o=e.root,r=0,s=0,a=0,u=[],l=0;for(;o!==k;)if(w(o))S(o.left,!1),S(o.right,!1),o===o.parent.right&&(r-=o.parent.delta),o=o.parent;else if(o.left===k||w(o.left)){s=r+o.start,a=r+o.end,o.setCachedOffsets(s,a,i);var c=!0;t&&o.ownerId&&o.ownerId!==t&&(c=!1),n&&L(o)&&(c=!1),c&&(u[l++]=o),S(o,!0),o.right===k||w(o.right)||(r+=o.delta,o=o.right)}else o=o.left;return S(e.root,!1),u}(this,e,t,n)},e.prototype.collectNodesFromOwner=function(e){return function(e,t){var n=e.root,i=[],o=0;for(;n!==k;)w(n)?(S(n.left,!1),S(n.right,!1),n=n.parent):n.left===k||w(n.left)?(n.ownerId===t&&(i[o++]=n),S(n,!0),n.right===k||w(n.right)||(n=n.right)):n=n.left;return S(e.root,!1),i}(this,e)},e.prototype.collectNodesPostOrder=function(){return function(e){var t=e.root,n=[],i=0;for(;t!==k;)w(t)?(S(t.left,!1),S(t.right,!1),t=t.parent):t.left===k||w(t.left)?t.right===k||w(t.right)?(n[i++]=t,S(t,!0)):t=t.right:t=t.left;return S(e.root,!1),n}(this)},e.prototype.insert=function(e){A(this,e),this._normalizeDeltaIfNecessary()},e.prototype.delete=function(e){P(this,e),this._normalizeDeltaIfNecessary()},e.prototype.resolveNode=function(e,t){for(var n=e,i=0;e!==this.root;)e===e.parent.right&&(i+=e.parent.delta),e=e.parent;var o=n.start+i,r=n.end+i;n.setCachedOffsets(o,r,t)},e.prototype.acceptReplace=function(e,t,n,i){for(var o=function(e,t,n){var i=e.root,o=0,r=0,s=0,a=[],u=0;for(;i!==k;)if(w(i))S(i.left,!1),S(i.right,!1),i===i.parent.right&&(o-=i.parent.delta),i=i.parent;else{if(!w(i.left)){if(o+i.maxEndn?S(i,!0):((s=o+i.end)>=t&&(i.setCachedOffsets(r,s,0),a[u++]=i),S(i,!0),i.right===k||w(i.right)||(o+=i.delta,i=i.right))}return S(e.root,!1),a}(this,e,e+t),r=0,s=o.length;rn?(o.start+=s,o.end+=s,o.delta+=s,(o.delta<-1073741824||o.delta>1073741824)&&(e.requestNormalizeDelta=!0),S(o,!0)):(S(o,!0),o.right===k||w(o.right)||(r+=o.delta,o=o.right))}S(e.root,!1)}(this,e,e+t,n),this._normalizeDeltaIfNecessary();for(r=0,s=o.length;rn)&&(1!==i&&(2===i||t))}function R(e,t,n,i,o){var r=function(e){return(48&e.metadata)>>>4}(e),s=0===r||2===r,a=1===r||2===r,u=n-t,l=i,c=Math.min(u,l),d=e.start,h=!1,p=e.end,f=!1;t<=d&&p<=n&&function(e){return(64&e.metadata)>>>6==1}(e)&&(e.start=t,h=!0,e.end=t,f=!0);var g=o?1:u>0?2:0;if(!h&&M(d,s,t,g)&&(h=!0),!f&&M(p,a,t,g)&&(f=!0),c>0&&!o){g=u>l?2:0;!h&&M(d,s,t+c,g)&&(h=!0),!f&&M(p,a,t+c,g)&&(f=!0)}g=o?1:0;!h&&M(d,s,n,g)&&(e.start=t+l,h=!0),!f&&M(p,a,n,g)&&(e.end=t+l,f=!0);var m=l-u;h||(e.start=Math.max(0,d+m)),f||(e.end=Math.max(0,p+m)),e.start>e.end&&(e.end=e.start)}function A(e,t){if(e.root===k)return t.parent=k,t.left=k,t.right=k,C(t,0),e.root=t,e.root;!function(e,t){var n=0,i=e.root,o=t.start,r=t.end;for(;;){var s=z(o,r,i.start+n,i.end+n);if(s<0){if(i.left===k){t.start-=n,t.end-=n,t.maxEnd-=n,i.left=t;break}i=i.left}else{if(i.right===k){t.start-=n+i.delta,t.end-=n+i.delta,t.maxEnd-=n+i.delta,i.right=t;break}n+=i.delta,i=i.right}}t.parent=i,t.left=k,t.right=k,C(t,1)}(e,t),H(t.parent);for(var n=t;n!==e.root&&1===b(n.parent);){var i;if(n.parent===n.parent.parent.left)1===b(i=n.parent.parent.right)?(C(n.parent,0),C(i,0),C(n.parent.parent,1),n=n.parent.parent):(n===n.parent.right&&W(e,n=n.parent),C(n.parent,0),C(n.parent.parent,1),j(e,n.parent.parent));else 1===b(i=n.parent.parent.left)?(C(n.parent,0),C(i,0),C(n.parent.parent,1),n=n.parent.parent):(n===n.parent.left&&j(e,n=n.parent),C(n.parent,0),C(n.parent.parent,1),W(e,n.parent.parent))}return C(e.root,0),t}function P(e,t){var n,i;if(t.left===k?(i=t,(n=t.right).delta+=t.delta,(n.delta<-1073741824||n.delta>1073741824)&&(e.requestNormalizeDelta=!0),n.start+=t.delta,n.end+=t.delta):t.right===k?(n=t.left,i=t):((n=(i=function(e){for(;e.left!==k;)e=e.left;return e}(t.right)).right).start+=i.delta,n.end+=i.delta,n.delta+=i.delta,(n.delta<-1073741824||n.delta>1073741824)&&(e.requestNormalizeDelta=!0),i.start+=t.delta,i.end+=t.delta,i.delta=t.delta,(i.delta<-1073741824||i.delta>1073741824)&&(e.requestNormalizeDelta=!0)),i===e.root)return e.root=n,C(n,0),t.detach(),F(),B(n),void(e.root.parent=k);var o,r=1===b(i);if(i===i.parent.left?i.parent.left=n:i.parent.right=n,i===t?n.parent=i.parent:(i.parent===t?n.parent=i:n.parent=i.parent,i.left=t.left,i.right=t.right,i.parent=t.parent,C(i,b(t)),t===e.root?e.root=i:t===t.parent.left?t.parent.left=i:t.parent.right=i,i.left!==k&&(i.left.parent=i),i.right!==k&&(i.right.parent=i)),t.detach(),r)return H(n.parent),i!==t&&(H(i),H(i.parent)),void F();for(H(n),H(n.parent),i!==t&&(H(i),H(i.parent));n!==e.root&&0===b(n);)n===n.parent.left?(1===b(o=n.parent.right)&&(C(o,0),C(n.parent,1),W(e,n.parent),o=n.parent.right),0===b(o.left)&&0===b(o.right)?(C(o,1),n=n.parent):(0===b(o.right)&&(C(o.left,0),C(o,1),j(e,o),o=n.parent.right),C(o,b(n.parent)),C(n.parent,0),C(o.right,0),W(e,n.parent),n=e.root)):(1===b(o=n.parent.left)&&(C(o,0),C(n.parent,1),j(e,n.parent),o=n.parent.left),0===b(o.left)&&0===b(o.right)?(C(o,1),n=n.parent):(0===b(o.left)&&(C(o.right,0),C(o,1),W(e,o),o=n.parent.left),C(o,b(n.parent)),C(n.parent,0),C(o.left,0),j(e,n.parent),n=e.root));C(n,0),F()}function F(){k.parent=k,k.delta=0,k.start=0,k.end=0}function W(e,t){var n=t.right;n.delta+=t.delta,(n.delta<-1073741824||n.delta>1073741824)&&(e.requestNormalizeDelta=!0),n.start+=t.delta,n.end+=t.delta,t.right=n.left,n.left!==k&&(n.left.parent=t),n.parent=t.parent,t.parent===k?e.root=n:t===t.parent.left?t.parent.left=n:t.parent.right=n,n.left=t,t.parent=n,B(t),B(n)}function j(e,t){var n=t.left;t.delta-=n.delta,(t.delta<-1073741824||t.delta>1073741824)&&(e.requestNormalizeDelta=!0),t.start-=n.delta,t.end-=n.delta,t.left=n.right,n.right!==k&&(n.right.parent=t),n.parent=t.parent,t.parent===k?e.root=n:t===t.parent.right?t.parent.right=n:t.parent.left=n,n.right=t,t.parent=n,B(t),B(n)}function V(e){var t=e.end;if(e.left!==k){var n=e.left.maxEnd;n>t&&(t=n)}if(e.right!==k){var i=e.right.maxEnd+e.delta;i>t&&(t=i)}return t}function B(e){e.maxEnd=V(e)}function H(e){for(;e!==k;){var t=V(e);if(e.maxEnd===t)return;e.maxEnd=t,e=e.parent}}function z(e,t,n,i){return e===n?t-i:e-n}var U=function(){function e(e,t){this.piece=e,this.color=t,this.size_left=0,this.lf_left=0,this.parent=this,this.left=this,this.right=this}return e.prototype.next=function(){if(this.right!==K)return q(this.right);for(var e=this;e.parent!==K&&e.parent.left!==e;)e=e.parent;return e.parent===K?K:e.parent},e.prototype.prev=function(){if(this.left!==K)return G(this.left);for(var e=this;e.parent!==K&&e.parent.right!==e;)e=e.parent;return e.parent===K?K:e.parent},e.prototype.detach=function(){this.parent=null,this.left=null,this.right=null},e}(),K=new U(null,0);function q(e){for(;e.left!==K;)e=e.left;return e}function G(e){for(;e.right!==K;)e=e.right;return e}function Z(e){return e===K?0:e.size_left+e.piece.length+Z(e.right)}function Y(e){return e===K?0:e.lf_left+e.piece.lineFeedCnt+Y(e.right)}function X(){K.parent=K}function J(e,t){var n=t.right;n.size_left+=t.size_left+(t.piece?t.piece.length:0),n.lf_left+=t.lf_left+(t.piece?t.piece.lineFeedCnt:0),t.right=n.left,n.left!==K&&(n.left.parent=t),n.parent=t.parent,t.parent===K?e.root=n:t.parent.left===t?t.parent.left=n:t.parent.right=n,n.left=t,t.parent=n}function Q(e,t){var n=t.left;t.left=n.right,n.right!==K&&(n.right.parent=t),n.parent=t.parent,t.size_left-=n.size_left+(n.piece?n.piece.length:0),t.lf_left-=n.lf_left+(n.piece?n.piece.lineFeedCnt:0),t.parent===K?e.root=n:t===t.parent.right?t.parent.right=n:t.parent.left=n,n.right=t,t.parent=n}function $(e,t){var n,i;if(n=t.left===K?(i=t).right:t.right===K?(i=t).left:(i=q(t.right)).right,i===e.root)return e.root=n,n.color=0,t.detach(),X(),void(e.root.parent=K);var o=1===i.color;if(i===i.parent.left?i.parent.left=n:i.parent.right=n,i===t?(n.parent=i.parent,ne(e,n)):(i.parent===t?n.parent=i:n.parent=i.parent,ne(e,n),i.left=t.left,i.right=t.right,i.parent=t.parent,i.color=t.color,t===e.root?e.root=i:t===t.parent.left?t.parent.left=i:t.parent.right=i,i.left!==K&&(i.left.parent=i),i.right!==K&&(i.right.parent=i),i.size_left=t.size_left,i.lf_left=t.lf_left,ne(e,i)),t.detach(),n.parent.left===n){var r=Z(n),s=Y(n);if(r!==n.parent.size_left||s!==n.parent.lf_left){var a=r-n.parent.size_left,u=s-n.parent.lf_left;n.parent.size_left=r,n.parent.lf_left=s,te(e,n.parent,a,u)}}if(ne(e,n.parent),o)X();else{for(var l;n!==e.root&&0===n.color;)n===n.parent.left?(1===(l=n.parent.right).color&&(l.color=0,n.parent.color=1,J(e,n.parent),l=n.parent.right),0===l.left.color&&0===l.right.color?(l.color=1,n=n.parent):(0===l.right.color&&(l.left.color=0,l.color=1,Q(e,l),l=n.parent.right),l.color=n.parent.color,n.parent.color=0,l.right.color=0,J(e,n.parent),n=e.root)):(1===(l=n.parent.left).color&&(l.color=0,n.parent.color=1,Q(e,n.parent),l=n.parent.left),0===l.left.color&&0===l.right.color?(l.color=1,n=n.parent):(0===l.left.color&&(l.right.color=0,l.color=1,J(e,l),l=n.parent.left),l.color=n.parent.color,n.parent.color=0,l.left.color=0,Q(e,n.parent),n=e.root));n.color=0,X()}}function ee(e,t){for(ne(e,t);t!==e.root&&1===t.parent.color;){var n;if(t.parent===t.parent.parent.left)1===(n=t.parent.parent.right).color?(t.parent.color=0,n.color=0,t.parent.parent.color=1,t=t.parent.parent):(t===t.parent.right&&J(e,t=t.parent),t.parent.color=0,t.parent.parent.color=1,Q(e,t.parent.parent));else 1===(n=t.parent.parent.left).color?(t.parent.color=0,n.color=0,t.parent.parent.color=1,t=t.parent.parent):(t===t.parent.left&&Q(e,t=t.parent),t.parent.color=0,t.parent.parent.color=1,J(e,t.parent.parent))}e.root.color=0}function te(e,t,n,i){for(;t!==e.root&&t!==K;)t.parent.left===t&&(t.parent.size_left+=n,t.parent.lf_left+=i),t=t.parent}function ne(e,t){var n=0,i=0;if(t!==e.root){if(0===n){for(;t!==e.root&&t===t.parent.right;)t=t.parent;if(t===e.root)return;n=Z((t=t.parent).left)-t.size_left,i=Y(t.left)-t.lf_left,t.size_left+=n,t.lf_left+=i}for(;t!==e.root&&(0!==n||0!==i);)t.parent.left===t&&(t.parent.size_left+=n,t.parent.lf_left+=i),t=t.parent}}K.parent=K,K.left=K,K.right=K,K.color=0;var ie=n("IErJ");function oe(e){var t;return(t=e[e.length-1]<65536?new Uint16Array(e.length):new Uint32Array(e.length)).set(e,0),t}var re=function(){return function(e,t,n,i,o){this.lineStarts=e,this.cr=t,this.lf=n,this.crlf=i,this.isBasicASCII=o}}();function se(e,t){void 0===t&&(t=!0);for(var n=[0],i=1,o=0,r=e.length;o=0;t--){var n=this._cache[t];if(n.nodeStartOffset<=e&&n.nodeStartOffset+n.node.piece.length>=e)return n}return null},e.prototype.get2=function(e){for(var t=this._cache.length-1;t>=0;t--){var n=this._cache[t];if(n.nodeStartLineNumber&&n.nodeStartLineNumber=e)return n}return null},e.prototype.set=function(e){this._cache.length>=this._limit&&this._cache.shift(),this._cache.push(e)},e.prototype.valdiate=function(e){for(var t=!1,n=this._cache,i=0;i=e)&&(n[i]=null,t=!0)}if(t){for(var r=[],s=0,a=n;s0){e[o].lineStarts||(e[o].lineStarts=se(e[o].buffer));var s=new ae(o+1,{line:0,column:0},{line:e[o].lineStarts.length-1,column:e[o].buffer.length-e[o].lineStarts[e[o].lineStarts.length-1]},e[o].lineStarts.length-1,e[o].buffer.length);this._buffers.push(e[o]),i=this.rbInsertRight(i,s)}this._searchCache=new le(1),this._lastVisitedLine={lineNumber:0,value:""},this.computeBufferMetadata()},e.prototype.normalizeEOL=function(e){var t=this,n=65535-Math.floor(21845),i=2*n,o="",r=0,s=[];if(this.iterate(this.root,function(a){var u=t.getNodeContent(a),l=u.length;if(r<=n||r+l0){var a=o.replace(/\r\n|\r|\n/g,e);s.push(new ue(a,se(a)))}this.create(s,e,!0)},e.prototype.getEOL=function(){return this._EOL},e.prototype.setEOL=function(e){this._EOL=e,this._EOLLength=this._EOL.length,this.normalizeEOL(e)},e.prototype.getOffsetAt=function(e,t){for(var n=0,i=this.root;i!==K;)if(i.left!==K&&i.lf_left+1>=e)i=i.left;else{if(i.lf_left+i.piece.lineFeedCnt+1>=e)return(n+=i.size_left)+(this.getAccumulatedValue(i,e-i.lf_left-2)+t-1);e-=i.lf_left+i.piece.lineFeedCnt,n+=i.size_left+i.piece.length,i=i.right}return n},e.prototype.getPositionAt=function(e){e=Math.floor(e),e=Math.max(0,e);for(var t=this.root,n=0,i=e;t!==K;)if(0!==t.size_left&&t.size_left>=e)t=t.left;else{if(t.size_left+t.piece.length>=e){var o=this.getIndexOf(t,e-t.size_left);if(n+=t.lf_left+o.index,0===o.index){var r=i-this.getOffsetAt(n+1,1);return new l.a(n+1,r+1)}return new l.a(n+1,o.remainder+1)}if(e-=t.size_left+t.piece.length,n+=t.lf_left+t.piece.lineFeedCnt,t.right===K){r=i-e-this.getOffsetAt(n+1,1);return new l.a(n+1,r+1)}t=t.right}return new l.a(1,1)},e.prototype.getValueInRange=function(e,t){if(e.startLineNumber===e.endLineNumber&&e.startColumn===e.endColumn)return"";var n=this.nodeAt2(e.startLineNumber,e.startColumn),i=this.nodeAt2(e.endLineNumber,e.endColumn),o=this.getValueInRange2(n,i);return t?t===this._EOL&&this._EOLNormalized&&t===this.getEOL()&&this._EOLNormalized?o:o.replace(/\r\n|\r|\n/g,t):o},e.prototype.getValueInRange2=function(e,t){if(e.node===t.node){var n=e.node,i=this._buffers[n.piece.bufferIndex].buffer,o=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);return i.substring(o+e.remainder,o+t.remainder)}var r=e.node,s=this._buffers[r.piece.bufferIndex].buffer,a=this.offsetInBuffer(r.piece.bufferIndex,r.piece.start),u=s.substring(a+e.remainder,a+r.piece.length);for(r=r.next();r!==K;){var l=this._buffers[r.piece.bufferIndex].buffer,c=this.offsetInBuffer(r.piece.bufferIndex,r.piece.start);if(r===t.node){u+=l.substring(c,c+t.remainder);break}u+=l.substr(c,r.piece.length),r=r.next()}return u},e.prototype.getLinesContent=function(){return this.getContentOfSubTree(this.root).split(/\r\n|\r|\n/)},e.prototype.getLength=function(){return this._length},e.prototype.getLineCount=function(){return this._lineCnt},e.prototype.getLineContent=function(e){return this._lastVisitedLine.lineNumber===e?this._lastVisitedLine.value:(this._lastVisitedLine.lineNumber=e,e===this._lineCnt?this._lastVisitedLine.value=this.getLineRawContent(e):this._EOLNormalized?this._lastVisitedLine.value=this.getLineRawContent(e,this._EOLLength):this._lastVisitedLine.value=this.getLineRawContent(e).replace(/(\r\n|\r|\n)$/,""),this._lastVisitedLine.value)},e.prototype.getLineCharCode=function(e,t){var n=this.nodeAt2(e,t+1);if(n.remainder===n.node.piece.length){var i=n.node.next();if(!i)return 0;var o=this._buffers[i.piece.bufferIndex],r=this.offsetInBuffer(i.piece.bufferIndex,i.piece.start);return o.buffer.charCodeAt(r)}o=this._buffers[n.node.piece.bufferIndex];var s=(r=this.offsetInBuffer(n.node.piece.bufferIndex,n.node.piece.start))+n.remainder;return o.buffer.charCodeAt(s)},e.prototype.getLineLength=function(e){if(e===this.getLineCount()){var t=this.getOffsetAt(e,1);return this.getLength()-t}return this.getOffsetAt(e+1,1)-this.getOffsetAt(e,1)-this._EOLLength},e.prototype.findMatchesInNode=function(e,t,n,i,o,r,s,a,u,l,d){var h,p=this._buffers[e.piece.bufferIndex],f=this.offsetInBuffer(e.piece.bufferIndex,e.piece.start),g=this.offsetInBuffer(e.piece.bufferIndex,o),m=this.offsetInBuffer(e.piece.bufferIndex,r);t.reset(g);var _={line:0,column:0};do{if(h=t.next(p.buffer)){if(h.index>=m)return l;this.positionInBuffer(e,h.index-f,_);var v=this.getLineFeedCnt(e.piece.bufferIndex,o,_),y=_.line===o.line?_.column-o.column+i:_.column+1,b=y+h[0].length;if(d[l++]=Object(ie.d)(new c.a(n+v,y,n+v,b),h,a),h.index+h[0].length>=m)return l;if(l>=u)return l}}while(h);return l},e.prototype.findMatchesLineByLine=function(e,t,n,i){var o=[],r=0,s=new ie.b(t.wordSeparators,t.regex),a=this.nodeAt2(e.startLineNumber,e.startColumn);if(null===a)return[];var u=this.nodeAt2(e.endLineNumber,e.endColumn);if(null===u)return[];var l=this.positionInBuffer(a.node,a.remainder),c=this.positionInBuffer(u.node,u.remainder);if(a.node===u.node)return this.findMatchesInNode(a.node,s,e.startLineNumber,e.startColumn,l,c,t,n,i,r,o),o;for(var d=e.startLineNumber,h=a.node;h!==u.node;){var p=this.getLineFeedCnt(h.piece.bufferIndex,l,h.piece.end);if(p>=1){var f=this._buffers[h.piece.bufferIndex].lineStarts,g=this.offsetInBuffer(h.piece.bufferIndex,h.piece.start),m=f[l.line+p],_=d===e.startLineNumber?e.startColumn:1;if((r=this.findMatchesInNode(h,s,d,_,l,this.positionInBuffer(h,m-g),t,n,i,r,o))>=i)return o;d+=p}var v=d===e.startLineNumber?e.startColumn-1:0;if(d===e.endLineNumber){var y=this.getLineContent(d).substring(v,e.endColumn-1);return r=this._findMatchesInLine(t,s,y,e.endLineNumber,v,r,o,n,i),o}if((r=this._findMatchesInLine(t,s,this.getLineContent(d).substr(v),d,v,r,o,n,i))>=i)return o;d++,h=(a=this.nodeAt2(d,1)).node,l=this.positionInBuffer(a.node,a.remainder)}if(d===e.endLineNumber){var b=d===e.startLineNumber?e.startColumn-1:0;y=this.getLineContent(d).substring(b,e.endColumn-1);return r=this._findMatchesInLine(t,s,y,e.endLineNumber,b,r,o,n,i),o}var C=d===e.startLineNumber?e.startColumn:1;return r=this.findMatchesInNode(u.node,s,d,C,l,c,t,n,i,r,o),o},e.prototype._findMatchesInLine=function(e,t,n,i,o,r,s,a,u){var l,d=e.wordSeparators;if(!a&&e.simpleSearch){for(var p=e.simpleSearch,f=p.length,g=n.length,m=-f;-1!==(m=n.indexOf(p,m+f));)if((!d||Object(ie.e)(d,n,g,m,f))&&(s[r++]=new h.b(new c.a(i,m+1+o,i,m+1+f+o),null),r>=u))return r;return r}t.reset(0);do{if((l=t.next(n))&&(s[r++]=Object(ie.d)(new c.a(i,l.index+1+o,i,l.index+1+l[0].length+o),l,a),r>=u))return r}while(l);return r},e.prototype.insert=function(e,t,n){if(void 0===n&&(n=!1),this._EOLNormalized=this._EOLNormalized&&n,this._lastVisitedLine.lineNumber=0,this._lastVisitedLine.value="",this.root!==K){var i=this.nodeAt(e),o=i.node,r=i.remainder,s=i.nodeStartOffset,a=o.piece,u=a.bufferIndex,l=this.positionInBuffer(o,r);if(0===o.piece.bufferIndex&&a.end.line===this._lastChangeBufferPos.line&&a.end.column===this._lastChangeBufferPos.column&&s+a.length===e&&t.length<65535)return this.appendToNode(o,t),void this.computeBufferMetadata();if(s===e)this.insertContentToNodeLeft(t,o),this._searchCache.valdiate(e);else if(s+o.piece.length>e){var c=[],d=new ae(a.bufferIndex,l,a.end,this.getLineFeedCnt(a.bufferIndex,l,a.end),this.offsetInBuffer(u,a.end)-this.offsetInBuffer(u,l));if(this.shouldCheckCRLF()&&this.endWithCR(t))if(10===this.nodeCharCodeAt(o,r)){var h={line:d.start.line+1,column:0};d=new ae(d.bufferIndex,h,d.end,this.getLineFeedCnt(d.bufferIndex,h,d.end),d.length-1),t+="\n"}if(this.shouldCheckCRLF()&&this.startWithLF(t))if(13===this.nodeCharCodeAt(o,r-1)){var p=this.positionInBuffer(o,r-1);this.deleteNodeTail(o,p),t="\r"+t,0===o.piece.length&&c.push(o)}else this.deleteNodeTail(o,l);else this.deleteNodeTail(o,l);var f=this.createNewPieces(t);d.length>0&&this.rbInsertRight(o,d);for(var g=o,m=0;m=0;u--)a=this.rbInsertLeft(a,s[u]);this.validateCRLFWithPrevNode(a),this.deleteNodes(n)},e.prototype.insertContentToNodeRight=function(e,t){this.adjustCarriageReturnFromNext(e,t)&&(e+="\n");for(var n=this.createNewPieces(e),i=this.rbInsertRight(t,n[0]),o=i,r=1;r=c))break;a=l+1}return n?(n.line=l,n.column=s-d,null):{line:l,column:s-d}},e.prototype.getLineFeedCnt=function(e,t,n){if(0===n.column)return n.line-t.line;var i=this._buffers[e].lineStarts;if(n.line===i.length-1)return n.line-t.line;var o=i[n.line+1],r=i[n.line]+n.column;if(o>r+1)return n.line-t.line;var s=r-1;return 13===this._buffers[e].buffer.charCodeAt(s)?n.line-t.line+1:n.line-t.line},e.prototype.offsetInBuffer=function(e,t){return this._buffers[e].lineStarts[t.line]+t.column},e.prototype.deleteNodes=function(e){for(var t=0;t65535){for(var t=[];e.length>65535;){var n=e.charCodeAt(65534),i=void 0;13===n||n>=55296&&n<=56319?(i=e.substring(0,65534),e=e.substring(65534)):(i=e.substring(0,65535),e=e.substring(65535));var o=se(i);t.push(new ae(this._buffers.length,{line:0,column:0},{line:o.length-1,column:i.length-o[o.length-1]},o.length-1,i.length)),this._buffers.push(new ue(i,o))}var r=se(e);return t.push(new ae(this._buffers.length,{line:0,column:0},{line:r.length-1,column:e.length-r[r.length-1]},r.length-1,e.length)),this._buffers.push(new ue(e,r)),t}var s=this._buffers[0].buffer.length,a=se(e,!1),u=this._lastChangeBufferPos;if(this._buffers[0].lineStarts[this._buffers[0].lineStarts.length-1]===s&&0!==s&&this.startWithLF(e)&&this.endWithCR(this._buffers[0].buffer)){this._lastChangeBufferPos={line:this._lastChangeBufferPos.line,column:this._lastChangeBufferPos.column+1},u=this._lastChangeBufferPos;for(var l=0;l=e-1)n=n.left;else{if(n.lf_left+n.piece.lineFeedCnt>e-1){r=this.getAccumulatedValue(n,e-n.lf_left-2),u=this.getAccumulatedValue(n,e-n.lf_left-1),s=this._buffers[n.piece.bufferIndex].buffer,a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);return l+=n.size_left,this._searchCache.set({node:n,nodeStartOffset:l,nodeStartLineNumber:c-(e-1-n.lf_left)}),s.substring(a+r,a+u-t)}if(n.lf_left+n.piece.lineFeedCnt===e-1){r=this.getAccumulatedValue(n,e-n.lf_left-2),s=this._buffers[n.piece.bufferIndex].buffer,a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);i=s.substring(a+r,a+n.piece.length);break}e-=n.lf_left+n.piece.lineFeedCnt,l+=n.size_left+n.piece.length,n=n.right}for(n=n.next();n!==K;){s=this._buffers[n.piece.bufferIndex].buffer;if(n.piece.lineFeedCnt>0){u=this.getAccumulatedValue(n,0),a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);return i+=s.substring(a,a+u-t)}a=this.offsetInBuffer(n.piece.bufferIndex,n.piece.start);i+=s.substr(a,n.piece.length),n=n.next()}return i},e.prototype.computeBufferMetadata=function(){for(var e=this.root,t=1,n=0;e!==K;)t+=e.lf_left+e.piece.lineFeedCnt,n+=e.size_left+e.piece.length,e=e.right;this._lineCnt=t,this._length=n,this._searchCache.valdiate(this._length)},e.prototype.getIndexOf=function(e,t){var n=e.piece,i=this.positionInBuffer(e,t),o=i.line-n.start.line;if(this.offsetInBuffer(n.bufferIndex,n.end)-this.offsetInBuffer(n.bufferIndex,n.start)===t){var r=this.getLineFeedCnt(e.piece.bufferIndex,n.start,i);if(r!==o)return{index:r,remainder:0}}return{index:o,remainder:i.column}},e.prototype.getAccumulatedValue=function(e,t){if(t<0)return 0;var n=e.piece,i=this._buffers[n.bufferIndex].lineStarts,o=n.start.line+t+1;return o>n.end.line?i[n.end.line]+n.end.column-i[n.start.line]-n.start.column:i[o]-i[n.start.line]-n.start.column},e.prototype.deleteNodeTail=function(e,t){var n=e.piece,i=n.lineFeedCnt,o=this.offsetInBuffer(n.bufferIndex,n.end),r=t,s=this.offsetInBuffer(n.bufferIndex,r),a=this.getLineFeedCnt(n.bufferIndex,n.start,r),u=a-i,l=s-o,c=n.length+l;e.piece=new ae(n.bufferIndex,n.start,r,a,c),te(this,e,l,u)},e.prototype.deleteNodeHead=function(e,t){var n=e.piece,i=n.lineFeedCnt,o=this.offsetInBuffer(n.bufferIndex,n.start),r=t,s=this.getLineFeedCnt(n.bufferIndex,r,n.end),a=s-i,u=o-this.offsetInBuffer(n.bufferIndex,r),l=n.length+u;e.piece=new ae(n.bufferIndex,r,n.end,s,l),te(this,e,u,a)},e.prototype.shrinkNode=function(e,t,n){var i=e.piece,o=i.start,r=i.end,s=i.length,a=i.lineFeedCnt,u=t,l=this.getLineFeedCnt(i.bufferIndex,i.start,u),c=this.offsetInBuffer(i.bufferIndex,t)-this.offsetInBuffer(i.bufferIndex,o);e.piece=new ae(i.bufferIndex,i.start,u,l,c),te(this,e,c-s,l-a);var d=new ae(i.bufferIndex,n,r,this.getLineFeedCnt(i.bufferIndex,n,r),this.offsetInBuffer(i.bufferIndex,r)-this.offsetInBuffer(i.bufferIndex,n)),h=this.rbInsertRight(e,d);this.validateCRLFWithPrevNode(h)},e.prototype.appendToNode=function(e,t){this.adjustCarriageReturnFromNext(t,e)&&(t+="\n");var n=this.shouldCheckCRLF()&&this.startWithLF(t)&&this.endWithCR(e),i=this._buffers[0].buffer.length;this._buffers[0].buffer+=t;for(var o=se(t,!1),r=0;re)t=t.left;else{if(t.size_left+t.piece.length>=e){i+=t.size_left;var o={node:t,remainder:e-t.size_left,nodeStartOffset:i};return this._searchCache.set(o),o}e-=t.size_left+t.piece.length,i+=t.size_left+t.piece.length,t=t.right}return null},e.prototype.nodeAt2=function(e,t){for(var n=this.root,i=0;n!==K;)if(n.left!==K&&n.lf_left>=e-1)n=n.left;else{if(n.lf_left+n.piece.lineFeedCnt>e-1){var o=this.getAccumulatedValue(n,e-n.lf_left-2),r=this.getAccumulatedValue(n,e-n.lf_left-1);return i+=n.size_left,{node:n,remainder:Math.min(o+t-1,r),nodeStartOffset:i}}if(n.lf_left+n.piece.lineFeedCnt===e-1){if((o=this.getAccumulatedValue(n,e-n.lf_left-2))+t-1<=n.piece.length)return{node:n,remainder:o+t-1,nodeStartOffset:i};t-=n.piece.length-o;break}e-=n.lf_left+n.piece.lineFeedCnt,i+=n.size_left+n.piece.length,n=n.right}for(n=n.next();n!==K;){if(n.piece.lineFeedCnt>0){r=this.getAccumulatedValue(n,0);var s=this.offsetOfNode(n);return{node:n,remainder:Math.min(t-1,r),nodeStartOffset:s}}if(n.piece.length>=t-1)return{node:n,remainder:t-1,nodeStartOffset:this.offsetOfNode(n)};t-=n.piece.length,n=n.next()}return null},e.prototype.nodeCharCodeAt=function(e,t){if(e.piece.lineFeedCnt<1)return-1;var n=this._buffers[e.piece.bufferIndex],i=this.offsetInBuffer(e.piece.bufferIndex,e.piece.start)+t;return n.buffer.charCodeAt(i)},e.prototype.offsetOfNode=function(e){if(!e)return 0;for(var t=e.size_left;e!==this.root;)e.parent.right===e&&(t+=e.parent.size_left+e.parent.piece.length),e=e.parent;return t},e.prototype.shouldCheckCRLF=function(){return!(this._EOLNormalized&&"\n"===this._EOL)},e.prototype.startWithLF=function(e){if("string"==typeof e)return 10===e.charCodeAt(0);if(e===K||0===e.piece.lineFeedCnt)return!1;var t=e.piece,n=this._buffers[t.bufferIndex].lineStarts,i=t.start.line,o=n[i]+t.start.column;return i!==n.length-1&&(!(n[i+1]>o+1)&&10===this._buffers[t.bufferIndex].buffer.charCodeAt(o))},e.prototype.endWithCR=function(e){return"string"==typeof e?13===e.charCodeAt(e.length-1):e!==K&&0!==e.piece.lineFeedCnt&&13===this.nodeCharCodeAt(e,e.piece.length-1)},e.prototype.validateCRLFWithPrevNode=function(e){if(this.shouldCheckCRLF()&&this.startWithLF(e)){var t=e.prev();this.endWithCR(t)&&this.fixCRLF(t,e)}},e.prototype.validateCRLFWithNextNode=function(e){if(this.shouldCheckCRLF()&&this.endWithCR(e)){var t=e.next();this.startWithLF(t)&&this.fixCRLF(e,t)}},e.prototype.fixCRLF=function(e,t){var n,i=[],o=this._buffers[e.piece.bufferIndex].lineStarts;n=0===e.piece.end.column?{line:e.piece.end.line-1,column:o[e.piece.end.line]-o[e.piece.end.line-1]-1}:{line:e.piece.end.line,column:e.piece.end.column-1};var r=e.piece.length-1,s=e.piece.lineFeedCnt-1;e.piece=new ae(e.piece.bufferIndex,e.piece.start,n,s,r),te(this,e,-1,-1),0===e.piece.length&&i.push(e);var a={line:t.piece.start.line+1,column:0},u=t.piece.length-1,l=this.getLineFeedCnt(t.piece.bufferIndex,a,t.piece.end);t.piece=new ae(t.piece.bufferIndex,a,t.piece.end,l,u),te(this,t,-1,-1),0===t.piece.length&&i.push(t);var c=this.createNewPieces("\r\n");this.rbInsertRight(e,c[0]);for(var d=0;d0){_.sort(function(e,t){return t.lineNumber-e.lineNumber}),S=[];u=0;for(var L=_.length;u0&&_[u-1].lineNumber===y)){var O=_[u].oldContent,E=this.getLineContent(y);0!==E.length&&E!==O&&-1===s.q(E)&&S.push(y)}}}return new h.a(C,w,S)},e.prototype._reduceOperations=function(e){return e.length<1e3?e:[this._toSingleEditOperation(e)]},e.prototype._toSingleEditOperation=function(e){for(var t=!1,n=e[0].range,i=e[e.length-1].range,o=new c.a(n.startLineNumber,n.startColumn,i.endLineNumber,i.endColumn),r=n.startLineNumber,s=n.startColumn,a=[],u=0,l=e.length;u0){var h=a.lines.length,p=a.lines[0],f=a.lines[h-1];d=1===h?new c.a(u,l,u,l+p.length):new c.a(u,l,u+h-1,f.length+1)}else d=new c.a(u,l,u,l);n=d.endLineNumber,i=d.endColumn,t.push(d),o=a}return t},e._sortOpsAscending=function(e,t){var n=c.a.compareRangesUsingEnds(e.range,t.range);return 0===n?e.sortIndex-t.sortIndex:n},e._sortOpsDescending=function(e,t){var n=c.a.compareRangesUsingEnds(e.range,t.range);return 0===n?t.sortIndex-e.sortIndex:-n},e}(),he=function(){function e(e,t,n,i,o,r,s,a){this._chunks=e,this._bom=t,this._cr=n,this._lf=i,this._crlf=o,this._containsRTL=r,this._isBasicASCII=s,this._normalizeEOL=a}return e.prototype._getEOL=function(e){var t=this._cr+this._lf+this._crlf,n=this._cr+this._crlf;return 0===t?1===e?"\n":"\r\n":n>t/2?"\r\n":"\n"},e.prototype.create=function(e){var t=this._getEOL(e),n=this._chunks;if(this._normalizeEOL&&("\r\n"===t&&(this._cr>0||this._lf>0)||"\n"===t&&(this._cr>0||this._crlf>0)))for(var i=0,o=n.length;i=55296&&t<=56319?(this._acceptChunk1(e.substr(0,e.length-1),!1),this._hasPreviousChar=!0,this._previousChar=t):(this._acceptChunk1(e,!1),this._hasPreviousChar=!1,this._previousChar=t)}},e.prototype._acceptChunk1=function(e,t){(t||0!==e.length)&&(this._hasPreviousChar?this._acceptChunk2(String.fromCharCode(this._previousChar)+e):this._acceptChunk2(e))},e.prototype._acceptChunk2=function(e){var t=function(e,t){e.length=0,e[0]=0;for(var n=1,i=0,o=0,r=0,s=!0,a=0,u=t.length;a126)&&(s=!1)}var c=new re(oe(e),i,o,r,s);return e.length=0,c}(this._tmpLineStarts,e);this.chunks.push(new ue(e,t.lineStarts)),this.cr+=t.cr,this.lf+=t.lf,this.crlf+=t.crlf,this.isBasicASCII&&(this.isBasicASCII=t.isBasicASCII),this.isBasicASCII||this.containsRTL||(this.containsRTL=s.h(e))},e.prototype.finish=function(e){return void 0===e&&(e=!0),this._finish(),new he(this.chunks,this.BOM,this.cr,this.lf,this.crlf,this.containsRTL,this.isBasicASCII,e)},e.prototype._finish=function(){if(0===this.chunks.length&&this._acceptChunk1("",!0),this._hasPreviousChar){this._hasPreviousChar=!1;var e=this.chunks[this.chunks.length-1];e.buffer+=String.fromCharCode(this._previousChar);var t=se(e.buffer);e.lineStarts=t,13===this._previousChar&&this.cr++}},e}(),fe=function(){return function(){this.changeType=1}}(),ge=function(){return function(e,t){this.changeType=2,this.lineNumber=e,this.detail=t}}(),me=function(){return function(e,t){this.changeType=3,this.fromLineNumber=e,this.toLineNumber=t}}(),_e=function(){return function(e,t,n){this.changeType=4,this.fromLineNumber=e,this.toLineNumber=t,this.detail=n}}(),ve=function(){return function(){this.changeType=5}}(),ye=function(){function e(e,t,n,i){this.changes=e,this.versionId=t,this.isUndoing=n,this.isRedoing=i}return e.prototype.containsEvent=function(e){for(var t=0,n=this.changes.length;t>>0}var xe=new Uint32Array(0).buffer,Ie=function(){function e(){this.tokens=[]}return e.prototype.add=function(e,t){if(this.tokens.length>0){var n=this.tokens[this.tokens.length-1];if(n.startLineNumber+n.tokens.length-1+1===e)return void n.tokens.push(t)}this.tokens.push(new De(e,[t]))},e}(),De=function(){return function(e,t){this.startLineNumber=e,this.tokens=t}}();function ke(e){return e instanceof Uint32Array?e:new Uint32Array(e)}var Te,Me=function(){function e(){this._lineTokens=[],this._len=0}return e.prototype.flush=function(){this._lineTokens=[],this._len=0},e.prototype.getTokens=function(e,t,n){var i=null;if(t1&&(o=Se.x.getLanguageId(i[1])!==e),!o)return xe}if(!i||0===i.length){var r=new Uint32Array(2);return r[0]=t,r[1]=Ne(e),r.buffer}return i[i.length-2]=t,0===i.byteOffset&&i.byteLength===i.buffer.byteLength?i.buffer:i},e.prototype._ensureLine=function(e){for(;e>=this._len;)this._lineTokens[this._len]=null,this._len++},e.prototype._deleteLines=function(e,t){0!==t&&(e+t>this._len&&(t=this._len-e),this._lineTokens.splice(e,t),this._len-=t)},e.prototype._insertLines=function(e,t){if(0!==t){for(var n=[],i=0;i=this._len))if(t.startLineNumber!==t.endLineNumber){this._lineTokens[n]=e._deleteEnding(this._lineTokens[n],t.startColumn-1);var i=t.endLineNumber-1,o=null;i=this._len||(0!==n?(this._lineTokens[o]=e._deleteEnding(this._lineTokens[o],t.column-1),this._lineTokens[o]=e._insert(this._lineTokens[o],t.column-1,i),this._insertLines(t.lineNumber,n)):this._lineTokens[o]=e._insert(this._lineTokens[o],t.column-1,i))}},e._deleteBeginning=function(t,n){return null===t||t===xe?t:e._delete(t,0,n)},e._deleteEnding=function(t,n){if(null===t||t===xe)return t;var i=ke(t),o=i[i.length-2];return e._delete(t,n,o)},e._delete=function(e,t,n){if(null===e||e===xe||t===n)return e;var i=ke(e),o=i.length>>>1;if(0===t&&i[i.length-2]===n)return xe;var r,s,a=we.a.findIndexInTokensArray(i,t),u=a>0?i[a-1<<1]:0;if(ns&&(i[r++]=p,i[r++]=i[1+(h<<1)],s=p)}if(r===i.length)return e;var f=new Uint32Array(r);return f.set(i.subarray(0,r),0),f.buffer},e._append=function(e,t){if(t===xe)return e;if(e===xe)return t;if(null===e)return e;if(null===t)return null;var n=ke(e),i=ke(t),o=i.length>>>1,r=new Uint32Array(n.length+i.length);r.set(n,0);for(var s=n.length,a=n[n.length-2],u=0;u>>1,r=we.a.findIndexInTokensArray(i,t);r>0&&(i[r-1<<1]===t&&r--);for(var s=r;s=this._len;)this._beginState[this._len]=null,this._valid[this._len]=!1,this._len++},e.prototype._deleteLines=function(e,t){0!==t&&(e+t>this._len&&(t=this._len-e),this._beginState.splice(e,t),this._valid.splice(e,t),this._len-=t)},e.prototype._insertLines=function(e,t){if(0!==t){for(var n=[],i=[],o=0;o=0;o--)this._invalidateLine(e.startLineNumber+o-1);this._acceptDeleteRange(e),this._acceptInsertText(new l.a(e.startLineNumber,e.startColumn),t)},e.prototype._acceptDeleteRange=function(e){e.startLineNumber-1>=this._len||this._deleteLines(e.startLineNumber,e.endLineNumber-e.startLineNumber)},e.prototype._acceptInsertText=function(e,t){e.lineNumber-1>=this._len||this._insertLines(e.lineNumber,t)},e}(),Pe=function(e){function t(t){var n=e.call(this)||this;return n._textModel=t,n._tokenizationStateStore=new Ae,n._revalidateTokensTimeout=-1,n._tokenizationSupport=null,n._register(Se.y.onDidChange(function(e){var t=n._textModel.getLanguageIdentifier();-1!==e.changedLanguages.indexOf(t.language)&&(n._resetTokenizationState(),n._textModel.clearTokens())})),n._register(n._textModel.onDidChangeRawContentFast(function(e){e.containsEvent(1)&&n._resetTokenizationState()})),n._register(n._textModel.onDidChangeContentFast(function(e){for(var t=0,i=e.changes.length;t20);){if(this._tokenizeOneInvalidLine(t)>=e)break}this._beginBackgroundTokenization(),this._textModel.setTokens(t.tokens)},t.prototype.tokenizeViewport=function(e,t){var n=new Ie;this._tokenizeViewport(n,e,t),this._textModel.setTokens(n.tokens)},t.prototype.reset=function(){this._resetTokenizationState(),this._textModel.clearTokens()},t.prototype.forceTokenization=function(e){var t=new Ie;this._updateTokensUntilLine(t,e),this._textModel.setTokens(t.tokens)},t.prototype.isCheapToTokenize=function(e){if(!this._tokenizationSupport)return!0;var t=this._tokenizationStateStore.invalidLineStartIndex+1;return!(e>t)&&(e0&&s>=1;s--){var a=this._textModel.getLineFirstNonWhitespaceColumn(s);if(0!==a&&a=0;s--){l=(h=Fe(u,this._tokenizationSupport,o[s],l)).endState}for(var c=t;c<=n;c++){var d=this._textModel.getLineContent(c),h=Fe(u,this._tokenizationSupport,d,l);e.add(c,h.tokens),this._tokenizationStateStore.setFakeTokens(c-1),l=h.endState}}},t}(r.a);function Fe(e,t,n,o){var r=null;if(t)try{r=t.tokenize2(n,o.clone(),0)}catch(e){Object(i.e)(e)}return r||(r=Object(Le.e)(e.id,n,o,0)),we.a.convertToEndOffset(r.tokens,n.length),r}var We=n("+jct"),je=n("Fllr"),Ve=n("Eeyw"),Be=n("iNUG"),He=n("KIxu"),ze=n("TNPA");n.d(t,"b",function(){return Ye}),n.d(t,"a",function(){return tt});var Ue=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}();function Ke(e){var t=new pe;return t.acceptChunk(e),t.finish()}function qe(e,t){return("string"==typeof e?Ke(e):e).create(t)}var Ge=0,Ze=function(){throw new Error("Invalid change accessor")},Ye=function(e){function t(n,i,r,u){void 0===u&&(u=null);var l=e.call(this)||this;l._onWillDispose=l._register(new o.a),l.onWillDispose=l._onWillDispose.event,l._onDidChangeDecorations=l._register(new ot),l.onDidChangeDecorations=l._onDidChangeDecorations.event,l._onDidChangeLanguage=l._register(new o.a),l.onDidChangeLanguage=l._onDidChangeLanguage.event,l._onDidChangeLanguageConfiguration=l._register(new o.a),l.onDidChangeLanguageConfiguration=l._onDidChangeLanguageConfiguration.event,l._onDidChangeTokens=l._register(new o.a),l.onDidChangeTokens=l._onDidChangeTokens.event,l._onDidChangeOptions=l._register(new o.a),l.onDidChangeOptions=l._onDidChangeOptions.event,l._onDidChangeAttached=l._register(new o.a),l.onDidChangeAttached=l._onDidChangeAttached.event,l._eventEmitter=l._register(new rt),Ge++,l.id="$model"+Ge,l.isForSimpleWidget=i.isForSimpleWidget,l._associatedResource=void 0===u||null===u?a.a.parse("inmemory://model/"+Ge):u,l._attachedEditorCount=0,l._buffer=qe(n,i.defaultEOL),l._options=t.resolveOptions(l._buffer,i);var d=l._buffer.getLineCount(),h=l._buffer.getValueLengthInRange(new c.a(1,1,d,l._buffer.getLineLength(d)+1),0);return i.largeFileOptimizations?l._isTooLargeForTokenization=h>t.LARGE_FILE_SIZE_THRESHOLD||d>t.LARGE_FILE_LINE_COUNT_THRESHOLD:l._isTooLargeForTokenization=!1,l._isTooLargeForSyncing=h>t.MODEL_SYNC_LIMIT,l._versionId=1,l._alternativeVersionId=1,l._isDisposed=!1,l._isDisposing=!1,l._languageIdentifier=r||Le.a,l._languageRegistryListener=je.a.onDidChange(function(e){e.languageIdentifier.id===l._languageIdentifier.id&&l._onDidChangeLanguageConfiguration.fire({})}),l._instanceId=s.I(Ge),l._lastDecorationId=0,l._decorations=Object.create(null),l._decorationsTree=new Xe,l._commandManager=new m(l),l._isUndoing=!1,l._isRedoing=!1,l._trimAutoWhitespaceLines=null,l._tokens=new Me,l._tokenization=new Pe(l),l}return Ue(t,e),t.createFromString=function(e,n,i,o){return void 0===n&&(n=t.DEFAULT_CREATION_OPTIONS),void 0===i&&(i=null),void 0===o&&(o=null),new t(e,n,i,o)},t.resolveOptions=function(e,t){if(t.detectIndentation){var n=y(e,t.tabSize,t.insertSpaces);return new h.e({tabSize:n.tabSize,indentSize:n.tabSize,insertSpaces:n.insertSpaces,trimAutoWhitespace:t.trimAutoWhitespace,defaultEOL:t.defaultEOL})}return new h.e({tabSize:t.tabSize,indentSize:t.indentSize,insertSpaces:t.insertSpaces,trimAutoWhitespace:t.trimAutoWhitespace,defaultEOL:t.defaultEOL})},t.prototype.onDidChangeRawContentFast=function(e){return this._eventEmitter.fastEvent(function(t){return e(t.rawContentChangedEvent)})},t.prototype.onDidChangeRawContent=function(e){return this._eventEmitter.slowEvent(function(t){return e(t.rawContentChangedEvent)})},t.prototype.onDidChangeContentFast=function(e){return this._eventEmitter.fastEvent(function(t){return e(t.contentChangedEvent)})},t.prototype.onDidChangeContent=function(e){return this._eventEmitter.slowEvent(function(t){return e(t.contentChangedEvent)})},t.prototype.dispose=function(){this._isDisposing=!0,this._onWillDispose.fire(),this._languageRegistryListener.dispose(),this._tokenization.dispose(),this._isDisposed=!0,e.prototype.dispose.call(this),this._isDisposing=!1},t.prototype._assertNotDisposed=function(){if(this._isDisposed)throw new Error("Model is disposed!")},t.prototype._emitContentChangedEvent=function(e,t){this._isDisposing||this._eventEmitter.fire(new be(e,t))},t.prototype.setValue=function(e){if(this._assertNotDisposed(),null!==e){var t=qe(e,this._options.defaultEOL);this.setValueFromTextBuffer(t)}},t.prototype._createContentChanged2=function(e,t,n,i,o,r,s){return{changes:[{range:e,rangeOffset:t,rangeLength:n,text:i}],eol:this._buffer.getEOL(),versionId:this.getVersionId(),isUndoing:o,isRedoing:r,isFlush:s}},t.prototype.setValueFromTextBuffer=function(e){if(this._assertNotDisposed(),null!==e){var t=this.getFullModelRange(),n=this.getValueLengthInRange(t),i=this.getLineCount(),o=this.getLineMaxColumn(i);this._buffer=e,this._increaseVersionId(),this._tokens.flush(),this._decorations=Object.create(null),this._decorationsTree=new Xe,this._commandManager=new m(this),this._trimAutoWhitespaceLines=null,this._emitContentChangedEvent(new ye([new fe],this._versionId,!1,!1),this._createContentChanged2(new c.a(1,1,i,o),0,n,this.getValue(),!1,!1,!0))}},t.prototype.setEOL=function(e){this._assertNotDisposed();var t=1===e?"\r\n":"\n";if(this._buffer.getEOL()!==t){var n=this.getFullModelRange(),i=this.getValueLengthInRange(n),o=this.getLineCount(),r=this.getLineMaxColumn(o);this._onBeforeEOLChange(),this._buffer.setEOL(t),this._increaseVersionId(),this._onAfterEOLChange(),this._emitContentChangedEvent(new ye([new ve],this._versionId,!1,!1),this._createContentChanged2(new c.a(1,1,o,r),0,i,this.getValue(),!1,!1,!1))}},t.prototype._onBeforeEOLChange=function(){var e=this.getVersionId(),t=this._decorationsTree.search(0,!1,!1,e);this._ensureNodesHaveRanges(t)},t.prototype._onAfterEOLChange=function(){for(var e=this.getVersionId(),t=this._decorationsTree.collectNodesPostOrder(),n=0,i=t.length;n0},t.prototype.getAttachedEditorCount=function(){return this._attachedEditorCount},t.prototype.isTooLargeForSyncing=function(){return this._isTooLargeForSyncing},t.prototype.isTooLargeForTokenization=function(){return this._isTooLargeForTokenization},t.prototype.isDisposed=function(){return this._isDisposed},t.prototype.isDominatedByLongLines=function(){if(this._assertNotDisposed(),this.isTooLargeForTokenization())return!1;for(var e=0,t=0,n=this._buffer.getLineCount(),i=1;i<=n;i++){var o=this._buffer.getLineLength(i);o>=1e4?t+=o:e+=o}return t>e},Object.defineProperty(t.prototype,"uri",{get:function(){return this._associatedResource},enumerable:!0,configurable:!0}),t.prototype.getOptions=function(){return this._assertNotDisposed(),this._options},t.prototype.getFormattingOptions=function(){return{tabSize:this._options.indentSize,insertSpaces:this._options.insertSpaces}},t.prototype.updateOptions=function(e){this._assertNotDisposed();var t=void 0!==e.tabSize?e.tabSize:this._options.tabSize,n=void 0!==e.indentSize?e.indentSize:this._options.indentSize,i=void 0!==e.insertSpaces?e.insertSpaces:this._options.insertSpaces,o=void 0!==e.trimAutoWhitespace?e.trimAutoWhitespace:this._options.trimAutoWhitespace,r=new h.e({tabSize:t,indentSize:n,insertSpaces:i,defaultEOL:this._options.defaultEOL,trimAutoWhitespace:o});if(!this._options.equals(r)){var s=this._options.createChangeEvent(r);this._options=r,this._onDidChangeOptions.fire(s)}},t.prototype.detectIndentation=function(e,t){this._assertNotDisposed();var n=y(this._buffer,t,e);this.updateOptions({insertSpaces:n.insertSpaces,tabSize:n.tabSize,indentSize:n.tabSize})},t._normalizeIndentationFromWhitespace=function(e,t,n){for(var i=0,o=0;othis.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineContent(e)},t.prototype.getLineLength=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineLength(e)},t.prototype.getLinesContent=function(){return this._assertNotDisposed(),this._buffer.getLinesContent()},t.prototype.getEOL=function(){return this._assertNotDisposed(),this._buffer.getEOL()},t.prototype.getLineMinColumn=function(e){return this._assertNotDisposed(),1},t.prototype.getLineMaxColumn=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineLength(e)+1},t.prototype.getLineFirstNonWhitespaceColumn=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineFirstNonWhitespaceColumn(e)},t.prototype.getLineLastNonWhitespaceColumn=function(e){if(this._assertNotDisposed(),e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._buffer.getLineLastNonWhitespaceColumn(e)},t.prototype._validateRangeRelaxedNoAllocations=function(e){var t,n,i=this._buffer.getLineCount(),o=e.startLineNumber,r=e.startColumn;if(o<1)t=1,n=1;else if(o>i)t=i,n=this.getLineMaxColumn(t);else{if(t=0|o,r<=1)n=1;else n=r>=(h=this.getLineMaxColumn(t))?h:0|r}var s,a,u=e.endLineNumber,l=e.endColumn;if(u<1)s=1,a=1;else if(u>i)s=i,a=this.getLineMaxColumn(s);else{var h;if(s=0|u,l<=1)a=1;else a=l>=(h=this.getLineMaxColumn(s))?h:0|l}return o===t&&r===n&&u===s&&l===a&&e instanceof c.a&&!(e instanceof d.a)?e:new c.a(t,n,s,a)},t.prototype._isValidPosition=function(e,t,n){if("number"!=typeof e||"number"!=typeof t)return!1;if(isNaN(e)||isNaN(t))return!1;if(e<1||t<1)return!1;if((0|e)!==e||(0|t)!==t)return!1;if(e>this._buffer.getLineCount())return!1;if(t>this.getLineMaxColumn(e))return!1;if(n&&t>1){var i=this._buffer.getLineCharCode(e,t-2);if(s.w(i))return!1}return!0},t.prototype._validatePosition=function(e,t,n){var i=Math.floor("number"!=typeof e||isNaN(e)?1:e),o=Math.floor("number"!=typeof t||isNaN(t)?1:t),r=this._buffer.getLineCount();if(i<1)return new l.a(1,1);if(i>r)return new l.a(r,this.getLineMaxColumn(r));if(o<=1)return new l.a(i,1);var a=this.getLineMaxColumn(i);if(o>=a)return new l.a(i,a);if(n){var u=this._buffer.getLineCharCode(i,o-2);if(s.w(u))return new l.a(i,o-1)}return new l.a(i,o)},t.prototype.validatePosition=function(e){return this._assertNotDisposed(),e instanceof l.a&&this._isValidPosition(e.lineNumber,e.column,!0)?e:this._validatePosition(e.lineNumber,e.column,!0)},t.prototype._isValidRange=function(e,t){var n=e.startLineNumber,i=e.startColumn,o=e.endLineNumber,r=e.endColumn;if(!this._isValidPosition(n,i,!1))return!1;if(!this._isValidPosition(o,r,!1))return!1;if(t){var a=i>1?this._buffer.getLineCharCode(n,i-2):0,u=r>1&&r<=this._buffer.getLineLength(o)?this._buffer.getLineCharCode(o,r-2):0,l=s.w(a),c=s.w(u);return!l&&!c}return!0},t.prototype.validateRange=function(e){if(this._assertNotDisposed(),e instanceof c.a&&!(e instanceof d.a)&&this._isValidRange(e,!0))return e;var t=this._validatePosition(e.startLineNumber,e.startColumn,!1),n=this._validatePosition(e.endLineNumber,e.endColumn,!1),i=t.lineNumber,o=t.column,r=n.lineNumber,a=n.column,u=o>1?this._buffer.getLineCharCode(i,o-2):0,l=a>1&&a<=this._buffer.getLineLength(r)?this._buffer.getLineCharCode(r,a-2):0,h=s.w(u),p=s.w(l);return h||p?i===r&&o===a?new c.a(i,o-1,r,a-1):h&&p?new c.a(i,o-1,r,a+1):h?new c.a(i,o-1,r,a):new c.a(i,o,r,a+1):new c.a(i,o,r,a)},t.prototype.modifyPosition=function(e,t){this._assertNotDisposed();var n=this.getOffsetAt(e)+t;return this.getPositionAt(Math.min(this._buffer.getLength(),Math.max(0,n)))},t.prototype.getFullModelRange=function(){this._assertNotDisposed();var e=this.getLineCount();return new c.a(1,1,e,this.getLineMaxColumn(e))},t.prototype.findMatchesLineByLine=function(e,t,n,i){return this._buffer.findMatchesLineByLine(e,t,n,i)},t.prototype.findMatches=function(e,t,n,i,o,r,s){var a;if(void 0===s&&(s=999),this._assertNotDisposed(),a=c.a.isIRange(t)?this.validateRange(t):this.getFullModelRange(),!n&&e.indexOf("\n")<0){var u=new ie.a(e,n,i,o).parseSearchRequest();return u?this.findMatchesLineByLine(a,u,r,s):[]}return ie.c.findMatches(this,new ie.a(e,n,i,o),a,r,s)},t.prototype.findNextMatch=function(e,t,n,i,o,r){this._assertNotDisposed();var s=this.validatePosition(t);if(!n&&e.indexOf("\n")<0){var a=new ie.a(e,n,i,o).parseSearchRequest();if(!a)return null;var u=this.getLineCount(),l=new c.a(s.lineNumber,s.column,u,this.getLineMaxColumn(u)),d=this.findMatchesLineByLine(l,a,r,1);return ie.c.findNextMatch(this,new ie.a(e,n,i,o),s,r),d.length>0?d[0]:(l=new c.a(1,1,s.lineNumber,this.getLineMaxColumn(s.lineNumber)),(d=this.findMatchesLineByLine(l,a,r,1)).length>0?d[0]:null)}return ie.c.findNextMatch(this,new ie.a(e,n,i,o),s,r)},t.prototype.findPreviousMatch=function(e,t,n,i,o,r){this._assertNotDisposed();var s=this.validatePosition(t);return ie.c.findPreviousMatch(this,new ie.a(e,n,i,o),s,r)},t.prototype.pushStackElement=function(){this._commandManager.pushStackElement()},t.prototype.pushEOL=function(e){if(("\n"===this.getEOL()?0:1)!==e)try{this._onDidChangeDecorations.beginDeferredEmit(),this._eventEmitter.beginDeferredEmit(),this._commandManager.pushEOL(e)}finally{this._eventEmitter.endDeferredEmit(),this._onDidChangeDecorations.endDeferredEmit()}},t.prototype.pushEditOperations=function(e,t,n){try{return this._onDidChangeDecorations.beginDeferredEmit(),this._eventEmitter.beginDeferredEmit(),this._pushEditOperations(e,t,n)}finally{this._eventEmitter.endDeferredEmit(),this._onDidChangeDecorations.endDeferredEmit()}},t.prototype._pushEditOperations=function(e,t,n){var i=this;if(this._options.trimAutoWhitespace&&this._trimAutoWhitespaceLines){for(var o=t.map(function(e){return{range:i.validateRange(e.range),text:e.text}}),r=!0,s=0,a=e.length;su.endLineNumber,f=u.startLineNumber>v.endLineNumber;if(!p&&!f){l=!0;break}}if(!l){r=!1;break}}if(r)for(s=0,a=this._trimAutoWhitespaceLines.length;sv.endLineNumber)&&!(g===v.startLineNumber&&v.startColumn===m&&v.isEmpty()&&y&&y.length>0&&"\n"===y.charAt(0)||g===v.startLineNumber&&1===v.startColumn&&v.isEmpty()&&y&&y.length>0&&"\n"===y.charAt(y.length-1))){_=!1;break}}_&&t.push({range:new c.a(g,1,g,m),text:null})}this._trimAutoWhitespaceLines=null}return this._commandManager.pushEditOperation(e,t,n)},t.prototype.applyEdits=function(e){try{return this._onDidChangeDecorations.beginDeferredEmit(),this._eventEmitter.beginDeferredEmit(),this._applyEdits(e)}finally{this._eventEmitter.endDeferredEmit(),this._onDidChangeDecorations.endDeferredEmit()}},t.prototype._applyEdits=function(e){for(var t=0,n=e.length;t=0;y--){var b=p+y,C=r-u-v+b;a.push(new ge(b,this.getLineContent(C)))}if(_this.getLineCount()?[]:this.getLinesDecorations(e,e,t,n)},t.prototype.getLinesDecorations=function(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=!1);var o=this.getLineCount(),r=Math.min(o,Math.max(1,e)),s=Math.min(o,Math.max(1,t)),a=this.getLineMaxColumn(s);return this._getDecorationsInRange(new c.a(r,1,s,a),n,i)},t.prototype.getDecorationsInRange=function(e,t,n){void 0===t&&(t=0),void 0===n&&(n=!1);var i=this.validateRange(e);return this._getDecorationsInRange(i,t,n)},t.prototype.getOverviewRulerDecorations=function(e,t){void 0===e&&(e=0),void 0===t&&(t=!1);var n=this.getVersionId(),i=this._decorationsTree.search(e,t,!0,n);return this._ensureNodesHaveRanges(i)},t.prototype.getAllDecorations=function(e,t){void 0===e&&(e=0),void 0===t&&(t=!1);var n=this.getVersionId(),i=this._decorationsTree.search(e,t,!1,n);return this._ensureNodesHaveRanges(i)},t.prototype._getDecorationsInRange=function(e,t,n){var i=this._buffer.getOffsetAt(e.startLineNumber,e.startColumn),o=this._buffer.getOffsetAt(e.endLineNumber,e.endColumn),r=this.getVersionId(),s=this._decorationsTree.intervalSearch(i,o,t,n,r);return this._ensureNodesHaveRanges(s)},t.prototype._ensureNodesHaveRanges=function(e){for(var t=0,n=e.length;tthis.getLineCount())throw new Error("Illegal value for lineNumber");this._tokens.setTokens(this._languageIdentifier.id,e-1,this._buffer.getLineLength(e),t)},t.prototype.setTokens=function(e){if(0!==e.length){for(var t=[],n=0,i=e.length;nthis.getLineCount())throw new Error("Illegal value for lineNumber");this._tokenization.forceTokenization(e)},t.prototype.isCheapToTokenize=function(e){return this._tokenization.isCheapToTokenize(e)},t.prototype.tokenizeIfCheap=function(e){this.isCheapToTokenize(e)&&this.forceTokenization(e)},t.prototype.getLineTokens=function(e){if(e<1||e>this.getLineCount())throw new Error("Illegal value for lineNumber");return this._getLineTokens(e)},t.prototype._getLineTokens=function(e){var t=this.getLineContent(e);return this._tokens.getTokens(this._languageIdentifier.id,e-1,t)},t.prototype.getLanguageIdentifier=function(){return this._languageIdentifier},t.prototype.getModeId=function(){return this._languageIdentifier.language},t.prototype.setMode=function(e){if(this._languageIdentifier.id!==e.id){var t={oldLanguage:this._languageIdentifier.language,newLanguage:e.language};this._languageIdentifier=e,this._onDidChangeLanguage.fire(t),this._onDidChangeLanguageConfiguration.fire({})}},t.prototype.getLanguageIdAtPosition=function(e,t){var n=this.validatePosition(new l.a(e,t)),i=this.getLineTokens(n.lineNumber);return i.getLanguageId(i.findTokenIndexAtOffset(n.column-1))},t.prototype.getWordAtPosition=function(e){this._assertNotDisposed();var n=this.validatePosition(e),i=this.getLineContent(n.lineNumber),o=this._getLineTokens(n.lineNumber),r=o.findTokenIndexAtOffset(n.column-1),s=t._findLanguageBoundaries(o,r),a=s[0],u=s[1],l=Object(We.d)(n.column,je.a.getWordDefinition(o.getLanguageId(r)),i.substring(a,u),a);if(l&&l.startColumn<=e.column&&e.column<=l.endColumn)return l;if(r>0&&a===n.column-1){var c=t._findLanguageBoundaries(o,r-1),d=c[0],h=c[1],p=Object(We.d)(n.column,je.a.getWordDefinition(o.getLanguageId(r-1)),i.substring(d,h),d);if(p&&p.startColumn<=e.column&&e.column<=p.endColumn)return p}return null},t._findLanguageBoundaries=function(e,t){for(var n=e.getLanguageId(t),i=0,o=t;o>=0&&e.getLanguageId(o)===n;o--)i=e.getStartOffset(o);for(var r=e.getLineContent().length,s=(o=t,e.getCount());o0&&n.getStartOffset(o)===e.column-1){a=n.getStartOffset(o);o--;var l=je.a.getBracketsSupport(n.getLanguageId(o));if(l&&!Object(Ve.b)(n.getStandardTokenType(o))){var c,d,h;s=Math.max(n.getStartOffset(o),e.column-1-l.maxBracketLength);if((c=Be.a.findPrevBracketInToken(l.reversedRegex,t,i,s,a))&&c.startColumn<=e.column&&e.column<=c.endColumn)if(d=(d=i.substring(c.startColumn-1,c.endColumn-1)).toLowerCase(),h=this._matchFoundBracket(c,l.textIsBracket[d],l.textIsOpenBracket[d]))return h}}return null},t.prototype._matchFoundBracket=function(e,t,n){if(!t)return null;var i;if(n){if(i=this._findMatchingBracketDown(t,e.getEndPosition()))return[e,i]}else if(i=this._findMatchingBracketUp(t,e.getStartPosition()))return[e,i];return null},t.prototype._findMatchingBracketUp=function(e,t){for(var n=e.languageIdentifier.id,i=e.reversedRegex,o=-1,r=t.lineNumber;r>=1;r--){var s=this._getLineTokens(r),a=s.getCount(),u=this._buffer.getLineContent(r),l=a-1,c=-1;for(r===t.lineNumber&&(l=s.findTokenIndexAtOffset(t.column-1),c=t.column-1);l>=0;l--){var d=s.getLanguageId(l),h=s.getStandardTokenType(l),p=s.getStartOffset(l),f=s.getEndOffset(l);if(-1===c&&(c=f),d===n&&!Object(Ve.b)(h))for(;;){var g=Be.a.findPrevBracketInToken(i,r,u,p,c);if(!g)break;var m=u.substring(g.startColumn-1,g.endColumn-1);if((m=m.toLowerCase())===e.open?o++:m===e.close&&o--,0===o)return g;c=g.startColumn-1}c=-1}}return null},t.prototype._findMatchingBracketDown=function(e,t){for(var n=e.languageIdentifier.id,i=e.forwardRegex,o=1,r=t.lineNumber,s=this.getLineCount();r<=s;r++){var a=this._getLineTokens(r),u=a.getCount(),l=this._buffer.getLineContent(r),c=0,d=0;for(r===t.lineNumber&&(c=a.findTokenIndexAtOffset(t.column-1),d=t.column-1);c=1;o--){var r=this._getLineTokens(o),s=r.getCount(),a=this._buffer.getLineContent(o),u=s-1,l=-1;for(o===t.lineNumber&&(u=r.findTokenIndexAtOffset(t.column-1),l=t.column-1);u>=0;u--){var c=r.getLanguageId(u),d=r.getStandardTokenType(u),h=r.getStartOffset(u),p=r.getEndOffset(u);if(-1===l&&(l=p),n!==c&&(n=c,i=je.a.getBracketsSupport(n)),i&&!Object(Ve.b)(d)){var f=Be.a.findPrevBracketInToken(i.reversedRegex,o,a,h,l);if(f)return this._toFoundBracket(i,f)}l=-1}}return null},t.prototype.findNextBracket=function(e){for(var t=this.validatePosition(e),n=-1,i=null,o=t.lineNumber,r=this.getLineCount();o<=r;o++){var s=this._getLineTokens(o),a=s.getCount(),u=this._buffer.getLineContent(o),l=0,c=0;for(o===t.lineNumber&&(l=s.findTokenIndexAtOffset(t.column-1),c=t.column-1);lo)throw new Error("Illegal value for lineNumber");for(var r=je.a.getFoldingRules(this._languageIdentifier.id),s=Boolean(r&&r.offSide),a=-2,u=-1,l=-2,c=-1,d=function(e){if(-1!==a&&(-2===a||a>e-1)){a=-1,u=-1;for(var t=e-2;t>=0;t--){var n=i._computeIndentLevel(t);if(n>=0){a=t,u=n;break}}}if(-2===l){l=-1,c=-1;for(t=e;t=0){l=t,c=r;break}}}},h=-2,p=-1,f=-2,g=-1,m=function(e){if(-2===h){h=-1,p=-1;for(var t=e-2;t>=0;t--){var n=i._computeIndentLevel(t);if(n>=0){h=t,p=n;break}}}if(-1!==f&&(-2===f||f=0){f=t,g=r;break}}}},_=0,v=!0,y=0,b=!0,C=0,w=0;v||b;w++){var S=e-w,L=e+w;if(0!==w&&(S<1||So||L>n)&&(b=!1),w>5e4&&(v=!1,b=!1),v){var O=void 0;if((E=this._computeIndentLevel(S-1))>=0?(l=S-1,c=E,O=Math.ceil(E/this._options.indentSize)):(d(S),O=this._getIndentLevelForWhitespaceLine(s,u,c)),0===w){if(_=S,y=L,0===(C=O))return{startLineNumber:_,endLineNumber:y,indent:C};continue}O>=C?_=S:v=!1}if(b){var E,N=void 0;(E=this._computeIndentLevel(L-1))>=0?(h=L-1,p=E,N=Math.ceil(E/this._options.indentSize)):(m(L),N=this._getIndentLevelForWhitespaceLine(s,p,g)),N>=C?y=L:b=!1}}return{startLineNumber:_,endLineNumber:y,indent:C}},t.prototype.getLinesIndentGuides=function(e,t){this._assertNotDisposed();var n=this.getLineCount();if(e<1||e>n)throw new Error("Illegal value for startLineNumber");if(t<1||t>n)throw new Error("Illegal value for endLineNumber");for(var i=je.a.getFoldingRules(this._languageIdentifier.id),o=Boolean(i&&i.offSide),r=new Array(t-e+1),s=-2,a=-1,u=-2,l=-1,c=e;c<=t;c++){var d=c-e,h=this._computeIndentLevel(c-1);if(h>=0)s=c-1,a=h,r[d]=Math.ceil(h/this._options.indentSize);else{if(-2===s){s=-1,a=-1;for(var p=c-2;p>=0;p--){if((f=this._computeIndentLevel(p))>=0){s=p,a=f;break}}}if(-1!==u&&(-2===u||u=0){u=p,l=f;break}}}r[d]=this._getIndentLevelForWhitespaceLine(o,a,l)}}return r},t.prototype._getIndentLevelForWhitespaceLine=function(e,t,n){return-1===t||-1===n?0:t0?this._deferredEvent?this._deferredEvent=this._deferredEvent.merge(e):this._deferredEvent=e:(this._fastEmitter.fire(e),this._slowEmitter.fire(e))},t}(r.a)},"0u1n":function(e,t){},"1Ccl":function(e,t){},"1LBi":function(e,t){},"1O6n":function(e,t){},"1Yb9":function(e,t,n){var i=n("mgnk"),o=n("UnEC"),r=Object.prototype,s=r.hasOwnProperty,a=r.propertyIsEnumerable,u=i(function(){return arguments}())?i:function(e){return o(e)&&s.call(e,"callee")&&!a.call(e,"callee")};e.exports=u},"1Z8u":function(e,t){},"1kli":function(e,t,n){var i=n("ZT2e"),o=/[\\^$.*+?()[\]{}|]/g,r=RegExp(o.source);e.exports=function(e){return(e=i(e))&&r.test(e)?e.replace(o,"\\$&"):e}},"1mBN":function(e,t){},"1sup":function(e,t,n){"use strict";t.b=function(e,t,n){"string"==typeof e&&(e=i.a.file(e));if(n){var h=n.getWorkspaceFolder(e);if(h){var p=n.getWorkspace().folders.length>1,f=void 0;if(f=Object(u.e)(h.uri,e)?"":Object(u.h)(h.uri,e),p){var g=h&&h.name?h.name:Object(u.b)(h.uri);f=f?g+" • "+f:g}return f}}if(e.scheme!==s.b.file&&e.scheme!==s.b.untitled)return e.with({query:null,fragment:null}).toString(!0);if(l(e.fsPath))return Object(o.normalize)(c(e.fsPath));var m=Object(o.normalize)(e.fsPath);!a.g&&t&&(m=function(e,t){if(a.g||!e||!t)return e;var n=d.original===t?d.normalized:void 0;n||(n=""+Object(r.G)(t,o.posix.sep)+o.posix.sep,d={original:t,normalized:n});(a.c?Object(r.J)(e,n):Object(r.K)(e,n))&&(e="~/"+e.substr(n.length));return e}(m,t.userHome));return m},t.a=function(e){if(!e)return;"string"==typeof e&&(e=i.a.file(e));var t=Object(u.b)(e)||(e.scheme===s.b.file?e.fsPath:e.path);if(l(t))return c(t);return t};var i=n("mrx5"),o=n("/uRs"),r=n("aL7J"),s=n("lapT"),a=n("ZfGv"),u=n("ZYUE");function l(e){return!(!a.g||!e||":"!==e[1])}function c(e){return l(e)?e.charAt(0).toUpperCase()+e.slice(1):e}var d=Object.create(null)},"1xIj":function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"b",function(){return r});var i=n("JVO/"),o=Object(i.c)("logService"),r=function(){function e(){}return e.prototype.trace=function(e){for(var t=[],n=1;n1){var m=n.getLineContent(g.lineNumber),_=i.q(m),v=-1===_?m.length+1:_+1;if(g.column<=v){var y=r.a.visibleColumnFromColumn2(t,n,g),b=r.a.prevIndentTabStop(y,t.indentSize),C=r.a.columnFromVisibleColumn2(t,n,g.lineNumber,b);f=new a.a(g.lineNumber,C,g.lineNumber,g.column)}else f=new a.a(g.lineNumber,g.column-1,g.lineNumber,g.column)}else{var w=s.a.left(t,n,g.lineNumber,g.column);f=new a.a(w.lineNumber,w.column,g.lineNumber,g.column)}}f.isEmpty()?l[d]=null:(f.startLineNumber!==f.endLineNumber&&(c=!0),l[d]=new o.a(f,""))}return[c,l]},e.cut=function(e,t,n){for(var i=[],s=0,u=n.length;s1?(d=c.lineNumber-1,h=t.getLineMaxColumn(c.lineNumber-1),p=c.lineNumber,f=t.getLineMaxColumn(c.lineNumber)):(d=c.lineNumber,h=1,p=c.lineNumber,f=t.getLineMaxColumn(c.lineNumber));var g=new a.a(d,h,p,f);g.isEmpty()?i[s]=null:i[s]=new o.a(g,"")}else i[s]=null;else i[s]=new o.a(l,"")}return new r.e(0,i,{shouldPushStackElementBefore:!0,shouldPushStackElementAfter:!0})},e}()},"2LSJ":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"InsertCursorAbove",function(){return b}),n.d(t,"InsertCursorBelow",function(){return C}),n.d(t,"MultiCursorSessionResult",function(){return O}),n.d(t,"MultiCursorSession",function(){return E}),n.d(t,"MultiCursorSelectionController",function(){return N}),n.d(t,"MultiCursorSelectionControllerAction",function(){return x}),n.d(t,"AddSelectionToNextFindMatchAction",function(){return I}),n.d(t,"AddSelectionToPreviousFindMatchAction",function(){return D}),n.d(t,"MoveSelectionToNextFindMatchAction",function(){return k}),n.d(t,"MoveSelectionToPreviousFindMatchAction",function(){return T}),n.d(t,"SelectHighlightsAction",function(){return M}),n.d(t,"CompatChangeAll",function(){return R}),n.d(t,"SelectionHighlighter",function(){return P});var i,o=n("hK2W"),r=n("odeJ"),s=n("uNfg"),a=n("tqet"),u=n("03Zz"),l=n("HAT9"),c=n("vTy2"),d=n("iHM7"),h=n("/9db"),p=n("D2uo"),f=n("0ly5"),g=n("PCC9"),m=n("T1Qz"),_=n("L5KM"),v=n("eoic"),y=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),b=function(e){function t(){return e.call(this,{id:"editor.action.insertCursorAbove",label:o.a("mutlicursor.insertAbove","Add Cursor Above"),alias:"Add Cursor Above",precondition:void 0,kbOpts:{kbExpr:h.a.editorTextFocus,primary:2576,linux:{primary:1552,secondary:[3088]},weight:100},menubarOpts:{menuId:22,group:"3_multi",title:o.a({key:"miInsertCursorAbove",comment:["&& denotes a mnemonic"]},"&&Add Cursor Above"),order:2}})||this}return y(t,e),t.prototype.run=function(e,t,n){if(t.hasModel()){var i=n&&!0===n.logicalLine,o=t._getCursors(),r=o.context;r.config.readOnly||(r.model.pushStackElement(),o.setStates(n.source,3,l.b.addCursorUp(r,o.getAll(),i)),o.reveal(!0,1,0))}},t}(u.b),C=function(e){function t(){return e.call(this,{id:"editor.action.insertCursorBelow",label:o.a("mutlicursor.insertBelow","Add Cursor Below"),alias:"Add Cursor Below",precondition:void 0,kbOpts:{kbExpr:h.a.editorTextFocus,primary:2578,linux:{primary:1554,secondary:[3090]},weight:100},menubarOpts:{menuId:22,group:"3_multi",title:o.a({key:"miInsertCursorBelow",comment:["&& denotes a mnemonic"]},"A&&dd Cursor Below"),order:3}})||this}return y(t,e),t.prototype.run=function(e,t,n){if(t.hasModel()){var i=n&&!0===n.logicalLine,o=t._getCursors(),r=o.context;r.config.readOnly||(r.model.pushStackElement(),o.setStates(n.source,3,l.b.addCursorDown(r,o.getAll(),i)),o.reveal(!0,2,0))}},t}(u.b),w=function(e){function t(){return e.call(this,{id:"editor.action.insertCursorAtEndOfEachLineSelected",label:o.a("mutlicursor.insertAtEndOfEachLineSelected","Add Cursors to Line Ends"),alias:"Add Cursors to Line Ends",precondition:void 0,kbOpts:{kbExpr:h.a.editorTextFocus,primary:1575,weight:100},menubarOpts:{menuId:22,group:"3_multi",title:o.a({key:"miInsertCursorAtEndOfEachLineSelected",comment:["&& denotes a mnemonic"]},"Add C&&ursors to Line Ends"),order:4}})||this}return y(t,e),t.prototype.getCursorsForSelection=function(e,t,n){if(!e.isEmpty()){for(var i=e.startLineNumber;i1&&n.push(new d.a(e.endLineNumber,e.endColumn,e.endLineNumber,e.endColumn))}},t.prototype.run=function(e,t){var n=this;if(t.hasModel()){var i=t.getModel(),o=[];t.getSelections().forEach(function(e){return n.getCursorsForSelection(e,i,o)}),o.length>0&&t.setSelections(o)}},t}(u.b),S=function(e){function t(){return e.call(this,{id:"editor.action.addCursorsToBottom",label:o.a("mutlicursor.addCursorsToBottom","Add Cursors To Bottom"),alias:"Add Cursors To Bottom",precondition:void 0})||this}return y(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getSelections(),i=t.getModel().getLineCount(),o=[],r=n[0].startLineNumber;r<=i;r++)o.push(new d.a(r,n[0].startColumn,r,n[0].endColumn));o.length>0&&t.setSelections(o)}},t}(u.b),L=function(e){function t(){return e.call(this,{id:"editor.action.addCursorsToTop",label:o.a("mutlicursor.addCursorsToTop","Add Cursors To Top"),alias:"Add Cursors To Top",precondition:void 0})||this}return y(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getSelections(),i=[],o=n[0].startLineNumber;o>=1;o--)i.push(new d.a(o,n[0].startColumn,o,n[0].endColumn));i.length>0&&t.setSelections(i)}},t}(u.b),O=function(){return function(e,t,n){this.selections=e,this.revealRange=t,this.revealScrollType=n}}(),E=function(){function e(e,t,n,i,o,r,s){this._editor=e,this.findController=t,this.isDisconnectedFromFindController=n,this.searchText=i,this.wholeWord=o,this.matchCase=r,this.currentMatch=s}return e.create=function(t,n){if(!t.hasModel())return null;var i=n.getState();if(!t.hasTextFocus()&&i.isRevealed&&i.searchString.length>0)return new e(t,n,!1,i.searchString,i.wholeWord,i.matchCase,null);var o,r,s=!1,a=t.getSelections();1===a.length&&a[0].isEmpty()?(s=!0,o=!0,r=!0):(o=i.wholeWord,r=i.matchCase);var u,l=t.getSelection(),c=null;if(l.isEmpty()){var h=t.getModel().getWordAtPosition(l.getStartPosition());if(!h)return null;u=h.word,c=new d.a(l.startLineNumber,h.startColumn,l.startLineNumber,h.endColumn)}else u=t.getModel().getValueInRange(l).replace(/\r\n/g,"\n");return new e(t,n,s,u,o,r,c)},e.prototype.addSelectionToNextFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getNextMatch();if(!e)return null;var t=this._editor.getSelections();return new O(t.concat(e),e,0)},e.prototype.moveSelectionToNextFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getNextMatch();if(!e)return null;var t=this._editor.getSelections();return new O(t.slice(0,t.length-1).concat(e),e,0)},e.prototype._getNextMatch=function(){if(!this._editor.hasModel())return null;if(this.currentMatch){var e=this.currentMatch;return this.currentMatch=null,e}this.findController.highlightFindOptions();var t=this._editor.getSelections(),n=t[t.length-1],i=this._editor.getModel().findNextMatch(this.searchText,n.getEndPosition(),!1,this.matchCase,this.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1);return i?new d.a(i.range.startLineNumber,i.range.startColumn,i.range.endLineNumber,i.range.endColumn):null},e.prototype.addSelectionToPreviousFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getPreviousMatch();if(!e)return null;var t=this._editor.getSelections();return new O(t.concat(e),e,0)},e.prototype.moveSelectionToPreviousFindMatch=function(){if(!this._editor.hasModel())return null;var e=this._getPreviousMatch();if(!e)return null;var t=this._editor.getSelections();return new O(t.slice(0,t.length-1).concat(e),e,0)},e.prototype._getPreviousMatch=function(){if(!this._editor.hasModel())return null;if(this.currentMatch){var e=this.currentMatch;return this.currentMatch=null,e}this.findController.highlightFindOptions();var t=this._editor.getSelections(),n=t[t.length-1],i=this._editor.getModel().findPreviousMatch(this.searchText,n.getStartPosition(),!1,this.matchCase,this.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1);return i?new d.a(i.range.startLineNumber,i.range.startColumn,i.range.endLineNumber,i.range.endColumn):null},e.prototype.selectAll=function(){return this._editor.hasModel()?(this.findController.highlightFindOptions(),this._editor.getModel().findMatches(this.searchText,!0,!1,this.matchCase,this.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1,1073741824)):[]},e}(),N=function(e){function t(t){var n=e.call(this)||this;return n._sessionDispose=n._register(new a.b),n._editor=t,n._ignoreSelectionChange=!1,n._session=null,n}return y(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype.dispose=function(){this._endSession(),e.prototype.dispose.call(this)},t.prototype.getId=function(){return t.ID},t.prototype._beginSessionIfNeeded=function(e){var t=this;if(!this._session){var n=E.create(this._editor,e);if(!n)return;this._session=n;var i={searchString:this._session.searchText};this._session.isDisconnectedFromFindController&&(i.wholeWordOverride=1,i.matchCaseOverride=1,i.isRegexOverride=2),e.getState().change(i,!1),this._sessionDispose.add(this._editor.onDidChangeCursorSelection(function(e){t._ignoreSelectionChange||t._endSession()})),this._sessionDispose.add(this._editor.onDidBlurEditorText(function(){t._endSession()})),this._sessionDispose.add(e.getState().onFindReplaceStateChange(function(e){(e.matchCase||e.wholeWord)&&t._endSession()}))}},t.prototype._endSession=function(){if(this._sessionDispose.clear(),this._session&&this._session.isDisconnectedFromFindController){this._session.findController.getState().change({wholeWordOverride:0,matchCaseOverride:0,isRegexOverride:0},!1)}this._session=null},t.prototype._setSelections=function(e){this._ignoreSelectionChange=!0,this._editor.setSelections(e),this._ignoreSelectionChange=!1},t.prototype._expandEmptyToWord=function(e,t){if(!t.isEmpty())return t;var n=e.getWordAtPosition(t.getStartPosition());return n?new d.a(t.startLineNumber,n.startColumn,t.startLineNumber,n.endColumn):t},t.prototype._applySessionResult=function(e){e&&(this._setSelections(e.selections),e.revealRange&&this._editor.revealRangeInCenterIfOutsideViewport(e.revealRange,e.revealScrollType))},t.prototype.getSession=function(e){return this._session},t.prototype.addSelectionToNextFindMatch=function(e){if(this._editor.hasModel()){if(!this._session){var t=this._editor.getSelections();if(t.length>1){var n=e.getState().matchCase;if(!F(this._editor.getModel(),t,n)){for(var i=this._editor.getModel(),o=[],r=0,s=t.length;r0&&n.isRegex)t=this._editor.getModel().findMatches(n.searchString,!0,n.isRegex,n.matchCase,n.wholeWord?this._editor.getConfiguration().wordSeparators:null,!1,1073741824);else{if(this._beginSessionIfNeeded(e),!this._session)return;t=this._session.selectAll()}if(t.length>0){for(var i=this._editor.getSelection(),o=0,r=t.length;o1){var a=o.getState().matchCase;if(!F(t.getModel(),s,a))return null}r=E.create(t,o)}if(!r)return null;if(r.currentMatch)return null;if(/^[ \t]+$/.test(r.searchText))return null;if(r.searchText.length>200)return null;var u=o.getState(),l=u.matchCase;if(u.isRevealed){var c=u.searchString;l||(c=c.toLowerCase());var d=r.searchText;if(l||(d=d.toLowerCase()),c===d&&r.matchCase===u.matchCase&&r.wholeWord===u.wholeWord&&!u.isRegex)return null}return new A(r.searchText,r.matchCase,r.wholeWord?t.getConfiguration().wordSeparators:null)},t.prototype._setState=function(e){if(A.softEquals(this.state,e))this.state=e;else if(this.state=e,this.state){if(this.editor.hasModel()){var n=this.editor.getModel();if(!n.isTooLargeForTokenization()){var i=g.i.has(n),o=n.findMatches(this.state.searchText,!0,!1,this.state.matchCase,this.state.wordSeparators,!1).map(function(e){return e.range});o.sort(c.a.compareRangesUsingStarts);var r=this.editor.getSelections();r.sort(c.a.compareRangesUsingStarts);for(var s=[],a=0,u=0,l=o.length,d=r.length;a=d)s.push(h),a++;else{var p=c.a.compareRangesUsingStarts(h,r[u]);p<0?(!r[u].isEmpty()&&c.a.areIntersecting(h,r[u])||s.push(h),a++):p>0?u++:(a++,u++)}}var f=s.map(function(e){return{range:e,options:i?t._SELECTION_HIGHLIGHT:t._SELECTION_HIGHLIGHT_OVERVIEW}});this.decorations=this.editor.deltaDecorations(this.decorations,f)}}}else this.decorations=this.editor.deltaDecorations(this.decorations,[])},t.prototype.dispose=function(){this._setState(null),e.prototype.dispose.call(this)},t.ID="editor.contrib.selectionHighlighter",t._SELECTION_HIGHLIGHT_OVERVIEW=f.a.register({stickiness:1,className:"selectionHighlight",overviewRuler:{color:Object(v.g)(_._32),position:p.d.Center}}),t._SELECTION_HIGHLIGHT=f.a.register({stickiness:1,className:"selectionHighlight"}),t}(a.a);function F(e,t,n){for(var i=W(e,t[0],!n),o=1,r=t.length;o=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},C=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},w=Object(_._36)("editor.wordHighlightBackground",{dark:"#575757B8",light:"#57575740",hc:null},o.a("wordHighlight","Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations."),!0),S=Object(_._36)("editor.wordHighlightStrongBackground",{dark:"#004972B8",light:"#0e639c40",hc:null},o.a("wordHighlightStrong","Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations."),!0),L=Object(_._36)("editor.wordHighlightBorder",{light:null,dark:null,hc:_.b},o.a("wordHighlightBorder","Border color of a symbol during read-access, like reading a variable.")),O=Object(_._36)("editor.wordHighlightStrongBorder",{light:null,dark:null,hc:_.b},o.a("wordHighlightStrongBorder","Border color of a symbol during write-access, like writing to a variable.")),E=Object(_._36)("editorOverviewRuler.wordHighlightForeground",{dark:"#A0A0A0CC",light:"#A0A0A0CC",hc:"#A0A0A0CC"},o.a("overviewRulerWordHighlightForeground","Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations."),!0),N=Object(_._36)("editorOverviewRuler.wordHighlightStrongForeground",{dark:"#C0A0C0CC",light:"#C0A0C0CC",hc:"#C0A0C0CC"},o.a("overviewRulerWordHighlightStrongForeground","Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations."),!0),x=new m.d("hasWordHighlights",!1);function I(e,t,n){var i=g.i.ordered(e);return Object(s.h)(i.map(function(i){return function(){return Promise.resolve(i.provideDocumentHighlights(e,t,n)).then(void 0,u.f)}}),r.n)}var D=function(){function e(e,t,n){var i=this;this._wordRange=this._getCurrentWordRange(e,t),this.result=Object(s.f)(function(o){return i._compute(e,t,n,o)})}return e.prototype._getCurrentWordRange=function(e,t){var n=e.getWordAtPosition(t.getPosition());return n?new d.a(t.startLineNumber,n.startColumn,t.startLineNumber,n.endColumn):null},e.prototype.isValid=function(e,t,n){for(var i=t.startLineNumber,o=t.startColumn,r=t.endColumn,s=this._getCurrentWordRange(e,t),a=Boolean(this._wordRange&&this._wordRange.equalsRange(s)),u=0,l=n.length;!a&&u=r&&(a=!0)}return a},e.prototype.cancel=function(){this.result.cancel()},e}(),k=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return y(t,e),t.prototype._compute=function(e,t,n,i){return I(e,t.getPosition(),i).then(function(e){return e||[]})},t}(D),T=function(e){function t(t,n,i){var o=e.call(this,t,n,i)||this;return o._selectionIsEmpty=n.isEmpty(),o}return y(t,e),t.prototype._compute=function(e,t,n,i){return Object(s.l)(250,i).then(function(){if(!t.isEmpty())return[];var i=e.getWordAtPosition(t.getPosition());return i?e.findMatches(i.word,!0,!1,!0,n,!1).map(function(e){return{range:e.range,kind:g.h.Text}}):[]})},t.prototype.isValid=function(t,n,i){var o=n.isEmpty();return this._selectionIsEmpty===o&&e.prototype.isValid.call(this,t,n,i)},t}(D);Object(c.e)("_executeDocumentHighlights",function(e,t){return I(e,t,a.a.None)});var M=function(){function e(e,t){var n=this;this.toUnhook=new l.b,this.workerRequestTokenId=0,this.workerRequestCompleted=!1,this.workerRequestValue=[],this.lastCursorPositionChangeTime=0,this.renderDecorationsTimer=-1,this.editor=e,this._hasWordHighlights=x.bindTo(t),this._ignorePositionChangeEvent=!1,this.occurrencesHighlight=this.editor.getConfiguration().contribInfo.occurrencesHighlight,this.model=this.editor.getModel(),this.toUnhook.add(e.onDidChangeCursorPosition(function(e){n._ignorePositionChangeEvent||n.occurrencesHighlight&&n._onPositionChanged(e)})),this.toUnhook.add(e.onDidChangeModelContent(function(e){n._stopAll()})),this.toUnhook.add(e.onDidChangeConfiguration(function(e){var t=n.editor.getConfiguration().contribInfo.occurrencesHighlight;n.occurrencesHighlight!==t&&(n.occurrencesHighlight=t,n._stopAll())})),this._decorationIds=[],this.workerRequestTokenId=0,this.workerRequest=null,this.workerRequestCompleted=!1,this.lastCursorPositionChangeTime=0,this.renderDecorationsTimer=-1}return e.prototype.hasDecorations=function(){return this._decorationIds.length>0},e.prototype.restore=function(){this.occurrencesHighlight&&this._run()},e.prototype._getSortedHighlights=function(){var e=this;return r.d(this._decorationIds.map(function(t){return e.model.getDecorationRange(t)}).sort(d.a.compareRangesUsingStarts))},e.prototype.moveNext=function(){var e=this,t=this._getSortedHighlights(),n=t[(r.j(t,function(t){return t.containsPosition(e.editor.getPosition())})+1)%t.length];try{this._ignorePositionChangeEvent=!0,this.editor.setPosition(n.getStartPosition()),this.editor.revealRangeInCenterIfOutsideViewport(n)}finally{this._ignorePositionChangeEvent=!1}},e.prototype.moveBack=function(){var e=this,t=this._getSortedHighlights(),n=t[(r.j(t,function(t){return t.containsPosition(e.editor.getPosition())})-1+t.length)%t.length];try{this._ignorePositionChangeEvent=!0,this.editor.setPosition(n.getStartPosition()),this.editor.revealRangeInCenterIfOutsideViewport(n)}finally{this._ignorePositionChangeEvent=!1}},e.prototype._removeDecorations=function(){this._decorationIds.length>0&&(this._decorationIds=this.editor.deltaDecorations(this._decorationIds,[]),this._hasWordHighlights.set(!1))},e.prototype._stopAll=function(){this._removeDecorations(),-1!==this.renderDecorationsTimer&&(clearTimeout(this.renderDecorationsTimer),this.renderDecorationsTimer=-1),null!==this.workerRequest&&(this.workerRequest.cancel(),this.workerRequest=null),this.workerRequestCompleted||(this.workerRequestTokenId++,this.workerRequestCompleted=!0)},e.prototype._onPositionChanged=function(e){this.occurrencesHighlight&&3===e.reason?this._run():this._stopAll()},e.prototype._run=function(){var e=this,t=this.editor.getSelection();if(t.startLineNumber===t.endLineNumber){var n=t.startLineNumber,i=t.startColumn,o=t.endColumn,r=this.model.getWordAtPosition({lineNumber:n,column:i});if(!r||r.startColumn>i||r.endColumn=n?(this.renderDecorationsTimer=-1,this.renderDecorations()):this.renderDecorationsTimer=setTimeout(function(){e.renderDecorations()},n-t)},e.prototype.renderDecorations=function(){this.renderDecorationsTimer=-1;for(var t=[],n=0,i=this.workerRequestValue.length;n0){n=o[0].getStartPosition();var r=t.getTopForPosition(n.lineNumber,n.column);i=t.getScrollTop()-r}}return new e(n,i)},e.prototype.restore=function(e){if(this._visiblePosition){var t=e.getTopForPosition(this._visiblePosition.lineNumber,this._visiblePosition.column);e.setScrollTop(t+this._visiblePositionScrollDelta)}},e}()},"5N57":function(e,t,n){var i=n("ICSD")(n("TQ3y"),"Set");e.exports=i},"5RGO":function(e,t){},"5TlO":function(e,t,n){"use strict";t.a=function(e,t){if(!e)throw new Error(t?"Assertion failed ("+t+")":"Assertion Failed")}},"5VRF":function(e,t,n){"use strict";n.d(t,"c",function(){return s}),n.d(t,"d",function(){return o}),t.f=function(e){return Array.isArray(e)?o.fromArray(e):e},n.d(t,"a",function(){return a}),n.d(t,"b",function(){return u}),n.d(t,"e",function(){return l});var i,o,r=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s={done:!0,value:void 0};!function(e){var t={next:function(){return s}};e.empty=function(){return t},e.single=function(e){var t=!1;return{next:function(){return t?s:(t=!0,{done:!1,value:e})}}},e.fromArray=function(e,t,n){return void 0===t&&(t=0),void 0===n&&(n=e.length),{next:function(){return t>=n?s:{done:!1,value:e[t++]}}}},e.from=function(t){return t?Array.isArray(t)?e.fromArray(t):t:e.empty()},e.map=function(e,t){return{next:function(){var n=e.next();return n.done?s:{done:!1,value:t(n.value)}}}},e.filter=function(e,t){return{next:function(){for(;;){var n=e.next();if(n.done)return s;if(t(n.value))return{done:!1,value:n.value}}}}},e.forEach=function(e,t){for(var n=e.next();!n.done;n=e.next())t(n.value)},e.collect=function(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY);var n=[];if(0===t)return n;for(var i=0,o=e.next();!(o.done||(n.push(o.value),++i>=t));o=e.next());return n},e.concat=function(){for(var e=[],t=0;t=e.length)return s;var t=e[n].next();return t.done?(n++,this.next()):t}}}}(o||(o={}));var a=function(){function e(e,t,n,i){void 0===t&&(t=0),void 0===n&&(n=e.length),void 0===i&&(i=t-1),this.items=e,this.start=t,this.end=n,this.index=i}return e.prototype.first=function(){return this.index=this.start,this.current()},e.prototype.next=function(){return this.index=Math.min(this.index+1,this.end),this.current()},e.prototype.current=function(){return this.index===this.start-1||this.index===this.end?null:this.items[this.index]},e}(),u=function(e){function t(t,n,i,o){return void 0===n&&(n=0),void 0===i&&(i=t.length),void 0===o&&(o=n-1),e.call(this,t,n,i,o)||this}return r(t,e),t.prototype.current=function(){return e.prototype.current.call(this)},t.prototype.previous=function(){return this.index=Math.max(this.index-1,this.start-1),this.current()},t.prototype.first=function(){return this.index=this.start,this.current()},t.prototype.last=function(){return this.index=this.end-1,this.current()},t.prototype.parent=function(){return null},t}(a),l=function(){function e(e,t){this.iterator=e,this.fn=t}return e.prototype.next=function(){return this.fn(this.iterator.next())},e}()},"5Zxu":function(e,t,n){var i=n("sBat");e.exports=function(e){var t=i(e),n=t%1;return t==t?n?t-n:t:0}},"5kgg":function(e,t){},"5lao":function(e,t,n){"use strict";n.d(t,"a",function(){return h}),n.d(t,"b",function(){return p});var i,o=n("ZfGv"),r=n("iXRW"),s=n("G8r4"),a=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),u=o.d?1.5:1.35;function l(e,t){if("number"==typeof e)return e;if(void 0===e)return t;var n=parseFloat(e);return isNaN(n)?t:n}function c(e,t,n){return en?n:e}function d(e,t){return"string"!=typeof e?t:e}var h=function(){function e(e){this.zoomLevel=e.zoomLevel,this.fontFamily=String(e.fontFamily),this.fontWeight=String(e.fontWeight),this.fontSize=e.fontSize,this.lineHeight=0|e.lineHeight,this.letterSpacing=e.letterSpacing}return e.createFromRawSettings=function(t,n,i){void 0===i&&(i=!1);var o=d(t.fontFamily,r.b.fontFamily),a=d(t.fontWeight,r.b.fontWeight),h=l(t.fontSize,r.b.fontSize);0===(h=c(h,0,100))?h=r.b.fontSize:h<8&&(h=8);var p=function(e,t){if("number"==typeof e)return Math.round(e);if(void 0===e)return t;var n=parseInt(e);return isNaN(n)?t:n}(t.lineHeight,0);0===(p=c(p,0,150))?p=Math.round(u*h):p<8&&(p=8);var f=l(t.letterSpacing,0);f=c(f,-5,20);var g=1+(i?0:.1*s.a.getZoomLevel());return new e({zoomLevel:n,fontFamily:o,fontWeight:a,fontSize:h*=g,lineHeight:p*=g,letterSpacing:f})},e.prototype.getId=function(){return this.zoomLevel+"-"+this.fontFamily+"-"+this.fontWeight+"-"+this.fontSize+"-"+this.lineHeight+"-"+this.letterSpacing},e.prototype.getMassagedFontFamily=function(){return/[,"']/.test(this.fontFamily)?this.fontFamily:/[+ ]/.test(this.fontFamily)?'"'+this.fontFamily+'"':this.fontFamily},e}(),p=function(e){function t(t,n){var i=e.call(this,t)||this;return i.isTrusted=n,i.isMonospace=t.isMonospace,i.typicalHalfwidthCharacterWidth=t.typicalHalfwidthCharacterWidth,i.typicalFullwidthCharacterWidth=t.typicalFullwidthCharacterWidth,i.canUseHalfwidthRightwardsArrow=t.canUseHalfwidthRightwardsArrow,i.spaceWidth=t.spaceWidth,i.maxDigitWidth=t.maxDigitWidth,i}return a(t,e),t.prototype.equals=function(e){return this.fontFamily===e.fontFamily&&this.fontWeight===e.fontWeight&&this.fontSize===e.fontSize&&this.lineHeight===e.lineHeight&&this.letterSpacing===e.letterSpacing&&this.typicalHalfwidthCharacterWidth===e.typicalHalfwidthCharacterWidth&&this.typicalFullwidthCharacterWidth===e.typicalFullwidthCharacterWidth&&this.canUseHalfwidthRightwardsArrow===e.canUseHalfwidthRightwardsArrow&&this.spaceWidth===e.spaceWidth&&this.maxDigitWidth===e.maxDigitWidth},t}(h)},"5tK6":function(e,t,n){"use strict";n.d(t,"a",function(){return m});var i,o=n("LCUL"),r=(n.n(o),n("tqet")),s=n("lAcG"),a=n("ZfGv"),u=n("KIxu"),l=n("Bug4"),c=n("b1X/"),d=n("Kp7x"),h=n("7/Cv"),p=n("Gxst"),f=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=!1,m=function(e){function t(t,n,i){void 0===i&&(i={});var o=e.call(this)||this;return o._state=3,o._onDidEnablementChange=o._register(new d.a),o.onDidEnablementChange=o._onDidEnablementChange.event,o._onDidStart=o._register(new d.a),o.onDidStart=o._onDidStart.event,o._onDidChange=o._register(new d.a),o.onDidChange=o._onDidChange.event,o._onDidReset=o._register(new d.a),o.onDidReset=o._onDidReset.event,o._onDidEnd=o._register(new d.a),o.onDidEnd=o._onDidEnd.event,o.linkedSash=void 0,o.orthogonalStartSashDisposables=o._register(new r.b),o.orthogonalEndSashDisposables=o._register(new r.b),o.el=Object(h.m)(t,Object(h.a)(".monaco-sash")),a.d&&Object(h.f)(o.el,"mac"),o._register(Object(p.a)(o.el,"mousedown")(o.onMouseDown,o)),o._register(Object(p.a)(o.el,"dblclick")(o.onMouseDoubleClick,o)),l.b.addTarget(o.el),o._register(Object(p.a)(o.el,l.a.Start)(o.onTouchStart,o)),s.k&&Object(h.f)(o.el,"touch"),o.setOrientation(i.orientation||0),o.hidden=!1,o.layoutProvider=n,o.orthogonalStartSash=i.orthogonalStartSash,o.orthogonalEndSash=i.orthogonalEndSash,Object(h.R)(o.el,"debug",g),o}return f(t,e),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},set:function(e){this._state!==e&&(Object(h.R)(this.el,"disabled",0===e),Object(h.R)(this.el,"minimum",1===e),Object(h.R)(this.el,"maximum",2===e),this._state=e,this._onDidEnablementChange.fire(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"orthogonalStartSash",{get:function(){return this._orthogonalStartSash},set:function(e){this.orthogonalStartSashDisposables.clear(),e?(this.orthogonalStartSashDisposables.add(e.onDidEnablementChange(this.onOrthogonalStartSashEnablementChange,this)),this.onOrthogonalStartSashEnablementChange(e.state)):this.onOrthogonalStartSashEnablementChange(0),this._orthogonalStartSash=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"orthogonalEndSash",{get:function(){return this._orthogonalEndSash},set:function(e){this.orthogonalEndSashDisposables.clear(),e?(this.orthogonalEndSashDisposables.add(e.onDidEnablementChange(this.onOrthogonalEndSashEnablementChange,this)),this.onOrthogonalEndSashEnablementChange(e.state)):this.onOrthogonalEndSashEnablementChange(0),this._orthogonalEndSash=e},enumerable:!0,configurable:!0}),t.prototype.setOrientation=function(e){this.orientation=e,1===this.orientation?(Object(h.f)(this.el,"horizontal"),Object(h.I)(this.el,"vertical")):(Object(h.I)(this.el,"horizontal"),Object(h.f)(this.el,"vertical")),this.layoutProvider&&this.layout()},t.prototype.onMouseDown=function(e){var t=this;h.c.stop(e,!1);var n=!1;if(!e.__orthogonalSashEvent){var i=this.getOrthogonalSash(e);i&&(n=!0,e.__orthogonalSashEvent=!0,i.onMouseDown(e))}if(this.linkedSash&&!e.__linkedSashEvent&&(e.__linkedSashEvent=!0,this.linkedSash.onMouseDown(e)),this.state){for(var o=Object(h.y)("iframe").concat(Object(h.y)("webview")),s=0,u=o;s=this.el.clientHeight-4)return this.orthogonalEndSash}else{if(e.offsetX<=4)return this.orthogonalStartSash;if(e.offsetX>=this.el.clientWidth-4)return this.orthogonalEndSash}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.el&&this.el.parentElement&&this.el.parentElement.removeChild(this.el),this.el=null},t}(r.a)},"5zde":function(e,t,n){n("zQR9"),n("qyJz"),e.exports=n("FeBl").Array.from},"606G":function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("JVO/"),o=Object(i.c)("editorWorkerService")},"67ys":function(e,t){},"6Hge":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("X6iQ"),o=n("80kS"),r=n("03Zz"),s=n("artP"),a=n("vTy2"),u=n("iHM7"),l=n("/9db"),c=n("PCC9"),d=n("hK2W"),h=n("tqet"),p=n("aL7J"),f=function(){function e(){}return e.prototype.provideSelectionRanges=function(e,t){for(var n=[],i=0,o=t;i=0;u--){if(95===(d=o.charCodeAt(u))||45===d)break;if(Object(p.y)(d)&&Object(p.z)(c))break;c=d}for(u+=1;l0&&0===t.getLineFirstNonWhitespaceColumn(n.lineNumber)&&0===t.getLineLastNonWhitespaceColumn(n.lineNumber)&&e.push({range:new a.a(n.lineNumber,1,n.lineNumber,t.getLineMaxColumn(n.lineNumber))})},e}(),g=n("NjuD"),m=n("ItKl"),_=n("zxiH");t.provideSelectionRanges=N;var v,y=this&&this.__extends||(v=function(e,t){return(v=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}v(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),b=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},C=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=this.ranges.length)return this;var i=new e(n,this.ranges);return i.ranges[n].equalsRange(this.ranges[this.index])?i.mov(t):i},e}(),S=function(){function e(e){this._ignoreSelection=!1,this._editor=e}return e.get=function(t){return t.getContribution(e._id)},e.prototype.dispose=function(){Object(h.f)(this._selectionListener)},e.prototype.getId=function(){return e._id},e.prototype.run=function(e){var t=this;if(this._editor.hasModel()){var n=this._editor.getSelections(),r=this._editor.getModel();if(c.u.has(r)){var s=Promise.resolve(void 0);return this._state||(s=N(r,n.map(function(e){return e.getPosition()}),o.a.None).then(function(e){if(i.n(e)&&e.length===n.length&&t._editor.hasModel()&&i.g(t._editor.getSelections(),n,function(e,t){return e.equalsSelection(t)})){for(var o=function(t){e[t]=e[t].filter(function(e){return e.containsPosition(n[t].getStartPosition())&&e.containsPosition(n[t].getEndPosition())}),e[t].unshift(n[t])},r=0;r=i.length)&&o.x(i.charCodeAt(n))},e.isHighSurrogate=function(e,t,n){var i=e.getLineContent(t);return!(n<0||n>=i.length)&&o.w(i.charCodeAt(n))},e.isInsideSurrogatePair=function(e,t,n){return this.isHighSurrogate(e,t,n-2)},e.visibleColumnFromColumn=function(e,t,n){var i=e.length;i>t-1&&(i=t-1);for(var r=0,s=0;s=t)return u-ts?s:o},e.nextRenderTabStop=function(e,t){return e+t-e%t},e.nextIndentTabStop=function(e,t){return e+t-e%t},e.prevRenderTabStop=function(e,t){return e-1-(e-1)%t},e.prevIndentTabStop=function(e,t){return e-1-(e-1)%t},e}()},"6jTg":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("odeJ"),o=n("zxiH"),r=n("tqet"),s=n("4tuZ"),a=n("03Zz"),u=n("PCC9"),l=n("X6iQ"),c=n("80kS"),d=n("mrx5"),h=n("jIdl"),p=function(){function e(){this.lenses=[],this._dispoables=new r.b}return e.prototype.dispose=function(){this._dispoables.dispose()},e.prototype.add=function(e,t){this._dispoables.add(e);for(var n=0,i=e.lenses;nt.symbol.range.startLineNumber?1:i.get(e.provider)i.get(t.provider)?1:e.symbol.range.startColumnt.symbol.range.startColumn?1:0}),r})}Object(a.j)("_executeCodeLensProvider",function(e,t){var n=t.resource,i=t.itemResolveCount;if(!(n instanceof d.a))throw Object(o.b)();var s=e.get(h.a).getModel(n);if(!s)throw Object(o.b)();var a=[],u=new r.b;return f(s,c.a.None).then(function(e){u.add(e);for(var t=[],n=function(e){void 0===i||Boolean(e.symbol.command)?a.push(e.symbol):i-- >0&&e.provider.resolveCodeLens&&t.push(Promise.resolve(e.provider.resolveCodeLens(s,e.symbol,c.a.None)).then(function(t){return a.push(t||e.symbol)}))},o=0,r=e.lenses;ono commands";else{for(var i=[],o=0;o"+s+"",this._commands.set(String(o),r)):a=""+s+"",i.push(a)}}var u=""===this._domNode.innerHTML||" "===this._domNode.innerHTML;this._domNode.innerHTML=i.join(" | "),this._editor.layoutContentWidget(this),u&&t&&g.f(this._domNode,"fadein")}},e.prototype.getCommand=function(e){return e.parentElement===this._domNode?this._commands.get(e.id):void 0},e.prototype.getId=function(){return this._id},e.prototype.getDomNode=function(){return this._domNode},e.prototype.setSymbolRange=function(e){if(this._editor.hasModel()){var t=e.startLineNumber,n=this._editor.getModel().getLineFirstNonWhitespaceColumn(t);this._widgetPosition={position:{lineNumber:t,column:n},preference:[1]}}},e.prototype.getPosition=function(){return this._widgetPosition||null},e.prototype.isVisible=function(){return this._domNode.hasAttribute("monaco-visible-content-widget")},e._idPool=0,e}(),L=function(){function e(){this._removeDecorations=[],this._addDecorations=[],this._addDecorationsCallbacks=[]}return e.prototype.addDecoration=function(e,t){this._addDecorations.push(e),this._addDecorationsCallbacks.push(t)},e.prototype.removeDecoration=function(e){this._removeDecorations.push(e)},e.prototype.commit=function(e){for(var t=e.deltaDecorations(this._removeDecorations,this._addDecorations),n=0,i=t.length;n a:hover { color: "+i+" !important; }")});var E=n("ItKl"),N=n("fAkY"),x=n("JVO/"),I=n("8xpx"),D=n("WTFd"),k=n("Cfmk"),T=n("dwjm"),M=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},R=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},A=Object(x.c)("ICodeLensCache"),P=function(){return function(e,t){this.lineCount=e,this.data=t}}(),F=function(){function e(e){var t=this;this._fakeProvider=new(function(){function e(){}return e.prototype.provideCodeLenses=function(){throw new Error("not supported")},e}()),this._cache=new D.a(20,.75);Object(i.k)(function(){return e.remove("codelens/cache",1)});var n="codelens/cache2",o=e.get(n,1,"{}");this._deserialize(o),Object(T.a)(e.onWillSaveState)(function(i){i.reason===k.c.SHUTDOWN&&e.store(n,t._serialize(),1)})}return e.prototype.put=function(e,t){var n=new p;n.add({lenses:t.lenses.map(function(e){return e.symbol}),dispose:function(){}},this._fakeProvider);var i=new P(e.getLineCount(),n);this._cache.set(e.uri.toString(),i)},e.prototype.get=function(e){var t=this._cache.get(e.uri.toString());return t&&t.lineCount===e.getLineCount()?t.data:void 0},e.prototype.delete=function(e){this._cache.delete(e.uri.toString())},e.prototype._serialize=function(){var e=Object.create(null);return this._cache.forEach(function(t,n){for(var i=new Set,o=0,r=t.data.lenses;o=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},j=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},V=function(){function e(e,t,n,i){var o=this;this._editor=e,this._commandService=t,this._notificationService=n,this._codeLensCache=i,this._globalToDispose=new r.b,this._localToDispose=new r.b,this._lenses=[],this._oldCodeLensModels=new r.b,this._modelChangeCounter=0,this._isEnabled=this._editor.getConfiguration().contribInfo.codeLens,this._globalToDispose.add(this._editor.onDidChangeModel(function(){return o._onModelChange()})),this._globalToDispose.add(this._editor.onDidChangeModelLanguage(function(){return o._onModelChange()})),this._globalToDispose.add(this._editor.onDidChangeConfiguration(function(){var e=o._isEnabled;o._isEnabled=o._editor.getConfiguration().contribInfo.codeLens,e!==o._isEnabled&&o._onModelChange()})),this._globalToDispose.add(u.b.onDidChange(this._onModelChange,this)),this._onModelChange()}return e.prototype.dispose=function(){this._localDispose(),this._globalToDispose.dispose(),this._oldCodeLensModels.dispose(),Object(r.f)(this._currentCodeLensModel)},e.prototype._localDispose=function(){this._currentFindCodeLensSymbolsPromise&&(this._currentFindCodeLensSymbolsPromise.cancel(),this._currentFindCodeLensSymbolsPromise=void 0,this._modelChangeCounter++),this._currentResolveCodeLensSymbolsPromise&&(this._currentResolveCodeLensSymbolsPromise.cancel(),this._currentResolveCodeLensSymbolsPromise=void 0),this._localToDispose.clear(),this._oldCodeLensModels.clear(),Object(r.f)(this._currentCodeLensModel)},e.prototype.getId=function(){return e.ID},e.prototype._onModelChange=function(){var e=this;this._localDispose();var t=this._editor.getModel();if(t&&this._isEnabled){var n=this._codeLensCache.get(t);if(n&&this._renderCodeLensSymbols(n),u.b.has(t)){for(var a=0,l=u.b.all(t);a0&&h.schedule()})),this._localToDispose.add(this._editor.onDidLayoutChange(function(){h.schedule()})),this._localToDispose.add(Object(r.h)(function(){if(e._editor.getModel()){var t=s.c.capture(e._editor);e._editor.changeDecorations(function(t){e._editor.changeViewZones(function(n){e._disposeAllLenses(t,n)})}),t.restore(e._editor)}else e._disposeAllLenses(void 0,void 0)})),this._localToDispose.add(this._editor.onDidChangeConfiguration(function(t){if(t.fontInfo)for(var n=0,i=e._lenses;ni||(n&&n[n.length-1].symbol.range.startLineNumber===l?n.push(u):(n=[u],o.push(n)))}var c=s.c.capture(this._editor);this._editor.changeDecorations(function(e){t._editor.changeViewZones(function(n){for(var i=new L,r=0,s=0;sn)return o;do{t%2&&(o+=e),(t=i(t/2))&&(e+=e)}while(t);return o}},"7/Cv":function(e,t,n){"use strict";t.p=function(e){for(;e.firstChild;)e.removeChild(e.firstChild)},t.K=function(e){e.parentNode&&e.parentNode.removeChild(e)},t.G=function(e){for(;e;){if(e===document.body)return!0;e=e.parentNode||e.host}return!1},n.d(t,"C",function(){return b}),n.d(t,"f",function(){return C}),n.d(t,"g",function(){return w}),n.d(t,"I",function(){return S}),n.d(t,"J",function(){return L}),n.d(t,"R",function(){return O}),t.h=N,n.d(t,"k",function(){return x}),t.i=function(e,t){return N(e,"mouseout",function(n){for(var i=n.relatedTarget||n.target;i&&i!==e;)i=i.parentNode;i!==e&&t(n)})},n.d(t,"N",function(){return I}),n.d(t,"P",function(){return D}),t.j=function(e,t,n,i,o){return new V(e,t,n,i,o)},t.u=B,n.d(t,"b",function(){return z}),t.z=function(e){var t=e.offsetParent,n=e.offsetTop,i=e.offsetLeft;for(;null!==(e=e.parentNode)&&e!==document.body&&e!==document.documentElement;){n-=e.scrollTop;var o=B(e);o&&(i-="rtl"!==o.direction?e.scrollLeft:-e.scrollLeft),e===t&&(i+=H.getBorderLeftWidth(e),n+=H.getBorderTopWidth(e),n+=e.offsetTop,i+=e.offsetLeft,t=e.offsetParent)}return{left:i,top:n}},t.x=function(e){var t=e.getBoundingClientRect();return{left:t.left+U.scrollX,top:t.top+U.scrollY,width:t.width,height:t.height}},n.d(t,"e",function(){return U}),t.B=function(e){var t=H.getMarginLeft(e)+H.getMarginRight(e);return e.offsetWidth+t},t.w=function(e){var t=H.getBorderLeftWidth(e)+H.getBorderRightWidth(e),n=H.getPaddingLeft(e)+H.getPaddingRight(e);return e.offsetWidth-t-n},t.v=function(e){var t=H.getBorderTopWidth(e)+H.getBorderBottomWidth(e),n=H.getPaddingTop(e)+H.getPaddingBottom(e);return e.offsetHeight-t-n},t.A=function(e){var t=H.getMarginTop(e)+H.getMarginBottom(e);return e.offsetHeight+t},t.E=K,t.t=function(e,t,n){for(;e;){if(b(e,t))return e;if(n)if("string"==typeof n){if(b(e,n))return null}else if(e===n)return null;e=e.parentNode}return null},t.s=q,t.r=function(e,t,n){void 0===n&&(n=Z());if(!n||!t)return;n.sheet.insertRule(e+"{"+t+"}",0)},t.H=function(e,t){void 0===t&&(t=Z());if(!t)return;for(var n=function(e){if(e&&e.sheet&&e.sheet.rules)return e.sheet.rules;if(e&&e.sheet&&e.sheet.cssRules)return e.sheet.cssRules;return[]}(t),i=[],o=0;o=0;o--)t.sheet.deleteRule(i[o])},t.F=function(e){if("object"==typeof HTMLElement)return e instanceof HTMLElement;return e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.nodeName},n.d(t,"d",function(){return Y}),n.d(t,"c",function(){return X}),t.O=function(e){for(var t=[],n=0;e&&e.nodeType===e.ELEMENT_NODE;n++)t[n]=e.scrollTop,e=e.parentNode;return t},t.M=function(e,t){for(var n=0;e&&e.nodeType===e.ELEMENT_NODE;n++)e.scrollTop!==t[n]&&(e.scrollTop=t[n]),e=e.parentNode},t.S=function(e){return new J(e)},t.m=function(e){for(var t=[],n=1;n=0;){if(r=s+o,(0===s||32===n.charCodeAt(s-1))&&32===n.charCodeAt(r))return this._lastStart=s,void(this._lastEnd=r+1);if(s>0&&32===n.charCodeAt(s-1)&&r===i)return this._lastStart=s-1,void(this._lastEnd=r);if(0===s&&r===i)return this._lastStart=0,void(this._lastEnd=r)}this._lastStart=-1}else this._lastStart=-1}else this._lastStart=-1},e.prototype.hasClass=function(e,t){return this._findClassName(e,t),-1!==this._lastStart},e.prototype.addClasses=function(e){for(var t=this,n=[],i=1;i0;){M.sort(F.sort),M.shift().execute()}A=!1},D=function(e,t){void 0===t&&(t=0);var n,i=new F(e,t);return T.push(i),R||(R=!0,n=P,k||(k=self.requestAnimationFrame||self.msRequestAnimationFrame||self.webkitRequestAnimationFrame||self.mozRequestAnimationFrame||self.oRequestAnimationFrame||function(e){return setTimeout(function(){return e((new Date).getTime())},0)}),k.call(self,n)),i},I=function(e,t){if(A){var n=new F(e,t);return M.push(n),n}return D(e,t)};var W=16,j=function(e,t){return t},V=function(e){function t(t,n,i,o,r){void 0===o&&(o=j),void 0===r&&(r=W);var s=e.call(this)||this,a=null,l=0,c=s._register(new u.e),d=function(){l=(new Date).getTime(),i(a),a=null};return s._register(N(t,n,function(e){a=o(a,e);var t=(new Date).getTime()-l;t>=r?(c.cancel(),d()):c.setIfNotSet(d,r-t)})),s}return g(t,e),t}(d.a);function B(e){return document.defaultView.getComputedStyle(e,null)}var H=function(){function e(){}return e.convertToPixels=function(e,t){return parseFloat(t)||0},e.getDimension=function(t,n,i){var o=B(t),r="0";return o&&(r=o.getPropertyValue?o.getPropertyValue(n):o.getAttribute(i)),e.convertToPixels(t,r)},e.getBorderLeftWidth=function(t){return e.getDimension(t,"border-left-width","borderLeftWidth")},e.getBorderRightWidth=function(t){return e.getDimension(t,"border-right-width","borderRightWidth")},e.getBorderTopWidth=function(t){return e.getDimension(t,"border-top-width","borderTopWidth")},e.getBorderBottomWidth=function(t){return e.getDimension(t,"border-bottom-width","borderBottomWidth")},e.getPaddingLeft=function(t){return e.getDimension(t,"padding-left","paddingLeft")},e.getPaddingRight=function(t){return e.getDimension(t,"padding-right","paddingRight")},e.getPaddingTop=function(t){return e.getDimension(t,"padding-top","paddingTop")},e.getPaddingBottom=function(t){return e.getDimension(t,"padding-bottom","paddingBottom")},e.getMarginLeft=function(t){return e.getDimension(t,"margin-left","marginLeft")},e.getMarginTop=function(t){return e.getDimension(t,"margin-top","marginTop")},e.getMarginRight=function(t){return e.getDimension(t,"margin-right","marginRight")},e.getMarginBottom=function(t){return e.getDimension(t,"margin-bottom","marginBottom")},e}(),z=function(){return function(e,t){this.width=e,this.height=t}}();var U=new(function(){function e(){}return Object.defineProperty(e.prototype,"scrollX",{get:function(){return"number"==typeof window.scrollX?window.scrollX:document.body.scrollLeft+document.documentElement.scrollLeft},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scrollY",{get:function(){return"number"==typeof window.scrollY?window.scrollY:document.body.scrollTop+document.documentElement.scrollTop},enumerable:!0,configurable:!0}),e}());function K(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function q(e){void 0===e&&(e=document.getElementsByTagName("head")[0]);var t=document.createElement("style");return t.type="text/css",t.media="screen",e.appendChild(t),t}var G=null;function Z(){return G||(G=q()),G}var Y={CLICK:"click",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:o.m?"webkitAnimationStart":"animationstart",ANIMATION_END:o.m?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:o.m?"webkitAnimationIteration":"animationiteration"},X={stop:function(e,t){e.preventDefault?e.preventDefault():e.returnValue=!1,t&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0)}};var J=function(e){function t(t){var n=e.call(this)||this;n._onDidFocus=n._register(new c.a),n.onDidFocus=n._onDidFocus.event,n._onDidBlur=n._register(new c.a),n.onDidBlur=n._onDidBlur.event;var i=K(document.activeElement,t),o=!1;return n._register(Object(r.a)(t,Y.FOCUS,!0)(function(){o=!1,i||(i=!0,n._onDidFocus.fire())})),n._register(Object(r.a)(t,Y.BLUR,!0)(function(){i&&(o=!0,window.setTimeout(function(){o&&(o=!1,i=!1,n._onDidBlur.fire())},0))})),n}return g(t,e),t}(d.a);var Q,$=/([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;function ee(e,t,n){for(var i=[],o=3;o|==|<=|>=|!<|!>|\|\||::|->>|->|~~\*|~~|!~~\*|!~~|~\*|!~\*|!~|.)/,this.BLOCK_COMMENT_REGEX=/^(\/\*[^]*?(?:\*\/|$))/,this.LINE_COMMENT_REGEX=this.createLineCommentRegex(t.lineCommentTypes),this.RESERVED_TOPLEVEL_REGEX=this.createReservedWordRegex(t.reservedToplevelWords),this.RESERVED_NEWLINE_REGEX=this.createReservedWordRegex(t.reservedNewlineWords),this.RESERVED_PLAIN_REGEX=this.createReservedWordRegex(t.reservedWords),this.WORD_REGEX=this.createWordRegex(t.specialWordChars),this.STRING_REGEX=this.createStringRegex(t.stringTypes),this.OPEN_PAREN_REGEX=this.createParenRegex(t.openParens),this.CLOSE_PAREN_REGEX=this.createParenRegex(t.closeParens),this.INDEXED_PLACEHOLDER_REGEX=this.createPlaceholderRegex(t.indexedPlaceholderTypes,"[0-9]*"),this.IDENT_NAMED_PLACEHOLDER_REGEX=this.createPlaceholderRegex(t.namedPlaceholderTypes,"[a-zA-Z0-9._$]+"),this.STRING_NAMED_PLACEHOLDER_REGEX=this.createPlaceholderRegex(t.namedPlaceholderTypes,this.createStringPattern(t.stringTypes))}return e.prototype.createLineCommentRegex=function(e){return new RegExp("^((?:"+e.map(function(e){return(0,o.default)(e)}).join("|")+").*?(?:\n|$))")},e.prototype.createReservedWordRegex=function(e){var t=e.join("|").replace(/ /g,"\\s+");return new RegExp("^("+t+")\\b","i")},e.prototype.createWordRegex=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return new RegExp("^([\\w"+e.join("")+"]+)")},e.prototype.createStringRegex=function(e){return new RegExp("^("+this.createStringPattern(e)+")")},e.prototype.createStringPattern=function(e){var t={"``":"((`[^`]*($|`))+)","[]":"((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)",'""':'(("[^"\\\\]*(?:\\\\.[^"\\\\]*)*("|$))+)',"''":"(('[^'\\\\]*(?:\\\\.[^'\\\\]*)*('|$))+)","N''":"((N'[^N'\\\\]*(?:\\\\.[^N'\\\\]*)*('|$))+)"};return e.map(function(e){return t[e]}).join("|")},e.prototype.createParenRegex=function(e){var t=this;return new RegExp("^("+e.map(function(e){return t.escapeParen(e)}).join("|")+")","i")},e.prototype.escapeParen=function(e){return 1===e.length?(0,o.default)(e):"\\b"+e+"\\b"},e.prototype.createPlaceholderRegex=function(e,t){if((0,i.default)(e))return!1;var n=e.map(o.default).join("|");return new RegExp("^((?:"+n+")(?:"+t+"))")},e.prototype.tokenize=function(e){for(var t=[],n=void 0;e.length;)n=this.getNextToken(e,n),e=e.substring(n.value.length),t.push(n);return t},e.prototype.getNextToken=function(e,t){return this.getWhitespaceToken(e)||this.getCommentToken(e)||this.getStringToken(e)||this.getOpenParenToken(e)||this.getCloseParenToken(e)||this.getPlaceholderToken(e)||this.getNumberToken(e)||this.getReservedWordToken(e,t)||this.getWordToken(e)||this.getOperatorToken(e)},e.prototype.getWhitespaceToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.WHITESPACE,regex:this.WHITESPACE_REGEX})},e.prototype.getCommentToken=function(e){return this.getLineCommentToken(e)||this.getBlockCommentToken(e)},e.prototype.getLineCommentToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.LINE_COMMENT,regex:this.LINE_COMMENT_REGEX})},e.prototype.getBlockCommentToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.BLOCK_COMMENT,regex:this.BLOCK_COMMENT_REGEX})},e.prototype.getStringToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.STRING,regex:this.STRING_REGEX})},e.prototype.getOpenParenToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.OPEN_PAREN,regex:this.OPEN_PAREN_REGEX})},e.prototype.getCloseParenToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.CLOSE_PAREN,regex:this.CLOSE_PAREN_REGEX})},e.prototype.getPlaceholderToken=function(e){return this.getIdentNamedPlaceholderToken(e)||this.getStringNamedPlaceholderToken(e)||this.getIndexedPlaceholderToken(e)},e.prototype.getIdentNamedPlaceholderToken=function(e){return this.getPlaceholderTokenWithKey({input:e,regex:this.IDENT_NAMED_PLACEHOLDER_REGEX,parseKey:function(e){return e.slice(1)}})},e.prototype.getStringNamedPlaceholderToken=function(e){var t=this;return this.getPlaceholderTokenWithKey({input:e,regex:this.STRING_NAMED_PLACEHOLDER_REGEX,parseKey:function(e){return t.getEscapedPlaceholderKey({key:e.slice(2,-1),quoteChar:e.slice(-1)})}})},e.prototype.getIndexedPlaceholderToken=function(e){return this.getPlaceholderTokenWithKey({input:e,regex:this.INDEXED_PLACEHOLDER_REGEX,parseKey:function(e){return e.slice(1)}})},e.prototype.getPlaceholderTokenWithKey=function(e){var t=e.input,n=e.regex,i=e.parseKey,o=this.getTokenOnFirstMatch({input:t,regex:n,type:r.default.PLACEHOLDER});return o&&(o.key=i(o.value)),o},e.prototype.getEscapedPlaceholderKey=function(e){var t=e.key,n=e.quoteChar;return t.replace(new RegExp((0,o.default)("\\")+n,"g"),n)},e.prototype.getNumberToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.NUMBER,regex:this.NUMBER_REGEX})},e.prototype.getOperatorToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.OPERATOR,regex:this.OPERATOR_REGEX})},e.prototype.getReservedWordToken=function(e,t){if(!t||!t.value||"."!==t.value)return this.getToplevelReservedToken(e)||this.getNewlineReservedToken(e)||this.getPlainReservedToken(e)},e.prototype.getToplevelReservedToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.RESERVED_TOPLEVEL,regex:this.RESERVED_TOPLEVEL_REGEX})},e.prototype.getNewlineReservedToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.RESERVED_NEWLINE,regex:this.RESERVED_NEWLINE_REGEX})},e.prototype.getPlainReservedToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.RESERVED,regex:this.RESERVED_PLAIN_REGEX})},e.prototype.getWordToken=function(e){return this.getTokenOnFirstMatch({input:e,type:r.default.WORD,regex:this.WORD_REGEX})},e.prototype.getTokenOnFirstMatch=function(e){var t=e.input,n=e.type,i=e.regex,o=t.match(i);if(o)return{type:n,value:o[1]}},e}();t.default=a,e.exports=t.default},"7VLx":function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("JVO/"),o=Object(i.c)("IWorkspaceEditService")},"7YfR":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,o=n("UqCF"),r=n("X6iQ"),s=n("zxiH"),a=n("tqet"),u=n("03Zz"),l=n("0WPX"),c=n("vTy2"),d=n("/9db"),h=n("Bzq0"),p=n("Evjx"),f=n("WTFd"),g=n("Cfmk"),m=n("PCC9"),_=n("odeJ"),v=n("JVO/"),y=n("Gzpe"),b=n("8xpx"),C=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),w=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},S=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},L=function(){function e(){}return e.prototype.select=function(e,t,n){if(0===n.length)return 0;for(var i=n[0].score[0],o=1;ou&&d.type===i[l].completion.kind&&d.insertText===i[l].completion.insertText&&(u=d.touch,a=l),i[l].completion.preselect&&-1===s)return l}return-1!==a?a:-1!==s?s:0},t.prototype.toJSON=function(){var e=[];return this._cache.forEach(function(t,n){e.push([n,t])}),e},t.prototype.fromJSON=function(e){this._cache.clear();for(var t=0,n=e;t0){this._seq=e[0][1].touch+1;for(var t=0,n=e;t=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},P=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},F=function(){function e(t,n){this._editor=t,this._index=0,this._ckOtherSuggestions=e.OtherSuggestions.bindTo(n)}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this._ckOtherSuggestions.reset(),Object(a.f)(this._listener),this._model=void 0,this._acceptNext=void 0,this._ignore=!1},e.prototype.set=function(t,n){var i=this,o=t.model,r=t.index;0!==o.items.length?e._moveIndex(!0,o,r)!==r?(this._acceptNext=n,this._model=o,this._index=r,this._listener=this._editor.onDidChangeCursorPosition(function(){i._ignore||i.reset()}),this._ckOtherSuggestions.set(!0)):this.reset():this.reset()},e._moveIndex=function(e,t,n){for(var i=n;(i=(i+t.items.length+(e?1:-1))%t.items.length)!==n&&t.items[i].completion.additionalTextEdits;);return i},e.prototype.next=function(){this._move(!0)},e.prototype.prev=function(){this._move(!1)},e.prototype._move=function(t){if(this._model)try{this._ignore=!0,this._index=e._moveIndex(t,this._model,this._index),this._acceptNext({index:this._index,item:this._model.items[this._index],model:this._model})}finally{this._ignore=!1}},e.OtherSuggestions=new M.d("hasOtherSuggestions",!1),e=A([P(1,M.c)],e)}(),W=n("Kp7x"),j=n("iHM7"),V=n("GYOr"),B=n("iXRW"),H=n("aL7J"),z=(function(){}(),function(){function e(t,n,i,o,r){void 0===r&&(r=B.a.contribInfo.suggest),this._snippetCompareFn=e._compareCompletionItems,this._items=t,this._column=n,this._wordDistance=o,this._options=r,this._refilterKind=1,this._lineContext=i,"top"===r.snippets?this._snippetCompareFn=e._compareCompletionItemsSnippetsUp:"bottom"===r.snippets&&(this._snippetCompareFn=e._compareCompletionItemsSnippetsDown)}return Object.defineProperty(e.prototype,"lineContext",{get:function(){return this._lineContext},set:function(e){this._lineContext.leadingLineContent===e.leadingLineContent&&this._lineContext.characterCountDelta===e.characterCountDelta||(this._refilterKind=this._lineContext.characterCountDelta2e3?V.d:V.e,u=0;u=d)l.score=V.a.Default;else if("string"==typeof l.completion.filterText){if(!(f=a(i,o,h,l.completion.filterText,l.filterTextLow,0,!1)))continue;0===Object(H.e)(l.completion.filterText,l.completion.label)?l.score=f:(l.score=Object(V.b)(i,o,h,l.completion.label,l.labelLow,0),l.score[0]=f[0])}else{var f;if(!(f=a(i,o,h,l.completion.label,l.labelLow,0,!1)))continue;l.score=f}}switch(l.idx=u,l.distance=this._wordDistance.distance(l.position,l.completion),s.push(l),this._stats.suggestionCount++,l.completion.kind){case 25:this._stats.snippetCount++;break;case 18:this._stats.textCount++}}this._filteredItems=s.sort(this._snippetCompareFn),this._refilterKind=0},e._compareCompletionItems=function(e,t){return e.score[0]>t.score[0]?-1:e.score[0]t.distance?1:e.idxt.idx?1:0},e._compareCompletionItemsSnippetsDown=function(t,n){if(t.completion.kind!==n.completion.kind){if(25===t.completion.kind)return 1;if(25===n.completion.kind)return-1}return e._compareCompletionItems(t,n)},e._compareCompletionItemsSnippetsUp=function(t,n){if(t.completion.kind!==n.completion.kind){if(25===t.completion.kind)return-1;if(25===n.completion.kind)return 1}return e._compareCompletionItems(t,n)},e}()),U=n("80kS"),K=n("NjuD"),q=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),G=function(){function e(){}return e.create=function(t,n){if(!n.getConfiguration().contribInfo.suggest.localityBonus)return Promise.resolve(e.None);if(!n.hasModel())return Promise.resolve(e.None);var i=n.getModel(),o=n.getPosition();return t.canComputeWordRanges(i.uri)?(new K.a).provideSelectionRanges(i,[o]).then(function(s){return s&&0!==s.length&&0!==s[0].length?t.computeWordRanges(i.uri,s[0][0].range).then(function(t){return new(function(e){function i(){return null!==e&&e.apply(this,arguments)||this}return q(i,e),i.prototype.distance=function(e,i){if(!t||!o.equals(n.getPosition()))return 0;if(17===i.kind)return 2<<20;var a=i.label,u=t[a];if(Object(r.m)(u))return 2<<20;for(var l=Object(r.c)(u,c.a.fromPositions(e),c.a.compareRangesUsingStarts),d=l>=0?u[l]:u[Math.max(0,~l-1)],h=s.length,p=0,f=s[0];p0?{triggerKind:2}:{triggerKind:0},this._requestToken=new U.b;var h=this._editor.getConfiguration().contribInfo,p=new Set,f=1;switch(h.suggest.snippets){case"top":f=0;break;case"bottom":f=2;break;case"none":p.add(25)}for(var g in h.suggest.filteredTypes){var _=Object(m.A)(g,!0);void 0!==_&&!1===h.suggest.filteredTypes[g]&&p.add(_)}var v=G.create(this._editorWorker,this._editor),y=Object(R.e)(l,this._editor.getPosition(),new R.a(f,p,n),u,this._requestToken.token);Promise.all([y,v]).then(function(t){var n=t[0],s=t[1];if(Object(a.f)(o._requestToken),0!==o._state&&o._editor.hasModel()){var u=o._editor.getModel();if(Object(r.n)(i)){var l=Object(R.d)(f);n=n.concat(i).sort(l)}var d=new Z(u,o._editor.getPosition(),c,e.shy);o._completionModel=new z(n,o._context.column,{leadingLineContent:d.leadingLineContent,characterCountDelta:d.column-o._context.column},s,o._editor.getConfiguration().contribInfo.suggest);for(var h=0,p=n;hthis._context.column&&this._completionModel.incomplete.size>0&&0!==e.leadingWord.word.length){var t=this._completionModel.incomplete,n=this._completionModel.adopt(t);this.trigger({auto:2===this._state,shy:!1},!0,t,n)}else{var i=this._completionModel.lineContext,o=!1;if(this._completionModel.lineContext={leadingLineContent:e.leadingLineContent,characterCountDelta:e.column-this._context.column},0===this._completionModel.items.length){if(Z.shouldAutoTrigger(this._editor)&&this._context.leadingWord.endColumn0)&&0===e.leadingWord.word.length)return void this.cancel()}this._onDidSuggest.fire({completionModel:this._completionModel,auto:this._context.auto,shy:this._context.shy,isFrozen:o})}}else this.cancel()},e}(),X=(n("YUwp"),n("7/Cv")),J=n("SWdJ"),Q=n("qecS"),$=n("NqM+"),ee=n("3ciN"),te=n("Yqb6"),ne=n("eoic"),ie=n("L5KM"),oe=n("VBCr"),re=n("6TMp"),se=n("GsV8"),ae=n("tpa8"),ue=n("lapT"),le=n("ZYUE"),ce=n("9XyG");function de(e,t,n,i){var o=i===D.ROOT_FOLDER?["rootfolder-icon"]:i===D.FOLDER?["folder-icon"]:["file-icon"];if(n){var r;if(n.scheme===ue.b.data)r=le.a.parseMetaData(n).get(le.a.META_DATA_LABEL);else r=he(Object(le.c)(n).toLowerCase());if(i===D.FOLDER)o.push(r+"-name-folder-icon");else{if(r){o.push(r+"-name-file-icon");for(var s=r.split("."),a=1;a=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},ve=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ye=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},be=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=0&&(l.extraClasses=(l.extraClasses||[]).concat(["deprecated"]),l.matches=[]),o.iconLabel.setLabel(s.label,void 0,l),o.typeLabel.textContent=(s.detail||"").replace(/\n.*$/m,""),Ne(e)?(Object(X.Q)(o.readMore),o.readMore.onmousedown=function(e){e.stopPropagation(),e.preventDefault()},o.readMore.onclick=function(e){e.stopPropagation(),e.preventDefault(),i.widget.toggleDetails()}):(Object(X.D)(o.readMore),o.readMore.onmousedown=null,o.readMore.onclick=null)},e.prototype.disposeTemplate=function(e){e.disposables.dispose()},e=_e([ve(3,pe.a),ve(4,re.a),ve(5,ne.c)],e)}(),Ie=function(){function e(e,t,n,i,o){var r=this;this.widget=t,this.editor=n,this.markdownRenderer=i,this.triggerKeybindingLabel=o,this.borderWidth=1,this.disposables=new a.b,this.el=Object(X.m)(e,Object(X.a)(".details")),this.disposables.add(Object(a.h)(function(){return e.removeChild(r.el)})),this.body=Object(X.a)(".body"),this.scrollbar=new Q.a(this.body,{}),Object(X.m)(this.el,this.scrollbar.getDomNode()),this.disposables.add(this.scrollbar),this.header=Object(X.m)(this.body,Object(X.a)(".header")),this.close=Object(X.m)(this.header,Object(X.a)("span.close")),this.close.title=k.a("readLess","Read less...{0}",this.triggerKeybindingLabel),this.type=Object(X.m)(this.header,Object(X.a)("p.type")),this.docs=Object(X.m)(this.body,Object(X.a)("p.docs")),this.ariaLabel=null,this.configureFont(),W.b.chain(this.editor.onDidChangeConfiguration.bind(this.editor)).filter(function(e){return e.fontInfo}).on(this.configureFont,this,this.disposables),i.onDidRenderCodeBlock(function(){return r.scrollbar.scanDomNode()},this,this.disposables)}return Object.defineProperty(e.prototype,"element",{get:function(){return this.el},enumerable:!0,configurable:!0}),e.prototype.renderLoading=function(){this.type.textContent=k.a("loading","Loading..."),this.docs.textContent=""},e.prototype.renderItem=function(e,t){var n=this;this.renderDisposeable=Object(a.f)(this.renderDisposeable);var i=e.completion,o=i.documentation,r=i.detail;if(t){var s="";s+="score: "+e.score[0]+(e.word?", compared '"+(e.completion.filterText&&e.completion.filterText+" (filterText)"||e.completion.label)+"' with '"+e.word+"'":" (no prefix)")+"\n",s+="distance: "+e.distance+", see localityBonus-setting\n",s+="index: "+e.idx+", based on "+(e.completion.sortText&&'sortText: "'+e.completion.sortText+'"'||"label")+"\n",o=(new ge.a).appendCodeblock("empty",s),r="Provider: "+e.provider._debugDisplayName}if(!t&&!Ne(e))return this.type.textContent="",this.docs.textContent="",Object(X.f)(this.el,"no-docs"),void(this.ariaLabel=null);if(Object(X.I)(this.el,"no-docs"),"string"==typeof o)Object(X.I)(this.docs,"markdown-docs"),this.docs.textContent=o;else{Object(X.f)(this.docs,"markdown-docs"),this.docs.innerHTML="";var u=this.markdownRenderer.render(o);this.renderDisposeable=u,this.docs.appendChild(u.element)}r?(this.type.innerText=r,Object(X.Q)(this.type)):(this.type.innerText="",Object(X.D)(this.type)),this.el.style.height=this.header.offsetHeight+this.docs.offsetHeight+2*this.borderWidth+"px",this.close.onmousedown=function(e){e.preventDefault(),e.stopPropagation()},this.close.onclick=function(e){e.preventDefault(),e.stopPropagation(),n.widget.toggleDetails()},this.body.scrollTop=0,this.scrollbar.scanDomNode(),this.ariaLabel=H.r("{0}{1}",r||"",o?"string"==typeof o?o:o.value:"")},e.prototype.getAriaLabel=function(){return this.ariaLabel},e.prototype.scrollDown=function(e){void 0===e&&(e=8),this.body.scrollTop+=e},e.prototype.scrollUp=function(e){void 0===e&&(e=8),this.body.scrollTop-=e},e.prototype.scrollTop=function(){this.body.scrollTop=0},e.prototype.scrollBottom=function(){this.body.scrollTop=this.body.scrollHeight},e.prototype.pageDown=function(){this.scrollDown(80)},e.prototype.pageUp=function(){this.scrollUp(80)},e.prototype.setBorderWidth=function(e){this.borderWidth=e},e.prototype.configureFont=function(){var e=this.editor.getConfiguration(),t=e.fontInfo.fontFamily,n=e.contribInfo.suggestFontSize||e.fontInfo.fontSize,i=e.contribInfo.suggestLineHeight||e.fontInfo.lineHeight,o=e.fontInfo.fontWeight,r=n+"px",s=i+"px";this.el.style.fontSize=r,this.el.style.fontWeight=o,this.type.style.fontFamily=t,this.close.style.height=s,this.close.style.width=s},e.prototype.dispose=function(){this.disposables.dispose(),this.renderDisposeable=Object(a.f)(this.renderDisposeable)},e}(),De=function(){function e(e,t,n,i,o,r,s,u,l){var c=this;this.editor=e,this.telemetryService=t,this.allowEditorOverflow=!0,this.suppressMouseDown=!0,this.state=null,this.isAuto=!1,this.loadingTimeout=a.a.None,this.currentSuggestionDetails=null,this.ignoreFocusEvents=!1,this.completionModel=null,this.showTimeout=new _.e,this.toDispose=new a.b,this.onDidSelectEmitter=new W.a,this.onDidFocusEmitter=new W.a,this.onDidHideEmitter=new W.a,this.onDidShowEmitter=new W.a,this.onDidSelect=this.onDidSelectEmitter.event,this.onDidFocus=this.onDidFocusEmitter.event,this.onDidHide=this.onDidHideEmitter.event,this.onDidShow=this.onDidShowEmitter.event,this.maxWidgetWidth=660,this.listWidth=330,this.firstFocusInCurrentList=!1,this.preferDocPositionTop=!1,this.docsPositionPreviousWidgetY=null,this.explainMode=!1,this._lastAriaAlertLabel=null;var d=r.lookupKeybinding("editor.action.triggerSuggest"),h=d?" ("+d.getLabel()+")":"",p=this.toDispose.add(new oe.a(e,s,u));this.isAuto=!1,this.focusedItem=null,this.storageService=o,this.element=Object(X.a)(".editor-widget.suggest-widget"),this.toDispose.add(Object(X.h)(this.element,"click",function(e){e.target===c.element&&c.hideWidget()})),this.messageElement=Object(X.m)(this.element,Object(X.a)(".message")),this.listElement=Object(X.m)(this.element,Object(X.a)(".tree")),this.details=l.createInstance(Ie,this.element,this,this.editor,p,h);var f=function(){return Object(X.R)(c.element,"no-icons",!c.editor.getConfiguration().contribInfo.suggest.showIcons)};f();var g=l.createInstance(xe,this,this.editor,h);this.list=new J.b(this.listElement,this,[g],{useShadows:!1,openController:{shouldOpen:function(){return!1}},mouseSupport:!1}),this.toDispose.add(Object(te.b)(this.list,i,{listInactiveFocusBackground:Le,listInactiveFocusOutline:ie.b})),this.toDispose.add(i.onThemeChange(function(e){return c.onThemeChange(e)})),this.toDispose.add(e.onDidLayoutChange(function(){return c.onEditorLayoutChange()})),this.toDispose.add(this.list.onMouseDown(function(e){return c.onListMouseDown(e)})),this.toDispose.add(this.list.onSelectionChange(function(e){return c.onListSelection(e)})),this.toDispose.add(this.list.onFocusChange(function(e){return c.onListFocus(e)})),this.toDispose.add(this.editor.onDidChangeCursorSelection(function(){return c.onCursorSelectionChanged()})),this.toDispose.add(this.editor.onDidChangeConfiguration(function(e){return e.contribInfo&&f()})),this.suggestWidgetVisible=R.b.Visible.bindTo(n),this.suggestWidgetMultipleSuggestions=R.b.MultipleSuggestions.bindTo(n),this.editor.addContentWidget(this),this.setState(0),this.onThemeChange(i.getTheme())}return e.prototype.onCursorSelectionChanged=function(){0!==this.state&&this.editor.layoutContentWidget(this)},e.prototype.onEditorLayoutChange=function(){3!==this.state&&5!==this.state||!this.expandDocsSettingFromStorage()||this.expandSideOrBelow()},e.prototype.onListMouseDown=function(e){void 0!==e.element&&void 0!==e.index&&(e.browserEvent.preventDefault(),e.browserEvent.stopPropagation(),this.select(e.element,e.index))},e.prototype.onListSelection=function(e){e.elements.length&&this.select(e.elements[0],e.indexes[0])},e.prototype.select=function(e,t){var n=this.completionModel;n&&(this.onDidSelectEmitter.fire({item:e,index:t,model:n}),this.editor.focus())},e.prototype._getSuggestionAriaAlertLabel=function(e){return this.expandDocsSettingFromStorage()?k.a("ariaCurrenttSuggestionReadDetails","Item {0}, docs: {1}",e.completion.label,this.details.getAriaLabel()):e.completion.label},e.prototype._ariaAlert=function(e){this._lastAriaAlertLabel!==e&&(this._lastAriaAlertLabel=e,this._lastAriaAlertLabel&&Object(o.a)(this._lastAriaAlertLabel,!0))},e.prototype.onThemeChange=function(e){var t=e.getColor(Ce);t&&(this.listElement.style.backgroundColor=t.toString(),this.details.element.style.backgroundColor=t.toString(),this.messageElement.style.backgroundColor=t.toString());var n=e.getColor(we);n&&(this.listElement.style.borderColor=n.toString(),this.details.element.style.borderColor=n.toString(),this.messageElement.style.borderColor=n.toString(),this.detailsBorderColor=n.toString());var i=e.getColor(ie.S);i&&(this.detailsFocusBorderColor=i.toString()),this.details.setBorderWidth("hc"===e.type?2:1)},e.prototype.onListFocus=function(e){var t=this;if(!this.ignoreFocusEvents){if(!e.elements.length)return this.currentSuggestionDetails&&(this.currentSuggestionDetails.cancel(),this.currentSuggestionDetails=null,this.focusedItem=null),void this._ariaAlert(null);if(this.completionModel){var n=e.elements[0],i=e.indexes[0];this.firstFocusInCurrentList=!this.focusedItem,n!==this.focusedItem&&(this.currentSuggestionDetails&&(this.currentSuggestionDetails.cancel(),this.currentSuggestionDetails=null),this.focusedItem=n,this.list.reveal(i),this.currentSuggestionDetails=Object(_.f)(function(e){return ye(t,void 0,void 0,function(){var t,i,o=this;return be(this,function(r){switch(r.label){case 0:return t=Object(_.g)(function(){return o.showDetails(!0)},250),e.onCancellationRequested(function(){return t.dispose()}),[4,n.resolve(e)];case 1:return i=r.sent(),t.dispose(),[2,i]}})})}),this.currentSuggestionDetails.then(function(){i>=t.list.length||n!==t.list.element(i)||(t.ignoreFocusEvents=!0,t.list.splice(i,1,[n]),t.list.setFocus([i]),t.ignoreFocusEvents=!1,t.expandDocsSettingFromStorage()?t.showDetails(!1):Object(X.I)(t.element,"docs-side"),t._ariaAlert(t._getSuggestionAriaAlertLabel(n)))}).catch(s.e)),this.onDidFocusEmitter.fire({item:n,index:i,model:this.completionModel})}}},e.prototype.setState=function(t){if(this.element){var n=this.state!==t;switch(this.state=t,Object(X.R)(this.element,"frozen",4===t),t){case 0:Object(X.D)(this.messageElement,this.details.element,this.listElement),this.hide(),this.listHeight=0,n&&this.list.splice(0,this.list.length),this.focusedItem=null;break;case 1:this.messageElement.textContent=e.LOADING_MESSAGE,Object(X.D)(this.listElement,this.details.element),Object(X.Q)(this.messageElement),Object(X.I)(this.element,"docs-side"),this.show(),this.focusedItem=null;break;case 2:this.messageElement.textContent=e.NO_SUGGESTIONS_MESSAGE,Object(X.D)(this.listElement,this.details.element),Object(X.Q)(this.messageElement),Object(X.I)(this.element,"docs-side"),this.show(),this.focusedItem=null;break;case 3:case 4:Object(X.D)(this.messageElement),Object(X.Q)(this.listElement),this.show();break;case 5:Object(X.D)(this.messageElement),Object(X.Q)(this.details.element,this.listElement),this.show(),this._ariaAlert(this.details.getAriaLabel())}}},e.prototype.showTriggered=function(e,t){var n=this;0===this.state&&(this.isAuto=!!e,this.isAuto||(this.loadingTimeout=Object(_.g)(function(){return n.setState(1)},t)))},e.prototype.showSuggestions=function(e,t,n,i){if(this.preferDocPositionTop=!1,this.docsPositionPreviousWidgetY=null,this.loadingTimeout.dispose(),this.currentSuggestionDetails&&(this.currentSuggestionDetails.cancel(),this.currentSuggestionDetails=null),this.completionModel!==e&&(this.completionModel=e),n&&2!==this.state&&0!==this.state)this.setState(4);else{var o=this.completionModel.items.length,r=0===o;if(this.suggestWidgetMultipleSuggestions.set(o>1),r)i?this.setState(0):this.setState(2),this.completionModel=null;else{if(3!==this.state){var s=this.completionModel.stats;s.wasAutomaticallyTriggered=!!i,this.telemetryService.publicLog("suggestWidget",me({},s))}this.focusedItem=null,this.list.splice(0,this.list.length,this.completionModel.items),n?this.setState(4):this.setState(3),this.list.reveal(t,0),this.list.setFocus([t]),this.detailsBorderColor&&(this.details.element.style.borderColor=this.detailsBorderColor)}}},e.prototype.selectNextPage=function(){switch(this.state){case 0:return!1;case 5:return this.details.pageDown(),!0;case 1:return!this.isAuto;default:return this.list.focusNextPage(),!0}},e.prototype.selectNext=function(){switch(this.state){case 0:return!1;case 1:return!this.isAuto;default:return this.list.focusNext(1,!0),!0}},e.prototype.selectLast=function(){switch(this.state){case 0:return!1;case 5:return this.details.scrollBottom(),!0;case 1:return!this.isAuto;default:return this.list.focusLast(),!0}},e.prototype.selectPreviousPage=function(){switch(this.state){case 0:return!1;case 5:return this.details.pageUp(),!0;case 1:return!this.isAuto;default:return this.list.focusPreviousPage(),!0}},e.prototype.selectPrevious=function(){switch(this.state){case 0:return!1;case 1:return!this.isAuto;default:return this.list.focusPrevious(1,!0),!1}},e.prototype.selectFirst=function(){switch(this.state){case 0:return!1;case 5:return this.details.scrollTop(),!0;case 1:return!this.isAuto;default:return this.list.focusFirst(),!0}},e.prototype.getFocusedItem=function(){if(0!==this.state&&2!==this.state&&1!==this.state&&this.completionModel)return{item:this.list.getFocusedElements()[0],index:this.list.getFocus()[0],model:this.completionModel}},e.prototype.toggleDetailsFocus=function(){5===this.state?(this.setState(3),this.detailsBorderColor&&(this.details.element.style.borderColor=this.detailsBorderColor)):3===this.state&&this.expandDocsSettingFromStorage()&&(this.setState(5),this.detailsFocusBorderColor&&(this.details.element.style.borderColor=this.detailsFocusBorderColor)),this.telemetryService.publicLog2("suggestWidget:toggleDetailsFocus")},e.prototype.toggleDetails=function(){if(Ne(this.list.getFocusedElements()[0]))if(this.expandDocsSettingFromStorage())this.updateExpandDocsSetting(!1),Object(X.D)(this.details.element),Object(X.I)(this.element,"docs-side"),Object(X.I)(this.element,"docs-below"),this.editor.layoutContentWidget(this),this.telemetryService.publicLog2("suggestWidget:collapseDetails");else{if(3!==this.state&&5!==this.state&&4!==this.state)return;this.updateExpandDocsSetting(!0),this.showDetails(!1),this._ariaAlert(this.details.getAriaLabel()),this.telemetryService.publicLog2("suggestWidget:expandDetails")}},e.prototype.showDetails=function(e){this.expandSideOrBelow(),Object(X.Q)(this.details.element),this.details.element.style.maxHeight=this.maxWidgetHeight+"px",e?this.details.renderLoading():this.details.renderItem(this.list.getFocusedElements()[0],this.explainMode),this.listElement.style.marginTop="0px",this.editor.layoutContentWidget(this),this.adjustDocsPosition(),this.editor.focus()},e.prototype.toggleExplainMode=function(){this.list.getFocusedElements()[0]&&this.expandDocsSettingFromStorage()&&(this.explainMode=!this.explainMode,this.showDetails(!1))},e.prototype.show=function(){var e=this,t=this.updateListHeight();t!==this.listHeight&&(this.editor.layoutContentWidget(this),this.listHeight=t),this.suggestWidgetVisible.set(!0),this.showTimeout.cancelAndSet(function(){Object(X.f)(e.element,"visible"),e.onDidShowEmitter.fire(e)},100)},e.prototype.hide=function(){this.suggestWidgetVisible.reset(),this.suggestWidgetMultipleSuggestions.reset(),Object(X.I)(this.element,"visible")},e.prototype.hideWidget=function(){this.loadingTimeout.dispose(),this.setState(0),this.onDidHideEmitter.fire(this)},e.prototype.getPosition=function(){if(0===this.state)return null;var e=[2,1];return this.preferDocPositionTop&&(e=[1]),{position:this.editor.getPosition(),preference:e}},e.prototype.getDomNode=function(){return this.element},e.prototype.getId=function(){return e.ID},e.prototype.updateListHeight=function(){var e=0;if(2===this.state||1===this.state)e=this.unfocusedHeight;else{var t=this.list.contentHeight/this.unfocusedHeight,n=this.editor.getConfiguration().contribInfo.suggest.maxVisibleSuggestions;e=Math.min(t,n)*this.unfocusedHeight}return this.element.style.lineHeight=this.unfocusedHeight+"px",this.listElement.style.height=e+"px",this.list.layout(e),e},e.prototype.adjustDocsPosition=function(){if(this.editor.hasModel()){var e=this.editor.getConfiguration().fontInfo.lineHeight,t=this.editor.getScrolledVisiblePosition(this.editor.getPosition()),n=Object(X.x)(this.editor.getDomNode()),i=n.left+t.left,o=n.top+t.top+t.height,r=Object(X.x)(this.element),s=r.left,a=r.top;if(this.docsPositionPreviousWidgetY&&this.docsPositionPreviousWidgetYa&&this.details.element.offsetHeight>this.listElement.offsetHeight&&(this.listElement.style.marginTop=this.details.element.offsetHeight-this.listElement.offsetHeight+"px")}},e.prototype.expandSideOrBelow=function(){if(!Ne(this.focusedItem)&&this.firstFocusInCurrentList)return Object(X.I)(this.element,"docs-side"),void Object(X.I)(this.element,"docs-below");var e=this.element.style.maxWidth.match(/(\d+)px/);!e||Number(e[1])=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},Me=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Re=function(e){function t(n,i){var o=e.call(this)||this;return o._editor=n,o._enabled=!1,o._ckAtEnd=t.AtEnd.bindTo(i),o._register(o._editor.onDidChangeConfiguration(function(e){return e.contribInfo&&o._update()})),o._update(),o}return ke(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),Object(a.f)(this._selectionListener),this._ckAtEnd.reset()},t.prototype._update=function(){var e=this,t="on"===this._editor.getConfiguration().contribInfo.tabCompletion;if(this._enabled!==t)if(this._enabled=t,this._enabled){var n=function(){if(e._editor.hasModel()){var t=e._editor.getModel(),n=e._editor.getSelection(),i=t.getWordAtPosition(n.getStartPosition());i?e._ckAtEnd.set(i.endColumn===n.getStartPosition().column):e._ckAtEnd.set(!1)}else e._ckAtEnd.set(!1)};this._selectionListener=this._editor.onDidChangeCursorSelection(n),n()}else this._selectionListener&&(this._ckAtEnd.reset(),this._selectionListener.dispose(),this._selectionListener=void 0)},t.AtEnd=new M.d("atEndOfWord",!1),t=Te([Me(1,M.c)],t)}(a.a),Ae=n("606G"),Pe=n("KIxu"),Fe=n("GfE5"),We=function(){function e(e,t,n){var i=this;this._disposables=new a.b,this._disposables.add(t.onDidShow(function(){return i._onItem(t.getFocusedItem())})),this._disposables.add(t.onDidFocus(this._onItem,this)),this._disposables.add(t.onDidHide(this.reset,this)),this._disposables.add(e.onWillType(function(t){if(i._active){var o=t.charCodeAt(t.length-1);i._active.acceptCharacters.has(o)&&e.getConfiguration().contribInfo.acceptSuggestionOnCommitCharacter&&n(i._active.item)}}))}return e.prototype._onItem=function(e){if(e&&Object(r.n)(e.item.completion.commitCharacters)){if(!this._active||this._active.item.item!==e.item){for(var t=new Fe.b,n=0,i=e.item.completion.commitCharacters;n0&&t.add(o.charCodeAt(0))}this._active={acceptCharacters:t,item:e}}}else this.reset()},e.prototype.reset=function(){this._active=void 0},e.prototype.dispose=function(){this._disposables.dispose()},e}();n.d(t,"SuggestController",function(){return Ke}),n.d(t,"TriggerSuggestAction",function(){return qe});var je=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Ve=this&&this.__assign||function(){return(Ve=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},He=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ze=!1,Ue=function(){function e(e,t){if(this._model=e,this._position=t,e.getLineMaxColumn(t.lineNumber)!==t.column){var n=e.getOffsetAt(t),i=e.getPositionAt(n+1);this._marker=e.deltaDecorations([],[{range:c.a.fromPositions(t,i),options:{stickiness:1}}])}}return e.prototype.dispose=function(){this._marker&&!this._model.isDisposed()&&this._model.deltaDecorations(this._marker,[])},e.prototype.delta=function(e){if(this._model.isDisposed()||this._position.lineNumber!==e.lineNumber)return 0;if(this._marker){var t=this._model.getDecorationRange(this._marker[0]);return this._model.getOffsetAt(t.getStartPosition())-this._model.getOffsetAt(e)}return this._model.getLineMaxColumn(e.lineNumber)-e.column},e}(),Ke=function(){function e(e,t,n,i,o,r){var s=this;this._editor=e,this._memoryService=n,this._commandService=i,this._contextKeyService=o,this._instantiationService=r,this._lineSuffix=new a.d,this._toDispose=new a.b,this._model=new Y(this._editor,t),this._widget=new _.b(function(){var e=s._instantiationService.createInstance(De,s._editor);s._toDispose.add(e),s._toDispose.add(e.onDidSelect(function(e){return s._insertSuggestion(e,!1,!0)},s));var t=new We(s._editor,e,function(e){return s._insertSuggestion(e,!1,!0)});s._toDispose.add(t),s._toDispose.add(s._model.onDidSuggest(function(e){0===e.completionModel.items.length&&t.reset()}));var n=R.b.MakesTextEdit.bindTo(s._contextKeyService);return s._toDispose.add(e.onDidFocus(function(e){var t=e.item,i=s._editor.getPosition(),o=t.completion.range.startColumn,r=i.column,a=!0;"smart"!==s._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter||2!==s._model.state||t.completion.command||t.completion.additionalTextEdits||4&t.completion.insertTextRules||r-o!==t.completion.insertText.length||(a=s._editor.getModel().getValueInRange({startLineNumber:i.lineNumber,startColumn:o,endLineNumber:i.lineNumber,endColumn:r})!==t.completion.insertText);n.set(a)})),s._toDispose.add(Object(a.h)(function(){return n.reset()})),e}),this._alternatives=new _.b(function(){return s._toDispose.add(new F(s._editor,s._contextKeyService))}),this._toDispose.add(r.createInstance(Re,e)),this._toDispose.add(this._model.onDidTrigger(function(e){s._widget.getValue().showTriggered(e.auto,e.shy?250:50),s._lineSuffix.value=new Ue(s._editor.getModel(),e.position)})),this._toDispose.add(this._model.onDidSuggest(function(e){if(!e.shy){var t=s._memoryService.select(s._editor.getModel(),s._editor.getPosition(),e.completionModel.items);s._widget.getValue().showSuggestions(e.completionModel,t,e.isFrozen,e.auto)}})),this._toDispose.add(this._model.onDidCancel(function(e){e.retrigger||s._widget.getValue().hideWidget()})),this._toDispose.add(this._editor.onDidBlurEditorWidget(function(){ze||(s._model.cancel(),s._model.clear())}));var u=R.b.AcceptSuggestionsOnEnter.bindTo(o),l=function(){var e=s._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter;u.set("on"===e||"smart"===e)};this._toDispose.add(this._editor.onDidChangeConfiguration(function(){return l()})),l()}return e.get=function(t){return t.getContribution(e.ID)},e.prototype.getId=function(){return e.ID},e.prototype.dispose=function(){this._alternatives.dispose(),this._toDispose.dispose(),this._widget.dispose(),this._model.dispose(),this._lineSuffix.dispose()},e.prototype._insertSuggestion=function(e,t,n){var i,o=this;if(!e||!e.item)return this._alternatives.getValue().reset(),this._model.cancel(),void this._model.clear();if(this._editor.hasModel()){var r=this._editor.getModel(),a=r.getAlternativeVersionId(),u=e.item,d=u.completion,f=u.position,g=this._editor.getPosition().column-f.column;n&&this._editor.pushUndoStop(),Array.isArray(d.additionalTextEdits)&&this._editor.executeEdits("suggestController.additionalTextEdits",d.additionalTextEdits.map(function(e){return l.a.replace(c.a.lift(e.range),e.text)})),this._memoryService.memorize(r,this._editor.getPosition(),e.item);var m=d.insertText;4&d.insertTextRules||(m=p.c.escape(m));var _=f.column-d.range.startColumn,v=d.range.endColumn-f.column,y=this._lineSuffix.value?this._lineSuffix.value.delta(this._editor.getPosition()):0;h.SnippetController2.get(this._editor).insert(m,{overwriteBefore:_+g,overwriteAfter:v+y,undoStopBefore:!1,undoStopAfter:!1,adjustWhitespace:!(1&d.insertTextRules)}),n&&this._editor.pushUndoStop(),d.command?d.command.id===qe.id?this._model.trigger({auto:!0,shy:!1},!0):((i=this._commandService).executeCommand.apply(i,[d.command.id].concat(d.command.arguments?d.command.arguments.slice():[])).catch(s.e).finally(function(){return o._model.clear()}),this._model.cancel()):(this._model.cancel(),this._model.clear()),t&&this._alternatives.getValue().set(e,function(e){for(;r.canUndo();){a!==r.getAlternativeVersionId()&&r.undo(),o._insertSuggestion(e,!1,!1);break}}),this._alertCompletionItem(e.item)}},e.prototype._alertCompletionItem=function(e){var t=e.completion;if(Object(r.n)(t.additionalTextEdits)){var n=k.a("arai.alert.snippet","Accepting '{0}' made {1} additional edits",t.label,t.additionalTextEdits.length);Object(o.a)(n)}},e.prototype.triggerSuggest=function(e){this._editor.hasModel()&&(this._model.trigger({auto:!1,shy:!1},!1,e),this._editor.revealLine(this._editor.getPosition().lineNumber,0),this._editor.focus())},e.prototype.triggerSuggestAndAcceptBest=function(e){var t=this;if(this._editor.hasModel()){var n=this._editor.getPosition(),i=function(){n.equals(t._editor.getPosition())&&t._commandService.executeCommand(e.fallback)};W.b.once(this._model.onDidTrigger)(function(e){var n=[];W.b.any(t._model.onDidTrigger,t._model.onDidCancel)(function(){Object(a.f)(n),i()},void 0,n),t._model.onDidSuggest(function(e){var o=e.completionModel;if(Object(a.f)(n),0!==o.items.length){var r=t._memoryService.select(t._editor.getModel(),t._editor.getPosition(),o.items),s=o.items[r];!function(e){if(4&e.completion.insertTextRules||e.completion.additionalTextEdits)return!0;var n=t._editor.getPosition(),i=e.completion.range.startColumn,o=n.column;return o-i!==e.completion.insertText.length||t._editor.getModel().getValueInRange({startLineNumber:n.lineNumber,startColumn:i,endLineNumber:n.lineNumber,endColumn:o})!==e.completion.insertText}(s)?i():(t._editor.pushUndoStop(),t._insertSuggestion({index:r,item:s,model:o},!0,!1))}else i()},void 0,n)}),this._model.trigger({auto:!1,shy:!0}),this._editor.revealLine(n.lineNumber,0),this._editor.focus()}},e.prototype.acceptSelectedSuggestion=function(e){var t=this._widget.getValue().getFocusedItem();this._insertSuggestion(t,!!e,!0)},e.prototype.acceptNextSuggestion=function(){this._alternatives.getValue().next()},e.prototype.acceptPrevSuggestion=function(){this._alternatives.getValue().prev()},e.prototype.cancelSuggestWidget=function(){this._model.cancel(),this._model.clear(),this._widget.getValue().hideWidget()},e.prototype.selectNextSuggestion=function(){this._widget.getValue().selectNext()},e.prototype.selectNextPageSuggestion=function(){this._widget.getValue().selectNextPage()},e.prototype.selectLastSuggestion=function(){this._widget.getValue().selectLast()},e.prototype.selectPrevSuggestion=function(){this._widget.getValue().selectPrevious()},e.prototype.selectPrevPageSuggestion=function(){this._widget.getValue().selectPreviousPage()},e.prototype.selectFirstSuggestion=function(){this._widget.getValue().selectFirst()},e.prototype.toggleSuggestionDetails=function(){this._widget.getValue().toggleDetails()},e.prototype.toggleExplainMode=function(){this._widget.getValue().toggleExplainMode()},e.prototype.toggleSuggestionFocus=function(){this._widget.getValue().toggleDetailsFocus()},e.ID="editor.contrib.suggestController",e=Be([He(1,Ae.a),He(2,I),He(3,T.b),He(4,M.c),He(5,v.a)],e)}(),qe=function(e){function t(){return e.call(this,{id:t.id,label:k.a("suggest.trigger.label","Trigger Suggest"),alias:"Trigger Suggest",precondition:M.a.and(d.a.writable,d.a.hasCompletionItemProvider),kbOpts:{kbExpr:d.a.textInputFocus,primary:2058,mac:{primary:266},weight:100}})||this}return je(t,e),t.prototype.run=function(e,t){var n=Ke.get(t);n&&n.triggerSuggest()},t.id="editor.action.triggerSuggest",t}(u.b);Object(u.h)(Ke),Object(u.f)(qe);var Ge=u.c.bindToContribution(Ke.get);Object(u.g)(new Ge({id:"acceptSelectedSuggestion",precondition:R.b.Visible,handler:function(e){return e.acceptSelectedSuggestion(!0)},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2}})),Object(u.g)(new Ge({id:"acceptSelectedSuggestionOnEnter",precondition:R.b.Visible,handler:function(e){return e.acceptSelectedSuggestion(!1)},kbOpts:{weight:190,kbExpr:M.a.and(d.a.textInputFocus,R.b.AcceptSuggestionsOnEnter,R.b.MakesTextEdit),primary:3}})),Object(u.g)(new Ge({id:"hideSuggestWidget",precondition:R.b.Visible,handler:function(e){return e.cancelSuggestWidget()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:9,secondary:[1033]}})),Object(u.g)(new Ge({id:"selectNextSuggestion",precondition:M.a.and(R.b.Visible,R.b.MultipleSuggestions),handler:function(e){return e.selectNextSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:18,secondary:[2066],mac:{primary:18,secondary:[2066,300]}}})),Object(u.g)(new Ge({id:"selectNextPageSuggestion",precondition:M.a.and(R.b.Visible,R.b.MultipleSuggestions),handler:function(e){return e.selectNextPageSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:12,secondary:[2060]}})),Object(u.g)(new Ge({id:"selectLastSuggestion",precondition:M.a.and(R.b.Visible,R.b.MultipleSuggestions),handler:function(e){return e.selectLastSuggestion()}})),Object(u.g)(new Ge({id:"selectPrevSuggestion",precondition:M.a.and(R.b.Visible,R.b.MultipleSuggestions),handler:function(e){return e.selectPrevSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:16,secondary:[2064],mac:{primary:16,secondary:[2064,302]}}})),Object(u.g)(new Ge({id:"selectPrevPageSuggestion",precondition:M.a.and(R.b.Visible,R.b.MultipleSuggestions),handler:function(e){return e.selectPrevPageSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:11,secondary:[2059]}})),Object(u.g)(new Ge({id:"selectFirstSuggestion",precondition:M.a.and(R.b.Visible,R.b.MultipleSuggestions),handler:function(e){return e.selectFirstSuggestion()}})),Object(u.g)(new Ge({id:"toggleSuggestionDetails",precondition:R.b.Visible,handler:function(e){return e.toggleSuggestionDetails()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2058,mac:{primary:266}}})),Object(u.g)(new Ge({id:"toggleExplainMode",precondition:R.b.Visible,handler:function(e){return e.toggleExplainMode()},kbOpts:{weight:100,primary:2133}})),Object(u.g)(new Ge({id:"toggleSuggestionFocus",precondition:R.b.Visible,handler:function(e){return e.toggleSuggestionFocus()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2570,mac:{primary:778}}})),Object(u.g)(new Ge({id:"insertBestCompletion",precondition:M.a.and(M.a.equals("config.editor.tabCompletion","on"),Re.AtEnd,R.b.Visible.toNegated(),F.OtherSuggestions.toNegated(),h.SnippetController2.InSnippetMode.toNegated()),handler:function(e,t){e.triggerSuggestAndAcceptBest(Object(Pe.h)(t)?Ve({fallback:"tab"},t):{fallback:"tab"})},kbOpts:{weight:190,primary:2}})),Object(u.g)(new Ge({id:"insertNextSuggestion",precondition:M.a.and(M.a.equals("config.editor.tabCompletion","on"),F.OtherSuggestions,R.b.Visible.toNegated(),h.SnippetController2.InSnippetMode.toNegated()),handler:function(e){return e.acceptNextSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:2}})),Object(u.g)(new Ge({id:"insertPrevSuggestion",precondition:M.a.and(M.a.equals("config.editor.tabCompletion","on"),F.OtherSuggestions,R.b.Visible.toNegated(),h.SnippetController2.InSnippetMode.toNegated()),handler:function(e){return e.acceptPrevSuggestion()},kbOpts:{weight:190,kbExpr:d.a.textInputFocus,primary:1026}}))},"7g0X":function(e,t,n){"use strict";n.d(t,"a",function(){return a}),n.d(t,"b",function(){return m}),n.d(t,"d",function(){return _}),n.d(t,"c",function(){return v}),n.d(t,"e",function(){return y});var i,o=n("aL7J"),r=n("JVO/"),s=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),a=function(){function e(){}return e.has=function(e){return l.create(e)},e.equals=function(e,t){return c.create(e,t)},e.regex=function(e,t){return p.create(e,t)},e.not=function(e){return h.create(e)},e.and=function(){for(var e=[],t=0;t=0){var n=e.split("!=");return d.create(n[0].trim(),this._deserializeValue(n[1],t))}if(e.indexOf("==")>=0){n=e.split("==");return c.create(n[0].trim(),this._deserializeValue(n[1],t))}if(e.indexOf("=~")>=0){n=e.split("=~");return p.create(n[0].trim(),this._deserializeRegexValue(n[1],t))}return/^\!\s*/.test(e)?h.create(e.substr(1).trim()):l.create(e)},e._deserializeValue=function(e,t){if("true"===(e=e.trim()))return!0;if("false"===e)return!1;var n=/^'([^']*)'$/.exec(e);return n?n[1].trim():e},e._deserializeRegexValue=function(e,t){if(Object(o.u)(e)){if(t)throw new Error("missing regexp-value for =~-expression");return console.warn("missing regexp-value for =~-expression"),null}var n=e.indexOf("/"),i=e.lastIndexOf("/");if(n===i||n<0){if(t)throw new Error("bad regexp-value '"+e+"', missing /-enclosure");return console.warn("bad regexp-value '"+e+"', missing /-enclosure"),null}var r=e.slice(n+1,i),s="i"===e[i+1]?"i":"";try{return new RegExp(r,s)}catch(n){if(t)throw new Error("bad regexp-value '"+e+"', parse error: "+n);return console.warn("bad regexp-value '"+e+"', parse error: "+n),null}},e}();function u(e,t){var n=e.getType(),i=t.getType();if(n!==i)return n-i;switch(n){case 1:case 2:case 3:case 4:case 6:case 7:case 5:return e.cmp(t);default:throw new Error("Unknown ContextKeyExpr!")}}var l=function(){function e(e){this.key=e}return e.create=function(t){return new e(t)},e.prototype.getType=function(){return 1},e.prototype.cmp=function(e){return this.keye.key?1:0},e.prototype.equals=function(t){return t instanceof e&&this.key===t.key},e.prototype.evaluate=function(e){return!!e.getValue(this.key)},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return h.create(this.key)},e}(),c=function(){function e(e,t){this.key=e,this.value=t}return e.create=function(t,n){return"boolean"==typeof n?n?l.create(t):h.create(t):new e(t,n)},e.prototype.getType=function(){return 3},e.prototype.cmp=function(e){return this.keye.key?1:this.valuee.value?1:0},e.prototype.equals=function(t){return t instanceof e&&(this.key===t.key&&this.value===t.value)},e.prototype.evaluate=function(e){return e.getValue(this.key)==this.value},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return d.create(this.key,this.value)},e}(),d=function(){function e(e,t){this.key=e,this.value=t}return e.create=function(t,n){return"boolean"==typeof n?n?h.create(t):l.create(t):new e(t,n)},e.prototype.getType=function(){return 4},e.prototype.cmp=function(e){return this.keye.key?1:this.valuee.value?1:0},e.prototype.equals=function(t){return t instanceof e&&(this.key===t.key&&this.value===t.value)},e.prototype.evaluate=function(e){return e.getValue(this.key)!=this.value},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return c.create(this.key,this.value)},e}(),h=function(){function e(e){this.key=e}return e.create=function(t){return new e(t)},e.prototype.getType=function(){return 2},e.prototype.cmp=function(e){return this.keye.key?1:0},e.prototype.equals=function(t){return t instanceof e&&this.key===t.key},e.prototype.evaluate=function(e){return!e.getValue(this.key)},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return l.create(this.key)},e}(),p=function(){function e(e,t){this.key=e,this.regexp=t}return e.create=function(t,n){return new e(t,n)},e.prototype.getType=function(){return 6},e.prototype.cmp=function(e){if(this.keye.key)return 1;var t=this.regexp?this.regexp.source:"",n=e.regexp?e.regexp.source:"";return tn?1:0},e.prototype.equals=function(t){if(t instanceof e){var n=this.regexp?this.regexp.source:"",i=t.regexp?t.regexp.source:"";return this.key===t.key&&n===i}return!1},e.prototype.evaluate=function(e){var t=e.getValue(this.key);return!!this.regexp&&this.regexp.test(t)},e.prototype.keys=function(){return[this.key]},e.prototype.negate=function(){return f.create(this)},e}(),f=function(){function e(e){this._actual=e}return e.create=function(t){return new e(t)},e.prototype.getType=function(){return 7},e.prototype.cmp=function(e){return this._actual.cmp(e._actual)},e.prototype.equals=function(t){return t instanceof e&&this._actual.equals(t._actual)},e.prototype.evaluate=function(e){return!this._actual.evaluate(e)},e.prototype.keys=function(){return this._actual.keys()},e.prototype.negate=function(){return this._actual},e}(),g=function(){function e(e){this.expr=e}return e.create=function(t){var n=e._normalizeArr(t);if(0!==n.length)return 1===n.length?n[0]:new e(n)},e.prototype.getType=function(){return 5},e.prototype.cmp=function(e){if(this.expr.lengthe.expr.length)return 1;for(var t=0,n=this.expr.length;t1;){for(var s=t.shift(),u=t.shift(),l=[],c=0,d=r(s);c0&&(n._decorations=n._editor.deltaDecorations(n._decorations,[])),n._updateBracketsSoon.schedule()})),n}return v(t,e),t.get=function(e){return e.getContribution(t.ID)},t.prototype.getId=function(){return t.ID},t.prototype.jumpToBracket=function(){if(this._editor.hasModel()){var e=this._editor.getModel(),t=this._editor.getSelections().map(function(t){var n=t.getStartPosition(),i=e.matchBracket(n),o=null;if(i)i[0].containsPosition(n)?o=i[1].getStartPosition():i[1].containsPosition(n)&&(o=i[0].getStartPosition());else{var r=e.findNextBracket(n);r&&r.range&&(o=r.range.getStartPosition())}return o?new c.a(o.lineNumber,o.column,o.lineNumber,o.column):new c.a(n.lineNumber,n.column,n.lineNumber,n.column)});this._editor.setSelections(t),this._editor.revealRange(t[0])}},t.prototype.selectToBracket=function(){if(this._editor.hasModel()){var e=this._editor.getModel(),t=[];this._editor.getSelections().forEach(function(n){var i=n.getStartPosition(),o=e.matchBracket(i),r=null,s=null;if(!o){var a=e.findNextBracket(i);a&&a.range&&(o=e.matchBracket(a.range.getStartPosition()))}o&&(o[0].startLineNumber===o[1].startLineNumber?(r=o[1].startColumn0&&(this._editor.setSelections(t),this._editor.revealRange(t[0]))}},t.prototype._updateBrackets=function(){if(this._matchBrackets){this._recomputeBrackets();for(var e=[],n=0,i=0,o=this._lastBracketsData.length;i1&&o.sort(l.a.compare);var c=[],d=0,h=0,p=n.length;for(s=0,a=o.length;s0&&void 0!==arguments[0]&&arguments[0];var e=[].concat(o()(this.provider));return"sql"===this.lang&&e.push.apply(e,o()(this.sqlHints)),e},registerCustomHintsProvider:function(){var e=this;this.providerDisposeID=r.languages.registerCompletionItemProvider(this.lang,{provideCompletionItems:function(t,n,i){var o=t.getWordUntilPosition(n);return{suggestions:function(e,t,n){n.word;var i=[];return e.length&&(i=e.map(function(e){return{label:e.name,kind:e.type?r.languages.CompletionItemKind[e.type]:r.languages.CompletionItemKind.Function,documentation:e.documentation,insertText:(n=e.name,n),detail:e.detail||"EMQX",range:t};var n})),i}(e.getHints(o),{startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:o.startColumn,endColumn:o.endColumn},o)}},triggerCharacters:[" "]})},registerCustomHoverProvider:function(){var e=this;r.languages.register({id:this.lang}),this.hoverDisposeID=r.languages.registerHoverProvider(this.lang,{provideHover:function(t,n){if(!t.getWordAtPosition(n))return{};var i,o,r,s=t.getWordAtPosition(n).word;return{contents:(i=s,o=e.provider,r=[],o.forEach(function(e){var t=e.name;e.name.match(/\$events\//)&&(t=e.name.split("/")[1].replace('"',"")),i===t&&r.push({value:function(e){var t=e.name,n=e.default,i=e.valueType;return i&&(t=t+": "+i),n?t+", value: "+n:t}(e)},{value:e.documentation})}),r)}}})}},mounted:function(){this.initEditor()},created:function(){var e=this;this.defineTheme(),window.onresize=function(){e.editor&&e.editor.layout()},this.provider.length&&(this.registerCustomHintsProvider(),this.registerCustomHoverProvider())},beforeDestroy:function(){this.editor&&(this.editor.getModel().dispose(),this.editor.dispose(),this.editor=null),this.providerDisposeID&&this.providerDisposeID.dispose(),this.hoverDisposeID&&this.hoverDisposeID.dispose()}},l={render:function(){var e=this.$createElement;return(this._self._c||e)("div",{staticClass:"monaco-view",attrs:{id:"monaco-"+this.id}})},staticRenderFns:[]};var c=n("VU/8")(u,l,!1,function(e){n("1Ccl")},null,null);t.a=c.exports},"9XyG":function(e,t,n){"use strict";n.d(t,"a",function(){return u}),n.d(t,"c",function(){return l}),n.d(t,"b",function(){return c});var i=n("hK2W"),o=n("Kp7x"),r=n("PCC9"),s=n("Fllr"),a=n("RWr8"),u=new(function(){function e(){this._onDidChangeLanguages=new o.a,this.onDidChangeLanguages=this._onDidChangeLanguages.event,this._languages=[],this._dynamicLanguages=[]}return e.prototype.registerLanguage=function(e){this._languages.push(e),this._onDidChangeLanguages.fire(void 0)},e.prototype.getLanguages=function(){return[].concat(this._languages).concat(this._dynamicLanguages)},e}());a.a.add("editor.modesRegistry",u);var l="plaintext",c=new r.p(l,1);u.registerLanguage({id:l,extensions:[".txt",".gitignore"],aliases:[i.a("plainText.alias","Plain Text"),"text"],mimetypes:["text/plain"]}),s.a.register(c,{brackets:[["(",")"],["[","]"],["{","}"]]})},"9bHL":function(e,t,n){"use strict";var i=n("TU7t"),o=n("tqet"),r=n("Bug4"),s=n("7/Cv"),a=n("Kp7x"),u=n("Gxst"),l=n("qecS"),c=n("vbff");function d(e,t){for(var n=[],i=0,o=t;i=r.range.end)){if(e.end=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},w={useShadows:!0,verticalScrollMode:1,setRowLineHeight:!0,supportDynamicHeights:!1,dnd:{getDragElements:function(e){return[e]},getDragURI:function(){return null},onDragStart:function(){},onDragOver:function(){return!1},drop:function(){}},horizontalScrolling:!1},S=function(){function e(e){this.elements=e}return e.prototype.update=function(){},e.prototype.getData=function(){return this.elements},e}(),L=function(){function e(e){this.elements=e}return e.prototype.update=function(){},e.prototype.getData=function(){return this.elements},e}(),O=function(){function e(){this.types=[],this.files=[]}return e.prototype.update=function(e){var t;if(e.types&&(t=this.types).splice.apply(t,[0,this.types.length].concat(e.types)),e.files){this.files.splice(0,this.files.length);for(var n=0;n=this.items.length?(this.rangeMap=new p,this.rangeMap.splice(0,0,_),this.items=_,d=[]):(this.rangeMap.splice(e,t,_),d=(i=this.items).splice.apply(i,[e,t].concat(_)));var v=n.length-t,y=this.getRenderRange(this.lastRenderTop,this.lastRenderHeight),b=h(g,v),C=c.a.intersect(y,b);for(l=C.start;l=-1&&en&&(this.scrollTop+=Math.min(14,Math.floor(.3*(t-n))))}},e.prototype.teardownDragAndDropScrollTopAnimation=function(){this.dragOverAnimationStopDisposable.dispose(),this.dragOverAnimationDisposable&&(this.dragOverAnimationDisposable.dispose(),this.dragOverAnimationDisposable=void 0)},e.prototype.getItemIndexFromEventTarget=function(e){for(var t=e;t instanceof HTMLElement&&t!==this.rowsContainer;){var n=t.getAttribute("data-index");if(n){var i=Number(n);if(!isNaN(i))return i}t=t.parentElement}},e.prototype.getRenderRange=function(e,t){return{start:this.rangeMap.indexAt(e),end:this.rangeMap.indexAfter(e+t-1)}},e.prototype._rerender=function(e,t){var n,i,o=this.getRenderRange(e,t);e===this.elementTop(o.start)?(n=o.start,i=0):o.end-o.start>1&&(n=o.start+1,i=this.elementTop(n)-e);for(var r=0;;){for(var s=this.getRenderRange(e,t),a=!1,u=s.start;u0?(i=t?(i+1)%o:(i+o-1)%o,n.children[i]):(i=n.parent.groups.indexOf(n),t?(i=(i+1)%r,n.parent.groups[i].children[0]):(i=(i+r-1)%r,n.parent.groups[i].children[n.parent.groups[i].children.length-1]))},e.prototype.nearestReference=function(e,t){var n=this.references.map(function(n,i){return{idx:i,prefixLen:a.b(n.uri.toString(),e.toString()),offsetDist:100*Math.abs(n.range.startLineNumber-t.lineNumber)+Math.abs(n.range.startColumn-t.column)}}).sort(function(e,t){return e.prefixLen>t.prefixLen?-1:e.prefixLent.offsetDist?1:0})[0];if(n)return this.references[n.idx]},e.prototype.firstReference=function(){for(var e=0,t=this.references;ei?1:l.a.compareRangesUsingStarts(e.range,t.range)},e}()},"9vcT":function(e,t){},AKCZ:function(e,t,n){"use strict";n.d(t,"a",function(){return l}),n.d(t,"b",function(){return c});var i,o=n("tqet"),r=n("Kp7x"),s=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),a=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},u=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]0?n.actionBar.push(r,{icon:!0,label:!1}):n.actionBar.isEmpty()||r&&0!==r.length||n.actionBar.clear(),e instanceof y&&e.getGroupLabel()?u.f(n.container,"has-group-label"):u.I(n.container,"has-group-label"),e instanceof y){var s=e,a=n;s.showBorder()?(u.f(a.container,"results-group-separator"),i.pickerGroupBorder&&(a.container.style.borderTopColor=i.pickerGroupBorder.toString())):(u.I(a.container,"results-group-separator"),a.container.style.borderTopColor=null);var l=s.getGroupLabel()||"";a.group&&(a.group.textContent=l,i.pickerGroupForeground&&(a.group.style.color=i.pickerGroupForeground.toString()))}if(e instanceof v){var c=e.getHighlights(),d=c[0],h=c[1],p=c[2],f=e.getIcon()?"quick-open-entry-icon "+e.getIcon():"";n.icon.className=f;var g=e.getLabelOptions()||Object.create(null);g.matches=d||[],g.title=e.getTooltip(),g.descriptionTitle=e.getDescriptionTooltip()||e.getDescription(),g.descriptionMatches=h||[],n.label.setLabel(o.m(e.getLabel()),e.getDescription(),g),n.detail.set(e.getDetail(),p),n.keybinding.set(e.getKeybinding())}},e.prototype.disposeTemplate=function(e,t){t.actionBar.dispose(),t.actionBar=null,t.container=null,t.entry=null,t.keybinding=null,t.detail=null,t.group=null,t.icon=null,t.label.dispose(),t.label=null},e}(),w=function(){function e(e,t){void 0===e&&(e=[]),void 0===t&&(t=new b),this._entries=e,this._dataSource=this,this._renderer=new C(t),this._filter=this,this._runner=this,this._accessibilityProvider=this}return Object.defineProperty(e.prototype,"entries",{get:function(){return this._entries},set:function(e){this._entries=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dataSource",{get:function(){return this._dataSource},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderer",{get:function(){return this._renderer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filter",{get:function(){return this._filter},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"runner",{get:function(){return this._runner},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"accessibilityProvider",{get:function(){return this._accessibilityProvider},enumerable:!0,configurable:!0}),e.prototype.getId=function(e){return e.getId()},e.prototype.getLabel=function(e){return o.n(e.getLabel())},e.prototype.getAriaLabel=function(e){return e.getAriaLabel()?i.a("quickOpenAriaLabelEntry","{0}, picker",e.getAriaLabel()):i.a("quickOpenAriaLabel","picker")},e.prototype.isVisible=function(e){return!e.isHidden()},e.prototype.run=function(e,t,n){return e.run(t,n)},e}()},Ao9X:function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"d",function(){return r}),n.d(t,"c",function(){return s}),n.d(t,"b",function(){return a});var i=n("iHM7"),o=function(){function e(e,t,n){void 0===n&&(n=!1),this._range=e,this._text=t,this.insertsAutoWhitespace=n}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._range,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return new i.a(n.endLineNumber,n.endColumn,n.endLineNumber,n.endColumn)},e}(),r=function(){function e(e,t,n){void 0===n&&(n=!1),this._range=e,this._text=t,this.insertsAutoWhitespace=n}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._range,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return new i.a(n.startLineNumber,n.startColumn,n.startLineNumber,n.startColumn)},e}(),s=function(){function e(e,t,n,i,o){void 0===o&&(o=!1),this._range=e,this._text=t,this._columnDeltaOffset=i,this._lineNumberDeltaOffset=n,this.insertsAutoWhitespace=o}return e.prototype.getEditOperations=function(e,t){t.addTrackedEditOperation(this._range,this._text)},e.prototype.computeCursorState=function(e,t){var n=t.getInverseEditOperations()[0].range;return new i.a(n.endLineNumber+this._lineNumberDeltaOffset,n.endColumn+this._columnDeltaOffset,n.endLineNumber+this._lineNumberDeltaOffset,n.endColumn+this._columnDeltaOffset)},e}(),a=function(){function e(e,t,n){this._range=e,this._text=t,this._initialSelection=n,this._selectionId=null}return e.prototype.getEditOperations=function(e,t){t.addEditOperation(this._range,this._text),this._selectionId=t.trackSelection(this._initialSelection)},e.prototype.computeCursorState=function(e,t){return t.getTrackedSelection(this._selectionId)},e}()},"B/Xy":function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("JVO/"),o=Object(i.c)("textModelService")},Bug4:function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"b",function(){return d});var i,o,r=n("X6iQ"),s=n("tqet"),a=n("7/Cv"),u=n("2VYG"),l=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),c=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s};!function(e){e.Tap="-monaco-gesturetap",e.Change="-monaco-gesturechange",e.Start="-monaco-gesturestart",e.End="-monaco-gesturesend",e.Contextmenu="-monaco-gesturecontextmenu"}(o||(o={}));var d=function(e){function t(){var t=e.call(this)||this;return t.dispatched=!1,t.activeTouches={},t.handle=null,t.targets=[],t._register(a.h(document,"touchstart",function(e){return t.onTouchStart(e)})),t._register(a.h(document,"touchend",function(e){return t.onTouchEnd(e)})),t._register(a.h(document,"touchmove",function(e){return t.onTouchMove(e)})),t}return l(t,e),t.addTarget=function(e){t.isTouchDevice()&&(t.INSTANCE||(t.INSTANCE=new t),t.INSTANCE.targets.push(e))},t.isTouchDevice=function(){return"ontouchstart"in window||navigator.maxTouchPoints>0||window.navigator.msMaxTouchPoints>0},t.prototype.dispose=function(){this.handle&&(this.handle.dispose(),this.handle=null),e.prototype.dispose.call(this)},t.prototype.onTouchStart=function(e){var t=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(var n=0,i=e.targetTouches.length;n=t.HOLD_DELAY&&Math.abs(c.initialPageX-r.s(c.rollingPageX))<30&&Math.abs(c.initialPageY-r.s(c.rollingPageY))<30){var h;(h=a.newGestureEvent(o.Contextmenu,c.initialTarget)).pageX=r.s(c.rollingPageX),h.pageY=r.s(c.rollingPageY),a.dispatchEvent(h)}else if(1===i){var p=r.s(c.rollingPageX),f=r.s(c.rollingPageY),g=r.s(c.rollingTimestamps)-c.rollingTimestamps[0],m=p-c.rollingPageX[0],_=f-c.rollingPageY[0],v=a.targets.filter(function(e){return c.initialTarget instanceof Node&&e.contains(c.initialTarget)});a.inertia(v,n,Math.abs(m)/g,m>0?1:-1,p,Math.abs(_)/g,_>0?1:-1,f)}a.dispatchEvent(a.newGestureEvent(o.End,c.initialTarget)),delete a.activeTouches[l.identifier]},a=this,u=0,l=e.changedTouches.length;u0&&(g=!1,p=r*i*h),u>0&&(g=!1,f=l*u*h);var m=d.newGestureEvent(o.Change);m.translationX=p,m.translationY=f,e.forEach(function(e){return e.dispatchEvent(m)}),g||d.inertia(e,a,i,r,s+p,u,l,c+f)})},t.prototype.onTouchMove=function(e){for(var t=Date.now(),n=0,i=e.changedTouches.length;n3&&(a.rollingPageX.shift(),a.rollingPageY.shift(),a.rollingTimestamps.shift()),a.rollingPageX.push(s.pageX),a.rollingPageY.push(s.pageY),a.rollingTimestamps.push(t)}else console.warn("end of an UNKNOWN touch",s)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)},t.SCROLL_FRICTION=-.005,t.HOLD_DELAY=700,c([u.a],t,"isTouchDevice",null),t}(s.a)},Bv73:function(e,t){},BwcV:function(e,t,n){"use strict";n.d(t,"a",function(){return l});var i,o=n("GfE5"),r=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=function(e){function t(t){for(var n=e.call(this,0)||this,i=0,o=t.length;i=0){for(var i=[],o=0,r=this._placeholderGroups[this._placeholderGroupsIdx];o0&&this._editor.executeEdits("snippet.placeholderTransform",i)}var d=!1;!0===t&&this._placeholderGroupsIdx0&&(this._placeholderGroupsIdx-=1,d=!0);var h=this._editor.getModel().changeDecorations(function(t){for(var i=new Set,o=[],r=0,s=n._placeholderGroups[n._placeholderGroupsIdx];r0)return!0}t=t.parent}return!1},Object.defineProperty(e.prototype,"isAtFirstPlaceholder",{get:function(){return this._placeholderGroupsIdx<=0||0===this._placeholderGroups.length},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAtLastPlaceholder",{get:function(){return this._placeholderGroupsIdx===this._placeholderGroups.length-1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasPlaceholder",{get:function(){return this._snippet.placeholders.length>0},enumerable:!0,configurable:!0}),e.prototype.computePossibleSelections=function(){for(var e=new Map,t=0,n=this._placeholderGroups;t0&&S!==d.getLineFirstNonWhitespaceColumn(F.positionLineNumber))&&e.adjustWhitespace(d,z,H),H.resolveVariables(new L([f,new N(u,W,k.length),new O(d,F),new x(d),new I,new D(h)]));var U=d.getOffsetAt(z)+b;b+=H.toString().length-d.getValueLengthInRange(B),l[W]=p.a.replace(B,H.toString()),c[W]=new R(t,H,U)}return{edits:l,snippets:c}},e.prototype.dispose=function(){Object(i.f)(this._snippets)},e.prototype._logInfo=function(){return'template="'+this._template+'", merged_templates="'+this._templateMerges.join(" -> ")+'"'},e.prototype.insert=function(){var t=this;if(this._editor.hasModel()){var n=e.createEditsAndSnippets(this._editor,this._template,this._options.overwriteBefore,this._options.overwriteAfter,!1,this._options.adjustWhitespace,this._options.clipboardText),i=n.edits,o=n.snippets;this._snippets=o,this._editor.executeEdits("snippet",i,function(e){return t._snippets[0].hasPlaceholder?t._move(!0):e.map(function(e){return a.a.fromPositions(e.range.getEndPosition())})}),this._editor.revealRange(this._editor.getSelections()[0])}},e.prototype.merge=function(t,n){var i=this;if(void 0===n&&(n=A),this._editor.hasModel()){this._templateMerges.push([this._snippets[0]._nestingLevel,this._snippets[0]._placeholderGroupsIdx,t]);var o=e.createEditsAndSnippets(this._editor,t,n.overwriteBefore,n.overwriteAfter,!0,n.adjustWhitespace,n.clipboardText),r=o.edits,s=o.snippets;this._editor.executeEdits("snippet",r,function(e){for(var t=0,n=i._snippets;t0},e}();n.d(t,"SnippetController2",function(){return B});var F=this&&this.__assign||function(){return(F=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},j=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},V={overwriteBefore:0,overwriteAfter:0,undoStopBefore:!0,undoStopAfter:!0,adjustWhitespace:!0,clipboardText:void 0},B=function(){function e(t,n,o){this._editor=t,this._logService=n,this._snippetListener=new i.b,this._modelVersionId=-1,this._inSnippet=e.InSnippetMode.bindTo(o),this._hasNextTabstop=e.HasNextTabstop.bindTo(o),this._hasPrevTabstop=e.HasPrevTabstop.bindTo(o)}return e.get=function(e){return e.getContribution("snippetController2")},e.prototype.dispose=function(){this._inSnippet.reset(),this._hasPrevTabstop.reset(),this._hasNextTabstop.reset(),Object(i.f)(this._session),this._snippetListener.dispose()},e.prototype.getId=function(){return"snippetController2"},e.prototype.insert=function(e,t){try{this._doInsert(e,void 0===t?V:F({},V,t))}catch(t){this.cancel(),this._logService.error(t),this._logService.error("snippet_error"),this._logService.error("insert_template=",e),this._logService.error("existing_template=",this._session?this._session._logInfo():"")}},e.prototype._doInsert=function(e,t){var n=this;this._editor.hasModel()&&(this._snippetListener.clear(),t.undoStopBefore&&this._editor.getModel().pushStackElement(),this._session?this._session.merge(e,t):(this._modelVersionId=this._editor.getModel().getAlternativeVersionId(),this._session=new P(this._editor,e,t),this._session.insert()),t.undoStopAfter&&this._editor.getModel().pushStackElement(),this._updateState(),this._snippetListener.add(this._editor.onDidChangeModelContent(function(e){return e.isFlush&&n.cancel()})),this._snippetListener.add(this._editor.onDidChangeModel(function(){return n.cancel()})),this._snippetListener.add(this._editor.onDidChangeCursorSelection(function(){return n._updateState()})))},e.prototype._updateState=function(){if(this._session&&this._editor.hasModel()){if(this._modelVersionId===this._editor.getModel().getAlternativeVersionId())return this.cancel();if(!this._session.hasPlaceholder)return this.cancel();if(this._session.isAtLastPlaceholder||!this._session.isSelectionWithinPlaceholders())return this.cancel();this._inSnippet.set(!0),this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder),this._hasNextTabstop.set(!this._session.isAtLastPlaceholder),this._handleChoice()}},e.prototype._handleChoice=function(){var e=this;if(this._session&&this._editor.hasModel()){var t=this._session.choice;if(t){if(this._currentChoice!==t){this._currentChoice=t,this._editor.setSelections(this._editor.getSelections().map(function(e){return a.a.fromPositions(e.getStartPosition())}));var n=t.options[0];Object(l.f)(this._editor,t.options.map(function(t,i){return{kind:13,label:t.value,insertText:t.value,sortText:Object(o.F)("a",i+1),range:s.a.fromPositions(e._editor.getPosition(),e._editor.getPosition().delta(0,n.value.length))}}))}}else this._currentChoice=void 0}else this._currentChoice=void 0},e.prototype.finish=function(){for(;this._inSnippet.get();)this.next()},e.prototype.cancel=function(e){void 0===e&&(e=!1),this._inSnippet.reset(),this._hasPrevTabstop.reset(),this._hasNextTabstop.reset(),this._snippetListener.clear(),Object(i.f)(this._session),this._session=void 0,this._modelVersionId=-1,e&&this._editor.setSelections([this._editor.getSelection()])},e.prototype.prev=function(){this._session&&this._session.prev(),this._updateState()},e.prototype.next=function(){this._session&&this._session.next(),this._updateState()},e.prototype.isInSnippet=function(){return Boolean(this._inSnippet.get())},e.InSnippetMode=new c.d("inSnippetMode",!1),e.HasNextTabstop=new c.d("hasNextTabstop",!1),e.HasPrevTabstop=new c.d("hasPrevTabstop",!1),e=W([j(1,d.a),j(2,c.c)],e)}();Object(r.h)(B);var H=r.c.bindToContribution(B.get);Object(r.g)(new H({id:"jumpToNextSnippetPlaceholder",precondition:c.a.and(B.InSnippetMode,B.HasNextTabstop),handler:function(e){return e.next()},kbOpts:{weight:130,kbExpr:u.a.editorTextFocus,primary:2}})),Object(r.g)(new H({id:"jumpToPrevSnippetPlaceholder",precondition:c.a.and(B.InSnippetMode,B.HasPrevTabstop),handler:function(e){return e.prev()},kbOpts:{weight:130,kbExpr:u.a.editorTextFocus,primary:1026}})),Object(r.g)(new H({id:"leaveSnippet",precondition:B.InSnippetMode,handler:function(e){return e.cancel(!0)},kbOpts:{weight:130,kbExpr:u.a.editorTextFocus,primary:9,secondary:[1033]}})),Object(r.g)(new H({id:"acceptSnippet",precondition:B.InSnippetMode,handler:function(e){return e.finish()}}))},C3c5:function(e,t,n){"use strict";t.e=h,n.d(t,"a",function(){return p}),n.d(t,"c",function(){return f}),n.d(t,"d",function(){return m}),n.d(t,"b",function(){return _});var i,o=n("AKCZ"),r=n("JVO/"),s=n("7g0X"),a=n("ItKl"),u=n("Kp7x"),l=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),c=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},d=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}};function h(e){return void 0!==e.command}var p=Object(r.c)("menuService"),f=new(function(){function e(){this._commands=new Map,this._menuItems=new Map,this._onDidChangeMenu=new u.a,this.onDidChangeMenu=this._onDidChangeMenu.event}return e.prototype.addCommand=function(e){var t=this;return this._commands.set(e.id,e),this._onDidChangeMenu.fire(0),{dispose:function(){t._commands.delete(e.id)&&t._onDidChangeMenu.fire(0)}}},e.prototype.getCommand=function(e){return this._commands.get(e)},e.prototype.getCommands=function(){var e=new Map;return this._commands.forEach(function(t,n){return e.set(n,t)}),e},e.prototype.appendMenuItem=function(e,t){var n=this,i=this._menuItems.get(e);return i?i.push(t):(i=[t],this._menuItems.set(e,i)),this._onDidChangeMenu.fire(e),{dispose:function(){var o=i.indexOf(t);o>=0&&(i.splice(o,1),n._onDidChangeMenu.fire(e))}}},e.prototype.getMenuItems=function(e){var t=(this._menuItems.get(e)||[]).slice(0);return 0===e&&this._appendImplicitItems(t),t},e.prototype._appendImplicitItems=function(e){for(var t=new Set,n=0,i=e.filter(function(e){return h(e)});n=0;o--){var r=e.charCodeAt(o),s=t.get(r);if(0===s){if(2===i)return this._createWord(e,i,s,o+1,this._findEndOfWord(e,t,i,o+1));i=1}else if(2===s){if(1===i)return this._createWord(e,i,s,o+1,this._findEndOfWord(e,t,i,o+1));i=2}else if(1===s&&0!==i)return this._createWord(e,i,s,o+1,this._findEndOfWord(e,t,i,o+1))}return 0!==i?this._createWord(e,i,1,0,this._findEndOfWord(e,t,i,0)):null},e._findEndOfWord=function(e,t,n,i){for(var o=e.length,r=i;r=0;o--){var r=e.charCodeAt(o),s=t.get(r);if(1===s)return o+1;if(1===n&&2===s)return o+1;if(2===n&&0===s)return o+1}return 0},e.moveWordLeft=function(t,n,i,o){var r=i.lineNumber,s=i.column,u=!1;1===s&&r>1&&(u=!0,r-=1,s=n.getLineMaxColumn(r));var l=e._findPreviousWordOnLine(t,n,new a.a(r,s));if(0===o){if(l&&!u)if(n.getLineLastNonWhitespaceColumn(r)1?new a.a(n-1,e.getLineMaxColumn(n-1)):t;for(var r=e.getLineContent(n),s=t.column-1;s>1;s--){var u=r.charCodeAt(s-2),l=r.charCodeAt(s-1);if(95!==u&&95===l)return new a.a(n,s);if(o.y(u)&&o.z(l))return new a.a(n,s);if(o.z(u)&&o.z(l)&&s+1=l.start+1&&(l=e._findNextWordOnLine(t,n,new a.a(r,l.end+1))),s=l?l.start+1:n.getLineMaxColumn(r);return new a.a(r,s)},e._moveWordPartRight=function(e,t){var n=t.lineNumber,i=e.getLineMaxColumn(n);if(t.column===i)return n1?c=1:(l--,c=n.getLineMaxColumn(l)):(h&&c<=h.end+1&&(h=e._findPreviousWordOnLine(t,n,new a.a(l,h.start+1))),h?c=h.end+1:c>1?c=1:(l--,c=n.getLineMaxColumn(l))),new u.a(l,c,s.lineNumber,s.column)},e._deleteWordPartLeft=function(t,n){if(!n.isEmpty())return n;var i=n.getPosition(),o=e._moveWordPartLeft(t,i);return new u.a(i.lineNumber,i.column,o.lineNumber,o.column)},e._findFirstNonWhitespaceChar=function(e,t){for(var n=e.length,i=t;i=f.start+1&&(f=e._findNextWordOnLine(t,n,new a.a(l,f.end+1))),f?c=f.start+1:c255)return 255;return 0|e},t.b=o,t.c=function(e){for(var t=e.length,n=new Uint32Array(t),i=0;i4294967295?4294967295:0|e}},CX1u:function(e,t,n){"use strict";t.c=function(e,t){void 0===t&&(t={});var n=o(t);return n.textContent=e,n},t.b=function(e,t){void 0===t&&(t={});var n=o(t);return function e(t,n,o){var r;if(2===n.type)r=document.createTextNode(n.content||"");else if(3===n.type)r=document.createElement("b");else if(4===n.type)r=document.createElement("i");else if(5===n.type&&o){var s=document.createElement("a");s.href="#",o.disposeables.add(i.k(s,"click",function(e){o.callback(String(n.index),e)})),r=s}else 7===n.type?r=document.createElement("br"):1===n.type&&(r=t);r&&t!==r&&t.appendChild(r),r&&Array.isArray(n.children)&&n.children.forEach(function(t){e(r,t,o)})}(n,function(e){for(var t={type:1,children:[]},n=0,i=t,o=[],a=new r(e);!a.eos();){var u=a.next(),l="\\"===u&&0!==s(a.peek());if(l&&(u=a.next()),l||0===s(u)||u!==a.peek())if("\n"===u)2===i.type&&(i=o.pop()),i.children.push({type:7});else if(2!==i.type){var c={type:2,content:u};i.children.push(c),o.push(i),i=c}else i.content+=u;else{a.advance(),2===i.type&&(i=o.pop());var d=s(u);if(i.type===d||5===i.type&&6===d)i=o.pop();else{var h={type:d,children:[]};5===d&&(h.index=n,n++),i.children.push(h),o.push(i),i=h}}}return 2===i.type&&(i=o.pop()),o.length,t}(e),t.actionHandler),n},t.a=o;var i=n("7/Cv");function o(e){var t=e.inline?"span":"div",n=document.createElement(t);return e.className&&(n.className=e.className),n}var r=function(){function e(e){this.source=e,this.index=0}return e.prototype.eos=function(){return this.index>=this.source.length},e.prototype.next=function(){var e=this.peek();return this.advance(),e},e.prototype.peek=function(){return this.source[this.index]},e.prototype.advance=function(){this.index++},e}();function s(e){switch(e){case"*":return 3;case"_":return 4;case"[":return 5;case"]":return 6;default:return 0}}},Cfmk:function(e,t,n){"use strict";n.d(t,"a",function(){return c}),n.d(t,"c",function(){return o}),n.d(t,"b",function(){return d});var i,o,r=n("JVO/"),s=n("Kp7x"),a=n("tqet"),u=n("KIxu"),l=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),c=Object(r.c)("storageService");!function(e){e[e.NONE=0]="NONE",e[e.SHUTDOWN=1]="SHUTDOWN"}(o||(o={}));var d=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._serviceBrand=null,t._onDidChangeStorage=t._register(new s.a),t.onDidChangeStorage=t._onDidChangeStorage.event,t.onWillSaveState=s.b.None,t.globalCache=new Map,t.workspaceCache=new Map,t}return l(t,e),t.prototype.getCache=function(e){return 0===e?this.globalCache:this.workspaceCache},t.prototype.get=function(e,t,n){var i=this.getCache(t).get(e);return Object(u.k)(i)?n:i},t.prototype.getBoolean=function(e,t,n){var i=this.getCache(t).get(e);return Object(u.k)(i)?n:"true"===i},t.prototype.store=function(e,t,n){if(Object(u.k)(t))return this.remove(e,n);var i=String(t);return this.getCache(n).get(e)===i?Promise.resolve():(this.getCache(n).set(e,i),this._onDidChangeStorage.fire({scope:n,key:e}),Promise.resolve())},t.prototype.remove=function(e,t){return this.getCache(t).delete(e)?(this._onDidChangeStorage.fire({scope:t,key:e}),Promise.resolve()):Promise.resolve()},t}(a.a)},Crnc:function(e,t,n){"use strict";n.d(t,"a",function(){return a});var i=!1,o=null;function r(e){if(!e.parent||e.parent===e)return null;try{var t=e.location,n=e.parent.location;if(t.protocol!==n.protocol||t.hostname!==n.hostname||t.port!==n.port)return i=!0,null}catch(e){return i=!0,null}return e.parent}function s(e,t){for(var n,i=e.document.getElementsByTagName("iframe"),o=0,r=i.length;o=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},m=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},_=function(e){function t(n,i){var o=e.call(this)||this;return o.closeTimeout=3e3,o._messageWidget=o._register(new a.d),o._messageListeners=o._register(new a.b),o._editor=n,o._visible=t.MESSAGE_VISIBLE.bindTo(i),o._register(o._editor.onDidAttemptReadOnlyEdit(function(){return o._onDidAttemptReadOnlyEdit()})),o}return f(t,e),t.get=function(e){return e.getContribution(t._id)},t.prototype.getId=function(){return t._id},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._visible.reset()},t.prototype.showMessage=function(e,t){var n,i=this;Object(u.a)(e),this._visible.set(!0),this._messageWidget.clear(),this._messageListeners.clear(),this._messageWidget.value=new y(this._editor,t,e),this._messageListeners.add(this._editor.onDidBlurEditorText(function(){return i.closeMessage()})),this._messageListeners.add(this._editor.onDidChangeCursorPosition(function(){return i.closeMessage()})),this._messageListeners.add(this._editor.onDidDispose(function(){return i.closeMessage()})),this._messageListeners.add(this._editor.onDidChangeModel(function(){return i.closeMessage()})),this._messageListeners.add(new s.e(function(){return i.closeMessage()},this.closeTimeout)),this._messageListeners.add(this._editor.onMouseMove(function(e){e.target.position&&(n?n.containsPosition(e.target.position)||i.closeMessage():n=new l.a(t.lineNumber-3,1,e.target.position.lineNumber+3,1))}))},t.prototype.closeMessage=function(){this._visible.reset(),this._messageListeners.clear(),this._messageWidget.value&&this._messageListeners.add(y.fadeOut(this._messageWidget.value))},t.prototype._onDidAttemptReadOnlyEdit=function(){this._editor.hasModel()&&this.showMessage(r.a("editor.readonly","Cannot edit in read-only editor"),this._editor.getPosition())},t._id="editor.contrib.messageController",t.MESSAGE_VISIBLE=new d.d("messageVisible",!1),t=g([m(1,d.c)],t)}(a.a),v=c.c.bindToContribution(_.get);Object(c.g)(new v({id:"leaveEditorMessage",precondition:_.MESSAGE_VISIBLE,handler:function(e){return e.closeMessage()},kbOpts:{weight:130,primary:9}}));var y=function(){function e(e,t,n){var i=t.lineNumber,o=t.column;this.allowEditorOverflow=!0,this.suppressMouseDown=!1,this._editor=e,this._editor.revealLinesInCenterIfOutsideViewport(i,i,0),this._position={lineNumber:i,column:o-1},this._domNode=document.createElement("div"),this._domNode.classList.add("monaco-editor-overlaymessage");var r=document.createElement("div");r.classList.add("message"),r.textContent=n,this._domNode.appendChild(r);var s=document.createElement("div");s.classList.add("anchor"),this._domNode.appendChild(s),this._editor.addContentWidget(this),this._domNode.classList.add("fadeIn")}return e.fadeOut=function(e){var t,n=function(){e.dispose(),clearTimeout(t),e.getDomNode().removeEventListener("animationend",n)};return t=setTimeout(n,110),e.getDomNode().addEventListener("animationend",n),e.getDomNode().classList.add("fadeOut"),{dispose:n}},e.prototype.dispose=function(){this._editor.removeContentWidget(this)},e.prototype.getId=function(){return"messageoverlay"},e.prototype.getDomNode=function(){return this._domNode},e.prototype.getPosition=function(){return{position:this._position,preference:[1]}},e}();Object(c.h)(_),Object(h.f)(function(e,t){var n=e.getColor(p._3);if(n){var i=e.type===h.b?2:1;t.addRule(".monaco-editor .monaco-editor-overlaymessage .anchor { border-top-color: "+n+"; }"),t.addRule(".monaco-editor .monaco-editor-overlaymessage .message { border: "+i+"px solid "+n+"; }")}var o=e.getColor(p._2);o&&t.addRule(".monaco-editor .monaco-editor-overlaymessage .message { background-color: "+o+"; }");var r=e.getColor(p._4);r&&t.addRule(".monaco-editor .monaco-editor-overlaymessage .message { color: "+r+"; }")})},D2uo:function(e,t,n){"use strict";var i,o;n.d(t,"d",function(){return i}),n.d(t,"c",function(){return o}),n.d(t,"e",function(){return r}),n.d(t,"b",function(){return s}),n.d(t,"a",function(){return a}),function(e){e[e.Left=1]="Left",e[e.Center=2]="Center",e[e.Right=4]="Right",e[e.Full=7]="Full"}(i||(i={})),function(e){e[e.Inline=1]="Inline"}(o||(o={}));var r=function(){function e(e){this.tabSize=0|e.tabSize,this.indentSize=0|e.tabSize,this.insertSpaces=Boolean(e.insertSpaces),this.defaultEOL=0|e.defaultEOL,this.trimAutoWhitespace=Boolean(e.trimAutoWhitespace)}return e.prototype.equals=function(e){return this.tabSize===e.tabSize&&this.indentSize===e.indentSize&&this.insertSpaces===e.insertSpaces&&this.defaultEOL===e.defaultEOL&&this.trimAutoWhitespace===e.trimAutoWhitespace},e.prototype.createChangeEvent=function(e){return{tabSize:this.tabSize!==e.tabSize,indentSize:this.indentSize!==e.indentSize,insertSpaces:this.insertSpaces!==e.insertSpaces,trimAutoWhitespace:this.trimAutoWhitespace!==e.trimAutoWhitespace}},e}(),s=function(){return function(e,t){this.range=e,this.matches=t}}(),a=function(){return function(e,t,n){this.reverseEdits=e,this.changes=t,this.trimAutoWhitespaceLineNumbers=n}}()},DBt1:function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("JVO/"),o=Object(i.c)("editorProgressService")},Dc0G:function(e,t,n){(function(e){var i=n("blYT"),o="object"==typeof t&&t&&!t.nodeType&&t,r=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=r&&r.exports===o&&i.process,a=function(){try{var e=r&&r.require&&r.require("util").types;return e||s&&s.binding&&s.binding("util")}catch(e){}}();e.exports=a}).call(t,n("3IRH")(e))},"EG+O":function(e,t){},EMDP:function(e,t,n){"use strict";n.d(t,"a",function(){return l}),n.d(t,"b",function(){return c});var i,o,r=n("mrx5"),s=n("ZYUE"),a=n("JVO/"),u=n("WTFd"),l=Object(a.c)("contextService");!function(e){e.isIWorkspace=function(e){return e&&"object"==typeof e&&"string"==typeof e.id&&Array.isArray(e.folders)}}(i||(i={})),function(e){e.isIWorkspaceFolder=function(e){return e&&"object"==typeof e&&r.a.isUri(e.uri)&&"string"==typeof e.name&&"function"==typeof e.toResource}}(o||(o={}));!function(){function e(e,t,n){void 0===t&&(t=[]),void 0===n&&(n=null),this._id=e,this._configuration=n,this._foldersMap=u.c.forPaths(),this.folders=t}Object.defineProperty(e.prototype,"folders",{get:function(){return this._folders},set:function(e){this._folders=e,this.updateFoldersMap()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"configuration",{get:function(){return this._configuration},set:function(e){this._configuration=e},enumerable:!0,configurable:!0}),e.prototype.getFolder=function(e){return e&&this._foldersMap.findSubstr(e.with({scheme:e.scheme,authority:e.authority,path:e.path}).toString())||null},e.prototype.updateFoldersMap=function(){this._foldersMap=u.c.forPaths();for(var e=0,t=this.folders;e0&&e.getLanguageId(a-1)===r;)a--;return new i(e,r,a,s+1,e.getStartOffset(a),e.getEndOffset(s))},t.b=function(e){return 0!=(7&e)};var i=function(){function e(e,t,n,i,o,r){this._actual=e,this.languageId=t,this._firstTokenIndex=n,this._lastTokenIndex=i,this.firstCharOffset=o,this._lastCharOffset=r}return e.prototype.getLineContent=function(){return this._actual.getLineContent().substring(this.firstCharOffset,this._lastCharOffset)},e.prototype.getTokenCount=function(){return this._lastTokenIndex-this._firstTokenIndex},e.prototype.findTokenIndexAtOffset=function(e){return this._actual.findTokenIndexAtOffset(e+this.firstCharOffset)-this._firstTokenIndex},e.prototype.getStandardTokenType=function(e){return this._actual.getStandardTokenType(e+this._firstTokenIndex)},e}()},EfIu:function(e,t,n){"use strict";n.d(t,"a",function(){return i}),n.d(t,"c",function(){return o}),n.d(t,"b",function(){return r}),n.d(t,"d",function(){return s}),n.d(t,"e",function(){return a}),n.d(t,"g",function(){return u}),n.d(t,"h",function(){return l}),n.d(t,"f",function(){return c});var i,o,r,s,a,u,l,c,d=n("hK2W");!function(e){e.noSelection=d.a("noSelection","No selection"),e.singleSelectionRange=d.a("singleSelectionRange","Line {0}, Column {1} ({2} selected)"),e.singleSelection=d.a("singleSelection","Line {0}, Column {1}"),e.multiSelectionRange=d.a("multiSelectionRange","{0} selections ({1} characters selected)"),e.multiSelection=d.a("multiSelection","{0} selections"),e.emergencyConfOn=d.a("emergencyConfOn","Now changing the setting `accessibilitySupport` to 'on'."),e.openingDocs=d.a("openingDocs","Now opening the Editor Accessibility documentation page."),e.readonlyDiffEditor=d.a("readonlyDiffEditor"," in a read-only pane of a diff editor."),e.editableDiffEditor=d.a("editableDiffEditor"," in a pane of a diff editor."),e.readonlyEditor=d.a("readonlyEditor"," in a read-only code editor"),e.editableEditor=d.a("editableEditor"," in a code editor"),e.changeConfigToOnMac=d.a("changeConfigToOnMac","To configure the editor to be optimized for usage with a Screen Reader press Command+E now."),e.changeConfigToOnWinLinux=d.a("changeConfigToOnWinLinux","To configure the editor to be optimized for usage with a Screen Reader press Control+E now."),e.auto_on=d.a("auto_on","The editor is configured to be optimized for usage with a Screen Reader."),e.auto_off=d.a("auto_off","The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time."),e.tabFocusModeOnMsg=d.a("tabFocusModeOnMsg","Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}."),e.tabFocusModeOnMsgNoKb=d.a("tabFocusModeOnMsgNoKb","Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding."),e.tabFocusModeOffMsg=d.a("tabFocusModeOffMsg","Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}."),e.tabFocusModeOffMsgNoKb=d.a("tabFocusModeOffMsgNoKb","Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding."),e.openDocMac=d.a("openDocMac","Press Command+H now to open a browser window with more information related to editor accessibility."),e.openDocWinLinux=d.a("openDocWinLinux","Press Control+H now to open a browser window with more information related to editor accessibility."),e.outroMsg=d.a("outroMsg","You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape."),e.showAccessibilityHelpAction=d.a("showAccessibilityHelpAction","Show Accessibility Help")}(i||(i={})),function(e){e.inspectTokensAction=d.a("inspectTokens","Developer: Inspect Tokens")}(o||(o={})),function(e){e.gotoLineLabelValidLineAndColumn=d.a("gotoLineLabelValidLineAndColumn","Go to line {0} and character {1}"),e.gotoLineLabelValidLine=d.a("gotoLineLabelValidLine","Go to line {0}"),e.gotoLineLabelEmptyWithLineLimit=d.a("gotoLineLabelEmptyWithLineLimit","Type a line number between 1 and {0} to navigate to"),e.gotoLineLabelEmptyWithLineAndColumnLimit=d.a("gotoLineLabelEmptyWithLineAndColumnLimit","Type a character between 1 and {0} to navigate to"),e.gotoLineAriaLabel=d.a("gotoLineAriaLabel","Current Line: {0}. Go to line {1}."),e.gotoLineActionInput=d.a("gotoLineActionInput","Type a line number, followed by an optional colon and a character number to navigate to"),e.gotoLineActionLabel=d.a("gotoLineActionLabel","Go to Line...")}(r||(r={})),function(e){e.ariaLabelEntryWithKey=d.a("ariaLabelEntryWithKey","{0}, {1}, commands"),e.ariaLabelEntry=d.a("ariaLabelEntry","{0}, commands"),e.quickCommandActionInput=d.a("quickCommandActionInput","Type the name of an action you want to execute"),e.quickCommandActionLabel=d.a("quickCommandActionLabel","Command Palette")}(s||(s={})),function(e){e.entryAriaLabel=d.a("entryAriaLabel","{0}, symbols"),e.quickOutlineActionInput=d.a("quickOutlineActionInput","Type the name of an identifier you wish to navigate to"),e.quickOutlineActionLabel=d.a("quickOutlineActionLabel","Go to Symbol..."),e._symbols_=d.a("symbols","symbols ({0})"),e._modules_=d.a("modules","modules ({0})"),e._class_=d.a("class","classes ({0})"),e._interface_=d.a("interface","interfaces ({0})"),e._method_=d.a("method","methods ({0})"),e._function_=d.a("function","functions ({0})"),e._property_=d.a("property","properties ({0})"),e._variable_=d.a("variable","variables ({0})"),e._variable2_=d.a("variable2","variables ({0})"),e._constructor_=d.a("_constructor","constructors ({0})"),e._call_=d.a("call","calls ({0})")}(a||(a={})),function(e){e.editorViewAccessibleLabel=d.a("editorViewAccessibleLabel","Editor content"),e.accessibilityHelpMessageIE=d.a("accessibilityHelpMessageIE","Press Ctrl+F1 for Accessibility Options."),e.accessibilityHelpMessage=d.a("accessibilityHelpMessage","Press Alt+F1 for Accessibility Options.")}(u||(u={})),function(e){e.toggleHighContrast=d.a("toggleHighContrast","Toggle High Contrast Theme")}(l||(l={})),function(e){e.bulkEditServiceSummary=d.a("bulkEditServiceSummary","Made {0} edits in {1} files")}(c||(c={}))},EfRI:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"DeleteWordPartLeft",function(){return d}),n.d(t,"DeleteWordPartRight",function(){return h}),n.d(t,"WordPartLeftCommand",function(){return p}),n.d(t,"CursorWordPartLeft",function(){return f}),n.d(t,"CursorWordPartLeftSelect",function(){return g}),n.d(t,"WordPartRightCommand",function(){return m}),n.d(t,"CursorWordPartRight",function(){return _}),n.d(t,"CursorWordPartRightSelect",function(){return v});var i,o=n("03Zz"),r=n("CIBl"),s=n("vTy2"),a=n("/9db"),u=n("I8T6"),l=n("ItKl"),c=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),d=function(e){function t(){return e.call(this,{whitespaceHeuristics:!0,wordNavigationType:0,id:"deleteWordPartLeft",precondition:a.a.writable,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:769},weight:100}})||this}return c(t,e),t.prototype._delete=function(e,t,n,i,o){var a=r.b.deleteWordPartLeft(e,t,n,i);return a||new s.a(1,1,1,1)},t}(u.DeleteWordCommand),h=function(e){function t(){return e.call(this,{whitespaceHeuristics:!0,wordNavigationType:2,id:"deleteWordPartRight",precondition:a.a.writable,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:788},weight:100}})||this}return c(t,e),t.prototype._delete=function(e,t,n,i,o){var a=r.b.deleteWordPartRight(e,t,n,i);if(a)return a;var u=t.getLineCount(),l=t.getLineMaxColumn(u);return new s.a(u,l,u,l)},t}(u.DeleteWordCommand),p=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return c(t,e),t.prototype._move=function(e,t,n,i){return r.b.moveWordPartLeft(e,t,n)},t}(u.MoveWordCommand),f=function(e){function t(){return e.call(this,{inSelectionMode:!1,wordNavigationType:0,id:"cursorWordPartLeft",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:783},weight:100}})||this}return c(t,e),t}(p);l.a.registerCommandAlias("cursorWordPartStartLeft","cursorWordPartLeft");var g=function(e){function t(){return e.call(this,{inSelectionMode:!0,wordNavigationType:0,id:"cursorWordPartLeftSelect",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:1807},weight:100}})||this}return c(t,e),t}(p);l.a.registerCommandAlias("cursorWordPartStartLeftSelect","cursorWordPartLeftSelect");var m=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return c(t,e),t.prototype._move=function(e,t,n,i){return r.b.moveWordPartRight(e,t,n)},t}(u.MoveWordCommand),_=function(e){function t(){return e.call(this,{inSelectionMode:!1,wordNavigationType:2,id:"cursorWordPartRight",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:785},weight:100}})||this}return c(t,e),t}(m),v=function(e){function t(){return e.call(this,{inSelectionMode:!0,wordNavigationType:2,id:"cursorWordPartRightSelect",precondition:void 0,kbOpts:{kbExpr:a.a.textInputFocus,primary:0,mac:{primary:1809},weight:100}})||this}return c(t,e),t}(m);Object(o.g)(new d),Object(o.g)(new h),Object(o.g)(new f),Object(o.g)(new g),Object(o.g)(new _),Object(o.g)(new v)},Evjx:function(e,t,n){"use strict";n.d(t,"d",function(){return u}),n.d(t,"b",function(){return c}),n.d(t,"a",function(){return d}),n.d(t,"c",function(){return _});var i,o,r=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),s=function(){function e(){this.value="",this.pos=0}return e.isDigitCharacter=function(e){return e>=48&&e<=57},e.isVariableCharacter=function(e){return 95===e||e>=97&&e<=122||e>=65&&e<=90},e.prototype.text=function(e){this.value=e,this.pos=0},e.prototype.tokenText=function(e){return this.value.substr(e.pos,e.len)},e.prototype.next=function(){if(this.pos>=this.value.length)return{type:14,pos:this.pos,len:0};var t,n=this.pos,i=0,o=this.value.charCodeAt(n);if("number"==typeof(t=e._table[o]))return this.pos+=1,{type:t,pos:n,len:1};if(e.isDigitCharacter(o)){t=8;do{i+=1,o=this.value.charCodeAt(n+i)}while(e.isDigitCharacter(o));return this.pos+=i,{type:t,pos:n,len:i}}if(e.isVariableCharacter(o)){t=9;do{o=this.value.charCodeAt(n+ ++i)}while(e.isVariableCharacter(o)||e.isDigitCharacter(o));return this.pos+=i,{type:t,pos:n,len:i}}t=10;do{i+=1,o=this.value.charCodeAt(n+i)}while(!isNaN(o)&&void 0===e._table[o]&&!e.isDigitCharacter(o)&&!e.isVariableCharacter(o));return this.pos+=i,{type:t,pos:n,len:i}},e._table=((o={})[36]=0,o[58]=1,o[44]=2,o[123]=3,o[125]=4,o[92]=5,o[47]=6,o[124]=7,o[43]=11,o[45]=12,o[63]=13,o),e}(),a=function(){function e(){this._children=[]}return e.prototype.appendChild=function(e){return e instanceof u&&this._children[this._children.length-1]instanceof u?this._children[this._children.length-1].value+=e.value:(e.parent=this,this._children.push(e)),this},e.prototype.replace=function(e,t){var n=e.parent,i=n.children.indexOf(e),o=n.children.slice(0);o.splice.apply(o,[i,1].concat(t)),n._children=o,function e(t,n){for(var i=0,o=t;it.index?1:0},Object.defineProperty(t.prototype,"isFinalTabstop",{get:function(){return 0===this.index},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"choice",{get:function(){return 1===this._children.length&&this._children[0]instanceof d?this._children[0]:void 0},enumerable:!0,configurable:!0}),t.prototype.clone=function(){var e=new t(this.index);return this.transform&&(e.transform=this.transform.clone()),e._children=this.children.map(function(e){return e.clone()}),e},t}(l),d=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.options=[],t}return r(t,e),t.prototype.appendChild=function(e){return e instanceof u&&(e.parent=this,this.options.push(e)),this},t.prototype.toString=function(){return this.options[0].value},t.prototype.len=function(){return this.options[0].len()},t.prototype.clone=function(){var e=new t;return this.options.forEach(e.appendChild,e),e},t}(a),h=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.regexp=new RegExp(""),t}return r(t,e),t.prototype.resolve=function(e){var t=this,n=!1,i=e.replace(this.regexp,function(){return n=!0,t._replace(Array.prototype.slice.call(arguments,0,-2))});return!n&&this._children.some(function(e){return e instanceof p&&Boolean(e.elseValue)})&&(i=this._replace([])),i},t.prototype._replace=function(e){for(var t="",n=0,i=this._children;n0;){var i=n.shift();if(!t(i))break;n.unshift.apply(n,i.children)}}var m=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return r(t,e),Object.defineProperty(t.prototype,"placeholderInfo",{get:function(){if(!this._placeholders){var e,t=[];this.walk(function(n){return n instanceof c&&(t.push(n),e=!e||e.index0?o.set(e.index,e.children):r.push(e)),!0});for(var a=0,u=r;a0&&t),!o.has(0)&&n&&i.appendChild(new c(0)),i},e.prototype._accept=function(e,t){if(void 0===e||this._token.type===e){var n=!t||this._scanner.tokenText(this._token);return this._token=this._scanner.next(),n}return!1},e.prototype._backTo=function(e){return this._scanner.pos=e.pos+e.len,this._token=e,!1},e.prototype._until=function(e){if(14===this._token.type)return!1;for(var t="",n=this._token.pos,i={type:14,pos:0,len:0};this._token.type!==e||5===i.type;)if(this._token.type===e&&(t+=this._scanner.value.substring(n,i.pos),n=this._token.pos),i=this._token,this._token=this._scanner.next(),14===this._token.type)return!1;return t+=this._scanner.value.substring(n,this._token.pos),this._token=this._scanner.next(),t},e.prototype._parse=function(e){return this._parseEscaped(e)||this._parseTabstopOrVariableName(e)||this._parseComplexPlaceholder(e)||this._parseComplexVariable(e)||this._parseAnything(e)},e.prototype._parseEscaped=function(e){var t;return!!(t=this._accept(5,!0))&&(t=this._accept(0,!0)||this._accept(4,!0)||this._accept(5,!0)||t,e.appendChild(new u(t)),!0)},e.prototype._parseTabstopOrVariableName=function(e){var t,n=this._token;return this._accept(0)&&(t=this._accept(9,!0)||this._accept(8,!0))?(e.appendChild(/^\d+$/.test(t)?new c(Number(t)):new f(t)),!0):this._backTo(n)},e.prototype._parseComplexPlaceholder=function(e){var t,n=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(8,!0))))return this._backTo(n);var i=new c(Number(t));if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(i),!0;if(!this._parse(i))return e.appendChild(new u("${"+t+":")),i.children.forEach(e.appendChild,e),!0}else{if(!(i.index>0&&this._accept(7)))return this._accept(6)?this._parseTransform(i)?(e.appendChild(i),!0):(this._backTo(n),!1):this._accept(4)?(e.appendChild(i),!0):this._backTo(n);for(var o=new d;;){if(this._parseChoiceElement(o)){if(this._accept(2))continue;if(this._accept(7)&&(i.appendChild(o),this._accept(4)))return e.appendChild(i),!0}return this._backTo(n),!1}}},e.prototype._parseChoiceElement=function(e){for(var t=this._token,n=[];2!==this._token.type&&7!==this._token.type;){var i=void 0;if(!(i=(i=this._accept(5,!0))?this._accept(2,!0)||this._accept(7,!0)||this._accept(5,!0)||i:this._accept(void 0,!0)))return this._backTo(t),!1;n.push(i)}return 0===n.length?(this._backTo(t),!1):(e.appendChild(new u(n.join(""))),!0)},e.prototype._parseComplexVariable=function(e){var t,n=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(9,!0))))return this._backTo(n);var i=new f(t);if(!this._accept(1))return this._accept(6)?this._parseTransform(i)?(e.appendChild(i),!0):(this._backTo(n),!1):this._accept(4)?(e.appendChild(i),!0):this._backTo(n);for(;;){if(this._accept(4))return e.appendChild(i),!0;if(!this._parse(i))return e.appendChild(new u("${"+t+":")),i.children.forEach(e.appendChild,e),!0}},e.prototype._parseTransform=function(e){for(var t=new h,n="",i="";!this._accept(6);){var o=void 0;if(o=this._accept(5,!0))n+=o=this._accept(6,!0)||o;else{if(14===this._token.type)return!1;n+=this._accept(void 0,!0)}}for(;!this._accept(6);){o=void 0;if(o=this._accept(5,!0))o=this._accept(5,!0)||this._accept(6,!0)||o,t.appendChild(new u(o));else if(!this._parseFormatString(t)&&!this._parseAnything(t))return!1}for(;!this._accept(4);){if(14===this._token.type)return!1;i+=this._accept(void 0,!0)}try{t.regexp=new RegExp(n,i)}catch(e){return!1}return e.transform=t,!0},e.prototype._parseFormatString=function(e){var t=this._token;if(!this._accept(0))return!1;var n=!1;this._accept(3)&&(n=!0);var i=this._accept(8,!0);if(!i)return this._backTo(t),!1;if(!n)return e.appendChild(new p(Number(i))),!0;if(this._accept(4))return e.appendChild(new p(Number(i))),!0;if(!this._accept(1))return this._backTo(t),!1;if(this._accept(6)){var o=this._accept(9,!0);return o&&this._accept(4)?(e.appendChild(new p(Number(i),o)),!0):(this._backTo(t),!1)}if(this._accept(11)){if(r=this._until(4))return e.appendChild(new p(Number(i),void 0,r,void 0)),!0}else if(this._accept(12)){if(s=this._until(4))return e.appendChild(new p(Number(i),void 0,void 0,s)),!0}else if(this._accept(13)){var r;if(r=this._until(1))if(s=this._until(4))return e.appendChild(new p(Number(i),void 0,r,s)),!0}else{var s;if(s=this._until(4))return e.appendChild(new p(Number(i),void 0,void 0,s)),!0}return this._backTo(t),!1},e.prototype._parseAnything=function(e){return 14!==this._token.type&&(e.appendChild(new u(this._scanner.tokenText(this._token))),this._accept(void 0),!0)},e}()},F5mM:function(e,t){},Fllr:function(e,t,n){"use strict";var i=n("zxiH"),o=n("Kp7x"),r=n("tqet"),s=n("aL7J"),a=n("vTy2"),u=n("+jct"),l=n("+oh4"),c=n("Eeyw"),d=function(){function e(t){if(t.autoClosingPairs?this._autoClosingPairs=t.autoClosingPairs.map(function(e){return new l.b(e)}):t.brackets?this._autoClosingPairs=t.brackets.map(function(e){return new l.b({open:e[0],close:e[1]})}):this._autoClosingPairs=[],t.__electricCharacterSupport&&t.__electricCharacterSupport.docComment){var n=t.__electricCharacterSupport.docComment;this._autoClosingPairs.push(new l.b({open:n.open,close:n.close||""}))}this._autoCloseBefore="string"==typeof t.autoCloseBefore?t.autoCloseBefore:e.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED,this._surroundingPairs=t.surroundingPairs||this._autoClosingPairs}return e.prototype.getAutoClosingPairs=function(){return this._autoClosingPairs},e.prototype.getAutoCloseBeforeSet=function(){return this._autoCloseBefore},e.shouldAutoClosePair=function(e,t,n){if(0===t.getTokenCount())return!0;var i=t.findTokenIndexAtOffset(n-2),o=t.getStandardTokenType(i);return e.isOK(o)},e.prototype.getSurroundingPairs=function(){return this._surroundingPairs},e.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED=";:.,=}])> \n\t",e}(),h=n("iNUG"),p=function(){function e(e){this._richEditBrackets=e}return e.prototype.getElectricCharacters=function(){var e=[];if(this._richEditBrackets)for(var t=0,n=this._richEditBrackets.brackets.length;t0&&n.length>0)for(i=0,o=this._brackets.length;i0)for(i=0,o=this._brackets.length;i1){var o=void 0,r=-1;for(o=t-1;o>=1;o--){if(e.getLanguageIdAtPosition(o,0)!==i)return r;var s=e.getLineContent(o);if(!n.shouldIgnore(s)&&!/^\s+$/.test(s)&&""!==s)return o;r=o}}return-1},e.prototype.getInheritIndentForLine=function(e,t,n){void 0===n&&(n=!0);var i=this.getIndentRulesSupport(e.getLanguageIdentifier().id);if(!i)return null;if(t<=1)return{indentation:"",action:null};var o=this.getPrecedingValidLine(e,t,i);if(o<0)return null;if(o<1)return{indentation:"",action:null};var r=e.getLineContent(o);if(i.shouldIncrease(r)||i.shouldIndentNextLine(r))return{indentation:s.s(r),action:l.a.Indent,line:o};if(i.shouldDecrease(r))return{indentation:s.s(r),action:null,line:o};if(1===o)return{indentation:s.s(e.getLineContent(o)),action:null,line:o};var a=o-1,u=i.getIndentMetadata(e.getLineContent(a));if(!(3&u)&&4&u){for(var c=0,d=a-1;d>0;d--)if(!i.shouldIndentNextLine(e.getLineContent(d))){c=d;break}return{indentation:s.s(e.getLineContent(c+1)),action:null,line:c+1}}if(n)return{indentation:s.s(e.getLineContent(o)),action:null,line:o};for(d=o;d>0;d--){var h=e.getLineContent(d);if(i.shouldIncrease(h))return{indentation:s.s(h),action:l.a.Indent,line:d};if(i.shouldIndentNextLine(h)){c=0;for(var p=d-1;p>0;p--)if(!i.shouldIndentNextLine(e.getLineContent(d))){c=p;break}return{indentation:s.s(e.getLineContent(c+1)),action:null,line:c+1}}if(i.shouldDecrease(h))return{indentation:s.s(h),action:null,line:d}}return{indentation:s.s(e.getLineContent(1)),action:null,line:1}},e.prototype.getGoodIndentForLine=function(e,t,n,o){var r=this.getIndentRulesSupport(t);if(!r)return null;var a=this.getInheritIndentForLine(e,n),u=e.getLineContent(n);if(a){var c=a.line;if(void 0!==c){var d=this._getOnEnterSupport(t),h=null;try{d&&(h=d.onEnter("",e.getLineContent(c),""))}catch(e){Object(i.e)(e)}if(h){var p=s.s(e.getLineContent(c));return h.removeText&&(p=p.substring(0,p.length-h.removeText)),h.indentAction===l.a.Indent||h.indentAction===l.a.IndentOutdent?p=o.shiftIndent(p):h.indentAction===l.a.Outdent&&(p=o.unshiftIndent(p)),r.shouldDecrease(u)&&(p=o.unshiftIndent(p)),h.appendText&&(p+=h.appendText),s.s(p)}}return r.shouldDecrease(u)?a.action===l.a.Indent?a.indentation:o.unshiftIndent(a.indentation):a.action===l.a.Indent?o.shiftIndent(a.indentation):a.indentation}return null},e.prototype.getIndentForEnter=function(e,t,n,i){e.forceTokenization(t.startLineNumber);var o,r,a=e.getLineTokens(t.startLineNumber),u=Object(c.a)(a,t.startColumn-1),d=u.getLineContent(),h=!1;(u.firstCharOffset>0&&a.getLanguageId(0)!==u.languageId?(h=!0,o=d.substr(0,t.startColumn-1-u.firstCharOffset)):o=a.getLineContent().substring(0,t.startColumn-1),t.isEmpty())?r=d.substr(t.startColumn-1-u.firstCharOffset):r=this.getScopedLineTokens(e,t.endLineNumber,t.endColumn).getLineContent().substr(t.endColumn-1-u.firstCharOffset);var p=this.getIndentRulesSupport(u.languageId);if(!p)return null;var f=o,g=s.s(o);if(!i&&!h){var m=this.getInheritIndentForLine(e,t.startLineNumber);p.shouldDecrease(o)&&m&&(g=m.indentation,m.action!==l.a.Indent&&(g=n.unshiftIndent(g))),f=g+s.B(s.B(o," "),"\t")}var _={getLineTokens:function(t){return e.getLineTokens(t)},getLanguageIdentifier:function(){return e.getLanguageIdentifier()},getLanguageIdAtPosition:function(t,n){return e.getLanguageIdAtPosition(t,n)},getLineContent:function(n){return n===t.startLineNumber?f:e.getLineContent(n)}},v=s.s(a.getLineContent()),y=this.getInheritIndentForLine(_,t.startLineNumber+1);if(!y){var b=h?v:g;return{beforeEnter:b,afterEnter:b}}var C=h?v:y.indentation;return y.action===l.a.Indent&&(C=n.shiftIndent(C)),p.shouldDecrease(r)&&(C=n.unshiftIndent(C)),{beforeEnter:h?v:g,afterEnter:C}},e.prototype.getIndentActionForType=function(e,t,n,i){var o=this.getScopedLineTokens(e,t.startLineNumber,t.startColumn),r=this.getIndentRulesSupport(o.languageId);if(!r)return null;var s,a=o.getLineContent(),u=a.substr(0,t.startColumn-1-o.firstCharOffset);t.isEmpty()?s=a.substr(t.startColumn-1-o.firstCharOffset):s=this.getScopedLineTokens(e,t.endLineNumber,t.endColumn).getLineContent().substr(t.endColumn-1-o.firstCharOffset);if(!r.shouldDecrease(u+s)&&r.shouldDecrease(u+n+s)){var c=this.getInheritIndentForLine(e,t.startLineNumber,!1);if(!c)return null;var d=c.indentation;return c.action!==l.a.Indent&&(d=i.unshiftIndent(d)),d}return null},e.prototype.getIndentMetadata=function(e,t){var n=this.getIndentRulesSupport(e.getLanguageIdentifier().id);return n?t<1||t>e.getLineCount()?null:n.getIndentMetadata(e.getLineContent(t)):null},e.prototype._getOnEnterSupport=function(e){var t=this._getRichEditSupport(e);return t&&t.onEnter||null},e.prototype.getRawEnterActionAtPosition=function(e,t,n){var i=this.getEnterAction(e,new a.a(t,n,t,n));return i?i.enterAction:null},e.prototype.getEnterAction=function(e,t){var n=this.getIndentationAtPosition(e,t.startLineNumber,t.startColumn),o=this.getScopedLineTokens(e,t.startLineNumber,t.startColumn),r=this._getOnEnterSupport(o.languageId);if(!r)return null;var s,a=o.getLineContent(),u=a.substr(0,t.startColumn-1-o.firstCharOffset);t.isEmpty()?s=a.substr(t.startColumn-1-o.firstCharOffset):s=this.getScopedLineTokens(e,t.endLineNumber,t.endColumn).getLineContent().substr(t.endColumn-1-o.firstCharOffset);var c=t.startLineNumber,d="";if(c>1&&0===o.firstCharOffset){var h=this.getScopedLineTokens(e,c-1);h.languageId===o.languageId&&(d=h.getLineContent())}var p=null;try{p=r.onEnter(d,u,s)}catch(e){Object(i.e)(e)}return p?(p.appendText||(p.indentAction===l.a.Indent||p.indentAction===l.a.IndentOutdent?p.appendText="\t":p.appendText=""),p.removeText&&(n=n.substring(0,n.length-p.removeText)),{enterAction:p,indentation:n}):null},e.prototype.getIndentationAtPosition=function(e,t,n){var i=e.getLineContent(t),o=s.s(i);return o.length>n-1&&(o=o.substring(0,n-1)),o},e.prototype.getScopedLineTokens=function(e,t,n){e.forceTokenization(t);var i=e.getLineTokens(t),o=void 0===n?e.getLineMaxColumn(t)-1:n-1;return Object(c.a)(i,o)},e.prototype.getBracketsSupport=function(e){var t=this._getRichEditSupport(e);return t&&t.brackets||null},e}())},G7Ib:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n("03Zz"),o=n("0Td8");Object(i.h)(o.f),Object(i.f)(o.e),Object(i.f)(o.g),Object(i.f)(o.h),Object(i.f)(o.d),Object(i.f)(o.a),Object(i.f)(o.c),Object(i.g)(new o.b)},G8ar:function(e,t,n){var i=n("cdq7"),o=n("8++/"),r=n("i6nN");e.exports=function(e,t,n){return t==t?r(e,t,n):i(e,o,n)}},G8r4:function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("Kp7x"),o=new(function(){function e(){this._zoomLevel=0,this._onDidChangeZoomLevel=new i.a,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event}return e.prototype.getZoomLevel=function(){return this._zoomLevel},e.prototype.setZoomLevel=function(e){e=Math.min(Math.max(-5,e),20),this._zoomLevel!==e&&(this._zoomLevel=e,this._onDidChangeZoomLevel.fire(this._zoomLevel))},e}())},GV5w:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"GotoLineEntry",function(){return g}),n.d(t,"GotoLineAction",function(){return m});var i,o=n("wtJh"),r=(n.n(o),n("aL7J")),s=n("Al6Q"),a=n("P1SM"),u=n("03Zz"),l=n("artP"),c=n("vTy2"),d=n("/9db"),h=n("zwZj"),p=n("EfIu"),f=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=function(e){function t(t,n,i){var o=e.call(this)||this;return o.editor=n,o.decorator=i,o.parseResult=o.parseInput(t),o}return f(t,e),t.prototype.parseInput=function(e){var t,n,i=e.split(",").map(function(e){return parseInt(e,10)}).filter(function(e){return!isNaN(e)});if(t=0===i.length?new l.a(-1,-1):1===i.length?new l.a(i[0],1):new l.a(i[0],i[1]),Object(a.a)(this.editor))n=this.editor.getModel();else{var o=this.editor.getModel();n=o?o.modified:null}var s=!!n&&n.validatePosition(t).equals(t);return{position:t,isValid:s,label:s?t.column&&t.column>1?r.r(p.b.gotoLineLabelValidLineAndColumn,t.lineNumber,t.column):r.r(p.b.gotoLineLabelValidLine,t.lineNumber):t.lineNumber<1||t.lineNumber>(n?n.getLineCount():0)?r.r(p.b.gotoLineLabelEmptyWithLineLimit,n?n.getLineCount():0):r.r(p.b.gotoLineLabelEmptyWithLineAndColumnLimit,n?n.getLineMaxColumn(t.lineNumber):0)}},t.prototype.getLabel=function(){return this.parseResult.label},t.prototype.getAriaLabel=function(){var e=this.editor.getPosition(),t=e?e.lineNumber:0;return r.r(p.b.gotoLineAriaLabel,t,this.parseResult.label)},t.prototype.run=function(e,t){return 1===e?this.runOpen():this.runPreview()},t.prototype.runOpen=function(){if(!this.parseResult.isValid)return!1;var e=this.toSelection();return this.editor.setSelection(e),this.editor.revealRangeInCenter(e,0),this.editor.focus(),!0},t.prototype.runPreview=function(){if(!this.parseResult.isValid)return this.decorator.clearDecorations(),!1;var e=this.toSelection();return this.editor.revealRangeInCenter(e,0),this.decorator.decorateLine(e,this.editor),!1},t.prototype.toSelection=function(){return new c.a(this.parseResult.position.lineNumber,this.parseResult.position.column,this.parseResult.position.lineNumber,this.parseResult.position.column)},t}(s.a),m=function(e){function t(){return e.call(this,p.b.gotoLineActionInput,{id:"editor.action.gotoLine",label:p.b.gotoLineActionLabel,alias:"Go to Line...",precondition:void 0,kbOpts:{kbExpr:d.a.focus,primary:2085,mac:{primary:293},weight:100}})||this}return f(t,e),t.prototype.run=function(e,t){var n=this;this._show(this.getController(t),{getModel:function(e){return new s.c([new g(e,t,n.getController(t))])},getAutoFocus:function(e){return{autoFocusFirstEntry:e.length>0}}})},t}(h.a);Object(u.f)(m)},GYOr:function(e,t,n){"use strict";n.d(t,"g",function(){return s}),t.f=function(e,t,n){void 0===n&&(n=!1);if("string"!=typeof e||"string"!=typeof t)return null;var i=y.get(e);i||(i=new RegExp(o.j(e),"i"),y.set(e,i));var r=i.exec(t);if(r)return[{start:r.index,end:r.index+r[0].length}];return n?v(e,t):_(e,t)},t.b=function(e,t,n,i,o,r){var s=D(e,t,0,i,o,0,!0);if(s)return s;for(var a=0,u=0,l=r,c=0;c=0)u+=1,a+=Math.pow(2,d),l=d+1;else if(0!==a)break}return[u,a,r]},t.c=function(e){if(void 0===e)return[];for(var t=e[1].toString(2),n=[],i=e[2];i=3)for(var l=Math.min(7,e.length-1),c=n+1;cu[0])&&(u=h))}}return u}(e,t,n,i,o,r,!0,s)};var i=n("WTFd"),o=n("aL7J");function r(){for(var e=[],t=0;t0?[{start:0,end:t.length}]:[]}.bind(void 0,!0);function a(e){return 97<=e&&e<=122}function u(e){return 65<=e&&e<=90}function l(e){return 48<=e&&e<=57}function c(e){return 32===e||9===e||10===e||13===e}var d=new Set;function h(e){return a(e)||u(e)||l(e)}function p(e,t){return 0===t.length?t=[e]:e.end===t[0].start?t[0].start=e.start:t.unshift(e),t}function f(e,t){for(var n=t;n0&&!h(e.charCodeAt(n-1)))return n}return e.length}function g(e,t,n,i){if(n===e.length)return[];if(i===t.length)return null;if(e[n]!==t[i].toLowerCase())return null;var o=null,r=i+1;for(o=g(e,t,n+1,i+1);!o&&(r=f(t,r))60)return null;var n=function(e){for(var t=0,n=0,i=0,o=0,r=0,s=0;s.2&&t<.8&&i>.6&&o<.2}(n)){if(!function(e){var t=e.upperPercent;return 0===e.lowerPercent&&t>.6}(n))return null;t=t.toLowerCase()}var i=null,o=0;for(e=e.toLowerCase();o/?".split("").forEach(function(e){return d.add(e.charCodeAt(0))});var _=r(s,m,function(e,t){var n=t.toLowerCase().indexOf(e.toLowerCase());return-1===n?null:[{start:n,end:n+e.length}]}),v=r(s,m,function(e,t){return function e(t,n,i,o){if(i===t.length)return[];if(o===n.length)return null;if(t[i]===n[o]){var r=null;return(r=e(t,n,i+1,o+1))?p({start:o,end:o+1},r):null}return e(t,n,i,o+1)}(e.toLowerCase(),t.toLowerCase(),0,0)}),y=new i.a(1e4);var b=128;function C(){for(var e=[],t=[0],n=1;n<=b;n++)t.push(-n);for(n=0;n<=b;n++){var i=t.slice(0);i[0]=-n,e.push(i)}return e}var w,S=C(),L=C(),O=C(),E=!1;function N(e,t,n,i,o){function r(e,t,n){for(void 0===n&&(n=" ");e.length=e.length)return!1;switch(e.charCodeAt(t)){case 95:case 45:case 46:case 32:case 47:case 92:case 39:case 34:case 58:case 36:return!0;default:return!1}}function I(e,t,n){return t[e]!==n[e]}function D(e,t,n,i,o,r,s){var a=e.length>b?b:e.length,u=i.length>b?b:i.length;if(!(n>=a||r>=u||a>u)&&function(e,t,n,i,o,r){for(;t1?1:p),g=S[l-1][c]+-1,m=S[l][c-1]+-1;m>=g?m>f?(S[l][c]=m,O[l][c]=4):m===f?(S[l][c]=m,O[l][c]=6):(S[l][c]=f,O[l][c]=2):g>f?(S[l][c]=g,O[l][c]=1):g===f?(S[l][c]=g,O[l][c]=3):(S[l][c]=f,O[l][c]=2)}if(E&&function(e,t,n,i){e=e.substr(t),n=n.substr(i),console.log(N(S,e,e.length,n,n.length)),console.log(N(O,e,e.length,n,n.length)),console.log(N(L,e,e.length,n,n.length))}(e,n,i,r),T=0,R=-100,A=r,P=s,function e(t,n,i,o,r){if(T>=10||i<-25)return;var s=0;for(;t>0&&n>0;){var a=L[t][n],u=O[t][n];if(4===u)n-=1,r?i-=5:0!==o&&(i-=1),r=!1,s=0;else{if(!(2&u))return;if(4&u&&e(t,n-1,0!==o?i-1:i,o,r),i+=a,t-=1,n-=1,r=!0,o+=Math.pow(2,n+A),1===a){if(s+=1,0===t&&!P)return}else i+=1+s*(a-1),s=0}}i-=n>=3?9:3*n;T+=1;i>R&&(R=i,M=o)}(l-1,c-1,a===u?1:0,0,!1),0!==T)return[R,M,r]}}function k(e,t,n,i,o,r,s){return t[n]!==r[s]?-1:s===n-i?e[n]===o[s]?7:5:!I(s,o,r)||0!==s&&I(s-1,o,r)?!x(r,s)||0!==s&&x(r,s-1)?x(r,s-1)||function(e,t){if(t<0||t>=e.length)return!1;switch(e.charCodeAt(t)){case 32:case 9:return!0;default:return!1}}(r,s-1)?5:1:5:e[n]===o[s]?7:5}!function(e){e.Default=Object.freeze([-100,0,0]),e.isDefault=function(e){return!e||-100===e[0]&&0===e[1]&&0===e[2]}}(w||(w={}));var T=0,M=0,R=0,A=0,P=!1;function F(e,t){if(!(t+1>=e.length)){var n=e[t],i=e[t+1];if(n!==i)return e.slice(0,t)+i+n+e.slice(t+2)}}},GZKt:function(e,t){},GfE5:function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"b",function(){return r});var i=n("CQAd"),o=function(){function e(t){var n=Object(i.d)(t);this._defaultValue=n,this._asciiMap=e._createAsciiMap(n),this._map=new Map}return e._createAsciiMap=function(e){for(var t=new Uint8Array(256),n=0;n<256;n++)t[n]=e;return t},e.prototype.set=function(e,t){var n=Object(i.d)(t);e>=0&&e<256?this._asciiMap[e]=n:this._map.set(e,n)},e.prototype.get=function(e){return e>=0&&e<256?this._asciiMap[e]:this._map.get(e)||this._defaultValue},e}(),r=function(){function e(){this._actual=new o(0)}return e.prototype.add=function(e){this._actual.set(e,1)},e.prototype.has=function(e){return 1===this._actual.get(e)},e}()},GsV8:function(e,t,n){"use strict";n.d(t,"a",function(){return o}),n.d(t,"b",function(){return r});var i=n("JVO/"),o=Object(i.c)("openerService"),r=Object.freeze({_serviceBrand:void 0,registerOpener:function(){return{dispose:function(){}}},registerValidator:function(){return{dispose:function(){}}},open:function(){return Promise.resolve(!1)}})},Gu5N:function(e,t){},Gu7T:function(e,t,n){"use strict";t.__esModule=!0;var i,o=n("c/Tr"),r=(i=o)&&i.__esModule?i:{default:i};t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);tc&&(d=c,h=e.model.getLineMaxColumn(d)),r.d.fromModelState(new r.f(new l.a(s.lineNumber,1,d,h),0,new u.a(d,h),0))}var p=t.modelState.selectionStart.getStartPosition().lineNumber;if(s.lineNumberp){c=e.viewModel.getLineCount();var f=a.lineNumber+1,g=1;return f>c&&(f=c,g=e.viewModel.getLineMaxColumn(f)),r.d.fromViewState(t.viewState.move(t.modelState.hasSelection(),f,g,0))}var m=t.modelState.selectionStart.getEndPosition();return r.d.fromModelState(t.modelState.move(t.modelState.hasSelection(),m.lineNumber,m.column,0))},e.word=function(e,t,n,i){var o=e.model.validatePosition(i);return r.d.fromModelState(a.a.word(e.config,e.model,t.modelState,n,o))},e.cancelSelection=function(e,t){if(!t.modelState.hasSelection())return new r.d(t.modelState,t.viewState);var n=t.viewState.position.lineNumber,i=t.viewState.position.column;return r.d.fromViewState(new r.f(new l.a(n,i,n,i),0,new u.a(n,i),0))},e.moveTo=function(e,t,n,i,o){var s=e.model.validatePosition(i),a=o?e.validateViewPosition(new u.a(o.lineNumber,o.column),s):e.convertModelPositionToViewPosition(s);return r.d.fromViewState(t.viewState.move(n,a.lineNumber,a.column,0))},e.move=function(e,t,n){var i=n.select,o=n.value;switch(n.direction){case 0:return 4===n.unit?this._moveHalfLineLeft(e,t,i):this._moveLeft(e,t,i,o);case 1:return 4===n.unit?this._moveHalfLineRight(e,t,i):this._moveRight(e,t,i,o);case 2:return 2===n.unit?this._moveUpByViewLines(e,t,i,o):this._moveUpByModelLines(e,t,i,o);case 3:return 2===n.unit?this._moveDownByViewLines(e,t,i,o):this._moveDownByModelLines(e,t,i,o);case 4:return this._moveToViewMinColumn(e,t,i);case 5:return this._moveToViewFirstNonWhitespaceColumn(e,t,i);case 6:return this._moveToViewCenterColumn(e,t,i);case 7:return this._moveToViewMaxColumn(e,t,i);case 8:return this._moveToViewLastNonWhitespaceColumn(e,t,i);case 9:var r=t[0],s=e.getCompletelyVisibleModelRange(),a=this._firstLineNumberInRange(e.model,s,o),u=e.model.getLineFirstNonWhitespaceColumn(a);return[this._moveToModelPosition(e,r,i,a,u)];case 11:r=t[0],s=e.getCompletelyVisibleModelRange(),a=this._lastLineNumberInRange(e.model,s,o),u=e.model.getLineFirstNonWhitespaceColumn(a);return[this._moveToModelPosition(e,r,i,a,u)];case 10:r=t[0],s=e.getCompletelyVisibleModelRange(),a=Math.round((s.startLineNumber+s.endLineNumber)/2),u=e.model.getLineFirstNonWhitespaceColumn(a);return[this._moveToModelPosition(e,r,i,a,u)];case 12:for(var l=e.getCompletelyVisibleViewRange(),c=[],d=0,h=t.length;dn.endLineNumber-1&&(o=n.endLineNumber-1),oo,d=i>r,h=ir)continue;if(yi)continue;if(v1&&o--,e.columnSelect(t,n,i.fromViewLineNumber,i.fromViewVisualColumn,i.toViewLineNumber,o)},e.columnSelectRight=function(e,t,n){for(var i=0,o=Math.min(n.fromViewLineNumber,n.toViewLineNumber),r=Math.max(n.fromViewLineNumber,n.toViewLineNumber),s=o;s<=r;s++){var l=t.getLineMaxColumn(s),c=a.a.visibleColumnFromColumn2(e,t,new u.a(s,l));i=Math.max(i,c)}var d=n.toViewVisualColumn;return d1)for(var r=n.modelState?n.modelState.position:null,s=n.viewState?n.viewState.position:null,a=0,u=o.length;ao&&(i=o);var r=new l.a(i,1,i,e.context.model.getLineMaxColumn(i)),s=0;if(n.at)switch(n.at){case y.RawAtArgument.Top:s=3;break;case y.RawAtArgument.Center:s=1;break;case y.RawAtArgument.Bottom:s=4}var a=e.context.convertModelRangeToViewRange(r);e.revealRange(!1,a,s,0)},t}(N))),e.SelectAll=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"selectAll",precondition:void 0})||this}return O(t,e),t.prototype.runCoreEditorCommand=function(e,t){e.context.model.pushStackElement(),e.setStates(t.source,3,[h.b.selectAll(e.context,e.getPrimaryCursor())])},t}(N))),e.SetSelection=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"setSelection",precondition:void 0})||this}return O(t,e),t.prototype.runCoreEditorCommand=function(e,t){e.context.model.pushStackElement(),e.setStates(t.source,3,[a.d.fromModelSelection(t.selection)])},t}(N)))}(C||(C={})),S=w||(w={}),L=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return O(t,e),t.prototype.runEditorCommand=function(e,t,n){var i=t._getCursors();i&&this.runCoreEditingCommand(t,i,n||{})},t}(r.c),S.CoreEditingCommand=L,S.LineBreakInsert=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"lineBreakInsert",precondition:g.a.writable,kbOpts:{weight:E,kbExpr:g.a.textInputFocus,primary:0,mac:{primary:301}}})||this}return O(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){e.pushUndoStop(),e.executeCommands(this.id,p.a.lineBreakInsert(t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection})))},t}(L))),S.Outdent=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"outdent",precondition:g.a.writable,kbOpts:{weight:E,kbExpr:m.a.and(g.a.editorTextFocus,g.a.tabDoesNotMoveFocus),primary:1026}})||this}return O(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){e.pushUndoStop(),e.executeCommands(this.id,p.a.outdent(t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection}))),e.pushUndoStop()},t}(L))),S.Tab=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"tab",precondition:g.a.writable,kbOpts:{weight:E,kbExpr:m.a.and(g.a.editorTextFocus,g.a.tabDoesNotMoveFocus),primary:2}})||this}return O(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){e.pushUndoStop(),e.executeCommands(this.id,p.a.tab(t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection}))),e.pushUndoStop()},t}(L))),S.DeleteLeft=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"deleteLeft",precondition:g.a.writable,kbOpts:{weight:E,kbExpr:g.a.textInputFocus,primary:1,secondary:[1025],mac:{primary:1,secondary:[1025,294,257]}}})||this}return O(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){var i=d.a.deleteLeft(t.getPrevEditOperationType(),t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection})),o=i[0],r=i[1];o&&e.pushUndoStop(),e.executeCommands(this.id,r),t.setPrevEditOperationType(2)},t}(L))),S.DeleteRight=Object(r.g)(new(function(e){function t(){return e.call(this,{id:"deleteRight",precondition:g.a.writable,kbOpts:{weight:E,kbExpr:g.a.textInputFocus,primary:20,mac:{primary:20,secondary:[290,276]}}})||this}return O(t,e),t.prototype.runCoreEditingCommand=function(e,t,n){var i=d.a.deleteRight(t.getPrevEditOperationType(),t.context.config,t.context.model,t.getAll().map(function(e){return e.modelState.selection})),o=i[0],r=i[1];o&&e.pushUndoStop(),e.executeCommands(this.id,r),t.setPrevEditOperationType(3)},t}(L)));var I=function(e){function t(t){var n=e.call(this,t)||this;return n._editorHandler=t.editorHandler,n._inputHandler=t.inputHandler,n}return O(t,e),t.prototype.runCommand=function(e,t){var n=e.get(s.a).getFocusedCodeEditor();if(n&&n.hasTextFocus())return this._runEditorHandler(e,n,t);var i=document.activeElement;if(!(i&&["input","textarea"].indexOf(i.tagName.toLowerCase())>=0)){var o=e.get(s.a).getActiveCodeEditor();return o?(o.focus(),this._runEditorHandler(e,o,t)):void 0}document.execCommand(this._inputHandler)},t.prototype._runEditorHandler=function(e,t,n){var i=this._editorHandler;"string"==typeof i?t.trigger("keyboard",i,n):((n=n||{}).source="keyboard",i.runEditorCommand(e,t,n))},t}(r.a),D=function(e){function t(t,n,i){var o=e.call(this,{id:t,precondition:void 0,description:i})||this;return o._handlerId=n,o}return O(t,e),t.prototype.runCommand=function(e,t){var n=e.get(s.a).getFocusedCodeEditor();n&&n.trigger("keyboard",this._handlerId,t)},t}(r.a);function k(e,t){x(new D("default:"+e,e)),x(new D(e,e,t))}x(new I({editorHandler:C.SelectAll,inputHandler:"selectAll",id:"editor.action.selectAll",precondition:g.a.textInputFocus,kbOpts:{weight:E,kbExpr:null,primary:2079},menubarOpts:{menuId:22,group:"1_basic",title:i.a({key:"miSelectAll",comment:["&& denotes a mnemonic"]},"&&Select All"),order:1}})),x(new I({editorHandler:f.b.Undo,inputHandler:"undo",id:f.b.Undo,precondition:g.a.writable,kbOpts:{weight:E,kbExpr:g.a.textInputFocus,primary:2104},menubarOpts:{menuId:14,group:"1_do",title:i.a({key:"miUndo",comment:["&& denotes a mnemonic"]},"&&Undo"),order:1}})),x(new D("default:"+f.b.Undo,f.b.Undo)),x(new I({editorHandler:f.b.Redo,inputHandler:"redo",id:f.b.Redo,precondition:g.a.writable,kbOpts:{weight:E,kbExpr:g.a.textInputFocus,primary:2103,secondary:[3128],mac:{primary:3128}},menubarOpts:{menuId:14,group:"1_do",title:i.a({key:"miRedo",comment:["&& denotes a mnemonic"]},"&&Redo"),order:2}})),x(new D("default:"+f.b.Redo,f.b.Redo)),k(f.b.Type,{description:"Type",args:[{name:"args",schema:{type:"object",required:["text"],properties:{text:{type:"string"}}}}]}),k(f.b.ReplacePreviousChar),k(f.b.CompositionStart),k(f.b.CompositionEnd),k(f.b.Paste),k(f.b.Cut)},Hv4S:function(e,t){},Hxdr:function(e,t){e.exports=function(e,t){for(var n=-1,i=null==e?0:e.length,o=Array(i);++n=n)break;var o=e.charCodeAt(t);if(110===o||114===o||87===o)return!0}}return!1}(this.searchString):this.searchString.indexOf("\n")>=0;var t=null;try{t=i.k(this.searchString,this.isRegex,{matchCase:this.matchCase,wholeWord:!1,multiline:e,global:!0})}catch(e){return null}if(!t)return null;var n=!this.isRegex&&!e;return n&&this.searchString.toLowerCase()!==this.searchString.toUpperCase()&&(n=this.matchCase),new l(t,this.wordSeparators?Object(o.a)(this.wordSeparators):null,n?this.searchString:null)},e}();var l=function(){return function(e,t,n){this.regex=e,this.wordSeparators=t,this.simpleSearch=n}}();function c(e,t,n){if(!n)return new a.b(e,null);for(var i=[],o=0,r=t.length;o>0);t[o]>=e?i=o-1:t[o+1]>=e?(n=o,i=o):n=o+1}return n+1},e}(),h=function(){function e(){}return e.findMatches=function(e,t,n,i,o){var r=t.parseSearchRequest();return r?r.regex.multiline?this._doFindMatchesMultiline(e,n,new f(r.wordSeparators,r.regex),i,o):this._doFindMatchesLineByLine(e,n,r,i,o):[]},e._getMultilineMatchRange=function(e,t,n,i,o,r){var a,u,l=0;if(a=i?t+o+(l=i.findLineFeedCountBeforeOffset(o)):t+o,i){var c=i.findLineFeedCountBeforeOffset(o+r.length)-l;u=a+r.length+c}else u=a+r.length;var d=e.getPositionAt(a),h=e.getPositionAt(u);return new s.a(d.lineNumber,d.column,h.lineNumber,h.column)},e._doFindMatchesMultiline=function(e,t,n,i,o){var r,s=e.getOffsetAt(t.getStartPosition()),a=e.getValueInRange(t,1),u="\r\n"===e.getEOL()?new d(a):null,l=[],h=0;for(n.reset(0);r=n.next(a);)if(l[h++]=c(this._getMultilineMatchRange(e,s,a,u,r.index,r[0]),r,i),h>=o)return l;return l},e._doFindMatchesLineByLine=function(e,t,n,i,o){var r=[],s=0;if(t.startLineNumber===t.endLineNumber){var a=e.getLineContent(t.startLineNumber).substring(t.startColumn-1,t.endColumn-1);return s=this._findMatchesInLine(n,a,t.startLineNumber,t.startColumn-1,s,r,i,o),r}var u=e.getLineContent(t.startLineNumber).substring(t.startColumn-1);s=this._findMatchesInLine(n,u,t.startLineNumber,t.startColumn-1,s,r,i,o);for(var l=t.startLineNumber+1;l=l))return o;return o}var v,y=new f(e.wordSeparators,e.regex);y.reset(0);do{if((v=y.next(t))&&(r[o++]=c(new s.a(n,v.index+1+i,n,v.index+1+v[0].length+i),v,u),o>=l))return o}while(v);return o},e.findNextMatch=function(e,t,n,i){var o=t.parseSearchRequest();if(!o)return null;var r=new f(o.wordSeparators,o.regex);return o.regex.multiline?this._doFindNextMatchMultiline(e,n,r,i):this._doFindNextMatchLineByLine(e,n,r,i)},e._doFindNextMatchMultiline=function(e,t,n,i){var o=new r.a(t.lineNumber,1),a=e.getOffsetAt(o),u=e.getLineCount(),l=e.getValueInRange(new s.a(o.lineNumber,o.column,u,e.getLineMaxColumn(u)),1),h="\r\n"===e.getEOL()?new d(l):null;n.reset(t.column-1);var p=n.next(l);return p?c(this._getMultilineMatchRange(e,a,l,h,p.index,p[0]),p,i):1!==t.lineNumber||1!==t.column?this._doFindNextMatchMultiline(e,new r.a(1,1),n,i):null},e._doFindNextMatchLineByLine=function(e,t,n,i){var o=e.getLineCount(),r=t.lineNumber,s=e.getLineContent(r),a=this._findFirstMatchInLine(n,s,r,t.column,i);if(a)return a;for(var u=1;u<=o;u++){var l=(r+u-1)%o,c=e.getLineContent(l+1),d=this._findFirstMatchInLine(n,c,l+1,1,i);if(d)return d}return null},e._findFirstMatchInLine=function(e,t,n,i,o){e.reset(i-1);var r=e.next(t);return r?c(new s.a(n,r.index+1,n,r.index+1+r[0].length),r,o):null},e.findPreviousMatch=function(e,t,n,i){var o=t.parseSearchRequest();if(!o)return null;var r=new f(o.wordSeparators,o.regex);return o.regex.multiline?this._doFindPreviousMatchMultiline(e,n,r,i):this._doFindPreviousMatchLineByLine(e,n,r,i)},e._doFindPreviousMatchMultiline=function(e,t,n,i){var o=this._doFindMatchesMultiline(e,new s.a(1,1,t.lineNumber,t.column),n,i,9990);if(o.length>0)return o[o.length-1];var a=e.getLineCount();return t.lineNumber!==a||t.column!==e.getLineMaxColumn(a)?this._doFindPreviousMatchMultiline(e,new r.a(a,e.getLineMaxColumn(a)),n,i):null},e._doFindPreviousMatchLineByLine=function(e,t,n,i){var o=e.getLineCount(),r=t.lineNumber,s=e.getLineContent(r).substring(0,t.column-1),a=this._findLastMatchInLine(n,s,r,i);if(a)return a;for(var u=1;u<=o;u++){var l=(o+r-u-1)%o,c=e.getLineContent(l+1),d=this._findLastMatchInLine(n,c,l+1,i);if(d)return d}return null},e._findLastMatchInLine=function(e,t,n,i){var o,r=null;for(e.reset(0);o=e.next(t);)r=c(new s.a(n,o.index+1,n,o.index+1+o[0].length),o,i);return r},e}();function p(e,t,n,i,o){return function(e,t,n,i,o){if(0===i)return!0;var r=t.charCodeAt(i-1);if(0!==e.get(r))return!0;if(13===r||10===r)return!0;if(o>0){var s=t.charCodeAt(i);if(0!==e.get(s))return!0}return!1}(e,t,0,i,o)&&function(e,t,n,i,o){if(i+o===n)return!0;var r=t.charCodeAt(i+o);if(0!==e.get(r))return!0;if(13===r||10===r)return!0;if(o>0){var s=t.charCodeAt(i+o-1);if(0!==e.get(s))return!0}return!1}(e,t,n,i,o)}var f=function(){function e(e,t){this._wordSeparators=e,this._searchRegex=t,this._prevMatchStartIndex=-1,this._prevMatchLength=0}return e.prototype.reset=function(e){this._searchRegex.lastIndex=e,this._prevMatchStartIndex=-1,this._prevMatchLength=0},e.prototype.next=function(e){var t,n=e.length;do{if(this._prevMatchStartIndex+this._prevMatchLength===n)return null;if(!(t=this._searchRegex.exec(e)))return null;var i=t.index,o=t[0].length;if(i===this._prevMatchStartIndex&&o===this._prevMatchLength){if(0===o){this._searchRegex.lastIndex+=1;continue}return null}if(this._prevMatchStartIndex=i,this._prevMatchLength=o,!this._wordSeparators||p(this._wordSeparators,e,n,i,o))return t}while(t);return null},e}()},IG52:function(e,t,n){"use strict";n.d(t,"c",function(){return g}),n.d(t,"d",function(){return m}),n.d(t,"b",function(){return _}),n.d(t,"a",function(){return y});var i,o=n("LC7R"),r=(n.n(o),n("ZfGv")),s=n("hK2W"),a=n("tqet"),u=n("AKCZ"),l=n("7/Cv"),c=n("KIxu"),d=n("Bug4"),h=n("gzF+"),p=n("Kp7x"),f=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),g=function(e){function t(t,n,i){var o=e.call(this)||this;return o.options=i,o._context=t||o,o._action=n,n instanceof u.a&&o._register(n.onDidChange(function(e){o.element&&o.handleActionChangeEvent(e)})),o}return f(t,e),t.prototype.handleActionChangeEvent=function(e){void 0!==e.enabled&&this.updateEnabled(),void 0!==e.checked&&this.updateChecked(),void 0!==e.class&&this.updateClass(),void 0!==e.label&&(this.updateLabel(),this.updateTooltip()),void 0!==e.tooltip&&this.updateTooltip()},Object.defineProperty(t.prototype,"actionRunner",{get:function(){return this._actionRunner},set:function(e){this._actionRunner=e},enumerable:!0,configurable:!0}),t.prototype.getAction=function(){return this._action},t.prototype.isEnabled=function(){return this._action.enabled},t.prototype.setActionContext=function(e){this._context=e},t.prototype.render=function(e){var t=this;this.element=e,d.b.addTarget(e);var n=this.options&&this.options.draggable;n&&(e.draggable=!0),this._register(l.h(this.element,d.a.Tap,function(e){return t.onClick(e)})),this._register(l.h(this.element,l.d.MOUSE_DOWN,function(e){n||l.c.stop(e,!0),t._action.enabled&&0===e.button&&t.element&&l.f(t.element,"active")})),this._register(l.h(this.element,l.d.CLICK,function(e){l.c.stop(e,!0),t.options&&t.options.isMenu?t.onClick(e):r.h(function(){return t.onClick(e)})})),this._register(l.h(this.element,l.d.DBLCLICK,function(e){l.c.stop(e,!0)})),[l.d.MOUSE_UP,l.d.MOUSE_OUT].forEach(function(e){t._register(l.h(t.element,e,function(e){l.c.stop(e),l.I(t.element,"active")}))})},t.prototype.onClick=function(e){var t;l.c.stop(e,!0),c.k(this._context)?t=e:(t=this._context,c.h(t)&&(t.event=e)),this._actionRunner.run(this._action,t)},t.prototype.focus=function(){this.element&&(this.element.focus(),l.f(this.element,"focused"))},t.prototype.blur=function(){this.element&&(this.element.blur(),l.I(this.element,"focused"))},t.prototype.updateEnabled=function(){},t.prototype.updateLabel=function(){},t.prototype.updateTooltip=function(){},t.prototype.updateClass=function(){},t.prototype.updateChecked=function(){},t.prototype.dispose=function(){this.element&&(l.K(this.element),this.element=void 0),e.prototype.dispose.call(this)},t}(a.a),m=function(e){function t(n){var i=e.call(this,t.ID,n,n?"separator text":"separator")||this;return i.checked=!1,i.radio=!1,i.enabled=!1,i}return f(t,e),t.ID="vs.actions.separator",t}(u.a),_=function(e){function t(t,n,i){void 0===i&&(i={});var o=e.call(this,t,n,i)||this;return o.options=i,o.options.icon=void 0!==i.icon&&i.icon,o.options.label=void 0===i.label||i.label,o.cssClass="",o}return f(t,e),t.prototype.render=function(t){e.prototype.render.call(this,t),this.element&&(this.label=l.m(this.element,l.a("a.action-label"))),this._action.id===m.ID?this.label.setAttribute("role","presentation"):this.options.isMenu?this.label.setAttribute("role","menuitem"):this.label.setAttribute("role","button"),this.options.label&&this.options.keybinding&&this.element&&(l.m(this.element,l.a("span.keybinding")).textContent=this.options.keybinding),this.updateClass(),this.updateLabel(),this.updateTooltip(),this.updateEnabled(),this.updateChecked()},t.prototype.focus=function(){e.prototype.focus.call(this),this.label.focus()},t.prototype.updateLabel=function(){this.options.label&&(this.label.textContent=this.getAction().label)},t.prototype.updateTooltip=function(){var e=null;this.getAction().tooltip?e=this.getAction().tooltip:!this.options.label&&this.getAction().label&&this.options.icon&&(e=this.getAction().label,this.options.keybinding&&(e=s.a({key:"titleLabel",comment:["action title","action keybinding"]},"{0} ({1})",e,this.options.keybinding))),e&&(this.label.title=e)},t.prototype.updateClass=function(){this.cssClass&&l.J(this.label,this.cssClass),this.options.icon?(this.cssClass=this.getAction().class,l.f(this.label,"icon"),this.cssClass&&l.g(this.label,this.cssClass),this.updateEnabled()):l.I(this.label,"icon")},t.prototype.updateEnabled=function(){this.getAction().enabled?(this.label.removeAttribute("aria-disabled"),this.element&&l.I(this.element,"disabled"),l.I(this.label,"disabled"),this.label.tabIndex=0):(this.label.setAttribute("aria-disabled","true"),this.element&&l.f(this.element,"disabled"),l.f(this.label,"disabled"),l.L(this.label))},t.prototype.updateChecked=function(){this.getAction().checked?l.f(this.label,"checked"):l.I(this.label,"checked")},t}(g),v={orientation:0,context:null,triggerKeys:{keys:[3,10],keyDown:!1}},y=function(e){function t(t,n){void 0===n&&(n=v);var i,o,r=e.call(this)||this;switch(r._onDidBlur=r._register(new p.a),r.onDidBlur=r._onDidBlur.event,r._onDidCancel=r._register(new p.a),r.onDidCancel=r._onDidCancel.event,r._onDidRun=r._register(new p.a),r.onDidRun=r._onDidRun.event,r._onDidBeforeRun=r._register(new p.a),r.onDidBeforeRun=r._onDidBeforeRun.event,r.options=n,r._context=n.context,r.options.triggerKeys||(r.options.triggerKeys=v.triggerKeys),r.options.actionRunner?r._actionRunner=r.options.actionRunner:(r._actionRunner=new u.b,r._register(r._actionRunner)),r._register(r._actionRunner.onDidRun(function(e){return r._onDidRun.fire(e)})),r._register(r._actionRunner.onDidBeforeRun(function(e){return r._onDidBeforeRun.fire(e)})),r.viewItems=[],r.focusedItem=void 0,r.domNode=document.createElement("div"),r.domNode.className="monaco-action-bar",!1!==n.animated&&l.f(r.domNode,"animated"),r.options.orientation){case 0:i=15,o=17;break;case 1:i=17,o=15,r.domNode.className+=" reverse";break;case 2:i=16,o=18,r.domNode.className+=" vertical";break;case 3:i=18,o=16,r.domNode.className+=" vertical reverse"}return r._register(l.h(r.domNode,l.d.KEY_DOWN,function(e){var t=new h.a(e),n=!0;t.equals(i)?r.focusPrevious():t.equals(o)?r.focusNext():t.equals(9)?r.cancel():r.isTriggerKeyEvent(t)?r.options.triggerKeys&&r.options.triggerKeys.keyDown&&r.doTrigger(t):n=!1,n&&(t.preventDefault(),t.stopPropagation())})),r._register(l.h(r.domNode,l.d.KEY_UP,function(e){var t=new h.a(e);r.isTriggerKeyEvent(t)?(r.options.triggerKeys&&!r.options.triggerKeys.keyDown&&r.doTrigger(t),t.preventDefault(),t.stopPropagation()):(t.equals(2)||t.equals(1026))&&r.updateFocusedItem()})),r.focusTracker=r._register(l.S(r.domNode)),r._register(r.focusTracker.onDidBlur(function(){document.activeElement!==r.domNode&&l.E(document.activeElement,r.domNode)||(r._onDidBlur.fire(),r.focusedItem=void 0)})),r._register(r.focusTracker.onDidFocus(function(){return r.updateFocusedItem()})),r.actionsList=document.createElement("ul"),r.actionsList.className="actions-container",r.actionsList.setAttribute("role","toolbar"),r.options.ariaLabel&&r.actionsList.setAttribute("aria-label",r.options.ariaLabel),r.domNode.appendChild(r.actionsList),t.appendChild(r.domNode),r}return f(t,e),t.prototype.isTriggerKeyEvent=function(e){var t=!1;return this.options.triggerKeys&&this.options.triggerKeys.keys.forEach(function(n){t=t||e.equals(n)}),t},t.prototype.updateFocusedItem=function(){for(var e=0;e=n.actionsList.children.length?(n.actionsList.appendChild(r),n.viewItems.push(i)):(n.actionsList.insertBefore(r,n.actionsList.children[o]),n.viewItems.splice(o,0,i),o++)})},t.prototype.clear=function(){this.viewItems=Object(a.f)(this.viewItems),l.p(this.actionsList)},t.prototype.isEmpty=function(){return 0===this.viewItems.length},t.prototype.focus=function(e){var t=!1,n=void 0;void 0===e?t=!0:"number"==typeof e?n=e:"boolean"==typeof e&&(t=e),t&&void 0===this.focusedItem?(this.focusedItem=this.viewItems.length-1,this.focusNext()):(void 0!==n&&(this.focusedItem=n),this.updateFocus())},t.prototype.focusNext=function(){void 0===this.focusedItem&&(this.focusedItem=this.viewItems.length-1);var e,t=this.focusedItem;do{this.focusedItem=(this.focusedItem+1)%this.viewItems.length,e=this.viewItems[this.focusedItem]}while(this.focusedItem!==t&&!e.isEnabled());this.focusedItem!==t||e.isEnabled()||(this.focusedItem=void 0),this.updateFocus()},t.prototype.focusPrevious=function(){void 0===this.focusedItem&&(this.focusedItem=0);var e,t=this.focusedItem;do{this.focusedItem=this.focusedItem-1,this.focusedItem<0&&(this.focusedItem=this.viewItems.length-1),e=this.viewItems[this.focusedItem]}while(this.focusedItem!==t&&!e.isEnabled());this.focusedItem!==t||e.isEnabled()||(this.focusedItem=void 0),this.updateFocus(!0)},t.prototype.updateFocus=function(e){void 0===this.focusedItem&&this.actionsList.focus();for(var t=0;t=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},g=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},m=function(e){function t(t,n,i,o,r,s,a,u,l,c){var d=e.call(this,t,i.getRawConfiguration(),{},o,r,s,a,u,l,c)||this;return d._parentEditor=i,d._overwriteOptions=n,e.prototype.updateOptions.call(d,d._overwriteOptions),d._register(i.onDidChangeConfiguration(function(e){return d._onParentConfigurationChanged(e)})),d}return p(t,e),t.prototype.getParentEditor=function(){return this._parentEditor},t.prototype._onParentConfigurationChanged=function(t){e.prototype.updateOptions.call(this,this._parentEditor.getRawConfiguration()),e.prototype.updateOptions.call(this,this._overwriteOptions)},t.prototype.updateOptions=function(t){o.g(this._overwriteOptions,t,!0),e.prototype.updateOptions.call(this,this._overwriteOptions)},t=f([g(3,l.a),g(4,r.a),g(5,a.b),g(6,u.c),g(7,d.c),g(8,c.a),g(9,h.b)],t)}(s.a)},ItKl:function(e,t,n){"use strict";n.d(t,"b",function(){return l}),n.d(t,"a",function(){return c});var i=n("tqet"),o=n("KIxu"),r=n("JVO/"),s=n("Kp7x"),a=n("EMhq"),u=n("WTFd"),l=Object(r.c)("commandService"),c=new(function(){function e(){this._commands=new Map,this._onDidRegisterCommand=new s.a,this.onDidRegisterCommand=this._onDidRegisterCommand.event}return e.prototype.registerCommand=function(e,t){var n=this;if(!e)throw new Error("invalid command");if("string"==typeof e){if(!t)throw new Error("invalid command");return this.registerCommand({id:e,handler:t})}if(e.description){for(var r=[],s=0,u=e.description.args;s1)&&l.fire(e),u=0},n)})},onLastListenerRemove:function(){r.dispose()}});return l.event},e.stopwatch=function(e){var i=(new Date).getTime();return n(t(e),function(e){return(new Date).getTime()-i})},e.latch=u,e.buffer=function(e,t,n){void 0===t&&(t=!1),void 0===n&&(n=[]);var i=n.slice(),o=e(function(e){i?i.push(e):s.fire(e)}),r=function(){i&&i.forEach(function(e){return s.fire(e)}),i=null},s=new h({onFirstListenerAdd:function(){o||(o=e(function(e){return s.fire(e)}))},onFirstListenerDidAdd:function(){i&&(t?setTimeout(r):r())},onLastListenerRemove:function(){o&&o.dispose(),o=null}});return s.event};var l=function(){function e(e){this.event=e}return e.prototype.map=function(t){return new e(n(this.event,t))},e.prototype.forEach=function(t){return new e(i(this.event,t))},e.prototype.filter=function(t){return new e(o(this.event,t))},e.prototype.reduce=function(t,n){return new e(r(this.event,t,n))},e.prototype.latch=function(){return new e(u(this.event))},e.prototype.on=function(e,t,n){return this.event(e,t,n)},e.prototype.once=function(e,n,i){return t(this.event)(e,n,i)},e}();e.chain=function(e){return new l(e)},e.fromNodeEventEmitter=function(e,t,n){void 0===n&&(n=function(e){return e});var i=function(){for(var e=[],t=0;t0?new d(this._options&&this._options.leakWarningThreshold):void 0}return Object.defineProperty(e.prototype,"event",{get:function(){var t=this;return this._event||(this._event=function(n,i,o){t._listeners||(t._listeners=new u.a);var r=t._listeners.isEmpty();r&&t._options&&t._options.onFirstListenerAdd&&t._options.onFirstListenerAdd(t);var s,l,c=t._listeners.push(i?[n,i]:n);return r&&t._options&&t._options.onFirstListenerDidAdd&&t._options.onFirstListenerDidAdd(t),t._options&&t._options.onListenerDidAdd&&t._options.onListenerDidAdd(t,n,i),t._leakageMon&&(s=t._leakageMon.check(t._listeners.size)),l={dispose:function(){(s&&s(),l.dispose=e._noop,t._disposed)||(c(),t._options&&t._options.onLastListenerRemove&&(t._listeners&&!t._listeners.isEmpty()||t._options.onLastListenerRemove(t)))}},o instanceof a.b?o.add(l):Array.isArray(o)&&o.push(l),l}),this._event},enumerable:!0,configurable:!0}),e.prototype.fire=function(e){if(this._listeners){this._deliveryQueue||(this._deliveryQueue=new u.a);for(var t=this._listeners.iterator(),n=t.next();!n.done;n=t.next())this._deliveryQueue.push([n.value,e]);for(;this._deliveryQueue.size>0;){var i=this._deliveryQueue.shift(),o=i[0],s=i[1];try{"function"==typeof o?o.call(void 0,s):o[0].call(o[1],s)}catch(n){Object(r.e)(n)}}}},e.prototype.dispose=function(){this._listeners&&this._listeners.clear(),this._deliveryQueue&&this._deliveryQueue.clear(),this._leakageMon&&this._leakageMon.dispose(),this._disposed=!0},e._noop=function(){},e}(),p=function(e){function t(t){var n=e.call(this,t)||this;return n._isPaused=0,n._eventQueue=new u.a,n._mergeFn=t&&t.merge,n}return l(t,e),t.prototype.pause=function(){this._isPaused++},t.prototype.resume=function(){if(0!==this._isPaused&&0==--this._isPaused)if(this._mergeFn){var t=this._eventQueue.toArray();this._eventQueue.clear(),e.prototype.fire.call(this,this._mergeFn(t))}else for(;!this._isPaused&&0!==this._eventQueue.size;)e.prototype.fire.call(this,this._eventQueue.shift())},t.prototype.fire=function(t){this._listeners&&(0!==this._isPaused?this._eventQueue.push(t):e.prototype.fire.call(this,t))},t}(h),f=function(){function e(){var e=this;this.hasListeners=!1,this.events=[],this.emitter=new h({onFirstListenerAdd:function(){return e.onFirstListenerAdd()},onLastListenerRemove:function(){return e.onLastListenerRemove()}})}return Object.defineProperty(e.prototype,"event",{get:function(){return this.emitter.event},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this,n={event:e,listener:null};this.events.push(n),this.hasListeners&&this.hook(n);return Object(a.h)(Object(s.a)(function(){t.hasListeners&&t.unhook(n);var e=t.events.indexOf(n);t.events.splice(e,1)}))},e.prototype.onFirstListenerAdd=function(){var e=this;this.hasListeners=!0,this.events.forEach(function(t){return e.hook(t)})},e.prototype.onLastListenerRemove=function(){var e=this;this.hasListeners=!1,this.events.forEach(function(t){return e.unhook(t)})},e.prototype.hook=function(e){var t=this;e.listener=e.event(function(e){return t.emitter.fire(e)})},e.prototype.unhook=function(e){e.listener&&e.listener.dispose(),e.listener=null},e.prototype.dispose=function(){this.emitter.dispose()},e}(),g=function(){function e(){this.buffers=[]}return e.prototype.wrapEvent=function(e){var t=this;return function(n,i,o){return e(function(e){var o=t.buffers[t.buffers.length-1];o?o.push(function(){return n.call(i,e)}):n.call(i,e)},void 0,o)}},e.prototype.bufferEvents=function(e){var t=[];this.buffers.push(t);var n=e();return this.buffers.pop(),t.forEach(function(e){return e()}),n},e}(),m=function(){function e(){var e=this;this.listening=!1,this.inputEvent=o.None,this.inputEventListener=a.a.None,this.emitter=new h({onFirstListenerDidAdd:function(){e.listening=!0,e.inputEventListener=e.inputEvent(e.emitter.fire,e.emitter)},onLastListenerRemove:function(){e.listening=!1,e.inputEventListener.dispose()}}),this.event=this.emitter.event}return Object.defineProperty(e.prototype,"input",{set:function(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.inputEventListener.dispose(),this.emitter.dispose()},e}()},Kx4b:function(e,t,n){"use strict";n.d(t,"a",function(){return a});var i=n("uNfg"),o=n("ZfGv"),r=n("ItKl"),s=n("RWr8"),a=new(function(){function e(){this._coreKeybindings=[],this._extensionKeybindings=[],this._cachedMergedKeybindings=null}return e.bindToCurrentPlatform=function(e){if(1===o.a){if(e&&e.win)return e.win}else if(2===o.a){if(e&&e.mac)return e.mac}else if(e&&e.linux)return e.linux;return e},e.prototype.registerKeybindingRule=function(t){var n=e.bindToCurrentPlatform(t);n&&n.primary&&((a=Object(i.f)(n.primary,o.a))&&this._registerDefaultKeybinding(a,t.id,void 0,t.weight,0,t.when));if(n&&Array.isArray(n.secondary))for(var r=0,s=n.secondary.length;r=21&&e<=30||(e>=31&&e<=56||(80===e||81===e||82===e||83===e||84===e||85===e||86===e||110===e||111===e||87===e||88===e||89===e||90===e||91===e||92===e))},e.prototype._assertNoCtrlAlt=function(t,n){t.ctrlKey&&t.altKey&&!t.metaKey&&e._mightProduceChar(t.keyCode)&&console.warn("Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ",t," for ",n)},e.prototype._registerDefaultKeybinding=function(e,t,n,i,r,s){1===o.a&&this._assertNoCtrlAlt(e.parts[0],t),this._coreKeybindings.push({keybinding:e,command:t,commandArgs:n,when:s,weight1:i,weight2:r}),this._cachedMergedKeybindings=null},e.prototype.getDefaultKeybindings=function(){return this._cachedMergedKeybindings||(this._cachedMergedKeybindings=[].concat(this._coreKeybindings).concat(this._extensionKeybindings),this._cachedMergedKeybindings.sort(u)),this._cachedMergedKeybindings.slice(0)},e}());function u(e,t){return e.weight1!==t.weight1?e.weight1-t.weight1:e.commandt.command?1:e.weight2-t.weight2}s.a.add("platform.keybindingsRegistry",a)},L5KM:function(e,t,n){"use strict";n.d(t,"a",function(){return l}),t._36=d,n.d(t,"T",function(){return f}),n.d(t,"R",function(){return g}),n.d(t,"S",function(){return m}),n.d(t,"e",function(){return _}),n.d(t,"b",function(){return v}),n.d(t,"_46",function(){return y}),n.d(t,"_45",function(){return b}),n.d(t,"_48",function(){return C}),n.d(t,"W",function(){return w}),n.d(t,"Y",function(){return S}),n.d(t,"X",function(){return L}),n.d(t,"V",function(){return O}),n.d(t,"U",function(){return E}),n.d(t,"_2",function(){return N}),n.d(t,"_4",function(){return x}),n.d(t,"_3",function(){return I}),n.d(t,"_5",function(){return D}),n.d(t,"_7",function(){return k}),n.d(t,"_6",function(){return T}),n.d(t,"Z",function(){return M}),n.d(t,"_1",function(){return R}),n.d(t,"_0",function(){return A}),n.d(t,"_14",function(){return W}),n.d(t,"_15",function(){return j}),n.d(t,"_8",function(){return V}),n.d(t,"_9",function(){return B}),n.d(t,"_20",function(){return H}),n.d(t,"_21",function(){return z}),n.d(t,"_19",function(){return U}),n.d(t,"_17",function(){return K}),n.d(t,"_18",function(){return q}),n.d(t,"_10",function(){return G}),n.d(t,"_16",function(){return Z}),n.d(t,"_11",function(){return Y}),n.d(t,"_13",function(){return X}),n.d(t,"_12",function(){return J}),n.d(t,"_47",function(){return Q}),n.d(t,"_34",function(){return $}),n.d(t,"_33",function(){return ee}),n.d(t,"c",function(){return te}),n.d(t,"d",function(){return ne}),n.d(t,"_37",function(){return ie}),n.d(t,"_39",function(){return oe}),n.d(t,"_40",function(){return re}),n.d(t,"_38",function(){return se}),n.d(t,"_35",function(){return ae}),n.d(t,"_23",function(){return ue}),n.d(t,"_24",function(){return le}),n.d(t,"_22",function(){return ce}),n.d(t,"_27",function(){return de}),n.d(t,"_25",function(){return he}),n.d(t,"_26",function(){return pe}),n.d(t,"_28",function(){return fe}),n.d(t,"q",function(){return ge}),n.d(t,"p",function(){return me}),n.d(t,"M",function(){return _e}),n.d(t,"L",function(){return ve}),n.d(t,"G",function(){return ye}),n.d(t,"F",function(){return be}),n.d(t,"z",function(){return Ce}),n.d(t,"y",function(){return we}),n.d(t,"o",function(){return Se}),n.d(t,"x",function(){return Le}),n.d(t,"N",function(){return Oe}),n.d(t,"P",function(){return Ee}),n.d(t,"O",function(){return Ne}),n.d(t,"Q",function(){return xe}),n.d(t,"H",function(){return Ie}),n.d(t,"I",function(){return De}),n.d(t,"E",function(){return ke}),n.d(t,"J",function(){return Te}),n.d(t,"K",function(){return Me}),n.d(t,"r",function(){return Re}),n.d(t,"t",function(){return Ae}),n.d(t,"v",function(){return Pe}),n.d(t,"s",function(){return Fe}),n.d(t,"u",function(){return We}),n.d(t,"w",function(){return je}),n.d(t,"C",function(){return Ve}),n.d(t,"A",function(){return Be}),n.d(t,"B",function(){return He}),n.d(t,"D",function(){return ze}),n.d(t,"n",function(){return Ue}),n.d(t,"g",function(){return Ke}),n.d(t,"h",function(){return qe}),n.d(t,"j",function(){return Ge}),n.d(t,"l",function(){return Ze}),n.d(t,"k",function(){return Ye}),n.d(t,"m",function(){return Xe}),n.d(t,"i",function(){return Je}),n.d(t,"_43",function(){return Qe}),n.d(t,"_44",function(){return $e}),n.d(t,"_41",function(){return et}),n.d(t,"_42",function(){return tt}),n.d(t,"_31",function(){return nt}),n.d(t,"_32",function(){return it}),n.d(t,"_29",function(){return ot}),t.f=rt,t._30=function(){for(var e=[],t=0;te.length)return!1;for(var o=0;o=65&&r<=90&&r+32===s||s>=65&&s<=90&&s+32===r))return!1}return!0},e.prototype._createOperationsForBlockComment=function(t,n,i,o,r){var s,a=t.startLineNumber,u=t.startColumn,l=t.endLineNumber,d=t.endColumn,h=o.getLineContent(a),p=o.getLineContent(l),f=h.lastIndexOf(n,u-1+n.length),g=p.indexOf(i,d-1-i.length);if(-1!==f&&-1!==g)if(a===l){h.substring(f+n.length,g).indexOf(i)>=0&&(f=-1,g=-1)}else{var m=h.substring(f+n.length),_=p.substring(0,g);(m.indexOf(i)>=0||_.indexOf(i)>=0)&&(f=-1,g=-1)}-1!==f&&-1!==g?(f+n.length0&&32===p.charCodeAt(g-1)&&(i=" "+i,g-=1),s=e._createRemoveBlockCommentOperations(new c.a(a,f+n.length+1,l,g+1),n,i)):(s=e._createAddBlockCommentOperations(t,n,i),this._usedEndToken=1===s.length?i:null);for(var v=0,y=s;va?r-1:r}},e}(),m=this&&this.__extends||(i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),_=function(e){function t(t,n){var i=e.call(this,n)||this;return i._type=t,i}return m(t,e),t.prototype.run=function(e,t){if(t.hasModel()){for(var n=t.getModel(),i=[],o=t.getSelections(),r=n.getOptions(),s=0,a=o;s0&&"#"===n.charAt(n.length-1)?n.substring(0,n.length-1):n)]=t,this._onDidChangeSchema.fire(e)},e.prototype.notifySchemaChanged=function(e){this._onDidChangeSchema.fire(e)},e}());i.a.add(r.JSONContribution,s)},M1c9:function(e,t){e.exports=function(e,t,n){var i=-1,o=e.length;t<0&&(t=-t>o?0:o+t),(n=n>o?o:n)<0&&(n+=o),o=t>n?0:n-t>>>0,t>>>=0;for(var r=Array(o);++i'),O=encodeURIComponent(''),N=encodeURIComponent(''),I=encodeURIComponent(''),k=encodeURIComponent(''),M=encodeURIComponent('');function A(e,t){return"."+i.className(e).split(" ").join(".")+' { background: url("data:image/svg+xml,'+i.getSVGData(e,t)+'") center center no-repeat; height: 16px; width: 16px; }'}!function(e){e.getSVGData=function(e,t){switch(e){case w.a.Ignore:var n=t.type===d.d?g.a.fromHex("#75BEFF"):g.a.fromHex("#007ACC");return t.type===d.d?k+encodeURIComponent(n.toString())+T:M+encodeURIComponent(n.toString())+R;case w.a.Info:var i=t.type===d.d?g.a.fromHex("#007ACC"):g.a.fromHex("#75BEFF");return t.type===d.d?k+encodeURIComponent(i.toString())+T:M+encodeURIComponent(i.toString())+R;case w.a.Warning:var o=t.type===d.d?g.a.fromHex("#DDB100"):g.a.fromHex("#fc0");return t.type===d.d?N+encodeURIComponent(o.toString())+x:I+encodeURIComponent(o.toString())+D;case w.a.Error:var r=t.type===d.d?g.a.fromHex("#A1260D"):g.a.fromHex("#F48771");return t.type===d.d?S+encodeURIComponent(r.toString())+L:O+encodeURIComponent(r.toString())+E}return""},e.className=function(e){switch(e){case w.a.Ignore:return"severity-icon severity-ignore";case w.a.Info:return"severity-icon severity-info";case w.a.Warning:return"severity-icon severity-warning";case w.a.Error:return"severity-icon severity-error"}return""}}(i||(i={})),Object(d.f)(function(e,t){t.addRule(A(w.a.Error,e)),t.addRule(A(w.a.Warning,e)),t.addRule(A(w.a.Info,e)),t.addRule(A(w.a.Ignore,e))});var P,F=this&&this.__extends||(P=function(e,t){return(P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}P(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),W=function(){function e(e,t,n){var i=this;this._lines=0,this._longestLineLength=0,this._relatedDiagnostics=new WeakMap,this._disposables=[],this._editor=t;var o=document.createElement("div");o.className="descriptioncontainer",o.setAttribute("aria-live","assertive"),o.setAttribute("role","alert"),this._messageBlock=document.createElement("div"),p.f(this._messageBlock,"message"),o.appendChild(this._messageBlock),this._relatedBlock=document.createElement("div"),o.appendChild(this._relatedBlock),this._disposables.push(p.k(this._relatedBlock,"click",function(e){e.preventDefault();var t=i._relatedDiagnostics.get(e.target);t&&n(t)})),this._scrollable=new m.b(o,{horizontal:1,vertical:1,useShadows:!1,horizontalScrollbarSize:3,verticalScrollbarSize:3}),e.appendChild(this._scrollable.getDomNode()),this._disposables.push(this._scrollable.onScroll(function(e){o.style.left="-"+e.scrollLeft+"px",o.style.top="-"+e.scrollTop+"px"})),this._disposables.push(this._scrollable)}return e.prototype.dispose=function(){Object(s.f)(this._disposables)},e.prototype.update=function(e){var t=e.source,n=e.message,i=e.relatedInformation,o=e.code,r=n.split(/\r\n|\r|\n/g);this._lines=r.length,this._longestLineLength=0;for(var s=0,a=r;s1?o.a("problems","{0} of {1} problems",n,r):o.a("change","{0} of {1} problem",n,r);this.setTitle(Object(b.b)(d.uri),h)}this._icon.className=i.className(u.c.toSeverity(this._severity)),this.editor.revealPositionInCenter(c,0)},t.prototype.updateMarker=function(e){this._container.classList.remove("stale"),this._message.update(e)},t.prototype.showStale=function(){this._container.classList.add("stale"),this._relayout()},t.prototype._doLayoutBody=function(t,n){e.prototype._doLayoutBody.call(this,t,n),this._heightInPixel=t,this._message.layout(t,n),this._container.style.height=t+"px"},t.prototype._onWidth=function(e){this._message.layout(this._heightInPixel,e)},t.prototype._relayout=function(){e.prototype._relayout.call(this,this.computeRequiredHeight())},t.prototype.computeRequiredHeight=function(){return 3+this._message.getHeightInLines()},t}(y.c),V=Object(f._30)(f.q,f.p),B=Object(f._30)(f.M,f.L),H=Object(f._30)(f.G,f.F),z=Object(f._36)("editorMarkerNavigationError.background",{dark:V,light:V,hc:V},o.a("editorMarkerNavigationError","Editor marker navigation widget error color.")),U=Object(f._36)("editorMarkerNavigationWarning.background",{dark:B,light:B,hc:B},o.a("editorMarkerNavigationWarning","Editor marker navigation widget warning color.")),K=Object(f._36)("editorMarkerNavigationInfo.background",{dark:H,light:H,hc:H},o.a("editorMarkerNavigationInfo","Editor marker navigation widget info color.")),q=Object(f._36)("editorMarkerNavigation.background",{dark:"#2D2D30",light:g.a.white,hc:"#0C141F"},o.a("editorMarkerNavigationBackground","Editor marker navigation widget background."));Object(d.f)(function(e,t){var n=e.getColor(f._46);n&&t.addRule(".monaco-editor .marker-widget a { color: "+n+"; }")});var G=n("aL7J"),Z=n("vORD"),Y=n("zxiH"),X=n("C3c5"),J=n("AKCZ"),Q=n("NqM+");n.d(t,"MarkerController",function(){return re}),n.d(t,"NextMarkerAction",function(){return ae});var $=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),ee=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},te=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ne=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},ie=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=0?this._markers[this._nextIdx]:void 0;this._markers=e||[],this._markers.sort(se.compareMarker),this._nextIdx=t?Math.max(-1,Object(v.c)(this._markers,t,se.compareMarker)):-1,this._onMarkerSetChanged.fire(this)},e.prototype.withoutWatchingEditorPosition=function(e){this._ignoreSelectionChange=!0;try{e()}finally{this._ignoreSelectionChange=!1}},e.prototype._initIdx=function(e){for(var t=!1,n=this._editor.getPosition(),i=0;i0?this._nextIdx=(this._nextIdx-1+this._markers.length)%this._markers.length:i=!0),n!==this._nextIdx){var o=this._markers[this._nextIdx];this._onCurrentMarkerChanged.fire(o)}return i},e.prototype.canNavigate=function(){return this._markers.length>0},e.prototype.findMarkerAtPosition=function(e){for(var t=0,n=this._markers;t=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},b=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},C=function(e){function t(t,n,i){var o=e.call(this)||this;return o._editor=t,o._codeEditorService=n,o._configurationService=i,o._localToDispose=o._register(new l.b),o._decorationsIds=[],o._colorDatas=new Map,o._colorDecoratorIds=[],o._decorationsTypes=new Set,o._register(t.onDidChangeModel(function(e){o._isEnabled=o.isEnabled(),o.onModelChanged()})),o._register(t.onDidChangeModelLanguage(function(e){return o.onModelChanged()})),o._register(f.c.onDidChange(function(e){return o.onModelChanged()})),o._register(t.onDidChangeConfiguration(function(e){var t=o._isEnabled;o._isEnabled=o.isEnabled(),t!==o._isEnabled&&(o._isEnabled?o.onModelChanged():o.removeAllDecorations())})),o._timeoutTimer=null,o._computePromise=null,o._isEnabled=o.isEnabled(),o.onModelChanged(),o}return v(t,e),t.prototype.isEnabled=function(){var e=this._editor.getModel();if(!e)return!1;var t=e.getLanguageIdentifier(),n=this._configurationService.getValue(t.language);if(n){var i=n.colorDecorators;if(i&&void 0!==i.enable&&!i.enable)return i.enable}return this._editor.getConfiguration().contribInfo.colorDecorators},t.prototype.getId=function(){return t.ID},t.get=function(e){return e.getContribution(this.ID)},t.prototype.dispose=function(){this.stop(),this.removeAllDecorations(),e.prototype.dispose.call(this)},t.prototype.onModelChanged=function(){var e=this;if(this.stop(),this._isEnabled){var n=this._editor.getModel();n&&f.c.has(n)&&(this._localToDispose.add(this._editor.onDidChangeModelContent(function(n){e._timeoutTimer||(e._timeoutTimer=new i.e,e._timeoutTimer.cancelAndSet(function(){e._timeoutTimer=null,e.beginCompute()},t.RECOMPUTE_TIME))})),this.beginCompute())}},t.prototype.beginCompute=function(){var e=this;this._computePromise=Object(i.f)(function(t){var n=e._editor.getModel();return n?Object(g.b)(n,t):Promise.resolve([])}),this._computePromise.then(function(t){e.updateDecorations(t),e.updateColorDecorators(t),e._computePromise=null},r.e)},t.prototype.stop=function(){this._timeoutTimer&&(this._timeoutTimer.cancel(),this._timeoutTimer=null),this._computePromise&&(this._computePromise.cancel(),this._computePromise=null),this._localToDispose.clear()},t.prototype.updateDecorations=function(e){var t=this,n=e.map(function(e){return{range:{startLineNumber:e.colorInfo.range.startLineNumber,startColumn:e.colorInfo.range.startColumn,endLineNumber:e.colorInfo.range.endLineNumber,endColumn:e.colorInfo.range.endColumn},options:p.a.EMPTY}});this._decorationsIds=this._editor.deltaDecorations(this._decorationsIds,n),this._colorDatas=new Map,this._decorationsIds.forEach(function(n,i){return t._colorDatas.set(n,e[i])})},t.prototype.updateColorDecorators=function(e){for(var t=this,n=[],i={},r=0;rthis.selection.endLineNumber?this.targetSelection=new u.a(this.targetPosition.lineNumber-this.selection.endLineNumber+this.selection.startLineNumber,this.targetPosition.column,this.targetPosition.lineNumber,this.selection.startLineNumber===this.selection.endLineNumber?this.targetPosition.column+this.selection.endColumn-this.selection.startColumn:this.selection.endColumn):this.targetPosition.lineNumber0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=e._maxRounds){t();break}if(!o){t();break}var l=i.findNextBracket(o);if(!l){t();break}if(Date.now()-u>e._maxDuration){setTimeout(function(){return e._bracketsRightYield(t,n+1,i,o,s)});break}var c=l.close;if(l.isOpen){var d=a.has(c)?a.get(c):0;a.set(c,d+1)}else{d=a.has(c)?a.get(c):0;if(d-=1,a.set(c,Math.max(0,d)),d<0){var h=s.get(c);h||(h=new r.a,s.set(c,h)),h.push(l.range)}}o=l.range.getEndPosition()}},e._bracketsLeftYield=function(t,n,i,r,s,a){for(var u=new Map,l=Date.now();;){if(n>=e._maxRounds&&0===s.size){t();break}if(!r){t();break}var c=i.findPrevBracket(r);if(!c){t();break}if(Date.now()-l>e._maxDuration){setTimeout(function(){return e._bracketsLeftYield(t,n+1,i,r,s,a)});break}var d=c.close;if(c.isOpen){m=u.has(d)?u.get(d):0;if(m-=1,u.set(d,Math.max(0,m)),m<0){var h=s.get(d);if(h){var p=h.shift();0===h.size&&s.delete(d);var f=o.a.fromPositions(c.range.getEndPosition(),p.getStartPosition()),g=o.a.fromPositions(c.range.getStartPosition(),p.getEndPosition());a.push({range:f}),a.push({range:g}),e._addBracketLeading(i,g,a)}}}else{var m=u.has(d)?u.get(d):0;u.set(d,m+1)}r=c.range.getStartPosition()}},e._addBracketLeading=function(e,t,n){if(t.startLineNumber!==t.endLineNumber){var r=t.startLineNumber,s=e.getLineFirstNonWhitespaceColumn(r);0!==s&&s!==t.startColumn&&(n.push({range:o.a.fromPositions(new i.a(r,s),t.getEndPosition())}),n.push({range:o.a.fromPositions(new i.a(r,1),t.getEndPosition())}));var a=r-1;if(a>0){var u=e.getLineFirstNonWhitespaceColumn(a);u===t.startColumn&&u!==e.getLineLastNonWhitespaceColumn(a)&&(n.push({range:o.a.fromPositions(new i.a(a,u),t.getEndPosition())}),n.push({range:o.a.fromPositions(new i.a(a,1),t.getEndPosition())}))}}},e._maxDuration=30,e._maxRounds=2,e}()},NkRn:function(e,t,n){var i=n("TQ3y").Symbol;e.exports=i},"NqM+":function(e,t,n){"use strict";n.d(t,"a",function(){return o});var i=n("JVO/"),o=Object(i.c)("keybindingService")},Nr0y:function(e,t,n){"use strict";var i,o=n("hK2W"),r=n("aL7J");!function(e){e[e.Ignore=0]="Ignore",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(i||(i={})),function(e){var t="error",n="warning",i="warn",s="info",a=Object.create(null);a[e.Error]=o.a("sev.error","Error"),a[e.Warning]=o.a("sev.warning","Warning"),a[e.Info]=o.a("sev.info","Info"),e.fromValue=function(o){return o?r.n(t,o)?e.Error:r.n(n,o)||r.n(i,o)?e.Warning:r.n(s,o)?e.Info:e.Ignore:e.Ignore}}(i||(i={})),t.a=i},Ny4g:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i,o,r,s,a,u,l,c,d,h,p,f,g,m,_,v,y,b,C,w,S,L,O,E,N,x,I,D,k,T,M=n("iXRW"),R=(n("tZcU"),n("80kS")),A=n("Kp7x"),P=n("uNfg"),F=n("mrx5"),W=n("artP"),j=n("vTy2"),V=n("iHM7"),B=n("c6Qy");!function(e){e[e.Unnecessary=1]="Unnecessary",e[e.Deprecated=2]="Deprecated"}(i||(i={})),function(e){e[e.Hint=1]="Hint",e[e.Info=2]="Info",e[e.Warning=4]="Warning",e[e.Error=8]="Error"}(o||(o={})),function(e){e[e.Unknown=0]="Unknown",e[e.Backspace=1]="Backspace",e[e.Tab=2]="Tab",e[e.Enter=3]="Enter",e[e.Shift=4]="Shift",e[e.Ctrl=5]="Ctrl",e[e.Alt=6]="Alt",e[e.PauseBreak=7]="PauseBreak",e[e.CapsLock=8]="CapsLock",e[e.Escape=9]="Escape",e[e.Space=10]="Space",e[e.PageUp=11]="PageUp",e[e.PageDown=12]="PageDown",e[e.End=13]="End",e[e.Home=14]="Home",e[e.LeftArrow=15]="LeftArrow",e[e.UpArrow=16]="UpArrow",e[e.RightArrow=17]="RightArrow",e[e.DownArrow=18]="DownArrow",e[e.Insert=19]="Insert",e[e.Delete=20]="Delete",e[e.KEY_0=21]="KEY_0",e[e.KEY_1=22]="KEY_1",e[e.KEY_2=23]="KEY_2",e[e.KEY_3=24]="KEY_3",e[e.KEY_4=25]="KEY_4",e[e.KEY_5=26]="KEY_5",e[e.KEY_6=27]="KEY_6",e[e.KEY_7=28]="KEY_7",e[e.KEY_8=29]="KEY_8",e[e.KEY_9=30]="KEY_9",e[e.KEY_A=31]="KEY_A",e[e.KEY_B=32]="KEY_B",e[e.KEY_C=33]="KEY_C",e[e.KEY_D=34]="KEY_D",e[e.KEY_E=35]="KEY_E",e[e.KEY_F=36]="KEY_F",e[e.KEY_G=37]="KEY_G",e[e.KEY_H=38]="KEY_H",e[e.KEY_I=39]="KEY_I",e[e.KEY_J=40]="KEY_J",e[e.KEY_K=41]="KEY_K",e[e.KEY_L=42]="KEY_L",e[e.KEY_M=43]="KEY_M",e[e.KEY_N=44]="KEY_N",e[e.KEY_O=45]="KEY_O",e[e.KEY_P=46]="KEY_P",e[e.KEY_Q=47]="KEY_Q",e[e.KEY_R=48]="KEY_R",e[e.KEY_S=49]="KEY_S",e[e.KEY_T=50]="KEY_T",e[e.KEY_U=51]="KEY_U",e[e.KEY_V=52]="KEY_V",e[e.KEY_W=53]="KEY_W",e[e.KEY_X=54]="KEY_X",e[e.KEY_Y=55]="KEY_Y",e[e.KEY_Z=56]="KEY_Z",e[e.Meta=57]="Meta",e[e.ContextMenu=58]="ContextMenu",e[e.F1=59]="F1",e[e.F2=60]="F2",e[e.F3=61]="F3",e[e.F4=62]="F4",e[e.F5=63]="F5",e[e.F6=64]="F6",e[e.F7=65]="F7",e[e.F8=66]="F8",e[e.F9=67]="F9",e[e.F10=68]="F10",e[e.F11=69]="F11",e[e.F12=70]="F12",e[e.F13=71]="F13",e[e.F14=72]="F14",e[e.F15=73]="F15",e[e.F16=74]="F16",e[e.F17=75]="F17",e[e.F18=76]="F18",e[e.F19=77]="F19",e[e.NumLock=78]="NumLock",e[e.ScrollLock=79]="ScrollLock",e[e.US_SEMICOLON=80]="US_SEMICOLON",e[e.US_EQUAL=81]="US_EQUAL",e[e.US_COMMA=82]="US_COMMA",e[e.US_MINUS=83]="US_MINUS",e[e.US_DOT=84]="US_DOT",e[e.US_SLASH=85]="US_SLASH",e[e.US_BACKTICK=86]="US_BACKTICK",e[e.US_OPEN_SQUARE_BRACKET=87]="US_OPEN_SQUARE_BRACKET",e[e.US_BACKSLASH=88]="US_BACKSLASH",e[e.US_CLOSE_SQUARE_BRACKET=89]="US_CLOSE_SQUARE_BRACKET",e[e.US_QUOTE=90]="US_QUOTE",e[e.OEM_8=91]="OEM_8",e[e.OEM_102=92]="OEM_102",e[e.NUMPAD_0=93]="NUMPAD_0",e[e.NUMPAD_1=94]="NUMPAD_1",e[e.NUMPAD_2=95]="NUMPAD_2",e[e.NUMPAD_3=96]="NUMPAD_3",e[e.NUMPAD_4=97]="NUMPAD_4",e[e.NUMPAD_5=98]="NUMPAD_5",e[e.NUMPAD_6=99]="NUMPAD_6",e[e.NUMPAD_7=100]="NUMPAD_7",e[e.NUMPAD_8=101]="NUMPAD_8",e[e.NUMPAD_9=102]="NUMPAD_9",e[e.NUMPAD_MULTIPLY=103]="NUMPAD_MULTIPLY",e[e.NUMPAD_ADD=104]="NUMPAD_ADD",e[e.NUMPAD_SEPARATOR=105]="NUMPAD_SEPARATOR",e[e.NUMPAD_SUBTRACT=106]="NUMPAD_SUBTRACT",e[e.NUMPAD_DECIMAL=107]="NUMPAD_DECIMAL",e[e.NUMPAD_DIVIDE=108]="NUMPAD_DIVIDE",e[e.KEY_IN_COMPOSITION=109]="KEY_IN_COMPOSITION",e[e.ABNT_C1=110]="ABNT_C1",e[e.ABNT_C2=111]="ABNT_C2",e[e.MAX_VALUE=112]="MAX_VALUE"}(r||(r={})),function(e){e[e.LTR=0]="LTR",e[e.RTL=1]="RTL"}(s||(s={})),function(e){e[e.Auto=1]="Auto",e[e.Hidden=2]="Hidden",e[e.Visible=3]="Visible"}(a||(a={})),function(e){e[e.Left=1]="Left",e[e.Center=2]="Center",e[e.Right=4]="Right",e[e.Full=7]="Full"}(u||(u={})),function(e){e[e.Inline=1]="Inline"}(l||(l={})),function(e){e[e.TextDefined=0]="TextDefined",e[e.LF=1]="LF",e[e.CRLF=2]="CRLF"}(c||(c={})),function(e){e[e.LF=1]="LF",e[e.CRLF=2]="CRLF"}(d||(d={})),function(e){e[e.LF=0]="LF",e[e.CRLF=1]="CRLF"}(h||(h={})),function(e){e[e.AlwaysGrowsWhenTypingAtEdges=0]="AlwaysGrowsWhenTypingAtEdges",e[e.NeverGrowsWhenTypingAtEdges=1]="NeverGrowsWhenTypingAtEdges",e[e.GrowsOnlyWhenTypingBefore=2]="GrowsOnlyWhenTypingBefore",e[e.GrowsOnlyWhenTypingAfter=3]="GrowsOnlyWhenTypingAfter"}(p||(p={})),function(e){e[e.Smooth=0]="Smooth",e[e.Immediate=1]="Immediate"}(f||(f={})),function(e){e[e.NotSet=0]="NotSet",e[e.ContentFlush=1]="ContentFlush",e[e.RecoverFromMarkers=2]="RecoverFromMarkers",e[e.Explicit=3]="Explicit",e[e.Paste=4]="Paste",e[e.Undo=5]="Undo",e[e.Redo=6]="Redo"}(g||(g={})),function(e){e[e.None=0]="None",e[e.Small=1]="Small",e[e.Large=2]="Large",e[e.SmallBlocks=3]="SmallBlocks",e[e.LargeBlocks=4]="LargeBlocks"}(m||(m={})),function(e){e[e.None=0]="None",e[e.Same=1]="Same",e[e.Indent=2]="Indent",e[e.DeepIndent=3]="DeepIndent"}(_||(_={})),function(e){e[e.Hidden=0]="Hidden",e[e.Blink=1]="Blink",e[e.Smooth=2]="Smooth",e[e.Phase=3]="Phase",e[e.Expand=4]="Expand",e[e.Solid=5]="Solid"}(v||(v={})),function(e){e[e.Line=1]="Line",e[e.Block=2]="Block",e[e.Underline=3]="Underline",e[e.LineThin=4]="LineThin",e[e.BlockOutline=5]="BlockOutline",e[e.UnderlineThin=6]="UnderlineThin"}(y||(y={})),function(e){e[e.Off=0]="Off",e[e.On=1]="On",e[e.Relative=2]="Relative",e[e.Interval=3]="Interval",e[e.Custom=4]="Custom"}(b||(b={})),function(e){e[e.EXACT=0]="EXACT",e[e.ABOVE=1]="ABOVE",e[e.BELOW=2]="BELOW"}(C||(C={})),function(e){e[e.TOP_RIGHT_CORNER=0]="TOP_RIGHT_CORNER",e[e.BOTTOM_RIGHT_CORNER=1]="BOTTOM_RIGHT_CORNER",e[e.TOP_CENTER=2]="TOP_CENTER"}(w||(w={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.TEXTAREA=1]="TEXTAREA",e[e.GUTTER_GLYPH_MARGIN=2]="GUTTER_GLYPH_MARGIN",e[e.GUTTER_LINE_NUMBERS=3]="GUTTER_LINE_NUMBERS",e[e.GUTTER_LINE_DECORATIONS=4]="GUTTER_LINE_DECORATIONS",e[e.GUTTER_VIEW_ZONE=5]="GUTTER_VIEW_ZONE",e[e.CONTENT_TEXT=6]="CONTENT_TEXT",e[e.CONTENT_EMPTY=7]="CONTENT_EMPTY",e[e.CONTENT_VIEW_ZONE=8]="CONTENT_VIEW_ZONE",e[e.CONTENT_WIDGET=9]="CONTENT_WIDGET",e[e.OVERVIEW_RULER=10]="OVERVIEW_RULER",e[e.SCROLLBAR=11]="SCROLLBAR",e[e.OVERLAY_WIDGET=12]="OVERLAY_WIDGET",e[e.OUTSIDE_EDITOR=13]="OUTSIDE_EDITOR"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Indent=1]="Indent",e[e.IndentOutdent=2]="IndentOutdent",e[e.Outdent=3]="Outdent"}(L||(L={})),function(e){e[e.Method=0]="Method",e[e.Function=1]="Function",e[e.Constructor=2]="Constructor",e[e.Field=3]="Field",e[e.Variable=4]="Variable",e[e.Class=5]="Class",e[e.Struct=6]="Struct",e[e.Interface=7]="Interface",e[e.Module=8]="Module",e[e.Property=9]="Property",e[e.Event=10]="Event",e[e.Operator=11]="Operator",e[e.Unit=12]="Unit",e[e.Value=13]="Value",e[e.Constant=14]="Constant",e[e.Enum=15]="Enum",e[e.EnumMember=16]="EnumMember",e[e.Keyword=17]="Keyword",e[e.Text=18]="Text",e[e.Color=19]="Color",e[e.File=20]="File",e[e.Reference=21]="Reference",e[e.Customcolor=22]="Customcolor",e[e.Folder=23]="Folder",e[e.TypeParameter=24]="TypeParameter",e[e.Snippet=25]="Snippet"}(O||(O={})),function(e){e[e.Deprecated=1]="Deprecated"}(E||(E={})),function(e){e[e.KeepWhitespace=1]="KeepWhitespace",e[e.InsertAsSnippet=4]="InsertAsSnippet"}(N||(N={})),function(e){e[e.Invoke=0]="Invoke",e[e.TriggerCharacter=1]="TriggerCharacter",e[e.TriggerForIncompleteCompletions=2]="TriggerForIncompleteCompletions"}(x||(x={})),function(e){e[e.Invoke=1]="Invoke",e[e.TriggerCharacter=2]="TriggerCharacter",e[e.ContentChange=3]="ContentChange"}(I||(I={})),function(e){e[e.Text=0]="Text",e[e.Read=1]="Read",e[e.Write=2]="Write"}(D||(D={})),function(e){e[e.File=0]="File",e[e.Module=1]="Module",e[e.Namespace=2]="Namespace",e[e.Package=3]="Package",e[e.Class=4]="Class",e[e.Method=5]="Method",e[e.Property=6]="Property",e[e.Field=7]="Field",e[e.Constructor=8]="Constructor",e[e.Enum=9]="Enum",e[e.Interface=10]="Interface",e[e.Function=11]="Function",e[e.Variable=12]="Variable",e[e.Constant=13]="Constant",e[e.String=14]="String",e[e.Number=15]="Number",e[e.Boolean=16]="Boolean",e[e.Array=17]="Array",e[e.Object=18]="Object",e[e.Key=19]="Key",e[e.Null=20]="Null",e[e.EnumMember=21]="EnumMember",e[e.Struct=22]="Struct",e[e.Event=23]="Event",e[e.Operator=24]="Operator",e[e.TypeParameter=25]="TypeParameter"}(k||(k={})),function(e){e[e.Deprecated=1]="Deprecated"}(T||(T={}));var H=function(){function e(){}return e.chord=function(e,t){return Object(P.a)(e,t)},e.CtrlCmd=2048,e.Shift=1024,e.Alt=512,e.WinCtrl=256,e}();function z(){return{editor:void 0,languages:void 0,CancellationTokenSource:R.b,Emitter:A.a,KeyCode:r,KeyMod:H,Position:W.a,Range:j.a,Selection:V.a,SelectionDirection:s,MarkerSeverity:o,MarkerTag:i,Uri:F.a,Token:B.a}}n("gvGx");var U,K=n("vORD"),q=n("7/Cv"),G=n("tqet"),Z=n("EMhq"),Y=n("+vUW"),X=n("lapT"),J=n("ZYUE"),Q=n("aL7J"),$=n("ItKl"),ee=this&&this.__extends||(U=function(e,t){return(U=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)},function(e,t){function n(){this.constructor=e}U(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),te=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},ne=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ie=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,r){function s(e){try{u(i.next(e))}catch(e){r(e)}}function a(e){try{u(i.throw(e))}catch(e){r(e)}}function u(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,a)}u((i=i.apply(e,t||[])).next())})},oe=this&&this.__generator||function(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]=this.ranges.length&&(this.nextIdx=0)):(this.nextIdx-=1,this.nextIdx<0&&(this.nextIdx=this.ranges.length-1));var n=this.ranges[this.nextIdx];this.ignoreSelectionChange=!0;try{var i=n.range.getStartPosition();this._editor.setPosition(i),this._editor.revealPositionInCenter(i,t)}finally{this.ignoreSelectionChange=!1}}},t.prototype.canNavigate=function(){return this.ranges&&this.ranges.length>0},t.prototype.next=function(e){void 0===e&&(e=0),this._move(!0,e)},t.prototype.previous=function(e){void 0===e&&(e=0),this._move(!1,e)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.ranges=[],this.disposed=!0},t}(G.a),de=n("5lao"),he=n("33h2"),pe=n("D2uo"),fe=n("PCC9"),ge=n("jUH2"),me=n("606G"),_e=n("B/Xy"),ve=n("odeJ"),ye=n("zxiH"),be=n("ZfGv"),Ce=n("KIxu"),we=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Se="$initialize",Le=!1;function Oe(e){be.f&&(Le||(Le=!0,console.warn("Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/Microsoft/monaco-editor#faq")),console.warn(e.message))}var Ee=function(){function e(e){this._workerId=-1,this._handler=e,this._lastSentReq=0,this._pendingReplies=Object.create(null)}return e.prototype.setWorkerId=function(e){this._workerId=e},e.prototype.sendMessage=function(e,t){var n=this,i=String(++this._lastSentReq);return new Promise(function(o,r){n._pendingReplies[i]={resolve:o,reject:r},n._send({vsWorker:n._workerId,req:i,method:e,args:t})})},e.prototype.handleMessage=function(e){e&&e.vsWorker&&(-1!==this._workerId&&e.vsWorker!==this._workerId||this._handleMessage(e))},e.prototype._handleMessage=function(e){var t=this;if(e.seq){var n=e;if(!this._pendingReplies[n.seq])return void console.warn("Got reply to unknown seq");var i=this._pendingReplies[n.seq];if(delete this._pendingReplies[n.seq],n.err){var o=n.err;return n.err.$isError&&((o=new Error).name=n.err.name,o.message=n.err.message,o.stack=n.err.stack),void i.reject(o)}i.resolve(n.res)}else{var r=e,s=r.req;this._handler.handleMessage(r.method,r.args).then(function(e){t._send({vsWorker:t._workerId,seq:s,res:e,err:void 0})},function(e){e.detail instanceof Error&&(e.detail=Object(ye.g)(e.detail)),t._send({vsWorker:t._workerId,seq:s,res:void 0,err:Object(ye.g)(e)})})}},e.prototype._send=function(e){var t=[];if(e.req)for(var n=e,i=0;i1&&f>1;){if(d.charCodeAt(p-2)!==h.charCodeAt(f-2))break;p--,f--}(p>1||f>1)&&this._pushTrimWhitespaceCharChange(o,r+1,1,p,s+1,1,f);for(var g=Fe._getLastNonBlankColumn(d,1),m=Fe._getLastNonBlankColumn(h,1),_=d.length+1,v=h.length+1;g<_&&mt&&(t=a),s>n&&(n=s),u>n&&(n=u)}t++,n++;var l=new qe.a(n,t,0);for(i=0,o=e.length;i=this._maxCharCode?0:this._states.get(e,t)},e}(),Ze=null;var Ye=null;var Xe=function(){function e(){}return e._createLink=function(e,t,n,i,o){var r=o-1;do{var s=t.charCodeAt(r);if(2!==e.get(s))break;r--}while(r>i);if(i>0){var a=t.charCodeAt(i-1),u=t.charCodeAt(r);(40===a&&41===u||91===a&&93===u||123===a&&125===u)&&r--}return{range:{startLineNumber:n,startColumn:i+1,endLineNumber:n,endColumn:r+2},url:t.substring(i,r+1)}},e.computeLinks=function(t,n){void 0===n&&(null===Ze&&(Ze=new Ge([[1,104,2],[1,72,2],[1,102,6],[1,70,6],[2,116,3],[2,84,3],[3,116,4],[3,84,4],[4,112,5],[4,80,5],[5,115,9],[5,83,9],[5,58,10],[6,105,7],[6,73,7],[7,108,8],[7,76,8],[8,101,9],[8,69,9],[9,58,10],[10,47,11],[11,47,12]])),n=Ze);for(var i=function(){if(null===Ye){Ye=new Ke.a(0);for(var e=0;e<" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…".length;e++)Ye.set(" \t<>'\"、。。、,.:;?!@#$%&*‘“〈《「『【〔([{「」}])〕】』」》〉”’`~…".charCodeAt(e),1);for(e=0;e<".,;".length;e++)Ye.set(".,;".charCodeAt(e),2)}return Ye}(),o=[],r=1,s=t.getLineCount();r<=s;r++){for(var a=t.getLineContent(r),u=a.length,l=0,c=0,d=0,h=1,p=!1,f=!1,g=!1;l=0?((i+=n?1:-1)<0?i=e.length-1:i%=e.length,e[i]):null},e.INSTANCE=new e,e}(),Qe=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),$e=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Qe(t,e),Object.defineProperty(t.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"version",{get:function(){return this._versionId},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"eol",{get:function(){return this._eol},enumerable:!0,configurable:!0}),t.prototype.getValue=function(){return this.getText()},t.prototype.getLinesContent=function(){return this._lines.slice(0)},t.prototype.getLineCount=function(){return this._lines.length},t.prototype.getLineContent=function(e){return this._lines[e-1]},t.prototype.getWordAtPosition=function(e,t){var n=Object(Ue.d)(e.column,Object(Ue.c)(t),this._lines[e.lineNumber-1],0);return n?new j.a(e.lineNumber,n.startColumn,e.lineNumber,n.endColumn):null},t.prototype.getWordUntilPosition=function(e,t){var n=this.getWordAtPosition(e,t);return n?{word:this._lines[e.lineNumber-1].substring(n.startColumn-1,e.column-1),startColumn:n.startColumn,endColumn:e.column}:{word:"",startColumn:e.column,endColumn:e.column}},t.prototype.createWordIterator=function(e){var t,n,i=this,o=0,r=0,s=[],a=function(){if(r=i._lines.length?Me.c:(n=i._lines[o],s=i._wordenize(n,e),r=0,o+=1,a())};return{next:a}},t.prototype.getLineWords=function(e,t){for(var n=this._lines[e-1],i=[],o=0,r=this._wordenize(n,t);othis._lines.length)t=this._lines.length,n=this._lines[t-1].length+1,i=!0;else{var o=this._lines[t-1].length+1;n<1?(n=1,i=!0):n>o&&(n=o,i=!0)}return i?{lineNumber:t,column:n}:e},t}(ze),et=function(){function e(e,t){this._host=e,this._models=Object.create(null),this._foreignModuleFactory=t,this._foreignModule=null}return e.prototype.dispose=function(){this._models=Object.create(null)},e.prototype._getModel=function(e){return this._models[e]},e.prototype._getModels=function(){var e=this,t=[];return Object.keys(this._models).forEach(function(n){return t.push(e._models[n])}),t},e.prototype.acceptNewModel=function(e){this._models[e.url]=new $e(F.a.parse(e.url),e.lines,e.EOL,e.versionId)},e.prototype.acceptModelChanged=function(e,t){this._models[e]&&this._models[e].onEvents(t)},e.prototype.acceptRemovedModel=function(e){this._models[e]&&delete this._models[e]},e.prototype.computeDiff=function(e,t,n){var i=this._getModel(e),o=this._getModel(t);if(!i||!o)return Promise.resolve(null);var r=i.getLinesContent(),s=o.getLinesContent(),a=new Be(r,s,{shouldComputeCharChanges:!0,shouldPostProcessCharChanges:!0,shouldIgnoreTrimWhitespace:n,shouldMakePrettyDiff:!0}).computeDiff(),u=!(a.length>0)&&this._modelsAreIdentical(i,o);return Promise.resolve({identical:u,changes:a})},e.prototype._modelsAreIdentical=function(e,t){var n=e.getLineCount();if(n!==t.getLineCount())return!1;for(var i=1;i<=n;i++){if(e.getLineContent(i)!==t.getLineContent(i))return!1}return!0},e.prototype.computeMoreMinimalEdits=function(t,n){var i=this._getModel(t);if(!i)return Promise.resolve(n);for(var o=[],r=void 0,s=0,a=n=Object(ke.o)(n,function(e,t){return e.range&&t.range?j.a.compareRangesUsingStarts(e.range,t.range):(e.range?0:1)-(t.range?0:1)});se._diffLimit)o.push({range:l,text:c});else for(var p=Object(Te.b)(h,c,!1),f=i.offsetAt(j.a.lift(l).getStartPosition()),g=0,m=p;g=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},lt=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},ct=6e4,dt=3e5;function ht(e,t){var n=e.getModel(t);return!!n&&!n.isTooLargeForSyncing()}var pt=function(e){function t(t,n,i){var o=e.call(this)||this;return o._modelService=t,o._workerManager=o._register(new gt(o._modelService)),o._logService=i,o._register(fe.q.register("*",{provideLinks:function(e,t){return ht(o._modelService,e.uri)?o._workerManager.withWorker().then(function(t){return t.computeLinks(e.uri)}).then(function(e){return e&&{links:e}}):Promise.resolve({links:[]})}})),o._register(fe.d.register("*",new ft(o._workerManager,n,o._modelService))),o}return at(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.canComputeDiff=function(e,t){return ht(this._modelService,e)&&ht(this._modelService,t)},t.prototype.computeDiff=function(e,t,n){return this._workerManager.withWorker().then(function(i){return i.computeDiff(e,t,n)})},t.prototype.computeMoreMinimalEdits=function(e,t){var n=this;if(Object(ke.n)(t)){if(!ht(this._modelService,e))return Promise.resolve(t);var i=st.a.create(!0),o=this._workerManager.withWorker().then(function(n){return n.computeMoreMinimalEdits(e,t)});return o.finally(function(){return n._logService.trace("FORMAT#computeMoreMinimalEdits",e.toString(!0),i.elapsed())}),o}return Promise.resolve(void 0)},t.prototype.canNavigateValueSet=function(e){return ht(this._modelService,e)},t.prototype.navigateValueSet=function(e,t,n){return this._workerManager.withWorker().then(function(i){return i.navigateValueSet(e,t,n)})},t.prototype.canComputeWordRanges=function(e){return ht(this._modelService,e)},t.prototype.computeWordRanges=function(e,t){return this._workerManager.withWorker().then(function(n){return n.computeWordRanges(e,t)})},t=ut([lt(0,tt.a),lt(1,it),lt(2,rt.a)],t)}(G.a),ft=function(){function e(e,t,n){this._debugDisplayName="wordbasedCompletions",this._workerManager=e,this._configurationService=t,this._modelService=n}return e.prototype.provideCompletionItems=function(e,t){if(this._configurationService.getValue(e.uri,t,"editor").wordBasedSuggestions&&ht(this._modelService,e.uri))return this._workerManager.withWorker().then(function(n){return n.textualSuggest(e.uri,t)})},e}(),gt=function(e){function t(t){var n=e.call(this)||this;return n._modelService=t,n._editorWorkerClient=null,n._lastWorkerUsedTime=(new Date).getTime(),n._register(new ve.c).cancelAndSet(function(){return n._checkStopIdleWorker()},Math.round(dt/2)),n._register(n._modelService.onModelRemoved(function(e){return n._checkStopEmptyWorker()})),n}return at(t,e),t.prototype.dispose=function(){this._editorWorkerClient&&(this._editorWorkerClient.dispose(),this._editorWorkerClient=null),e.prototype.dispose.call(this)},t.prototype._checkStopEmptyWorker=function(){this._editorWorkerClient&&(0===this._modelService.getModels().length&&(this._editorWorkerClient.dispose(),this._editorWorkerClient=null))},t.prototype._checkStopIdleWorker=function(){this._editorWorkerClient&&((new Date).getTime()-this._lastWorkerUsedTime>dt&&(this._editorWorkerClient.dispose(),this._editorWorkerClient=null))},t.prototype.withWorker=function(){return this._lastWorkerUsedTime=(new Date).getTime(),this._editorWorkerClient||(this._editorWorkerClient=new yt(this._modelService,"editorWorkerService")),Promise.resolve(this._editorWorkerClient)},t}(G.a),mt=function(e){function t(t,n,i){var o=e.call(this)||this;if(o._syncedModels=Object.create(null),o._syncedModelsLastUsedTime=Object.create(null),o._proxy=t,o._modelService=n,!i){var r=new ve.c;r.cancelAndSet(function(){return o._checkStopModelSync()},Math.round(ct/2)),o._register(r)}return o}return at(t,e),t.prototype.dispose=function(){for(var t in this._syncedModels)Object(G.f)(this._syncedModels[t]);this._syncedModels=Object.create(null),this._syncedModelsLastUsedTime=Object.create(null),e.prototype.dispose.call(this)},t.prototype.ensureSyncedResources=function(e){for(var t=0,n=e;tct&&t.push(n)}for(var i=0,o=t;i'"_]/g,"-")}function kt(e,t){return new Error(e.languageId+": "+t)}function Tt(e,t,n,i,o){var r=null;return t.replace(/\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g,function(t,s,a,u,l,c,d,h,p){return xt(a)?xt(u)?!xt(l)&&l0;){var i=e.tokenizer[n];if(i)return i;var o=n.lastIndexOf(".");n=o<0?null:n.substr(0,o)}return null}var Rt=function(){function e(e){this._maxCacheDepth=e,this._entries=Object.create(null)}return e.create=function(e,t){return this._INSTANCE.create(e,t)},e.prototype.create=function(e,t){if(null!==e&&e.depth>=this._maxCacheDepth)return new At(e,t);var n=At.getStackElementId(e);n.length>0&&(n+="|"),n+=t;var i=this._entries[n];return i||(i=new At(e,t),this._entries[n]=i,i)},e._INSTANCE=new e(5),e}(),At=function(){function e(e,t){this.parent=e,this.state=t,this.depth=(this.parent?this.parent.depth:0)+1}return e.getStackElementId=function(e){for(var t="";null!==e;)t.length>0&&(t+="|"),t+=e.state,e=e.parent;return t},e._equals=function(e,t){for(;null!==e&&null!==t;){if(e===t)return!0;if(e.state!==t.state)return!1;e=e.parent,t=t.parent}return null===e&&null===t},e.prototype.equals=function(t){return e._equals(this,t)},e.prototype.push=function(e){return Rt.create(this,e)},e.prototype.pop=function(){return this.parent},e.prototype.popall=function(){for(var e=this;e.parent;)e=e.parent;return e},e.prototype.switchTo=function(e){return Rt.create(this.parent,e)},e}(),Pt=function(){function e(e,t){this.modeId=e,this.state=t}return e.prototype.equals=function(e){return this.modeId===e.modeId&&this.state.equals(e.state)},e.prototype.clone=function(){return this.state.clone()===this.state?this:new e(this.modeId,this.state)},e}(),Ft=function(){function e(e){this._maxCacheDepth=e,this._entries=Object.create(null)}return e.create=function(e,t){return this._INSTANCE.create(e,t)},e.prototype.create=function(e,t){if(null!==t)return new Wt(e,t);if(null!==e&&e.depth>=this._maxCacheDepth)return new Wt(e,t);var n=At.getStackElementId(e),i=this._entries[n];return i||(i=new Wt(e,null),this._entries[n]=i,i)},e._INSTANCE=new e(5),e}(),Wt=function(){function e(e,t){this.stack=e,this.embeddedModeData=t}return e.prototype.clone=function(){return(this.embeddedModeData?this.embeddedModeData.clone():null)===this.embeddedModeData?this:Ft.create(this.stack,this.embeddedModeData)},e.prototype.equals=function(t){return t instanceof e&&(!!this.stack.equals(t.stack)&&(null===this.embeddedModeData&&null===t.embeddedModeData||null!==this.embeddedModeData&&null!==t.embeddedModeData&&this.embeddedModeData.equals(t.embeddedModeData)))},e}(),jt=function(){function e(){this._tokens=[],this._language=null,this._lastTokenType=null,this._lastTokenLanguage=null}return e.prototype.enterMode=function(e,t){this._language=t},e.prototype.emit=function(e,t){this._lastTokenType===t&&this._lastTokenLanguage===this._language||(this._lastTokenType=t,this._lastTokenLanguage=this._language,this._tokens.push(new B.a(e,t,this._language)))},e.prototype.nestedModeTokenize=function(e,t,n){var i=t.modeId,o=t.state,r=fe.y.get(i);if(!r)return this.enterMode(n,i),this.emit(n,""),o;var s=r.tokenize(e,o,n);return this._tokens=this._tokens.concat(s.tokens),this._lastTokenType=null,this._lastTokenLanguage=null,this._language=null,s.endState},e.prototype.finalize=function(e){return new B.b(this._tokens,e)},e}(),Vt=function(){function e(e,t){this._modeService=e,this._theme=t,this._prependTokens=null,this._tokens=[],this._currentLanguageId=0,this._lastTokenMetadata=0}return e.prototype.enterMode=function(e,t){this._currentLanguageId=this._modeService.getLanguageIdentifier(t).id},e.prototype.emit=function(e,t){var n=this._theme.match(this._currentLanguageId,t);this._lastTokenMetadata!==n&&(this._lastTokenMetadata=n,this._tokens.push(e),this._tokens.push(n))},e._merge=function(e,t,n){var i=null!==e?e.length:0,o=t.length,r=null!==n?n.length:0;if(0===i&&0===o&&0===r)return new Uint32Array(0);if(0===i&&0===o)return n;if(0===o&&0===r)return e;var s=new Uint32Array(i+o+r);null!==e&&s.set(e);for(var a=0;a0&&i.nestedModeTokenize(s,t.embeddedModeData,n);var a=e.substring(o);return this._myTokenize(a,t,n+o,i)},e.prototype._safeRuleName=function(e){return e?e.name:"(unknown)"},e.prototype._myTokenize=function(e,t,n,i){i.enterMode(n,this._modeId);for(var o,r,s=e.length,a=t.embeddedModeData,u=t.stack,l=0,c=null,d=!0;d||l=s)break;d=!1;var w=this._lexer.tokenizer[g];if(!w&&!(w=Mt(this._lexer,g)))throw kt(this._lexer,"tokenizer state is not defined: "+g);for(var S=e.substr(l),L=0,O=w;L=this._lexer.maxStack)throw kt(this._lexer,"maximum tokenizer stack size reached: ["+u.state+","+u.parent.state+",...]");u=u.push(g)}else if("@pop"===v.next){if(u.depth<=1)throw kt(this._lexer,"trying to pop an empty stack in rule: "+this._safeRuleName(y));u=u.pop()}else if("@popall"===v.next)u=u.popall();else{var x;if("@"===(x=Tt(this._lexer,v.next,_,m,g))[0]&&(x=x.substr(1)),!Mt(this._lexer,x))throw kt(this._lexer,"trying to set a next state '"+x+"' that is undefined in rule: "+this._safeRuleName(y));u=u.push(x)}}v.log&&"string"==typeof v.log&&(o=this._lexer,r=this._lexer.languageId+": "+Tt(this._lexer,v.log,_,m,g),console.log(o.languageId+": "+r))}if(null===N)throw kt(this._lexer,"lexer rule has no well-defined action in rule: "+this._safeRuleName(y));if(Array.isArray(N)){if(c&&c.groups.length>0)throw kt(this._lexer,"groups cannot be nested: "+this._safeRuleName(y));if(m.length!==N.length+1)throw kt(this._lexer,"matched number of groups does not match the number of actions in rule: "+this._safeRuleName(y));for(var I=0,D=1;D=0&&a()})})},e.colorizeLine=function(e,t,n,i,o){void 0===o&&(o=4);var r=Lt.d.isBasicASCII(e,t),s=Lt.d.containsRTL(e,r,n);return Object(St.e)(new St.c(!1,!0,e,!1,r,s,0,i,[],o,0,-1,"none",!1,!1,null)).html},e.colorizeModelLine=function(e,t,n){void 0===n&&(n=4);var i=e.getLineContent(t);e.forceTokenization(t);var o=e.getLineTokens(t).inflate();return this.colorizeLine(i,e.mightContainNonBasicASCII(),e.mightContainRTL(),o,n)},e}();function Ut(e,t,n){return new Promise(function(i,o){var r=function(){var s=function(e,t,n){for(var i=[],o=n.getInitialState(),r=0,s=e.length;r"),o=u.endState}return i.join("")}(e,t,n);if(n instanceof Bt){var a=n.getLoadStatus();if(!1===a.loaded)return void a.promise.then(r,o)}i(s)};r()})}function Kt(e,t){var n=[],i=new Uint32Array(2);i[0]=0,i[1]=16793600;for(var o=0,r=e.length;o")}return n.join("")}var qt=n("gzF+"),Gt=n("Nr0y"),Zt=n("P1SM"),Yt=n("TeKV"),Xt=n("0WPX"),Jt=n("Gzpe"),Qt=n("WTFd"),$t=n("rHGw"),en=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),tn=function(){function e(e,t,n){void 0===e&&(e={}),void 0===t&&(t=[]),void 0===n&&(n=[]),this._contents=e,this._keys=t,this._overrides=n,this.isFrozen=!1}return Object.defineProperty(e.prototype,"contents",{get:function(){return this.checkAndFreeze(this._contents)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"overrides",{get:function(){return this.checkAndFreeze(this._overrides)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"keys",{get:function(){return this.checkAndFreeze(this._keys)},enumerable:!0,configurable:!0}),e.prototype.isEmpty=function(){return 0===this._keys.length&&0===Object.keys(this._contents).length&&0===this._overrides.length},e.prototype.getValue=function(e){return e?Object(Jt.d)(this.contents,e):this.contents},e.prototype.override=function(t){var n=this.getContentsForOverrideIdentifer(t);if(!n||"object"!=typeof n||!Object.keys(n).length)return this;for(var i={},o=0,r=ke.e(Object.keys(this.contents).concat(Object.keys(n)));o5e3&&n._leaveChordMode():n._leaveChordMode()},500)},t.prototype._leaveChordMode=function(){this._currentChordStatusMessage&&(this._currentChordStatusMessage.dispose(),this._currentChordStatusMessage=null),this._currentChordChecker.cancel(),this._currentChord=null},t.prototype._dispatch=function(e,t){return this._doDispatch(this.resolveKeyboardEvent(e),t)},t.prototype._doDispatch=function(e,t){var n=this,i=!1;if(e.isChord())return console.warn("Unexpected keyboard event mapped to a chord"),!1;var o=e.getDispatchParts()[0];if(null===o)return i;var r=this._contextKeyService.getContext(t),s=this._currentChord?this._currentChord.keypress:null,a=e.getLabel(),u=this._getResolver().resolve(r,s,o);return u&&u.enterChord?(i=!0,this._enterChordMode(o,a),i):(this._currentChord&&(u&&u.commandId||(this._notificationService.status(rn.a("missing.chord","The key combination ({0}, {1}) is not a command.",this._currentChord.label,a),{hideAfter:1e4}),i=!0)),this._leaveChordMode(),u&&u.commandId&&(u.bubble||(i=!0),void 0===u.commandArgs?this._commandService.executeCommand(u.commandId).then(void 0,function(e){return n._notificationService.warn(e)}):this._commandService.executeCommand(u.commandId,u.commandArgs).then(void 0,function(e){return n._notificationService.warn(e)}),this._telemetryService.publicLog2("workbenchActionExecuted",{id:u.commandId,from:"keybinding"})),i)},t.prototype.mightProducePrintableCharacter=function(e){return!e.ctrlKey&&!e.metaKey&&(e.keyCode>=31&&e.keyCode<=56||e.keyCode>=21&&e.keyCode<=30)},t}(G.a),un=n("7g0X"),ln=function(){function e(t,n){this._defaultKeybindings=t,this._defaultBoundCommands=new Map;for(var i=0,o=t.length;i=0;c--)this._isTargetedForRemoval(e[c],a,u,s,l)&&e.splice(c,1);else n.push(r)}return e.concat(n)},e.prototype._addKeyPress=function(t,n){var i=this._map.get(t);if(void 0===i)return this._map.set(t,[n]),void this._addToLookupMap(n);for(var o=i.length-1;o>=0;o--){var r=i[o];if(r.command!==n.command){var s=r.keypressParts.length>1,a=n.keypressParts.length>1;s&&a&&r.keypressParts[1]!==n.keypressParts[1]||e.whenIsEntirelyIncluded(r.when,n.when)&&this._removeFromLookupMap(r)}}i.push(n),this._addToLookupMap(n)},e.prototype._addToLookupMap=function(e){if(e.command){var t=this._lookupMap.get(e.command);void 0===t?(t=[e],this._lookupMap.set(e.command,t)):t.push(e)}},e.prototype._removeFromLookupMap=function(e){if(e.command){var t=this._lookupMap.get(e.command);if(void 0!==t)for(var n=0,i=t.length;n1&&null!==u.keypressParts[1]?{enterChord:!0,commandId:null,commandArgs:null,bubble:!1}:{enterChord:!1,commandId:u.command,commandArgs:u.commandArgs,bubble:u.bubble}:null},e.prototype._findCommand=function(t,n){for(var i=n.length-1;i>=0;i--){var o=n[i];if(e.contextMatchesRules(t,o.when))return o}return null},e.contextMatchesRules=function(e,t){return!t||t.evaluate(e)},e}(),cn=n("Kx4b"),dn=function(){return function(e,t,n,i,o){this.resolvedKeybinding=e,this.keypressParts=e?function(e){for(var t=[],n=0,i=e.length;n1},t.prototype.getParts=function(){var e=this;return this._parts.map(function(t){return e._getPart(t)})},t.prototype._getPart=function(e){return new P.d(e.ctrlKey,e.shiftKey,e.altKey,e.metaKey,this._getLabel(e),this._getAriaLabel(e))},t.prototype.getDispatchParts=function(){var e=this;return this._parts.map(function(t){return e._getDispatchPart(t)})},t}(P.c),gn=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),mn=function(e){function t(t,n){return e.call(this,n,t.parts)||this}return gn(t,e),t.prototype._keyCodeToUILabel=function(e){if(2===this._os)switch(e){case 15:return"←";case 16:return"↑";case 17:return"→";case 18:return"↓"}return P.b.toString(e)},t.prototype._getLabel=function(e){return e.isDuplicateModifierCase()?"":this._keyCodeToUILabel(e.keyCode)},t.prototype._getAriaLabel=function(e){return e.isDuplicateModifierCase()?"":P.b.toString(e.keyCode)},t.prototype._getDispatchPart=function(e){return t.getDispatchStr(e)},t.getDispatchStr=function(e){if(e.isModifierKey())return null;var t="";return e.ctrlKey&&(t+="ctrl+"),e.shiftKey&&(t+="shift+"),e.altKey&&(t+="alt+"),e.metaKey&&(t+="meta+"),t+=P.b.toString(e.keyCode)},t}(fn),_n=n("fAkY"),vn=n("EMDP"),yn=n("EfIu"),bn=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Cn=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},wn=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},Sn=function(){function e(e){this.model=e,this._onDispose=new A.a}return Object.defineProperty(e.prototype,"textEditorModel",{get:function(){return this.model},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this._onDispose.fire()},e}();var Ln=function(){function e(){}return e.prototype.setEditor=function(e){this.editor=e},e.prototype.createModelReference=function(e){var t,n,i,o=this,r=null;return this.editor&&(t=this.editor,n=function(t){return o.findModel(t,e)},i=function(t){return o.findModel(t.getOriginalEditor(),e)||o.findModel(t.getModifiedEditor(),e)},r=Object(Zt.a)(t)?n(t):i(t)),r?Promise.resolve(new G.c(new Sn(r))):Promise.reject(new Error("Model not found"))},e.prototype.findModel=function(e,t){var n=e.getModel();return n&&n.uri.toString()!==t.toString()?null:n},e}(),On=function(){function e(){}return e.prototype.showWhile=function(e,t){return Promise.resolve(void 0)},e}(),En=function(){return function(){}}(),Nn=function(){function e(){}return e.prototype.info=function(e){return this.notify({severity:Gt.a.Info,message:e})},e.prototype.warn=function(e){return this.notify({severity:Gt.a.Warning,message:e})},e.prototype.error=function(e){return this.notify({severity:Gt.a.Error,message:e})},e.prototype.notify=function(t){switch(t.severity){case Gt.a.Error:console.error(t.message);break;case Gt.a.Warning:console.warn(t.message);break;default:console.log(t.message)}return e.NO_OP},e.prototype.status=function(e,t){return G.a.None},e.NO_OP=new _n.b,e}(),xn=function(){function e(e){this._onWillExecuteCommand=new A.a,this._onDidExecuteCommand=new A.a,this._instantiationService=e,this._dynamicCommands=Object.create(null)}return e.prototype.addCommand=function(e){var t=this,n=e.id;return this._dynamicCommands[n]=e,Object(G.h)(function(){delete t._dynamicCommands[n]})},e.prototype.executeCommand=function(e){for(var t=[],n=1;n0){var v=e[r-1];m=0===v.originalEndLineNumber?v.originalStartLineNumber+1:v.originalEndLineNumber+1,_=0===v.modifiedEndLineNumber?v.modifiedStartLineNumber+1:v.modifiedEndLineNumber+1}var y=f-3+1,b=g-3+1;if(yS)N+=E=S-N,x+=E;if(x>L)N+=E=L-x,x+=E;h[p++]=new ti(C,N,w,x),i[o++]=new ni(h)}var I=i[0].entries,D=[],k=0;for(r=1,s=i.length;rd)&&(d=_),0!==v&&(0===h||vp)&&(p=y)}var b=document.createElement("div");b.className="diff-review-row";var C=document.createElement("div");C.className="diff-review-cell diff-review-summary";var w=d-c+1,S=p-h+1;C.appendChild(document.createTextNode(a+1+"/"+this._diffs.length+": @@ -"+c+","+w+" +"+h+","+S+" @@")),b.setAttribute("data-line",String(h));var L=function(e){return 0===e?rn.a("no_lines","no lines"):1===e?rn.a("one_line","1 line"):rn.a("more_lines","{0} lines",e)},O=L(w),E=L(S);b.setAttribute("aria-label",rn.a({key:"header",comment:["This is the ARIA label for a git diff header.","A git diff header looks like this: @@ -154,12 +159,39 @@.","That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.","Variables 0 and 1 refer to the diff index out of total number of diffs.","Variables 2 and 4 will be numbers (a line number).",'Variables 3 and 5 will be "no lines", "1 line" or "X lines", localized separately.']},"Difference {0} of {1}: original {2}, {3}, modified {4}, {5}",a+1,this._diffs.length,c,O,h,E)),b.appendChild(C),b.setAttribute("role","listitem"),l.appendChild(b);var N=h;for(f=0,g=u.length;f0&&o[o.length-1])&&(6===r[0]||2===r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]o.modifiedStartLineNumber?rn.a("diff.clipboard.copyDeletedLinesContent.label","Copy deleted lines"):rn.a("diff.clipboard.copyDeletedLinesContent.single.label","Copy deleted line"),void 0,!0,function(){return fi(a,void 0,void 0,function(){return gi(this,function(e){switch(e.label){case 0:return[4,this._clipboardService.writeText(o.originalContent.join(l)+l)];case 1:return e.sent(),[2]}})})}));var d=0,h=void 0;return o.originalEndLineNumber>o.modifiedStartLineNumber&&(h=new Yn.a("diff.clipboard.copyDeletedLineContent",rn.a("diff.clipboard.copyDeletedLineContent.label","Copy deleted line ({0})",o.originalStartLineNumber),void 0,!0,function(){return fi(a,void 0,void 0,function(){return gi(this,function(e){switch(e.label){case 0:return[4,this._clipboardService.writeText(o.originalContent[d])];case 1:return e.sent(),[2]}})})}),c.push(h)),i.getConfiguration().readOnly||c.push(new Yn.a("diff.inline.revertChange",rn.a("diff.inline.revertChange.label","Revert this change"),void 0,!0,function(){return fi(a,void 0,void 0,function(){var e;return gi(this,function(t){return 0===o.modifiedEndLineNumber?(e=i.getModel().getLineMaxColumn(o.modifiedStartLineNumber),i.executeEdits("diffEditor",[{range:new j.a(o.modifiedStartLineNumber,e,o.modifiedStartLineNumber,e),text:l+o.originalContent.join(l)}])):(e=i.getModel().getLineMaxColumn(o.modifiedEndLineNumber),i.executeEdits("diffEditor",[{range:new j.a(o.modifiedStartLineNumber,1,o.modifiedEndLineNumber,e),text:o.originalContent.join(l)}])),[2]})})})),a._register(q.k(a._diffActions,"mousedown",function(e){var t=q.x(a._diffActions),n=t.top,i=t.height,r=Math.floor(u/3);e.preventDefault(),a._contextMenuService.showContextMenu({getAnchor:function(){return{x:e.posx,y:n+i+r}},getActions:function(){return h&&(h.label=rn.a("diff.clipboard.copyDeletedLineContent.label","Copy deleted line ({0})",o.originalStartLineNumber+d)),c},autoSelectFirstItem:!0})})),a._register(i.onMouseMove(function(e){8===e.target.type||5===e.target.type?e.target.detail.viewZoneId===a._viewZoneId?(a.visibility=!0,d=a._updateLightBulbPosition(a._marginDomNode,e.event.browserEvent.y,u)):a.visibility=!1:a.visibility=!1})),a}return pi(t,e),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility!==e&&(this._visibility=e,this._diffActions.style.visibility=e?"visible":"hidden")},enumerable:!0,configurable:!0}),t.prototype._updateLightBulbPosition=function(e,t,n){var i=t-q.x(e).top,o=Math.floor(i/n),r=o*n;return this._diffActions.style.top=r+"px",o},t}(G.a),_i=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),vi=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},yi=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},bi=function(){function e(e,t){this._contextMenuService=e,this._clipboardService=t,this._zones=[],this.inlineDiffMargins=[],this._zonesMap={},this._decorations=[]}return e.prototype.getForeignViewZones=function(e){var t=this;return e.filter(function(e){return!t._zonesMap[String(e.id)]})},e.prototype.clean=function(e){var t=this;this._zones.length>0&&e.changeViewZones(function(e){for(var n=0,i=t._zones.length;n0?o/n:0;return{height:Math.max(0,Math.floor(e.contentHeight*r)),top:Math.floor(t*r)}},t.prototype._createDataSource=function(){var e=this;return{getWidth:function(){return e._width},getHeight:function(){return e._height-e._reviewHeight},getContainerDomNode:function(){return e._containerDomElement},relayoutEditors:function(){e._doLayout()},getOriginalEditor:function(){return e.originalEditor},getModifiedEditor:function(){return e.modifiedEditor}}},t.prototype._setStrategy=function(e){this._strategy&&this._strategy.dispose(),this._strategy=e,e.applyColors(this._themeService.getTheme()),this._diffComputationResult&&this._updateDecorations(),this._measureDomElement(!0)},t.prototype._getLineChangeAtOrBeforeLineNumber=function(e,t){var n=this._diffComputationResult?this._diffComputationResult.changes:[];if(0===n.length||e=a?i=r+1:(i=r,o=r)}return n[i]},t.prototype._getEquivalentLineForOriginalLineNumber=function(e){var t=this._getLineChangeAtOrBeforeLineNumber(e,function(e){return e.originalStartLineNumber});if(!t)return e;var n=t.originalStartLineNumber+(t.originalEndLineNumber>0?-1:0),i=t.modifiedStartLineNumber+(t.modifiedEndLineNumber>0?-1:0),o=t.originalEndLineNumber>0?t.originalEndLineNumber-t.originalStartLineNumber+1:0,r=t.modifiedEndLineNumber>0?t.modifiedEndLineNumber-t.modifiedStartLineNumber+1:0,s=e-n;return s<=o?i+Math.min(s,r):i+r-o+s},t.prototype._getEquivalentLineForModifiedLineNumber=function(e){var t=this._getLineChangeAtOrBeforeLineNumber(e,function(e){return e.modifiedStartLineNumber});if(!t)return e;var n=t.originalStartLineNumber+(t.originalEndLineNumber>0?-1:0),i=t.modifiedStartLineNumber+(t.modifiedEndLineNumber>0?-1:0),o=t.originalEndLineNumber>0?t.originalEndLineNumber-t.originalStartLineNumber+1:0,r=t.modifiedEndLineNumber>0?t.modifiedEndLineNumber-t.modifiedStartLineNumber+1:0,s=e-i;return s<=r?n+Math.min(s,o):n+o-r+s},t.prototype.getDiffLineInformationForOriginal=function(e){return this._diffComputationResult?{equivalentLineNumber:this._getEquivalentLineForOriginalLineNumber(e)}:null},t.prototype.getDiffLineInformationForModified=function(e){return this._diffComputationResult?{equivalentLineNumber:this._getEquivalentLineForModifiedLineNumber(e)}:null},t.ONE_OVERVIEW_WIDTH=15,t.ENTIRE_DIFF_OVERVIEW_WIDTH=30,t.UPDATE_DIFF_DECORATIONS_DELAY=200,t=vi([yi(3,me.a),yi(4,un.c),yi(5,nt.a),yi(6,K.a),yi(7,$n.c),yi(8,_n.a),yi(9,hi.a)],t)}(G.a),Si=function(e){function t(t){var n=e.call(this)||this;return n._dataSource=t,n._insertColor=null,n._removeColor=null,n}return _i(t,e),t.prototype.applyColors=function(e){var t=(e.getColor(Qn.j)||Qn.g).transparent(2),n=(e.getColor(Qn.l)||Qn.h).transparent(2),i=!t.equals(this._insertColor)||!n.equals(this._removeColor);return this._insertColor=t,this._removeColor=n,i},t.prototype.getEditorsDiffDecorations=function(e,t,n,i,o,r,s){o=o.sort(function(e,t){return e.afterLineNumber-t.afterLineNumber}),i=i.sort(function(e,t){return e.afterLineNumber-t.afterLineNumber});var a=this._getViewZones(e,i,o,r,s,n),u=this._getOriginalEditorDecorations(e,t,n,r,s),l=this._getModifiedEditorDecorations(e,t,n,r,s);return{original:{decorations:u.decorations,overviewZones:u.overviewZones,zones:a.original},modified:{decorations:l.decorations,overviewZones:l.overviewZones,zones:a.modified}}},t}(G.a),Li=function(){function e(e){this._source=e,this._index=-1,this.current=null,this.advance()}return e.prototype.advance=function(){this._index++,this._index0){var n=e[e.length-1];if(n.afterLineNumber===t.afterLineNumber&&null===n.domNode)return void(n.heightInLines+=t.heightInLines)}e.push(t)},d=new Li(this.modifiedForeignVZ),h=new Li(this.originalForeignVZ),p=0,f=this.lineChanges.length;p<=f;p++){var g=p0?-1:0),s=g.modifiedStartLineNumber+(g.modifiedEndLineNumber>0?-1:0),o=g.originalEndLineNumber>0?g.originalEndLineNumber-g.originalStartLineNumber+1:0,i=g.modifiedEndLineNumber>0?g.modifiedEndLineNumber-g.modifiedStartLineNumber+1:0,a=Math.max(g.originalStartLineNumber,g.originalEndLineNumber),u=Math.max(g.modifiedStartLineNumber,g.modifiedEndLineNumber)):(a=r+=1e7+o,u=s+=1e7+i);for(var m,_=[],v=[];d.current&&d.current.afterLineNumber<=u;){var y=void 0;y=d.current.afterLineNumber<=s?r-s+d.current.afterLineNumber:a;var b=null;g&&g.modifiedStartLineNumber<=d.current.afterLineNumber&&d.current.afterLineNumber<=g.modifiedEndLineNumber&&(b=this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion()),_.push({afterLineNumber:y,heightInLines:d.current.heightInLines,domNode:null,marginDomNode:b}),d.advance()}for(;h.current&&h.current.afterLineNumber<=a;){y=void 0;y=h.current.afterLineNumber<=r?s-r+h.current.afterLineNumber:u,v.push({afterLineNumber:y,heightInLines:h.current.heightInLines,domNode:null}),h.advance()}if(null!==g&&Ti(g))(m=this._produceOriginalFromDiff(g,o,i))&&_.push(m);if(null!==g&&Mi(g))(m=this._produceModifiedFromDiff(g,o,i))&&v.push(m);var C=0,w=0;for(_=_.sort(l),v=v.sort(l);C<_.length&&w=L.heightInLines?(S.heightInLines-=L.heightInLines,w++):(L.heightInLines-=S.heightInLines,C++)}for(;C<_.length;)c(t,_[C]),C++;for(;w2*t.MINIMUM_EDITOR_WIDTH?(in-t.MINIMUM_EDITOR_WIDTH&&(i=n-t.MINIMUM_EDITOR_WIDTH)):i=o,this._sashPosition!==i&&(this._sashPosition=i,this._sash.layout()),this._sashPosition},t.prototype.onSashDragStart=function(){this._startSashPosition=this._sashPosition},t.prototype.onSashDrag=function(e){var t=this._dataSource.getWidth()-wi.ENTIRE_DIFF_OVERVIEW_WIDTH,n=this.layout((this._startSashPosition+(e.currentX-e.startX))/t);this._sashRatio=n/t,this._dataSource.relayoutEditors()},t.prototype.onSashDragEnd=function(){this._sash.layout()},t.prototype.onSashReset=function(){this._sashRatio=.5,this._dataSource.relayoutEditors(),this._sash.layout()},t.prototype.getVerticalSashTop=function(e){return 0},t.prototype.getVerticalSashLeft=function(e){return this._sashPosition},t.prototype.getVerticalSashHeight=function(e){return this._dataSource.getHeight()},t.prototype._getViewZones=function(e,t,n,i,o){return new Ii(e,t,n).getViewZones()},t.prototype._getOriginalEditorDecorations=function(e,t,n,i,o){for(var r=String(this._removeColor),s={decorations:[],overviewZones:[]},a=i.getModel(),u=0,l=e.length;ut?{afterLineNumber:Math.max(e.originalStartLineNumber,e.originalEndLineNumber),heightInLines:n-t,domNode:null}:null},t.prototype._produceModifiedFromDiff=function(e,t,n){return t>n?{afterLineNumber:Math.max(e.modifiedStartLineNumber,e.modifiedEndLineNumber),heightInLines:t-n,domNode:null}:null},t}(Oi),Di=function(e){function t(t,n){var i=e.call(this,t)||this;return i.decorationsLeft=t.getOriginalEditor().getLayoutInfo().decorationsLeft,i._register(t.getOriginalEditor().onDidLayoutChange(function(e){i.decorationsLeft!==e.decorationsLeft&&(i.decorationsLeft=e.decorationsLeft,t.relayoutEditors())})),i}return _i(t,e),t.prototype.setEnableSplitViewResizing=function(e){},t.prototype._getViewZones=function(e,t,n,i,o,r){return new ki(e,t,n,i,o,r).getViewZones()},t.prototype._getOriginalEditorDecorations=function(e,t,n,i,o){for(var r=String(this._removeColor),s={decorations:[],overviewZones:[]},a=0,u=e.length;a'])}h+=this.modifiedEditorConfiguration.viewInfo.scrollBeyondLastColumn;var m=document.createElement("div");m.className="view-lines line-delete",m.innerHTML=a.build(),Kn.a.applyFontInfoSlow(m,this.modifiedEditorConfiguration.fontInfo);var _=document.createElement("div");return _.className="inline-deleted-margin-view-zone",_.innerHTML=u.join(""),Kn.a.applyFontInfoSlow(_,this.modifiedEditorConfiguration.fontInfo),{shouldNotShrink:!0,afterLineNumber:0===e.modifiedEndLineNumber?e.modifiedStartLineNumber:e.modifiedStartLineNumber-1,heightInLines:t,minWidthInPx:h*d,domNode:m,marginDomNode:_,diff:{originalStartLineNumber:e.originalStartLineNumber,originalEndLineNumber:e.originalEndLineNumber,modifiedStartLineNumber:e.modifiedStartLineNumber,modifiedEndLineNumber:e.modifiedEndLineNumber,originalContent:p}}},t.prototype._renderOriginalLine=function(e,t,n,i,o,r,s){var a=t.getLineTokens(o),u=a.getLineContent(),l=ci.a.filter(r,o,1,u.length+1);s.appendASCIIString('
    ');var c=Lt.d.isBasicASCII(u,t.mightContainNonBasicASCII()),d=Lt.d.containsRTL(u,c,t.mightContainRTL()),h=Object(St.d)(new St.c(n.fontInfo.isMonospace&&!n.viewInfo.disableMonospaceOptimizations,n.fontInfo.canUseHalfwidthRightwardsArrow,u,!1,c,d,0,a,l,i,n.fontInfo.spaceWidth,n.viewInfo.stopRenderingLineAfter,n.viewInfo.renderWhitespace,n.viewInfo.renderControlCharacters,n.viewInfo.fontLigatures,null),s);s.appendASCIIString("
    ");var p=h.characterMapping.getAbsoluteOffsets();return p.length>0?p[p.length-1]:0},t}(Oi);function Ti(e){return e.modifiedEndLineNumber>0}function Mi(e){return e.originalEndLineNumber>0}Object($n.f)(function(e,t){var n=e.getColor(Qn.j);n&&(t.addRule(".monaco-editor .line-insert, .monaco-editor .char-insert { background-color: "+n+"; }"),t.addRule(".monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: "+n+"; }"),t.addRule(".monaco-editor .inline-added-margin-view-zone { background-color: "+n+"; }"));var i=e.getColor(Qn.l);i&&(t.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { background-color: "+i+"; }"),t.addRule(".monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: "+i+"; }"),t.addRule(".monaco-editor .inline-deleted-margin-view-zone { background-color: "+i+"; }"));var o=e.getColor(Qn.k);o&&t.addRule(".monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px "+("hc"===e.type?"dashed":"solid")+" "+o+"; }");var r=e.getColor(Qn.m);r&&t.addRule(".monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px "+("hc"===e.type?"dashed":"solid")+" "+r+"; }");var s=e.getColor(Qn._37);s&&t.addRule(".monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px "+s+"; }");var a=e.getColor(Qn.i);a&&t.addRule(".monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid "+a+"; }")});var Ri=n("lthF"),Ai=n("sKqm"),Pi=n("C3c5"),Fi=n("NqM+"),Wi=n("xJaW"),ji=n("44YW"),Vi=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),Bi=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},Hi=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},zi=0,Ui=!1;var Ki=function(e){function t(t,n,i,o,r,s,a,u,l,c){var d=this;return(n=n||{}).ariaLabel=n.ariaLabel||yn.g.editorViewAccessibleLabel,n.ariaLabel=n.ariaLabel+";"+(Vn.j?yn.g.accessibilityHelpMessageIE:yn.g.accessibilityHelpMessage),(d=e.call(this,t,n,{},i,o,r,s,u,l,c)||this)._standaloneKeybindingService=a instanceof In?a:null,Ui||(Ui=!0,Bn.b(document.body)),d}return Vi(t,e),t.prototype.addCommand=function(e,t,n){if(!this._standaloneKeybindingService)return console.warn("Cannot add command because the editor is configured with an unrecognized KeybindingService"),null;var i="DYNAMIC_"+ ++zi,o=un.a.deserialize(n);return this._standaloneKeybindingService.addDynamicKeybinding(i,e,t,o),i},t.prototype.createContextKey=function(e,t){return this._contextKeyService.createKey(e,t)},t.prototype.addAction=function(e){var t=this;if("string"!=typeof e.id||"string"!=typeof e.label||"function"!=typeof e.run)throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");if(!this._standaloneKeybindingService)return console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService"),G.a.None;var n=e.id,i=e.label,o=un.a.and(un.a.equals("editorId",this.getId()),un.a.deserialize(e.precondition)),r=e.keybindings,s=un.a.and(o,un.a.deserialize(e.keybindingContext)),a=e.contextMenuGroupId||null,u=e.contextMenuOrder||0,l=function(){return Promise.resolve(e.run(t))},c=new G.b,d=this.getId()+":"+n;if(c.add($.a.registerCommand(d,l)),a){var h={command:{id:d,title:i},when:o,group:a,order:u};c.add(Pi.c.appendMenuItem(7,h))}if(Array.isArray(r))for(var p=0,f=r;p=0}}(e);to.push(n),n.userConfigured?io.push(n):no.push(n),t&&!n.userConfigured&&to.forEach(function(e){e.mime===n.mime||e.userConfigured||(n.extension&&e.extension===n.extension&&console.warn("Overwriting extension <<"+n.extension+">> to now point to mime <<"+n.mime+">>"),n.filename&&e.filename===n.filename&&console.warn("Overwriting filename <<"+n.filename+">> to now point to mime <<"+n.mime+">>"),n.filepattern&&e.filepattern===n.filepattern&&console.warn("Overwriting filepattern <<"+n.filepattern+">> to now point to mime <<"+n.mime+">>"),n.firstline&&e.firstline===n.firstline&&console.warn("Overwriting firstline <<"+n.firstline+">> to now point to mime <<"+n.mime+">>"))})}function ro(e,t){var n;if(e)switch(e.scheme){case X.b.file:n=e.fsPath;break;case X.b.data:n=J.a.parseMetaData(e).get(J.a.META_DATA_LABEL);break;default:n=e.path}if(!n)return[eo];n=n.toLowerCase();var i=Object(Ji.basename)(n),o=so(n,i,io);if(o)return[o,$i];var r=so(n,i,no);if(r)return[r,$i];if(t){var s=function(e){Object(Q.L)(e)&&(e=e.substr(1));if(e.length>0)for(var t=to.length-1;t>=0;t--){var n=to[t];if(n.firstline){var i=e.match(n.firstline);if(i&&i.length>0)return n.mime}}return null}(t);if(s)return[s,$i]}return[eo]}function so(e,t,n){for(var i=null,o=null,r=null,s=n.length-1;s>=0;s--){var a=n[s];if(t===a.filenameLowercase){i=a;break}if(a.filepattern&&(!o||a.filepattern.length>o.filepattern.length)){var u=a.filepatternOnPath?e:t;Object(Qi.a)(a.filepatternLowercase,u)&&(o=a)}a.extension&&(!r||a.extension.length>r.extension.length)&&Object(Q.m)(t,a.extensionLowercase)&&(r=a)}return i?i.mime:o?o.mime:r?r.mime:null}var ao=n("9XyG"),uo=n("RWr8"),lo=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),co=Object.prototype.hasOwnProperty,ho=function(e){function t(t,n){void 0===t&&(t=!0),void 0===n&&(n=!1);var i=e.call(this)||this;return i._onDidChange=i._register(new A.a),i.onDidChange=i._onDidChange.event,i._warnOnOverwrite=n,i._nextLanguageId2=1,i._languageIdToLanguage=[],i._languageToLanguageId=Object.create(null),i._languages={},i._mimeTypesMap={},i._nameMap={},i._lowercaseNameMap={},t&&(i._initializeFromRegistry(),i._register(ao.a.onDidChangeLanguages(function(e){return i._initializeFromRegistry()}))),i}return lo(t,e),t.prototype._initializeFromRegistry=function(){this._languages={},this._mimeTypesMap={},this._nameMap={},this._lowercaseNameMap={};var e=ao.a.getLanguages();this._registerLanguages(e)},t.prototype._registerLanguages=function(e){for(var t=this,n=0,i=e;n0&&((n=e.mimetypes).push.apply(n,t.mimetypes),o=t.mimetypes[0]),o||(o="text/x-"+i,e.mimetypes.push(o)),Array.isArray(t.extensions))for(var r=0,s=t.extensions;r0){var p=t.firstLine;"^"!==p.charAt(0)&&(p="^"+p);try{var f=new RegExp(p);Q.E(f)||oo({id:i,mime:o,firstline:f},this._warnOnOverwrite)}catch(e){Object(ye.e)(e)}}e.aliases.push(i);var g=null;if(void 0!==t.aliases&&Array.isArray(t.aliases)&&(g=0===t.aliases.length?[null]:t.aliases),null!==g)for(var m=0,_=g;m<_.length;m++){var v=_[m];v&&0!==v.length&&e.aliases.push(v)}var y=null!==g&&g.length>0;if(y&&null===g[0]);else{var b=(y?g[0]:null)||i;!y&&e.name||(e.name=b)}t.configuration&&e.configurationFiles.push(t.configuration)},t.prototype.isRegisteredMode=function(e){return!!co.call(this._mimeTypesMap,e)||co.call(this._languages,e)},t.prototype.getModeIdForLanguageNameLowercase=function(e){return co.call(this._lowercaseNameMap,e)?this._lowercaseNameMap[e].language:null},t.prototype.extractModeIds=function(e){var t=this;return e?e.split(",").map(function(e){return e.trim()}).map(function(e){return co.call(t._mimeTypesMap,e)?t._mimeTypesMap[e].language:e}).filter(function(e){return co.call(t._languages,e)}):[]},t.prototype.getLanguageIdentifier=function(e){if(e===ge.b||0===e)return ge.a;var t;if("string"==typeof e)t=e;else if(!(t=this._languageIdToLanguage[e]))return null;return co.call(this._languages,t)?this._languages[t].identifier:null},t.prototype.getModeIdsFromFilepathOrFirstLine=function(e,t){if(!e&&!t)return[];var n=ro(e,t);return this.extractModeIds(n.join(","))},t}(G.a),po=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),fo=function(e){function t(t,n){var i=e.call(this)||this;return i._onDidChange=i._register(new A.a),i.onDidChange=i._onDidChange.event,i._selector=n,i.languageIdentifier=i._selector(),i._register(t(function(){return i._evaluate()})),i}return po(t,e),t.prototype._evaluate=function(){var e=this._selector();e.id!==this.languageIdentifier.id&&(this.languageIdentifier=e,this._onDidChange.fire(this.languageIdentifier))},t}(G.a),go=function(){function e(e){var t=this;void 0===e&&(e=!1),this._onDidCreateMode=new A.a,this.onDidCreateMode=this._onDidCreateMode.event,this._onLanguagesMaybeChanged=new A.a,this.onLanguagesMaybeChanged=this._onLanguagesMaybeChanged.event,this._instantiatedModes={},this._registry=new ho(!0,e),this._registry.onDidChange(function(){return t._onLanguagesMaybeChanged.fire()})}return e.prototype.isRegisteredMode=function(e){return this._registry.isRegisteredMode(e)},e.prototype.getModeIdForLanguageName=function(e){return this._registry.getModeIdForLanguageNameLowercase(e)},e.prototype.getModeIdByFilepathOrFirstLine=function(e,t){var n=this._registry.getModeIdsFromFilepathOrFirstLine(e,t);return n.length>0?n[0]:null},e.prototype.getModeId=function(e){var t=this._registry.extractModeIds(e);return t.length>0?t[0]:null},e.prototype.getLanguageIdentifier=function(e){return this._registry.getLanguageIdentifier(e)},e.prototype.create=function(e){var t=this;return new fo(this.onLanguagesMaybeChanged,function(){var n=t.getModeId(e);return t._createModeAndGetLanguageIdentifier(n)})},e.prototype.createByFilepathOrFirstLine=function(e,t){var n=this;return new fo(this.onLanguagesMaybeChanged,function(){var i=n.getModeIdByFilepathOrFirstLine(e,t);return n._createModeAndGetLanguageIdentifier(i)})},e.prototype._createModeAndGetLanguageIdentifier=function(e){var t=this.getLanguageIdentifier(e||"plaintext")||ge.a;return this._getOrCreateMode(t.language),t},e.prototype.triggerMode=function(e){var t=this.getModeId(e);this._getOrCreateMode(t||"plaintext")},e.prototype._getOrCreateMode=function(e){if(!this._instantiatedModes.hasOwnProperty(e)){var t=this.getLanguageIdentifier(e)||ge.a;this._instantiatedModes[e]=new Xi(t),this._onDidCreateMode.fire(this._instantiatedModes[e])}return this._instantiatedModes[e]},e}(),mo=this&&this.__extends||function(){var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(t,n)};return function(t,n){function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}}(),_o=this&&this.__decorate||function(e,t,n,i){var o,r=arguments.length,s=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},vo=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}};function yo(e){return e.toString()}var bo=function(){function e(e,t,n){this._modelEventListeners=new G.b,this.model=e,this._languageSelection=null,this._languageSelectionListener=null,this._modelEventListeners.add(e.onWillDispose(function(){return t(e)})),this._modelEventListeners.add(e.onDidChangeLanguage(function(t){return n(e,t)}))}return e.prototype._disposeLanguageSelection=function(){this._languageSelectionListener&&(this._languageSelectionListener.dispose(),this._languageSelectionListener=null),this._languageSelection&&(this._languageSelection.dispose(),this._languageSelection=null)},e.prototype.dispose=function(){this._modelEventListeners.dispose(),this._disposeLanguageSelection()},e.prototype.setLanguage=function(e){var t=this;this._disposeLanguageSelection(),this._languageSelection=e,this._languageSelectionListener=this._languageSelection.onDidChange(function(){return t.model.setMode(e.languageIdentifier)}),this.model.setMode(e.languageIdentifier)},e}(),Co=be.c||be.d?1:2,wo=function(e){function t(t,n){var i=e.call(this)||this;return i._onModelAdded=i._register(new A.a),i.onModelAdded=i._onModelAdded.event,i._onModelRemoved=i._register(new A.a),i.onModelRemoved=i._onModelRemoved.event,i._onModelModeChanged=i._register(new A.a),i.onModelModeChanged=i._onModelModeChanged.event,i._configurationService=t,i._resourcePropertiesService=n,i._models={},i._modelCreationOptionsByLanguageAndResource=Object.create(null),i._configurationServiceSubscription=i._configurationService.onDidChangeConfiguration(function(e){return i._updateModelOptions()}),i._updateModelOptions(),i}return mo(t,e),t._readModelOptions=function(e,t){var n=M.c.tabSize;if(e.editor&&void 0!==e.editor.tabSize){var i=parseInt(e.editor.tabSize,10);isNaN(i)||(n=i),n<1&&(n=1)}var o=n;if(e.editor&&void 0!==e.editor.indentSize&&"tabSize"!==e.editor.indentSize){var r=parseInt(e.editor.indentSize,10);isNaN(r)||(o=r),o<1&&(o=1)}var s=M.c.insertSpaces;e.editor&&void 0!==e.editor.insertSpaces&&(s="false"!==e.editor.insertSpaces&&Boolean(e.editor.insertSpaces));var a=Co,u=e.eol;"\r\n"===u?a=2:"\n"===u&&(a=1);var l=M.c.trimAutoWhitespace;e.editor&&void 0!==e.editor.trimAutoWhitespace&&(l="false"!==e.editor.trimAutoWhitespace&&Boolean(e.editor.trimAutoWhitespace));var c=M.c.detectIndentation;e.editor&&void 0!==e.editor.detectIndentation&&(c="false"!==e.editor.detectIndentation&&Boolean(e.editor.detectIndentation));var d=M.c.largeFileOptimizations;return e.editor&&void 0!==e.editor.largeFileOptimizations&&(d="false"!==e.editor.largeFileOptimizations&&Boolean(e.editor.largeFileOptimizations)),{isForSimpleWidget:t,tabSize:n,indentSize:o,insertSpaces:s,detectIndentation:c,defaultEOL:a,trimAutoWhitespace:l,largeFileOptimizations:d}},t.prototype.getCreationOptions=function(e,n,i){var o=this._modelCreationOptionsByLanguageAndResource[e+n];if(!o){var r=this._configurationService.getValue("editor",{overrideIdentifier:e,resource:n}),s=this._resourcePropertiesService.getEOL(n,e);o=t._readModelOptions({editor:r,eol:s},i),this._modelCreationOptionsByLanguageAndResource[e+n]=o}return o},t.prototype._updateModelOptions=function(){var e=this._modelCreationOptionsByLanguageAndResource;this._modelCreationOptionsByLanguageAndResource=Object.create(null);for(var n=Object.keys(this._models),i=0,o=n.length;i=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},No=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},xo=function(e){function t(t,n){void 0===n&&(n=q.s());var i=e.call(this)||this;return i._decorationOptionProviders=new Map,i._styleSheet=n,i._themeService=t,i}return Oo(t,e),t.prototype.registerDecorationType=function(e,t,n){var i=this._decorationOptionProviders.get(e);if(!i){var o={styleSheet:this._styleSheet,key:e,parentTypeKey:n,options:t||Object.create(null)};i=n?new Io(this._themeService,o):new Do(this._themeService,o),this._decorationOptionProviders.set(e,i)}i.refCount++},t.prototype.removeDecorationType=function(e){var t=this._decorationOptionProviders.get(e);t&&(t.refCount--,t.refCount<=0&&(this._decorationOptionProviders.delete(e),t.dispose(),this.listCodeEditors().forEach(function(t){return t.removeDecorations(e)})))},t.prototype.resolveDecorationOptions=function(e,t){var n=this._decorationOptionProviders.get(e);if(!n)throw new Error("Unknown decoration type key: "+e);return n.getOptions(this,t)},t=Eo([No(0,$n.c)],t)}(Lo),Io=function(){function e(e,t){this._parentTypeKey=t.parentTypeKey,this.refCount=0,this._beforeContentRules=new To(3,t,e),this._afterContentRules=new To(4,t,e)}return e.prototype.getOptions=function(e,t){var n=e.resolveDecorationOptions(this._parentTypeKey,!0);return this._beforeContentRules&&(n.beforeContentClassName=this._beforeContentRules.className),this._afterContentRules&&(n.afterContentClassName=this._afterContentRules.className),n},e.prototype.dispose=function(){this._beforeContentRules&&(this._beforeContentRules.dispose(),this._beforeContentRules=null),this._afterContentRules&&(this._afterContentRules.dispose(),this._afterContentRules=null)},e}(),Do=function(){function e(e,t){var n=this;this._disposables=new G.b,this.refCount=0;var i=function(i){var o=new To(i,t,e);if(n._disposables.add(o),o.hasContent)return o.className};this.className=i(0);var o,r=(o=new To(1,t,e),n._disposables.add(o),o.hasContent?{className:o.className,hasLetterSpacing:o.hasLetterSpacing}:null);r&&(this.inlineClassName=r.className,this.inlineClassNameAffectsLetterSpacing=r.hasLetterSpacing),this.beforeContentClassName=i(3),this.afterContentClassName=i(4),this.glyphMarginClassName=i(2);var s=t.options;this.isWholeLine=Boolean(s.isWholeLine),this.stickiness=s.rangeBehavior;var a=s.light&&s.light.overviewRulerColor||s.overviewRulerColor,u=s.dark&&s.dark.overviewRulerColor||s.overviewRulerColor;void 0===a&&void 0===u||(this.overviewRuler={color:a||u,darkColor:u||a,position:s.overviewRulerLane||pe.d.Center})}return e.prototype.getOptions=function(e,t){return t?{inlineClassName:this.inlineClassName,beforeContentClassName:this.beforeContentClassName,afterContentClassName:this.afterContentClassName,className:this.className,glyphMarginClassName:this.glyphMarginClassName,isWholeLine:this.isWholeLine,overviewRuler:this.overviewRuler,stickiness:this.stickiness}:this},e.prototype.dispose=function(){this._disposables.dispose()},e}(),ko={color:"color:{0} !important;",opacity:"opacity:{0};",backgroundColor:"background-color:{0};",outline:"outline:{0};",outlineColor:"outline-color:{0};",outlineStyle:"outline-style:{0};",outlineWidth:"outline-width:{0};",border:"border:{0};",borderColor:"border-color:{0};",borderRadius:"border-radius:{0};",borderSpacing:"border-spacing:{0};",borderStyle:"border-style:{0};",borderWidth:"border-width:{0};",fontStyle:"font-style:{0};",fontWeight:"font-weight:{0};",textDecoration:"text-decoration:{0};",cursor:"cursor:{0};",letterSpacing:"letter-spacing:{0};",gutterIconPath:"background:{0} center center no-repeat;",gutterIconSize:"background-size:{0};",contentText:"content:'{0}';",contentIconPath:"content:{0};",margin:"margin:{0};",width:"width:{0};",height:"height:{0};"},To=function(){function e(e,t,n){var i=this;this._theme=n.getTheme(),this._ruleType=e,this._providerArgs=t,this._usesThemeColors=!1,this._hasContent=!1,this._hasLetterSpacing=!1;var o=Mo.getClassName(this._providerArgs.key,e);this._providerArgs.parentTypeKey&&(o=o+" "+Mo.getClassName(this._providerArgs.parentTypeKey,e)),this._className=o,this._unThemedSelector=Mo.getSelector(this._providerArgs.key,this._providerArgs.parentTypeKey,e),this._buildCSS(),this._usesThemeColors?this._themeListener=n.onThemeChange(function(e){i._theme=n.getTheme(),i._removeCSS(),i._buildCSS()}):this._themeListener=null}return e.prototype.dispose=function(){this._hasContent&&(this._removeCSS(),this._hasContent=!1),this._themeListener&&(this._themeListener.dispose(),this._themeListener=null)},Object.defineProperty(e.prototype,"hasContent",{get:function(){return this._hasContent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasLetterSpacing",{get:function(){return this._hasLetterSpacing},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"className",{get:function(){return this._className},enumerable:!0,configurable:!0}),e.prototype._buildCSS=function(){var e,t,n,i=this._providerArgs.options;switch(this._ruleType){case 0:e=this.getCSSTextForModelDecorationClassName(i),t=this.getCSSTextForModelDecorationClassName(i.light),n=this.getCSSTextForModelDecorationClassName(i.dark);break;case 1:e=this.getCSSTextForModelDecorationInlineClassName(i),t=this.getCSSTextForModelDecorationInlineClassName(i.light),n=this.getCSSTextForModelDecorationInlineClassName(i.dark);break;case 2:e=this.getCSSTextForModelDecorationGlyphMarginClassName(i),t=this.getCSSTextForModelDecorationGlyphMarginClassName(i.light),n=this.getCSSTextForModelDecorationGlyphMarginClassName(i.dark);break;case 3:e=this.getCSSTextForModelDecorationContentClassName(i.before),t=this.getCSSTextForModelDecorationContentClassName(i.light&&i.light.before),n=this.getCSSTextForModelDecorationContentClassName(i.dark&&i.dark.before);break;case 4:e=this.getCSSTextForModelDecorationContentClassName(i.after),t=this.getCSSTextForModelDecorationContentClassName(i.light&&i.light.after),n=this.getCSSTextForModelDecorationContentClassName(i.dark&&i.dark.after);break;default:throw new Error("Unknown rule type: "+this._ruleType)}var o=this._providerArgs.styleSheet.sheet,r=!1;e.length>0&&(o.insertRule(this._unThemedSelector+" {"+e+"}",0),r=!0),t.length>0&&(o.insertRule(".vs"+this._unThemedSelector+" {"+t+"}",0),r=!0),n.length>0&&(o.insertRule(".vs-dark"+this._unThemedSelector+", .hc-black"+this._unThemedSelector+" {"+n+"}",0),r=!0),this._hasContent=r},e.prototype._removeCSS=function(){q.H(this._unThemedSelector,this._providerArgs.styleSheet)},e.prototype.getCSSTextForModelDecorationClassName=function(e){if(!e)return"";var t=[];return this.collectCSSText(e,["backgroundColor"],t),this.collectCSSText(e,["outline","outlineColor","outlineStyle","outlineWidth"],t),this.collectBorderSettingsCSSText(e,t),t.join("")},e.prototype.getCSSTextForModelDecorationInlineClassName=function(e){if(!e)return"";var t=[];return this.collectCSSText(e,["fontStyle","fontWeight","textDecoration","cursor","color","opacity","letterSpacing"],t),e.letterSpacing&&(this._hasLetterSpacing=!0),t.join("")},e.prototype.getCSSTextForModelDecorationContentClassName=function(e){if(!e)return"";var t=[];if(void 0!==e){if(this.collectBorderSettingsCSSText(e,t),void 0!==e.contentIconPath&&t.push(Q.r(ko.contentIconPath,q.n(F.a.revive(e.contentIconPath)))),"string"==typeof e.contentText){var n=e.contentText.match(/^.*$/m)[0].replace(/['\\]/g,"\\$&");t.push(Q.r(ko.contentText,n))}this.collectCSSText(e,["fontStyle","fontWeight","textDecoration","color","opacity","backgroundColor","margin"],t),this.collectCSSText(e,["width","height"],t)&&t.push("display:inline-block;")}return t.join("")},e.prototype.getCSSTextForModelDecorationGlyphMarginClassName=function(e){if(!e)return"";var t=[];return void 0!==e.gutterIconPath&&(t.push(Q.r(ko.gutterIconPath,q.n(F.a.revive(e.gutterIconPath)))),void 0!==e.gutterIconSize&&t.push(Q.r(ko.gutterIconSize,e.gutterIconSize))),t.join("")},e.prototype.collectBorderSettingsCSSText=function(e,t){return!!this.collectCSSText(e,["border","borderColor","borderRadius","borderSpacing","borderStyle","borderWidth"],t)&&(t.push(Q.r("box-sizing: border-box;")),!0)},e.prototype.collectCSSText=function(e,t,n){for(var i=n.length,o=0,r=t;ot)return 1;return 0}(e.token,t.token);return 0!==n?n:e.index-t.index});for(var n=0,i="000000",o="ffffff";e.length>=1&&""===e[0].token;){var r=e.shift();-1!==r.fontStyle&&(n=r.fontStyle),null!==r.foreground&&(i=r.foreground),null!==r.background&&(o=r.background)}for(var s=new Vo,a=0,u=t;a>>0,this._cache.set(t,n)}return(n|e<<0)>>>0},e}(),Ho=/\b(comment|string|regex|regexp)\b/;var zo,Uo,Ko,qo=function(){function e(e,t,n){this._fontStyle=e,this._foreground=t,this._background=n,this.metadata=(this._fontStyle<<11|this._foreground<<14|this._background<<23)>>>0}return e.prototype.clone=function(){return new e(this._fontStyle,this._foreground,this._background)},e.prototype.acceptOverwrite=function(e,t,n){-1!==e&&(this._fontStyle=e),0!==t&&(this._foreground=t),0!==n&&(this._background=n),this.metadata=(this._fontStyle<<11|this._foreground<<14|this._background<<23)>>>0},e}(),Go=function(){function e(e){this._mainRule=e,this._children=new Map}return e.prototype.match=function(e){if(""===e)return this._mainRule;var t,n,i=e.indexOf(".");-1===i?(t=e,n=""):(t=e.substring(0,i),n=e.substring(i+1));var o=this._children.get(t);return void 0!==o?o.match(n):this._mainRule},e.prototype.insert=function(t,n,i,o){if(""!==t){var r,s,a=t.indexOf(".");-1===a?(r=t,s=""):(r=t.substring(0,a),s=t.substring(a+1));var u=this._children.get(r);void 0===u&&(u=new e(this._mainRule.clone()),this._children.set(r,u)),u.insert(s,n,i,o)}else this._mainRule.acceptOverwrite(n,i,o)},e}();var Zo={base:"vs",inherit:!1,rules:[{token:"",foreground:"000000",background:"fffffe"},{token:"invalid",foreground:"cd3131"},{token:"emphasis",fontStyle:"italic"},{token:"strong",fontStyle:"bold"},{token:"variable",foreground:"001188"},{token:"variable.predefined",foreground:"4864AA"},{token:"constant",foreground:"dd0000"},{token:"comment",foreground:"008000"},{token:"number",foreground:"09885A"},{token:"number.hex",foreground:"3030c0"},{token:"regexp",foreground:"800000"},{token:"annotation",foreground:"808080"},{token:"type",foreground:"008080"},{token:"delimiter",foreground:"000000"},{token:"delimiter.html",foreground:"383838"},{token:"delimiter.xml",foreground:"0000FF"},{token:"tag",foreground:"800000"},{token:"tag.id.pug",foreground:"4F76AC"},{token:"tag.class.pug",foreground:"4F76AC"},{token:"meta.scss",foreground:"800000"},{token:"metatag",foreground:"e00000"},{token:"metatag.content.html",foreground:"FF0000"},{token:"metatag.html",foreground:"808080"},{token:"metatag.xml",foreground:"808080"},{token:"metatag.php",fontStyle:"bold"},{token:"key",foreground:"863B00"},{token:"string.key.json",foreground:"A31515"},{token:"string.value.json",foreground:"0451A5"},{token:"attribute.name",foreground:"FF0000"},{token:"attribute.value",foreground:"0451A5"},{token:"attribute.value.number",foreground:"09885A"},{token:"attribute.value.unit",foreground:"09885A"},{token:"attribute.value.html",foreground:"0000FF"},{token:"attribute.value.xml",foreground:"0000FF"},{token:"string",foreground:"A31515"},{token:"string.html",foreground:"0000FF"},{token:"string.sql",foreground:"FF0000"},{token:"string.yaml",foreground:"0451A5"},{token:"keyword",foreground:"0000FF"},{token:"keyword.json",foreground:"0451A5"},{token:"keyword.flow",foreground:"AF00DB"},{token:"keyword.flow.scss",foreground:"0000FF"},{token:"operator.scss",foreground:"666666"},{token:"operator.sql",foreground:"778899"},{token:"operator.swift",foreground:"666666"},{token:"predefined.sql",foreground:"FF00FF"}],colors:(zo={},zo[Qn.o]="#FFFFFE",zo[Qn.x]="#000000",zo[Qn.E]="#E5EBF1",zo[Jn.h]="#D3D3D3",zo[Jn.a]="#939393",zo[Qn.J]="#ADD6FF4D",zo)},Yo={base:"vs-dark",inherit:!1,rules:[{token:"",foreground:"D4D4D4",background:"1E1E1E"},{token:"invalid",foreground:"f44747"},{token:"emphasis",fontStyle:"italic"},{token:"strong",fontStyle:"bold"},{token:"variable",foreground:"74B0DF"},{token:"variable.predefined",foreground:"4864AA"},{token:"variable.parameter",foreground:"9CDCFE"},{token:"constant",foreground:"569CD6"},{token:"comment",foreground:"608B4E"},{token:"number",foreground:"B5CEA8"},{token:"number.hex",foreground:"5BB498"},{token:"regexp",foreground:"B46695"},{token:"annotation",foreground:"cc6666"},{token:"type",foreground:"3DC9B0"},{token:"delimiter",foreground:"DCDCDC"},{token:"delimiter.html",foreground:"808080"},{token:"delimiter.xml",foreground:"808080"},{token:"tag",foreground:"569CD6"},{token:"tag.id.pug",foreground:"4F76AC"},{token:"tag.class.pug",foreground:"4F76AC"},{token:"meta.scss",foreground:"A79873"},{token:"meta.tag",foreground:"CE9178"},{token:"metatag",foreground:"DD6A6F"},{token:"metatag.content.html",foreground:"9CDCFE"},{token:"metatag.html",foreground:"569CD6"},{token:"metatag.xml",foreground:"569CD6"},{token:"metatag.php",fontStyle:"bold"},{token:"key",foreground:"9CDCFE"},{token:"string.key.json",foreground:"9CDCFE"},{token:"string.value.json",foreground:"CE9178"},{token:"attribute.name",foreground:"9CDCFE"},{token:"attribute.value",foreground:"CE9178"},{token:"attribute.value.number.css",foreground:"B5CEA8"},{token:"attribute.value.unit.css",foreground:"B5CEA8"},{token:"attribute.value.hex.css",foreground:"D4D4D4"},{token:"string",foreground:"CE9178"},{token:"string.sql",foreground:"FF0000"},{token:"keyword",foreground:"569CD6"},{token:"keyword.flow",foreground:"C586C0"},{token:"keyword.json",foreground:"CE9178"},{token:"keyword.flow.scss",foreground:"569CD6"},{token:"operator.scss",foreground:"909090"},{token:"operator.sql",foreground:"778899"},{token:"operator.swift",foreground:"909090"},{token:"predefined.sql",foreground:"FF00FF"}],colors:(Uo={},Uo[Qn.o]="#1E1E1E",Uo[Qn.x]="#D4D4D4",Uo[Qn.E]="#3A3D41",Uo[Jn.h]="#404040",Uo[Jn.a]="#707070",Uo[Qn.J]="#ADD6FF26",Uo)},Xo={base:"hc-black",inherit:!1,rules:[{token:"",foreground:"FFFFFF",background:"000000"},{token:"invalid",foreground:"f44747"},{token:"emphasis",fontStyle:"italic"},{token:"strong",fontStyle:"bold"},{token:"variable",foreground:"1AEBFF"},{token:"variable.parameter",foreground:"9CDCFE"},{token:"constant",foreground:"569CD6"},{token:"comment",foreground:"608B4E"},{token:"number",foreground:"FFFFFF"},{token:"regexp",foreground:"C0C0C0"},{token:"annotation",foreground:"569CD6"},{token:"type",foreground:"3DC9B0"},{token:"delimiter",foreground:"FFFF00"},{token:"delimiter.html",foreground:"FFFF00"},{token:"tag",foreground:"569CD6"},{token:"tag.id.pug",foreground:"4F76AC"},{token:"tag.class.pug",foreground:"4F76AC"},{token:"meta",foreground:"D4D4D4"},{token:"meta.tag",foreground:"CE9178"},{token:"metatag",foreground:"569CD6"},{token:"metatag.content.html",foreground:"1AEBFF"},{token:"metatag.html",foreground:"569CD6"},{token:"metatag.xml",foreground:"569CD6"},{token:"metatag.php",fontStyle:"bold"},{token:"key",foreground:"9CDCFE"},{token:"string.key",foreground:"9CDCFE"},{token:"string.value",foreground:"CE9178"},{token:"attribute.name",foreground:"569CD6"},{token:"attribute.value",foreground:"3FF23F"},{token:"string",foreground:"CE9178"},{token:"string.sql",foreground:"FF0000"},{token:"keyword",foreground:"569CD6"},{token:"keyword.flow",foreground:"C586C0"},{token:"operator.sql",foreground:"778899"},{token:"operator.swift",foreground:"909090"},{token:"predefined.sql",foreground:"FF00FF"}],colors:(Ko={},Ko[Qn.o]="#000000",Ko[Qn.x]="#FFFFFF",Ko[Jn.h]="#FFFFFF",Ko[Jn.a]="#FFFFFF",Ko)},Jo="vs",Qo="vs-dark",$o="hc-black",er=uo.a.as(Qn.a.ColorContribution),tr=uo.a.as($n.a.ThemingContribution),nr=function(){function e(e,t){this.themeData=t;var n=t.base;e.length>0?(this.id=n+" "+e,this.themeName=e):(this.id=n,this.themeName=n),this.colors=null,this.defaultColors=Object.create(null),this._tokenTheme=null}return Object.defineProperty(e.prototype,"base",{get:function(){return this.themeData.base},enumerable:!0,configurable:!0}),e.prototype.notifyBaseUpdated=function(){this.themeData.inherit&&(this.colors=null,this._tokenTheme=null)},e.prototype.getColors=function(){if(!this.colors){var e=new Map;for(var t in this.themeData.colors)e.set(t,Po.a.fromHex(this.themeData.colors[t]));if(this.themeData.inherit){var n=or(this.themeData.base);for(var t in n.colors)e.has(t)||e.set(t,Po.a.fromHex(n.colors[t]))}this.colors=e}return this.colors},e.prototype.getColor=function(e,t){var n=this.getColors().get(e);return n||(!1!==t?this.getDefault(e):void 0)},e.prototype.getDefault=function(e){var t=this.defaultColors[e];return t||(t=er.resolveDefaultColor(e,this),this.defaultColors[e]=t,t)},e.prototype.defines=function(e){return Object.prototype.hasOwnProperty.call(this.getColors(),e)},Object.defineProperty(e.prototype,"type",{get:function(){switch(this.base){case Jo:return"light";case $o:return"hc";default:return"dark"}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tokenTheme",{get:function(){if(!this._tokenTheme){var e=[],t=[];if(this.themeData.inherit){var n=or(this.themeData.base);e=n.rules,n.encodedTokensColors&&(t=n.encodedTokensColors)}e=e.concat(this.themeData.rules),this.themeData.encodedTokensColors&&(t=this.themeData.encodedTokensColors),this._tokenTheme=Bo.createFromRawTokenTheme(e,t)}return this._tokenTheme},enumerable:!0,configurable:!0}),e}();function ir(e){return e===Jo||e===Qo||e===$o}function or(e){switch(e){case Jo:return Zo;case Qo:return Yo;case $o:return Xo}}function rr(e){var t=or(e);return new nr(e,t)}var sr=function(){function e(){this.environment=Object.create(null),this._onThemeChange=new A.a,this._onIconThemeChange=new A.a,this._knownThemes=new Map,this._knownThemes.set(Jo,rr(Jo)),this._knownThemes.set(Qo,rr(Qo)),this._knownThemes.set($o,rr($o)),this._styleElement=q.s(),this._styleElement.className="monaco-colors",this.setTheme(Jo)}return Object.defineProperty(e.prototype,"onThemeChange",{get:function(){return this._onThemeChange.event},enumerable:!0,configurable:!0}),e.prototype.defineTheme=function(e,t){if(!/^[a-z0-9\-]+$/i.test(e))throw new Error("Illegal theme name!");if(!ir(t.base)&&!ir(e))throw new Error("Illegal theme base!");this._knownThemes.set(e,new nr(e,t)),ir(e)&&this._knownThemes.forEach(function(t){t.base===e&&t.notifyBaseUpdated()}),this._theme&&this._theme.themeName===e&&this.setTheme(e)},e.prototype.getTheme=function(){return this._theme},e.prototype.setTheme=function(e){var t,n=this;if(t=this._knownThemes.has(e)?this._knownThemes.get(e):this._knownThemes.get(Jo),this._theme===t)return t.id;this._theme=t;var i=[],o={},r={addRule:function(e){o[e]||(i.push(e),o[e]=!0)}};tr.getThemingParticipants().forEach(function(e){return e(t,r,n.environment)});var s=t.tokenTheme.getColorMap();return r.addRule(function(e){for(var t=[],n=1,i=e.length;n=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,n,s):o(t,n))||s);return r>3&&s&&Object.defineProperty(t,n,s),s},lr=this&&this.__param||function(e,t){return function(n,i){t(n,i,e)}},cr="data-keybinding-context",dr=function(){function e(e,t){this._id=e,this._parent=t,this._value=Object.create(null),this._value._contextId=e}return e.prototype.setValue=function(e,t){return this._value[e]!==t&&(this._value[e]=t,!0)},e.prototype.removeValue=function(e){return e in this._value&&(delete this._value[e],!0)},e.prototype.getValue=function(e){var t=this._value[e];return void 0===t&&this._parent?this._parent.getValue(e):t},e}(),hr=function(e){function t(){return e.call(this,-1,null)||this}return ar(t,e),t.prototype.setValue=function(e,t){return!1},t.prototype.removeValue=function(e){return!1},t.prototype.getValue=function(e){},t.INSTANCE=new t,t}(dr),pr=function(e){function t(t,n,i){var o=e.call(this,t,null)||this;return o._configurationService=n,o._values=new Map,o._listener=o._configurationService.onDidChangeConfiguration(function(e){if(6===e.source){var t=Object(Qt.d)(o._values);o._values.clear(),i.fire(new mr(t))}else{for(var n=[],r=0,s=e.affectedKeys;r1){var i=n.shift();i&&(o.focusItemByElement(i.container),n.push(i)),o.mnemonics.set(t,n)}}})),be.c&&o._register(Object(q.h)(r,q.d.KEY_DOWN,function(e){var t=new qt.a(e);t.equals(14)||t.equals(11)?(o.focusedItem=o.viewItems.length-1,o.focusNext(),q.c.stop(e,!0)):(t.equals(13)||t.equals(12))&&(o.focusedItem=0,o.focusPrevious(),q.c.stop(e,!0))})),o._register(Object(q.h)(o.domNode,q.d.MOUSE_OUT,function(e){var t=e.relatedTarget;Object(q.E)(t,o.domNode)||(o.focusedItem=void 0,o.scrollTopHold=o.menuElement.scrollTop,o.updateFocus(),e.stopPropagation())})),o._register(Object(q.h)(o.domNode,q.d.MOUSE_UP,function(e){q.c.stop(e,!0)})),o._register(Object(q.h)(o.actionsList,q.d.MOUSE_OVER,function(e){var t=e.target;if(t&&Object(q.E)(t,o.actionsList)&&t!==o.actionsList){for(;t.parentElement!==o.actionsList&&null!==t.parentElement;)t=t.parentElement;if(Object(q.C)(t,"action-item")){var n=o.focusedItem;o.scrollTopHold=o.menuElement.scrollTop,o.setFocusedItem(t),n!==o.focusedItem&&o.updateFocus()}}}));var s={parent:o};return o.mnemonics=new Map,o.push(n,{icon:!0,label:!0,isMenu:!0}),o.scrollableElement=o._register(new Zn.a(r,{alwaysConsumeMouseWheel:!0,horizontal:2,vertical:3,verticalScrollbarSize:7,handleMouseWheel:!0,useShadows:!0})),o.scrollableElement.getDomNode().style.position=null,r.style.maxHeight=Math.max(10,window.innerHeight-t.getBoundingClientRect().top-30)+"px",o.menuDisposables.add(o.scrollableElement.onScroll(function(){o._onScroll.fire()},o)),o._register(Object(q.h)(o.menuElement,q.d.SCROLL,function(e){void 0!==o.scrollTopHold&&(o.menuElement.scrollTop=o.scrollTopHold,o.scrollTopHold=void 0),o.scrollableElement.scanDomNode()})),t.appendChild(o.scrollableElement.getDomNode()),o.scrollableElement.scanDomNode(),o.viewItems.filter(function(e){return!(e instanceof xr)}).forEach(function(e,t,n){e.updatePositionInSet(t+1,n.length)}),o}return Cr(t,e),t.prototype.style=function(e){var t=this.getContainer(),n=e.foregroundColor?""+e.foregroundColor:null,i=e.backgroundColor?""+e.backgroundColor:null,o=e.borderColor?"2px solid "+e.borderColor:null,r=e.shadowColor?"0 2px 4px "+e.shadowColor:null;t.style.border=o,this.domNode.style.color=n,this.domNode.style.backgroundColor=i,t.style.boxShadow=r,this.viewItems&&this.viewItems.forEach(function(t){(t instanceof Er||t instanceof xr)&&t.style(e)})},t.prototype.getContainer=function(){return this.scrollableElement.getDomNode()},Object.defineProperty(t.prototype,"onScroll",{get:function(){return this._onScroll.event},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scrollOffset",{get:function(){return this.menuElement.scrollTop},enumerable:!0,configurable:!0}),t.prototype.focusItemByElement=function(e){var t=this.focusedItem;this.setFocusedItem(e),t!==this.focusedItem&&this.updateFocus()},t.prototype.setFocusedItem=function(e){for(var t=0;t